Illustrated C/C++ source sheets, symbol index, API relationship graph, compiler console and debug trace

LIVE AI / FLEXIBLE SENSING / FLIGHT CONTEXT

Sensoraia API

Live AI and sensing, connected to the flight.
See, listen, inspect and return supported results while airborne.

Loading...
Searching...
No Matches
lwir_device_v4l2.c File Reference

Native Linux UVC acquisition with bounded mapped-buffer ownership. More...

#include "lwir_device.h"
#include <errno.h>
#include <time.h>
#include <linux/videodev2.h>
#include <linux/usbdevice_fs.h>
#include <fcntl.h>
#include <limits.h>
#include <poll.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/file.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/sysmacros.h>
#include <unistd.h>
Include dependency graph for lwir_device_v4l2.c:

Go to the source code of this file.

Data Structures

struct  video_state_transport
 Context handed to the lwir_state.c protocol through struct lwir_state_io. More...

Functions

static bool video_format_valid (const struct lwir_device_options *options, enum lwir_frame_layout layout, const struct v4l2_format *format)
 Check that the format the driver actually granted is exactly the native camera format.
static bool video_cancelled (const struct lwir_device *device)
 Poll the borrowed cancellation flag.
static bool video_now (uint64_t *microseconds)
 Read CLOCK_MONOTONIC in microseconds.
static bool video_checkpoint (const struct lwir_device *device, uint64_t deadline)
 Combined cancellation and deadline check placed between setup steps.
static int video_ioctl (int descriptor, unsigned long request, void *argument)
 ioctl() with a bounded retry on EINTR.
static bool video_text (const char *directory, const char *name, char *text, size_t capacity)
 Read one short sysfs/procfs attribute as a validated single-line string.
static bool video_identity (const struct stat *node, enum lwir_frame_layout *layout, char serial[64], char power_key[160], char power_port[64], unsigned *usb_bus, unsigned *usb_address)
 Resolve a V4L2 character device to its USB camera identity through sysfs.
static int video_probe (const char *path, const struct lwir_device_options *options, struct lwir_device *candidate)
 Test one V4L2 node and, if it is a usable camera, open and lock it.
static bool video_power_marker (struct lwir_device *device, bool complete)
 Read or publish the per-USB-instance startup qualification marker.
void lwir_device_close (struct lwir_device *device)
 Release a session in the reverse order of setup.
static bool video_setup (struct lwir_device *device, struct lwir_device_options *options, uint64_t deadline)
 Negotiate the native format, map the capture buffers and start streaming.
bool lwir_device_open (struct lwir_device_options *options, struct lwir_device *device)
 Find, lock and start exactly one supported camera within the timeout.
static bool video_sequence (struct lwir_device *device, uint32_t sequence, bool *continuous)
 Extend the kernel's 32-bit frame sequence to a monotonic 64-bit count.
static bool video_fail (struct lwir_device *device, int error)
 Poison the session after a fatal kernel or protocol error.
static bool video_ready (const struct lwir_device *device)
 Verify session invariants before touching the stream.
static bool video_destination_valid (const struct lwir_device *device, const void *destination, size_t bytes)
 Reject caller memory that overlaps any mapped camera buffer.
static bool video_ranges_separate (const void *first, size_t first_bytes, const void *second, size_t second_bytes)
 Test that two byte ranges do not overlap.
static bool video_requeue (struct lwir_device *device, unsigned index)
 Return a dequeued buffer to the driver.
static bool video_dequeue (struct lwir_device *device, struct v4l2_buffer *buffer, bool *received)
 Non-blocking VIDIOC_DQBUF with validation of what the kernel returned.
static bool video_timestamp_fresh (const struct v4l2_buffer *buffer, uint64_t start, uint64_t now)
 Check that a MONOTONIC kernel timestamp lies within [start, now].
static bool video_frame_qualified (const struct lwir_device *device, const struct v4l2_buffer *buffer, uint64_t start, uint64_t now)
 Structural and content check of a dequeued frame, independent of the request.
static void video_qualification (struct lwir_device *device, bool valid, bool continuous, uint64_t now)
 Advance the eight-consecutive-good-frames startup counter.
bool lwir_device_acquire (struct lwir_device *device, const struct lwir_device_options *options, uint8_t *destination, size_t capacity, struct lwir_device_observation *observation)
 Wait for, validate and copy the first acceptable frame that started after this call.
bool lwir_device_discard (struct lwir_device *device, bool *received)
 Dequeue and immediately requeue at most one pending frame.
static int video_state_transfer (void *context, bool input, uint16_t address, uint8_t *data, unsigned length, unsigned timeout)
 One Tiny1-C vendor mailbox control transfer over usbfs.
