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
Go to the documentation of this file.
1/*
2 * Copyright 2026 OpenUAS
3 * SPDX-License-Identifier: Apache-2.0
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
18/** @file
19 * @brief Native Linux UVC acquisition with bounded mapped-buffer ownership.
20 *
21 * @details
22 * Implements lwir_device.h directly on the kernel uvcvideo driver through
23 * V4L2 MMAP buffers and Linux usbfs control transfers.
24 *
25 * @par Cameras
26 * - Tiny1-C, USB 0bda:5840: YUYV transport 256x384 = 256x192 image plane
27 * followed by a 256x192 temperature plane (Kelvin*64, little-endian),
28 * 196608 bytes per frame at 25 fps (#LWIR_COMBINED).
29 * - TDK, USB 5474:5411: 640x512 YUYV image only (#LWIR_YUYV_IMAGE).
30 *
31 * @par How the pieces fit
32 * 1. Discovery (video_probe(), video_identity()) maps a /dev/videoN node to
33 * its USB device through sysfs, checks vendor/product/serial and takes an
34 * exclusive non-blocking flock so no second process (for example a control
35 * command while USHER captures) can share the camera.
36 * 2. Setup (video_setup()) negotiates the exact native format and maps
37 * #LWIR_VIDEO_BUFFERS MMAP buffers, then starts streaming.
38 * 3. Acquisition (lwir_device_acquire()) polls in 25 ms slices, dequeues a
39 * buffer, validates it, copies it if accepted and always requeues it.
40 * 4. Startup qualification is persisted per USB power instance by a runtime
41 * marker (video_power_marker()).
42 * 5. Optional Tiny1-C state/control uses vendor control transfers over usbfs
43 * (video_state_open(), video_state_transfer()) beside the running stream.
44 *
45 * @par Buffer ownership
46 * A mapped buffer belongs to user space only between VIDIOC_DQBUF and
47 * VIDIOC_QBUF. Everything needed from it (pixels, sequence, timestamp, flags)
48 * is copied or snapshotted before requeue: after QBUF the kernel may refill
49 * the memory and the driver may rewrite buffer metadata at any moment. This
50 * ordering was required by a real hardware fault, not by theory.
51 *
52 * @par Failure model
53 * Fatal kernel or protocol errors set lwir_device::video_failed, poisoning
54 * the session until close and reopen; partial recovery of a V4L2 queue in an
55 * unknown state is not attempted. A failed munmap keeps ownership so a later
56 * close retries it and open refuses with EBUSY. close() is never retried
57 * because Linux releases the descriptor number even on error, and another
58 * thread may already have reused it.
59 *
60 * @par Startup qualification
61 * The first power-up of the camera needs eight consecutive valid frames.
62 * Linux exposes no sensor power-cycle counter, so a fresh USB enumeration is
63 * the observable power boundary: the marker
64 * /run/lock/sensoraia-lwir-UID/usb-PORT.ready stores
65 * "bootid:sysfs-inode:busnum:devnum". Qualification is never repeated for
66 * later requests, sequence gaps, bad frames, reopen or worker restart within
67 * the same instance. Marker failures are explicit errors rather than a silent
68 * fallback to another warmup.
69 *
70 * @par Freshness and latency
71 * A frame is accepted only when its kernel CLOCK_MONOTONIC timestamp (taken
72 * by uvcvideo at start of frame) is not earlier than the request, so the
73 * photo never predates the trigger. Measured cost is about 8.6 ms average
74 * wait for the next frame start plus about 36.1 ms USB delivery; that is the
75 * sensor/USB limit, not overhead of this code. For non-MONOTONIC clocks the
76 * already-queued buffers are drained once instead.
77 *
78 * @par Policies
79 * - No heap allocation; all state is in the caller's struct lwir_device.
80 * - No memcpy by project policy: bounded byte loops are used. Compilers
81 * vectorize them; -fno-tree-loop-distribute-patterns stops them from being
82 * turned back into memcpy calls.
83 * - Interrupted system calls are retried a bounded number of times so a
84 * signal storm cannot spin forever.
85 *
86 * @par Threading
87 * Single-threaded per session. Only the borrowed cancellation flag is read
88 * asynchronously.
89 */
90#include "lwir_device.h"
91
92#include <errno.h>
93#include <time.h>
94#include <linux/videodev2.h>
95#include <linux/usbdevice_fs.h>
96#include <fcntl.h>
97#include <limits.h>
98#include <poll.h>
99#include <stdio.h>
100#include <stdlib.h>
101#include <string.h>
102#include <sys/file.h>
103#include <sys/ioctl.h>
104#include <sys/mman.h>
105#include <sys/stat.h>
106#include <sys/sysmacros.h>
107#include <unistd.h>
108
109/**
110 * @brief Check that the format the driver actually granted is exactly the native camera format.
111 * @details VIDIOC_S_FMT may silently adjust any requested field, so every
112 * field that affects buffer interpretation is compared after negotiation:
113 * geometry, YUYV, progressive field order, tightly packed rows and the exact
114 * frame size. For the combined layout the transport height is twice the plane
115 * height because the temperature plane follows the image plane.
116 * @param options Caller policy; non-zero width/height must equal the native
117 * geometry and an optional measurement region must fit it.
118 * @param layout Layout implied by the USB identity.
119 * @param format Format returned by the driver.
120 * @return True only for an exact match; false otherwise (errno untouched).
121 */
123 enum lwir_frame_layout layout, const struct v4l2_format *format)
124{
125 if (!options || !format || format->type != V4L2_BUF_TYPE_VIDEO_CAPTURE
126 || (layout != LWIR_COMBINED && layout != LWIR_YUYV_IMAGE)) return false;
127 const unsigned width = layout == LWIR_COMBINED ? 256U : 640U;
128 const unsigned height = layout == LWIR_COMBINED ? 192U : 512U;
129 /* lwir_frame_bytes() sizes both planes (4 bytes/pixel); image-only YUYV carries half of that. */
130 const size_t bytes = lwir_frame_bytes(width, height) / (layout == LWIR_COMBINED ? 1U : 2U);
131 const struct v4l2_pix_format *pixels = &format->fmt.pix;
132 return (!options->width || (options->width == width && options->height == height))
133 && pixels->width == width && pixels->height == height * (layout == LWIR_COMBINED ? 2U : 1U)
134 && pixels->pixelformat == V4L2_PIX_FMT_YUYV && pixels->field == V4L2_FIELD_NONE
135 && pixels->bytesperline == width * 2U && pixels->sizeimage == bytes
136 && (!options->measurement || lwir_measurement_valid(width, height, options->measurement));
137}
138
139/**
140 * @brief Poll the borrowed cancellation flag.
141 * @param device Session whose optional flag is read.
142 * @return True when a flag is attached and set.
143 */
144static bool video_cancelled(const struct lwir_device *device)
145{
146 return device->cancelled && *device->cancelled;
147}
148
149/**
150 * @brief Read CLOCK_MONOTONIC in microseconds.
151 * @details MONOTONIC is the clock uvcvideo uses for buffer timestamps, so
152 * host and kernel times are directly comparable. The conversion is checked
153 * for malformed values and 64-bit overflow instead of trusting the kernel.
154 * @param microseconds Output, written only on success.
155 * @return True on success.
156 * @par Errors
157 * errno from clock_gettime(); EPROTO malformed timespec; EOVERFLOW unrepresentable.
158 */
159static bool video_now(uint64_t *microseconds)
160{
161 struct timespec now;
162 if (clock_gettime(CLOCK_MONOTONIC, &now)) return false;
163 if (now.tv_sec < 0 || now.tv_nsec < 0 || now.tv_nsec >= 1000000000L) { errno = EPROTO; return false; }
164 /* Division form of the bound avoids computing the overflowing product. */
165 if ((uint64_t)now.tv_sec > (UINT64_MAX - (uint64_t)now.tv_nsec / 1000U) / 1000000U) { errno = EOVERFLOW; return false; }
166 *microseconds = (uint64_t)now.tv_sec * 1000000U + (uint64_t)now.tv_nsec / 1000U;
167 return true;
168}
169
170/**
171 * @brief Combined cancellation and deadline check placed between setup steps.
172 * @details Setup issues several ioctls that can each take noticeable time on
173 * USB; checking between them keeps open within its timeout budget.
174 * @param device Session whose cancellation flag is consulted.
175 * @param deadline Absolute CLOCK_MONOTONIC limit in microseconds.
176 * @return True to continue.
177 * @par Errors
178 * EINTR cancelled; ETIMEDOUT deadline reached; clock errors from video_now().
179 */
180static bool video_checkpoint(const struct lwir_device *device, uint64_t deadline)
181{
182 if (video_cancelled(device)) { errno = EINTR; return false; }
183 uint64_t now;
184 if (!video_now(&now)) return false;
185 if (now >= deadline) { errno = ETIMEDOUT; return false; }
186 return true;
187}
188
189/**
190 * @brief ioctl() with a bounded retry on EINTR.
191 * @details Signals (including the one that sets the cancellation flag) may
192 * interrupt V4L2 calls. Retrying keeps transient interruptions harmless,
193 * while the eight-attempt cap guarantees a signal storm still returns so the
194 * caller can notice cancellation.
195 * @param descriptor Open V4L2 descriptor.
196 * @param request V4L2 request code.
197 * @param argument Request-specific structure, updated by the kernel.
198 * @return ioctl() result; -1 with errno set on failure (EINTR after the cap).
199 */
200static int video_ioctl(int descriptor, unsigned long request, void *argument)
201{
202 for (unsigned attempt = 0; attempt < 8; ++attempt) {
203 const int result = ioctl(descriptor, request, argument);
204 if (result >= 0 || errno != EINTR) return result;
205 }
206 errno = EINTR;
207 return -1;
208}
209
210/**
211 * @brief Read one short sysfs/procfs attribute as a validated single-line string.
212 * @details Reads until EOF into the caller buffer. If the buffer fills, one
213 * further byte is attempted: any data there means the value was truncated and
214 * the whole read is rejected, because a cut-off identity string could match
215 * the wrong device. Trailing newline characters are stripped, a terminator
216 * must still fit, and control characters are refused so the value is safe to
217 * embed in the marker file and log lines.
218 * @param directory sysfs directory.
219 * @param name Attribute file name inside @p directory.
220 * @param text Output buffer; NUL-terminated only on success.
221 * @param capacity Size of @p text, at least 2.
222 * @return True for a non-empty, complete, printable value. errno is
223 * meaningful only for open/read failures; validation failures leave it unspecified.
224 */
225static bool video_text(const char *directory, const char *name, char *text, size_t capacity)
226{
227 char path[PATH_MAX];
228 int count = snprintf(path, sizeof(path), "%s/%s", directory, name);
229 if (count < 0 || (size_t)count >= sizeof(path) || capacity < 2) return false;
230 const int descriptor = open(path, O_RDONLY | O_NONBLOCK | O_CLOEXEC | O_NOFOLLOW);
231 if (descriptor < 0) return false;
232 size_t used = 0;
233 bool valid = true;
234 unsigned interruptions = 0;
235 while (used < capacity) {
236 ssize_t received = read(descriptor, text + used, capacity - used);
237 if (received < 0 && errno == EINTR && ++interruptions < 8) continue;
238 if (received < 0) { valid = false; break; }
239 if (!received) break;
240 used += (size_t)received;
241 }
242 /* A full buffer is ambiguous: probe for one more byte to tell "exact fit" from truncation. */
243 if (valid && used == capacity) {
244 char extra;
245 if (read(descriptor, &extra, 1) != 0) valid = false;
246 }
247 if (close(descriptor)) valid = false;
248 if (!valid || !used) return false;
249 while (used && (text[used - 1] == '\n' || text[used - 1] == '\r')) --used;
250 /* Without a trailing newline to strip, an exact fit leaves no room for the terminator. */
251 if (used >= capacity) return false;
252 for (size_t index = 0; index < used; ++index)
253 if ((unsigned char)text[index] < 32 || text[index] == 127) return false;
254 text[used] = '\0';
255 return used != 0;
256}
257
258/**
259 * @brief Resolve a V4L2 character device to its USB camera identity through sysfs.
260 * @details
261 * 1. /sys/dev/char/MAJOR:MINOR/device points at the USB interface that owns
262 * the video node; it is canonicalized with realpath().
263 * 2. Walk up at most 16 directories to the first ancestor exposing
264 * idVendor/idProduct, which is the USB device itself. The first such
265 * ancestor decides: an unsupported vendor/product is rejected rather than
266 * walking further up to a hub.
267 * 3. The last path component is the physical port name (digits, '-' and
268 * '.'), which is stable across re-enumeration and so names the marker.
269 * 4. Build the power key from boot_id, the sysfs directory inode, busnum and
270 * devnum. A new boot, a new enumeration (new sysfs node, new address) or a
271 * different bus all change the key; that is how a sensor power cycle is
272 * detected without any counter from the camera.
273 *
274 * Bus and address are range-checked because they later form the usbfs path
275 * /dev/bus/usb/BBB/DDD and its expected device number (USB addresses are
276 * 1..127).
277 * @param node stat() of the video node; must be a character device.
278 * @param layout Output: layout implied by vendor/product.
279 * @param serial Output: USB serial or empty string.
280 * @param power_key Output: power-instance key (see above).
281 * @param power_port Output: USB port name.
282 * @param usb_bus Output: USB bus number.
283 * @param usb_address Output: USB device address.
284 * @return True when the node belongs to a supported camera.
285 * @par Errors
286 * ENODEV not a supported camera or no USB ancestor; EPROTO malformed bus or
287 * address; EOVERFLOW key too long; other errno from realpath/stat/sysfs reads.
288 * @note Outputs may be partially written on failure.
289 */
290static bool video_identity(const struct stat *node, enum lwir_frame_layout *layout, char serial[64],
291 char power_key[160], char power_port[64], unsigned *usb_bus, unsigned *usb_address)
292{
293 if (!S_ISCHR(node->st_mode)) { errno = ENODEV; return false; }
294 char path[PATH_MAX], resolved[PATH_MAX];
295 int length = snprintf(path, sizeof(path), "/sys/dev/char/%u:%u/device", major(node->st_rdev), minor(node->st_rdev));
296 if (length < 0 || (size_t)length >= sizeof(path) || !realpath(path, resolved)) return false;
297 for (unsigned parent = 0; parent < 16; ++parent) {
298 char vendor[16], product[16];
299 if (video_text(resolved, "idVendor", vendor, sizeof(vendor)) && video_text(resolved, "idProduct", product, sizeof(product))) {
300 if (!strcmp(vendor, "0bda") && !strcmp(product, "5840")) *layout = LWIR_COMBINED;
301 else if (!strcmp(vendor, "5474") && !strcmp(product, "5411")) *layout = LWIR_YUYV_IMAGE;
302 else { errno = ENODEV; return false; }
303 serial[0] = '\0';
304 /* Serial is optional; a camera without one can still be selected without --serial. */
305 if (!video_text(resolved, "serial", serial, 64)) serial[0] = '\0';
306 char boot[64], bus[16], address[16];
307 struct stat identity;
308 const char *port = strrchr(resolved, '/');
309 if (!port || !port[1] || strlen(port + 1) >= 64
310 || strspn(port + 1, "0123456789-.") != strlen(port + 1)
311 || stat(resolved, &identity) || !S_ISDIR(identity.st_mode)
312 || !video_text("/proc/sys/kernel/random", "boot_id", boot, sizeof(boot))
313 || !video_text(resolved, "busnum", bus, sizeof(bus))
314 || !video_text(resolved, "devnum", address, sizeof(address))) return false;
315 if (!bus[0] || !address[0] || strspn(bus, "0123456789") != strlen(bus)
316 || strspn(address, "0123456789") != strlen(address)) { errno = EPROTO; return false; }
317 errno = 0;
318 const unsigned long bus_number = strtoul(bus, NULL, 10), device_number = strtoul(address, NULL, 10);
319 if (errno || !bus_number || bus_number > 999 || !device_number || device_number > 127) { errno = EPROTO; return false; }
320 *usb_bus = (unsigned)bus_number; *usb_address = (unsigned)device_number;
321 /* The sysfs inode differs per enumeration even when bus/address happen to be reused. */
322 const int count = snprintf(power_key, 160, "%s:%llu:%s:%s", boot,
323 (unsigned long long)identity.st_ino, bus, address);
324 if (count < 0 || count >= 160) { errno = EOVERFLOW; return false; }
325 /* Inclusive bound copies the terminator; length was checked against 64 above. */
326 for (size_t index = 0; index <= strlen(port + 1); ++index) power_port[index] = port[index + 1];
327 return true;
328 }
329 char *separator = strrchr(resolved, '/');
330 if (!separator || separator == resolved) break;
331 *separator = '\0';
332 }
333 errno = ENODEV;
334 return false;
335}
336
337/**
338 * @brief Test one V4L2 node and, if it is a usable camera, open and lock it.
339 * @details
340 * Identity is established from sysfs before opening, so unrelated video
341 * devices are never opened. After open, fstat() must report the same inode
342 * and device numbers as the earlier lstat(); otherwise the node was replaced
343 * in between and the descriptor might belong to a different device. The
344 * driver must be uvcvideo with capture and streaming capability.
345 *
346 * flock(LOCK_EX | LOCK_NB) gives exclusive ownership across processes:
347 * a second LWIRcam instance, or a control command issued while USHER is
348 * capturing, fails immediately instead of fighting over the stream.
349 * The lock is released automatically when the descriptor is closed.
350 *
351 * The return value has three states so the scan in lwir_device_open() can
352 * skip non-matching nodes but stop on a matching camera it cannot use: a busy
353 * or permission-denied camera must be reported, not silently ignored.
354 * @param path Candidate node (symlinks resolved first).
355 * @param options Selection policy (serial filter, cancellation flag).
356 * @param candidate Output session, overwritten only on a match.
357 * @return 1 matched, opened and locked; 0 not a candidate (errno says why);
358 * -1 hard failure on a matching node (errno from open/ioctl/flock).
359 */
360static int video_probe(const char *path, const struct lwir_device_options *options, struct lwir_device *candidate)
361{
362 char resolved[PATH_MAX], serial[64] = {0}, power_key[160] = {0}, power_port[64] = {0};
363 struct stat node, opened;
364 enum lwir_frame_layout layout;
365 unsigned usb_bus, usb_address;
366 if (!realpath(path, resolved) || lstat(resolved, &node)
367 || !video_identity(&node, &layout, serial, power_key, power_port, &usb_bus, &usb_address)) return 0;
368 if (options->serial && strcmp(options->serial, serial)) { errno = ENODEV; return 0; }
369 const int descriptor = open(resolved, O_RDWR | O_NONBLOCK | O_CLOEXEC | O_NOFOLLOW);
370 if (descriptor < 0) return -1;
371 int error = 0;
372 struct v4l2_capability capability = {0};
373 if (fstat(descriptor, &opened) || !S_ISCHR(opened.st_mode) || opened.st_dev != node.st_dev || opened.st_rdev != node.st_rdev
374 || opened.st_ino != node.st_ino) error = ENODEV;
375 else if (video_ioctl(descriptor, VIDIOC_QUERYCAP, &capability)) error = errno;
376 /* device_caps describes this node; capabilities covers the whole physical device when DEVICE_CAPS is set. */
377 const uint32_t capabilities = capability.capabilities & V4L2_CAP_DEVICE_CAPS ? capability.device_caps : capability.capabilities;
378 const bool capture = !error && !strncmp((const char *)capability.driver, "uvcvideo", sizeof(capability.driver))
379 && (capabilities & V4L2_CAP_VIDEO_CAPTURE) && (capabilities & V4L2_CAP_STREAMING);
380 if (capture && flock(descriptor, LOCK_EX | LOCK_NB)) error = errno;
381 if (error || !capture) {
382 /* The descriptor was never published, so a close error cannot affect any other owner. */
384 errno = error ? error : ENOTSUP;
385 return error ? -1 : 0;
386 }
387 *candidate = (struct lwir_device){.video_fd = descriptor, .video_open = true,
388 .layout = layout, .cancelled = options->cancelled, .video_usb_bus = usb_bus, .video_usb_address = usb_address};
389 for (size_t index = 0; index < sizeof(candidate->serial); ++index) candidate->serial[index] = serial[index];
390 for (size_t index = 0; index < sizeof(candidate->video_power_key); ++index) candidate->video_power_key[index] = power_key[index];
391 for (size_t index = 0; index < sizeof(candidate->video_power_port); ++index) candidate->video_power_port[index] = power_port[index];
392 return 1;
393}
394
395/**
396 * @brief Read or publish the per-USB-instance startup qualification marker.
397 * @details
398 * The marker /run/lock/sensoraia-lwir-UID/usb-PORT.ready holds the power key
399 * of the USB instance that already completed eight-frame qualification. /run
400 * is normally tmpfs, so a reboot clears it; boot_id inside the key covers the
401 * case where it does not.
402 *
403 * Security and integrity checks: the directory must be a real directory owned
404 * by the effective user with no group/other access, and the marker a regular
405 * single-link file with the same ownership. All opens use O_NOFOLLOW and
406 * *at() calls relative to the verified directory descriptor, so a symlink or
407 * hard link planted by another user cannot redirect or spoof the marker.
408 *
409 * Read mode (@p complete false): a missing marker means "not yet qualified";
410 * a marker with a different key (an earlier power instance) likewise. A
411 * matching key restores eight good frames so no wait is imposed after reopen
412 * or worker restart.
413 *
414 * Write mode (@p complete true): the key is written to usb-PORT.pending,
415 * created with O_EXCL, and renamed over the .ready file. rename is atomic, so
416 * a concurrent reader or a crash sees either the old or the new complete
417 * marker, never a partial key.
418 *
419 * Any failure is returned as an error instead of being treated as "not
420 * ready": a silent fallback would quietly impose a new warmup on a camera that
421 * does not need one and hide a broken runtime directory.
422 * @param device Session supplying the power key and port; @c video_power_ready
423 * and possibly @c video_good_frames are updated.
424 * @param complete False to read, true to publish completion.
425 * @return True on success (including "no marker" in read mode).
426 * @par Errors
427 * EINVAL missing key/port; EACCES unsafe ownership, mode or link count;
428 * EOVERFLOW name too long; EPROTO embedded NUL; EIO unexpected EOF/short
429 * write; other errno from mkdir/open/read/write/rename/close.
430 */
431static bool video_power_marker(struct lwir_device *device, bool complete)
432{
433 char directory[128], filename[96], temporary[96];
434 int count = snprintf(directory, sizeof(directory), "/run/lock/sensoraia-lwir-%lu", (unsigned long)geteuid());
435 if (count < 0 || (size_t)count >= sizeof(directory) || !device->video_power_key[0] || !device->video_power_port[0]) { errno = EINVAL; return false; }
436 if (mkdir(directory, 0700) && errno != EEXIST) return false;
437 const int folder = open(directory, O_RDONLY | O_DIRECTORY | O_NONBLOCK | O_CLOEXEC | O_NOFOLLOW);
438 if (folder < 0) return false;
439 struct stat identity;
440 bool valid = fstat(folder, &identity) == 0 && S_ISDIR(identity.st_mode)
441 && identity.st_uid == geteuid() && !(identity.st_mode & 0077);
442 if (!valid) { close(folder); errno = EACCES; return false; }
443 count = snprintf(filename, sizeof(filename), "usb-%s.ready", device->video_power_port);
444 int pending = snprintf(temporary, sizeof(temporary), "usb-%s.pending", device->video_power_port);
445 if (count < 0 || (size_t)count >= sizeof(filename) || pending < 0 || (size_t)pending >= sizeof(temporary)) {
446 close(folder); errno = EOVERFLOW; return false;
447 }
448 if (!complete) {
449 const int file = openat(folder, filename, O_RDONLY | O_NONBLOCK | O_CLOEXEC | O_NOFOLLOW);
450 if (file < 0) {
451 const int error = errno;
452 close(folder);
453 if (error == ENOENT) { device->video_power_ready = false; return true; }
454 errno = error; return false;
455 }
456 char key[160] = {0};
457 valid = fstat(file, &identity) == 0 && S_ISREG(identity.st_mode) && identity.st_uid == geteuid()
458 && identity.st_nlink == 1 && !(identity.st_mode & 0077) && identity.st_size > 0 && identity.st_size < (off_t)sizeof(key);
459 if (!valid) errno = EACCES;
460 if (valid) {
461 size_t used = 0;
462 unsigned interruptions = 0;
463 while (used < (size_t)identity.st_size) {
464 const ssize_t received = read(file, key + used, (size_t)identity.st_size - used);
465 if (received < 0 && errno == EINTR && ++interruptions < 8) continue;
466 if (received <= 0) { valid = false; if (!received) errno = EIO; break; }
467 used += (size_t)received;
468 }
469 if (valid && memchr(key, '\0', used)) { valid = false; errno = EPROTO; }
470 }
471 /* Keep the first failure's errno; close errors override it only if they occur. */
472 int error = errno;
473 if (close(file)) { valid = false; error = errno; }
474 if (close(folder)) { valid = false; error = errno; }
475 if (!valid) { errno = error ? error : EIO; return false; }
476 device->video_power_ready = !strcmp(key, device->video_power_key);
477 /* Seed the latched counter so acquisition sees the instance as qualified immediately. */
478 if (device->video_power_ready) device->video_good_frames = 8;
479 return true;
480 }
481 /* A leftover .pending from an interrupted earlier write would make O_EXCL fail forever. */
482 if (unlinkat(folder, temporary, 0) && errno != ENOENT) { const int error = errno; close(folder); errno = error; return false; }
483 const int file = openat(folder, temporary, O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC | O_NOFOLLOW, 0600);
484 if (file < 0) { const int error = errno; close(folder); errno = error; return false; }
485 const size_t length = strlen(device->video_power_key);
486 size_t written = 0;
487 unsigned interruptions = 0;
488 while (written < length) {
489 const ssize_t result = write(file, device->video_power_key + written, length - written);
490 if (result < 0 && errno == EINTR && ++interruptions < 8) continue;
491 if (result <= 0) { valid = false; if (!result) errno = EIO; break; }
492 written += (size_t)result;
493 }
494 int error = errno;
495 /* Close before rename so a write-back error reported at close cannot publish a bad marker. */
496 if (close(file)) { valid = false; error = errno; }
497 if (valid && renameat(folder, temporary, folder, filename)) { valid = false; error = errno; }
498 if (!valid) unlinkat(folder, temporary, 0);
499 if (close(folder)) { valid = false; error = errno; }
500 if (valid) device->video_power_ready = true;
501 else errno = error;
502 return valid;
503}
504
505/**
506 * @brief Release a session in the reverse order of setup.
507 * @details
508 * 1. STREAMOFF returns all buffers from the driver queue to user space.
509 * 2. munmap each mapping. A failed unmap keeps its entry marked as mapped and
510 * the session struct is not cleared, so a later close retries it and
511 * lwir_device_open() refuses with EBUSY rather than losing track of
512 * memory the process still maps.
513 * 3. REQBUFS with count 0 frees the kernel buffers when the driver allows it.
514 * 4. close() the descriptor exactly once. Its state is cleared first and a
515 * close error is only logged: Linux frees the number even on error, so
516 * retrying could close an unrelated descriptor opened by another thread.
517 *
518 * Errors of STREAMOFF/REQBUFS are deliberately ignored; there is no better
519 * recovery than continuing teardown, and closing the descriptor ends the
520 * stream regardless.
521 * @param device Session to release; NULL and already-closed sessions are accepted.
522 * @note errno is preserved so callers can close on an error path without
523 * losing the original cause.
524 */
525void lwir_device_close(struct lwir_device *device)
526{
527 if (!device) return;
528 const int error = errno;
529 bool mappings_remain = false;
530 enum v4l2_buf_type type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
531 if (device->video_open) {
532 if (device->video_streaming) video_ioctl(device->video_fd, VIDIOC_STREAMOFF, &type);
533 }
534 for (unsigned index = 0; index < LWIR_VIDEO_BUFFERS; ++index) {
535 struct lwir_video_buffer *buffer = &device->video_buffers[index];
536 if (!buffer->mapped) continue;
537 if (munmap(buffer->address, buffer->length) == 0) *buffer = (struct lwir_video_buffer){0};
538 else {
539 mappings_remain = true;
540 fprintf(stderr, "LWIR: mapping cleanup failed; ownership retained: %s\n", strerror(errno));
541 }
542 }
543 if (device->video_open) {
544 if (device->video_count) {
545 struct v4l2_requestbuffers buffers = {.type = type, .memory = V4L2_MEMORY_MMAP};
546 video_ioctl(device->video_fd, VIDIOC_REQBUFS, &buffers);
547 }
548 const int descriptor = device->video_fd;
549 device->video_open = false;
550 device->video_streaming = false;
551 device->video_fd = -1;
552 if (close(descriptor)) fprintf(stderr, "LWIR: camera close reported an error: %s\n", strerror(errno));
553 }
554 if (!mappings_remain) *device = (struct lwir_device){0};
555 errno = error;
556}
557
558/**
559 * @brief Negotiate the native format, map the capture buffers and start streaming.
560 * @details
561 * 1. Request the native YUYV format; for the combined layout the transport
562 * height is doubled to carry the temperature plane.
563 * 2. Verify the granted format exactly (video_format_valid()).
564 * 3. REQBUFS for #LWIR_VIDEO_BUFFERS MMAP buffers. The driver may grant a
565 * different count; it is recorded before validation so close frees the
566 * kernel buffers even when the count is rejected.
567 * 4. For each buffer: QUERYBUF, check its size against both the frame and
568 * #LWIR_MAX_FRAME_BYTES, mmap it, record the mapping immediately (so close
569 * can unmap it on any later failure), and queue it to the driver.
570 * 5. STREAMON. lwir_device::video_streaming is set beforehand so close issues
571 * STREAMOFF even if STREAMON failed half-way.
572 *
573 * Cancellation/deadline checkpoints sit between ioctls because each one may
574 * block on USB. On failure the partially built state is left for
575 * lwir_device_close(), which is the single teardown path.
576 * @param device Probed, locked session.
577 * @param options Policy; on success width, height and layout are written back.
578 * @param deadline Absolute CLOCK_MONOTONIC limit in microseconds.
579 * @return True when streaming.
580 * @par Errors
581 * ENOTSUP thermal data required from an image-only camera, unexpected format
582 * or buffer count; EPROTO inconsistent QUERYBUF; EFAULT NULL mapping;
583 * EINTR/ETIMEDOUT checkpoints; other errno from ioctl/mmap.
584 */
585static bool video_setup(struct lwir_device *device, struct lwir_device_options *options, uint64_t deadline)
586{
587 const unsigned width = device->layout == LWIR_COMBINED ? 256U : 640U;
588 const unsigned height = device->layout == LWIR_COMBINED ? 192U : 512U;
589 if (device->layout == LWIR_YUYV_IMAGE && options->requires_thermal) { errno = ENOTSUP; return false; }
590 if (!video_checkpoint(device, deadline)) return false;
591 struct v4l2_format format = {.type = V4L2_BUF_TYPE_VIDEO_CAPTURE, .fmt.pix = {
592 .width = width, .height = height * (device->layout == LWIR_COMBINED ? 2U : 1U),
593 .pixelformat = V4L2_PIX_FMT_YUYV, .field = V4L2_FIELD_NONE}};
594 if (video_ioctl(device->video_fd, VIDIOC_S_FMT, &format)) return false;
595 if (!video_format_valid(options, device->layout, &format)) { errno = ENOTSUP; return false; }
596 device->video_width = width; device->video_height = height;
597 device->video_bytes = format.fmt.pix.sizeimage;
598 struct v4l2_requestbuffers buffers = {.count = LWIR_VIDEO_BUFFERS,
599 .type = V4L2_BUF_TYPE_VIDEO_CAPTURE, .memory = V4L2_MEMORY_MMAP};
600 if (video_ioctl(device->video_fd, VIDIOC_REQBUFS, &buffers)) return false;
601 device->video_count = buffers.count;
602 if (buffers.count < 2 || buffers.count > LWIR_VIDEO_BUFFERS) { errno = ENOTSUP; return false; }
603 for (unsigned index = 0; index < buffers.count; ++index) {
604 if (!video_checkpoint(device, deadline)) return false;
605 struct v4l2_buffer buffer = {.type = buffers.type, .memory = buffers.memory, .index = index};
606 if (video_ioctl(device->video_fd, VIDIOC_QUERYBUF, &buffer)) return false;
607 if (buffer.type != buffers.type || buffer.memory != buffers.memory || buffer.index != index
608 || buffer.length < device->video_bytes || buffer.length > LWIR_MAX_FRAME_BYTES) {
609 errno = EPROTO; return false;
610 }
611 void *address = mmap(NULL, buffer.length, PROT_READ | PROT_WRITE, MAP_SHARED, device->video_fd, buffer.m.offset);
612 if (address == MAP_FAILED) return false;
613 /* Record before the NULL check: even a NULL mapping must still be unmapped by close. */
614 device->video_buffers[index] = (struct lwir_video_buffer){address, buffer.length, true};
615 if (!address) { errno = EFAULT; return false; }
616 if (!video_checkpoint(device, deadline)) return false;
617 if (video_ioctl(device->video_fd, VIDIOC_QBUF, &buffer)) return false;
618 }
619 if (!video_checkpoint(device, deadline)) return false;
620 enum v4l2_buf_type type = buffers.type;
621 /* Set first: a STREAMON that fails may still have changed driver state that STREAMOFF must undo. */
622 device->video_streaming = true;
623 if (video_ioctl(device->video_fd, VIDIOC_STREAMON, &type)) return false;
624 if (!video_checkpoint(device, deadline)) return false;
625 options->width = width; options->height = height; options->layout = device->layout;
626 fprintf(stderr, "LWIR: native V4L2 YUYV %ux%u transport, %ux%u %s\n", width, format.fmt.pix.height,
627 width, height, device->layout == LWIR_COMBINED ? "image and temperature planes" : "image only");
628 fprintf(stderr, "LWIR: %s\n", device->video_power_ready
629 ? "USB instance already started; no frame-count startup wait"
630 : "first startup for this USB instance; qualifying eight frames once");
631 return true;
632}
633
634/**
635 * @brief Find, lock and start exactly one supported camera within the timeout.
636 * @details
637 * 1. Validate options and refuse while the session still owns anything,
638 * including mappings kept after a failed munmap (EBUSY).
639 * 2. Compute one absolute deadline covering discovery and setup.
640 * 3. With an explicit device path, probe only that node. Otherwise probe
641 * /dev/video0..63. A second matching camera is an error (EEXIST) rather
642 * than "first wins": with two cameras attached the choice would depend on
643 * enumeration order, so the caller must disambiguate with a serial or path.
644 * Each match holds its own flock until the scan decides.
645 * 4. Read the startup marker, then set up streaming.
646 *
647 * Every failure after a successful probe closes the session, so the caller
648 * never has to clean up after a false return.
649 * @return True when streaming; errno set otherwise (see lwir_device.h).
650 */
652{
653 if (!options || !device || !options->timeout_ms || options->timeout_ms > 120000 || options->warmup_ms >= options->timeout_ms
654 || ((options->width || options->height) && !lwir_frame_bytes(options->width, options->height))
655 || (options->serial && strnlen(options->serial, sizeof(device->serial)) >= sizeof(device->serial))) {
656 errno = EINVAL; return false;
657 }
658 if (device->video_open) { errno = EBUSY; return false; }
659 for (unsigned index = 0; index < LWIR_VIDEO_BUFFERS; ++index)
660 if (device->video_buffers[index].mapped) { errno = EBUSY; return false; }
661 device->cancelled = options->cancelled;
662 uint64_t started;
663 if (!video_now(&started)) return false;
664 const uint64_t duration = (uint64_t)options->timeout_ms * 1000U;
665 if (started > UINT64_MAX - duration) { errno = EOVERFLOW; return false; }
666 const uint64_t deadline = started + duration;
667 if (!video_checkpoint(device, deadline)) return false;
668 if (options->device_path) {
669 if (!options->device_path[0]) { errno = EINVAL; return false; }
670 if (video_probe(options->device_path, options, device) != 1) return false;
671 } else {
672 for (unsigned index = 0; index < 64; ++index) {
673 if (!video_checkpoint(device, deadline)) { lwir_device_close(device); return false; }
674 char path[64];
675 snprintf(path, sizeof(path), "/dev/video%u", index);
676 struct lwir_device candidate = {0};
677 const int result = video_probe(path, options, &candidate);
678 if (result < 0) { lwir_device_close(device); return false; }
679 if (result == 1) {
680 /* Ambiguity: release both locks so neither camera stays held by a failed open. */
681 if (device->video_open) {
682 lwir_device_close(&candidate); lwir_device_close(device);
683 errno = EEXIST; return false;
684 }
685 *device = candidate;
686 }
687 }
688 if (!device->video_open) { errno = ENODEV; return false; }
689 }
690 if (!video_power_marker(device, false) || !video_setup(device, options, deadline)) { lwir_device_close(device); return false; }
691 return true;
692}
693
694/**
695 * @brief Extend the kernel's 32-bit frame sequence to a monotonic 64-bit count.
696 * @details The forward distance is computed in unsigned 32-bit arithmetic,
697 * so wrap-around of the kernel counter is handled naturally. A zero distance
698 * (repeated number) or a distance above half the range (interpreted as going
699 * backwards) is rejected as inconsistent. Dropped frames advance the 64-bit
700 * count by the full distance so gaps stay visible in observations, and are
701 * reported as non-continuous to the qualification logic.
702 * @param device Session sequence state, updated on success.
703 * @param sequence Raw v4l2_buffer::sequence.
704 * @param continuous Output: true for the first frame or an exact successor.
705 * @return False for a duplicate, backwards or overflowing sequence (state unchanged).
706 * @note The first frame is numbered raw + 1. The reason for the offset is not
707 * documented in the code; it at least keeps the extended value non-zero.
708 */
709static bool video_sequence(struct lwir_device *device, uint32_t sequence, bool *continuous)
710{
711 *continuous = !device->video_have_sequence || sequence == device->video_last_sequence + 1U;
712 if (!device->video_have_sequence) device->video_sequence = (uint64_t)sequence + 1;
713 else {
714 const uint32_t distance = sequence - device->video_last_sequence;
715 if (!distance || distance > UINT32_MAX / 2U || device->video_sequence > UINT64_MAX - distance) return false;
716 device->video_sequence += distance;
717 }
718 device->video_last_sequence = sequence;
719 device->video_have_sequence = true;
720 return true;
721}
722
723/**
724 * @brief Poison the session after a fatal kernel or protocol error.
725 * @details After an unexpected DQBUF/QBUF/poll failure the driver queue is
726 * in an unknown state (a buffer may be lost or still owned by user space).
727 * Rather than guess, every later operation fails with EIO until the caller
728 * closes and reopens, which rebuilds the queue from scratch.
729 * @param device Session to poison.
730 * @param error errno value to report.
731 * @return Always false, for direct use in return statements.
732 */
733static bool video_fail(struct lwir_device *device, int error)
734{
735 device->video_failed = true;
736 errno = error;
737 return false;
738}
739
740/**
741 * @brief Verify session invariants before touching the stream.
742 * @details Re-derives the expected geometry and frame size from the layout and
743 * checks every mapping. This guards against use of a zeroed, closed, partially
744 * opened or caller-corrupted session, which would otherwise lead to reads
745 * outside a mapping.
746 * @param device Session to check; NULL accepted.
747 * @return True when streaming and consistent.
748 * @par Errors
749 * EINVAL not open/streaming or inconsistent; EIO poisoned by video_fail().
750 */
751static bool video_ready(const struct lwir_device *device)
752{
753 if (!device || !device->video_open || !device->video_streaming || device->video_fd < 0
754 || device->video_count < 2 || device->video_count > LWIR_VIDEO_BUFFERS
755 || (device->layout != LWIR_COMBINED && device->layout != LWIR_YUYV_IMAGE)) { errno = EINVAL; return false; }
756 if (device->video_failed) { errno = EIO; return false; }
757 const unsigned width = device->layout == LWIR_COMBINED ? 256U : 640U;
758 const unsigned height = device->layout == LWIR_COMBINED ? 192U : 512U;
759 const size_t bytes = lwir_frame_bytes(width, height) / (device->layout == LWIR_COMBINED ? 1U : 2U);
760 if (device->video_width != width || device->video_height != height || device->video_bytes != bytes) { errno = EINVAL; return false; }
761 for (unsigned index = 0; index < device->video_count; ++index) {
762 const struct lwir_video_buffer *buffer = &device->video_buffers[index];
763 if (!buffer->mapped || !buffer->address || buffer->address == MAP_FAILED
764 || buffer->length < bytes || buffer->length > LWIR_MAX_FRAME_BYTES) { errno = EINVAL; return false; }
765 }
766 return true;
767}
768
769/**
770 * @brief Reject caller memory that overlaps any mapped camera buffer.
771 * @details A destination inside a mapping would let the copy read and write
772 * the same kernel-owned memory, and the kernel may rewrite it after requeue.
773 * Address arithmetic is done on uintptr_t with explicit wrap checks, so a
774 * range that wraps around the address space is rejected instead of passing
775 * the overlap test by overflow.
776 * @param device Session whose first @c video_count mappings are checked.
777 * @param destination Start of the caller range.
778 * @param bytes Length of the caller range.
779 * @return True when the range is well-formed and disjoint from every mapping.
780 */
781static bool video_destination_valid(const struct lwir_device *device, const void *destination, size_t bytes)
782{
783 const uintptr_t start = (uintptr_t)destination;
784 if (start > UINTPTR_MAX - bytes) return false;
785 for (unsigned index = 0; index < device->video_count; ++index) {
786 const uintptr_t mapped = (uintptr_t)device->video_buffers[index].address;
787 const size_t length = device->video_buffers[index].length;
788 /* Half-open interval overlap test, after ruling out a wrapping mapping end. */
789 if (mapped > UINTPTR_MAX - length || (start < mapped + length && mapped < start + bytes)) return false;
790 }
791 return true;
792}
793
794/**
795 * @brief Test that two byte ranges do not overlap.
796 * @details Compares the lengths against the gap between the start addresses
797 * instead of computing end addresses, so no addition can overflow. Used to
798 * keep the frame, the observation and the session struct apart: an overlap
799 * would let a frame copy corrupt the session or the observation.
800 * @param first Start of the first range.
801 * @param first_bytes Length of the first range.
802 * @param second Start of the second range.
803 * @param second_bytes Length of the second range.
804 * @return True when the ranges are disjoint (touching ranges are disjoint).
805 */
806static bool video_ranges_separate(const void *first, size_t first_bytes, const void *second, size_t second_bytes)
807{
808 const uintptr_t first_start = (uintptr_t)first, second_start = (uintptr_t)second;
809 return first_start <= second_start ? first_bytes <= second_start - first_start : second_bytes <= first_start - second_start;
810}
811
812/**
813 * @brief Return a dequeued buffer to the driver.
814 * @details A fresh v4l2_buffer is used rather than the dequeued one, so the
815 * caller's copy of sequence/timestamp/flags is not touched by the ioctl.
816 * Failure is fatal: the buffer has left the ring and the stream would
817 * silently run with fewer buffers.
818 * @param device Session.
819 * @param index Buffer index previously dequeued.
820 * @return True on success; false after video_fail().
821 */
822static bool video_requeue(struct lwir_device *device, unsigned index)
823{
824 struct v4l2_buffer buffer = {.type = V4L2_BUF_TYPE_VIDEO_CAPTURE, .memory = V4L2_MEMORY_MMAP, .index = index};
825 if (video_ioctl(device->video_fd, VIDIOC_QBUF, &buffer)) return video_fail(device, errno);
826 return true;
827}
828
829/**
830 * @brief Non-blocking VIDIOC_DQBUF with validation of what the kernel returned.
831 * @details EAGAIN (nothing ready on the O_NONBLOCK descriptor) and EINTR after
832 * the bounded retries are reported as "no frame", not errors. An index outside
833 * the mapped set is fatal without requeue, since an unknown index cannot be
834 * returned safely. A wrong type or memory model is requeued first, so the
835 * ring stays complete, and then treated as fatal.
836 * @param device Session.
837 * @param buffer Output: dequeued buffer metadata, valid when @p received.
838 * @param received Output: whether a buffer is now owned by the caller.
839 * @return True on success (with or without a frame); false after video_fail().
840 * @warning When @p received is true the caller owns the buffer and must call
841 * video_requeue() on every path.
842 */
843static bool video_dequeue(struct lwir_device *device, struct v4l2_buffer *buffer, bool *received)
844{
845 *buffer = (struct v4l2_buffer){.type = V4L2_BUF_TYPE_VIDEO_CAPTURE, .memory = V4L2_MEMORY_MMAP};
846 *received = false;
847 if (video_ioctl(device->video_fd, VIDIOC_DQBUF, buffer)) {
848 if (errno == EAGAIN || errno == EINTR) return true;
849 return video_fail(device, errno);
850 }
851 if (buffer->index >= device->video_count || buffer->index >= LWIR_VIDEO_BUFFERS
852 || !device->video_buffers[buffer->index].mapped) return video_fail(device, EPROTO);
853 if (buffer->type != V4L2_BUF_TYPE_VIDEO_CAPTURE || buffer->memory != V4L2_MEMORY_MMAP) {
854 if (!video_requeue(device, buffer->index)) return false;
855 return video_fail(device, EPROTO);
856 }
857 *received = true;
858 return true;
859}
860
861/**
862 * @brief Check that a MONOTONIC kernel timestamp lies within [start, now].
863 * @details uvcvideo stamps buffers at start of frame. Requiring the stamp to
864 * be at or after the request start guarantees the image was not exposed
865 * before the trigger. A stamp after @p now is impossible on one clock and is
866 * rejected as inconsistent. Buffers whose clock is not MONOTONIC cannot be
867 * compared and pass here; lwir_device_acquire() compensates by draining the
868 * already-queued buffers once.
869 * @param buffer Dequeued buffer.
870 * @param start Earliest acceptable time, CLOCK_MONOTONIC microseconds.
871 * @param now Host time at dequeue, CLOCK_MONOTONIC microseconds.
872 * @return True when fresh or when freshness cannot be judged.
873 */
874static bool video_timestamp_fresh(const struct v4l2_buffer *buffer, uint64_t start, uint64_t now)
875{
876 if ((buffer->flags & V4L2_BUF_FLAG_TIMESTAMP_MASK) != V4L2_BUF_FLAG_TIMESTAMP_MONOTONIC) return true;
877 if (buffer->timestamp.tv_sec < 0 || buffer->timestamp.tv_usec < 0 || buffer->timestamp.tv_usec >= 1000000
878 || (uint64_t)buffer->timestamp.tv_sec > (UINT64_MAX - (uint64_t)buffer->timestamp.tv_usec) / 1000000U) return false;
879 const uint64_t timestamp = (uint64_t)buffer->timestamp.tv_sec * 1000000U + (uint64_t)buffer->timestamp.tv_usec;
880 return timestamp >= start && timestamp <= now;
881}
882
883/**
884 * @brief Structural and content check of a dequeued frame, independent of the request.
885 * @details Rejects driver-flagged errors, short or oversized payloads, and
886 * stamps older than max(@p start, now - 1 s). The one-second window lets
887 * frames that arrived before a request still count toward startup
888 * qualification while excluding stale backlog. For the combined layout,
889 * lwir_frame_capture_valid() rejects the neutral fill frames (all byte pairs
890 * 00,80) the Tiny1-C emits at transitions, and an invalid thermal plane.
891 * @param device Session (layout, geometry, mappings).
892 * @param buffer Dequeued buffer, still owned by the caller.
893 * @param start Additional lower time bound; 0 for none.
894 * @param now Host time at dequeue.
895 * @return True when the frame is usable for qualification.
896 */
897static bool video_frame_qualified(const struct lwir_device *device, const struct v4l2_buffer *buffer,
898 uint64_t start, uint64_t now)
899{
900 const uint64_t recent = now > 1000000U ? now - 1000000U : 0;
901 if ((buffer->flags & V4L2_BUF_FLAG_ERROR) || buffer->bytesused != device->video_bytes
902 || buffer->length < buffer->bytesused || buffer->length > device->video_buffers[buffer->index].length
903 || !video_timestamp_fresh(buffer, start > recent ? start : recent, now)) return false;
904 return device->layout != LWIR_COMBINED || lwir_frame_capture_valid(
905 device->video_buffers[buffer->index].address, buffer->bytesused, device->video_width, device->video_height);
906}
907
908/**
909 * @brief Advance the eight-consecutive-good-frames startup counter.
910 * @details Once eight is reached the counter latches for the rest of the USB
911 * power instance: later bad frames or gaps must not impose another startup
912 * wait. Before that, an invalid frame resets to zero and a sequence gap
913 * restarts the count with the current frame as the first good one.
914 * @param device Session counter and last-good arrival time.
915 * @param valid Result of video_frame_qualified() and the sequence check.
916 * @param continuous Whether the frame directly follows the previous one.
917 * @param now Host arrival time of the frame.
918 */
919static void video_qualification(struct lwir_device *device, bool valid, bool continuous, uint64_t now)
920{
921 if (device->video_good_frames >= 8) return;
922 if (!valid) { device->video_good_frames = 0; return; }
923 if (!continuous) device->video_good_frames = 0;
924 if (device->video_good_frames < 8) ++device->video_good_frames;
925 device->video_good_arrival_us = now;
926}
927
928/**
929 * @brief Wait for, validate and copy the first acceptable frame that started after this call.
930 * @details
931 * Loop structure, each iteration bounded by a 25 ms poll() slice so that
932 * cancellation and the deadline are noticed promptly:
933 * 1. poll() for a filled buffer; POLLERR/POLLHUP/POLLNVAL (for example an
934 * unplugged camera) poison the session.
935 * 2. Dequeue one buffer and read the host clock immediately.
936 * 3. Grade the frame in increasing strictness:
937 * - @c usable: structurally valid, recent, correct sequence; feeds the
938 * startup qualification counter even when it predates the request.
939 * - @c valid: additionally started at or after the request (freshness).
940 * - @c scene_valid: additionally passes the optional scene check.
941 * 4. For non-MONOTONIC clocks freshness is unknowable, so the first good
942 * frame triggers a one-time drain of all already-queued buffers; the next
943 * frame is then certainly produced after the request.
944 * 5. Accept when the instance is qualified (eight good frames), optional
945 * settling holds, and on first startup only, @c warmup_ms has elapsed.
946 * 6. Copy what is needed and snapshot sequence/timestamp/flags, then requeue.
947 * The order matters: after QBUF the kernel may overwrite both pixels and
948 * metadata.
949 * 7. Persist the startup marker once qualification and warmup are complete.
950 *
951 * Settling uses @p destination as the previous-image store: the image plane
952 * of each scene-valid frame is copied there and the next frame is compared
953 * against it, so no extra buffer is needed. The temperature plane is copied
954 * only for the accepted frame.
955 * @return True with a fresh frame in @p destination.
956 * @par Errors
957 * EINVAL arguments/aliasing; EIO poisoned session or poll error; ETIMEDOUT
958 * deadline, including completion that would land after it; EINTR cancelled;
959 * kernel errno from failed ioctls (session then poisoned).
960 * @warning On failure @p destination may contain partial or settling data and
961 * must be ignored.
962 */
964 uint8_t *destination, size_t capacity, struct lwir_device_observation *observation)
965{
966 if (!options || !destination || !observation) { errno = EINVAL; return false; }
967 if (!video_ready(device)) return false;
968 if (capacity < device->video_bytes || !video_destination_valid(device, destination, device->video_bytes)
969 || !video_destination_valid(device, observation, sizeof(*observation))
970 || !video_ranges_separate(destination, device->video_bytes, observation, sizeof(*observation))
971 || !video_ranges_separate(destination, device->video_bytes, device, sizeof(*device))
972 || !video_ranges_separate(observation, sizeof(*observation), device, sizeof(*device)) || options->width != device->video_width
973 || options->height != device->video_height || !options->timeout_ms || options->timeout_ms > 120000
974 || options->warmup_ms >= options->timeout_ms) { errno = EINVAL; return false; }
975 uint64_t start;
976 if (!video_now(&start)) return false;
977 const uint64_t duration = (uint64_t)options->timeout_ms * 1000U;
978 if (start > UINT64_MAX - duration) { errno = EOVERFLOW; return false; }
979 const uint64_t deadline = start + duration;
980 /* Only the first startup of a USB instance may wait for warmup; it also makes the non-MONOTONIC drain redundant. */
981 const bool first_startup = !device->video_power_ready;
982 bool request_queue_drained = first_startup;
983 bool have_previous_image = false;
984 unsigned skipped = 0;
985 uint64_t last_arrival = start;
986 const size_t image_bytes = device->layout == LWIR_COMBINED ? device->video_bytes / 2 : device->video_bytes;
987 while (!video_cancelled(device)) {
988 uint64_t now;
989 if (!video_now(&now)) return false;
990 if (now < start || now >= deadline) { errno = ETIMEDOUT; return false; }
991 /* Round up so a sub-millisecond remainder still polls instead of spinning with timeout 0. */
992 const uint64_t remaining = (deadline - now + 999U) / 1000U;
993 struct pollfd descriptor = {.fd = device->video_fd, .events = POLLIN};
994 const int ready = poll(&descriptor, 1, remaining > 25 ? 25 : (int)remaining);
995 if (ready < 0 && errno == EINTR) continue;
996 if (ready < 0) return video_fail(device, errno);
997 if (!ready) continue;
998 if (descriptor.revents & (POLLERR | POLLHUP | POLLNVAL)) return video_fail(device, EIO);
999 if (!(descriptor.revents & POLLIN)) continue;
1000 if (video_cancelled(device)) break;
1001 struct v4l2_buffer buffer;
1002 bool received;
1003 if (!video_dequeue(device, &buffer, &received)) return false;
1004 if (!received) continue;
1005 /* From here the buffer is owned: every path below must requeue it before returning. */
1006 const bool clock_read = video_now(&now);
1007 const int clock_error = errno;
1008 const bool clock_valid = clock_read && now >= start && now < deadline;
1009 bool continuous = false;
1010 const bool sequence_valid = video_sequence(device, buffer.sequence, &continuous);
1011 /* usable ignores the request start so pre-request frames still count toward qualification. */
1012 const bool usable = clock_valid && sequence_valid && video_frame_qualified(device, &buffer, 0, now);
1013 const bool valid = usable && video_timestamp_fresh(&buffer, start, now);
1014 const uint8_t *source = device->video_buffers[buffer.index].address;
1015 /* The scene check exists only for combined data, so requesting it on image-only rejects every frame. */
1016 const bool scene_valid = valid && (!options->scene_check
1017 || (device->layout == LWIR_COMBINED && lwir_frame_plausible(source, buffer.bytesused, options->width, options->height)));
1018 if (!scene_valid && skipped < UINT_MAX) ++skipped;
1019 const bool monotonic = (buffer.flags & V4L2_BUF_FLAG_TIMESTAMP_MASK) == V4L2_BUF_FLAG_TIMESTAMP_MONOTONIC;
1020 video_qualification(device, usable, continuous, now);
1021 /* Unknown clock: this frame may predate the request. Discard it and the queued backlog once,
1022 * bounded by the buffer count so a fast stream cannot keep this loop busy. */
1023 if (scene_valid && !monotonic && !request_queue_drained) {
1024 if (!video_requeue(device, buffer.index)) return false;
1025 for (unsigned index = 0; index < device->video_count; ++index) {
1026 bool pending;
1027 if (!lwir_device_discard(device, &pending)) return false;
1028 if (!pending) break;
1029 }
1030 request_queue_drained = true;
1031 continue;
1032 }
1033 bool accepted = false;
1034 if (!scene_valid) have_previous_image = false;
1035 else {
1036 /* destination holds the previous scene-valid image plane; compare before overwriting it.
1037 * A gap or >1 s pause makes that comparison meaningless, so settling restarts. */
1038 const bool settled = have_previous_image && continuous && now - last_arrival <= 1000000U
1039 && (!options->settle || lwir_frame_settled(source, destination, options->width, options->height));
1040 have_previous_image = true;
1041 const bool qualified = device->video_good_frames >= 8;
1042 const bool settled_now = !options->settle || settled;
1043 accepted = qualified && settled_now && (!first_startup || now - start >= (uint64_t)options->warmup_ms * 1000U);
1044 /* Bounded byte loops instead of memcpy (project policy); they still vectorize. */
1045 if (options->settle || accepted) for (size_t index = 0; index < image_bytes; ++index) destination[index] = source[index];
1046 if (accepted && device->layout == LWIR_COMBINED)
1047 for (size_t index = image_bytes; index < device->video_bytes; ++index) destination[index] = source[index];
1048 }
1049 last_arrival = now;
1050 struct lwir_device_observation selected = {0};
1051 /* Snapshot metadata before QBUF: the driver may clear or rewrite it once requeued. */
1052 if (accepted) {
1053 selected = (struct lwir_device_observation){.sequence = device->video_sequence, .arrival_us = now,
1054 .kernel_monotonic_us = monotonic ? (uint64_t)buffer.timestamp.tv_sec * 1000000U + (uint64_t)buffer.timestamp.tv_usec : 0,
1055 .kernel_timestamp_flags = buffer.flags & (V4L2_BUF_FLAG_TIMESTAMP_MASK | V4L2_BUF_FLAG_TSTAMP_SRC_MASK)};
1056 }
1057 if (!video_requeue(device, buffer.index)) return false;
1058 /* Clock failure is reported only now, after the buffer is safely back in the ring. */
1059 if (!clock_valid) { errno = clock_read ? ETIMEDOUT : clock_error; return false; }
1060 /* A marker that cannot be written is fatal rather than silently forcing a future warmup. */
1061 if (!device->video_power_ready && device->video_good_frames >= 8
1062 && now - start >= (uint64_t)options->warmup_ms * 1000U && !video_power_marker(device, true)) return video_fail(device, errno);
1063 if (accepted) {
1064 /* Copy and marker I/O take time; never hand back a result past the caller's budget. */
1065 uint64_t finished;
1066 if (!video_now(&finished) || finished < now || finished >= deadline) { errno = ETIMEDOUT; return false; }
1067 if (video_cancelled(device)) break;
1068 if (skipped) fprintf(stderr, "LWIR: skipped %u unusable/stale frames before capture; startup wait was %s\n",
1069 skipped, first_startup ? "initial-only" : "disabled");
1070 *observation = selected;
1071 return true;
1072 }
1073 }
1074 errno = EINTR;
1075 return false;
1076}
1077
1078/**
1079 * @brief Dequeue and immediately requeue at most one pending frame.
1080 * @details Used to empty the queue (for example the non-MONOTONIC drain in
1081 * lwir_device_acquire()) and to keep the stream moving between requests.
1082 * The frame still feeds startup qualification with the one-second recency
1083 * window, and the marker is published as soon as eight good frames are seen;
1084 * no warmup delay applies here because there is no request start to measure from.
1085 * @return True on success, including when no frame was pending.
1086 * @par Errors
1087 * EINVAL bad arguments or session; EIO poisoned; EINTR cancelled; kernel or
1088 * clock errno (session then poisoned).
1089 */
1090bool lwir_device_discard(struct lwir_device *device, bool *received)
1091{
1092 if (!received) { errno = EINVAL; return false; }
1093 if (!video_ready(device)) return false;
1094 if (video_cancelled(device)) { errno = EINTR; return false; }
1095 struct v4l2_buffer buffer;
1096 if (!video_dequeue(device, &buffer, received)) return false;
1097 if (!*received) return true;
1098 bool continuous;
1099 const bool sequence_valid = video_sequence(device, buffer.sequence, &continuous);
1100 uint64_t now;
1101 const bool clock_valid = video_now(&now);
1102 if (!clock_valid) {
1103 /* Return the buffer first so the poisoned session still holds a complete ring for close. */
1104 const int error = errno;
1105 if (!video_requeue(device, buffer.index)) return false;
1106 return video_fail(device, error);
1107 }
1108 video_qualification(device, sequence_valid && video_frame_qualified(device, &buffer, 0, now), continuous, now);
1109 if (!video_requeue(device, buffer.index)) return false;
1110 if (!device->video_power_ready && device->video_good_frames >= 8 && !video_power_marker(device, true)) return video_fail(device, errno);
1111 return true;
1112}
1113
1114/** @brief Context handed to the lwir_state.c protocol through struct lwir_state_io. */
1116 struct lwir_device *device; /**< Session supplying the cancellation flag. */
1117 int descriptor; /**< usbfs descriptor, open only for the duration of one operation. */
1118};
1119
1120/**
1121 * @brief One Tiny1-C vendor mailbox control transfer over usbfs.
1122 * @details Reads use bmRequestType 0xc1 / bRequest 0x44 and writes 0x41 /
1123 * 0x45 (vendor type, interface recipient), with wValue 0x78 and the mailbox
1124 * address in wIndex. Linux usbfs permits vendor-type control requests without
1125 * claiming the interface, so uvcvideo is never detached and streaming
1126 * continues undisturbed. Length (64 bytes) and timeout (50 ms) caps keep a
1127 * misbehaving camera from blocking the caller for long.
1128 * @param context struct video_state_transport.
1129 * @param input True for device-to-host (read), false for host-to-device (write).
1130 * @param address Mailbox address placed in wIndex.
1131 * @param data Transfer buffer of @p length bytes.
1132 * @param length 1..64 bytes.
1133 * @param timeout 1..50 milliseconds.
1134 * @return Bytes transferred, or a negative code interpreted by lwir_state.c:
1135 * -10 cancelled/interrupted, -7 timeout, -2 invalid argument, -1 other
1136 * I/O error. These values follow the numbering of the retired libusb
1137 * backend so lwir_state.c stays backend-neutral.
1138 */
1139static int video_state_transfer(void *context, bool input, uint16_t address, uint8_t *data,
1140 unsigned length, unsigned timeout)
1141{
1142 const struct video_state_transport *transport = context;
1143 if (video_cancelled(transport->device)) return -10;
1144 if (!data || !length || length > 64 || !timeout || timeout > 50) return -2;
1145 struct usbdevfs_ctrltransfer control = {.bRequestType = input ? 0xc1 : 0x41,
1146 .bRequest = input ? 0x44 : 0x45, .wValue = 0x78, .wIndex = address,
1147 .wLength = (uint16_t)length, .timeout = timeout, .data = data};
1148 const int result = ioctl(transport->descriptor, USBDEVFS_CONTROL, &control);
1149 if (result >= 0) return result;
1150 return errno == ETIMEDOUT ? -7 : errno == EINTR ? -10 : -1;
1151}
1152
1153/**
1154 * @brief Clock callback for lwir_state.c.
1155 * @param context Unused.
1156 * @return CLOCK_MONOTONIC microseconds, or UINT64_MAX if the clock fails so
1157 * that any deadline comparison in the protocol treats it as expired.
1158 */
1159static uint64_t video_state_now(void *context)
1160{
1161 (void)context;
1162 uint64_t now;
1163 return video_now(&now) ? now : UINT64_MAX;
1164}
1165
1166/**
1167 * @brief Short cancellable delay between mailbox polls for lwir_state.c.
1168 * @details nanosleep() is resumed with the remaining time after signals, but
1169 * cancellation is checked on every interruption so a cancel request ends the
1170 * pause immediately. The 10 ms cap keeps cancellation latency small.
1171 * @param context struct video_state_transport.
1172 * @param milliseconds 1..10.
1173 * @return True when the full delay elapsed without cancellation.
1174 */
1175static bool video_state_pause(void *context, unsigned milliseconds)
1176{
1177 const struct video_state_transport *transport = context;
1178 if (!milliseconds || milliseconds > 10 || video_cancelled(transport->device)) return false;
1179 struct timespec remaining = {.tv_nsec = (long)milliseconds * 1000000L};
1180 while (nanosleep(&remaining, &remaining))
1181 if (errno != EINTR || video_cancelled(transport->device)) return false;
1182 return !video_cancelled(transport->device);
1183}
1184
1185/**
1186 * @brief Confirm the streaming camera is still the same USB power instance.
1187 * @details Re-derives the identity from the open V4L2 descriptor and compares
1188 * power key, bus and address with those recorded at open. If the camera
1189 * re-enumerated meanwhile, the stored bus/address may now name a different
1190 * device, and vendor writes must never reach it.
1191 * @param device Open session.
1192 * @return True when unchanged and combined-layout.
1193 * @par Errors
1194 * ENODEV identity changed or unavailable; errno from fstat().
1195 */
1196static bool video_state_identity(struct lwir_device *device)
1197{
1198 struct stat node;
1199 enum lwir_frame_layout layout;
1200 char serial[64], key[160], port[64];
1201 unsigned bus, address;
1202 if (fstat(device->video_fd, &node)) return false;
1203 if (!video_identity(&node, &layout, serial, key, port, &bus, &address)) { errno = ENODEV; return false; }
1204 if (layout != LWIR_COMBINED || strcmp(key, device->video_power_key)
1205 || bus != device->video_usb_bus || address != device->video_usb_address) { errno = ENODEV; return false; }
1206 return true;
1207}
1208
1209/**
1210 * @brief Open the usbfs node of the streaming Tiny1-C for one state/control operation.
1211 * @details
1212 * 1. Require a healthy combined-layout session and verify identity.
1213 * 2. Open /dev/bus/usb/BBB/DDD.
1214 * 3. Check the opened node is the expected usbfs character device: major 189,
1215 * minor (bus - 1) * 128 + address - 1.
1216 * 4. Verify identity again after open, closing the window in which the camera
1217 * could re-enumerate and another device take over the address.
1218 *
1219 * The node is opened per operation and closed on every path by the caller,
1220 * so no usbfs handle outlives a single request.
1221 * @param device Open, healthy session.
1222 * @return usbfs descriptor, or -1 with errno set.
1223 * @par Errors
1224 * EINVAL/EIO session not ready; ENOTSUP image-only camera; EINTR cancelled;
1225 * ENODEV identity mismatch; EOVERFLOW path too long; errno from open/fstat.
1226 */
1227static int video_state_open(struct lwir_device *device)
1228{
1229 if (!video_ready(device)) return -1;
1230 if (device->layout != LWIR_COMBINED) { errno = ENOTSUP; return -1; }
1231 if (video_cancelled(device)) { errno = EINTR; return -1; }
1232 if (!video_state_identity(device)) return -1;
1233 char path[64];
1234 const int length = snprintf(path, sizeof(path), "/dev/bus/usb/%03u/%03u", device->video_usb_bus, device->video_usb_address);
1235 if (length <= 0 || (size_t)length >= sizeof(path)) { errno = EOVERFLOW; return -1; }
1236 const int descriptor = open(path, O_RDWR | O_NONBLOCK | O_CLOEXEC | O_NOFOLLOW);
1237 if (descriptor < 0) return -1;
1238 struct stat node;
1239 const dev_t expected = makedev(189, (device->video_usb_bus - 1U) * 128U + device->video_usb_address - 1U);
1240 int error = 0;
1241 if (fstat(descriptor, &node)) error = errno;
1242 else if (!S_ISCHR(node.st_mode) || node.st_rdev != expected) error = ENODEV;
1243 else if (!video_state_identity(device)) error = errno;
1244 if (error) { close(descriptor); errno = error; return -1; }
1245 return descriptor;
1246}
1247
1248/**
1249 * @brief Shared implementation of control write and read-back.
1250 * @details Validates the request, opens usbfs, runs the lwir_state.c
1251 * mailbox protocol once, and closes usbfs. The reply status is mapped to
1252 * errno for callers that only check errno. A close error turns the result
1253 * into a failure even though a write may already have been submitted;
1254 * nothing is replayed, so the caller should read back instead of retrying.
1255 * @param device Open combined-layout session.
1256 * @param request Control kind and value.
1257 * @param result Output reply; reset to LWIR_STATE_INVALID first.
1258 * @param read_only True for a read; FFC is an action and has no read form.
1259 * @return True on success.
1260 * @par Errors
1261 * EINVAL invalid request; errno from video_state_open(); EINTR cancelled;
1262 * ETIMEDOUT camera timeout; EIO any other protocol failure.
1263 */
1264static bool video_control(struct lwir_device *device, const struct lwir_control_request *request,
1265 struct lwir_control_result *result, bool read_only)
1266{
1267 if (!result) { errno = EINVAL; return false; }
1268 *result = (struct lwir_control_result){.reply = {.status = LWIR_STATE_INVALID}};
1269 if (!lwir_control_valid(request) || (read_only && request->kind == LWIR_CONTROL_FFC)) { errno = EINVAL; return false; }
1270 const int descriptor = video_state_open(device);
1271 if (descriptor < 0) {
1272 result->reply.status = errno == EINTR ? LWIR_STATE_CANCELLED : errno == ENOTSUP ? LWIR_STATE_UNSUPPORTED : LWIR_STATE_IO_ERROR;
1273 result->reply.transport_error = -errno;
1274 return false;
1275 }
1276 struct video_state_transport transport = {.device = device, .descriptor = descriptor};
1278 bool success = read_only ? lwir_state_control_read(&io, request->kind, result) : lwir_state_control(&io, request, result);
1279 if (close(descriptor)) success = false;
1280 if (!success) errno = result->reply.status == LWIR_STATE_CANCELLED ? EINTR :
1281 result->reply.status == LWIR_STATE_TIMEOUT ? ETIMEDOUT : EIO;
1282 return success;
1283}
1284
1285/**
1286 * @brief Public control write; see lwir_device.h.
1287 * @return True when acknowledged.
1288 */
1291{
1292 return video_control(device, request, result, false);
1293}
1294
1295/**
1296 * @brief Public control read; see lwir_device.h.
1297 * @details Builds a request only so the shared validation path can be reused.
1298 * @return True when the value was read.
1299 */
1302{
1303 /* Placeholder value only; presumably needed to satisfy lwir_control_valid() for emissivity. Nothing is written. */
1304 const struct lwir_control_request request = {.kind = kind, .value = kind == LWIR_CONTROL_EMISSIVITY ? 1 : 0};
1305 return video_control(device, &request, result, true);
1306}
1307
1308/**
1309 * @brief Best-effort read-only snapshot of Tiny1-C state; never writes settings.
1310 * @details All fields start as skipped and the first as an I/O error, so a
1311 * failure to open usbfs is reported on a field instead of looking like an
1312 * empty but successful read. lwir_state_read() overwrites what it reaches.
1313 * The usbfs close result is ignored because nothing was written. Image-only
1314 * sessions (or NULL) return a zero, not-requested snapshot without any USB
1315 * traffic.
1316 * @note errno is preserved; outcomes are reported only through @p state.
1317 * @note The snapshot is taken after the frame and is not frame-atomic.
1318 */
1319void lwir_device_read_state(struct lwir_device *device, struct lwir_device_state *state)
1320{
1321 if (!state) return;
1322 const int error = errno;
1323 *state = (struct lwir_device_state){0};
1324 if (device && device->layout == LWIR_COMBINED) {
1325 state->requested = true;
1326 video_now(&state->started_us);
1327 state->finished_us = state->started_us;
1328 for (unsigned index = 0; index < LWIR_STATE_FIELDS; ++index) state->values[index].status = LWIR_STATE_SKIPPED;
1329 state->values[0].status = LWIR_STATE_IO_ERROR;
1330 struct video_state_transport transport = {.device = device, .descriptor = video_state_open(device)};
1331 if (transport.descriptor >= 0) {
1332 const struct lwir_state_io io = {&transport, video_state_transfer, video_state_now, video_state_pause};
1333 lwir_state_read(&io, state);
1334 close(transport.descriptor);
1335 } else {
1336 state->values[0].transport_error = -errno;
1337 }
1338 if (video_cancelled(device)) state->values[0].status = LWIR_STATE_CANCELLED;
1339 }
1340 errno = error;
1341}
static unsigned capacity[COVERAGE_CAMERAS]
uint8_t bytes[CHDK_CONTROL_REPLY_SIZE]
Definition chdk_pipe.c:144
int descriptor
Definition chdk_pipe.c:142
void(* close)(struct usbfs_handle *)
Definition chdkbridge.c:57
static bool capture(struct transport *transport, FILE *file, const struct capture_settings *settings)
Capture to the camera's SD card and download the resulting JPEG.
int(* open)(const struct usbfs_device *, struct usbfs_handle *)
Definition chdkbridge.c:56
static bool start(uint32_t session)
Admit a nonzero session and discard correlation from the previous one.
static uint64_t milliseconds(void)
Read elapsed-time evidence unaffected by changes to civil time.
union dc_shot_union request
static bool pending
static bool started
static bool ready
Tiny1C/TDK acquisition and Tiny1C state, without image or mission logic.
#define LWIR_VIDEO_BUFFERS
Number of V4L2 MMAP buffers requested from uvcvideo.
Definition lwir_device.h:70
static bool video_now(uint64_t *microseconds)
Read CLOCK_MONOTONIC in microseconds.
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 int video_ioctl(int descriptor, unsigned long request, void *argument)
ioctl() with a bounded retry on EINTR.
static bool video_checkpoint(const struct lwir_device *device, uint64_t deadline)
Combined cancellation and deadline check placed between setup steps.
bool lwir_device_discard(struct lwir_device *device, bool *received)
Dequeue and immediately requeue at most one pending frame.
static bool video_state_pause(void *context, unsigned milliseconds)
Short cancellable delay between mailbox polls for lwir_state.c.
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.
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.
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.
static uint64_t video_state_now(void *context)
Clock callback for lwir_state.c.
bool lwir_device_open(struct lwir_device_options *options, struct lwir_device *device)
Find, lock and start exactly one supported camera within the timeout.
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.
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 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_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 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 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_control_read(struct lwir_device *device, enum lwir_control_kind kind, struct lwir_control_result *result)
Public control read; see lwir_device.h.
static bool video_cancelled(const struct lwir_device *device)
Poll the borrowed cancellation flag.
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_fail(struct lwir_device *device, int error)
Poison the session after a fatal kernel or protocol error.
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 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_requeue(struct lwir_device *device, unsigned index)
Return a dequeued buffer to the driver.
static bool video_ready(const struct lwir_device *device)
Verify session invariants before touching the stream.
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.
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_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_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 void video_qualification(struct lwir_device *device, bool valid, bool continuous, uint64_t now)
Advance the eight-consecutive-good-frames startup counter.
static bool video_state_identity(struct lwir_device *device)
Confirm the streaming camera is still the same USB power instance.
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].
bool lwir_measurement_valid(unsigned width, unsigned height, const struct lwir_measurement *measurement)
Validate a measurement request against native geometry.
Definition lwir_frame.c:84
bool lwir_frame_capture_valid(const uint8_t *frame, size_t bytes, unsigned width, unsigned height)
Live-capture qualification.
Definition lwir_frame.c:446
bool lwir_frame_plausible(const uint8_t *frame, size_t bytes, unsigned width, unsigned height)
Conservative scene-plausibility heuristic.
Definition lwir_frame.c:465
size_t lwir_frame_bytes(unsigned width, unsigned height)
Combined frame size for supported geometry.
Definition lwir_frame.c:56
bool lwir_frame_settled(const uint8_t *frame, const uint8_t *previous_image, unsigned width, unsigned height)
Image-stability heuristic between consecutive frames.
Definition lwir_frame.c:498
lwir_frame_layout
Buffer content kinds: full image+thermal frame, or the YUYV image plane alone.
Definition lwir_frame.h:54
@ LWIR_YUYV_IMAGE
Definition lwir_frame.h:54
@ LWIR_COMBINED
Definition lwir_frame.h:54
#define LWIR_MAX_FRAME_BYTES
Largest combined frame: two planes of 2 bytes per pixel.
Definition lwir_frame.h:51
struct jpeg_error_mgr error
Definition lwir_image.c:60
void lwir_state_read(const struct lwir_state_io *io, struct lwir_device_state *state)
Read all fields of struct lwir_device_state within LWIR_STATE_BUDGET_MS.
Definition lwir_state.c:159
bool lwir_state_control_read(const struct lwir_state_io *io, enum lwir_control_kind kind, struct lwir_control_result *result)
Targeted read of one controllable setting; performs no setting writes.
Definition lwir_state.c:331
bool lwir_state_control(const struct lwir_state_io *io, const struct lwir_control_request *request, struct lwir_control_result *result)
Apply one setting with read-back verification, or trigger FFC.
Definition lwir_state.c:366
bool lwir_control_valid(const struct lwir_control_request *request)
Range-check a control request (vendor-header limits).
Definition lwir_state.c:231
lwir_control_kind
Settings that lwir_state_control() may change.
Definition lwir_state.h:175
@ LWIR_CONTROL_FFC
Definition lwir_state.h:177
@ LWIR_CONTROL_EMISSIVITY
Definition lwir_state.h:176
@ LWIR_STATE_INVALID
Definition lwir_state.h:117
@ LWIR_STATE_UNSUPPORTED
Definition lwir_state.h:116
@ LWIR_STATE_TIMEOUT
Definition lwir_state.h:117
@ LWIR_STATE_CANCELLED
Definition lwir_state.h:118
@ LWIR_STATE_IO_ERROR
Definition lwir_state.h:117
#define PATH_MAX
Definition path_utils.h:39
static size_t count
Definition pose_log.c:79
static uint64_t accepted
Definition pose_log.c:81
One requested setting change; validate with lwir_control_valid().
Definition lwir_state.h:181
enum lwir_control_kind kind
Setting to change.
Definition lwir_state.h:182
Outcome of lwir_state_control() or lwir_state_control_read().
Definition lwir_state.h:195
Host observation plus optional kernel clock evidence, never automatic exposure qualification.
Bounded camera policy; Tiny1C requires full 256x192 image and temperature planes.
Definition lwir_device.h:93
One post-capture snapshot of all lwir_state_field values.
Definition lwir_state.h:135
Caller-owned session, initialized to zero before opening.
unsigned video_width
char serial[64]
char video_power_port[64]
uint32_t video_last_sequence
uint64_t video_good_arrival_us
bool video_have_sequence
unsigned video_height
enum lwir_frame_layout layout
const volatile sig_atomic_t * cancelled
unsigned video_usb_bus
struct lwir_video_buffer video_buffers[LWIR_VIDEO_BUFFERS]
unsigned video_count
bool video_failed
size_t video_bytes
unsigned video_good_frames
bool video_streaming
bool video_power_ready
uint64_t video_sequence
unsigned video_usb_address
char video_power_key[160]
Transport and clock callbacks driving the mailbox protocol.
Definition lwir_state.h:147
One kernel capture buffer mapped into this process.
Definition lwir_device.h:73
bool mapped
Ownership flag for the mapping.
Definition lwir_device.h:80
Validated capture and reporting policy, fixed before the sample loop.
Definition earcam.c:137
Single-session USB transport with bounded input staging.
Definition chdkbridge.c:102
Context handed to the lwir_state.c protocol through struct lwir_state_io.
struct lwir_device * device
bool valid
Definition usher.c:537
struct usher_control_result result
Definition usher.c:377