Command-line entry point of the lwircam executable. More...
#include "lwir_frame.h"#include "lwir_image.h"#include "lwir_features.h"#include "boot_id.h"#include "sha256fst.h"#include "lwir_render.h"#include "bounded_ini.h"#include "inference_settings.h"#include "version.h"#include <errno.h>#include <fcntl.h>#include <math.h>#include <poll.h>#include <signal.h>#include <stdio.h>#include <stdlib.h>#include <string.h>#include <sys/stat.h>#include <sys/wait.h>#include <time.h>#include <unistd.h>#include "lwir_device.h"
Go to the source code of this file.
Data Structures | |
| struct | capture_options |
| Effective run policy: INI settings first, then command-line overrides. More... | |
| struct | config_parser |
| Callback context while reading the settings INI. More... | |
Enumerations | |
| enum | config_field { CONFIG_FORMAT , CONFIG_WIDTH , CONFIG_HEIGHT , CONFIG_WARMUP_MS , CONFIG_TIMEOUT_MS , CONFIG_WINDOW_LOW_C , CONFIG_WINDOW_HIGH_C , CONFIG_PERCENTILE_LOW , CONFIG_PERCENTILE_HIGH , CONFIG_PALETTE , CONFIG_LEGEND , CONFIG_DENOISE_K , CONFIG_SERIAL , CONFIG_GAIN_LABEL , CONFIG_CORRECTIONS , CONFIG_SCENE_CHECK , CONFIG_SETTLE , CONFIG_THRESHOLD_LOW_C , CONFIG_THRESHOLD_HIGH_C , CONFIG_WARN_PERCENT , CONFIG_STATS , CONFIG_POINT , CONFIG_LINE , CONFIG_AVERAGE_3X3 , CONFIG_ROI , CONFIG_ROTATE , CONFIG_MIRROR , CONFIG_FLIP , CONFIG_DEVICE_STATE , CONFIG_SCORE_THRESHOLD , CONFIG_CLASS_INDEX , CONFIG_DEVICE , CONFIG_JPEG_QUALITY , CONFIG_FIELD_COUNT } |
| Configuration identities shared by key lookup and duplicate/pair masks. More... | |
Functions | |
| static bool | parse_unsigned (const char *text, unsigned maximum, unsigned *value) |
| Strictly parse a decimal unsigned integer with an upper bound. | |
| 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 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 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 | config_field (void *context, const char *key, const char *value) |
| Accept one key = value pair from the settings INI. | |
| static bool | load_config (const char *path, struct capture_options *options) |
Load the settings INI into options before command-line parsing. | |
| static void | interrupt_capture (int signal_number) |
| SIGINT/SIGTERM handler: record the signal for cooperative cancellation. | |
| static void | usage (FILE *output) |
| Print the build version and command-line synopsis. | |
| 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 bool | monotonic_ms (uint64_t *milliseconds) |
| Read CLOCK_MONOTONIC in milliseconds. | |
| static bool | read_raw (const struct capture_options *options) |
| Load a replay frame into captured_frame. | |
| static struct lwir_device_options | device_policy (const struct capture_options *options) |
| Translate capture options into the device-layer acquisition policy. | |
| static bool | open_camera (struct capture_options *options, struct lwir_device *device) |
| Open the camera and adopt its negotiated geometry, layout and serial. | |
| 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 void | read_device_state (struct lwir_device *device, const struct capture_options *options) |
| Optionally attach read-only device state to the evidence. | |
| static bool | capture_camera (struct capture_options *options) |
| One-shot camera capture: open, acquire, optional state, close. | |
| static bool | report_statistics (const struct capture_options *options) |
| Measure the selected region, print statistics and attach them to the evidence. | |
| static bool | initialize_evidence (const struct capture_options *options) |
| Reset the evidence record and stamp the request start time. | |
| static bool | publish_frame (struct capture_options *options) |
| Validate, hash and durably publish captured_frame. | |
| static bool | begin_inference (const struct capture_options *options) |
| Open the configured inference backend, if any. | |
| static int | save_capture (struct capture_options *options) |
| Child-process body of one-shot mode: run a control or a capture. | |
| static int | serve_captures (struct capture_options *options) |
| Persistent --capture-server loop driven by USHER over stdin/stdout. | |
| static int | supervise (pid_t child, unsigned timeout_ms) |
| Parent side of one-shot mode: wait for the capture child under a deadline. | |
| int | main (int count, char **arguments) |
| Program entry: select the mode, load policy and run it. | |
Variables | |
| static struct inference_settings | model_settings |
| static uint8_t | captured_frame [LWIR_MAX_FRAME_BYTES] |
| static volatile sig_atomic_t | interrupted |
| static struct lwir_evidence | capture_evidence |
| static char | device_serial [64] |
| static struct lwir_profile | correction_profile |
| static struct lwir_temperature_stats | captured_statistics |
| static struct lwir_device_state | captured_device_state |
| static char | device_state_text [4096] |
| static char | configured_serial [64] |
| static char | configured_gain [32] |
| static char | configured_corrections [1024] |
| static char | configured_device [1024] |
Detailed Description
Command-line entry point of the lwircam executable.
One binary serves several mutually exclusive roles, selected by options:
- One-shot capture (default): main() forks; the child runs save_capture() while the parent supervise()s it against a monotonic deadline, so a wedged USB/UVC call cannot outlive timeout_ms.
- Persistent capture server (--capture-server): serve_captures() keeps the camera streaming and answers one absolute output path per stdin line. This is the interface USHER drives.
- Raw replay (--raw FRAME --size W H): renders a recorded frame through the same statistics/JPEG/publication path, marked as simulated.
- Standalone camera controls (--get-control, --set-gain, --set-emissivity-128, --set-agc-mode, --set-agc, --ffc): exactly one control per invocation, no image output.
- Optional builds: analysis builds add --analyze, --check-model, --calibration and --geolocate; mock builds add --mock-image and --mock-layer. Those options are rejected in builds without the feature.
Capture data flow:
- Acquire a frame (camera via lwir_device, or replay file) into the static captured_frame buffer. Freshness is measured from the start of the request, so a published photo is never older than the request.
- Optionally read device state (--device-state): opt-in, read-only, after the frame (not frame-atomic) and bounded to 250 ms.
- Optionally compute temperature statistics/threshold coverage.
- Hash the frame bytes (SHA-256) into the evidence record.
- Optionally write a raw companion (--record-raw or --native-raw, which derives PATH.raw) for byte-exact verification.
- Encode the JPEG with evidence metadata; the temperature plane is stored exactly in APP15 markers. Capture defaults to quality 95 with 4:4:4 sampling (0 in the library means legacy quality 100).
- Publish durably without overwriting: the image library writes a temporary file, fsyncs it, link()s it to the final name (fails if it exists) and fsyncs the directory. main() also refuses an existing output up front.
Configuration precedence: the settings INI (--settings/--config, or the discovered default lwircam settings file) is loaded first, then command-line options override or extend it. Each INI key may appear only once.
Exit codes: 0 success; 1 runtime failure; 2 usage/configuration error (including capture-server protocol violations); 124 supervisor timeout; 128+signal when interrupted by SIGINT/SIGTERM.
Memory policy: no heap in this file and no memcpy (project policy); strings are copied with bounded loops into fixed static storage.
Definition in file lwir_capture.c.
Enumeration Type Documentation
◆ config_field
| enum config_field |
Configuration identities shared by key lookup and duplicate/pair masks.
Each enumerator is both an index into the key table in config_field() and a bit position in config_parser::seen. Setting a bit on first sight lets a repeated key be rejected, and load_config() tests groups of bits to require complete pairs (window, percentiles, thresholds) and to forbid window and percentiles together.
Definition at line 195 of file lwir_capture.c.
Function Documentation
◆ acquire_frame()
|
static |
Acquire one frame into captured_frame and record its timing evidence.
The device layer applies warmup, qualification and the deadline, and rejects frames timestamped before the acquisition started. Because that start follows the request time stamped by initialize_evidence(), photos are never older than the request.
- Parameters
-
device Open session. options Acquisition policy.
- Returns
- false on timeout, cancellation or invalid frame, errno set by the device layer.
Definition at line 944 of file lwir_capture.c.
◆ begin_inference()
|
static |
Open the configured inference backend, if any.
Opening before the camera means a bad model fails fast as a configuration error instead of after a capture.
- Parameters
-
options Score threshold and class index for ONNX.
- Returns
- true for the native backend or a successfully opened ONNX model; false (callers exit 2) otherwise, with the reason on stderr.
Definition at line 1148 of file lwir_capture.c.
◆ capture_camera()
|
static |
One-shot camera capture: open, acquire, optional state, close.
The session is closed before publication so encoding and fsync do not hold the camera.
- Parameters
-
[in,out] options Geometry and layout are filled from the device.
- Returns
- true when a frame is in captured_frame; errno describes failures.
Definition at line 987 of file lwir_capture.c.
◆ config_field()
|
static |
Accept one key = value pair from the settings INI.
Maps the key to its config_field identity, rejects unknown or repeated keys, validates the value and stores it in the options. Strings are copied with bounded loops into static buffers because the INI reader's value storage does not outlive the callback. Paired Celsius values are only staged; load_config() checks their completeness and ordering.
- Parameters
-
context A struct config_parser. key INI key. value INI value text.
- Returns
- false for an unknown/duplicate key or an invalid value, which makes the whole settings file invalid.
Definition at line 264 of file lwir_capture.c.
◆ device_policy()
|
static |
Translate capture options into the device-layer acquisition policy.
requires_thermal is true whenever any requested feature needs the temperature plane, letting the device layer refuse image-only cameras up front instead of producing incomplete evidence.
- Parameters
-
options Current policy; pointers inside the result alias it.
- Returns
- Device options by value; interrupted is passed as the cancel flag.
Definition at line 898 of file lwir_capture.c.
◆ initialize_evidence()
|
static |
Reset the evidence record and stamp the request start time.
Called before acquisition: request_us is the freshness floor for the frame. Exposure and frame duration are -1 and the time error is UINT64_MAX because this camera path does not measure them; they must read as unknown rather than zero.
- Parameters
-
options Supplies the gain label, replay serial, view and raw path.
- Returns
- false if the monotonic clock is unavailable.
Definition at line 1059 of file lwir_capture.c.
◆ interrupt_capture()
|
static |
SIGINT/SIGTERM handler: record the signal for cooperative cancellation.
Only stores into a sig_atomic_t; capture loops poll interrupted (and the device layer receives it as its cancel flag) so cleanup runs in normal context.
- Parameters
-
signal_number Delivered signal, later reported as exit code 128+signal.
Definition at line 438 of file lwir_capture.c.
◆ load_config()
|
static |
Load the settings INI into options before command-line parsing.
Resets model_settings to the native backend, lets the shared inference-settings reader dispatch each key to config_field(), then applies cross-key rules: format = LWIR_CONFIG_V1 is mandatory, thresholds and window values must come in complete pairs, and a fixed window excludes percentiles. A configured size must form a valid frame geometry.
- Parameters
-
path Settings file path. [in,out] options Defaults on entry; INI values on return.
- Returns
- true when the file is readable and every key is valid; on false the caller exits with code 2. The reader's error text is not printed here.
- Note
- The pair masks use 32-bit constants; this is sufficient only because every identity they test is below 32 (CONFIG_JPEG_QUALITY is not).
Definition at line 399 of file lwir_capture.c.
◆ main()
| int main | ( | int | count, |
| char ** | arguments ) |
Program entry: select the mode, load policy and run it.
Order matters: --features, --version and --help short-circuit; the settings file is located and loaded before parse_options() so CLI values override INI values; analysis/mock modes return before the camera is touched; the correction profile is loaded and an existing output is refused before signal handlers are installed and the capture starts. Server mode runs in-process; one-shot mode forks so the parent can enforce the deadline.
- Parameters
-
count argc. arguments argv.
- Returns
- 0 success; 1 runtime failure; 2 usage/configuration error; 124 timeout; 128+signal when interrupted.
Definition at line 1443 of file lwir_capture.c.
◆ monotonic_ms()
|
static |
Read CLOCK_MONOTONIC in milliseconds.
Monotonic time is immune to wall-clock steps (NTP/GPS), which would otherwise falsely trigger or postpone deadlines.
- Parameters
-
[out] milliseconds Current monotonic time.
- Returns
- false if clock_gettime() fails (errno set by it).
Definition at line 836 of file lwir_capture.c.
◆ open_camera()
|
static |
Open the camera and adopt its negotiated geometry, layout and serial.
The serial is copied into static storage so the evidence pointer remains valid after the device session is closed.
- Parameters
-
[in,out] options Width, height and layout are updated from the device. [out] device Session to close with lwir_device_close().
- Returns
- false on open failure, errno set by the device layer.
Definition at line 920 of file lwir_capture.c.
◆ parse_coordinates()
|
static |
Parse an INI coordinate list such as x,y or x,y,w,h.
Each field must start with a digit (blocking strtoul's sign and whitespace acceptance) and be followed by exactly , or, for the last one, the end of the string.
- Parameters
-
text Comma-separated decimal values. count Number of fields expected (2 or 4). [out] coordinates At least countelements.
- Returns
- true when exactly
countvalues, each <= LWIR_MAX_WIDTH, are present.
Definition at line 559 of file lwir_capture.c.
◆ parse_options()
|
static |
Apply command-line options on top of the INI settings and validate the mode.
Three passes:
- Parse each option, rejecting repeats where a second value would be ambiguous, and feature options missing from this build profile.
- Reject any argument of 1024+ bytes or containing control characters, so paths and labels cannot inject lines into logs or metadata.
- Enforce mode rules: a standalone control admits only its selector, --device, --serial and --timeout-ms; analysis-only runs exclude capture; everything else must satisfy the mutual-exclusion expression at the end.
- Parameters
-
count argc. arguments argv; strings are referenced, not copied. [in,out] options INI-derived values on entry; final policy on return.
- Returns
- false for any usage error; the caller prints usage and exits 2.
- Note
- --settings/--config was already consumed by main(); here it only has to repeat the same path.
Definition at line 592 of file lwir_capture.c.
◆ parse_unsigned()
|
static |
Strictly parse a decimal unsigned integer with an upper bound.
Pre-scans for digits only, because strtoul() would otherwise accept leading whitespace, a sign (wrapping "-1" to a huge value) or a 0x prefix.
- Parameters
-
text NUL-terminated input; NULL or empty is rejected. maximum Largest accepted value. [out] value Written only on success.
- Returns
- true for a pure digit string within range.
Definition at line 505 of file lwir_capture.c.
◆ publish_frame()
|
static |
Validate, hash and durably publish captured_frame.
Refuses publication when a correction profile disagrees with the device gain readback or with the serial/gain label/geometry, because applying the wrong profile would silently corrupt temperatures. Then hashes the frame, optionally reports statistics, writes the raw companion and the JPEG. Each writer uses the no-overwrite publication of the image library. In analysis builds an ONNX failure is only reported: the photograph stays.
- Parameters
-
[in,out] options Output paths and rendering policy.
- Returns
- true when the JPEG (and requested companion) were published. false with errno EINVAL for profile conflicts, or the writer's errno.
Publication is all-or-nothing: when the JPEG cannot be published after the raw companion was written, that companion is removed again, so a failed request never leaves an orphaned raw file or blocks a later request for the same name (link() refuses existing names).
Definition at line 1095 of file lwir_capture.c.
◆ read_device_state()
|
static |
Optionally attach read-only device state to the evidence.
Runs only with --device-state, after the frame, so the state is not frame-atomic. The device layer bounds the query to 250 ms. State is best effort: failure never fails the capture, and errno is preserved so a later failure report is not masked by a state-query error.
- Parameters
-
device Open session. options Supplies the device_state flag.
Definition at line 967 of file lwir_capture.c.
◆ read_raw()
|
static |
Load a replay frame into captured_frame.
Opens with O_NOFOLLOW and O_NONBLOCK and requires a regular file of exactly the expected size, so symlinks, FIFOs and devices cannot block or redirect the read. A trailing-byte probe catches files that grew after fstat(). The frame is then structurally validated and, with --scene-check, checked for plausibility.
- Parameters
-
options Supplies the replay path and geometry.
- Returns
- true on success. On failure errno is EINVAL (wrong type/size/content), EIO (read or close error) or the open()/fdopen() error.
Definition at line 857 of file lwir_capture.c.
◆ report_statistics()
|
static |
Measure the selected region, print statistics and attach them to the evidence.
Values are device-reported temperatures (raw / 64 - 273.15), not calibrated surface temperatures. Standard deviation uses the single-pass moment formula, clamped at zero against rounding. Threshold coverage excludes endpoint codes (0/65535), and the range warning is purely diagnostic: it never changes camera settings.
- Parameters
-
options Measurement, thresholds and warning percentage.
- Returns
- false with errno EINVAL if the measurement cannot be computed.
Definition at line 1009 of file lwir_capture.c.
◆ save_capture()
|
static |
Child-process body of one-shot mode: run a control or a capture.
For a standalone control, a fresh valid frame is acquired first, because the camera's control mailbox is not reliably responsive right after stream start. Writes are submitted once and never replayed; setters are verified by readback, while FFC only reports acknowledgement. Failure lines report submitted=0|1 so the operator knows whether the camera may have changed. For a capture, the frame is acquired (camera or replay) and published; the output path is printed on success.
- Parameters
-
[in,out] options Run policy.
- Returns
- 0 success; 1 runtime failure; 2 inference configuration error; 128+signal when interrupted.
Definition at line 1177 of file lwir_capture.c.
◆ select_measurement()
|
static |
Select the single point, line or rectangle measurement.
The zero-initialised measurement (kind LWIR_RECTANGLE, width 0) means "none chosen yet"; any prior selection makes a second one fail, so the INI and command line together can name at most one measurement. Bounds against the frame are checked later, once the geometry is known.
- Parameters
-
[in,out] options Receives the measurement and enables statistics. kind Point, line or rectangle. coordinates x y for a point; x0 y0 x1 y1 for a line; x y w h for a rectangle.
- Returns
- false if a measurement was already selected or a rectangle is empty.
Definition at line 532 of file lwir_capture.c.
◆ serve_captures()
|
static |
Persistent --capture-server loop driven by USHER over stdin/stdout.
Protocol:
- After the camera (or replay frame) is ready, prints LWIR_SERVER_READY.
- Each stdin line is an absolute output path, or GEO:path to geolocate an existing JPEG in analysis builds.
- A capture replies LWIR_SERVER_TIMING request_us arrival_us then LWIR_SERVER_OK; a geolocation replies LWIR_SERVER_OK only.
- Strictly one request at a time: bytes after the newline (pipelining), embedded NULs, control characters, relative or overlong paths are protocol errors (result 2).
- Any failure prints LWIR_SERVER_ERROR and ends the server. There is no automatic replay; USHER's supervisor must explicitly restart it.
While idle, stdin is polled every 10 ms and camera frames are discarded so the 4-buffer driver queue never hands a stale frame to the next request; if no frame arrives for timeout_ms the server fails. Each request has an alarm() hang watchdog of timeout_ms rounded up to seconds: SIGALRM is not handled, so a wedged request terminates the process.
warmup_ms is forced to 0 per request: startup qualification happens once per USB power instance (tracked by the device layer's driver marker), never per request.
- Parameters
-
[in,out] options Policy; output and record_raw are rewritten per request.
- Returns
- 0 when stdin reaches EOF cleanly; 1 runtime failure; 2 inference configuration, correction-profile mismatch (before READY) or protocol error; 128+signal when interrupted.
Definition at line 1254 of file lwir_capture.c.
◆ supervise()
|
static |
Parent side of one-shot mode: wait for the capture child under a deadline.
Polls waitpid() every 10 ms against a monotonic deadline. On timeout or SIGINT/SIGTERM it sends SIGTERM, then SIGKILL after 250 ms. Publication may already have happened, or be half-done, when the child is stopped, so the outcome is reported as ambiguous and nothing is retried automatically. A failing clock is treated as an expired deadline (fail safe).
- Parameters
-
child Capture child process id. timeout_ms Deadline from start of supervision.
- Returns
- The child's exit status; 1 if it died by a signal or waiting failed; 124 on timeout; 128+signal when this process was interrupted.
Definition at line 1394 of file lwir_capture.c.
◆ temperature_band()
|
static |
Convert a Celsius band to device raw codes (Kelvin * 64).
Rounds to nearest and re-checks ordering after rounding, because two distinct close temperatures can collapse onto the same raw code.
- Parameters
-
low_c Lower bound in degrees Celsius. high_c Upper bound in degrees Celsius. [out] low_raw Lower raw code; written only when both bounds are representable. [out] high_raw Upper raw code.
- Returns
- true when both bounds are finite, within 0..65535 and strictly ordered.
Definition at line 178 of file lwir_capture.c.
◆ usage()
|
static |
Print the build version and command-line synopsis.
Lines for optional features are compiled in only when the matching build profile is enabled, so help never advertises unavailable options.
- Parameters
-
output stdout for --help, stderr after a usage error.
Definition at line 451 of file lwir_capture.c.
Variable Documentation
◆ capture_evidence
|
static |
Definition at line 154 of file lwir_capture.c.
◆ captured_device_state
|
static |
Definition at line 158 of file lwir_capture.c.
◆ captured_frame
|
static |
Definition at line 151 of file lwir_capture.c.
◆ captured_statistics
|
static |
Definition at line 157 of file lwir_capture.c.
◆ configured_corrections
|
static |
Definition at line 160 of file lwir_capture.c.
◆ configured_device
|
static |
Definition at line 161 of file lwir_capture.c.
◆ configured_gain
|
static |
Definition at line 160 of file lwir_capture.c.
◆ configured_serial
|
static |
Definition at line 160 of file lwir_capture.c.
◆ correction_profile
|
static |
Definition at line 156 of file lwir_capture.c.
◆ device_serial
|
static |
Definition at line 155 of file lwir_capture.c.
◆ device_state_text
|
static |
Definition at line 159 of file lwir_capture.c.
◆ interrupted
|
static |
Definition at line 153 of file lwir_capture.c.
◆ model_settings
|
static |
Definition at line 148 of file lwir_capture.c.