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
image_exif.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 image_exif.c
20 * @brief JPEG EXIF updates for USHER flight and thermal-capture provenance.
21 * @details Existing JPEG markers are copied while prior EXIF is replaced by a standards
22 * compliant APP1 block. Default in-place updates avoid temporary files and leave
23 * equal-position image bytes untouched. IMAGE_EXIF_ATOMIC_REPLACE selects the older
24 * sibling-file/fsync/rename method when original-file retention is more important.
25 * In-place writes are not atomic; interrupted mutation can damage the JPEG. Neither
26 * method promises full power-loss durability, since the parent directory is not synced.
27 */
28#include "image_exif.h"
29#include "boot_id.h"
30#include "exifite.h"
31#include "motion_compensation.h"
32
33#include <errno.h>
34#include <fcntl.h>
35#include <inttypes.h>
36#include <limits.h>
37#include <math.h>
38#include <stdbool.h>
39#include <stdatomic.h>
40#include <stddef.h>
41#include <stdint.h>
42#include <stdio.h>
43#include <stdlib.h>
44#include <string.h>
45#include <sys/stat.h>
46#include <unistd.h>
47
48#define ANGLE_BFP_SCALE 4096.0
49#define SPEED_BFP_SCALE 524288.0
50#define POSITION_BFP_SCALE 256.0
51#define RAD_TO_DEG 57.29577951308232
52#define ASCII_COMMENT_PREFIX_SIZE 8U
53#define EXIF_WORKSPACE_COUNT 8U
54#define EXIF_SCRATCH_CAPACITY 8192U
55#define SHOT_COMMENT_CAPACITY 1536U
56#define COMPLETE_RECORD_CAPACITY 4096U
57
65
67static _Thread_local struct exif_workspace *active_workspace;
68
69/** @brief Claim a bounded EXIF editing slot for the current thread.
70 * @return Owned slot, or NULL with EBUSY for reentry or EAGAIN for exhaustion.
71 * @details Keep large scratch buffers off worker stacks. Acquire ordering
72 * pairs with release so a new owner does not race the previous user. */
74{
75 if (active_workspace != NULL) {
76 errno = EBUSY;
77 return NULL;
78 }
79 for (size_t index = 0; index < EXIF_WORKSPACE_COUNT; ++index) {
80 bool expected = false;
81 if (atomic_compare_exchange_strong_explicit(&exif_workspaces[index].in_use, &expected, true,
82 memory_order_acquire, memory_order_relaxed)) {
84 workspace->temporary_name[0] = '\0';
85 exif_document_init(&workspace->document);
87 return workspace;
88 }
89 }
90 errno = EAGAIN;
91 return NULL;
92}
93
94/** @brief Return an editing slot to the shared pool.
95 * @param workspace Thread-owned slot, or NULL.
96 * @details Clear the thread-local reference before making the slot
97 * available. All borrowed document and scratch pointers expire here. */
99{
100 if (workspace == NULL) {
101 return;
102 }
103 active_workspace = NULL;
104 atomic_store_explicit(&workspace->in_use, false, memory_order_release);
105}
106
107/** @brief Import an existing JPEG EXIF block into the active editing slot.
108 * @param filename JPEG to read.
109 * @return Borrowed editable document, or NULL if the slot or metadata is unavailable.
110 * @details Parse the bounded payload before importing its entries so a
111 * metadata-only update can retain the image's existing tags. */
112static struct exif_document *load_exif(const char *filename)
113{
114 if (!active_workspace) return NULL;
115 size_t size;
116 struct exif_view view;
117 if (exif_read_jpeg(filename, active_workspace->payload, sizeof(active_workspace->payload), &size) != 0
118 || exif_parse(&view, active_workspace->payload, size) != 0
119 || image_exif_import(&active_workspace->document, &view) != 0) return NULL;
120 return &active_workspace->document;
121}
122
123/** @brief Encode one signed GPS coordinate as EXIF hemisphere and DMS tags.
124 * @param[in,out] exif Editable EXIF document.
125 * @param reference_tag GPS tag for the hemisphere letter.
126 * @param coordinate_tag GPS tag for the three unsigned rationals.
127 * @param coordinate Signed coordinate in units of 10^-7 degrees.
128 * @param limit Inclusive absolute bound in the same units.
129 * @param positive Hemisphere for nonnegative values.
130 * @param negative Hemisphere for negative values.
131 * @return Zero on success, or -1 on invalid range or insufficient tag storage.
132 * @details Split the magnitude with integer arithmetic so coordinate
133 * conversion does not introduce floating-point rollover between DMS fields.
134 * A failure after setting the hemisphere can leave the document modified. */
135static int set_coordinate(struct exif_document *exif, uint16_t reference_tag, uint16_t coordinate_tag,
136 int32_t coordinate, int32_t limit, char positive, char negative)
137{
138 if (coordinate < -limit || coordinate > limit) {
139 return -1;
140 }
141
142 char reference[2] = {coordinate < 0 ? negative : positive, '\0'};
143 if (exif_document_ascii(exif, EXIF_GPS, reference_tag, reference) != 0) {
144 return -1;
145 }
146
147 unsigned char *entry = exif_document_reserve(exif, EXIF_GPS, coordinate_tag, EXIF_RATIONAL, 3);
148 if (entry == NULL) {
149 return -1;
150 }
151
152 uint64_t absolute = coordinate < 0 ? (uint64_t)(-(int64_t)coordinate) : (uint64_t)coordinate;
153 uint32_t degrees = (uint32_t)(absolute / 10000000U);
154 uint64_t remainder = absolute % 10000000U;
155 uint32_t minutes = (uint32_t)((remainder * 60U) / 10000000U);
156 remainder = remainder * 60U - (uint64_t)minutes * 10000000U;
157 uint32_t seconds_millionths = (uint32_t)((remainder * 60U * 1000000U) / 10000000U);
158
159 exif_encode_long(entry, degrees);
160 exif_encode_long(entry + 4, 1);
161 exif_encode_long(entry + 8, minutes);
162 exif_encode_long(entry + 12, 1);
163 exif_encode_long(entry + 16, seconds_millionths);
164 exif_encode_long(entry + 20, 1000000U);
165 return 0;
166}
167
168/** @brief Convert a flight-controller heading to the EXIF angular range.
169 * @param angle_bfp Angle in flight-controller fixed-point radians.
170 * @return Degrees in [0, 360).
171 * @details Wrap negative headings before encoding unsigned EXIF rationals. */
172static double normalized_degrees(int32_t angle_bfp)
173{
174 double degrees = angle_bfp / ANGLE_BFP_SCALE * RAD_TO_DEG;
175 degrees = fmod(degrees, 360.0);
176 return degrees < 0.0 ? degrees + 360.0 : degrees;
177}
178
179/** @brief Form a nonnegative numerator for an EXIF rational.
180 * @param value Quantity to encode.
181 * @param scale Positive finite denominator scale.
182 * @return Rounded numerator, saturated at UINT32_MAX; zero for nonpositive or nonfinite input.
183 * @details Saturate before converting so an out-of-range value cannot wrap. */
184static uint32_t scaled_unsigned(double value, double scale)
185{
186 if (!isfinite(value) || value <= 0.0) {
187 return 0;
188 }
189 double scaled = value * scale;
190 return scaled >= UINT32_MAX ? UINT32_MAX : (uint32_t)llround(scaled);
191}
192
193/** @brief Add GPS fields and the flight-pose description to an editable document.
194 * @param[in,out] exif Document owned by the active workspace.
195 * @param original Pose supplied by the caller; never modified.
196 * @param delay Estimated capture delay in seconds.
197 * @param compensate Nonzero to attempt ground-motion compensation.
198 * @param timing Optional capture delivery evidence.
199 * @return Zero on success, or -1 if a tag or the bounded description cannot be written.
200 * @details Apply optional compensation to a local copy. Keep standard EXIF
201 * fields for generic viewers and record fixed-point and physical units in
202 * the description for consumers that need the full flight pose. */
203static int add_shot_tags(struct exif_document *exif, const union dc_shot_union *original, double delay, int compensate,
204 const struct capture_timing *timing)
205{
206 union dc_shot_union adjusted = *original;
207 int32_t latitude = original->data.lat;
208 int32_t longitude = original->data.lon;
209 const int applied = compensate && compensate_ground_position(&latitude, &longitude,
210 original->data.vground / SPEED_BFP_SCALE, original->data.course / ANGLE_BFP_SCALE, delay);
211 adjusted.data.lat = latitude;
212 adjusted.data.lon = longitude;
213 const union dc_shot_union *shot = &adjusted;
214 unsigned char *version = exif_document_reserve(exif, EXIF_GPS, EXIF_GPS_VERSION, EXIF_BYTE, 4);
215 if (version == NULL) {
216 return -1;
217 }
218 version[0] = 2;
219 version[1] = 3;
220
222 shot->data.lat, 900000000, 'N', 'S') != 0
224 shot->data.lon, 1800000000, 'E', 'W') != 0) {
225 return -1;
226 }
227
228 unsigned char *altitude_reference = exif_document_reserve(exif, EXIF_GPS, EXIF_GPS_ALTITUDE_REF,
229 EXIF_BYTE, 1);
230 if (altitude_reference == NULL) {
231 return -1;
232 }
233 altitude_reference[0] = shot->data.alt < 0 ? 1 : 0;
234 uint64_t altitude_mm = shot->data.alt < 0 ? (uint64_t)(-(int64_t)shot->data.alt) : (uint64_t)shot->data.alt;
235 if (altitude_mm > UINT32_MAX
236 || exif_document_rational(exif, EXIF_GPS, EXIF_GPS_ALTITUDE, (uint32_t)altitude_mm, 1000) != 0) {
237 return -1;
238 }
239
240 double speed_m_s = shot->data.vground / SPEED_BFP_SCALE;
241 double course_deg = normalized_degrees(shot->data.course);
242 double yaw_deg = normalized_degrees(shot->data.psi);
245 scaled_unsigned(fabs(speed_m_s) * 3.6, 1000.0), 1000) != 0
248 scaled_unsigned(course_deg, 10000.0), 10000) != 0
251 scaled_unsigned(yaw_deg, 10000.0), 10000) != 0) {
252 return -1;
253 }
254
255 char *comment = (char *)active_workspace->scratch;
256 int comment_length = snprintf(comment, SHOT_COMMENT_CAPACITY,
257 "Paparazzi USHER MORA; nr=%" PRId32 "; lat_e7deg=%" PRId32
258 "; lon_e7deg=%" PRId32 "; alt_mm=%" PRId32
259 "; phi_bfp=%" PRId32 "; theta_bfp=%" PRId32
260 "; psi_bfp=%" PRId32 "; vground_bfp=%" PRId32
261 "; course_bfp=%" PRId32 "; groundalt_bfp=%" PRId32
262 "; lat_deg=%.7f; lon_deg=%.7f; alt_m=%.3f"
263 "; roll_deg=%.4f; pitch_deg=%.4f; yaw_deg=%.4f"
264 "; speed_m_s=%.4f; course_deg=%.4f; groundalt_m=%.3f",
265 shot->data.nr, shot->data.lat, shot->data.lon, shot->data.alt,
266 shot->data.phi, shot->data.theta, shot->data.psi,
267 shot->data.vground, shot->data.course, shot->data.groundalt,
268 shot->data.lat / 1e7, shot->data.lon / 1e7, shot->data.alt / 1000.0,
269 shot->data.phi / ANGLE_BFP_SCALE * RAD_TO_DEG,
270 shot->data.theta / ANGLE_BFP_SCALE * RAD_TO_DEG,
271 shot->data.psi / ANGLE_BFP_SCALE * RAD_TO_DEG,
272 speed_m_s, course_deg, shot->data.groundalt / POSITION_BFP_SCALE);
273 if (comment_length < 0 || (size_t)comment_length >= SHOT_COMMENT_CAPACITY) {
274 return -1;
275 }
276 if (isfinite(delay) && delay >= 0) {
277 int extra = snprintf(comment + comment_length, SHOT_COMMENT_CAPACITY - (size_t)comment_length,
278 "; original_lat_deg=%.7f; original_lon_deg=%.7f; request_to_frame_arrival_s=%.9f"
279 "; position_compensation=%s; timing_reference=%s"
280 "; exposure_latency_known=false; attitude_compensated=false; altitude_compensated=false",
281 original->data.lat / 1e7, original->data.lon / 1e7, delay,
282 applied ? "constant_ground_velocity_estimate" : "not_applied",
283 timing && capture_timing_valid(timing)
284 && timing->callback_arrival ? "server_request_to_callback" : "server_request_to_uvc_return");
285 if (extra < 0 || (size_t)extra >= SHOT_COMMENT_CAPACITY - (size_t)comment_length) return -1;
286 comment_length += extra;
287 }
288 if (timing && capture_timing_valid(timing)) {
289 char boot_id[37];
291 int extra = snprintf(comment + comment_length, SHOT_COMMENT_CAPACITY - (size_t)comment_length,
292 "; mora_boot_id=%s; camera_request_monotonic_us=%" PRIu64
293 "; frame_arrival_monotonic_us=%" PRIu64 "; capture_time_kind=%s",
295 timing->callback_arrival ? "sdk_callback_not_exposure" : "uvc_return_not_exposure");
296 if (extra < 0 || (size_t)extra >= SHOT_COMMENT_CAPACITY - (size_t)comment_length) return -1;
297 comment_length += extra;
298 if (timing->callback_arrival) {
299 extra = snprintf(comment + comment_length, SHOT_COMMENT_CAPACITY - (size_t)comment_length,
300 "; callback_sequence=%" PRIu64 "; callback_drops=%" PRIu64,
301 timing->callback_sequence, timing->callback_drops);
302 if (extra < 0 || (size_t)extra >= SHOT_COMMENT_CAPACITY - (size_t)comment_length) return -1;
303 }
304 }
306 || exif_document_ascii(exif, EXIF_PRIMARY, EXIF_SOFTWARE, "Paparazzi USHER") != 0) {
307 return -1;
308 }
309 return 0;
310}
311
312static int save_exif(const char *filename, struct exif_document *exif);
313
314/** @brief Write an EXIF UserComment composed of flight and analysis records.
315 * @param[in,out] exif Document already carrying the flight description.
316 * @param tag Optional section label as an empty or nonempty string, never NULL.
317 * @param information Null-terminated analysis text, at most 8192 bytes.
318 * @return Zero on success, or -1 on invalid input or insufficient storage.
319 * @details Snapshot the description before reserving another entry so
320 * rebuilding the tag storage cannot invalidate the bytes being copied. */
321static int set_tagged_comment(struct exif_document *exif, const char *tag, const char *information)
322{
323 if (!exif || !tag || !information) return -1;
324 const size_t information_length = strnlen(information, 8193);
325 if (information_length > 8192) return -1;
326 struct exif_value description;
328 || description.format != EXIF_ASCII || description.size > COMPLETE_RECORD_CAPACITY) return -1;
329 const size_t description_length = strnlen((const char *)description.data, description.size);
330 unsigned char saved_description[COMPLETE_RECORD_CAPACITY];
331 for (size_t index = 0; index < description_length; ++index) saved_description[index] = description.data[index];
332 char separator[64];
333 const int separator_length = tag[0] ? snprintf(separator, sizeof(separator), "\n%s\n", tag) : 0;
334 if (separator_length < 0 || (size_t)separator_length >= sizeof(separator)) return -1;
335 const size_t length = ASCII_COMMENT_PREFIX_SIZE + description_length + (size_t)separator_length
336 + information_length + 1;
338 EXIF_UNDEFINED, (uint32_t)length);
339 if (!entry) return -1;
340 const unsigned char prefix[8] = {'A', 'S', 'C', 'I', 'I', 0, 0, 0};
341 size_t offset = 0;
342 for (size_t index = 0; index < sizeof(prefix); ++index) entry[offset++] = prefix[index];
343 for (size_t index = 0; index < description_length; ++index) entry[offset++] = saved_description[index];
344 for (size_t index = 0; index < (size_t)separator_length; ++index) entry[offset++] = (unsigned char)separator[index];
345 for (size_t index = 0; index < information_length; ++index) entry[offset++] = (unsigned char)information[index];
346 return 0;
347}
348
349/** @brief Compatibility wrapper for analysis that becomes available after the flight EXIF write.
350 * @details Prefer the combined writer when the result is already available, so
351 * the original need not be streamed to a replacement file twice.
352 */
353static int write_tagged_comment(const char *filename, const char *tag, const char *information)
354{
355 if (!filename) return -1;
357 if (workspace == NULL) return -1;
358 struct exif_document *exif = load_exif(filename);
359 if (!exif) {
361 return -1;
362 }
363 if (set_tagged_comment(exif, tag, information) != 0) {
365 return -1;
366 }
367 int result = save_exif(filename, exif);
369 return result;
370}
371
372int image_exif_write_hotspots(const char *filename, const char *information)
373{
374 return write_tagged_comment(filename, "LWIR_HOTSPOTS_V1", information);
375}
376
377int image_exif_write_object_detections(const char *filename, const char *information)
378{
379 return write_tagged_comment(filename, "AICAM_OBJECTS_V1", information);
380}
381
382int image_exif_write_mock_map(const char *filename, double horizontal_fov, double vertical_fov)
383{
384 if (filename == NULL || !isfinite(horizontal_fov) || !isfinite(vertical_fov)
385 || horizontal_fov <= 0 || horizontal_fov >= 179 || vertical_fov <= 0 || vertical_fov >= 179) return -1;
387 if (workspace == NULL) return -1;
388 struct exif_document *exif = load_exif(filename);
389 if (exif == NULL) {
391 return -1;
392 }
393 char record[256];
394 int length = snprintf(record, sizeof(record),
395 "{\"schema\":\"USHER_MOCK_MAP_V1\",\"tile_scheme\":\"XYZ\",\"zoom\":18,"
396 "\"projection\":\"pinhole_flat_ground\",\"horizontal_fov_deg\":%.9g,"
397 "\"vertical_fov_deg\":%.9g}", horizontal_fov, vertical_fov);
398 if (length < 0 || (size_t)length >= sizeof(record)
401 return -1;
402 }
403 int result = save_exif(filename, exif);
405 return result;
406}
407
408int image_exif_write(const char *filename, const union dc_shot_union *shot)
409{
410 return image_exif_write_timed(filename, shot, -1, 0);
411}
412
413int image_exif_write_timed(const char *filename, const union dc_shot_union *shot,
414 double capture_delay_s, int compensate)
415{
416 return image_exif_write_capture(filename, shot, capture_delay_s, compensate, NULL);
417}
418
419int image_exif_write_capture(const char *filename, const union dc_shot_union *shot,
420 double capture_delay_s, int compensate, const struct capture_timing *timing)
421{
422 return image_exif_write_complete(filename, shot, capture_delay_s, compensate, timing, NULL, 0, NULL);
423}
424
425/** @brief Extend the flight description with observation provenance.
426 * @param[in,out] exif Active document containing the existing description.
427 * @param timing Optional timing, frame-identity and pose evidence.
428 * @param aligned Whether the primary capture pose came from synchronized evidence.
429 * @return Zero on success, or -1 on malformed metadata or insufficient storage.
430 * @details Record frame identity separately from timing and pose alignment.
431 * A bound frame may lack a valid exposure interval; navigation uncertainty
432 * is recorded only when a pose is marked valid. */
433static int add_observation_tags(struct exif_document *exif, const struct capture_timing *timing, bool aligned)
434{
435 const struct capture_observation empty = {0};
436 const struct capture_observation *observation = timing ? &timing->observation : &empty;
437 if (!capture_observation_valid(observation) && !observation->frame_bound) observation = &empty;
438 struct exif_value description;
440 || description.format != EXIF_ASCII || description.size > COMPLETE_RECORD_CAPACITY) return -1;
441 char boot[37];
442 usher_boot_id(boot);
443 char *record = (char *)active_workspace->scratch;
444 int length = snprintf(record, COMPLETE_RECORD_CAPACITY,
445 "%.*s; altitude_datum=flight_controller_navigation; capture_pose_synchronized=%s"
446 "; observation_time_kind=%s; observation_pose_aligned=%s; frame_identity_bound=%s"
447 "; observation_earliest_monotonic_us=%" PRIu64 "; observation_latest_monotonic_us=%" PRIu64
448 "; observation_sequence=%" PRIu64 "; sensor_timestamp_ns=%" PRIu64 "; observation_boot_id=%s",
449 (int)description.size, description.data, aligned ? "true" : "false",
450 capture_time_name(observation->kind), observation->pose_valid ? "true" : "false",
451 observation->frame_bound ? "true" : "false",
452 observation->earliest_us, observation->latest_us, observation->sequence, observation->sensor_timestamp_ns, boot);
453 if (length < 0 || (size_t)length >= COMPLETE_RECORD_CAPACITY) return -1;
454 if (observation->pose_valid) {
455 const union dc_shot_union *pose = &observation->pose;
456 if (!isfinite(observation->pose_uncertainty_m) || observation->pose_uncertainty_m < 0) return -1;
457 int extra = snprintf(record + length, COMPLETE_RECORD_CAPACITY - (size_t)length,
458 "; observation_lat_deg=%.7f; observation_lon_deg=%.7f; observation_alt_m=%.3f"
459 "; observation_agl_m=%.3f; observation_roll_deg=%.4f; observation_pitch_deg=%.4f"
460 "; observation_yaw_deg=%.4f; observation_pose_uncertainty_m=%.3f"
461 "; navigation_position_method=%s; navigation_position_age_ms=%" PRIu32,
462 pose->data.lat / 1e7, pose->data.lon / 1e7, pose->data.alt / 1000.0,
465 observation->pose_uncertainty_m,
466 observation->navigation_projected ? "gps_receipt_velocity_projection" : "fc_state_sample",
467 observation->navigation_age_ms);
468 if (extra < 0 || (size_t)extra >= COMPLETE_RECORD_CAPACITY - (size_t)length) return -1;
469 }
471}
472
473int image_exif_write_complete(const char *filename, const union dc_shot_union *shot,
474 double capture_delay_s, int compensate, const struct capture_timing *timing,
475 const union dc_shot_union *request, double uncertainty_m, const char *objects)
476{
477 if (filename == NULL || shot == NULL) {
478 errno = EINVAL;
479 return -1;
480 }
481
483 if (workspace == NULL) {
484 return -1;
485 }
486 struct exif_document *exif = &workspace->document;
487 size_t capture_size = 0;
488 struct exif_view view;
489 if (exif_read_jpeg(filename, workspace->payload, sizeof(workspace->payload), &capture_size) == 0
490 && exif_parse(&view, workspace->payload, capture_size) == 0) {
491 struct exif_value capture;
492 for (size_t field = 0; field < sizeof(image_exif_capture_tags) / sizeof(image_exif_capture_tags[0]); ++field) {
493 if (!exif_get(&view, EXIF_CAMERA, image_exif_capture_tags[field], &capture)) continue;
494 unsigned char *stored = exif_document_reserve(exif, EXIF_CAMERA, image_exif_capture_tags[field],
495 (enum exif_format)capture.format, capture.count);
496 if (!stored) {
498 return -1;
499 }
500 for (size_t index = 0; index < capture.size; ++index) stored[index] = capture.data[index];
501 }
502 }
503 if (timing && capture_timing_valid(timing)) {
505 }
506 if (add_shot_tags(exif, shot, capture_delay_s, request ? 0 : compensate, timing) != 0) {
507 fprintf(stderr, "EXIF:\tfailed to create shot metadata for %s\n", filename);
509 return -1;
510 }
511
512 if (request) {
513 /* Exposure-aligned coordinates improve the geotag, but the original FC
514 * request remains essential when investigating latency or pose errors later. */
515 struct exif_value description;
516 char *record = (char *)active_workspace->scratch;
518 || description.format != EXIF_ASCII || description.size > 1536
519 || !isfinite(uncertainty_m) || uncertainty_m < 0) {
521 return -1;
522 }
523 const int length = snprintf(record, COMPLETE_RECORD_CAPACITY,
524 "%.*s; pose_reference=bounded_sensor_exposure_estimate; pose_uncertainty_m=%.3f"
525 "; request_lat_e7deg=%" PRId32 "; request_lon_e7deg=%" PRId32 "; request_alt_mm=%" PRId32
526 "; request_phi_bfp=%" PRId32 "; request_theta_bfp=%" PRId32 "; request_psi_bfp=%" PRId32
527 "; request_groundalt_bfp=%" PRId32 "; request_vground_bfp=%" PRId32 "; request_course_bfp=%" PRId32,
528 (int)description.size, description.data, uncertainty_m, request->data.lat, request->data.lon, request->data.alt,
529 request->data.phi, request->data.theta, request->data.psi, request->data.groundalt, request->data.vground,
530 request->data.course);
531 if (length < 0 || (size_t)length >= COMPLETE_RECORD_CAPACITY
534 return -1;
535 }
536 }
537 if (add_observation_tags(exif, timing, request != NULL) != 0
538 || set_tagged_comment(exif, objects ? "AICAM_OBJECTS_V1" : "", objects ? objects : "") != 0) {
540 return -1;
541 }
542
543 int result = save_exif(filename, exif);
545 return result;
546}
547
548/** @brief Replace metadata while streaming the original compressed payload unchanged.
549 * @param filename Existing image, exclusively owned by the caller during publication.
550 * @param exif Metadata ownership is consumed on every exit.
551 * @return Zero after replacement, -1 on failure with the original path retained.
552 * @details The temporary sits beside the original so rename stays on one filesystem.
553 * Flush and file sync happen before rename. This helper does not sync the parent
554 * directory, so do not treat success as a complete power-loss durability guarantee.
555 */
556static int save_exif(const char *filename, struct exif_document *exif)
557{
558 if (active_workspace == NULL) {
559 errno = EINVAL;
560 return -1;
561 }
562 struct stat file_status, path_status;
563 FILE *input = fopen(filename, IMAGE_EXIF_ATOMIC_REPLACE ? "rb" : "r+b");
564 int source_result = input == NULL ? -1 : fstat(fileno(input), &file_status);
565 if (source_result == 0) source_result = lstat(filename, &path_status);
566 if (source_result == 0 && (!S_ISREG(file_status.st_mode) || !S_ISREG(path_status.st_mode)
567 || file_status.st_dev != path_status.st_dev || file_status.st_ino != path_status.st_ino)) {
568 errno = EINVAL;
569 source_result = -1;
570 }
571 if (source_result != 0) {
572 fprintf(stderr, "EXIF:\tfailed to open %s: %s\n", filename, strerror(errno));
573 if (input != NULL) {
574 const int saved_errno = errno;
575 fclose(input);
576 errno = saved_errno;
577 }
578 return -1;
579 }
580
581 uint32_t width, height;
582 unsigned components;
583 int metadata_result = exif_jpeg_dimensions(input, &width, &height, &components);
584 if (!metadata_result && components != 1 && components != 3) {
585 errno = EINVAL;
586 metadata_result = -1;
587 }
588 if (!metadata_result) {
590 EXIF_UNDEFINED, 4);
591 if (!configuration) metadata_result = -1;
592 else {
593 configuration[0] = 1;
594 if (components == 3) { configuration[1] = 2; configuration[2] = 3; }
595 }
597 if (!dimension) metadata_result = -1;
598 else exif_encode_long(dimension, width);
600 if (!dimension) metadata_result = -1;
601 else exif_encode_long(dimension, height);
602 }
603 unsigned char *exif_data = active_workspace->payload;
604 size_t exif_size = 0;
605 if (metadata_result != 0 || fseek(input, 0, SEEK_SET) != 0
606 || exif_serialize(exif, exif_data, EXIF_MAX_PAYLOAD, &exif_size) != 0) {
607 const int saved_errno = errno;
608 fclose(input);
609 errno = saved_errno;
610 return -1;
611 }
612
613#if IMAGE_EXIF_ATOMIC_REPLACE
614 int name_length = snprintf(active_workspace->temporary_name, sizeof(active_workspace->temporary_name),
615 "%s.exif.XXXXXX", filename);
616 if (name_length < 0 || (size_t)name_length >= sizeof(active_workspace->temporary_name)) {
617 fclose(input);
618 errno = ENAMETOOLONG;
619 return -1;
620 }
621 char *temporary_name = active_workspace->temporary_name;
622 int temporary_fd = mkstemp(temporary_name);
623 FILE *output = temporary_fd >= 0 ? fdopen(temporary_fd, "wb") : NULL;
624 int result = 0;
625 if (output == NULL || fchmod(temporary_fd, file_status.st_mode & 0777) != 0
626 || exif_rewrite_jpeg(input, output, exif_data, exif_size) != 0
627 || fflush(output) != 0 || fsync(temporary_fd) != 0) {
628 result = -1;
629 }
630 if (fclose(input) != 0) {
631 result = -1;
632 }
633 if (output != NULL && fclose(output) != 0) {
634 result = -1;
635 } else if (output == NULL && temporary_fd >= 0) {
636 close(temporary_fd);
637 }
638
639 if (result == 0) {
640 if (lstat(filename, &path_status) != 0 || !S_ISREG(path_status.st_mode)
641 || file_status.st_dev != path_status.st_dev || file_status.st_ino != path_status.st_ino
642 || file_status.st_size != path_status.st_size
643 || file_status.st_mtim.tv_sec != path_status.st_mtim.tv_sec
644 || file_status.st_mtim.tv_nsec != path_status.st_mtim.tv_nsec) {
645 errno = ESTALE;
646 result = -1;
647 } else if (rename(temporary_name, filename) != 0) {
648 result = -1;
649 }
650 }
651 if (result != 0) {
652 int saved_errno = errno;
653 unlink(temporary_name);
654 fprintf(stderr, "EXIF:\tfailed to update %s: %s\n", filename, strerror(saved_errno));
655 errno = saved_errno;
656 }
657
658 return result;
659#else
660 int result = 0;
661 if (lstat(filename, &path_status) != 0 || !S_ISREG(path_status.st_mode) ||
662 file_status.st_dev != path_status.st_dev || file_status.st_ino != path_status.st_ino ||
663 file_status.st_size != path_status.st_size ||
664 file_status.st_mtim.tv_sec != path_status.st_mtim.tv_sec ||
665 file_status.st_mtim.tv_nsec != path_status.st_mtim.tv_nsec) {
666 errno = ESTALE;
667 result = -1;
668 } else if (exif_update_jpeg(input, exif_data, exif_size) != 0 || fsync(fileno(input)) != 0) {
669 result = -1;
670 } else if (lstat(filename, &path_status) != 0 || !S_ISREG(path_status.st_mode) ||
671 file_status.st_dev != path_status.st_dev || file_status.st_ino != path_status.st_ino) {
672 errno = ESTALE;
673 result = -1;
674 }
675 int saved_errno = errno;
676 if (fclose(input) != 0 && result == 0) {
677 saved_errno = errno;
678 result = -1;
679 }
680 if (result != 0) {
681 fprintf(stderr, "EXIF:\tfailed to update %s in place: %s\n", filename, strerror(saved_errno));
682 errno = saved_errno;
683 }
684 return result;
685#endif
686}
Read Linux's boot-unique identifier for pose-log session provenance.
static void usher_boot_id(char result[37])
Fill a 36-character boot UUID or the stable fallback "unknown".
Definition boot_id.h:36
static double latitude
static double longitude
static bool capture_timing_valid(const struct capture_timing *timing)
Check whether timing evidence is internally consistent and recent.
static bool capture_observation_valid(const struct capture_observation *observation)
Check that an observation supplies a usable time interval.
static const char * capture_time_name(enum capture_time_kind kind)
Get the text label used when recording observation timing.
size_t size
Definition chdk_pipe.c:143
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.
static int record(const union dc_shot_union *shot)
Retrieve a point and admit a new observation only when its credit is free.
union dc_shot_union request
#define ANGLE_BFP_SCALE
#define POSITION_BFP_SCALE
#define RAD_TO_DEG
Definition ear_fusion.c:35
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
void exif_encode_long(unsigned char *data, uint32_t value)
Encode a 32-bit value in the writer's little-endian representation.
Definition exifite.c:106
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
exif_format
TIFF field-type numbers used by Sensoraia's metadata.
Definition exifite.h:64
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
int exif_document_rational(struct exif_document *document, enum exif_directory directory, uint16_t tag, uint32_t numerator, uint32_t denominator)
Store an unsigned measurement as an exact numerator/denominator pair.
Definition exifite.c:572
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_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 exif_document_ascii(struct exif_document *document, enum exif_directory directory, uint16_t tag, const char *text)
Replace an ASCII field, including its terminating NUL byte.
Definition exifite.c:543
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
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_BYTE
Definition exifite.h:65
@ EXIF_LONG
Definition exifite.h:68
@ EXIF_UNDEFINED
Definition exifite.h:70
@ EXIF_RATIONAL
Definition exifite.h:69
@ EXIF_CAMERA
Definition exifite.h:59
@ EXIF_PRIMARY
Definition exifite.h:59
@ EXIF_GPS
Definition exifite.h:59
@ EXIF_GPS_TRACK
Definition exifite.h:111
@ EXIF_GPS_SPEED_REF
Definition exifite.h:108
@ EXIF_GPS_VERSION
Definition exifite.h:101
@ EXIF_COMPONENTS_CONFIGURATION
Definition exifite.h:90
@ EXIF_GPS_ALTITUDE_REF
Definition exifite.h:106
@ EXIF_GPS_DIRECTION_REF
Definition exifite.h:112
@ EXIF_GPS_LATITUDE
Definition exifite.h:103
@ EXIF_DOCUMENT_NAME
Definition exifite.h:79
@ EXIF_GPS_LATITUDE_REF
Definition exifite.h:102
@ EXIF_GPS_SPEED
Definition exifite.h:109
@ EXIF_PIXEL_Y_DIMENSION
Definition exifite.h:97
@ EXIF_GPS_LONGITUDE
Definition exifite.h:105
@ EXIF_GPS_ALTITUDE
Definition exifite.h:107
@ EXIF_PIXEL_X_DIMENSION
Definition exifite.h:96
@ EXIF_GPS_TRACK_REF
Definition exifite.h:110
@ EXIF_IMAGE_DESCRIPTION
Definition exifite.h:80
@ EXIF_SOFTWARE
Definition exifite.h:85
@ EXIF_USER_COMMENT
Definition exifite.h:93
@ EXIF_GPS_LONGITUDE_REF
Definition exifite.h:104
@ EXIF_GPS_DIRECTION
Definition exifite.h:113
static int write_tagged_comment(const char *filename, const char *tag, const char *information)
Compatibility wrapper for analysis that becomes available after the flight EXIF write.
Definition image_exif.c:353
int image_exif_write_hotspots(const char *filename, const char *information)
Append structured thermal hotspot/geolocation evidence to JPEG EXIF.
Definition image_exif.c:372
#define SPEED_BFP_SCALE
Definition image_exif.c:49
static struct exif_workspace * workspace_acquire(void)
Claim a bounded EXIF editing slot for the current thread.
Definition image_exif.c:73
int image_exif_write_timed(const char *filename, const union dc_shot_union *shot, double capture_delay_s, int compensate)
Add flight metadata with optional capture-delay motion compensation.
Definition image_exif.c:413
static double normalized_degrees(int32_t angle_bfp)
Convert a flight-controller heading to the EXIF angular range.
Definition image_exif.c:172
int image_exif_write_complete(const char *filename, const union dc_shot_union *shot, double capture_delay_s, int compensate, const struct capture_timing *timing, const union dc_shot_union *request, double uncertainty_m, const char *objects)
Write flight provenance and an available object-detection result in one metadata transaction.
Definition image_exif.c:473
#define ASCII_COMMENT_PREFIX_SIZE
Definition image_exif.c:52
static int add_observation_tags(struct exif_document *exif, const struct capture_timing *timing, bool aligned)
Extend the flight description with observation provenance.
Definition image_exif.c:433
static uint32_t scaled_unsigned(double value, double scale)
Form a nonnegative numerator for an EXIF rational.
Definition image_exif.c:184
static int set_tagged_comment(struct exif_document *exif, const char *tag, const char *information)
Write an EXIF UserComment composed of flight and analysis records.
Definition image_exif.c:321
static int add_shot_tags(struct exif_document *exif, const union dc_shot_union *original, double delay, int compensate, const struct capture_timing *timing)
Add GPS fields and the flight-pose description to an editable document.
Definition image_exif.c:203
static void workspace_release(struct exif_workspace *workspace)
Return an editing slot to the shared pool.
Definition image_exif.c:98
#define COMPLETE_RECORD_CAPACITY
Definition image_exif.c:56
static _Thread_local struct exif_workspace * active_workspace
Definition image_exif.c:67
int image_exif_write_capture(const char *filename, const union dc_shot_union *shot, double capture_delay_s, int compensate, const struct capture_timing *timing)
Add flight metadata using authoritative capture timing when available.
Definition image_exif.c:419
#define EXIF_SCRATCH_CAPACITY
Definition image_exif.c:54
#define SHOT_COMMENT_CAPACITY
Definition image_exif.c:55
#define EXIF_WORKSPACE_COUNT
Definition image_exif.c:53
static int save_exif(const char *filename, struct exif_document *exif)
Replace metadata while streaming the original compressed payload unchanged.
Definition image_exif.c:556
int image_exif_write_object_detections(const char *filename, const char *information)
Append structured object-detection evidence (AICam) to JPEG EXIF.
Definition image_exif.c:377
static int set_coordinate(struct exif_document *exif, uint16_t reference_tag, uint16_t coordinate_tag, int32_t coordinate, int32_t limit, char positive, char negative)
Encode one signed GPS coordinate as EXIF hemisphere and DMS tags.
Definition image_exif.c:135
int image_exif_write(const char *filename, const union dc_shot_union *shot)
Add standard USHER flight metadata to a JPEG.
Definition image_exif.c:408
static struct exif_workspace exif_workspaces[EXIF_WORKSPACE_COUNT]
Definition image_exif.c:66
int image_exif_write_mock_map(const char *filename, double horizontal_fov, double vertical_fov)
Label a synthetic map fixture with its geometry and provider-neutral XYZ tile scheme.
Definition image_exif.c:382
static struct exif_document * load_exif(const char *filename)
Import an existing JPEG EXIF block into the active editing slot.
Definition image_exif.c:112
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
#define IMAGE_EXIF_ATOMIC_REPLACE
Select sibling-file atomic replacement instead of the default in-place update.
Definition image_exif.h:70
static const uint16_t image_exif_capture_tags[]
Application-owned opaque evidence retained by photo metadata updates.
Definition image_exif.h:35
static struct image_mock_workspace workspace
static double capture_delay_s
struct exif_document exif
Definition lwir_image.c:64
Advance a position along ground velocity by a bounded elapsed interval.
static int compensate_ground_position(int32_t *latitude, int32_t *longitude, double speed, double course, double delay)
Correct latitude/longitude for horizontal platform motion during capture.
#define PATH_MAX
Definition path_utils.h:39
static char boot_id[37]
Definition pose_log.c:84
static FILE * output
Definition pose_log.c:77
enum capture_time_kind kind
union dc_shot_union pose
Shared observation evidence with optional LWIR request/frame-delivery timing.
uint64_t callback_drops
struct capture_observation observation
uint64_t request_monotonic_us
uint64_t arrival_monotonic_us
uint64_t callback_sequence
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
char temporary_name[PATH_MAX]
Definition image_exif.c:60
struct exif_document document
Definition image_exif.c:63
atomic_bool in_use
Definition image_exif.c:59
unsigned char scratch[EXIF_SCRATCH_CAPACITY]
Definition image_exif.c:61
unsigned char payload[EXIF_MAX_PAYLOAD]
Definition image_exif.c:62
struct dc_shot_union::@351207206061007345226276304225222200157171312155 data
struct usher_control_result result
Definition usher.c:377
union dc_shot_union shot
Definition usher.c:534