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_image.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 LWIR JPEG encoder and durable no-overwrite file publisher.
20 *
21 * @details Implements lwir_image.h. Every photo goes through one static libjpeg
22 * workspace so no heap allocation is made per photo by this module (libjpeg
23 * still allocates internally). Consequently the encoder is single-threaded
24 * and not re-entrant.
25 *
26 * Marker order inside each JPEG, all before the first scanline:
27 * 1. APP14 "LWIREV02" provenance text (only with evidence).
28 * 2. APP1 EXIF with the sensor-capture tag (only with evidence, live frames).
29 * 3. APP15 thermal chunks (combined frames only).
30 * libjpeg may emit its own JFIF APP0 before these, so readers must scan
31 * markers rather than expect APP1 directly after SOI.
32 *
33 * Codec errors longjmp from jpeg_failure() back to encode_jpeg() with
34 * errno = EIO. Publication writes a temporary, fsyncs, link()s and fsyncs
35 * the directory; see publish().
36 */
37
38#include "lwir_image.h"
39#include "lwir_container.h"
40#include "exifite.h"
41#include "lwir_render.h"
42
43#include <errno.h>
44#include <fcntl.h>
45#include <limits.h>
46#include <setjmp.h>
47#include <stdio.h>
48#include <stdlib.h>
49#include <string.h>
50#include <unistd.h>
51
52#include <jpeglib.h>
53
54/** @brief Static encoder state shared by every photo.
55 * @details Static storage avoids per-photo heap use and keeps worst-case
56 * memory fixed. Shared state is why the encoder is not re-entrant.
57 */
58static struct {
59 struct jpeg_compress_struct encoder; /**< libjpeg compressor, zeroed and recreated per photo. */
60 struct jpeg_error_mgr error; /**< Standard error manager with error_exit redirected to jpeg_failure(). */
61 jmp_buf recovery; /**< Target of jpeg_failure(); armed in encode_jpeg(). */
62 uint8_t marker[LWIR_THERMAL_HEADER_BYTES + LWIR_THERMAL_CHUNK_CAPACITY]; /**< One APP15 chunk being assembled. */
63 uint8_t row[LWIR_MAX_WIDTH * 3U]; /**< One interleaved YCbCr display row; the renderer is given its capacity. */
64 struct exif_document exif; /**< EXIF builder for the sensor-capture tag. */
65 uint8_t exif_payload[EXIF_MAX_PAYLOAD]; /**< Serialized EXIF APP1 payload. */
66 char evidence[8192]; /**< APP14 text; well below the 65533-byte APPn limit, so one marker suffices. */
68
69/** @brief Store @p value as four little-endian bytes.
70 * @param destination At least four writable bytes.
71 * @param value Value to encode.
72 * @details Explicit byte order keeps the APP15 header independent of host endianness.
73 */
74static void write_u32(uint8_t *destination, uint32_t value)
75{
76 for (size_t index = 0; index < 4; ++index) destination[index] = (uint8_t)(value >> (index * 8));
77}
78
79/** @brief libjpeg error_exit replacement: abandon the photo instead of exiting.
80 * @param encoder Unused; the single static workspace already identifies the photo.
81 * @note Does not return; jumps to the recovery point armed by the encoder.
82 * @details The default handler calls exit(), which would kill the capture
83 * worker. errno is set to EIO before jumping so the caller sees an I/O-class
84 * failure regardless of the libjpeg message code.
85 */
86static void jpeg_failure(j_common_ptr encoder)
87{
88 (void)encoder;
89 errno = EIO;
90 longjmp(jpeg_workspace.recovery, 1);
91}
92
93/** @brief Write application provenance without taking ownership of the encoder.
94 * @param encoder Started compressor; markers must precede the first scanline.
95 * @param width Native frame width.
96 * @param height Native frame height.
97 * @param display_width Encoded width after orientation.
98 * @param display_height Encoded height after orientation.
99 * @param synthetic True for replayed/simulated frames.
100 * @param evidence Optional provenance; NULL writes no APP14 or EXIF at all.
101 * @param render Resolved display policy (never NULL here).
102 * @param range Window and clipping counts from lwir_render_prepare().
103 * @return Zero on success, otherwise the errno value the encoder owner must publish:
104 * ENOSPC when the text exceeds the fixed evidence buffer, EINVAL when the
105 * sensor-capture record cannot be encoded or serialized.
106 * @details Teardown stays with the owner so marker failures retain cleanup/error ordering.
107 * Builds the APP14 text in several bounded snprintf steps; each step checks
108 * truncation so a partial key=value record is never emitted.
109 * @warning jpeg_write_marker() can still longjmp on codec failure; that unwinds
110 * straight to encode_jpeg() and bypasses this function's return value.
111 */
112static int write_provenance_markers(j_compress_ptr encoder, unsigned width, unsigned height,
113 unsigned display_width, unsigned display_height, bool synthetic,
114 const struct lwir_evidence *evidence, const struct lwir_render_options *render,
115 const struct lwir_render_range *range)
116{
117 if (evidence != NULL) {
118 /* Unavailable facts are written as "unknown"/"unverified" rather than omitted,
119 * so a reader never mistakes absence for a default or a measured value. */
120 const int length = snprintf(jpeg_workspace.evidence, sizeof(jpeg_workspace.evidence),
121 "LWIREV02\nsource=%s\nserial=%s\ngain=%s\nfirmware=unknown\nffc=unknown\nenvironment=unknown\nlens_focus=unknown\npower_on_age=unknown\nboot_id=%s\n"
122 "sequence=%llu\nrequest_us=%llu\narrival_us=%llu\nrequest_id=%llu\nexposure=unknown\ncalibration=unverified\n"
123 "width=%u\nheight=%u\nframe_sha256=%s\nraw_file=%s\nrendering=%s\n"
124 "display_width=%u\ndisplay_height=%u\nrotation_cw=%u\nmirror=%u\nflip=%u\nraw_coordinates=native\norientation_order=rotate_mirror_flip\n"
125 "view=%u\npalette=%u\nlegend=%u\nwindow_low_kelvin64=%d\nwindow_high_kelvin64=%d\nclipped_low=%zu\nclipped_high=%zu\ninvalid_codes=%zu\n"
126 "profile_sha256=%s\nscale_ppm=%u\noffset_mk=%d\nsupport_min_raw=%u\nsupport_max_raw=%u\nbad_pixel_count=%u\ndenoise_kelvin64=%u\ngain_source=user_or_unknown\n",
127 synthetic ? "replay" : "camera", evidence->serial ? evidence->serial : "unknown",
128 evidence->gain ? evidence->gain : "unknown", evidence->capture.boot_id,
129 (unsigned long long)evidence->capture.sequence, (unsigned long long)evidence->request_us,
130 (unsigned long long)evidence->arrival_us, (unsigned long long)evidence->request_id, width, height, evidence->frame_sha256,
131 evidence->raw_path ? evidence->raw_path : "none", evidence->rendering ? evidence->rendering : "sensor",
132 display_width, display_height, render->rotation, render->mirror ? 1U : 0U, render->flip ? 1U : 0U,
133 (unsigned)render->view, (unsigned)render->palette, render->legend ? 1U : 0U, range->low, range->high, range->below, range->above, range->invalid,
134 render->profile ? render->profile->sha256 : "none", render->profile ? render->profile->scale_ppm : 1000000U,
135 render->profile ? render->profile->offset_mk : 0, render->profile ? render->profile->range_min : 1U,
136 render->profile ? render->profile->range_max : 65534U, render->profile ? render->profile->bad_count : 0U, render->denoise_raw);
137 if (length < 0 || (size_t)length >= sizeof(jpeg_workspace.evidence)) {
138 return ENOSPC;
139 }
140 size_t evidence_length = (size_t)length;
141 /* Mirrors the encoder's mapping of quality 0 to the legacy fixed 100. */
142 const int quality_length = snprintf(jpeg_workspace.evidence + evidence_length, sizeof(jpeg_workspace.evidence) - evidence_length,
143 "jpeg_quality=%u\njpeg_sampling=444\n", render->jpeg_quality ? render->jpeg_quality : 100U);
144 if (quality_length < 0 || (size_t)quality_length >= sizeof(jpeg_workspace.evidence) - evidence_length) return ENOSPC;
145 evidence_length += (size_t)quality_length;
146 /* Kernel buffer time is kept as evidence only; it is not proven to mark exposure. */
147 const int timestamp_length = snprintf(jpeg_workspace.evidence + evidence_length, sizeof(jpeg_workspace.evidence) - evidence_length,
148 "kernel_monotonic_us=%llu\nkernel_timestamp_flags=%u\nkernel_timestamp_is_qualified_exposure=false\n",
149 (unsigned long long)evidence->kernel_monotonic_us, evidence->kernel_timestamp_flags);
150 if (timestamp_length < 0 || (size_t)timestamp_length >= sizeof(jpeg_workspace.evidence) - evidence_length) return ENOSPC;
151 evidence_length += (size_t)timestamp_length;
152 if (evidence->measurement && evidence->statistics) {
153 const struct lwir_measurement *measurement = evidence->measurement;
154 const struct lwir_temperature_stats *statistics = evidence->statistics;
155 const struct lwir_thresholds *thresholds = evidence->thresholds;
156 /* A point reports a 1x1 ROI; a zero ROI width means the whole frame.
157 * Gotcha: the reported height is also selected by roi.width, not roi.height. */
158 const int added = snprintf(jpeg_workspace.evidence + evidence_length, sizeof(jpeg_workspace.evidence) - evidence_length,
159 "measurement=%s\nmeasurement_coordinates=native\nmeasurement_roi=%u,%u,%u,%u\nmeasurement_line_end=%u,%u\naverage_3x3=%u\n"
160 "measurement_pixels=%zu\nmeasurement_endpoint_codes=%zu\nmeasurement_min_raw=%u\nmeasurement_min_xy=%u,%u\n"
161 "measurement_max_raw=%u\nmeasurement_max_xy=%u,%u\nmeasurement_sum_raw=%llu\nmeasurement_sum_squared_raw=%llu\n"
162 "coverage_enabled=%u\ncoverage_source=original_centers\ncoverage_low_kelvin64=%u\ncoverage_high_kelvin64=%u\n"
163 "coverage_below=%zu\ncoverage_within=%zu\ncoverage_above=%zu\nwarn_percent=%u\n",
164 measurement->kind == LWIR_POINT ? "point" : measurement->kind == LWIR_LINE ? "line" : "roi",
165 measurement->roi.x, measurement->roi.y, measurement->kind == LWIR_POINT ? 1U : measurement->roi.width ? measurement->roi.width : width,
166 measurement->kind == LWIR_POINT ? 1U : measurement->roi.width ? measurement->roi.height : height,
167 measurement->end_x, measurement->end_y, measurement->average_3x3 ? 1U : 0U, statistics->pixels, statistics->endpoint_codes,
168 statistics->min_raw, statistics->min_x, statistics->min_y, statistics->max_raw, statistics->max_x, statistics->max_y,
169 (unsigned long long)statistics->sum_raw, (unsigned long long)statistics->sum_squared_raw,
170 thresholds && thresholds->enabled ? 1U : 0U, thresholds ? thresholds->low : 0U, thresholds ? thresholds->high : 0U,
171 statistics->below, statistics->within, statistics->above, evidence->warn_percent);
172 if (added < 0 || (size_t)added >= sizeof(jpeg_workspace.evidence) - evidence_length) {
173 return ENOSPC;
174 }
175 evidence_length += (size_t)added;
176 }
177 if (evidence->layout == LWIR_YUYV_IMAGE) {
178 /* Tells readers why no APP15 layer exists, instead of leaving it to guesswork. */
179 const int added = snprintf(jpeg_workspace.evidence + evidence_length, sizeof(jpeg_workspace.evidence) - evidence_length,
180 "device=tdk_5474_5411\nframe_layout=yuyv_image\ntemperature_data=unavailable\nyuv_range=limited\n");
181 if (added < 0 || (size_t)added >= sizeof(jpeg_workspace.evidence) - evidence_length) return ENOSPC;
182 evidence_length += (size_t)added;
183 }
184 /* Synthetic output passes NULL so replayed files never carry live device state.
185 * A zero length means the state text did not fit the remaining buffer. */
186 const size_t state_length = lwir_state_format(synthetic ? NULL : evidence->device_state,
187 jpeg_workspace.evidence + evidence_length, sizeof(jpeg_workspace.evidence) - evidence_length);
188 if (!state_length) return ENOSPC;
189 evidence_length += state_length;
190 jpeg_write_marker(encoder, JPEG_APP0 + 14, (const JOCTET *)jpeg_workspace.evidence, (unsigned)evidence_length);
191 /* Only live frames get the sensor-capture tag, so replays cannot pose as timed exposures. */
192 if (!synthetic) {
196 size_t size = 0;
198 exif_serialize(&jpeg_workspace.exif, jpeg_workspace.exif_payload,
199 sizeof(jpeg_workspace.exif_payload), &size) != 0) {
200 return EINVAL;
201 }
202 jpeg_write_marker(encoder, JPEG_APP0 + 1, jpeg_workspace.exif_payload, (unsigned)size);
203 }
204 }
205 return 0;
206}
207
208/** @brief Preserve exact native temperatures independently of display rendering.
209 * @param encoder Started compressor; called before the first scanline.
210 * @param frame Combined frame; the temperature plane starts after the YUYV plane.
211 * @param width Native width.
212 * @param height Native height.
213 * @param synthetic Selects the LWIRSIM1 instead of the LWIRRAW1 signature.
214 * @details Splits the width*height*2-byte plane into APP15 chunks of at most
215 * LWIR_THERMAL_CHUNK_CAPACITY bytes, each with the full header. Offsets are
216 * relative to the plane start and strictly sequential, which the reader
217 * enforces. Bytes are copied verbatim, so JPEG quality never touches them.
218 * Codec failures longjmp to encode_jpeg().
219 */
220static void write_thermal_markers(j_compress_ptr encoder, const uint8_t *frame,
221 unsigned width, unsigned height, bool synthetic)
222{
223 const size_t plane_bytes = (size_t)width * height * 2;
224 /* The temperature plane follows the equally sized YUYV plane in the combined frame. */
225 const char *signature = synthetic ? LWIR_THERMAL_SYNTHETIC_SIGNATURE : LWIR_THERMAL_SENSOR_SIGNATURE;
226 for (size_t offset = 0; offset < plane_bytes;) {
227 const size_t remaining = plane_bytes - offset;
228 const size_t chunk = remaining < LWIR_THERMAL_CHUNK_CAPACITY ? remaining : LWIR_THERMAL_CHUNK_CAPACITY;
229 for (size_t index = 0; index < LWIR_THERMAL_SIGNATURE_BYTES; ++index) jpeg_workspace.marker[index] = (uint8_t)signature[index];
232 write_u32(jpeg_workspace.marker + LWIR_THERMAL_DATA_OFFSET, (uint32_t)offset);
233 for (size_t index = 0; index < chunk; ++index) {
234 jpeg_workspace.marker[LWIR_THERMAL_HEADER_BYTES + index] = frame[plane_bytes + offset + index];
235 }
236 jpeg_write_marker(encoder, LWIR_THERMAL_APP_MARKER, jpeg_workspace.marker,
237 (unsigned)(LWIR_THERMAL_HEADER_BYTES + chunk));
238 offset += chunk;
239 }
240}
241
242/** @brief Expand one limited-range video component to full range.
243 * @param value Component sample from the limited-range source.
244 * @param low Lowest legal code (16 for luma).
245 * @param span Legal code span: 219 for luma (16..235), 224 for chroma (16..240).
246 * @return Full-range 0..255 component.
247 * @details JPEG/JFIF assumes full-range YCbCr, so passing TDK video through
248 * unchanged would look washed out. Out-of-range inputs clamp. Chroma scales
249 * symmetrically around the neutral 128 and truncates toward zero; luma rounds.
250 * @note The chroma branch is selected by span == 224 and ignores @p low,
251 * implicitly assuming low == 16.
252 */
253static uint8_t expand_video_component(uint8_t value, unsigned low, unsigned span)
254{
255 if (value <= low) return 0;
256 if (value >= low + span) return 255;
257 if (span == 224) return (uint8_t)(128 + ((int)value - 128) * 255 / 224);
258 return (uint8_t)((((unsigned)value - low) * 255U + span / 2U) / span);
259}
260
261/** @brief Own the serial codec lifecycle and the ordered marker/scanline stages.
262 * @param output Caller-owned stream; flush/sync/close remain with the caller.
263 * @param frame Frame already size-checked by lwir_encode_jpeg().
264 * @param bytes Exact frame size.
265 * @param width Native width.
266 * @param height Native height.
267 * @param synthetic True for replayed/simulated frames.
268 * @param evidence Optional provenance; required for any display orientation.
269 * @param render Display policy (never NULL here).
270 * @return True when the full JPEG was handed to the stream. On false, errno is
271 * EINVAL, ENOTSUP, ENOSPC, EIO, or the renderer's errno; discard the output.
272 * @details Validates the image-only and orientation rules before touching the
273 * codec, writes markers, then renders and compresses one row at a time so the
274 * only image buffer is the single-row workspace.
275 */
276static bool encode_jpeg(FILE *output, const uint8_t *frame, size_t bytes, unsigned width, unsigned height,
277 bool synthetic, const struct lwir_evidence *evidence, const struct lwir_render_options *render)
278{
279 if (!render || render->jpeg_quality > 100) { errno = EINVAL; return false; }
281 unsigned display_width, display_height;
282 /* volatile and never modified: stays well defined when read after the setjmp below. */
283 const volatile bool image_only = evidence && evidence->layout == LWIR_YUYV_IMAGE;
284 /* Image-only frames have no temperature plane, so anything thermal is unsupported. */
285 if (image_only && (synthetic || render->view != LWIR_SENSOR || render->legend || render->profile || render->denoise_raw ||
286 render->palette != LWIR_WHITE_HOT || evidence->statistics || evidence->device_state || evidence->raw_path)) {
287 errno = ENOTSUP;
288 return false;
289 }
290 /* Oriented display pixels require native/display provenance; never publish an ambiguous mapping. */
291 if (!evidence && (render->rotation || render->mirror || render->flip)) { errno = EINVAL; return false; }
292 if (!lwir_render_dimensions(width, height, render, &display_width, &display_height) ||
293 !lwir_render_prepare(frame, bytes, width, height, render, &range)) return false;
294 struct jpeg_compress_struct *encoder = &jpeg_workspace.encoder;
295 /* Zeroing first makes jpeg_destroy_compress() safe even if a failure jumps
296 * back before jpeg_create_compress() finished. */
297 *encoder = (struct jpeg_compress_struct){0};
298 encoder->err = jpeg_std_error(&jpeg_workspace.error);
299 jpeg_workspace.error.error_exit = jpeg_failure;
300 /* Codec failures land here with errno = EIO. Only state not modified after
301 * this point (the encoder pointer) or declared volatile may be relied on. */
302 if (setjmp(jpeg_workspace.recovery) != 0) {
303 jpeg_destroy_compress(encoder);
304 return false;
305 }
306 jpeg_create_compress(encoder);
307 jpeg_stdio_dest(encoder, output);
308 encoder->image_width = display_width;
309 encoder->image_height = display_height;
310 encoder->input_components = 3;
311 /* The renderer already emits YCbCr rows, so libjpeg skips any RGB conversion pass. */
312 encoder->in_color_space = JCS_YCbCr;
313 jpeg_set_defaults(encoder);
314 /* force_baseline keeps quantization tables 8-bit; quality 0 means legacy 100. */
315 jpeg_set_quality(encoder, render->jpeg_quality ? (int)render->jpeg_quality : 100, TRUE);
316 /* Standard Huffman tables avoid an extra statistics pass, trading slightly larger files for speed. */
317 encoder->optimize_coding = FALSE;
318 /* Force 4:4:4: chroma subsampling would smear one- or two-pixel thermal edges. */
319 for (size_t component = 0; component < 3; ++component) {
320 encoder->comp_info[component].h_samp_factor = 1;
321 encoder->comp_info[component].v_samp_factor = 1;
322 }
323 jpeg_start_compress(encoder, TRUE);
324 /* All markers must be written after start and before the first scanline. */
325 const int provenance_error = write_provenance_markers(encoder, width, height, display_width, display_height,
326 synthetic, evidence, render, &range);
327 if (provenance_error != 0) {
328 /* Not a codec error, so no longjmp happened: tear down here and keep the specific errno. */
329 jpeg_destroy_compress(encoder);
330 errno = provenance_error;
331 return false;
332 }
333 if (!image_only) write_thermal_markers(encoder, frame, width, height, synthetic);
334 while (encoder->next_scanline < encoder->image_height) {
335 if (!lwir_render_row(frame, bytes, width, height, encoder->next_scanline,
336 render, &range, jpeg_workspace.row, sizeof(jpeg_workspace.row))) {
337 jpeg_destroy_compress(encoder); return false;
338 }
339 if (image_only) {
340 /* TDK video is limited range (Y 16..235, Cb/Cr 16..240); JPEG expects full range. */
341 for (size_t column = 0; column < display_width; ++column) {
342 jpeg_workspace.row[column * 3] = expand_video_component(jpeg_workspace.row[column * 3], 16, 219);
343 for (size_t component = 1; component < 3; ++component)
344 jpeg_workspace.row[column * 3 + component] = expand_video_component(jpeg_workspace.row[column * 3 + component], 16, 224);
345 }
346 }
347 JSAMPROW row = jpeg_workspace.row;
348 /* Defensive: a short write is treated as I/O failure rather than retried. */
349 if (jpeg_write_scanlines(encoder, &row, 1) != 1) {
350 jpeg_destroy_compress(encoder);
351 errno = EIO;
352 return false;
353 }
354 }
355 /* Write errors while flushing the codec also longjmp to the recovery point. */
356 jpeg_finish_compress(encoder);
357 jpeg_destroy_compress(encoder);
358 return true;
359}
360
361/** @brief Open the directory that will contain @p path, for fsync after linking.
362 * @param path Destination path; a name without '/' resolves to ".", "/name" to "/".
363 * @return Read-only directory descriptor (close-on-exec), or -1 with errno set;
364 * ENAMETOOLONG when the directory part exceeds PATH_MAX.
365 * @details Copies the directory part with a bounded loop instead of memcpy.
366 */
367static int open_parent(const char *path)
368{
369 char directory[PATH_MAX];
370 const char *separator = strrchr(path, '/');
371 const size_t length = separator ? (size_t)(separator - path) : 1;
372 if (length >= sizeof(directory)) { errno = ENAMETOOLONG; return -1; }
373 if (!separator) { directory[0] = '.'; directory[1] = '\0'; }
374 else if (length == 0) { directory[0] = '/'; directory[1] = '\0'; }
375 else { for (size_t index = 0; index < length; ++index) directory[index] = path[index]; directory[length] = '\0'; }
376 return open(directory, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
377}
378
379/** @brief Report the bundled codec; see lwir_image.h. */
380const char *lwir_jpeg_provider(void)
381{
382 return "ijg-9f";
383}
384
385/** @brief Validate the frame size for its layout, then encode; see lwir_image.h.
386 * @details Image-only frames are half the combined size. Layout values beyond
387 * the known enum are rejected rather than guessed. A NULL render becomes the
388 * plain sensor view with quality 0, i.e. legacy 100.
389 */
390bool lwir_encode_jpeg(FILE *output, const uint8_t *frame, size_t bytes, unsigned width, unsigned height,
391 bool synthetic, const struct lwir_evidence *evidence, const struct lwir_render_options *render)
392{
393 const size_t expected = lwir_frame_bytes(width, height) / (evidence && evidence->layout == LWIR_YUYV_IMAGE ? 2U : 1U);
394 if (!output || !frame || !expected || bytes != expected || (evidence && evidence->layout > LWIR_YUYV_IMAGE)) {
395 errno = EINVAL; return false;
396 }
397 const struct lwir_render_options sensor = {.view = LWIR_SENSOR};
398 return encode_jpeg(output, frame, bytes, width, height, synthetic, evidence, render ? render : &sensor);
399}
400
401/** @brief Durably publish a JPEG or raw companion under a new name.
402 * @param path Final destination; must not exist.
403 * @param frame Frame to encode or copy.
404 * @param bytes Exact frame size (half size for image-only JPEG output).
405 * @param width Native width.
406 * @param height Native height.
407 * @param synthetic True for replayed/simulated frames (JPEG only).
408 * @param raw True writes @p frame verbatim instead of encoding a JPEG.
409 * @param evidence Optional provenance (JPEG only).
410 * @param render Optional display policy (JPEG only).
411 * @return True when the file is complete, named and the directory synced.
412 * On false, errno holds the first failure (later cleanup does not overwrite it)
413 * and @p path does not exist: a name this call already linked is removed again.
414 * @details Sequence: mkstemp "PATH.part.XXXXXX" -> write -> fflush + fsync ->
415 * link() to @p path -> fsync directory -> unlink temporary -> fsync directory.
416 * link() fails with EEXIST instead of replacing an existing file (unlike
417 * rename()), so publication is atomic and never overwrites. The temporary is
418 * removed on every path. Because link() refuses existing names, a name removed
419 * on rollback is always one this call created, never someone else's file.
420 * @note mkstemp creates the file owner-only (0600); the linked name keeps that mode.
421 */
422static bool publish(const char *path, const uint8_t *frame, size_t bytes,
423 unsigned width, unsigned height, bool synthetic, bool raw,
424 const struct lwir_evidence *evidence, const struct lwir_render_options *render)
425{
426 const size_t expected = lwir_frame_bytes(width, height) / (!raw && evidence && evidence->layout == LWIR_YUYV_IMAGE ? 2U : 1U);
427 if (path == NULL || path[0] == '\0' || !frame || !expected || bytes != expected) {
428 errno = EINVAL;
429 return false;
430 }
431 char temporary[PATH_MAX];
432 const int length = snprintf(temporary, sizeof(temporary), "%s.part.XXXXXX", path);
433 if (length < 0 || (size_t)length >= sizeof(temporary)) {
434 errno = ENAMETOOLONG;
435 return false;
436 }
437 /* Sibling of the destination: same filesystem, so link() cannot fail with EXDEV. */
438 const int descriptor = mkstemp(temporary);
439 if (descriptor < 0) return false;
440 /* Open the directory before writing anything, so this failure costs no I/O. */
441 const int directory = open_parent(path);
442 if (directory < 0) { const int saved_errno = errno; close(descriptor); unlink(temporary); errno = saved_errno; return false; }
443 FILE *output = fdopen(descriptor, "wb");
444 if (output == NULL) {
445 const int saved_errno = errno;
447 close(directory);
448 unlink(temporary);
449 errno = saved_errno;
450 return false;
451 }
452 bool success = raw ? fwrite(frame, 1, bytes, output) == bytes :
453 lwir_encode_jpeg(output, frame, bytes, width, height, synthetic, evidence, render);
454 /* Data must be durable before the name becomes visible. */
455 if (success && fflush(output) != 0) success = false;
456 if (success && fsync(descriptor) != 0) success = false;
457 /* Capture the first failure now; later cleanup calls may overwrite errno. */
458 int saved_errno = errno;
459 if (fclose(output) != 0 && success) {
460 success = false;
461 saved_errno = errno;
462 }
463 /* No-overwrite atomic visibility: link() refuses an existing destination. */
464 bool linked = false;
465 if (success && link(temporary, path) != 0) {
466 success = false;
467 saved_errno = errno;
468 } else if (success) {
469 linked = true;
470 }
471 /* Persist the new directory entry before reporting success. */
472 if (success && fsync(directory) != 0) { success = false; saved_errno = errno; }
473 /* The final name already holds the complete file, so a leftover temporary is
474 * only a warning. */
475 if (unlink(temporary) != 0 && success) {
476 fprintf(stderr, "LWIR: published %s, but could not remove %s: %s\n", path, temporary, strerror(errno));
477 }
478 /* Second sync persists removal of the temporary entry. */
479 if (success && fsync(directory) != 0) { success = false; saved_errno = errno; }
480 /* A failure report must not leave an unconfirmed file under the final name. */
481 if (!success && linked && unlink(path) == 0) fsync(directory);
482 if (close(directory) != 0 && success) { success = false; saved_errno = errno; unlink(path); }
483 errno = saved_errno;
484 return success;
485}
486
487/** @brief Remove a file this process published and persist the removal; see lwir_image.h. */
488bool lwir_remove_published(const char *path)
489{
490 if (!path || !path[0]) { errno = EINVAL; return false; }
491 const int directory = open_parent(path);
492 if (directory < 0) return false;
493 bool success = unlink(path) == 0 && fsync(directory) == 0;
494 const int saved_errno = errno;
495 if (close(directory) != 0) success = false;
496 errno = saved_errno;
497 return success;
498}
499
500/** @brief Publish the sensor view without evidence; see lwir_image.h. */
501bool lwir_write_jpeg(const char *path, const uint8_t *frame, size_t bytes,
502 unsigned width, unsigned height, bool synthetic)
503{
504 return publish(path, frame, bytes, width, height, synthetic, false, NULL, NULL);
505}
506
507/** @brief Publish the sensor view with provenance; see lwir_image.h. */
508bool lwir_write_jpeg_evidence(const char *path, const uint8_t *frame, size_t bytes,
509 unsigned width, unsigned height, bool synthetic,
510 const struct lwir_evidence *evidence)
511{
512 return publish(path, frame, bytes, width, height, synthetic, false, evidence, NULL);
513}
514
515/** @brief Publish the combined frame verbatim; see lwir_image.h. */
516bool lwir_write_raw(const char *path, const uint8_t *frame, size_t bytes, unsigned width, unsigned height)
517{
518 return publish(path, frame, bytes, width, height, false, true, NULL, NULL);
519}
520
521/** @brief Publish a rendered view with provenance; see lwir_image.h. */
522bool lwir_write_jpeg_rendered(const char *path, const uint8_t *frame, size_t bytes,
523 unsigned width, unsigned height, bool synthetic,
524 const struct lwir_evidence *evidence, const struct lwir_render_options *render)
525{
526 return publish(path, frame, bytes, width, height, synthetic, false, evidence, render);
527}
size_t size
Definition chdk_pipe.c:143
uint8_t bytes[CHDK_CONTROL_REPLY_SIZE]
Definition chdk_pipe.c:144
int descriptor
Definition chdk_pipe.c:142
void(* close)(struct usbfs_handle *)
Definition chdkbridge.c:57
static bool capture(struct transport *transport, FILE *file, const struct capture_settings *settings)
Capture to the camera's SD card and download the resulting JPEG.
int(* open)(const struct usbfs_device *, struct usbfs_handle *)
Definition chdkbridge.c:56
struct latest_measurement measurement
static bool range(size_t total, size_t offset, size_t length)
Check a byte span without forming a potentially overflowing end offset.
Definition exifite.c:133
Bounded C11 EXIF metadata and JPEG streaming interfaces.
int exif_serialize(const struct exif_document *document, unsigned char *payload, size_t capacity, size_t *size)
Serialize a document into one complete EXIF APP1 payload.
Definition exifite.c:736
void exif_document_init(struct exif_document *document)
Start a fresh upright sRGB/Y-Cb-Cr document with EXIF 2.32 defaults.
Definition exifite.c:412
unsigned char * exif_document_reserve(struct exif_document *document, enum exif_directory directory, uint16_t tag, enum exif_format format, uint32_t count)
Create or replace a field with zeroed, bounded value storage.
Definition exifite.c:508
#define EXIF_MAX_PAYLOAD
APP1 payload ceiling: the JPEG length includes its own two bytes.
Definition exifite.h:51
@ EXIF_UNDEFINED
Definition exifite.h:70
@ EXIF_CAMERA
Definition exifite.h:59
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_CHUNK_CAPACITY
@ LWIR_THERMAL_HEIGHT_OFFSET
size_t lwir_frame_bytes(unsigned width, unsigned height)
Combined frame size for supported geometry.
Definition lwir_frame.c:56
#define LWIR_MAX_WIDTH
Largest supported native width in pixels.
Definition lwir_frame.h:47
@ LWIR_POINT
Definition lwir_frame.h:71
@ LWIR_LINE
Definition lwir_frame.h:72
@ LWIR_YUYV_IMAGE
Definition lwir_frame.h:54
char evidence[8192]
Definition lwir_image.c:66
static void write_thermal_markers(j_compress_ptr encoder, const uint8_t *frame, unsigned width, unsigned height, bool synthetic)
Preserve exact native temperatures independently of display rendering.
Definition lwir_image.c:220
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
static bool publish(const char *path, const uint8_t *frame, size_t bytes, unsigned width, unsigned height, bool synthetic, bool raw, const struct lwir_evidence *evidence, const struct lwir_render_options *render)
Durably publish a JPEG or raw companion under a new name.
Definition lwir_image.c:422
bool lwir_write_jpeg(const char *path, const uint8_t *frame, size_t bytes, unsigned width, unsigned height, bool synthetic)
Publish the sensor view without evidence; see lwir_image.h.
Definition lwir_image.c:501
struct exif_document exif
Definition lwir_image.c:64
static int open_parent(const char *path)
Open the directory that will contain path, for fsync after linking.
Definition lwir_image.c:367
struct jpeg_compress_struct encoder
Definition lwir_image.c:59
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
uint8_t marker[LWIR_THERMAL_HEADER_BYTES+LWIR_THERMAL_CHUNK_CAPACITY]
Definition lwir_image.c:62
static struct @376007165063146230013315373164007004315140235344 jpeg_workspace
Static encoder state shared by every photo.
static void write_u32(uint8_t *destination, uint32_t value)
Store value as four little-endian bytes.
Definition lwir_image.c:74
uint8_t row[LWIR_MAX_WIDTH *3U]
Definition lwir_image.c:63
static int write_provenance_markers(j_compress_ptr encoder, unsigned width, unsigned height, unsigned display_width, unsigned display_height, bool synthetic, const struct lwir_evidence *evidence, const struct lwir_render_options *render, const struct lwir_render_range *range)
Write application provenance without taking ownership of the encoder.
Definition lwir_image.c:112
static uint8_t expand_video_component(uint8_t value, unsigned low, unsigned span)
Expand one limited-range video component to full range.
Definition lwir_image.c:253
static bool encode_jpeg(FILE *output, const uint8_t *frame, size_t bytes, unsigned width, unsigned height, bool synthetic, const struct lwir_evidence *evidence, const struct lwir_render_options *render)
Own the serial codec lifecycle and the ordered marker/scanline stages.
Definition lwir_image.c:276
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
bool lwir_write_jpeg_evidence(const char *path, const uint8_t *frame, size_t bytes, unsigned width, unsigned height, bool synthetic, const struct lwir_evidence *evidence)
Publish the sensor view with provenance; see lwir_image.h.
Definition lwir_image.c:508
jmp_buf recovery
Definition lwir_image.c:61
static void jpeg_failure(j_common_ptr encoder)
libjpeg error_exit replacement: abandon the photo instead of exiting.
Definition lwir_image.c:86
const char * lwir_jpeg_provider(void)
Report the bundled codec; see lwir_image.h.
Definition lwir_image.c:380
uint8_t exif_payload[EXIF_MAX_PAYLOAD]
Definition lwir_image.c:65
bool lwir_encode_jpeg(FILE *output, const uint8_t *frame, size_t bytes, unsigned width, unsigned height, bool synthetic, const struct lwir_evidence *evidence, const struct lwir_render_options *render)
Validate the frame size for its layout, then encode; see lwir_image.h.
Definition lwir_image.c:390
struct jpeg_error_mgr error
Definition lwir_image.c:60
JPEG encoding and durable no-overwrite publication of LWIR frames.
uint8_t frame[LWIR_MAX_FRAME_BYTES]
Definition lwir_mock.c:58
bool lwir_render_dimensions(unsigned width, unsigned height, const struct lwir_render_options *options, unsigned *display_width, unsigned *display_height)
Display size after orientation.
bool lwir_render_prepare(const uint8_t *frame, size_t bytes, unsigned width, unsigned height, const struct lwir_render_options *options, struct lwir_render_range *range)
Validate a render request and resolve its display window and counts.
bool lwir_render_row(const uint8_t *frame, size_t bytes, unsigned width, unsigned height, unsigned row, const struct lwir_render_options *options, const struct lwir_render_range *range, uint8_t *output, size_t capacity)
Render one oriented display row as interleaved Y/Cb/Cr.
Display rendering of Tiny1-C frames into JPEG-ready Y/Cb/Cr scanlines.
@ LWIR_WHITE_HOT
Definition lwir_render.h:58
@ LWIR_SENSOR
Definition lwir_render.h:52
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
#define PATH_MAX
Definition path_utils.h:39
static FILE * output
Definition pose_log.c:77
#define SENSOR_CAPTURE_BYTES
static bool sensor_capture_encode(const struct sensor_capture *record, unsigned char *data, size_t capacity)
Encode a SENSOR02 record in the fixed on-disk layout.
#define SENSOR_CAPTURE_TAG
Caller-owned bounded writer with no heap allocation.
Definition exifite.h:156
Borrowed provenance for one publication; strings must outlive encoding.
Definition lwir_image.h:63
One native-coordinate measurement request.
Definition lwir_frame.h:76
Display policy for one rendering request; never affects stored samples.
Resolved display window and diagnostic counts from lwir_render_prepare().
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
uint16_t high
Definition lwir_frame.h:92