static uint64_t video_state_now (void *context)
 Clock callback for lwir_state.c.
static bool video_state_pause (void *context, unsigned milliseconds)
 Short cancellable delay between mailbox polls for lwir_state.c.
static bool video_state_identity (struct lwir_device *device)
 Confirm the streaming camera is still the same USB power instance.
static int video_state_open (struct lwir_device *device)
 Open the usbfs node of the streaming Tiny1-C for one state/control operation.
static bool video_control (struct lwir_device *device, const struct lwir_control_request *request, struct lwir_control_result *result, bool read_only)
 Shared implementation of control write and read-back.
bool lwir_device_control (struct lwir_device *device, const struct lwir_control_request *request, struct lwir_control_result *result)
 Public control write; see lwir_device.h.
bool lwir_device_control_read (struct lwir_device *device, enum lwir_control_kind kind, struct lwir_control_result *result)
 Public control read; see lwir_device.h.
void lwir_device_read_state (struct lwir_device *device, struct lwir_device_state *state)
 Best-effort read-only snapshot of Tiny1-C state; never writes settings.

Detailed Description

Native Linux UVC acquisition with bounded mapped-buffer ownership.

Implements lwir_device.h directly on the kernel uvcvideo driver through V4L2 MMAP buffers and Linux usbfs control transfers.

Cameras
  • Tiny1-C, USB 0bda:5840: YUYV transport 256x384 = 256x192 image plane followed by a 256x192 temperature plane (Kelvin*64, little-endian), 196608 bytes per frame at 25 fps (LWIR_COMBINED).
  • TDK, USB 5474:5411: 640x512 YUYV image only (LWIR_YUYV_IMAGE).
How the pieces fit
  1. Discovery (video_probe(), video_identity()) maps a /dev/videoN node to its USB device through sysfs, checks vendor/product/serial and takes an exclusive non-blocking flock so no second process (for example a control command while USHER captures) can share the camera.
  2. Setup (video_setup()) negotiates the exact native format and maps LWIR_VIDEO_BUFFERS MMAP buffers, then starts streaming.
  3. Acquisition (lwir_device_acquire()) polls in 25 ms slices, dequeues a buffer, validates it, copies it if accepted and always requeues it.
  4. Startup qualification is persisted per USB power instance by a runtime marker (video_power_marker()).
  5. Optional Tiny1-C state/control uses vendor control transfers over usbfs (video_state_open(), video_state_transfer()) beside the running stream.
Buffer ownership
A mapped buffer belongs to user space only between VIDIOC_DQBUF and VIDIOC_QBUF. Everything needed from it (pixels, sequence, timestamp, flags) is copied or snapshotted before requeue: after QBUF the kernel may refill the memory and the driver may rewrite buffer metadata at any moment. This ordering was required by a real hardware fault, not by theory.
Failure model
Fatal kernel or protocol errors set lwir_device::video_failed, poisoning the session until close and reopen; partial recovery of a V4L2 queue in an unknown state is not attempted. A failed munmap keeps ownership so a later close retries it and open refuses with EBUSY. close() is never retried because Linux releases the descriptor number even on error, and another thread may already have reused it.
Startup qualification
The first power-up of the camera needs eight consecutive valid frames. Linux exposes no sensor power-cycle counter, so a fresh USB enumeration is the observable power boundary: the marker /run/lock/sensoraia-lwir-UID/usb-PORT.ready stores "bootid:sysfs-inode:busnum:devnum". Qualification is never repeated for later requests, sequence gaps, bad frames, reopen or worker restart within the same instance. Marker failures are explicit errors rather than a silent fallback to another warmup.
Freshness and latency
A frame is accepted only when its kernel CLOCK_MONOTONIC timestamp (taken by uvcvideo at start of frame) is not earlier than the request, so the photo never predates the trigger. Measured cost is about 8.6 ms average wait for the next frame start plus about 36.1 ms USB delivery; that is the sensor/USB limit, not overhead of this code. For non-MONOTONIC clocks the already-queued buffers are drained once instead.
Policies
  • No heap allocation; all state is in the caller's struct lwir_device.
  • No memcpy by project policy: bounded byte loops are used. Compilers vectorize them; -fno-tree-loop-distribute-patterns stops them from being turned back into memcpy calls.
  • Interrupted system calls are retried a bounded number of times so a signal storm cannot spin forever.
Threading
Single-threaded per session. Only the borrowed cancellation flag is read asynchronously.

Definition in file lwir_device_v4l2.c.

Function Documentation

