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_mock.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_mock.c
20 * @brief Development replay: convert an ordinary JPEG into LWIR evidence (LWIR_ENABLE_MOCK).
21 * @details Two modes:
22 * - layer only: keep the source's compressed bytes and insert LWIRSIM1 APP15
23 * temperature chunks derived from luminance;
24 * - full: decode, build a combined image+temperature frame, re-render it with the
25 * normal LWIR renderer, and carry the source EXIF across.
26 * An existing embedded temperature layer is always reused rather than synthesized.
27 * Output goes to a same-directory temporary file, is fsynced, then published
28 * without overwriting unrelated files. All buffers are static (no heap).
29 */
30#include "lwir_mock.h"
31#include "lwir_container.h"
32#include "lwir_frame.h"
33#include "lwir_image.h"
34#include "lwir_render.h"
35#include "exifite.h"
36
37#include <errno.h>
38#include <fcntl.h>
39#include <limits.h>
40#include <setjmp.h>
41#include <stdio.h>
42#include <stdlib.h>
43#include <string.h>
44#include <sys/stat.h>
45#include <unistd.h>
46
47#include <jpeglib.h>
48
49/** @brief Static workspace: maximum-size buffers would be too large for the stack and the heap is avoided.
50 * @details frame holds the combined layout (image plane of Y/neutral-chroma pairs,
51 * then little-endian Kelvin*64 temperatures); thermal receives an embedded layer;
52 * marker is one APP15 segment body (20-byte header + 65000 data) and doubles as
53 * the copy buffer. Makes the module non-reentrant. */
54static struct {
55 struct jpeg_decompress_struct decoder;
56 struct jpeg_error_mgr error;
57 jmp_buf recovery;
60 uint8_t row[LWIR_MAX_WIDTH * 3];
61 uint8_t marker[65020];
64
65/**
66 * @brief libjpeg fatal-error hook.
67 * @param decoder Unused; the workspace is global.
68 * @details libjpeg's default handler calls exit(); jumping back to decode_mock()
69 * turns corrupt input into an ordinary false return.
70 */
71static void mock_jpeg_error(j_common_ptr decoder)
72{
73 (void)decoder;
74 longjmp(mock_workspace.recovery, 1);
75}
76
77/**
78 * @brief Map display luminance to a synthetic Kelvin*64 sample.
79 * @param luminance 0..255 grey level.
80 * @return round((celsius + 273.15) * 64).
81 * @details Piecewise: 0..128 spans 15..20 degC (background), 129..229 rises
82 * steeply to about 594 degC (hot objects), and >= 230 saturates at 600 degC.
83 * Only gives tests a plausible scene; it is not a calibration.
84 */
85static uint16_t synthetic_raw(uint8_t luminance)
86{
87 const double celsius = luminance <= 128 ? 15.0 + 5.0 * luminance / 128.0 :
88 luminance < 230 ? 20.0 + 580.0 * (luminance - 128) / 102.0 : 600.0;
89 return (uint16_t)((celsius + 273.15) * 64.0 + 0.5);
90}
91
92/**
93 * @brief Decode a JPEG into the combined workspace frame.
94 * @param input Open stream positioned at the start of the JPEG.
95 * @param width In: required width when @p embedded; out: decoded width.
96 * @param height In: required height when @p embedded; out: decoded height.
97 * @param embedded True to take temperatures from the workspace thermal layer
98 * instead of synthesizing them.
99 * @return True only for a complete decode with no libjpeg warnings and a size
100 * accepted by lwir_frame_bytes(); false otherwise (frame contents undefined).
101 * @details Converts RGB to integer BT.601-style luma (77/150/29 >> 8) and stores
102 * Y with neutral chroma 128 so the image plane matches the camera's layout.
103 */
104static bool decode_mock(FILE *input, unsigned *width, unsigned *height, bool embedded)
105{
106 struct jpeg_decompress_struct *decoder = &mock_workspace.decoder;
107 *decoder = (struct jpeg_decompress_struct){0};
108 decoder->err = jpeg_std_error(&mock_workspace.error);
109 mock_workspace.error.error_exit = mock_jpeg_error;
110 /* Every libjpeg failure lands here; only static state is touched afterwards, so no volatile is needed. */
111 if (setjmp(mock_workspace.recovery)) {
112 jpeg_destroy_decompress(decoder);
113 return false;
114 }
115 jpeg_create_decompress(decoder);
116 jpeg_stdio_src(decoder, input);
117 bool valid = jpeg_read_header(decoder, TRUE) == JPEG_HEADER_OK &&
118 lwir_frame_bytes(decoder->image_width, decoder->image_height) != 0;
119 if (embedded && (decoder->image_width != *width || decoder->image_height != *height)) valid = false;
120 decoder->out_color_space = JCS_RGB;
121 if (valid) valid = jpeg_start_decompress(decoder) && decoder->output_components == 3;
122 if (valid) {
123 *width = decoder->output_width;
124 *height = decoder->output_height;
125 const size_t pixels = (size_t)*width * *height;
126 while (valid && decoder->output_scanline < decoder->output_height) {
127 const size_t row_number = decoder->output_scanline;
128 JSAMPROW row = mock_workspace.row;
129 valid = jpeg_read_scanlines(decoder, &row, 1) == 1;
130 for (unsigned column = 0; valid && column < *width; ++column) {
131 const size_t pixel = row_number * *width + column;
132 const uint8_t *rgb = row + column * 3;
133 const uint8_t luminance = (uint8_t)((77U * rgb[0] + 150U * rgb[1] + 29U * rgb[2]) >> 8);
134 mock_workspace.frame[pixel * 2] = luminance;
135 mock_workspace.frame[pixel * 2 + 1] = 128;
136 const uint16_t raw = embedded ? (uint16_t)mock_workspace.thermal[pixel * 2] |
137 (uint16_t)((uint16_t)mock_workspace.thermal[pixel * 2 + 1] << 8) : synthetic_raw(luminance);
138 mock_workspace.frame[(pixels + pixel) * 2] = (uint8_t)raw;
139 mock_workspace.frame[(pixels + pixel) * 2 + 1] = (uint8_t)(raw >> 8);
140 }
141 }
142 /* Warnings mean libjpeg patched over damage; refuse rather than build evidence from guessed pixels. */
143 if (valid) valid = jpeg_finish_decompress(decoder) && mock_workspace.error.num_warnings == 0;
144 }
145 jpeg_destroy_decompress(decoder);
146 return valid;
147}
148
149/**
150 * @brief Store a 32-bit value little-endian.
151 * @param output Destination of at least 4 bytes.
152 * @param number Value to store.
153 */
154static void write_u32(uint8_t *output, uint32_t number)
155{
156 for (unsigned index = 0; index < 4; ++index) output[index] = (uint8_t)(number >> (index * 8));
157}
158
159/**
160 * @brief Copy a JPEG while inserting the workspace temperature plane as LWIRSIM1 APP15 chunks.
161 * @param input Source JPEG; rewound here.
162 * @param output Destination stream.
163 * @param width Temperature width.
164 * @param height Temperature height.
165 * @return True if everything was copied; false on a non-JPEG source or any I/O error.
166 * @details Each chunk is "LWIRSIM1", width, height, byte offset (all u32 LE) and
167 * up to 65000 data bytes, keeping the segment under JPEG's 65535-byte limit.
168 * Chunks go right after SOI; the remaining source bytes, including its own
169 * segments and compressed pixels, are copied unchanged.
170 */
171static bool attach_layer(FILE *input, FILE *output, unsigned width, unsigned height)
172{
173 uint8_t header[2];
174 if (fseeko(input, 0, SEEK_SET) != 0 || fread(header, 1, 2, input) != 2 ||
175 header[0] != 0xff || header[1] != 0xd8 || fwrite(header, 1, 2, output) != 2) return false;
176 const size_t pixels = (size_t)width * height;
177 for (size_t offset = 0; offset < pixels * 2;) {
178 const size_t chunk = pixels * 2 - offset < 65000 ? pixels * 2 - offset : 65000;
179 uint8_t *marker = mock_workspace.marker;
180 for (size_t index = 0; index < 8; ++index) marker[index] = (uint8_t)"LWIRSIM1"[index];
181 write_u32(marker + 8, width); write_u32(marker + 12, height); write_u32(marker + 16, (uint32_t)offset);
182 for (size_t index = 0; index < chunk; ++index)
183 marker[20 + index] = mock_workspace.frame[pixels * 2 + offset + index];
184 /* The JPEG length field counts itself (2 bytes) plus the 20-byte header and data. */
185 const size_t length = chunk + 22;
186 const uint8_t prefix[4] = {0xff, 0xef, (uint8_t)(length >> 8), (uint8_t)length};
187 if (fwrite(prefix, 1, sizeof(prefix), output) != sizeof(prefix) ||
188 fwrite(marker, 1, chunk + 20, output) != chunk + 20) return false;
189 offset += chunk;
190 }
191 size_t received;
192 while ((received = fread(mock_workspace.marker, 1, sizeof(mock_workspace.marker), input)) != 0)
193 if (fwrite(mock_workspace.marker, 1, received, output) != received) return false;
194 return !ferror(input);
195}
196
197/**
198 * @brief Produce mock LWIR evidence from @p input_path at @p output_path.
199 * @return 0 on success, -1 on any failure.
200 * @details Steps: open and identify the source; read any embedded layer; decode
201 * if needed; write a mode-matched temporary file next to the output; check that
202 * the source did not change meanwhile; publish with link() (fails if the name
203 * exists) or, in place, rename() after confirming the path still names the same
204 * inode; finally fsync the directory.
205 * @warning -1 is also returned if only the final directory fsync fails, after the
206 * file has already been published.
207 */
208int lwir_process_mock(const char *input_path, const char *output_path, bool layer_only)
209{
210 if (!input_path || !output_path) return -1;
211 const int input_fd = open(input_path, O_RDONLY | O_CLOEXEC | O_NOFOLLOW);
212 if (input_fd < 0) return -1;
213 /* Identity snapshot: used to detect concurrent modification and an in-place path swap. */
214 struct stat original;
215 if (fstat(input_fd, &original) != 0 || !S_ISREG(original.st_mode) ||
216 original.st_size <= 0 || original.st_size > 256 * 1024 * 1024) { close(input_fd); return -1; }
217 FILE *input = fdopen(input_fd, "rb");
218 if (!input) { close(input_fd); return -1; }
219 unsigned width = 0, height = 0;
220 /* Stays true unless a sensor (LWIRRAW1) layer is found, so absent provenance defaults to synthetic. */
221 bool synthetic = true;
222 const int layer = lwir_read_temperature_stream(input, mock_workspace.thermal,
223 sizeof(mock_workspace.thermal), &width, &height, &synthetic);
224 /* Existing evidence needs no visual decode, including an oriented display JPEG. */
225 if (layer == 1 && layer_only) return fclose(input) == 0 ? 0 : -1;
226 bool success = layer >= 0 && fseeko(input, 0, SEEK_SET) == 0 && decode_mock(input, &width, &height, layer == 1);
227 const bool in_place = strcmp(input_path, output_path) == 0;
228 struct stat existing;
229 /* Out-of-place output must not exist yet; any lstat error other than ENOENT is also a refusal. */
230 if (!in_place && (lstat(output_path, &existing) == 0 || errno != ENOENT)) success = false;
231 char temporary[PATH_MAX];
232 /* Same directory as the output so link()/rename() stay on one filesystem. */
233 const int length = snprintf(temporary, sizeof(temporary), "%s.mock.XXXXXX", output_path);
234 if (length < 0 || (size_t)length >= sizeof(temporary)) success = false;
235 int output_fd = -1;
236 if (success) output_fd = mkstemp(temporary);
237 const bool temporary_created = output_fd >= 0;
238 if (success && output_fd < 0) success = false;
239 if (success && fchmod(output_fd, original.st_mode & 0777) != 0) success = false;
240 FILE *output = NULL;
241 if (success && layer_only) {
242 output = fdopen(output_fd, "wb");
243 if (!output) success = false;
244 else {
245 output_fd = -1;
246 success = attach_layer(input, output, width, height) && fflush(output) == 0 && fsync(fileno(output)) == 0;
247 }
248 } else if (success) {
249 /* The renderer creates its file by path, so release the reserved name; it is briefly unclaimed. */
250 success = close(output_fd) == 0 && unlink(temporary) == 0;
251 output_fd = -1;
252 struct lwir_render_options render = {.view = LWIR_PERCENTILE, .palette = LWIR_WHITE_HOT,
253 .low_percentile = 2, .high_percentile = 98};
254 /* NULL device state: synthetic or replayed imagery must never claim live camera provenance. */
255 if (success) success = lwir_write_jpeg_rendered(temporary, mock_workspace.frame,
256 lwir_frame_bytes(width, height), width, height, synthetic, NULL, &render);
257 if (success) success = chmod(temporary, original.st_mode & 0777) == 0;
258 size_t exif_size = 0;
259 /* ENODATA means the source simply has no EXIF; any other read failure aborts. */
260 if (success && exif_read_jpeg(input_path, mock_workspace.exif, sizeof(mock_workspace.exif), &exif_size) == 0) {
261 output = fopen(temporary, "r+b");
262 success = output && exif_update_jpeg(output, mock_workspace.exif, exif_size) == 0 && fsync(fileno(output)) == 0;
263 } else if (success && errno != ENODATA) success = false;
264 }
265 if (output) { if (fclose(output) != 0) success = false; }
266 if (output_fd >= 0) close(output_fd);
267 struct stat current;
268 /* A source rewritten mid-run would make the output inconsistent with it. */
269 if (fstat(input_fd, &current) != 0 || original.st_size != current.st_size ||
270 original.st_mtim.tv_sec != current.st_mtim.tv_sec || original.st_mtim.tv_nsec != current.st_mtim.tv_nsec) success = false;
271 if (fclose(input) != 0) success = false;
272 if (success) {
273 if (in_place) {
274 /* Replace only if the path still names the file we read, not a substitute. */
275 struct stat named;
276 success = lstat(input_path, &named) == 0 && named.st_dev == original.st_dev && named.st_ino == original.st_ino &&
277 rename(temporary, output_path) == 0;
278 } else success = link(temporary, output_path) == 0;
279 }
280 /* After link() this drops the extra name; after rename() it fails harmlessly. */
281 if (temporary_created) unlink(temporary);
282 if (success) {
283 /* Persist the new directory entry, not just the file data. */
284 char parent[PATH_MAX];
285 const size_t path_size = strlen(output_path);
286 if (path_size >= sizeof(parent)) return -1;
287 for (size_t index = 0; index <= path_size; ++index) parent[index] = output_path[index];
288 char *separator = strrchr(parent, '/');
289 if (!separator) { parent[0] = '.'; parent[1] = '\0'; }
290 else if (separator == parent) separator[1] = '\0';
291 else *separator = '\0';
292 const int directory = open(parent, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
293 if (directory < 0) return -1;
294 success = fsync(directory) == 0;
295 if (close(directory) != 0) success = false;
296 }
297 return success ? 0 : -1;
298}
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_read_jpeg(const char *filename, unsigned char *payload, size_t capacity, size_t *size)
Read the single EXIF APP1 segment before the first JPEG scan.
Definition exifite.c:1022
#define EXIF_MAX_PAYLOAD
APP1 payload ceiling: the JPEG length includes its own two bytes.
Definition exifite.h:51
int exif_update_jpeg(FILE *file, const unsigned char *payload, size_t size)
Replace EXIF in a regular JPEG file without a temporary file.
Definition exifite.c:1649
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.
Exact thermal evidence in JPEG containers, independent of analysis.
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
#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
struct exif_document exif
Definition lwir_image.c:64
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
uint8_t row[LWIR_MAX_WIDTH *3U]
Definition lwir_image.c:63
jmp_buf recovery
Definition lwir_image.c:61
struct jpeg_error_mgr error
Definition lwir_image.c:60
JPEG encoding and durable no-overwrite publication of LWIR frames.
static void write_u32(uint8_t *output, uint32_t number)
Store a 32-bit value little-endian.
Definition lwir_mock.c:154
static uint16_t synthetic_raw(uint8_t luminance)
Map display luminance to a synthetic Kelvin*64 sample.
Definition lwir_mock.c:85
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
struct jpeg_decompress_struct decoder
Definition lwir_mock.c:55
uint8_t frame[LWIR_MAX_FRAME_BYTES]
Definition lwir_mock.c:58
static void mock_jpeg_error(j_common_ptr decoder)
libjpeg fatal-error hook.
Definition lwir_mock.c:71
static bool decode_mock(FILE *input, unsigned *width, unsigned *height, bool embedded)
Decode a JPEG into the combined workspace frame.
Definition lwir_mock.c:104
uint8_t thermal[LWIR_MAX_WIDTH *LWIR_MAX_HEIGHT *2]
Definition lwir_mock.c:59
static struct @327164226255333372052267047366105116027344330166 mock_workspace
Static workspace: maximum-size buffers would be too large for the stack and the heap is avoided.
static bool attach_layer(FILE *input, FILE *output, unsigned width, unsigned height)
Copy a JPEG while inserting the workspace temperature plane as LWIRSIM1 APP15 chunks.
Definition lwir_mock.c:171
Optional development replay adapter, independent of geographic analysis.
Display rendering of Tiny1-C frames into JPEG-ready Y/Cb/Cr scanlines.
@ LWIR_WHITE_HOT
Definition lwir_render.h:58
@ LWIR_PERCENTILE
Definition lwir_render.h:54
#define PATH_MAX
Definition path_utils.h:39
static const char header[]
Definition pose_log.c:87
static FILE * output
Definition pose_log.c:77
static int output_fd
Definition serial_tx.c:39
Display policy for one rendering request; never affects stored samples.
bool valid
Definition usher.c:537