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_capture.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/**
19 * @file lwir_capture.c
20 * @brief Command-line entry point of the `lwircam` executable.
21 *
22 * @details
23 * One binary serves several mutually exclusive roles, selected by options:
24 * - **One-shot capture** (default): `main()` forks; the child runs
25 * save_capture() while the parent supervise()s it against a monotonic
26 * deadline, so a wedged USB/UVC call cannot outlive `timeout_ms`.
27 * - **Persistent capture server** (`--capture-server`): serve_captures() keeps
28 * the camera streaming and answers one absolute output path per stdin line.
29 * This is the interface USHER drives.
30 * - **Raw replay** (`--raw FRAME --size W H`): renders a recorded frame through
31 * the same statistics/JPEG/publication path, marked as simulated.
32 * - **Standalone camera controls** (`--get-control`, `--set-gain`,
33 * `--set-emissivity-128`, `--set-agc-mode`, `--set-agc`, `--ffc`): exactly one
34 * control per invocation, no image output.
35 * - **Optional builds**: analysis builds add `--analyze`, `--check-model`,
36 * `--calibration` and `--geolocate`; mock builds add `--mock-image` and
37 * `--mock-layer`. Those options are rejected in builds without the feature.
38 *
39 * Capture data flow:
40 * 1. Acquire a frame (camera via lwir_device, or replay file) into the static
41 * ::captured_frame buffer. Freshness is measured from the start of the
42 * request, so a published photo is never older than the request.
43 * 2. Optionally read device state (`--device-state`): opt-in, read-only,
44 * after the frame (not frame-atomic) and bounded to 250 ms.
45 * 3. Optionally compute temperature statistics/threshold coverage.
46 * 4. Hash the frame bytes (SHA-256) into the evidence record.
47 * 5. Optionally write a raw companion (`--record-raw` or `--native-raw`, which
48 * derives `PATH.raw`) for byte-exact verification.
49 * 6. Encode the JPEG with evidence metadata; the temperature plane is stored
50 * exactly in APP15 markers. Capture defaults to quality 95 with 4:4:4
51 * sampling (0 in the library means legacy quality 100).
52 * 7. Publish durably without overwriting: the image library writes a temporary
53 * file, fsyncs it, link()s it to the final name (fails if it exists) and
54 * fsyncs the directory. `main()` also refuses an existing output up front.
55 *
56 * Configuration precedence: the settings INI (`--settings`/`--config`, or the
57 * discovered default `lwircam` settings file) is loaded first, then command-line
58 * options override or extend it. Each INI key may appear only once.
59 *
60 * Exit codes: 0 success; 1 runtime failure; 2 usage/configuration error
61 * (including capture-server protocol violations); 124 supervisor timeout;
62 * 128+signal when interrupted by SIGINT/SIGTERM.
63 *
64 * Memory policy: no heap in this file and no memcpy (project policy); strings
65 * are copied with bounded loops into fixed static storage.
66 */
67
68#include "lwir_frame.h"
69#include "lwir_image.h"
70#include "lwir_features.h"
71#if LWIR_ENABLE_ANALYSIS
72#include "lwir_analysis.h"
73#include "lwir_inference.h"
74#endif
75#if LWIR_ENABLE_MOCK
76#include "lwir_mock.h"
77#endif
78#include "boot_id.h"
79#include "sha256fst.h"
80#include "lwir_render.h"
81#include "bounded_ini.h"
82#include "inference_settings.h"
83#include "version.h"
84
85#include <errno.h>
86#include <fcntl.h>
87#include <math.h>
88#include <poll.h>
89#include <signal.h>
90#include <stdio.h>
91#include <stdlib.h>
92#include <string.h>
93#include <sys/stat.h>
94#include <sys/wait.h>
95#include <time.h>
96#include <unistd.h>
97
98#include "lwir_device.h"
99
100/**
101 * @brief Effective run policy: INI settings first, then command-line overrides.
102 *
103 * String members point either into `argv` or into the static `configured_*`
104 * buffers, so they stay valid for the whole process lifetime.
105 */
107 const char *output; /**< Final JPEG path; rewritten per request in server mode. */
108 const char *raw; /**< Replay input frame (`--raw`); selects replay instead of the camera. */
109 const char *serial; /**< Camera serial to select; must be < 64 bytes. */
110 const char *device_path; /**< Explicit `/dev/...` node; V4L2 builds only. */
111 const char *record_raw; /**< Raw companion path; explicit or derived `OUTPUT.raw` from native_raw. */
112 const char *gain_label; /**< Metadata label matched against the correction profile; physical gain is `--set-gain`. */
113 const char *corrections; /**< Correction profile path; must match serial/gain label/geometry. */
114 const char *replay_serial; /**< Serial recorded in replay evidence; replay only. */
115 const char *config; /**< Settings INI path, loaded before argument parsing. */
116 const char *calibration; /**< Geolocation calibration file (analysis builds). */
117 const char *geolocate_input; /**< JPEG to geolocate offline (analysis builds). */
118 const char *mock_input; /**< Mock source image (mock builds). */
119 bool mock_layer_only; /**< `--mock-layer`: update the input in place, no separate output. */
120 unsigned width; /**< Image/temperature plane width; 0 = negotiate with the camera. */
121 unsigned height; /**< Plane height, not the doubled UVC height of combined frames. */
122 unsigned warmup_ms; /**< Startup qualification time; forced to 0 for controls and server requests. */
123 unsigned timeout_ms; /**< Supervisor deadline, server watchdog and idle-frame timeout. */
124 bool report_stats; /**< Print statistics; implied by measurements and thresholds. */
126 bool settle;
127 bool device_state; /**< Opt-in read-only state query after the frame. */
128 bool control_selected; /**< A standalone control was requested; excludes every capture mode. */
129 bool control_read; /**< The selected control is `--get-control` rather than a write/trigger. */
131 bool server;
132 bool capture_requested; /**< Explicit `--capture`; only valid together with an output. */
133 bool warmup_only; /**< `--warmup`: qualify the camera once, publish nothing. */
134 bool native_raw; /**< Derive the raw companion as `OUTPUT.raw`. */
135 bool warn_percent_set; /**< Distinguishes an explicit `--warn-percent` from the default of 1. */
136 bool jpeg_quality_selected; /**< Rejects a repeated `--jpeg-quality`; INI may still set the base value. */
137 unsigned warn_percent;
141 enum lwir_frame_layout layout; /**< Filled from the opened device; image-only cameras halve the frame size. */
142 const char *inference_input;
145 unsigned class_index;
146};
147
149
150/* Static to keep the ~196 KB frame off the stack. */
152/* Holds the signal number (0 = none) so exit codes can report 128+signal. */
153static volatile sig_atomic_t interrupted;
155static char device_serial[64];
159static char device_state_text[4096];
161static char configured_device[1024];
162static bool parse_unsigned(const char *text, unsigned maximum, unsigned *value);
163static bool select_measurement(struct capture_options *options, enum lwir_measurement_kind kind, const unsigned *coordinates);
164static bool parse_coordinates(const char *text, unsigned count, unsigned *coordinates);
165
166/**
167 * @brief Convert a Celsius band to device raw codes (Kelvin * 64).
168 *
169 * @details Rounds to nearest and re-checks ordering after rounding, because two
170 * distinct close temperatures can collapse onto the same raw code.
171 *
172 * @param low_c Lower bound in degrees Celsius.
173 * @param high_c Upper bound in degrees Celsius.
174 * @param[out] low_raw Lower raw code; written only when both bounds are representable.
175 * @param[out] high_raw Upper raw code.
176 * @return true when both bounds are finite, within 0..65535 and strictly ordered.
177 */
178static bool temperature_band(double low_c, double high_c, uint16_t *low_raw, uint16_t *high_raw)
179{
180 const double low = (low_c + 273.15) * 64, high = (high_c + 273.15) * 64;
181 if (!isfinite(low) || !isfinite(high) || low < 0 || high > 65535 || low >= high) return false;
182 *low_raw = (uint16_t)(low + 0.5); *high_raw = (uint16_t)(high + 0.5);
183 return *low_raw < *high_raw;
184}
185
186/**
187 * @brief Configuration identities shared by key lookup and duplicate/pair masks.
188 *
189 * @details Each enumerator is both an index into the key table in
190 * config_field() and a bit position in config_parser::seen. Setting a bit on
191 * first sight lets a repeated key be rejected, and load_config() tests groups of
192 * bits to require complete pairs (window, percentiles, thresholds) and to
193 * forbid window and percentiles together.
194 */
231
232_Static_assert(CONFIG_FIELD_COUNT <= 64, "Configuration identities must fit the duplicate mask");
233
234/**
235 * @brief Callback context while reading the settings INI.
236 *
237 * Paired Celsius values are staged here and validated together in
238 * load_config(), since either half may arrive first.
239 */
242 uint64_t seen; /**< Bit per ::config_field already accepted. */
243 double low_c;
244 double high_c;
247};
248
249/**
250 * @brief Accept one `key = value` pair from the settings INI.
251 *
252 * @details Maps the key to its ::config_field identity, rejects unknown or
253 * repeated keys, validates the value and stores it in the options. Strings are
254 * copied with bounded loops into static buffers because the INI reader's value
255 * storage does not outlive the callback. Paired Celsius values are only staged;
256 * load_config() checks their completeness and ordering.
257 *
258 * @param context A struct config_parser.
259 * @param key INI key.
260 * @param value INI value text.
261 * @return false for an unknown/duplicate key or an invalid value, which makes
262 * the whole settings file invalid.
263 */
264static bool config_field(void *context, const char *key, const char *value)
265{
266 struct config_parser *parser = context;
267 struct capture_options *options = parser->options;
268 static const char *const keys[CONFIG_FIELD_COUNT] = {
269 [CONFIG_FORMAT] = "format",
270 [CONFIG_WIDTH] = "width",
271 [CONFIG_HEIGHT] = "height",
272 [CONFIG_WARMUP_MS] = "warmup_ms",
273 [CONFIG_TIMEOUT_MS] = "timeout_ms",
274 [CONFIG_WINDOW_LOW_C] = "window_low_c",
275 [CONFIG_WINDOW_HIGH_C] = "window_high_c",
276 [CONFIG_PERCENTILE_LOW] = "percentile_low",
277 [CONFIG_PERCENTILE_HIGH] = "percentile_high",
278 [CONFIG_PALETTE] = "palette",
279 [CONFIG_LEGEND] = "legend",
280 [CONFIG_DENOISE_K] = "denoise_k",
281 [CONFIG_SERIAL] = "serial",
282 [CONFIG_GAIN_LABEL] = "gain_label",
283 [CONFIG_CORRECTIONS] = "corrections",
284 [CONFIG_SCENE_CHECK] = "scene_check",
285 [CONFIG_SETTLE] = "settle",
286 [CONFIG_THRESHOLD_LOW_C] = "threshold_low_c",
287 [CONFIG_THRESHOLD_HIGH_C] = "threshold_high_c",
288 [CONFIG_WARN_PERCENT] = "warn_percent",
289 [CONFIG_STATS] = "stats",
290 [CONFIG_POINT] = "point",
291 [CONFIG_LINE] = "line",
292 [CONFIG_AVERAGE_3X3] = "average_3x3",
293 [CONFIG_ROI] = "roi",
294 [CONFIG_ROTATE] = "rotate",
295 [CONFIG_MIRROR] = "mirror",
296 [CONFIG_FLIP] = "flip",
297 [CONFIG_DEVICE_STATE] = "device_state",
298 [CONFIG_SCORE_THRESHOLD] = "score_threshold",
299 [CONFIG_CLASS_INDEX] = "class_index",
300 [CONFIG_DEVICE] = "device",
301 [CONFIG_JPEG_QUALITY] = "jpeg_quality"
302 };
303 const unsigned fields = sizeof(keys) / sizeof(keys[0]);
304 unsigned field = 0;
305 while (field < fields && strcmp(key, keys[field])) ++field;
306 if (field == fields || (parser->seen & (UINT64_C(1) << field))) return false;
307 parser->seen |= UINT64_C(1) << field;
308 if (field == CONFIG_DEVICE) {
309 /* The index <= strlen bound also copies the terminator; control characters are refused. */
310 if (strncmp(value, "/dev/", 5) || strlen(value) >= sizeof(configured_device)) return false;
311 for (size_t index = 0; index <= strlen(value); ++index) {
312 if (((unsigned char)value[index] < 32 && value[index]) || value[index] == 127) return false;
313 configured_device[index] = value[index];
314 }
315 options->device_path = configured_device;
316 return true;
317 }
318 if (field == CONFIG_FORMAT) return !strcmp(value, "LWIR_CONFIG_V1");
319 if (field == CONFIG_SCORE_THRESHOLD)
320 return ini_real(value, &options->score_threshold) && options->score_threshold >= 0 && options->score_threshold <= 1;
321 if (field == CONFIG_CLASS_INDEX) return parse_unsigned(value, 4095, &options->class_index);
322 /* Relies on SERIAL, GAIN_LABEL and CORRECTIONS being contiguous in the enum. */
323 if (field >= CONFIG_SERIAL && field <= CONFIG_CORRECTIONS) {
324 char *destination = field == CONFIG_SERIAL ? configured_serial : field == CONFIG_GAIN_LABEL ? configured_gain : configured_corrections;
325 const size_t capacity = field == CONFIG_SERIAL ? sizeof(configured_serial) : field == CONFIG_GAIN_LABEL ? sizeof(configured_gain) : sizeof(configured_corrections);
326 if (strlen(value) >= capacity) return false;
327 for (size_t index = 0; index <= strlen(value); ++index) { if (((unsigned char)value[index] < 32 && value[index]) || value[index] == 127) return false; destination[index] = value[index]; }
328 if (field == CONFIG_SERIAL) options->serial = destination;
329 else if (field == CONFIG_GAIN_LABEL) options->gain_label = destination;
330 else options->corrections = destination;
331 return true;
332 }
333 if (field == CONFIG_PALETTE) {
334 if (!strcmp(value, "white-hot")) options->render.palette = LWIR_WHITE_HOT;
335 else if (!strcmp(value, "black-hot")) options->render.palette = LWIR_BLACK_HOT;
336 else if (!strcmp(value, "iron")) options->render.palette = LWIR_IRON;
337 else return false;
338 return true;
339 }
340 if (field == CONFIG_POINT || field == CONFIG_LINE || field == CONFIG_ROI) {
341 unsigned coordinates[4];
342 return parse_coordinates(value, field == CONFIG_POINT ? 2 : 4, coordinates) &&
344 }
345 if (field == CONFIG_WINDOW_LOW_C || field == CONFIG_WINDOW_HIGH_C || field == CONFIG_DENOISE_K ||
346 field == CONFIG_THRESHOLD_LOW_C || field == CONFIG_THRESHOLD_HIGH_C) {
347 double number;
348 if (!ini_real(value, &number)) return false;
349 if (field == CONFIG_WINDOW_LOW_C) parser->low_c = number;
350 else if (field == CONFIG_WINDOW_HIGH_C) parser->high_c = number;
351 else if (field == CONFIG_THRESHOLD_LOW_C) parser->threshold_low_c = number;
352 else if (field == CONFIG_THRESHOLD_HIGH_C) parser->threshold_high_c = number;
353 /* Stored in raw-code units (x64, like temperatures); must not round down to 0. */
354 else { if (number <= 0 || number > 10) return false; options->render.denoise_raw = (unsigned)(number * 64 + 0.5); if (!options->render.denoise_raw) return false; }
355 return true;
356 }
357 /* Remaining keys are unsigned; 120000 is the shared ceiling, tightened per key below. */
358 unsigned number;
359 if (!parse_unsigned(value, 120000, &number)) return false;
360 switch (field) {
361 case CONFIG_WIDTH: options->width = number; break;
362 case CONFIG_HEIGHT: options->height = number; break;
363 case CONFIG_WARMUP_MS: options->warmup_ms = number; break;
364 case CONFIG_TIMEOUT_MS: options->timeout_ms = number; break;
365 case CONFIG_JPEG_QUALITY: if (!number || number > 100) return false; options->render.jpeg_quality = number; break;
366 case CONFIG_PERCENTILE_LOW: options->render.low_percentile = number; break;
367 case CONFIG_PERCENTILE_HIGH: options->render.high_percentile = number; break;
368 case CONFIG_LEGEND: if (number > 1) return false; options->render.legend = number != 0; break;
369 case CONFIG_SCENE_CHECK: if (number > 1) return false; options->scene_check = number != 0; break;
370 case CONFIG_SETTLE: if (number > 1) return false; options->settle = number != 0; break;
371 case CONFIG_WARN_PERCENT: if (!number || number > 100) return false; options->warn_percent = number; options->warn_percent_set = true; break;
372 case CONFIG_STATS: if (number > 1) return false; options->report_stats |= number != 0; break;
373 case CONFIG_AVERAGE_3X3: if (number > 1) return false; options->measurement.average_3x3 = number != 0; options->report_stats |= number != 0; break;
374 case CONFIG_ROTATE: if (number > 270 || number % 90) return false; options->render.rotation = number; break;
375 case CONFIG_MIRROR: if (number > 1) return false; options->render.mirror = number != 0; break;
376 case CONFIG_FLIP: if (number > 1) return false; options->render.flip = number != 0; break;
377 case CONFIG_DEVICE_STATE: if (number > 1) return false; options->device_state = number != 0; break;
378 default: return false;
379 }
380 return true;
381}
382
383/**
384 * @brief Load the settings INI into @p options before command-line parsing.
385 *
386 * @details Resets ::model_settings to the native backend, lets the shared
387 * inference-settings reader dispatch each key to config_field(), then applies
388 * cross-key rules: `format = LWIR_CONFIG_V1` is mandatory, thresholds and
389 * window values must come in complete pairs, and a fixed window excludes
390 * percentiles. A configured size must form a valid frame geometry.
391 *
392 * @param path Settings file path.
393 * @param[in,out] options Defaults on entry; INI values on return.
394 * @return true when the file is readable and every key is valid; on false the
395 * caller exits with code 2. The reader's error text is not printed here.
396 * @note The pair masks use 32-bit constants; this is sufficient only because
397 * every identity they test is below 32 (::CONFIG_JPEG_QUALITY is not).
398 */
399static bool load_config(const char *path, struct capture_options *options)
400{
401 char error[1024];
403 struct config_parser parser = {.options = options};
404 if (!inference_settings_read(&model_settings, path, config_field, &parser, error, sizeof(error)) ||
405 !(parser.seen & (UINT32_C(1) << CONFIG_FORMAT))) return false;
406 const uint32_t window = (UINT32_C(1) << CONFIG_WINDOW_LOW_C) | (UINT32_C(1) << CONFIG_WINDOW_HIGH_C);
407 const uint32_t percentiles = (UINT32_C(1) << CONFIG_PERCENTILE_LOW) | (UINT32_C(1) << CONFIG_PERCENTILE_HIGH);
408 const uint32_t thresholds = (UINT32_C(1) << CONFIG_THRESHOLD_LOW_C) | (UINT32_C(1) << CONFIG_THRESHOLD_HIGH_C);
409 if (parser.seen & thresholds) {
410 if ((parser.seen & thresholds) != thresholds ||
411 !temperature_band(parser.threshold_low_c, parser.threshold_high_c, &options->thresholds.low, &options->thresholds.high)) return false;
412 options->thresholds.enabled = true; options->report_stats = true;
413 }
414 if ((parser.seen & window) && (parser.seen & percentiles)) return false;
415 if (parser.seen & window) {
416 if ((parser.seen & window) != window) return false;
417 const double low = (parser.low_c + 273.15) * 64, high = (parser.high_c + 273.15) * 64;
418 if (low < 0 || high > 65535 || low >= high) return false;
419 options->render.low = (int32_t)(low + 0.5); options->render.high = (int32_t)(high + 0.5);
420 if (options->render.low >= options->render.high) return false;
421 options->render.view = LWIR_FIXED;
422 } else if (parser.seen & percentiles) {
423 if ((parser.seen & percentiles) != percentiles || options->render.low_percentile >= options->render.high_percentile || options->render.high_percentile > 100) return false;
424 options->render.view = LWIR_PERCENTILE;
425 }
426 return (!options->width && !options->height) || lwir_frame_bytes(options->width, options->height) != 0;
427}
428
429/**
430 * @brief SIGINT/SIGTERM handler: record the signal for cooperative cancellation.
431 *
432 * @details Only stores into a sig_atomic_t; capture loops poll ::interrupted
433 * (and the device layer receives it as its cancel flag) so cleanup runs in
434 * normal context.
435 *
436 * @param signal_number Delivered signal, later reported as exit code 128+signal.
437 */
438static void interrupt_capture(int signal_number)
439{
440 interrupted = signal_number;
441}
442
443/**
444 * @brief Print the build version and command-line synopsis.
445 *
446 * @details Lines for optional features are compiled in only when the matching
447 * build profile is enabled, so help never advertises unavailable options.
448 *
449 * @param output stdout for `--help`, stderr after a usage error.
450 */
451static void usage(FILE *output)
452{
453 fprintf(output, "%s\nUsage: lwircam [--capture] [--output FILE] [--serial SERIAL] [--size WIDTH HEIGHT]\n",
455 fprintf(output, "Model settings: --settings FILE (--config alias); analysis builds: --check-model or --analyze FILE.jpg\n");
456#if LWIR_ENABLE_ANALYSIS
457 fprintf(output, " [--calibration FILE] [--geolocate FILE]\n");
458#endif
459#if LWIR_ENABLE_MOCK
460 fprintf(output, " [--mock-image FILE | --mock-layer FILE]\n");
461#endif
462 fprintf(output, " [--warmup-ms MS] [--timeout-ms MS]\n"
463 " [--device /dev/videoN]\n"
464 " [--jpeg-quality 1..100] (capture default: 95; sampling: 4:4:4)\n"
465 " [--stats] [--roi X Y WIDTH HEIGHT] OUTPUT.jpg\n"
466 " [--point X Y | --line X0 Y0 X1 Y1] [--average-3x3]\n"
467 " [--thresholds LOW_C HIGH_C] [--warn-percent 1..100]\n"
468 " [--rotate 0|90|180|270] [--mirror] [--flip]\n"
469 " [--window LOW_C HIGH_C | --percentiles LOW HIGH]\n"
470 " [--palette white-hot|black-hot|iron] [--legend]\n"
471 " [--corrections FILE] [--denoise-k K] [--gain-label LABEL]\n"
472 " [--replay-serial SERIAL] [--bare]\n"
473 " [--record-raw FILE | --native-raw] [--config FILE]\n"
474 " [--device-state]\n"
475 " [--scene-check] [--settle] [--capture-server | --warmup]\n"
476 " lwircam --raw FRAME.yuyt --size WIDTH HEIGHT OUTPUT.jpg\n"
477 "WIDTH and HEIGHT describe the image/temperature planes, not the doubled UVC height.\n"
478 "Tiny1C 0bda:5840: combined image/temperature; TDK 5474:5411: native 640x512 image only.\n"
479 "TDK supports JPEG and orientation, not thermal measurements/rendering/raw/state controls.\n"
480 "Statistics report device values to stderr, not calibrated surface temperatures.\n"
481 "All measurement coordinates are native; coverage uses original centers, excluding 0/65535.\n"
482 "Thresholds are an inclusive diagnostic band, not a display window or gain command.\n"
483 "Orientation is clockwise rotate, then mirror, then flip; raw thermal bytes stay native.\n"
484 "Device-state queries are opt-in, read-only, bounded to 250 ms and bench-unverified.\n"
485 "Thermal replay is marked LWIRSIM1; Tiny1C temperatures use LWIRRAW1; TDK has no thermal markers.\n");
486 fprintf(output, "Standalone Tiny1C controls (one per invocation, no output image):\n"
487 " lwircam --get-control gain|emissivity-128|agc-mode|agc\n"
488 " lwircam [--device /dev/videoN | --serial SERIAL] --set-gain low|high\n"
489 " lwircam --set-emissivity-128 1..128 | --set-agc-mode 0..5 | --set-agc 0|1 | --ffc\n"
490 "Setters require matching readback; FFC completion is not calibration validation. Never auto-retry.\n"
491 "Output: LWIR_CONTROL_OK control=NAME operation=read|write|trigger ...; failures report submitted=0|1.\n");
492}
493
494/**
495 * @brief Strictly parse a decimal unsigned integer with an upper bound.
496 *
497 * @details Pre-scans for digits only, because strtoul() would otherwise accept
498 * leading whitespace, a sign (wrapping "-1" to a huge value) or a `0x` prefix.
499 *
500 * @param text NUL-terminated input; NULL or empty is rejected.
501 * @param maximum Largest accepted value.
502 * @param[out] value Written only on success.
503 * @return true for a pure digit string within range.
504 */
505static bool parse_unsigned(const char *text, unsigned maximum, unsigned *value)
506{
507 if (text == NULL || text[0] == '\0') return false;
508 for (const char *cursor = text; *cursor != '\0'; ++cursor) {
509 if (*cursor < '0' || *cursor > '9') return false;
510 }
511 errno = 0;
512 char *end = NULL;
513 const unsigned long parsed = strtoul(text, &end, 10);
514 if (errno != 0 || end == NULL || *end != '\0' || parsed > maximum) return false;
515 *value = (unsigned)parsed;
516 return true;
517}
518
519/**
520 * @brief Select the single point, line or rectangle measurement.
521 *
522 * @details The zero-initialised measurement (kind ::LWIR_RECTANGLE, width 0)
523 * means "none chosen yet"; any prior selection makes a second one fail, so the
524 * INI and command line together can name at most one measurement. Bounds
525 * against the frame are checked later, once the geometry is known.
526 *
527 * @param[in,out] options Receives the measurement and enables statistics.
528 * @param kind Point, line or rectangle.
529 * @param coordinates `x y` for a point; `x0 y0 x1 y1` for a line; `x y w h` for a rectangle.
530 * @return false if a measurement was already selected or a rectangle is empty.
531 */
532static bool select_measurement(struct capture_options *options, enum lwir_measurement_kind kind, const unsigned *coordinates)
533{
534 if (options->measurement.roi.width || options->measurement.kind != LWIR_RECTANGLE) return false;
535 options->measurement.kind = kind;
536 options->measurement.roi = (struct lwir_roi){.x = coordinates[0], .y = coordinates[1], .width = 1, .height = 1};
537 if (kind == LWIR_RECTANGLE) {
538 if (!coordinates[2] || !coordinates[3]) return false;
539 options->measurement.roi.width = coordinates[2]; options->measurement.roi.height = coordinates[3];
540 } else if (kind == LWIR_LINE) {
541 options->measurement.end_x = coordinates[2]; options->measurement.end_y = coordinates[3];
542 }
543 options->report_stats = true;
544 return true;
545}
546
547/**
548 * @brief Parse an INI coordinate list such as `x,y` or `x,y,w,h`.
549 *
550 * @details Each field must start with a digit (blocking strtoul's sign and
551 * whitespace acceptance) and be followed by exactly `,` or, for the last one,
552 * the end of the string.
553 *
554 * @param text Comma-separated decimal values.
555 * @param count Number of fields expected (2 or 4).
556 * @param[out] coordinates At least @p count elements.
557 * @return true when exactly @p count values, each <= LWIR_MAX_WIDTH, are present.
558 */
559static bool parse_coordinates(const char *text, unsigned count, unsigned *coordinates)
560{
561 for (unsigned index = 0; index < count; ++index) {
562 if (*text < '0' || *text > '9') return false;
563 errno = 0; char *end;
564 const unsigned long value = strtoul(text, &end, 10);
565 if (errno || value > LWIR_MAX_WIDTH || (index + 1 < count ? *end != ',' : *end != '\0')) return false;
566 coordinates[index] = (unsigned)value;
567 text = end + (index + 1 < count ? 1 : 0);
568 }
569 return true;
570}
571
572/**
573 * @brief Apply command-line options on top of the INI settings and validate the mode.
574 *
575 * @details Three passes:
576 * 1. Parse each option, rejecting repeats where a second value would be
577 * ambiguous, and feature options missing from this build profile.
578 * 2. Reject any argument of 1024+ bytes or containing control characters, so
579 * paths and labels cannot inject lines into logs or metadata.
580 * 3. Enforce mode rules: a standalone control admits only its selector,
581 * `--device`, `--serial` and `--timeout-ms`; analysis-only runs exclude
582 * capture; everything else must satisfy the mutual-exclusion expression at
583 * the end.
584 *
585 * @param count argc.
586 * @param arguments argv; strings are referenced, not copied.
587 * @param[in,out] options INI-derived values on entry; final policy on return.
588 * @return false for any usage error; the caller prints usage and exits 2.
589 * @note `--settings`/`--config` was already consumed by main(); here it only
590 * has to repeat the same path.
591 */
592static bool parse_options(int count, char **arguments, struct capture_options *options)
593{
594 for (int index = 1; index < count; ++index) {
595 const char *argument = arguments[index];
596 if ((!LWIR_ENABLE_ANALYSIS && (!strcmp(argument, "--geolocate") || !strcmp(argument, "--calibration"))) ||
597 (!LWIR_ENABLE_MOCK && (!strcmp(argument, "--mock-image") || !strcmp(argument, "--mock-layer")))) {
598 fprintf(stderr, "LWIR: option unavailable in this build profile: %s\n", argument);
599 return false;
600 }
601 if (!strcmp(argument, "--get-control")) {
602 if (options->control_selected || ++index >= count) return false;
603 const char *name = arguments[index];
604 if (strcmp(name, "gain") && strcmp(name, "emissivity-128") && strcmp(name, "agc-mode") && strcmp(name, "agc")) return false;
605 options->control_selected = true; options->control_read = true;
606 /* Placeholder value only keeps the request valid: emissivity must be 1..128 even for a read. */
607 options->control = (struct lwir_control_request){.kind = !strcmp(name, "gain") ? LWIR_CONTROL_GAIN :
608 !strcmp(name, "emissivity-128") ? LWIR_CONTROL_EMISSIVITY : !strcmp(name, "agc-mode") ? LWIR_CONTROL_AGC_MODE : LWIR_CONTROL_AGC_ENABLE,
609 .value = !strcmp(name, "emissivity-128") ? 1 : 0};
610 } else if (!strcmp(argument, "--set-gain") || !strcmp(argument, "--set-emissivity-128") ||
611 !strcmp(argument, "--set-agc-mode") || !strcmp(argument, "--set-agc") || !strcmp(argument, "--ffc")) {
612 if (options->control_selected) return false;
613 options->control_selected = true;
614 if (!strcmp(argument, "--ffc")) options->control = (struct lwir_control_request){.kind = LWIR_CONTROL_FFC};
615 else {
616 if (++index >= count) return false;
617 if (!strcmp(argument, "--set-gain")) {
618 if (strcmp(arguments[index], "low") && strcmp(arguments[index], "high")) return false;
619 options->control = (struct lwir_control_request){.kind = LWIR_CONTROL_GAIN, .value = !strcmp(arguments[index], "high")};
620 } else {
621 unsigned value;
622 if (!parse_unsigned(arguments[index], 128, &value)) return false;
623 options->control = (struct lwir_control_request){.kind = !strcmp(argument, "--set-emissivity-128") ? LWIR_CONTROL_EMISSIVITY :
624 !strcmp(argument, "--set-agc-mode") ? LWIR_CONTROL_AGC_MODE : LWIR_CONTROL_AGC_ENABLE, .value = (uint16_t)value};
625 }
626 }
627 if (!lwir_control_valid(&options->control)) return false;
628 } else if (strcmp(argument, "--config") == 0 || strcmp(argument, "--settings") == 0) {
629 /* Already loaded by main(); only the identical path is accepted here. */
630 if (++index >= count || !options->config || strcmp(options->config, arguments[index])) return false;
631 } else if (!strcmp(argument, "--analyze")) {
632 if (!LWIR_ENABLE_ANALYSIS || options->inference_input || ++index >= count) return false;
633 options->inference_input = arguments[index];
634 } else if (!strcmp(argument, "--check-model")) {
635 if (!LWIR_ENABLE_ANALYSIS || options->check_model) return false;
636 options->check_model = true;
637 } else if (strcmp(argument, "--capture-server") == 0) {
638 options->server = true;
639 } else if (strcmp(argument, "--device-state") == 0) {
640 options->device_state = true;
641 } else if (!strcmp(argument, "--jpeg-quality")) {
642 /* Repeats are rejected, but one CLI value may override the INI value. */
643 if (options->jpeg_quality_selected || ++index >= count || !parse_unsigned(arguments[index], 100, &options->render.jpeg_quality)
644 || !options->render.jpeg_quality) return false;
645 options->jpeg_quality_selected = true;
646 } else if (!strcmp(argument, "--device")) {
647 if (options->device_path || ++index >= count || strncmp(arguments[index], "/dev/", 5)) return false;
648 options->device_path = arguments[index];
649 } else if (strcmp(argument, "--capture") == 0) {
650 if (options->capture_requested) return false;
651 options->capture_requested = true;
652 } else if (strcmp(argument, "--mock-image") == 0 || strcmp(argument, "--mock-layer") == 0) {
653 if (options->mock_input || ++index >= count || !arguments[index][0]) return false;
654 options->mock_input = arguments[index];
655 options->mock_layer_only = strcmp(argument, "--mock-layer") == 0;
656 } else if (strcmp(argument, "--output") == 0 || strcmp(argument, "--calibration") == 0 ||
657 strcmp(argument, "--geolocate") == 0) {
658 const char **destination = strcmp(argument, "--output") == 0 ? &options->output :
659 strcmp(argument, "--calibration") == 0 ? &options->calibration : &options->geolocate_input;
660 if (*destination || ++index >= count || !arguments[index][0]) return false;
661 *destination = arguments[index];
662 } else if (strcmp(argument, "--warmup") == 0) {
663 options->warmup_only = true;
664 } else if (strcmp(argument, "--native-raw") == 0) {
665 options->native_raw = true;
666 } else if (strcmp(argument, "--bare") == 0) {
667 /* Accepted for compatibility; it has no effect in this file. */
668 continue;
669 } else if (strcmp(argument, "--raw") == 0 || strcmp(argument, "--serial") == 0 ||
670 strcmp(argument, "--record-raw") == 0 || strcmp(argument, "--gain-label") == 0) {
671 if (++index >= count || arguments[index][0] == '\0') return false;
672 const char **destination = strcmp(argument, "--raw") == 0 ? &options->raw :
673 strcmp(argument, "--serial") == 0 ? &options->serial :
674 strcmp(argument, "--record-raw") == 0 ? &options->record_raw : &options->gain_label;
675 if (*destination != NULL) return false;
676 *destination = arguments[index];
677 } else if (strcmp(argument, "--corrections") == 0 || strcmp(argument, "--replay-serial") == 0) {
678 /* An INI value counts as already set, so these cannot be overridden from the CLI. */
679 const char **destination = !strcmp(argument, "--corrections") ? &options->corrections : &options->replay_serial;
680 if (*destination || ++index >= count || !arguments[index][0]) return false;
681 *destination = arguments[index];
682 } else if (strcmp(argument, "--denoise-k") == 0) {
683 double threshold;
684 if (++index >= count || !ini_real(arguments[index], &threshold) || threshold <= 0 || threshold > 10) return false;
685 options->render.denoise_raw = (unsigned)(threshold * 64 + 0.5);
686 if (!options->render.denoise_raw) return false;
687 } else if (strcmp(argument, "--size") == 0) {
688 if (options->width != 0 || index + 2 >= count ||
689 !parse_unsigned(arguments[index + 1], LWIR_MAX_WIDTH, &options->width) ||
690 !parse_unsigned(arguments[index + 2], LWIR_MAX_HEIGHT, &options->height) ||
691 lwir_frame_bytes(options->width, options->height) == 0) return false;
692 index += 2;
693 } else if (strcmp(argument, "--warmup-ms") == 0 || strcmp(argument, "--timeout-ms") == 0) {
694 if (++index >= count) return false;
695 unsigned *destination = strcmp(argument, "--warmup-ms") == 0 ? &options->warmup_ms : &options->timeout_ms;
696 if (!parse_unsigned(arguments[index], 120000, destination)) return false;
697 } else if (strcmp(argument, "--window") == 0) {
698 /* LWIR_SENSOR means no display view chosen yet; window and percentiles are exclusive. */
699 if (options->render.view != LWIR_SENSOR || index + 2 >= count) return false;
700 int32_t *limits[2] = {&options->render.low, &options->render.high};
701 for (unsigned bound = 0; bound < 2; ++bound) {
702 char *end;
703 errno = 0;
704 const double celsius = strtod(arguments[++index], &end);
705 const double scaled = (celsius + 273.15) * 64;
706 if (errno || end == arguments[index] || *end || !isfinite(scaled) || scaled < 0 || scaled > 65535) return false;
707 *limits[bound] = (int32_t)(scaled + 0.5);
708 }
709 if (options->render.low >= options->render.high) return false;
710 options->render.view = LWIR_FIXED;
711 } else if (strcmp(argument, "--percentiles") == 0) {
712 if (options->render.view != LWIR_SENSOR || index + 2 >= count ||
713 !parse_unsigned(arguments[index + 1], 100, &options->render.low_percentile) ||
714 !parse_unsigned(arguments[index + 2], 100, &options->render.high_percentile) ||
715 options->render.low_percentile >= options->render.high_percentile) return false;
716 options->render.view = LWIR_PERCENTILE;
717 index += 2;
718 } else if (strcmp(argument, "--palette") == 0) {
719 if (++index >= count) return false;
720 if (!strcmp(arguments[index], "white-hot")) options->render.palette = LWIR_WHITE_HOT;
721 else if (!strcmp(arguments[index], "black-hot")) options->render.palette = LWIR_BLACK_HOT;
722 else if (!strcmp(arguments[index], "iron")) options->render.palette = LWIR_IRON;
723 else return false;
724 } else if (strcmp(argument, "--legend") == 0) {
725 options->render.legend = true;
726 } else if (strcmp(argument, "--stats") == 0) {
727 options->report_stats = true;
728 } else if (strcmp(argument, "--rotate") == 0) {
729 if (++index >= count || !parse_unsigned(arguments[index], 270, &options->render.rotation) || options->render.rotation % 90) return false;
730 } else if (strcmp(argument, "--mirror") == 0) {
731 options->render.mirror = true;
732 } else if (strcmp(argument, "--flip") == 0) {
733 options->render.flip = true;
734 } else if (strcmp(argument, "--thresholds") == 0) {
735 double low, high;
736 if (options->thresholds.enabled || index + 2 >= count ||
737 !ini_real(arguments[index + 1], &low) || !ini_real(arguments[index + 2], &high) ||
738 !temperature_band(low, high, &options->thresholds.low, &options->thresholds.high)) return false;
739 options->thresholds.enabled = true; options->report_stats = true; index += 2;
740 } else if (strcmp(argument, "--warn-percent") == 0) {
741 if (options->warn_percent_set || ++index >= count || !parse_unsigned(arguments[index], 100, &options->warn_percent) || !options->warn_percent) return false;
742 options->warn_percent_set = true;
743 } else if (strcmp(argument, "--average-3x3") == 0) {
744 options->measurement.average_3x3 = true; options->report_stats = true;
745 } else if (strcmp(argument, "--scene-check") == 0) {
746 options->scene_check = true;
747 } else if (strcmp(argument, "--settle") == 0) {
748 options->settle = true;
749 } else if (!strcmp(argument, "--roi") || !strcmp(argument, "--point") || !strcmp(argument, "--line")) {
750 const enum lwir_measurement_kind kind = !strcmp(argument, "--point") ? LWIR_POINT : !strcmp(argument, "--line") ? LWIR_LINE : LWIR_RECTANGLE;
751 const unsigned fields = kind == LWIR_POINT ? 2U : 4U;
752 unsigned coordinates[4] = {0};
753 if (index + (int)fields >= count) return false;
754 for (unsigned field = 0; field < fields; ++field) {
755 if (!parse_unsigned(arguments[++index], LWIR_MAX_WIDTH, &coordinates[field])) return false;
756 }
757 if (!select_measurement(options, kind, coordinates)) return false;
758 } else {
759 /* The only positional argument is the output path, accepted once. */
760 if (argument[0] == '-' || argument[0] == '\0' || options->output != NULL) return false;
761 options->output = argument;
762 }
763 }
764 for (int index = 1; index < count; ++index) {
765 if (strlen(arguments[index]) >= 1024) return false;
766 for (const char *cursor = arguments[index]; *cursor; ++cursor) if ((unsigned char)*cursor < 32 || *cursor == 127) return false;
767 }
768 if (options->control_selected) {
769 /* Allow-list: every token must be a control selector or one of its permitted companions; others abort. */
770 for (int index = 1; index < count; ++index) {
771 const char *argument = arguments[index];
772 if (!strcmp(argument, "--ffc")) continue;
773 if (!strcmp(argument, "--set-gain") || !strcmp(argument, "--set-emissivity-128") || !strcmp(argument, "--set-agc-mode") ||
774 !strcmp(argument, "--set-agc") || !strcmp(argument, "--get-control") || !strcmp(argument, "--device") || !strcmp(argument, "--serial") || !strcmp(argument, "--timeout-ms")) {
775 ++index;
776 } else return false;
777 }
778 /* Controls need one fresh frame, not startup qualification. */
779 options->warmup_ms = 0;
780 return options->timeout_ms > 0 && (!options->serial || strlen(options->serial) < 64);
781 }
782 if (options->inference_input || options->check_model) {
783 /* Offline model checks/analysis never touch the camera and need the ONNX backend from settings. */
784 return LWIR_ENABLE_ANALYSIS && model_settings.backend == INFERENCE_ONNX && !options->output &&
785 !options->server && !options->capture_requested && !options->raw && !options->geolocate_input &&
786 !options->mock_input && !options->device_path && !(options->inference_input && options->check_model);
787 }
788 /*
789 * Capture-mode rules, one conjunct each:
790 * - some product is requested (output, server, warmup, geolocation or mock);
791 * - mock runs exclude camera/replay/raw modes, and --mock-layer has no separate output;
792 * - --capture requires an output, and the deadline must exceed warmup;
793 * - geolocation, warmup and server are mutually exclusive with each other and
794 * with a fixed output or raw companion (the server derives per-request paths);
795 * - --native-raw and --record-raw are alternative raw companion sources;
796 * - the sensor view has no palette/legend, and corrections/denoise need a thermal view;
797 * - replay serial applies only to replay, and labels/serials fit their buffers;
798 * - a raw companion may not alias the output or the replay input;
799 * - replay needs an explicit size and cannot select a camera serial;
800 * - device state and device path need a live camera;
801 * - --warn-percent only applies with thresholds;
802 * - a known geometry must contain the measurement (else the device validates it later).
803 */
804 return (options->output != NULL || options->server || options->warmup_only || options->geolocate_input != NULL || options->mock_input != NULL) &&
805 (!options->mock_input || (!options->capture_requested && !options->server && !options->warmup_only &&
806 !options->raw && !options->geolocate_input && !options->record_raw && !options->native_raw &&
807 (!options->mock_layer_only || !options->output))) &&
808 (!options->capture_requested || options->output != NULL) && options->timeout_ms > options->warmup_ms &&
809 (!options->geolocate_input || (!options->output && !options->server && !options->warmup_only && !options->native_raw && !options->record_raw)) &&
810 (!options->warmup_only || (!options->output && !options->server && !options->record_raw && !options->native_raw)) &&
811 (!options->server || (!options->output && !options->record_raw && !options->warmup_only)) &&
812 (!options->native_raw || !options->record_raw) &&
813 (options->render.view != LWIR_SENSOR || (!options->render.legend && options->render.palette == LWIR_WHITE_HOT)) &&
814 (!options->replay_serial || (options->raw && strlen(options->replay_serial) < 64)) &&
815 (!options->gain_label || strlen(options->gain_label) < 32) &&
816 (!options->serial || strlen(options->serial) < 64) &&
817 ((!options->corrections && !options->render.denoise_raw) || options->render.view != LWIR_SENSOR) &&
818 (!options->record_raw || (options->output && strcmp(options->record_raw, options->output) &&
819 (!options->raw || strcmp(options->record_raw, options->raw)))) &&
820 (options->raw == NULL || (options->width != 0 && options->serial == NULL)) &&
821 (!options->device_state || (!options->raw && !options->mock_input && !options->geolocate_input)) &&
822 (!options->device_path || (!options->raw && !options->mock_input && !options->geolocate_input)) &&
823 (!options->warn_percent_set || options->thresholds.enabled) &&
824 (options->width == 0 || lwir_measurement_valid(options->width, options->height, &options->measurement));
825}
826
827/**
828 * @brief Read CLOCK_MONOTONIC in milliseconds.
829 *
830 * @details Monotonic time is immune to wall-clock steps (NTP/GPS), which would
831 * otherwise falsely trigger or postpone deadlines.
832 *
833 * @param[out] milliseconds Current monotonic time.
834 * @return false if clock_gettime() fails (errno set by it).
835 */
836static bool monotonic_ms(uint64_t *milliseconds)
837{
838 struct timespec now;
839 if (clock_gettime(CLOCK_MONOTONIC, &now) != 0) return false;
840 *milliseconds = (uint64_t)now.tv_sec * 1000 + (uint64_t)now.tv_nsec / 1000000;
841 return true;
842}
843
844/**
845 * @brief Load a replay frame into ::captured_frame.
846 *
847 * @details Opens with O_NOFOLLOW and O_NONBLOCK and requires a regular file of
848 * exactly the expected size, so symlinks, FIFOs and devices cannot block or
849 * redirect the read. A trailing-byte probe catches files that grew after
850 * fstat(). The frame is then structurally validated and, with `--scene-check`,
851 * checked for plausibility.
852 *
853 * @param options Supplies the replay path and geometry.
854 * @return true on success. On failure errno is EINVAL (wrong type/size/content),
855 * EIO (read or close error) or the open()/fdopen() error.
856 */
857static bool read_raw(const struct capture_options *options)
858{
859 const size_t bytes = lwir_frame_bytes(options->width, options->height);
860 const int descriptor = open(options->raw, O_RDONLY | O_NONBLOCK | O_CLOEXEC | O_NOFOLLOW);
861 if (descriptor < 0) return false;
862 struct stat status;
863 if (fstat(descriptor, &status) != 0 || !S_ISREG(status.st_mode) || status.st_size != (off_t)bytes) {
865 errno = EINVAL;
866 return false;
867 }
868 FILE *input = fdopen(descriptor, "rb");
869 if (input == NULL) { const int saved_errno = errno; close(descriptor); errno = saved_errno; return false; }
870 if (input == NULL) return false;
871 const size_t received = fread(captured_frame, 1, bytes, input);
872 const int extra = received == bytes && !ferror(input) && !feof(input) ? fgetc(input) : EOF;
873 const bool io_error = ferror(input) != 0;
874 const int close_result = fclose(input);
875 if (io_error || close_result != 0) {
876 errno = EIO;
877 return false;
878 }
879 if (received != bytes || extra != EOF ||
881 (options->scene_check && !lwir_frame_plausible(captured_frame, bytes, options->width, options->height))) {
882 errno = EINVAL;
883 return false;
884 }
885 return true;
886}
887
888/**
889 * @brief Translate capture options into the device-layer acquisition policy.
890 *
891 * @details `requires_thermal` is true whenever any requested feature needs the
892 * temperature plane, letting the device layer refuse image-only cameras
893 * up front instead of producing incomplete evidence.
894 *
895 * @param options Current policy; pointers inside the result alias it.
896 * @return Device options by value; ::interrupted is passed as the cancel flag.
897 */
899{
900 return (struct lwir_device_options){.serial = options->serial, .device_path = options->device_path,
901 .width = options->width, .height = options->height,
902 .warmup_ms = options->warmup_ms, .timeout_ms = options->timeout_ms,
903 .scene_check = options->scene_check, .settle = options->settle,
904 .measurement = &options->measurement, .cancelled = &interrupted, .layout = options->layout,
905 .requires_thermal = options->control_selected || options->report_stats || options->thresholds.enabled || options->render.view != LWIR_SENSOR ||
906 options->corrections || options->render.denoise_raw || options->device_state || options->record_raw ||
907 options->native_raw || options->calibration || options->gain_label || options->scene_check};
908}
909
910/**
911 * @brief Open the camera and adopt its negotiated geometry, layout and serial.
912 *
913 * @details The serial is copied into static storage so the evidence pointer
914 * remains valid after the device session is closed.
915 *
916 * @param[in,out] options Width, height and layout are updated from the device.
917 * @param[out] device Session to close with lwir_device_close().
918 * @return false on open failure, errno set by the device layer.
919 */
920static bool open_camera(struct capture_options *options, struct lwir_device *device)
921{
923 if (!lwir_device_open(&policy, device)) return false;
924 options->width = policy.width;
925 options->height = policy.height;
926 options->layout = device->layout;
927 for (size_t index = 0; index < sizeof(device_serial); ++index) device_serial[index] = device->serial[index];
928 capture_evidence.serial = device_serial[0] ? device_serial : "unknown";
929 return true;
930}
931
932/**
933 * @brief Acquire one frame into ::captured_frame and record its timing evidence.
934 *
935 * @details The device layer applies warmup, qualification and the deadline,
936 * and rejects frames timestamped before the acquisition started. Because that
937 * start follows the request time stamped by initialize_evidence(), photos are
938 * never older than the request.
939 *
940 * @param device Open session.
941 * @param options Acquisition policy.
942 * @return false on timeout, cancellation or invalid frame, errno set by the device layer.
943 */
944static bool acquire_frame(struct lwir_device *device, const struct capture_options *options)
945{
946 const struct lwir_device_options policy = device_policy(options);
947 struct lwir_device_observation observation;
948 if (!lwir_device_acquire(device, &policy, captured_frame, sizeof(captured_frame), &observation)) return false;
949 capture_evidence.capture.sequence = observation.sequence;
950 capture_evidence.arrival_us = observation.arrival_us;
951 capture_evidence.kernel_monotonic_us = observation.kernel_monotonic_us;
952 capture_evidence.kernel_timestamp_flags = observation.kernel_timestamp_flags;
953 return true;
954}
955
956/**
957 * @brief Optionally attach read-only device state to the evidence.
958 *
959 * @details Runs only with `--device-state`, after the frame, so the state is
960 * not frame-atomic. The device layer bounds the query to 250 ms. State is
961 * best effort: failure never fails the capture, and errno is preserved so a
962 * later failure report is not masked by a state-query error.
963 *
964 * @param device Open session.
965 * @param options Supplies the device_state flag.
966 */
967static void read_device_state(struct lwir_device *device, const struct capture_options *options)
968{
969 if (!options->device_state) return;
970 const int saved_errno = errno;
974 fprintf(stderr, "LWIR: read-only device state (after frame; not exposure/FFC history)\n%s", device_state_text);
975 errno = saved_errno;
976}
977
978/**
979 * @brief One-shot camera capture: open, acquire, optional state, close.
980 *
981 * @details The session is closed before publication so encoding and fsync do
982 * not hold the camera.
983 *
984 * @param[in,out] options Geometry and layout are filled from the device.
985 * @return true when a frame is in ::captured_frame; errno describes failures.
986 */
988{
989 struct lwir_device session = {0};
990 if (!open_camera(options, &session)) return false;
991 const bool acquired = acquire_frame(&session, options);
992 if (acquired) read_device_state(&session, options);
994 return acquired;
995}
996
997/**
998 * @brief Measure the selected region, print statistics and attach them to the evidence.
999 *
1000 * @details Values are device-reported temperatures (raw / 64 - 273.15), not
1001 * calibrated surface temperatures. Standard deviation uses the single-pass
1002 * moment formula, clamped at zero against rounding. Threshold coverage
1003 * excludes endpoint codes (0/65535), and the range warning is purely
1004 * diagnostic: it never changes camera settings.
1005 *
1006 * @param options Measurement, thresholds and warning percentage.
1007 * @return false with errno EINVAL if the measurement cannot be computed.
1008 */
1010{
1011 struct lwir_temperature_stats *statistics = &captured_statistics;
1013 options->width, options->height, &options->measurement, &options->thresholds, statistics)) {
1014 errno = EINVAL;
1015 return false;
1016 }
1017 const double mean_raw = (double)statistics->sum_raw / statistics->pixels;
1018 const double variance = (double)statistics->sum_squared_raw / statistics->pixels - mean_raw * mean_raw;
1019 const double deviation = sqrt(variance > 0 ? variance : 0) / 64.0;
1020 fprintf(stderr, "LWIR: %s %s (%zu native centers, %s): reported C min=%.3f at %u,%u max=%.3f at %u,%u mean=%.3f"
1021 " spatial-stdev=%.3f endpoint-codes=%zu (calibration unverified)\n",
1022 options->raw ? "replay" : "camera", options->measurement.kind == LWIR_POINT ? "point" : options->measurement.kind == LWIR_LINE ? "line" : "ROI",
1023 statistics->pixels, options->measurement.average_3x3 ? "3x3 averaged" : "original pixels",
1024 statistics->min_raw / 64.0 - 273.15, statistics->min_x, statistics->min_y,
1025 statistics->max_raw / 64.0 - 273.15, statistics->max_x, statistics->max_y,
1026 mean_raw / 64.0 - 273.15, deviation, statistics->endpoint_codes);
1027 if (options->thresholds.enabled) {
1028 const size_t valid = statistics->pixels - statistics->endpoint_codes;
1029 const double fraction = valid ? 100.0 / valid : 0;
1030 fprintf(stderr, "LWIR: raw coverage [%.6f, %.6f] C valid=%zu below=%zu (%.3f%%) within=%zu (%.3f%%) above=%zu (%.3f%%) status=%s\n",
1031 options->thresholds.low / 64.0 - 273.15, options->thresholds.high / 64.0 - 273.15, valid,
1032 statistics->below, statistics->below * fraction, statistics->within, statistics->within * fraction,
1033 statistics->above, statistics->above * fraction, valid ? "available" : "unavailable");
1034 /* Inclusive warning percentage, calculated exactly in integers; never change camera settings. */
1035 if (valid && (statistics->below * 100 >= valid * options->warn_percent || statistics->above * 100 >= valid * options->warn_percent)) {
1036 fprintf(stderr, "LWIR: RANGE WARNING below=%u above=%u limit=%u%% (diagnostic only; gain/saturation/calibration unverified)\n",
1037 statistics->below * 100 >= valid * options->warn_percent ? 1U : 0U,
1038 statistics->above * 100 >= valid * options->warn_percent ? 1U : 0U, options->warn_percent);
1039 }
1040 }
1041 capture_evidence.measurement = &options->measurement;
1042 capture_evidence.thresholds = &options->thresholds;
1043 capture_evidence.statistics = statistics;
1044 capture_evidence.warn_percent = options->warn_percent;
1045 return true;
1046}
1047
1048/**
1049 * @brief Reset the evidence record and stamp the request start time.
1050 *
1051 * @details Called before acquisition: `request_us` is the freshness floor for
1052 * the frame. Exposure and frame duration are -1 and the time error is
1053 * UINT64_MAX because this camera path does not measure them; they must read as
1054 * unknown rather than zero.
1055 *
1056 * @param options Supplies the gain label, replay serial, view and raw path.
1057 * @return false if the monotonic clock is unavailable.
1058 */
1060{
1061 capture_evidence = (struct lwir_evidence){0};
1062 usher_boot_id(capture_evidence.capture.boot_id);
1063 capture_evidence.capture.process_id = (uint32_t)getpid();
1064 capture_evidence.capture.exposure_us = -1;
1065 capture_evidence.capture.frame_duration_us = -1;
1066 capture_evidence.capture.time_error_us = UINT64_MAX;
1067 capture_evidence.gain = options->gain_label;
1068 capture_evidence.serial = options->raw ? options->replay_serial : device_serial[0] ? device_serial : "unknown";
1069 capture_evidence.rendering = options->render.view == LWIR_SENSOR ? "sensor" : "thermal";
1070 capture_evidence.raw_path = options->record_raw;
1071 uint64_t requested;
1072 if (!monotonic_ms(&requested)) return false;
1073 capture_evidence.request_us = requested * 1000;
1074 return true;
1075}
1076
1077/**
1078 * @brief Validate, hash and durably publish ::captured_frame.
1079 *
1080 * @details Refuses publication when a correction profile disagrees with the
1081 * device gain readback or with the serial/gain label/geometry, because
1082 * applying the wrong profile would silently corrupt temperatures. Then hashes
1083 * the frame, optionally reports statistics, writes the raw companion and the
1084 * JPEG. Each writer uses the no-overwrite publication of the image library.
1085 * In analysis builds an ONNX failure is only reported: the photograph stays.
1086 *
1087 * @param[in,out] options Output paths and rendering policy.
1088 * @return true when the JPEG (and requested companion) were published.
1089 * false with errno EINVAL for profile conflicts, or the writer's errno.
1090 * @details Publication is all-or-nothing: when the JPEG cannot be published
1091 * after the raw companion was written, that companion is removed again, so a
1092 * failed request never leaves an orphaned raw file or blocks a later request
1093 * for the same name (link() refuses existing names).
1094 */
1096{
1097 uint16_t selected_gain;
1098 if (options->render.profile && options->gain_label &&
1099 lwir_state_u16(capture_evidence.device_state, LWIR_STATE_GAIN, &selected_gain) &&
1100 ((!strcmp(options->gain_label, "high") && selected_gain != 1) ||
1101 (!strcmp(options->gain_label, "low") && selected_gain != 0))) {
1102 fprintf(stderr, "LWIR: device gain selection conflicts with correction profile label; no publication\n");
1103 errno = EINVAL; return false;
1104 }
1105 if (options->render.profile && !lwir_profile_matches(options->render.profile, options->width, options->height,
1106 capture_evidence.serial, options->gain_label)) {
1107 fprintf(stderr, "LWIR: correction profile serial/gain/geometry mismatch; no publication\n");
1108 errno = EINVAL; return false;
1109 }
1110 capture_evidence.capture.width = options->width;
1111 capture_evidence.capture.height = options->height;
1112 capture_evidence.layout = options->layout;
1113 /* Image-only cameras deliver half of the combined frame size (no temperature plane). */
1114 const size_t bytes = lwir_frame_bytes(options->width, options->height) / (options->layout == LWIR_YUYV_IMAGE ? 2U : 1U);
1116 const bool prepared = !interrupted && (!options->report_stats || report_statistics(options));
1117 const bool raw_published = prepared && options->record_raw && lwir_write_raw(options->record_raw, captured_frame,
1118 lwir_frame_bytes(options->width, options->height), options->width, options->height);
1119 const bool published = prepared && (!options->record_raw || raw_published) &&
1121 options->width, options->height, options->raw != NULL, &capture_evidence, &options->render);
1122 if (!published && raw_published) {
1123 const int saved_errno = errno;
1124 if (!lwir_remove_published(options->record_raw))
1125 fprintf(stderr, "LWIR: JPEG failed and raw companion %s could not be removed: %s\n", options->record_raw, strerror(errno));
1126 errno = saved_errno;
1127 }
1128#if LWIR_ENABLE_ANALYSIS
1129 if (published && model_settings.backend == INFERENCE_ONNX) {
1130 char error[2048];
1131 if (!lwir_inference_image(options->output, capture_evidence.request_id, error, sizeof(error)))
1132 fprintf(stderr, "LWIR: analysis_failed; photograph retained: %s\n", error);
1133 }
1134#endif
1135 return published;
1136}
1137
1138/**
1139 * @brief Open the configured inference backend, if any.
1140 *
1141 * @details Opening before the camera means a bad model fails fast as a
1142 * configuration error instead of after a capture.
1143 *
1144 * @param options Score threshold and class index for ONNX.
1145 * @return true for the native backend or a successfully opened ONNX model;
1146 * false (callers exit 2) otherwise, with the reason on stderr.
1147 */
1148static bool begin_inference(const struct capture_options *options)
1149{
1150 if (model_settings.backend != INFERENCE_ONNX) return model_settings.backend == INFERENCE_NATIVE;
1151#if LWIR_ENABLE_ANALYSIS
1152 char error[2048];
1153 if (lwir_inference_open(&model_settings, options->score_threshold, options->class_index, error, sizeof(error))) return true;
1154 fprintf(stderr, "LWIR: %s\n", error);
1155#else
1156 (void)options;
1157 fprintf(stderr, "LWIR: ONNX requires an analysis-enabled build\n");
1158#endif
1159 return false;
1160}
1161
1162/**
1163 * @brief Child-process body of one-shot mode: run a control or a capture.
1164 *
1165 * @details For a standalone control, a fresh valid frame is acquired first,
1166 * because the camera's control mailbox is not reliably responsive right after
1167 * stream start. Writes are submitted once and never replayed; setters are
1168 * verified by readback, while FFC only reports acknowledgement. Failure lines
1169 * report `submitted=0|1` so the operator knows whether the camera may have
1170 * changed. For a capture, the frame is acquired (camera or replay) and
1171 * published; the output path is printed on success.
1172 *
1173 * @param[in,out] options Run policy.
1174 * @return 0 success; 1 runtime failure; 2 inference configuration error;
1175 * 128+signal when interrupted.
1176 */
1178{
1179 if (options->control_selected) {
1180 struct lwir_device device = {0};
1181 if (!open_camera(options, &device) || !acquire_frame(&device, options)) {
1182 lwir_device_close(&device);
1183 fprintf(stderr, "LWIR: control setup failed: %s\n", strerror(errno));
1184 return 1;
1185 }
1186 static const char *const names[] = {"gain", "emissivity-128", "agc-mode", "agc", "ffc"};
1187 /* Indexed by reply status; out-of-range values print "unknown" below. */
1188 static const char *const statuses[] = {"not_requested", "ok", "unsupported", "timeout", "io_error",
1189 "invalid", "busy", "skipped", "cancelled"};
1190 const char *name = names[options->control.kind];
1192 const bool success = options->control_read ? lwir_device_control_read(&device, options->control.kind, &result) :
1193 lwir_device_control(&device, &options->control, &result);
1194 lwir_device_close(&device);
1195 if (!success) {
1196 const unsigned status = (unsigned)result.reply.status;
1197 fprintf(stderr, "LWIR: control %s failed status=%s transport=%d device=%u submitted=%u verified=%u; %s; never retry automatically\n",
1198 name, status < sizeof(statuses) / sizeof(statuses[0]) ? statuses[status] : "unknown",
1199 result.reply.transport_error, result.reply.device_status, result.submitted ? 1U : 0U, result.verified ? 1U : 0U,
1200 result.submitted ? "camera state may have changed" : "no command submitted");
1201 return 1;
1202 }
1203 if (options->control_read) printf("LWIR_CONTROL_OK control=%s operation=read value=%u\n", name, result.readback);
1204 else if (options->control.kind == LWIR_CONTROL_FFC) printf("LWIR_CONTROL_OK control=ffc operation=trigger acknowledged=1 verified=0\n");
1205 else printf("LWIR_CONTROL_OK control=%s operation=write value=%u readback=%u verified=1\n", name,
1206 options->control.value, result.readback);
1207 return fflush(stdout) == 0 ? 0 : 1;
1208 }
1209 if (!begin_inference(options)) return 2;
1210 if (!initialize_evidence(options)) return 1;
1211 errno = 0;
1212 const bool acquired = options->raw != NULL ? read_raw(options) : capture_camera(options);
1213 /* --warmup qualifies the camera only; nothing is published. */
1214 if (options->warmup_only && acquired && !interrupted) return 0;
1215 if (!acquired || !publish_frame(options)) {
1216 if (interrupted) errno = EINTR;
1217 fprintf(stderr, "LWIR: capture failed: %s\n", strerror(errno));
1218 return interrupted ? 128 + interrupted : 1;
1219 }
1220 puts(options->output);
1221 return fflush(stdout) == 0 ? 0 : 1;
1222}
1223
1224/**
1225 * @brief Persistent `--capture-server` loop driven by USHER over stdin/stdout.
1226 *
1227 * @details Protocol:
1228 * - After the camera (or replay frame) is ready, prints `LWIR_SERVER_READY`.
1229 * - Each stdin line is an absolute output path, or `GEO:path` to geolocate an
1230 * existing JPEG in analysis builds.
1231 * - A capture replies `LWIR_SERVER_TIMING request_us arrival_us` then
1232 * `LWIR_SERVER_OK`; a geolocation replies `LWIR_SERVER_OK` only.
1233 * - Strictly one request at a time: bytes after the newline (pipelining),
1234 * embedded NULs, control characters, relative or overlong paths are
1235 * protocol errors (result 2).
1236 * - Any failure prints `LWIR_SERVER_ERROR` and ends the server. There is no
1237 * automatic replay; USHER's supervisor must explicitly restart it.
1238 *
1239 * While idle, stdin is polled every 10 ms and camera frames are discarded so
1240 * the 4-buffer driver queue never hands a stale frame to the next request; if
1241 * no frame arrives for `timeout_ms` the server fails. Each request has an
1242 * alarm() hang watchdog of `timeout_ms` rounded up to seconds: SIGALRM is not
1243 * handled, so a wedged request terminates the process.
1244 *
1245 * `warmup_ms` is forced to 0 per request: startup qualification happens once
1246 * per USB power instance (tracked by the device layer's driver marker), never
1247 * per request.
1248 *
1249 * @param[in,out] options Policy; `output` and `record_raw` are rewritten per request.
1250 * @return 0 when stdin reaches EOF cleanly; 1 runtime failure; 2 inference
1251 * configuration, correction-profile mismatch (before READY) or protocol
1252 * error; 128+signal when interrupted.
1253 */
1255{
1256 if (!begin_inference(options)) return 2;
1257 /* Bounds camera startup; the default SIGALRM action kills a hung open. */
1258 alarm((options->timeout_ms + 999) / 1000);
1259 struct lwir_device session = {0};
1260 if (!options->raw && (!open_camera(options, &session) || !acquire_frame(&session, options))) {
1261 lwir_device_close(&session); return 1;
1262 }
1263 if (options->raw && !read_raw(options)) return 1;
1264 /* Same check publish_frame() applies per request, done once now: a profile that
1265 * can never match would otherwise pass startup and then fail every capture in flight. */
1266 const char *profile_serial = options->raw ? options->replay_serial : device_serial[0] ? device_serial : "unknown";
1267 if (options->render.profile && !lwir_profile_matches(options->render.profile, options->width, options->height,
1268 profile_serial, options->gain_label)) {
1269 fprintf(stderr, "LWIR: correction profile does not match this camera's serial/gain label/geometry; not ready\n");
1270 lwir_device_close(&session); return 2;
1271 }
1272 const int flags = fcntl(STDIN_FILENO, F_GETFL);
1273 /* Non-blocking stdin lets the loop keep draining camera frames between requests. */
1274 if (flags < 0 || fcntl(STDIN_FILENO, F_SETFL, flags | O_NONBLOCK) != 0) { lwir_device_close(&session); return 1; }
1275 uint64_t last_frame;
1276 if (!monotonic_ms(&last_frame)) { lwir_device_close(&session); return 1; }
1277 puts("LWIR_SERVER_READY");
1278 if (fflush(stdout)) { lwir_device_close(&session); return 1; }
1279 alarm(0);
1280 /* 1100 bytes: a 1023-byte path plus the optional "GEO:" prefix, newline and slack. */
1281 char command[1100], raw_path[1100];
1282 size_t used = 0;
1283 uint64_t last_request = 0, replay_sequence = 0;
1284 bool have_request = false;
1285 int result = 0;
1286 while (!interrupted) {
1287 struct pollfd input = {.fd = STDIN_FILENO, .events = POLLIN};
1288 const int ready = poll(&input, 1, 10);
1289 if (ready < 0 && errno == EINTR) continue;
1290 if (ready < 0 || (input.revents & (POLLERR | POLLNVAL))) { result = 1; break; }
1291 if (input.revents & (POLLIN | POLLHUP)) {
1292 /* Reserve one byte for the terminator so the buffer is always a valid string. */
1293 const ssize_t received = read(STDIN_FILENO, command + used, sizeof(command) - used - 1);
1294 if (received < 0 && (errno == EINTR || errno == EAGAIN)) continue;
1295 /* EOF means USHER closed the pipe: a clean shutdown, not an error. */
1296 if (received <= 0) { result = received < 0 ? 1 : 0; break; }
1297 /* The watchdog starts at the first byte of a request, covering slow partial lines too. */
1298 if (!used) alarm((options->timeout_ms + 999) / 1000);
1299 used += (size_t)received;
1300 command[used] = '\0';
1301 char *newline = memchr(command, '\n', used);
1302 /* Partial line: keep accumulating unless the buffer is already full. */
1303 if (!newline) { if (used + 1 == sizeof(command)) { result = 2; break; } continue; }
1304 /* The newline must be the last byte read: anything after it is a pipelined request. */
1305 if (newline != command + used - 1 || memchr(command, '\0', used)) { result = 2; break; }
1306 *newline = '\0';
1307 for (size_t index = 0; index + 1 < used; ++index) if ((unsigned char)command[index] < 32 || command[index] == 127) { result = 2; break; }
1308 if (result) break;
1309 const bool geolocate = strncmp(command, "GEO:", 4) == 0;
1310 char *output_path = geolocate ? command + 4 : command;
1311 /* Request ids are never reused: a capture after id UINT64_MAX is refused. */
1312 if (output_path[0] != '/' || strlen(output_path) >= 1024 ||
1313 (!geolocate && have_request && last_request == UINT64_MAX)) { result = 2; break; }
1314 for (size_t index = 0; command[index]; ++index) {
1315 /* Defensive repeat of the control-character check on the terminated string. */
1316 if ((unsigned char)command[index] < 32 || command[index] == 127) { result = 2; break; }
1317 }
1318 if (result) break;
1319 if (geolocate) {
1320#if LWIR_ENABLE_ANALYSIS
1321 if (lwir_geolocate_image(output_path, options->calibration) != 0) { result = 1; break; }
1322 puts("LWIR_SERVER_OK");
1323 if (fflush(stdout) != 0) { result = 1; break; }
1324 alarm(0);
1325 used = 0;
1326 continue;
1327#else
1328 fprintf(stderr, "LWIR: geographic analysis unavailable in this build profile\n");
1329 result = 2;
1330 break;
1331#endif
1332 }
1333 const uint64_t request = have_request ? last_request + 1 : 1;
1334 last_request = request; have_request = true;
1335 /* Startup qualification already happened once for this USB power instance. */
1336 options->output = command; options->warmup_ms = 0;
1337 options->record_raw = NULL;
1338 if (options->native_raw) {
1339 const int length = snprintf(raw_path, sizeof(raw_path), "%s.raw", command);
1340 if (length < 0 || (size_t)length >= sizeof(raw_path)) { result = 2; break; }
1341 options->record_raw = raw_path;
1342 }
1343 if (!initialize_evidence(options)) { result = 1; break; }
1344 capture_evidence.request_id = request;
1345 if (!options->raw) {
1346 bool discarded = false;
1347 /* Drop queued frames so the published frame was exposed after this request. */
1348 if (!lwir_device_discard(&session, &discarded) || !acquire_frame(&session, options)) { result = 1; break; }
1350 } else {
1351 /* Replay re-reads the file per request and synthesises arrival time and sequence. */
1352 if (!read_raw(options) || !monotonic_ms(&last_frame)) { result = 1; break; }
1353 capture_evidence.arrival_us = last_frame * 1000;
1354 capture_evidence.capture.sequence = ++replay_sequence;
1355 }
1356 if (!publish_frame(options)) { result = 1; break; }
1357 printf("LWIR_SERVER_TIMING %llu %llu\nLWIR_SERVER_OK\n",
1358 (unsigned long long)capture_evidence.request_us,
1359 (unsigned long long)capture_evidence.arrival_us);
1360 if (fflush(stdout) || !monotonic_ms(&last_frame)) { result = 1; break; }
1361 alarm(0);
1362 used = 0;
1363 } else if (!options->raw) {
1364 /* Idle: keep the driver queue empty and detect a camera that stopped streaming. */
1365 bool discarded = false;
1366 uint64_t now;
1367 if (!lwir_device_discard(&session, &discarded) || !monotonic_ms(&now)) { result = 1; break; }
1368 if (discarded) last_frame = now;
1369 if (now - last_frame >= options->timeout_ms) { result = 1; break; }
1370 }
1371 }
1372 if (result) { puts("LWIR_SERVER_ERROR request failed; no automatic replay"); fflush(stdout); }
1373 /* Even closing the device may hang on USB; give it one second before SIGALRM kills the process. */
1374 alarm(1);
1376 alarm(0);
1377 return interrupted ? 128 + interrupted : result;
1378}
1379
1380/**
1381 * @brief Parent side of one-shot mode: wait for the capture child under a deadline.
1382 *
1383 * @details Polls waitpid() every 10 ms against a monotonic deadline. On timeout
1384 * or SIGINT/SIGTERM it sends SIGTERM, then SIGKILL after 250 ms. Publication may
1385 * already have happened, or be half-done, when the child is stopped, so the
1386 * outcome is reported as ambiguous and nothing is retried automatically. A
1387 * failing clock is treated as an expired deadline (fail safe).
1388 *
1389 * @param child Capture child process id.
1390 * @param timeout_ms Deadline from start of supervision.
1391 * @return The child's exit status; 1 if it died by a signal or waiting failed;
1392 * 124 on timeout; 128+signal when this process was interrupted.
1393 */
1394static int supervise(pid_t child, unsigned timeout_ms)
1395{
1396 uint64_t start = 0;
1397 const bool clock_valid = monotonic_ms(&start);
1398 bool terminating = false;
1399 uint64_t stop_started = 0;
1400 for (;;) {
1401 int status;
1402 const pid_t reaped = waitpid(child, &status, WNOHANG);
1403 if (reaped == child) {
1404 /* Exiting during termination still counts as cancelled, whatever its own status. */
1405 if (terminating) return interrupted ? 128 + interrupted : 124;
1406 return WIFEXITED(status) ? WEXITSTATUS(status) : 1;
1407 }
1408 if (reaped < 0 && errno != EINTR) return 1;
1409 uint64_t now = start;
1410 const bool now_valid = clock_valid && monotonic_ms(&now);
1411 const bool timed_out = !now_valid || now - start >= timeout_ms;
1412 if (!terminating && (interrupted || timed_out)) {
1413 terminating = true;
1414 stop_started = now;
1415 kill(child, SIGTERM);
1416 fprintf(stderr, "LWIR: lifecycle cancelled/timed out; publication may be ambiguous, never retry automatically\n");
1417 }
1418 if (terminating && (!now_valid || now - stop_started >= 250)) {
1419 kill(child, SIGKILL);
1420 do { } while (waitpid(child, &status, 0) < 0 && errno == EINTR);
1421 return interrupted ? 128 + interrupted : 124;
1422 }
1423 const struct timespec pause = {.tv_nsec = 10000000};
1424 if (nanosleep(&pause, NULL) != 0 && errno != EINTR) { kill(child, SIGKILL); waitpid(child, &status, 0); return 1; }
1425 }
1426}
1427
1428/**
1429 * @brief Program entry: select the mode, load policy and run it.
1430 *
1431 * @details Order matters: `--features`, `--version` and `--help` short-circuit;
1432 * the settings file is located and loaded before parse_options() so CLI values
1433 * override INI values; analysis/mock modes return before the camera is
1434 * touched; the correction profile is loaded and an existing output is refused
1435 * before signal handlers are installed and the capture starts. Server mode runs
1436 * in-process; one-shot mode forks so the parent can enforce the deadline.
1437 *
1438 * @param count argc.
1439 * @param arguments argv.
1440 * @return 0 success; 1 runtime failure; 2 usage/configuration error;
1441 * 124 timeout; 128+signal when interrupted.
1442 */
1443int main(int count, char **arguments)
1444{
1445 if (count == 2 && !strcmp(arguments[1], "--features")) {
1446 printf("analysis=%d mock=%d jpeg=%s capture=v4l2\n", LWIR_ENABLE_ANALYSIS, LWIR_ENABLE_MOCK,
1448 return 0;
1449 }
1450 if (count == 2 && strcmp(arguments[1], "--version") == 0) {
1452 return 0;
1453 }
1454 if (count == 2 && strcmp(arguments[1], "--help") == 0) {
1455 usage(stdout);
1456 return 0;
1457 }
1458 struct capture_options options = {.warmup_ms = 5000, .timeout_ms = 20000, .warn_percent = 1, .score_threshold = 0.6};
1459 options.render.jpeg_quality = 95;
1461 /* Pre-scan for the settings path: the INI must be applied before CLI options override it. */
1462 for (int index = 1; index < count; ++index) {
1463 if (!strcmp(arguments[index], "--config") || !strcmp(arguments[index], "--settings")) {
1464 if (options.config || ++index >= count || !arguments[index][0]) return 2;
1465 options.config = arguments[index];
1466 }
1467 }
1468 char default_settings[INFERENCE_PATH_CAPACITY];
1469 if (!options.config && inference_settings_find("lwircam", "lwir_cam", default_settings, sizeof(default_settings)))
1470 options.config = default_settings;
1471 if (options.config && !load_config(options.config, &options)) {
1472 fprintf(stderr, "LWIR: invalid runtime policy: %s\n", options.config); return 2;
1473 }
1474 if (!parse_options(count, arguments, &options)) {
1475 usage(stderr);
1476 return 2;
1477 }
1478#if LWIR_ENABLE_ANALYSIS
1479 if (options.inference_input || options.check_model) {
1480 if (!begin_inference(&options)) return 2;
1481 char error[2048];
1482 const bool valid = options.check_model || lwir_inference_image(options.inference_input, 1, error, sizeof(error));
1483 if (!valid) fprintf(stderr, "LWIR: %s\n", error);
1484 else puts(options.check_model ? "lwircam model ready adapter=lwir_classifier_v1" : "OK");
1486 return valid ? 0 : 1;
1487 }
1488 if (options.geolocate_input)
1489 return lwir_geolocate_image(options.geolocate_input, options.calibration) == 0 ? 0 : 1;
1490#endif
1491#if LWIR_ENABLE_MOCK
1492 if (options.mock_input)
1493 return lwir_process_mock(options.mock_input, options.output ? options.output : options.mock_input,
1494 options.mock_layer_only) == 0 ? 0 : 1;
1495#endif
1496 if (options.corrections) {
1497 if (!lwir_profile_load(options.corrections, &correction_profile)) {
1498 fprintf(stderr, "LWIR: invalid correction profile: %s\n", options.corrections); return 2;
1499 }
1500 options.render.profile = &correction_profile;
1501 }
1502 struct stat existing;
1503 /* Early, friendly refusal; the link()-based publication is the authoritative no-overwrite guard. */
1504 if (options.output && lstat(options.output, &existing) == 0) {
1505 fprintf(stderr, "LWIR: refusing to overwrite %s\n", options.output);
1506 return 1;
1507 }
1508 if (options.output && errno != ENOENT) {
1509 fprintf(stderr, "LWIR: cannot inspect %s: %s\n", options.output, strerror(errno));
1510 return 1;
1511 }
1512 char raw_path[1100];
1513 if (options.native_raw && options.output) {
1514 const int length = snprintf(raw_path, sizeof(raw_path), "%s.raw", options.output);
1515 if (length < 0 || (size_t)length >= sizeof(raw_path)) return 2;
1516 options.record_raw = raw_path;
1517 }
1518 struct sigaction action = {.sa_handler = interrupt_capture};
1519 if (sigemptyset(&action.sa_mask) != 0 || sigaction(SIGINT, &action, NULL) != 0 ||
1520 sigaction(SIGTERM, &action, NULL) != 0) {
1521 fprintf(stderr, "LWIR: cannot install cancellation handlers: %s\n", strerror(errno));
1522 return 1;
1523 }
1524 if (options.server) return serve_captures(&options);
1525 /* The child inherits the handlers, so both observe SIGINT/SIGTERM sent to the process group. */
1526 const pid_t child = fork();
1527 if (child < 0) { fprintf(stderr, "LWIR: cannot fork capture: %s\n", strerror(errno)); return 1; }
1528 if (child == 0) _exit(save_capture(&options));
1529 return supervise(child, options.timeout_ms);
1530}
Read Linux's boot-unique identifier for pose-log session provenance.
static void usher_boot_id(char result[37])
Fill a 36-character boot UUID or the stable fallback "unknown".
Definition boot_id.h:36
Allocation-free flat key=value mechanics; callers own schemas and storage.
static bool ini_real(const char *text, double *number)
Parse finite decimal/exponent notation, rejecting range errors and suffixes.
Definition bounded_ini.h:67
static unsigned capacity[COVERAGE_CAMERAS]
static uint32_t session
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 volatile sig_atomic_t interrupted
Signal-safe cancellation flag checked before blocking USB calls.
Definition chdkbridge.c:131
static uint64_t monotonic_ms(void)
Read a wall-clock-independent time base; return zero if the clock fails.
Definition chdkbridge.c:141
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.
static pid_t child
union dc_shot_union request
static bool ready
static int parse_unsigned(const char *text, unsigned int minimum, unsigned int maximum, unsigned int *value)
Parse a bounded unsigned command-line value.
Definition earcam.c:344
bool inference_settings_find(const char *application, const char *module, char *filename, size_t capacity)
Discover application_settings.ini in adjacent, development-module, then installed-share order.
bool inference_settings_read(struct inference_settings *settings, const char *filename, ini_field_handler extra, void *context, char *error, size_t capacity)
Parse one flat INI, delegate application keys and resolve paths against the selected file.
void inference_settings_init(struct inference_settings *settings, enum inference_backend backend)
Reset storage and select conservative thread/timeout defaults.
Shared application_settings.ini discovery with module-owned extra keys.
#define INFERENCE_PATH_CAPACITY
@ INFERENCE_NATIVE
@ INFERENCE_ONNX
int lwir_geolocate_image(const char *filename, const char *calibration_path)
Detect, optionally geolocate and record hotspots for one saved JPEG.
Optional saved-image adapter combining thermal detection, pose and projection.
static char device_serial[64]
static char configured_corrections[1024]
static void usage(FILE *output)
Print the build version and command-line synopsis.
static struct lwir_device_state captured_device_state
static char configured_gain[32]
config_field
Configuration identities shared by key lookup and duplicate/pair masks.
@ CONFIG_WIDTH
@ CONFIG_FIELD_COUNT
@ CONFIG_SCENE_CHECK
@ CONFIG_DENOISE_K
@ CONFIG_DEVICE_STATE
@ CONFIG_PERCENTILE_LOW
@ CONFIG_LEGEND
@ CONFIG_ROI
@ CONFIG_PALETTE
@ CONFIG_THRESHOLD_HIGH_C
@ CONFIG_SETTLE
@ CONFIG_HEIGHT
@ CONFIG_THRESHOLD_LOW_C
@ CONFIG_WINDOW_LOW_C
@ CONFIG_ROTATE
@ CONFIG_POINT
@ CONFIG_FLIP
@ CONFIG_AVERAGE_3X3
@ CONFIG_PERCENTILE_HIGH
@ CONFIG_FORMAT
@ CONFIG_MIRROR
@ CONFIG_TIMEOUT_MS
@ CONFIG_JPEG_QUALITY
@ CONFIG_SCORE_THRESHOLD
@ CONFIG_DEVICE
@ CONFIG_WARMUP_MS
@ CONFIG_GAIN_LABEL
@ CONFIG_CLASS_INDEX
@ CONFIG_LINE
@ CONFIG_STATS
@ CONFIG_WINDOW_HIGH_C
@ CONFIG_SERIAL
@ CONFIG_CORRECTIONS
@ CONFIG_WARN_PERCENT
static int serve_captures(struct capture_options *options)
Persistent --capture-server loop driven by USHER over stdin/stdout.
static struct lwir_evidence capture_evidence
static bool acquire_frame(struct lwir_device *device, const struct capture_options *options)
Acquire one frame into captured_frame and record its timing evidence.
static bool load_config(const char *path, struct capture_options *options)
Load the settings INI into options before command-line parsing.
static bool temperature_band(double low_c, double high_c, uint16_t *low_raw, uint16_t *high_raw)
Convert a Celsius band to device raw codes (Kelvin * 64).
static bool parse_options(int count, char **arguments, struct capture_options *options)
Apply command-line options on top of the INI settings and validate the mode.
static struct lwir_profile correction_profile
static bool open_camera(struct capture_options *options, struct lwir_device *device)
Open the camera and adopt its negotiated geometry, layout and serial.
static uint8_t captured_frame[LWIR_MAX_FRAME_BYTES]
static bool initialize_evidence(const struct capture_options *options)
Reset the evidence record and stamp the request start time.
static bool read_raw(const struct capture_options *options)
Load a replay frame into captured_frame.
static int supervise(pid_t child, unsigned timeout_ms)
Parent side of one-shot mode: wait for the capture child under a deadline.
static bool begin_inference(const struct capture_options *options)
Open the configured inference backend, if any.
static bool publish_frame(struct capture_options *options)
Validate, hash and durably publish captured_frame.
static char configured_serial[64]
static bool capture_camera(struct capture_options *options)
One-shot camera capture: open, acquire, optional state, close.
static int save_capture(struct capture_options *options)
Child-process body of one-shot mode: run a control or a capture.
static char device_state_text[4096]
static void read_device_state(struct lwir_device *device, const struct capture_options *options)
Optionally attach read-only device state to the evidence.
int main(int count, char **arguments)
Program entry: select the mode, load policy and run it.
static bool select_measurement(struct capture_options *options, enum lwir_measurement_kind kind, const unsigned *coordinates)
Select the single point, line or rectangle measurement.
static struct lwir_device_options device_policy(const struct capture_options *options)
Translate capture options into the device-layer acquisition policy.
static struct lwir_temperature_stats captured_statistics
static bool parse_coordinates(const char *text, unsigned count, unsigned *coordinates)
Parse an INI coordinate list such as x,y or x,y,w,h.
static void interrupt_capture(int signal_number)
SIGINT/SIGTERM handler: record the signal for cooperative cancellation.
static char configured_device[1024]
static bool parse_unsigned(const char *text, unsigned maximum, unsigned *value)
Strictly parse a decimal unsigned integer with an upper bound.
static bool report_statistics(const struct capture_options *options)
Measure the selected region, print statistics and attach them to the evidence.
static struct inference_settings model_settings
Tiny1C/TDK acquisition and Tiny1C state, without image or mission logic.
bool lwir_device_discard(struct lwir_device *device, bool *received)
Drain one pending frame without retaining the borrowed UVC buffer.
void lwir_device_read_state(struct lwir_device *device, struct lwir_device_state *state)
Read bounded optional state after acquisition, never writing device 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)
Copy a qualified, fresh camera-layout frame into caller-owned storage.
bool lwir_device_open(struct lwir_device_options *options, struct lwir_device *device)
Open/start a bounded camera-specific combined or image-only YUY2 stream.
bool lwir_device_control(struct lwir_device *device, const struct lwir_control_request *request, struct lwir_control_result *result)
Submit one Tiny1-C vendor control write (or FFC action) as a standalone operation.
bool lwir_device_control_read(struct lwir_device *device, enum lwir_control_kind kind, struct lwir_control_result *result)
Read the current value of one Tiny1-C control without writing it.
void lwir_device_close(struct lwir_device *device)
Close an initialized session; safe repeatedly and preserves errno.
Positive opt-ins shared by the worker and its USHER adapter.
#define LWIR_ENABLE_MOCK
1 builds the development replay/synthetic-temperature adapter (lwir_mock).
#define LWIR_ENABLE_ANALYSIS
1 builds the optional ONNX analysis of saved photos (lwir_inference).
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_measure_temperature(const uint8_t *frame, size_t bytes, unsigned width, unsigned height, const struct lwir_measurement *measurement, const struct lwir_thresholds *thresholds, struct lwir_temperature_stats *statistics)
Measure a point, line or rectangle in native coordinates.
Definition lwir_frame.c:326
bool lwir_frame_valid(const uint8_t *frame, size_t bytes, unsigned width, unsigned height)
Structural check: non-NULL, supported geometry, exact combined size.
Definition lwir_frame.c:420
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
Native frame arithmetic and camera measurements; no codec or flight dependencies.
#define LWIR_MAX_WIDTH
Largest supported native width in pixels.
Definition lwir_frame.h:47
lwir_measurement_kind
Ordinary camera measurements, independent of optional hotspot analysis.
Definition lwir_frame.h:69
@ LWIR_POINT
Definition lwir_frame.h:71
@ LWIR_LINE
Definition lwir_frame.h:72
@ LWIR_RECTANGLE
Definition lwir_frame.h:70
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
#define LWIR_MAX_FRAME_BYTES
Largest combined frame: two planes of 2 bytes per pixel.
Definition lwir_frame.h:51
#define LWIR_MAX_HEIGHT
Largest supported native height in pixels.
Definition lwir_frame.h:49
bool lwir_write_raw(const char *path, const uint8_t *frame, size_t bytes, unsigned width, unsigned height)
Publish the combined frame verbatim; see lwir_image.h.
Definition lwir_image.c:516
bool lwir_write_jpeg_rendered(const char *path, const uint8_t *frame, size_t bytes, unsigned width, unsigned height, bool synthetic, const struct lwir_evidence *evidence, const struct lwir_render_options *render)
Publish a rendered view with provenance; see lwir_image.h.
Definition lwir_image.c:522
bool lwir_remove_published(const char *path)
Remove a file this process published and persist the removal; see lwir_image.h.
Definition lwir_image.c:488
const char * lwir_jpeg_provider(void)
Report the bundled codec; see lwir_image.h.
Definition lwir_image.c:380
struct jpeg_error_mgr error
Definition lwir_image.c:60
JPEG encoding and durable no-overwrite publication of LWIR frames.
void lwir_inference_close(void)
Release the classifier; harmless when not open. Threshold/category are reset by the next open.
bool lwir_inference_image(const char *filename, unsigned long long sequence, char *error, size_t capacity)
Classify one saved photo and publish its evidence sidecar.
bool lwir_inference_open(const struct inference_settings *settings, double threshold, unsigned category, char *error, size_t capacity)
Open and qualify the LWIR classifier (see lwir_inference.h).
Optional serialized LWIR model adapter, separate from USB capture and calibration.
int lwir_process_mock(const char *input_path, const char *output_path, bool layer_only)
Produce mock LWIR evidence from input_path at output_path.
Definition lwir_mock.c:208
Optional development replay adapter, independent of geographic analysis.
bool lwir_profile_load(const char *path, struct lwir_profile *profile)
Load and fully validate a profile; see lwir_render.h.
bool lwir_profile_matches(const struct lwir_profile *profile, unsigned width, unsigned height, const char *serial, const char *gain)
Exact match of geometry, serial and gain label; see lwir_render.h.
Display rendering of Tiny1-C frames into JPEG-ready Y/Cb/Cr scanlines.
@ LWIR_IRON
Definition lwir_render.h:60
@ LWIR_BLACK_HOT
Definition lwir_render.h:59
@ LWIR_WHITE_HOT
Definition lwir_render.h:58
@ LWIR_FIXED
Definition lwir_render.h:53
@ LWIR_SENSOR
Definition lwir_render.h:52
@ LWIR_PERCENTILE
Definition lwir_render.h:54
bool lwir_state_u16(const struct lwir_device_state *state, enum lwir_state_field field, uint16_t *value)
Decode a validated big-endian two-byte snapshot field.
Definition lwir_state.c:412
size_t lwir_state_format(const struct lwir_device_state *state, char *output, size_t capacity)
Render snapshot evidence as key=value lines for the JPEG APP14 segment.
Definition lwir_state.c:430
bool lwir_control_valid(const struct lwir_control_request *request)
Range-check a control request (vendor-header limits).
Definition lwir_state.c:231
@ LWIR_STATE_GAIN
Definition lwir_state.h:88
@ LWIR_CONTROL_GAIN
Definition lwir_state.h:176
@ LWIR_CONTROL_FFC
Definition lwir_state.h:177
@ LWIR_CONTROL_AGC_MODE
Definition lwir_state.h:176
@ LWIR_CONTROL_EMISSIVITY
Definition lwir_state.h:176
@ LWIR_CONTROL_AGC_ENABLE
Definition lwir_state.h:177
Build-version string exported by the standalone LWIR application.
#define LWIRCAM_BUILD_VERSION
Human-readable identity, e.g. "LWIRcam 1.0.0 (Git unknown)", built by literal concatenation.
Definition version.h:34
static size_t count
Definition pose_log.c:79
static FILE * output
Definition pose_log.c:77
void sha256_hex(const void *data, size_t length, char *output)
Hash one memory region to a lowercase hexadecimal string.
Definition sha256fst.c:272
Allocation-free, portable SHA-256 checksums for memory and streams.
Effective run policy: INI settings first, then command-line overrides.
const char * mock_input
const char * config
const char * replay_serial
const char * inference_input
const char * calibration
struct lwir_thresholds thresholds
enum lwir_frame_layout layout
const char * corrections
unsigned class_index
struct lwir_measurement measurement
struct lwir_render_options render
const char * raw
const char * serial
const char * output
struct lwir_control_request control
const char * gain_label
const char * record_raw
unsigned warn_percent
const char * geolocate_input
unsigned timeout_ms
const char * device_path
Callback context while reading the settings INI.
struct capture_options * options
double threshold_high_c
double threshold_low_c
Per-application configuration; all resolved paths belong to this caller-owned value.
One requested setting change; validate with lwir_control_valid().
Definition lwir_state.h:181
uint16_t value
New value in the units of the matching lwir_state_field.
Definition lwir_state.h:183
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.
char serial[64]
enum lwir_frame_layout layout
Borrowed provenance for one publication; strings must outlive encoding.
Definition lwir_image.h:63
One native-coordinate measurement request.
Definition lwir_frame.h:76
Measured display-correction profile for one camera, gain label and geometry.
Definition lwir_render.h:70
Display policy for one rendering request; never affects stored samples.
Native rectangle; a zero width/height pair selects the full image.
Definition lwir_frame.h:61
Raw-unit measurement results; derive mean/variance from the sums and pixels.
Definition lwir_frame.h:98
Optional coverage band counted alongside measurement statistics.
Definition lwir_frame.h:89
Validated capture and reporting policy, fixed before the sample loop.
Definition earcam.c:137
bool server
Definition earcam.c:147
bool check_model
Definition earcam.c:149
bool valid
Definition usher.c:537
struct usher_control_result result
Definition usher.c:377