◆ lwir_device_acquire()

bool lwir_device_acquire ( struct lwir_device * device,
const struct lwir_device_options * options,
uint8_t * destination,
size_t capacity,
struct lwir_device_observation * observation )

Wait for, validate and copy the first acceptable frame that started after this call.

Copy a qualified, fresh camera-layout frame into caller-owned storage.

Loop structure, each iteration bounded by a 25 ms poll() slice so that cancellation and the deadline are noticed promptly:

  1. poll() for a filled buffer; POLLERR/POLLHUP/POLLNVAL (for example an unplugged camera) poison the session.
  2. Dequeue one buffer and read the host clock immediately.
  3. Grade the frame in increasing strictness:
    • usable: structurally valid, recent, correct sequence; feeds the startup qualification counter even when it predates the request.
    • valid: additionally started at or after the request (freshness).
    • scene_valid: additionally passes the optional scene check.
  4. For non-MONOTONIC clocks freshness is unknowable, so the first good frame triggers a one-time drain of all already-queued buffers; the next frame is then certainly produced after the request.
  5. Accept when the instance is qualified (eight good frames), optional settling holds, and on first startup only, warmup_ms has elapsed.
  6. Copy what is needed and snapshot sequence/timestamp/flags, then requeue. The order matters: after QBUF the kernel may overwrite both pixels and metadata.
  7. Persist the startup marker once qualification and warmup are complete.

Settling uses destination as the previous-image store: the image plane of each scene-valid frame is copied there and the next frame is compared against it, so no extra buffer is needed. The temperature plane is copied only for the accepted frame.

Returns
True with a fresh frame in destination.
Errors
EINVAL arguments/aliasing; EIO poisoned session or poll error; ETIMEDOUT deadline, including completion that would land after it; EINTR cancelled; kernel errno from failed ioctls (session then poisoned).
Warning
On failure destination may contain partial or settling data and must be ignored.

Definition at line 963 of file lwir_device_v4l2.c.

◆ lwir_device_close()

void lwir_device_close ( struct lwir_device * device)

Release a session in the reverse order of setup.

Close an initialized session; safe repeatedly and preserves errno.

  1. STREAMOFF returns all buffers from the driver queue to user space.
  2. munmap each mapping. A failed unmap keeps its entry marked as mapped and the session struct is not cleared, so a later close retries it and lwir_device_open() refuses with EBUSY rather than losing track of memory the process still maps.
  3. REQBUFS with count 0 frees the kernel buffers when the driver allows it.
  4. close() the descriptor exactly once. Its state is cleared first and a close error is only logged: Linux frees the number even on error, so retrying could close an unrelated descriptor opened by another thread.

Errors of STREAMOFF/REQBUFS are deliberately ignored; there is no better recovery than continuing teardown, and closing the descriptor ends the stream regardless.

Parameters
deviceSession to release; NULL and already-closed sessions are accepted.
Note
errno is preserved so callers can close on an error path without losing the original cause.

Definition at line 525 of file lwir_device_v4l2.c.

◆ lwir_device_control()

bool lwir_device_control ( struct lwir_device * device,
const struct lwir_control_request * request,
struct lwir_control_result * result )

Public control write; see lwir_device.h.

Submit one Tiny1-C vendor control write (or FFC action) as a standalone operation.

Returns
True when acknowledged.

Definition at line 1289 of file lwir_device_v4l2.c.

◆ lwir_device_control_read()

bool lwir_device_control_read ( struct lwir_device * device,
enum lwir_control_kind kind,
struct lwir_control_result * result )

Public control read; see lwir_device.h.

Read the current value of one Tiny1-C control without writing it.

Builds a request only so the shared validation path can be reused.

Returns
True when the value was read.

Definition at line 1300 of file lwir_device_v4l2.c.

◆ lwir_device_discard()

bool lwir_device_discard ( struct lwir_device * device,
bool * received )

Dequeue and immediately requeue at most one pending frame.

Drain one pending frame without retaining the borrowed UVC buffer.

Used to empty the queue (for example the non-MONOTONIC drain in lwir_device_acquire()) and to keep the stream moving between requests. The frame still feeds startup qualification with the one-second recency window, and the marker is published as soon as eight good frames are seen; no warmup delay applies here because there is no request start to measure from.

Returns
True on success, including when no frame was pending.
Errors
EINVAL bad arguments or session; EIO poisoned; EINTR cancelled; kernel or clock errno (session then poisoned).

Definition at line 1090 of file lwir_device_v4l2.c.

◆ lwir_device_open()

bool lwir_device_open ( struct lwir_device_options * options,
struct lwir_device * device )

