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_analysis.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 Serial saved-image analysis adapter, not part of the camera driver.
20 *
21 * @details Built only when `LWIR_ENABLE_ANALYSIS=1`. Works on an already saved
22 * LWIR JPEG: extracts the embedded exact Kelvin*64 temperature plane, detects
23 * hotspots, reads the observation pose from EXIF ImageDescription, optionally
24 * projects each hotspot to the ground, and writes a text record into EXIF
25 * UserComment. The entropy-coded display image is not decoded or recompressed.
26 *
27 * Memory: large buffers are file-scope statics (no heap, no large stack frames
28 * apart from the 8 KiB record and EXIF payload copy in read_pose()), which is
29 * why the adapter is strictly serial.
30 */
31#include "lwir_analysis.h"
32#include "lwir_detection.h"
33#include "lwir_geolocation.h"
34
35#include "lwir_container.h"
36#include "image_exif.h"
37#include "lwir_frame.h"
38
39#include <errno.h>
40#include <fcntl.h>
41#include <limits.h>
42#include <math.h>
43#include <stdarg.h>
44#include <stdio.h>
45#include <stdlib.h>
46#include <string.h>
47#include <sys/types.h>
48#include <sys/stat.h>
49#include <unistd.h>
50
51/* Static rather than stack/heap: together these exceed typical worker stacks, and
52 * keeping them here makes the whole adapter single-instance (not reentrant). */
55/* Copy of the original ImageDescription, prepended to the UserComment record. */
56static unsigned char geolocation_description[8192];
57/* Native little-endian Kelvin*64 plane; the detector reads it, never modifies it. */
60
61/**
62 * @brief Decode one unsigned 16-bit little-endian value.
63 * @details Byte-wise assembly is independent of host endianness and alignment,
64 * so the plane can be read straight from an arbitrary byte buffer.
65 * @param bytes At least two readable bytes.
66 * @return The decoded value.
67 */
68static uint16_t read_u16_le(const uint8_t *bytes)
69{
70 return (uint16_t)bytes[0] | (uint16_t)((uint16_t)bytes[1] << 8);
71}
72
73/**
74 * @brief Raw Kelvin*64 code of one pixel in the static temperature plane.
75 * @param pixel Row-major native index (y * width + x); caller bounds-checks it.
76 * @return Raw code; 0 and 65535 are sensor endpoint codes, not real temperatures.
77 * @note Celsius is code / 64 - 273.15.
78 */
79static uint16_t temperature_at(size_t pixel)
80{
81 return read_u16_le(temperature_plane + pixel * 2);
82}
83
84/**
85 * @brief Intermediate pose values parsed from the ImageDescription key=value list.
86 * @details Angles are still in degrees here; read_pose() converts them.
87 * `agl` holds height above ground from `altitude_agl_m` or `groundalt_m`.
88 * `seen` is a bitmask indexed like the key table in read_pose(), used both for
89 * duplicate-key rejection and required-key checks. `uncertainty` stays -1 when
90 * absent, which later disqualifies `synchronized`.
91 */
94 unsigned seen;
95 bool synchronized, exposure_interval;
96};
97
98/**
99 * @brief Parse a finite decimal number from a non-NUL-terminated slice.
100 * @details Trims spaces/tabs, copies the slice into a bounded local buffer so
101 * strtod() has a terminator (EXIF text is not guaranteed to be NUL-terminated at
102 * the slice end), and requires strtod() to consume every remaining character.
103 * @param value Start of the value slice (may be unterminated).
104 * @param length Slice length in bytes.
105 * @param[out] number Written only on success.
106 * @return True for a complete finite number; false for empty, overlong (>= 96
107 * bytes after trimming), partial, out-of-range (ERANGE), NaN or infinite input.
108 * @note Locale-dependent strtod(); presumably the process uses the "C" locale.
109 */
110static bool parse_description_number(const char *value, size_t length, double *number)
111{
112 char text[96];
113 while (length && (*value == ' ' || *value == '\t')) { ++value; --length; }
114 while (length && (value[length - 1] == ' ' || value[length - 1] == '\t')) --length;
115 if (!length || length >= sizeof(text)) return false;
116 for (size_t index = 0; index < length; ++index) text[index] = value[index];
117 text[length] = '\0';
118 errno = 0;
119 char *end = NULL;
120 const double parsed = strtod(text, &end);
121 if (errno || end == text || *end || !isfinite(parsed)) return false;
122 *number = parsed;
123 return true;
124}
125
126/**
127 * @brief Read the observation pose recorded in a saved image's EXIF ImageDescription.
128 * @details The description is a `key=value; key=value` list written at capture
129 * time. Segments end at ';' or NUL; segments without '=' and unknown keys are
130 * ignored, but a duplicated known key or an unparsable number rejects the whole
131 * pose rather than guessing which value is right.
132 *
133 * Required: `lat_deg`, `lon_deg`, `alt_m` (WGS84 ellipsoidal height, as sent by
134 * the flight controller), `roll_deg`, `pitch_deg`, `yaw_deg`, and either
135 * `altitude_agl_m` or `groundalt_m`. Both carry height above ground: USHER's
136 * `groundalt_m` is the flight controller's `groundalt` field, which Paparazzi
137 * fills with altitude above ground, not the ground's own altitude. When both are
138 * present `altitude_agl_m` wins.
139 *
140 * Timing qualification: `synchronized` is true only when
141 * `capture_pose_synchronized=true`, `observation_time_kind` names an
142 * exposure-bounding interval, and a non-negative `pose_uncertainty_m` is present.
143 * Any other time kind (for example a plain arrival time) leaves it false.
144 * @param filename Saved JPEG to read; opened independently of the publisher.
145 * @param[out] pose Written only on success; angles converted to radians.
146 * @return True when a complete pose was parsed; false when EXIF or the
147 * description is absent/malformed or required keys are missing. Callers treat
148 * false as "missing pose", never as a zero pose.
149 * @note Uses a stack copy of the EXIF payload (EXIF_MAX_PAYLOAD bytes).
150 */
151static bool read_pose(const char *filename, struct lwir_camera_pose *pose)
152{
153 unsigned char payload[EXIF_MAX_PAYLOAD];
154 size_t payload_size = 0;
155 struct exif_view view;
156 struct exif_value description;
157 if (exif_read_jpeg(filename, payload, sizeof(payload), &payload_size) != 0
158 || exif_parse(&view, payload, payload_size) != 0
159 || !exif_get(&view, EXIF_PRIMARY, EXIF_IMAGE_DESCRIPTION, &description)
160 || description.format != EXIF_ASCII || description.size > 8192) return false;
161 struct pose_fields fields = {.uncertainty = -1};
162 size_t offset = 0;
163 while (offset < description.size) {
164 const size_t start = offset;
165 while (offset < description.size && description.data[offset] != ';' && description.data[offset] != 0) ++offset;
166 const size_t end = offset;
167 if (offset < description.size) {
168 if (description.data[offset] == ';') ++offset;
169 else offset = description.size;
170 }
171 size_t separator = start;
172 while (separator < end && description.data[separator] != '=') ++separator;
173 if (separator == end) continue;
174 size_t key_start = start, key_end = separator;
175 while (key_start < key_end && (description.data[key_start] == ' ' || description.data[key_start] == '\t')) ++key_start;
176 while (key_end > key_start && (description.data[key_end - 1] == ' ' || description.data[key_end - 1] == '\t')) --key_end;
177 const char *key = (const char *)description.data + key_start;
178 const size_t key_length = key_end - key_start;
179 const char *value = (const char *)description.data + separator + 1;
180 size_t value_length = end - separator - 1;
181 while (value_length && (*value == ' ' || *value == '\t')) { ++value; --value_length; }
182 while (value_length && (value[value_length - 1] == ' ' || value[value_length - 1] == '\t')) --value_length;
183 static const char *const names[] = {"lat_deg", "lon_deg", "alt_m", "roll_deg", "pitch_deg", "yaw_deg",
184 "altitude_agl_m", "groundalt_m", "pose_uncertainty_m", "capture_pose_synchronized", "observation_time_kind"};
185 unsigned field = 0;
186 while (field < sizeof(names) / sizeof(names[0])
187 && (strlen(names[field]) != key_length || memcmp(key, names[field], key_length))) ++field;
188 if (field == sizeof(names) / sizeof(names[0])) continue;
189 const unsigned field_bit = 1U << field;
190 if (fields.seen & field_bit) return false;
191 fields.seen |= field_bit;
192 if (field == 9) {
193 while (value_length && (*value == ' ' || *value == '\t')) { ++value; --value_length; }
194 fields.synchronized = value_length == 4 && !memcmp(value, "true", 4);
195 if (!fields.synchronized && !(value_length == 5 && !memcmp(value, "false", 5))) return false;
196 continue;
197 }
198 if (field == 10) {
199 /* Command-to-download presumably qualifies because it brackets the
200 * exposure, unlike an arrival time that only follows it. */
201 fields.exposure_interval = (value_length == 24 && !memcmp(value, "sensor_exposure_interval", 24))
202 || (value_length == 28 && !memcmp(value, "calibrated_exposure_interval", 28))
203 || (value_length == sizeof("command_to_download_interval") - 1 &&
204 !memcmp(value, "command_to_download_interval", sizeof("command_to_download_interval") - 1));
205 continue;
206 }
207 double number;
208 if (!parse_description_number(value, value_length, &number)) return false;
209 switch (field) {
210 case 0: fields.latitude = number; break;
211 case 1: fields.longitude = number; break;
212 case 2: fields.altitude = number; break;
213 case 3: fields.roll = number; break;
214 case 4: fields.pitch = number; break;
215 case 5: fields.yaw = number; break;
216 case 6: fields.agl = number; break;
217 /* groundalt_m is a fallback for the same quantity; never overwrite an explicit AGL. */
218 case 7: if (!(fields.seen & (1U << 6))) fields.agl = number; break;
219 case 8: fields.uncertainty = number; break;
220 default: return false;
221 }
222 }
223 const unsigned required = (1U << 0) | (1U << 1) | (1U << 2) | (1U << 3) | (1U << 4) | (1U << 5);
224 if ((fields.seen & required) != required || !(fields.seen & ((1U << 6) | (1U << 7)))) return false;
225 *pose = (struct lwir_camera_pose){
226 .latitude_deg = fields.latitude, .longitude_deg = fields.longitude,
227 .altitude_ellipsoid_m = fields.altitude, .agl_m = fields.agl,
228 .roll_rad = fields.roll * (3.14159265358979323846 / 180),
229 .pitch_rad = fields.pitch * (3.14159265358979323846 / 180),
230 .yaw_rad = fields.yaw * (3.14159265358979323846 / 180),
231 .uncertainty_m = fields.uncertainty,
232 .synchronized = fields.synchronized && fields.exposure_interval && fields.uncertainty >= 0};
233 return true;
234}
235
236/**
237 * @brief Append printf-formatted text to a fixed record buffer.
238 * @details Fails instead of truncating, so a published record is never silently
239 * cut in the middle of a key/value pair.
240 * @param record Destination buffer, NUL-terminated after each successful append.
241 * @param capacity Total size of @p record in bytes.
242 * @param[in,out] used Bytes already used (excluding the terminator); advanced on success.
243 * @param format printf format string.
244 * @param ... Format arguments.
245 * @return True on success; false on encoding error or insufficient space.
246 */
247static bool append_record(char *record, size_t capacity, size_t *used, const char *format, ...)
248{
249 if (*used >= capacity) return false;
250 va_list arguments;
251 va_start(arguments, format);
252 const int count = vsnprintf(record + *used, capacity - *used, format, arguments);
253 va_end(arguments);
254 if (count < 0 || (size_t)count >= capacity - *used) return false;
255 *used += (size_t)count;
256 return true;
257}
258
259/**
260 * @brief Store the analysis record in the in-memory EXIF document's UserComment.
261 * @details Layout: the 8-byte EXIF character-code prefix `ASCII\0\0\0`, the
262 * original ImageDescription text (so pose evidence is visible in one field), a
263 * `\nLWIR_HOTSPOTS_V1\n` version separator, the record, and a terminating NUL.
264 * The description is copied out first because exif_document_reserve() can move
265 * existing values that `description.data` borrows.
266 * @param information NUL-terminated record, at most 8192 characters.
267 * @return True when the tag was reserved and filled; false for an oversized or
268 * non-ASCII-format description, an oversized record, or exhausted document
269 * capacity (errno ENOSPC/EINVAL from exif_document_reserve()).
270 * @note exif_document_reserve() replaces an existing UserComment, so re-running
271 * analysis overwrites rather than stacks records.
272 */
273static bool set_hotspot_comment(const char *information)
274{
275 struct exif_value description = {0};
276 size_t description_length = 0;
278 if (description.format != EXIF_ASCII || description.size > sizeof(geolocation_description)) return false;
279 description_length = exif_text_length(&description);
280 if (description_length > sizeof(geolocation_description)) return false;
281 for (size_t index = 0; index < description_length; ++index)
282 geolocation_description[index] = description.data[index];
283 }
284 const size_t information_length = strnlen(information, 8193);
285 if (information_length > 8192) return false;
286 static const unsigned char prefix[8] = {'A', 'S', 'C', 'I', 'I', 0, 0, 0};
287 const size_t tag_length = sizeof("\nLWIR_HOTSPOTS_V1\n") - 1;
288 const size_t total = sizeof(prefix) + description_length + tag_length + information_length + 1;
289 if (total > UINT32_MAX) return false;
291 EXIF_USER_COMMENT, EXIF_UNDEFINED, (uint32_t)total);
292 if (!comment) return false;
293 size_t offset = 0;
294 for (size_t index = 0; index < sizeof(prefix); ++index) comment[offset++] = prefix[index];
295 for (size_t index = 0; index < description_length; ++index) comment[offset++] = geolocation_description[index];
296 static const char separator[] = "\nLWIR_HOTSPOTS_V1\n";
297 for (size_t index = 0; index < tag_length; ++index) comment[offset++] = (unsigned char)separator[index];
298 for (size_t index = 0; index < information_length; ++index) comment[offset++] = (unsigned char)information[index];
299 comment[offset] = 0;
300 return true;
301}
302
303/**
304 * @brief Rewrite a JPEG's EXIF with the analysis record, keeping image data intact.
305 * @details Opens with O_NOFOLLOW and requires a regular file, so a symlink cannot
306 * redirect the write. Existing EXIF is imported (ENODATA means none, which is
307 * acceptable); other read/parse failures abort rather than discard metadata.
308 *
309 * With IMAGE_EXIF_ATOMIC_REPLACE the JPEG is streamed to a sibling mkstemp()
310 * file (same directory, so rename() stays atomic on one filesystem) with the
311 * original permission bits, fsync()ed, and renamed over the original only if the
312 * path still names the same inode (dev/ino), so a concurrently replaced file is
313 * not clobbered. Otherwise the EXIF segment is updated in place.
314 * @param filename Target JPEG path.
315 * @param information NUL-terminated analysis record.
316 * @return 0 on success, -1 on any open, stat, EXIF, write, sync or rename
317 * failure (errno may reflect the failing call; not guaranteed).
318 * @note The containing directory is not fsync()ed after rename(), so the rename
319 * itself may not survive a sudden power loss.
320 * @warning In-place mode cannot roll back a partially written update.
321 */
322static int publish_hotspot_comment(const char *filename, const char *information)
323{
324 if (!filename || !information) return -1;
325 const int input_fd = open(filename, O_RDWR | O_CLOEXEC | O_NOFOLLOW);
326 if (input_fd < 0) return -1;
327 struct stat original;
328 if (fstat(input_fd, &original) != 0 || !S_ISREG(original.st_mode)) { close(input_fd); return -1; }
329 FILE *input = fdopen(input_fd, "r+b");
330 if (!input) { close(input_fd); return -1; }
331 size_t payload_size = 0;
332 struct exif_view view;
334 bool success = fseeko(input, 0, SEEK_SET) == 0;
335 if (success) {
336 const int read_result = exif_read_stream(input, geolocation_exif_payload,
337 sizeof(geolocation_exif_payload), &payload_size);
338 if (read_result == 0) {
339 success = exif_parse(&view, geolocation_exif_payload, payload_size) == 0
341 } else if (errno != ENODATA) {
342 success = false;
343 }
344 }
345 success = success && set_hotspot_comment(information)
347 sizeof(geolocation_exif_payload), &payload_size) == 0;
348#if IMAGE_EXIF_ATOMIC_REPLACE
349 char temporary[PATH_MAX];
350 int temporary_length = snprintf(temporary, sizeof(temporary), "%s.lwir.XXXXXX", filename);
351 int output_fd = -1;
352 bool temporary_created = false;
353 FILE *output = NULL;
354 if (success && (temporary_length < 0 || (size_t)temporary_length >= sizeof(temporary))) success = false;
355 if (success) output_fd = mkstemp(temporary);
356 if (success && output_fd < 0) success = false;
357 if (output_fd >= 0) temporary_created = true;
358 if (success && fchmod(output_fd, original.st_mode & 0777) != 0) success = false;
359 if (success) output = fdopen(output_fd, "wb");
360 if (success && !output) success = false;
361 /* The FILE now owns the descriptor; avoid a double close below. */
362 if (output) output_fd = -1;
363 if (success) success = fseeko(input, 0, SEEK_SET) == 0
364 && exif_rewrite_jpeg(input, output, geolocation_exif_payload, payload_size) == 0
365 && fflush(output) == 0 && fsync(fileno(output)) == 0;
366 if (output && fclose(output) != 0) success = false;
367 if (output_fd >= 0) close(output_fd);
368 struct stat current;
369 if (success) success = lstat(filename, &current) == 0
370 && current.st_dev == original.st_dev && current.st_ino == original.st_ino;
371 if (success) success = rename(temporary, filename) == 0;
372 if (!success && temporary_created) unlink(temporary);
373#else
374 success = success && fseeko(input, 0, SEEK_SET) == 0
375 && exif_update_jpeg(input, geolocation_exif_payload, payload_size) == 0
376 && fsync(fileno(input)) == 0;
377#endif
378 if (fclose(input) != 0) success = false;
379 return success ? 0 : -1;
380}
381
382/**
383 * @brief Detect, optionally geolocate and record hotspots for one saved JPEG.
384 * @details See lwir_analysis.h for the contract. Order of evaluation:
385 * -# Read the embedded temperature plane: invalid -> `status=invalid_native_frame`;
386 * absent -> `status=no_temperature_plane` (both published, return value from publishing).
387 * -# Read pose and calibration (each may be missing without aborting).
388 * -# Detect hotspots, then derive a single status with precedence
389 * missing pose > missing calibration > invalid calibration > unverified
390 * calibration, finally overridden by `no_hotspots`.
391 * -# For each hotspot, report the rounded pixel, its nearest-pixel temperature
392 * and the subpixel projection input; project only when status is `estimated`.
393 * @return 0 when a record was published, -1 otherwise.
394 */
395int lwir_geolocate_image(const char *filename, const char *calibration_path)
396{
397 if (!filename || !*filename) return -1;
398 unsigned width = 0, height = 0;
399 bool synthetic = false;
400 const int layer = lwir_read_temperature_layer(filename, temperature_plane, sizeof(temperature_plane),
401 &width, &height, &synthetic);
402 char record[8192];
403 size_t used = 0;
404 if (layer < 0)
405 return publish_hotspot_comment(filename, "status=invalid_native_frame; count=0; coordinates_omitted=true");
406 /* Header states the model limits next to every result: flat ground, zero GPS
407 * antenna offset, apparent (uncorrected) temperatures, unknown accuracy. */
408 if (!append_record(record, sizeof(record), &used,
409 "coordinate_datum=WGS84; ground_model=local_horizontal_plane; gps_camera_offset_m=0; "
410 "temperature_surface_correction=not_applied; absolute_accuracy_m=unknown; temperature_kind=%s; ",
411 synthetic ? "synthetic" : "sensor_apparent")) return -1;
412 if (layer == 0) {
413 if (!append_record(record, sizeof(record), &used, "status=no_temperature_plane; count=0")) return -1;
414 return publish_hotspot_comment(filename, record);
415 }
416 struct lwir_camera_pose pose = {0};
417 const bool have_pose = read_pose(filename, &pose);
418 struct lwir_camera_geometry geometry = {0};
419 const bool have_calibration = calibration_path && *calibration_path
420 && lwir_geolocation_load_calibration(calibration_path, width, height, &geometry);
421 struct lwir_hotspot_set hotspots;
422 if (!lwir_detect_hotspots(temperature_plane, (size_t)width * height * 2, width, height,
423 &detection_workspace, &hotspots)) return -1;
424 const char *status = "estimated";
425 if (!have_pose) status = "missing_shot_pose";
426 else if (!calibration_path || !*calibration_path) status = "missing_camera_calibration";
427 else if (!have_calibration) status = "invalid_camera_calibration";
428 /* Synthetic frames presumably come from simulation with known geometry, so an
429 * unverified profile is accepted there but never for sensor data. Pose timing
430 * is deliberately not gated here; it is reported for the consumer instead. */
431 else if (!geometry.verified && !synthetic) status = "unverified_camera_calibration";
432 if (hotspots.count == 0) status = "no_hotspots";
433 if (!append_record(record, sizeof(record), &used,
434 "capture_pose_synchronized=%s; capture_pose_uncertainty_m=%.6f; status=%s; calibration_verified=%s; "
435 "count=%zu; generic_candidate_count=%zu; tray_candidate_count=%zu; "
436 "selection_pass=%s; center_method=subpixel_temperature_weighted_centroid; "
437 "temperature_sample_method=nearest_pixel; temperature_units=C\n",
438 pose.synchronized ? "true" : "false", pose.uncertainty_m, status,
439 have_calibration && geometry.verified ? "true" : "false", hotspots.count,
440 hotspots.generic_count, hotspots.tray_count,
441 hotspots.tray_pass_selected ? "fire_tray_hypothesis" : "generic_hotspot_fallback")) return -1;
442 for (size_t index = 0; index < hotspots.count; ++index) {
443 const struct lwir_hotspot *hotspot = &hotspots.candidates[index];
444 /* The weighted centroid lies within the component's bounding box, so this
445 * check is defensive. The pixel nearest the centroid may be cooler than the
446 * threshold (e.g. a ring-shaped blob), hence center_above_detection_threshold. */
447 const unsigned pixel_x = (unsigned)lround(hotspot->center_x);
448 const unsigned pixel_y = (unsigned)lround(hotspot->center_y);
449 if (pixel_x >= width || pixel_y >= height) return -1;
450 const uint16_t raw = temperature_at((size_t)pixel_y * width + pixel_x);
451 if (!append_record(record, sizeof(record), &used,
452 "hotspot=%zu; pixel_x=%u; pixel_y=%u; center_temperature_c=%.6f; raw_kelvin_x64=%u; "
453 "center_above_detection_threshold=%s; projection_pixel_x=%.6f; projection_pixel_y=%.6f",
454 index + 1, pixel_x, pixel_y, raw / 64.0 - 273.15, raw,
455 raw / 64.0 - 273.15 >= hotspots.threshold_celsius ? "true" : "false",
456 hotspot->center_x, hotspot->center_y)) return -1;
457 /* Project the subpixel centroid, not the rounded pixel, to avoid up to
458 * half a pixel of extra ground error. */
460 if (!strcmp(status, "estimated") && lwir_geolocation_project(hotspot->center_x, hotspot->center_y, &geometry, &pose, &point)) {
461 if (!append_record(record, sizeof(record), &used,
462 "; location_status=estimated; latitude_deg=%.9f; longitude_deg=%.9f; "
463 "altitude_ellipsoid_m=%.6f; slant_range_m=%.6f\n",
464 point.latitude_deg, point.longitude_deg, point.altitude_ellipsoid_m, point.slant_range_m)) return -1;
465 } else {
466 const char *location_status = !strcmp(status, "estimated") ? "invalid_geometry_or_horizon" : status;
467 if (!append_record(record, sizeof(record), &used, "; location_status=%s\n", location_status)) return -1;
468 }
469 }
470 return publish_hotspot_comment(filename, record);
471}
static unsigned capacity[COVERAGE_CAMERAS]
uint8_t bytes[CHDK_CONTROL_REPLY_SIZE]
Definition chdk_pipe.c:144
void(* close)(struct usbfs_handle *)
Definition chdkbridge.c:57
int(* open)(const struct usbfs_device *, struct usbfs_handle *)
Definition chdkbridge.c:56
static bool start(uint32_t session)
Admit a nonzero session and discard correlation from the previous one.
static int record(const union dc_shot_union *shot)
Retrieve a point and admit a new observation only when its credit is free.
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
int exif_parse(struct exif_view *view, const unsigned char *payload, size_t size)
Validate an EXIF APP1 payload and create a borrowed view.
Definition exifite.c:257
bool exif_get(const struct exif_view *view, enum exif_directory directory, uint16_t tag, struct exif_value *value)
Look up a directory-local tag without copying its bytes.
Definition exifite.c:310
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
bool exif_document_get(const struct exif_document *document, enum exif_directory directory, uint16_t tag, struct exif_value *value)
Borrow a field from the current writable document.
Definition exifite.c:447
#define EXIF_MAX_PAYLOAD
APP1 payload ceiling: the JPEG length includes its own two bytes.
Definition exifite.h:51
int exif_read_stream(FILE *input, unsigned char *payload, size_t capacity, size_t *size)
Read capture EXIF from an already-open JPEG without reopening its path.
Definition exifite.c:1013
int exif_rewrite_jpeg(FILE *input, FILE *output, const unsigned char *payload, size_t size)
Stream a JPEG with one new EXIF segment instead of its old EXIF records.
Definition exifite.c:1518
size_t exif_text_length(const struct exif_value *value)
Count text bytes after trimming trailing NUL padding only.
Definition exifite.c:399
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
@ EXIF_ASCII
Definition exifite.h:66
@ EXIF_UNDEFINED
Definition exifite.h:70
@ EXIF_CAMERA
Definition exifite.h:59
@ EXIF_PRIMARY
Definition exifite.h:59
@ EXIF_IMAGE_DESCRIPTION
Definition exifite.h:80
@ EXIF_USER_COMMENT
Definition exifite.h:93
Flight, timing, and thermal-analysis metadata writing for captured JPEGs.
static int image_exif_import(struct exif_document *document, const struct exif_view *view)
Import standard metadata plus the application's approved capture evidence.
Definition image_exif.h:58
static struct lwir_detection_workspace detection_workspace
static unsigned char geolocation_exif_payload[EXIF_MAX_PAYLOAD]
static int publish_hotspot_comment(const char *filename, const char *information)
Rewrite a JPEG's EXIF with the analysis record, keeping image data intact.
static uint8_t temperature_plane[LWIR_MAX_WIDTH *LWIR_MAX_HEIGHT *2]
static bool read_pose(const char *filename, struct lwir_camera_pose *pose)
Read the observation pose recorded in a saved image's EXIF ImageDescription.
static bool set_hotspot_comment(const char *information)
Store the analysis record in the in-memory EXIF document's UserComment.
static bool parse_description_number(const char *value, size_t length, double *number)
Parse a finite decimal number from a non-NUL-terminated slice.
static uint16_t read_u16_le(const uint8_t *bytes)
Decode one unsigned 16-bit little-endian value.
static struct exif_document geolocation_exif_document
static bool append_record(char *record, size_t capacity, size_t *used, const char *format,...)
Append printf-formatted text to a fixed record buffer.
static uint16_t temperature_at(size_t pixel)
Raw Kelvin*64 code of one pixel in the static temperature plane.
int lwir_geolocate_image(const char *filename, const char *calibration_path)
Detect, optionally geolocate and record hotspots for one saved JPEG.
static unsigned char geolocation_description[8192]
Optional saved-image adapter combining thermal detection, pose and projection.
static const char * calibration_path
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.
Exact thermal evidence in JPEG containers, independent of analysis.
bool lwir_detect_hotspots(const uint8_t *temperature, size_t bytes, unsigned width, unsigned height, struct lwir_detection_workspace *workspace, struct lwir_hotspot_set *result)
Detect and rank hot connected components in a native temperature plane.
Optional thermal candidate detection, independent of pose and image files.
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
bool lwir_geolocation_project(double pixel_x, double pixel_y, const struct lwir_camera_geometry *camera, const struct lwir_camera_pose *pose, struct lwir_ground_point *point)
Project a native subpixel location onto the local ground plane.
bool lwir_geolocation_load_calibration(const char *path, unsigned width, unsigned height, struct lwir_camera_geometry *geometry)
Load a calibration profile for one native image size.
Optional camera calibration and native pixel-to-ground geometry only.
#define PATH_MAX
Definition path_utils.h:39
static size_t count
Definition pose_log.c:79
static FILE * output
Definition pose_log.c:77
static int output_fd
Definition serial_tx.c:39
Caller-owned bounded writer with no heap allocation.
Definition exifite.h:156
Borrowed bytes plus enough type information for safe interpretation.
Definition exifite.h:119
const unsigned char * data
Definition exifite.h:120
size_t size
Definition exifite.h:121
uint16_t format
Definition exifite.h:123
Borrowed view of a validated APP1 payload.
Definition exifite.h:131
Projection calibration in native coordinates, never display coordinates.
bool verified
Operator verification claim; loading coefficients does not establish it.
Observation pose; geographic angles are degrees, attitude angles radians.
bool synchronized
Timing qualification retained for caller policy, not inferred by geometry.
double uncertainty_m
Observation uncertainty retained for caller qualification, not applied by projection.
double latitude_deg
Navigation reference latitude in WGS84 degrees.
Caller-owned scratch storage; never reserved by an imagery-only build.
WGS84 estimate on a local horizontal plane, not a surveyed accuracy claim.
Bounded ranking, retaining the existing two-candidate mission policy.
bool tray_pass_selected
True when candidates came from the tray ranking.
struct lwir_hotspot candidates[2]
Best first; only the first count entries are valid.
size_t generic_count
All components that passed the contrast check, not only retained ones.
size_t count
Valid entries in candidates (0..2).
size_t tray_count
Subset of generic_count classified tray-like.
double threshold_celsius
Frame threshold actually applied; NaN when the plane has no valid codes.
A thermal component expressed only in native sensor coordinates.
double center_x
Subpixel centroid column weighted by excess over local background; center_y likewise.
One timestamped geographic position for a replay annotation.
Intermediate pose values parsed from the ImageDescription key=value list.
double uncertainty
double longitude
double latitude
bool exposure_interval
double altitude
unsigned seen