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_container.c
Go to the documentation of this file.
1/*
2 * Copyright 2026 OpenUAS
3 * SPDX-License-Identifier: Apache-2.0
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
18/** @file
19 * @brief Bounded thermal-marker reader; JPEG pixels are deliberately left alone.
20 *
21 * @details Walks JPEG marker segments from SOI up to the first SOS or EOI and
22 * reassembles the APP15 temperature plane written by lwir_image.c. Optionally
23 * parses the APP14 "LWIREV02" text for native geometry and identity. The
24 * walk uses one fixed 65534-byte segment buffer on the stack and copies
25 * samples straight into the caller's destination, so no heap or intermediate
26 * plane is needed.
27 *
28 * Defensive rules: regular files of at most 256 MiB only; every chunk is
29 * checked for signature, dimensions, offset continuity and capacity; and the
30 * file's identity, size and timestamps must be identical before and after the
31 * walk, so a file replaced or rewritten mid-read is rejected.
32 */
33#include "lwir_container.h"
34#include "lwir_frame.h"
35#include "exifite.h"
36#include "bounded_ini.h"
37
38#include <fcntl.h>
39#include <stdio.h>
40#include <string.h>
41#include <sys/stat.h>
42#include <unistd.h>
43
44/** @brief Decode a little-endian uint32 from four bytes.
45 * @param bytes At least four readable bytes.
46 * @return Decoded value, independent of host endianness.
47 */
48static uint32_t read_u32_le(const uint8_t *bytes)
49{
50 return (uint32_t)bytes[0] | ((uint32_t)bytes[1] << 8)
51 | ((uint32_t)bytes[2] << 16) | ((uint32_t)bytes[3] << 24);
52}
53
54/** @brief Accumulator for the INI callback over the APP14 provenance text. */
56 struct lwir_saved_geometry value; /**< Parsed values, copied out only on full success. */
57 unsigned seen; /**< Bit per key in geometry_field()'s name table; detects duplicates and completeness. */
58};
59
60/** @brief ini_parse() callback that extracts the eleven geometry keys.
61 * @param context struct geometry_fields accumulator.
62 * @param key Key from the LWIREV02 text.
63 * @param value Value text, NUL-terminated.
64 * @return False aborts the parse: duplicate key, malformed number, or a value
65 * out of range. Unrelated keys return true and are ignored, so newer writers
66 * can add fields without breaking older readers.
67 * @details Table index drives both validation and the @c seen bit. Ranges:
68 * width/height and flags at most 65535, rotation a multiple of 90 up to 270,
69 * mirror/flip/legend 0 or 1, source "camera" or "replay", boot_id non-empty
70 * and shorter than its buffer, frame_sha256 exactly 64 lowercase hex digits.
71 */
72static bool geometry_field(void *context, const char *key, const char *value)
73{
74 struct geometry_fields *fields = context;
75 const char *names[] = {"width", "height", "rotation_cw", "mirror", "flip", "legend",
76 "source", "sequence", "arrival_us", "boot_id", "frame_sha256"};
77 unsigned index = 0;
78 while (index < 11 && strcmp(key, names[index])) ++index;
79 if (index == 11) return true;
80 /* A repeated key could otherwise silently override an earlier value. */
81 if (fields->seen & (1U << index)) return false;
82 fields->seen |= 1U << index;
83 if (index == 6) {
84 fields->value.camera = !strcmp(value, "camera");
85 return fields->value.camera || !strcmp(value, "replay");
86 }
87 if (index >= 9) {
88 /* Bounded copy including the terminator; length was checked against the buffer. */
89 const size_t length = strlen(value);
90 char *output = index == 9 ? fields->value.boot_id : fields->value.frame_sha256;
91 const size_t limit = index == 9 ? sizeof(fields->value.boot_id) : sizeof(fields->value.frame_sha256);
92 if (!length || length >= limit || (index == 10 && (length != 64 || strspn(value, "0123456789abcdef") != 64))) return false;
93 for (size_t character = 0; character <= length; ++character) output[character] = value[character];
94 return true;
95 }
96 uint64_t number;
97 if (!ini_uint(value, &number)) return false;
98 if (index < 6 && number > 65535) return false;
99 if (index == 0) fields->value.width = (unsigned)number;
100 if (index == 1) fields->value.height = (unsigned)number;
101 if (index == 2) { if (number > 270 || number % 90) return false; fields->value.rotation = (unsigned)number; }
102 if (index >= 3 && index <= 5 && number > 1) return false;
103 if (index == 3) fields->value.mirror = number != 0;
104 if (index == 4) fields->value.flip = number != 0;
105 if (index == 5) fields->value.legend = number != 0;
106 if (index == 7) fields->value.sequence = number;
107 if (index == 8) fields->value.arrival_us = number;
108 return true;
109}
110
111/** @brief Walk JPEG markers, reassemble the APP15 plane and optionally check APP14.
112 * @param input Borrowed stream; rewound to the start, never closed here.
113 * @param destination Caller-owned sample storage; may be partially written on failure.
114 * @param capacity Writable bytes in destination.
115 * @param width Native width, written only on result 1.
116 * @param height Native height, written only on result 1.
117 * @param synthetic True for LWIRSIM1, written only on result 1.
118 * @param geometry Optional; when non-NULL, LWIREV02 evidence becomes mandatory
119 * and is cross-checked against the layer and the JPEG dimensions.
120 * @return 1 complete layer, 0 no layer (only possible with @p geometry NULL),
121 * -1 invalid input, inconsistency or I/O failure. errno is not normalized.
122 * @details Stops at SOS or EOI because the custom markers are always written
123 * before the scan; entropy-coded data is never inspected. APP15 segments
124 * with foreign signatures are skipped, since other software may also use
125 * APP15. A file stability check (device, inode, size, mtime, ctime) runs
126 * last, even after failures, and overrides any earlier success.
127 */
128static int read_temperature_stream(FILE *input, uint8_t *destination, size_t capacity,
129 unsigned *width, unsigned *height, bool *synthetic,
130 struct lwir_saved_geometry *geometry)
131{
132 if (!input || !destination || !width || !height || !synthetic) return -1;
133 struct stat before = {0}, after = {0};
134 /* 256 MiB bounds the walk; real LWIR photos are far smaller. */
135 bool valid = fstat(fileno(input), &before) == 0 && S_ISREG(before.st_mode)
136 && before.st_size >= 4 && before.st_size <= (off_t)(256U * 1024U * 1024U);
137 if (valid) valid = fseeko(input, 0, SEEK_SET) == 0;
138 uint32_t jpeg_width = 0, jpeg_height = 0;
139 unsigned components = 0;
140 /* Quarter-turn rotation swaps display axes, so either native maximum may be the display width. */
141 const unsigned display_limit = LWIR_MAX_WIDTH > LWIR_MAX_HEIGHT ? LWIR_MAX_WIDTH : LWIR_MAX_HEIGHT;
142 if (valid) valid = exif_jpeg_dimensions(input, &jpeg_width, &jpeg_height, &components) == 0
143 && jpeg_width <= display_limit && jpeg_height <= display_limit
144 && jpeg_width > 0 && jpeg_height > 0;
145 if (valid) valid = fseeko(input, 0, SEEK_SET) == 0;
146 uint8_t soi[2] = {0};
147 if (valid) valid = fread(soi, 1, sizeof(soi), input) == sizeof(soi) && soi[0] == 0xff && soi[1] == 0xd8;
148 /* Largest possible APPn payload: 16-bit length minus its own two bytes. */
149 uint8_t marker_payload[65534];
150 size_t expected = 0, copied = 0;
151 uint32_t layer_width = 0, layer_height = 0;
152 bool found_layer = false, layer_synthetic = false;
153 struct geometry_fields fields = {0};
154 bool found_geometry = false;
155 while (valid) {
156 int byte = fgetc(input);
157 if (byte != 0xff) { valid = false; break; }
158 /* Any number of 0xff fill bytes may precede a marker code. */
159 do { byte = fgetc(input); } while (byte == 0xff);
160 if (byte == EOF) { valid = false; break; }
161 const unsigned marker = (unsigned)byte;
162 /* Custom markers always precede the scan, so stop before entropy-coded data. */
163 if (marker == 0xda || marker == 0xd9) break;
164 /* TEM and RSTn are standalone markers without a length field. */
165 if (marker == 0x01 || (marker >= 0xd0 && marker <= 0xd7)) continue;
166 const int length_high = fgetc(input), length_low = fgetc(input);
167 if (length_high == EOF || length_low == EOF) { valid = false; break; }
168 const size_t segment_length = ((size_t)length_high << 8) | (size_t)length_low;
169 if (segment_length < 2 || segment_length - 2 > sizeof(marker_payload)) { valid = false; break; }
170 const size_t payload_size = segment_length - 2;
172 if (fread(marker_payload, 1, payload_size, input) != payload_size) { valid = false; break; }
173 if (payload_size < LWIR_THERMAL_SIGNATURE_BYTES) continue;
174 /* Other software may use APP15 too; only our two signatures are claimed. */
175 const bool is_synthetic = !memcmp(marker_payload, LWIR_THERMAL_SYNTHETIC_SIGNATURE, LWIR_THERMAL_SIGNATURE_BYTES);
176 const bool is_sensor = !memcmp(marker_payload, LWIR_THERMAL_SENSOR_SIGNATURE, LWIR_THERMAL_SIGNATURE_BYTES);
177 if (!is_synthetic && !is_sensor) continue;
178 /* A signed chunk without samples is malformed, not foreign. */
179 if (payload_size <= LWIR_THERMAL_HEADER_BYTES) { valid = false; break; }
180 const uint32_t marker_width = read_u32_le(marker_payload + LWIR_THERMAL_WIDTH_OFFSET);
181 const uint32_t marker_height = read_u32_le(marker_payload + LWIR_THERMAL_HEIGHT_OFFSET);
182 if (!found_layer) {
183 /* The first chunk fixes the layer geometry and the capacity requirement. */
184 if (!marker_width || !marker_height || marker_width > LWIR_MAX_WIDTH || marker_height > LWIR_MAX_HEIGHT) {
185 valid = false;
186 break;
187 }
188 layer_width = marker_width;
189 layer_height = marker_height;
190 expected = (size_t)layer_width * layer_height * 2;
191 if (expected > capacity) { valid = false; break; }
192 }
193 /* Later chunks must agree on size and kind, continue exactly at the
194 * bytes copied so far (no gaps, reordering or duplicates) and not
195 * overrun the plane; this also guarantees the destination copy fits. */
196 if (marker_width != layer_width || marker_height != layer_height
197 || read_u32_le(marker_payload + LWIR_THERMAL_DATA_OFFSET) != copied
198 || payload_size - LWIR_THERMAL_HEADER_BYTES > expected - copied
199 || (found_layer && layer_synthetic != is_synthetic)) { valid = false; break; }
200 found_layer = true;
201 layer_synthetic = is_synthetic;
202 for (size_t index = LWIR_THERMAL_HEADER_BYTES; index < payload_size; ++index)
203 destination[copied++] = marker_payload[index];
204 } else if (geometry && marker == 0xee) {
205 /* APP14 is also used by Adobe; only the LWIREV02 record is parsed, and only once. */
206 if (fread(marker_payload, 1, payload_size, input) != payload_size) { valid = false; break; }
207 if (payload_size >= 9 && !memcmp(marker_payload, "LWIREV02\n", 9)) {
208 if (found_geometry || !ini_parse((char *)marker_payload + 9, payload_size - 9, geometry_field, &fields)) {
209 valid = false; break;
210 }
211 found_geometry = true;
212 }
213 } else if (fseeko(input, (off_t)payload_size, SEEK_CUR) != 0) {
214 valid = false;
215 }
216 }
217 if (found_layer && copied != expected) valid = false;
218 /* 2047 = all eleven key bits. A camera source must pair with LWIRRAW1 and
219 * replay with LWIRSIM1; JPEG size must equal native size after rotation. */
220 if (geometry && (!found_geometry || fields.seen != 2047 || fields.value.width != layer_width
221 || fields.value.height != layer_height || fields.value.camera == layer_synthetic
222 || jpeg_width != (fields.value.rotation % 180 ? layer_height : layer_width)
223 || jpeg_height != (fields.value.rotation % 180 ? layer_width : layer_height))) valid = false;
224 /* Reject files rewritten or replaced during the walk, even if parsing looked fine. */
225 if (fstat(fileno(input), &after) != 0 || before.st_dev != after.st_dev || before.st_ino != after.st_ino
226 || before.st_size != after.st_size || before.st_mtim.tv_sec != after.st_mtim.tv_sec
227 || before.st_mtim.tv_nsec != after.st_mtim.tv_nsec || before.st_ctim.tv_sec != after.st_ctim.tv_sec
228 || before.st_ctim.tv_nsec != after.st_ctim.tv_nsec) valid = false;
229 if (!valid) return -1;
230 if (!found_layer) return 0;
231 *width = layer_width;
232 *height = layer_height;
233 *synthetic = layer_synthetic;
234 if (geometry) *geometry = fields.value;
235 return 1;
236}
237
238/** @brief Public stream reader without geometry; see lwir_container.h. */
239int lwir_read_temperature_stream(FILE *input, uint8_t *destination, size_t capacity,
240 unsigned *width, unsigned *height, bool *synthetic)
241{
242 return read_temperature_stream(input, destination, capacity, width, height, synthetic, NULL);
243}
244
245/** @brief Open @p filename safely and read layer plus geometry; see lwir_container.h.
246 * @details O_NOFOLLOW refuses a symlinked final component; O_NONBLOCK keeps
247 * a FIFO from blocking the open so the regular-file check can reject it.
248 * Results go through locals and are copied out only on success.
249 */
250int lwir_read_temperature_evidence(const char *filename, uint8_t *destination, size_t capacity,
251 struct lwir_saved_geometry *geometry)
252{
253 if (!filename || !geometry) return -1;
254 const int descriptor = open(filename, O_RDONLY | O_NONBLOCK | O_CLOEXEC | O_NOFOLLOW);
255 if (descriptor < 0) return -1;
256 FILE *input = fdopen(descriptor, "rb");
257 if (!input) { close(descriptor); return -1; }
258 unsigned width = 0, height = 0;
259 bool synthetic = false;
260 struct lwir_saved_geometry result = {0};
261 int status = read_temperature_stream(input, destination, capacity, &width, &height, &synthetic, &result);
262 /* A close failure invalidates an otherwise successful read. */
263 if (fclose(input)) status = -1;
264 if (status == 1) *geometry = result;
265 return status;
266}
267
268/** @brief Open @p filename safely and read the layer only; see lwir_container.h.
269 * @details Same open flags as lwir_read_temperature_evidence(). Outputs are
270 * written only when the result is 1 and the stream closed cleanly.
271 */
272int lwir_read_temperature_layer(const char *filename, uint8_t *destination, size_t capacity,
273 unsigned *width, unsigned *height, bool *synthetic)
274{
275 if (!filename || !destination || !width || !height || !synthetic) return -1;
276 const int descriptor = open(filename, O_RDONLY | O_NONBLOCK | O_CLOEXEC | O_NOFOLLOW);
277 if (descriptor < 0) return -1;
278 FILE *input = fdopen(descriptor, "rb");
279 if (!input) { close(descriptor); return -1; }
280 unsigned native_width = 0, native_height = 0;
281 bool native_synthetic = false;
282 const int result = lwir_read_temperature_stream(input, destination, capacity,
283 &native_width, &native_height, &native_synthetic);
284 if (fclose(input) != 0) return -1;
285 if (result == 1) { *width = native_width; *height = native_height; *synthetic = native_synthetic; }
286 return result;
287}
Allocation-free flat key=value mechanics; callers own schemas and storage.
static bool ini_uint(const char *text, uint64_t *number)
Parse digits-only uint64; overflow and signs are rejected.
Definition bounded_ini.h:52
static bool ini_parse(char *buffer, size_t length, ini_field_handler handler, void *context)
Destructively parse flat fields with blank lines and #/; comment lines.
static unsigned capacity[COVERAGE_CAMERAS]
uint8_t bytes[CHDK_CONTROL_REPLY_SIZE]
Definition chdk_pipe.c:144
int descriptor
Definition chdk_pipe.c:142
void(* close)(struct usbfs_handle *)
Definition chdkbridge.c:57
int(* open)(const struct usbfs_device *, struct usbfs_handle *)
Definition chdkbridge.c:56
Bounded C11 EXIF metadata and JPEG streaming interfaces.
int exif_jpeg_dimensions(FILE *input, uint32_t *width, uint32_t *height, unsigned *components)
Inspect the frame header without allocating or decoding image pixels.
Definition exifite.c:1309
int lwir_read_temperature_layer(const char *filename, uint8_t *destination, size_t capacity, unsigned *width, unsigned *height, bool *synthetic)
Open filename safely and read the layer only; see lwir_container.h.
static int read_temperature_stream(FILE *input, uint8_t *destination, size_t capacity, unsigned *width, unsigned *height, bool *synthetic, struct lwir_saved_geometry *geometry)
Walk JPEG markers, reassemble the APP15 plane and optionally check APP14.
int lwir_read_temperature_stream(FILE *input, uint8_t *destination, size_t capacity, unsigned *width, unsigned *height, bool *synthetic)
Public stream reader without geometry; see lwir_container.h.
int lwir_read_temperature_evidence(const char *filename, uint8_t *destination, size_t capacity, struct lwir_saved_geometry *geometry)
Open filename safely and read layer plus geometry; see lwir_container.h.
static bool geometry_field(void *context, const char *key, const char *value)
ini_parse() callback that extracts the eleven geometry keys.
static uint32_t read_u32_le(const uint8_t *bytes)
Decode a little-endian uint32 from four bytes.
Exact thermal evidence in JPEG containers, independent of analysis.
#define LWIR_THERMAL_SENSOR_SIGNATURE
Signature of a temperature plane read from the live camera.
#define LWIR_THERMAL_SYNTHETIC_SIGNATURE
Signature of a temperature plane produced by synthetic replay.
@ LWIR_THERMAL_HEADER_BYTES
@ LWIR_THERMAL_APP_MARKER
@ LWIR_THERMAL_DATA_OFFSET
@ LWIR_THERMAL_SIGNATURE_BYTES
@ LWIR_THERMAL_WIDTH_OFFSET
@ LWIR_THERMAL_HEIGHT_OFFSET
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
#define LWIR_MAX_HEIGHT
Largest supported native height in pixels.
Definition lwir_frame.h:49
uint8_t marker[LWIR_THERMAL_HEADER_BYTES+LWIR_THERMAL_CHUNK_CAPACITY]
Definition lwir_image.c:62
static FILE * output
Definition pose_log.c:77
Accumulator for the INI callback over the APP14 provenance text.
struct lwir_saved_geometry value
Native geometry and identity recovered from the APP14 "LWIREV02" text.
bool valid
Definition usher.c:537
struct usher_control_result result
Definition usher.c:377