Find, lock and start exactly one supported camera within the timeout.

Open/start a bounded camera-specific combined or image-only YUY2 stream.

  1. Validate options and refuse while the session still owns anything, including mappings kept after a failed munmap (EBUSY).
  2. Compute one absolute deadline covering discovery and setup.
  3. With an explicit device path, probe only that node. Otherwise probe /dev/video0..63. A second matching camera is an error (EEXIST) rather than "first wins": with two cameras attached the choice would depend on enumeration order, so the caller must disambiguate with a serial or path. Each match holds its own flock until the scan decides.
  4. Read the startup marker, then set up streaming.

Every failure after a successful probe closes the session, so the caller never has to clean up after a false return.

Returns
True when streaming; errno set otherwise (see lwir_device.h).

Definition at line 651 of file lwir_device_v4l2.c.

◆ lwir_device_read_state()

void lwir_device_read_state ( struct lwir_device * device,
struct lwir_device_state * state )

Best-effort read-only snapshot of Tiny1-C state; never writes settings.

Read bounded optional state after acquisition, never writing device settings.

All fields start as skipped and the first as an I/O error, so a failure to open usbfs is reported on a field instead of looking like an empty but successful read. lwir_state_read() overwrites what it reaches. The usbfs close result is ignored because nothing was written. Image-only sessions (or NULL) return a zero, not-requested snapshot without any USB traffic.

Note
errno is preserved; outcomes are reported only through state.
The snapshot is taken after the frame and is not frame-atomic.

Definition at line 1319 of file lwir_device_v4l2.c.

◆ video_cancelled()

bool video_cancelled ( const struct lwir_device * device)
static

Poll the borrowed cancellation flag.

Parameters
deviceSession whose optional flag is read.
Returns
True when a flag is attached and set.

Definition at line 144 of file lwir_device_v4l2.c.

◆ video_checkpoint()

bool video_checkpoint ( const struct lwir_device * device,
uint64_t deadline )
static

Combined cancellation and deadline check placed between setup steps.

Setup issues several ioctls that can each take noticeable time on USB; checking between them keeps open within its timeout budget.

Parameters
deviceSession whose cancellation flag is consulted.
deadlineAbsolute CLOCK_MONOTONIC limit in microseconds.
Returns
True to continue.
Errors
EINTR cancelled; ETIMEDOUT deadline reached; clock errors from video_now().

Definition at line 180 of file lwir_device_v4l2.c.

◆ video_control()

bool video_control ( struct lwir_device * device,
const struct lwir_control_request * request,
struct lwir_control_result * result,
bool read_only )
static

Shared implementation of control write and read-back.

Validates the request, opens usbfs, runs the lwir_state.c mailbox protocol once, and closes usbfs. The reply status is mapped to errno for callers that only check errno. A close error turns the result into a failure even though a write may already have been submitted; nothing is replayed, so the caller should read back instead of retrying.

Parameters
deviceOpen combined-layout session.
requestControl kind and value.
resultOutput reply; reset to LWIR_STATE_INVALID first.
read_onlyTrue for a read; FFC is an action and has no read form.
Returns
True on success.
Errors
EINVAL invalid request; errno from video_state_open(); EINTR cancelled; ETIMEDOUT camera timeout; EIO any other protocol failure.

Definition at line 1264 of file lwir_device_v4l2.c.

◆ video_dequeue()

bool video_dequeue ( struct lwir_device * device,
struct v4l2_buffer * buffer,
bool * received )
static

Non-blocking VIDIOC_DQBUF with validation of what the kernel returned.

EAGAIN (nothing ready on the O_NONBLOCK descriptor) and EINTR after the bounded retries are reported as "no frame", not errors. An index outside the mapped set is fatal without requeue, since an unknown index cannot be returned safely. A wrong type or memory model is requeued first, so the ring stays complete, and then treated as fatal.

Parameters
deviceSession.
bufferOutput: dequeued buffer metadata, valid when received.
receivedOutput: whether a buffer is now owned by the caller.
Returns
True on success (with or without a frame); false after video_fail().
Warning
When received is true the caller owns the buffer and must call video_requeue() on every path.

Definition at line 843 of file lwir_device_v4l2.c.

◆ video_destination_valid()

bool video_destination_valid ( const struct lwir_device * device,
const void * destination,
size_t bytes )
static

Reject caller memory that overlaps any mapped camera buffer.

A destination inside a mapping would let the copy read and write the same kernel-owned memory, and the kernel may rewrite it after requeue. Address arithmetic is done on uintptr_t with explicit wrap checks, so a range that wraps around the address space is rejected instead of passing the overlap test by overflow.

Parameters
deviceSession whose first video_count mappings are checked.
destinationStart of the caller range.
bytesLength of the caller range.
Returns
True when the range is well-formed and disjoint from every mapping.

Definition at line 781 of file lwir_device_v4l2.c.

◆ video_fail()

bool video_fail ( struct lwir_device * device,
int error )
static

Poison the session after a fatal kernel or protocol error.

After an unexpected DQBUF/QBUF/poll failure the driver queue is in an unknown state (a buffer may be lost or still owned by user space). Rather than guess, every later operation fails with EIO until the caller closes and reopens, which rebuilds the queue from scratch.

Parameters
deviceSession to poison.
errorerrno value to report.
Returns
Always false, for direct use in return statements.

Definition at line 733 of file lwir_device_v4l2.c.

◆ video_format_valid()

bool video_format_valid ( const struct lwir_device_options * options,
enum lwir_frame_layout layout,
const struct v4l2_format * format )
static

Check that the format the driver actually granted is exactly the native camera format.

VIDIOC_S_FMT may silently adjust any requested field, so every field that affects buffer interpretation is compared after negotiation: geometry, YUYV, progressive field order, tightly packed rows and the exact frame size. For the combined layout the transport height is twice the plane height because the temperature plane follows the image plane.

Parameters
optionsCaller policy; non-zero width/height must equal the native geometry and an optional measurement region must fit it.
layoutLayout implied by the USB identity.
formatFormat returned by the driver.
Returns
True only for an exact match; false otherwise (errno untouched).

Definition at line 122 of file lwir_device_v4l2.c.

◆ video_frame_qualified()

bool video_frame_qualified ( const struct lwir_device * device,
const struct v4l2_buffer * buffer,
uint64_t start,
uint64_t now )
static

Structural and content check of a dequeued frame, independent of the request.

Rejects driver-flagged errors, short or oversized payloads, and stamps older than max(start, now - 1 s). The one-second window lets frames that arrived before a request still count toward startup qualification while excluding stale backlog. For the combined layout, lwir_frame_capture_valid() rejects the neutral fill frames (all byte pairs 00,80) the Tiny1-C emits at transitions, and an invalid thermal plane.

Parameters
deviceSession (layout, geometry, mappings).
bufferDequeued buffer, still owned by the caller.
startAdditional lower time bound; 0 for none.
nowHost time at dequeue.
Returns
True when the frame is usable for qualification.

Definition at line 897 of file lwir_device_v4l2.c.

◆ video_identity()

bool video_identity ( const struct stat * node,
enum lwir_frame_layout * layout,
char serial[64],
char power_key[160],
char power_port[64],
unsigned * usb_bus,
unsigned * usb_address )
static

Resolve a V4L2 character device to its USB camera identity through sysfs.

  1. /sys/dev/char/MAJOR:MINOR/device points at the USB interface that owns the video node; it is canonicalized with realpath().
  2. Walk up at most 16 directories to the first ancestor exposing idVendor/idProduct, which is the USB device itself. The first such ancestor decides: an unsupported vendor/product is rejected rather than walking further up to a hub.
  3. The last path component is the physical port name (digits, '-' and '.'), which is stable across re-enumeration and so names the marker.
  4. Build the power key from boot_id, the sysfs directory inode, busnum and devnum. A new boot, a new enumeration (new sysfs node, new address) or a different bus all change the key; that is how a sensor power cycle is detected without any counter from the camera.

Bus and address are range-checked because they later form the usbfs path /dev/bus/usb/BBB/DDD and its expected device number (USB addresses are 1..127).

Parameters
nodestat() of the video node; must be a character device.
layoutOutput: layout implied by vendor/product.
serialOutput: USB serial or empty string.
power_keyOutput: power-instance key (see above).
power_portOutput: USB port name.
usb_busOutput: USB bus number.
usb_addressOutput: USB device address.
Returns
True when the node belongs to a supported camera.
Errors
ENODEV not a supported camera or no USB ancestor; EPROTO malformed bus or address; EOVERFLOW key too long; other errno from realpath/stat/sysfs reads.
Note
Outputs may be partially written on failure.

Definition at line 290 of file lwir_device_v4l2.c.

◆ video_ioctl()

int video_ioctl ( int descriptor,
unsigned long request,
void * argument )
static

ioctl() with a bounded retry on EINTR.

Signals (including the one that sets the cancellation flag) may interrupt V4L2 calls. Retrying keeps transient interruptions harmless, while the eight-attempt cap guarantees a signal storm still returns so the caller can notice cancellation.

Parameters
descriptorOpen V4L2 descriptor.
requestV4L2 request code.
argumentRequest-specific structure, updated by the kernel.
Returns
ioctl() result; -1 with errno set on failure (EINTR after the cap).

Definition at line 200 of file lwir_device_v4l2.c.

◆ video_now()

bool video_now ( uint64_t * microseconds)
static

Read CLOCK_MONOTONIC in microseconds.

MONOTONIC is the clock uvcvideo uses for buffer timestamps, so host and kernel times are directly comparable. The conversion is checked for malformed values and 64-bit overflow instead of trusting the kernel.

Parameters
microsecondsOutput, written only on success.
Returns
True on success.
Errors
errno from clock_gettime(); EPROTO malformed timespec; EOVERFLOW unrepresentable.

Definition at line 159 of file lwir_device_v4l2.c.

◆ video_power_marker()

bool video_power_marker ( struct lwir_device * device,
bool complete )
static

Read or publish the per-USB-instance startup qualification marker.

The marker /run/lock/sensoraia-lwir-UID/usb-PORT.ready holds the power key of the USB instance that already completed eight-frame qualification. /run is normally tmpfs, so a reboot clears it; boot_id inside the key covers the case where it does not.

Security and integrity checks: the directory must be a real directory owned by the effective user with no group/other access, and the marker a regular single-link file with the same ownership. All opens use O_NOFOLLOW and *at() calls relative to the verified directory descriptor, so a symlink or hard link planted by another user cannot redirect or spoof the marker.

Read mode (complete false): a missing marker means "not yet qualified"; a marker with a different key (an earlier power instance) likewise. A matching key restores eight good frames so no wait is imposed after reopen or worker restart.

Write mode (complete true): the key is written to usb-PORT.pending, created with O_EXCL, and renamed over the .ready file. rename is atomic, so a concurrent reader or a crash sees either the old or the new complete marker, never a partial key.

Any failure is returned as an error instead of being treated as "not ready": a silent fallback would quietly impose a new warmup on a camera that does not need one and hide a broken runtime directory.

Parameters
deviceSession supplying the power key and port; video_power_ready and possibly video_good_frames are updated.
completeFalse to read, true to publish completion.
Returns
True on success (including "no marker" in read mode).
Errors
EINVAL missing key/port; EACCES unsafe ownership, mode or link count; EOVERFLOW name too long; EPROTO embedded NUL; EIO unexpected EOF/short write; other errno from mkdir/open/read/write/rename/close.

Definition at line 431 of file lwir_device_v4l2.c.

◆ video_probe()

int video_probe ( const char * path,
const struct lwir_device_options * options,
struct lwir_device * candidate )
static

Test one V4L2 node and, if it is a usable camera, open and lock it.

Identity is established from sysfs before opening, so unrelated video devices are never opened. After open, fstat() must report the same inode and device numbers as the earlier lstat(); otherwise the node was replaced in between and the descriptor might belong to a different device. The driver must be uvcvideo with capture and streaming capability.

flock(LOCK_EX | LOCK_NB) gives exclusive ownership across processes: a second LWIRcam instance, or a control command issued while USHER is capturing, fails immediately instead of fighting over the stream. The lock is released automatically when the descriptor is closed.

The return value has three states so the scan in lwir_device_open() can skip non-matching nodes but stop on a matching camera it cannot use: a busy or permission-denied camera must be reported, not silently ignored.

Parameters
pathCandidate node (symlinks resolved first).
optionsSelection policy (serial filter, cancellation flag).
candidateOutput session, overwritten only on a match.
Returns
1 matched, opened and locked; 0 not a candidate (errno says why); -1 hard failure on a matching node (errno from open/ioctl/flock).

Definition at line 360 of file lwir_device_v4l2.c.

◆ video_qualification()

void video_qualification ( struct lwir_device * device,
bool valid,
bool continuous,
uint64_t now )
static

Advance the eight-consecutive-good-frames startup counter.

Once eight is reached the counter latches for the rest of the USB power instance: later bad frames or gaps must not impose another startup wait. Before that, an invalid frame resets to zero and a sequence gap restarts the count with the current frame as the first good one.

Parameters
deviceSession counter and last-good arrival time.
validResult of video_frame_qualified() and the sequence check.
continuousWhether the frame directly follows the previous one.
nowHost arrival time of the frame.

Definition at line 919 of file lwir_device_v4l2.c.

◆ video_ranges_separate()

bool video_ranges_separate ( const void * first,
size_t first_bytes,
const void * second,
size_t second_bytes )
static

Test that two byte ranges do not overlap.

Compares the lengths against the gap between the start addresses instead of computing end addresses, so no addition can overflow. Used to keep the frame, the observation and the session struct apart: an overlap would let a frame copy corrupt the session or the observation.

Parameters
firstStart of the first range.
first_bytesLength of the first range.
secondStart of the second range.
second_bytesLength of the second range.
Returns
True when the ranges are disjoint (touching ranges are disjoint).

Definition at line 806 of file lwir_device_v4l2.c.

◆ video_ready()

bool video_ready ( const struct lwir_device * device)
static

Verify session invariants before touching the stream.

Re-derives the expected geometry and frame size from the layout and checks every mapping. This guards against use of a zeroed, closed, partially opened or caller-corrupted session, which would otherwise lead to reads outside a mapping.

Parameters
deviceSession to check; NULL accepted.
Returns
True when streaming and consistent.
Errors
EINVAL not open/streaming or inconsistent; EIO poisoned by video_fail().

Definition at line 751 of file lwir_device_v4l2.c.

◆ video_requeue()

bool video_requeue ( struct lwir_device * device,
unsigned index )
static

Return a dequeued buffer to the driver.

A fresh v4l2_buffer is used rather than the dequeued one, so the caller's copy of sequence/timestamp/flags is not touched by the ioctl. Failure is fatal: the buffer has left the ring and the stream would silently run with fewer buffers.

Parameters
deviceSession.
indexBuffer index previously dequeued.
Returns
True on success; false after video_fail().

Definition at line 822 of file lwir_device_v4l2.c.

◆ video_sequence()

bool video_sequence ( struct lwir_device * device,
uint32_t sequence,
bool * continuous )
static

Extend the kernel's 32-bit frame sequence to a monotonic 64-bit count.

The forward distance is computed in unsigned 32-bit arithmetic, so wrap-around of the kernel counter is handled naturally. A zero distance (repeated number) or a distance above half the range (interpreted as going backwards) is rejected as inconsistent. Dropped frames advance the 64-bit count by the full distance so gaps stay visible in observations, and are reported as non-continuous to the qualification logic.

Parameters
deviceSession sequence state, updated on success.
sequenceRaw v4l2_buffer::sequence.
continuousOutput: true for the first frame or an exact successor.
Returns
False for a duplicate, backwards or overflowing sequence (state unchanged).
Note
The first frame is numbered raw + 1. The reason for the offset is not documented in the code; it at least keeps the extended value non-zero.

Definition at line 709 of file lwir_device_v4l2.c.

◆ video_setup()

bool video_setup ( struct lwir_device * device,
struct lwir_device_options * options,
uint64_t deadline )
static

Negotiate the native format, map the capture buffers and start streaming.

  1. Request the native YUYV format; for the combined layout the transport height is doubled to carry the temperature plane.
  2. Verify the granted format exactly (video_format_valid()).
  3. REQBUFS for LWIR_VIDEO_BUFFERS MMAP buffers. The driver may grant a different count; it is recorded before validation so close frees the kernel buffers even when the count is rejected.
  4. For each buffer: QUERYBUF, check its size against both the frame and LWIR_MAX_FRAME_BYTES, mmap it, record the mapping immediately (so close can unmap it on any later failure), and queue it to the driver.
  5. STREAMON. lwir_device::video_streaming is set beforehand so close issues STREAMOFF even if STREAMON failed half-way.

Cancellation/deadline checkpoints sit between ioctls because each one may block on USB. On failure the partially built state is left for lwir_device_close(), which is the single teardown path.

Parameters
deviceProbed, locked session.
optionsPolicy; on success width, height and layout are written back.
deadlineAbsolute CLOCK_MONOTONIC limit in microseconds.
Returns
True when streaming.
Errors
ENOTSUP thermal data required from an image-only camera, unexpected format or buffer count; EPROTO inconsistent QUERYBUF; EFAULT NULL mapping; EINTR/ETIMEDOUT checkpoints; other errno from ioctl/mmap.

Definition at line 585 of file lwir_device_v4l2.c.

◆ video_state_identity()

bool video_state_identity ( struct lwir_device * device)
static

Confirm the streaming camera is still the same USB power instance.

Re-derives the identity from the open V4L2 descriptor and compares power key, bus and address with those recorded at open. If the camera re-enumerated meanwhile, the stored bus/address may now name a different device, and vendor writes must never reach it.

Parameters
deviceOpen session.
Returns
True when unchanged and combined-layout.
Errors
ENODEV identity changed or unavailable; errno from fstat().

Definition at line 1196 of file lwir_device_v4l2.c.

◆ video_state_now()

uint64_t video_state_now ( void * context)
static

Clock callback for lwir_state.c.

Parameters
contextUnused.
Returns
CLOCK_MONOTONIC microseconds, or UINT64_MAX if the clock fails so that any deadline comparison in the protocol treats it as expired.

Definition at line 1159 of file lwir_device_v4l2.c.

◆ video_state_open()

int video_state_open ( struct lwir_device * device)
static

Open the usbfs node of the streaming Tiny1-C for one state/control operation.

  1. Require a healthy combined-layout session and verify identity.
  2. Open /dev/bus/usb/BBB/DDD.
  3. Check the opened node is the expected usbfs character device: major 189, minor (bus - 1) * 128 + address - 1.
  4. Verify identity again after open, closing the window in which the camera could re-enumerate and another device take over the address.

The node is opened per operation and closed on every path by the caller, so no usbfs handle outlives a single request.

Parameters
deviceOpen, healthy session.
Returns
usbfs descriptor, or -1 with errno set.
Errors
EINVAL/EIO session not ready; ENOTSUP image-only camera; EINTR cancelled; ENODEV identity mismatch; EOVERFLOW path too long; errno from open/fstat.

Definition at line 1227 of file lwir_device_v4l2.c.

◆ video_state_pause()

bool video_state_pause ( void * context,
unsigned milliseconds )
static

Short cancellable delay between mailbox polls for lwir_state.c.

nanosleep() is resumed with the remaining time after signals, but cancellation is checked on every interruption so a cancel request ends the pause immediately. The 10 ms cap keeps cancellation latency small.

Parameters
contextstruct video_state_transport.
milliseconds1..10.
Returns
True when the full delay elapsed without cancellation.

Definition at line 1175 of file lwir_device_v4l2.c.

◆ video_state_transfer()

int video_state_transfer ( void * context,
bool input,
uint16_t address,
uint8_t * data,
unsigned length,
unsigned timeout )
static

One Tiny1-C vendor mailbox control transfer over usbfs.

Reads use bmRequestType 0xc1 / bRequest 0x44 and writes 0x41 / 0x45 (vendor type, interface recipient), with wValue 0x78 and the mailbox address in wIndex. Linux usbfs permits vendor-type control requests without claiming the interface, so uvcvideo is never detached and streaming continues undisturbed. Length (64 bytes) and timeout (50 ms) caps keep a misbehaving camera from blocking the caller for long.

Parameters
contextstruct video_state_transport.
inputTrue for device-to-host (read), false for host-to-device (write).
addressMailbox address placed in wIndex.
dataTransfer buffer of length bytes.
length1..64 bytes.
timeout1..50 milliseconds.
Returns
Bytes transferred, or a negative code interpreted by lwir_state.c: -10 cancelled/interrupted, -7 timeout, -2 invalid argument, -1 other I/O error. These values follow the numbering of the retired libusb backend so lwir_state.c stays backend-neutral.

Definition at line 1139 of file lwir_device_v4l2.c.

◆ video_text()

bool video_text ( const char * directory,
const char * name,
char * text,
size_t capacity )
static

Read one short sysfs/procfs attribute as a validated single-line string.

Reads until EOF into the caller buffer. If the buffer fills, one further byte is attempted: any data there means the value was truncated and the whole read is rejected, because a cut-off identity string could match the wrong device. Trailing newline characters are stripped, a terminator must still fit, and control characters are refused so the value is safe to embed in the marker file and log lines.

Parameters
directorysysfs directory.
nameAttribute file name inside directory.
textOutput buffer; NUL-terminated only on success.
capacitySize of text, at least 2.
Returns
True for a non-empty, complete, printable value. errno is meaningful only for open/read failures; validation failures leave it unspecified.

Definition at line 225 of file lwir_device_v4l2.c.

◆ video_timestamp_fresh()

bool video_timestamp_fresh ( const struct v4l2_buffer * buffer,
uint64_t start,
uint64_t now )
static

Check that a MONOTONIC kernel timestamp lies within [start, now].

uvcvideo stamps buffers at start of frame. Requiring the stamp to be at or after the request start guarantees the image was not exposed before the trigger. A stamp after now is impossible on one clock and is rejected as inconsistent. Buffers whose clock is not MONOTONIC cannot be compared and pass here; lwir_device_acquire() compensates by draining the already-queued buffers once.

Parameters
bufferDequeued buffer.
startEarliest acceptable time, CLOCK_MONOTONIC microseconds.
nowHost time at dequeue, CLOCK_MONOTONIC microseconds.
Returns
True when fresh or when freshness cannot be judged.

Definition at line 874 of file lwir_device_v4l2.c.