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
exifite.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 exifite.c
20 * @brief Allocation-free EXIF parsing, serialization and bounded JPEG streaming.
21 * @details The implementation keeps three jobs separate: validate borrowed TIFF
22 * bytes, collect caller-owned values, then stream JPEG markers around a serialized
23 * APP1 payload. That separation lets us check each boundary without allocating
24 * image-sized buffers or interpreting manufacturer-specific pointer structures.
25 * @see exifite.h for public contracts and storage ownership.
26 */
27
28#include "exifite.h"
29
30#include <errno.h>
31#include <limits.h>
32#include <stdio.h>
33#include <string.h>
34#include <sys/stat.h>
35#include <unistd.h>
36
37/** @brief Standard primary-IFD link to the camera/EXIF directory. */
38#define EXIF_CAMERA_POINTER 0x8769U
39/** @brief Standard primary-IFD link to the GPS directory. */
40#define EXIF_GPS_POINTER 0x8825U
41/** @brief Bounds validation work and its stack-based duplicate-tag table.
42 * @details Input may contain more fields than our writer, but cannot demand
43 * unbounded memory or quadratic validation work from the embedded board. */
44#define EXIF_MAX_INPUT_ENTRIES 256U
45
46/** @brief Fixed TIFF layout widths, expressed separately from JPEG framing. */
47#define TIFF_HEADER_SIZE 8U
48/** @brief Bytes occupied by one TIFF directory entry. */
49#define TIFF_ENTRY_SIZE 12U
50/** @brief Maximum TIFF value length stored directly in a directory entry. */
51#define TIFF_INLINE_SIZE 4U
52/** @brief Bytes occupied by a TIFF directory's entry count. */
53#define TIFF_DIRECTORY_COUNT_SIZE 2U
54/** @brief Bytes occupied by the next-directory link after an entry table. */
55#define TIFF_DIRECTORY_NEXT_SIZE 4U
56/** @brief Limit on JPEG header segments inspected before reaching image data. */
57#define JPEG_MAX_HEADER_SEGMENTS 1024U
58/** @brief Limit on ordinary JPEG header segment bytes inspected. */
59#define JPEG_MAX_HEADER_BYTES (4U * 1024U * 1024U)
60/** @brief Read-ahead capacity independent of image dimensions. */
61#define JPEG_STREAM_CAPACITY 8192U
62
63/** @brief APP1 identifier; its terminators are part of the on-disk signature. */
64static const unsigned char exif_signature[] = {'E', 'x', 'i', 'f', 0, 0};
65
66/** @brief Use one predictable error for invalid arguments and malformed values.
67 * @return Always -1, after setting errno to EINVAL.
68 */
69static int invalid(void)
70{
71 errno = EINVAL;
72 return -1;
73}
74
75/** @brief Read two already-checked bytes without alignment or host-endian assumptions.
76 * @param[in] data At least two accessible bytes.
77 * @param[in] little True for little-endian TIFF, false for big-endian TIFF.
78 * @return Decoded unsigned 16-bit value.
79 */
80static uint16_t read_short(const unsigned char *data, bool little)
81{
82 return little ? (uint16_t)((uint16_t)data[0] | (uint16_t)data[1] << 8)
83 : (uint16_t)((uint16_t)data[0] << 8 | data[1]);
84}
85
86/** @brief Read four checked bytes; casts precede shifts to avoid signed promotion.
87 * @param[in] data At least four accessible bytes.
88 * @param[in] little Byte order declared by the input TIFF header.
89 * @return Decoded unsigned 32-bit value.
90 */
91static uint32_t read_long(const unsigned char *data, bool little)
92{
93 return little ? (uint32_t)data[0] | (uint32_t)data[1] << 8 | (uint32_t)data[2] << 16 |
94 (uint32_t)data[3] << 24
95 : (uint32_t)data[0] << 24 | (uint32_t)data[1] << 16 | (uint32_t)data[2] << 8 |
96 (uint32_t)data[3];
97}
98
99void exif_encode_short(unsigned char *data, uint16_t value)
100{
101 /* Reserved storage may be unaligned; byte stores also keep host byte order irrelevant. */
102 data[0] = (unsigned char)value;
103 data[1] = (unsigned char)(value >> 8);
104}
105
106void exif_encode_long(unsigned char *data, uint32_t value)
107{
108 for (size_t index = 0; index < 4; ++index) {
109 data[index] = (unsigned char)(value >> (index * 8));
110 }
111}
112
113/** @brief Map TIFF's numbered representations to their component byte widths.
114 * @param[in] format On-disk TIFF type identifier.
115 * @return Component width, or zero for an unsupported type.
116 * @details The table includes ordinary TIFF types beyond our named enum values
117 * so unknown but structurally valid input fields can be checked and then ignored.
118 */
119static size_t format_size(uint16_t format)
120{
121 static const unsigned char sizes[] = {0, 1, 1, 2, 4, 8, 1, 1, 2, 4, 8, 4, 8};
122 return format < sizeof(sizes) ? sizes[format] : 0;
123}
124
125/** @brief Check a byte span without forming a potentially overflowing end offset.
126 * @param[in] total Accessible bytes in the enclosing storage.
127 * @param[in] offset Proposed starting offset.
128 * @param[in] length Proposed span length.
129 * @return True when the entire span fits.
130 * @details Check the start first; only then is the subtraction safe. Keep this
131 * order when extending the parser with another field or pointer check.
132 */
133static bool range(size_t total, size_t offset, size_t length)
134{
135 return offset <= total && length <= total - offset;
136}
137
138/** @brief Detect caller-buffer aliasing without adding lengths to addresses.
139 * @param[in] first First storage address.
140 * @param[in] first_size First storage length in bytes.
141 * @param[in] second Second storage address.
142 * @param[in] second_size Second storage length in bytes.
143 * @return True for overlapping nonempty spans.
144 * @details Address differences avoid wraparound at the end of an address space.
145 * This uses the flat uintptr_t address representation of our Linux targets.
146 */
147static bool overlaps(const void *first, size_t first_size, const void *second, size_t second_size)
148{
149 if (!first_size || !second_size) {
150 return false;
151 }
152 const uintptr_t first_address = (uintptr_t)first;
153 const uintptr_t second_address = (uintptr_t)second;
154 return first_address <= second_address ? second_address - first_address < first_size
155 : first_address - second_address < second_size;
156}
157
158/** @brief Resolve one TIFF entry into checked, borrowed value bytes.
159 * @param[in] view TIFF storage and declared byte order.
160 * @param[in] offset TIFF-relative offset of the twelve-byte directory entry.
161 * @param[out] value Field descriptor; use only when validation succeeds.
162 * @return True for a supported, fully accessible representation.
163 * @details TIFF stores values of at most four bytes directly in the entry;
164 * larger values use an offset relative to the TIFF header. Count validation
165 * precedes multiplication, so an untrusted component count cannot overflow.
166 */
167static bool entry_value(const struct exif_view *view, size_t offset, struct exif_value *value)
168{
169 if (!range(view->size, offset, TIFF_ENTRY_SIZE)) {
170 return false;
171 }
172 const unsigned char *entry = view->tiff + offset;
173 const uint16_t format = read_short(entry + 2, view->little_endian);
174 const size_t unit = format_size(format);
175 const uint32_t count = read_long(entry + 4, view->little_endian);
176 if (!unit || !count || count > view->size / unit) {
177 return false;
178 }
179 const size_t size = unit * count;
180 /* The last four entry bytes are either the value itself or its TIFF-relative offset. */
181 const size_t location =
182 size <= TIFF_INLINE_SIZE ? offset + 8 : read_long(entry + 8, view->little_endian);
183 if ((size > TIFF_INLINE_SIZE && location < TIFF_HEADER_SIZE) ||
184 !range(view->size, location, size)) {
185 return false;
186 }
187 *value = (struct exif_value){.data = view->tiff + location,
188 .size = size,
189 .count = count,
190 .format = format,
191 .little_endian = view->little_endian};
192 if (format == EXIF_ASCII && value->data[size - 1] != 0) {
193 return false;
194 }
195 if (format == EXIF_RATIONAL || format == EXIF_SRATIONAL) {
196 for (size_t index = 0; index < count; ++index) {
197 if (read_long(value->data + index * 8 + 4, view->little_endian) == 0) {
198 return false;
199 }
200 }
201 }
202 return true;
203}
204
205/** @brief Validate one bounded IFD and discover the two supported child links.
206 * @param[in,out] view Candidate view; primary-directory links fill child offsets.
207 * @param[in] directory Directory identity to validate.
208 * @return True for an absent directory or a valid directory table and its values.
209 * @details Duplicate tags are ambiguous, so reject them rather than let readers
210 * disagree over which value wins. A small bounded scan avoids heap-backed sets
211 * and does not assume that camera entries arrive sorted.
212 */
213static bool validate_directory(struct exif_view *view, enum exif_directory directory)
214{
215 const size_t offset = view->directories[directory];
216 if (!offset) {
217 return true;
218 }
219 if (offset < TIFF_HEADER_SIZE || !range(view->size, offset, TIFF_DIRECTORY_COUNT_SIZE)) {
220 return false;
221 }
222 const size_t count = read_short(view->tiff + offset, view->little_endian);
224 !range(view->size, offset + TIFF_DIRECTORY_COUNT_SIZE,
226 return false;
227 }
228 uint16_t tags[EXIF_MAX_INPUT_ENTRIES];
229 for (size_t index = 0; index < count; ++index) {
230 const size_t entry = offset + TIFF_DIRECTORY_COUNT_SIZE + index * TIFF_ENTRY_SIZE;
231 const uint16_t tag = read_short(view->tiff + entry, view->little_endian);
232 for (size_t previous = 0; previous < index; ++previous) {
233 if (tags[previous] == tag) {
234 return false;
235 }
236 }
237 tags[index] = tag;
238 struct exif_value value;
239 if (!entry_value(view, entry, &value)) {
240 return false;
241 }
242 if (tag == EXIF_CAMERA_POINTER || tag == EXIF_GPS_POINTER) {
243 /* Only primary-IFD child links are followed; nested/vendor graphs stay out of scope. */
244 if (directory != EXIF_PRIMARY || value.format != EXIF_LONG || value.count != 1) {
245 return false;
246 }
247 const uint32_t target = read_long(value.data, view->little_endian);
248 if (target < TIFF_HEADER_SIZE) {
249 return false;
250 }
251 view->directories[tag == EXIF_CAMERA_POINTER ? EXIF_CAMERA : EXIF_GPS] = target;
252 }
253 }
254 return true;
255}
256
257int exif_parse(struct exif_view *view, const unsigned char *payload, size_t size)
258{
259 if (!view) {
260 return invalid();
261 }
262 *view = (struct exif_view){0};
263 if (!payload || size < sizeof(exif_signature) + TIFF_HEADER_SIZE || size > EXIF_MAX_PAYLOAD ||
264 memcmp(payload, exif_signature, sizeof(exif_signature)) != 0) {
265 return invalid();
266 }
267 const unsigned char *tiff = payload + sizeof(exif_signature);
268 const bool little = tiff[0] == 'I' && tiff[1] == 'I';
269 if ((!little && !(tiff[0] == 'M' && tiff[1] == 'M')) || read_short(tiff + 2, little) != 42) {
270 return invalid();
271 }
272 /* Publish only after every supported table is checked; failure leaves no partial view. */
273 struct exif_view candidate = {.tiff = tiff,
274 .size = size - sizeof(exif_signature),
275 .directories = {read_long(tiff + 4, little), 0, 0},
276 .little_endian = little};
277 if (candidate.directories[EXIF_PRIMARY] < TIFF_HEADER_SIZE) {
278 return invalid();
279 }
280 for (size_t index = 0; index < EXIF_DIRECTORY_COUNT; ++index) {
281 if (!validate_directory(&candidate, (enum exif_directory)index)) {
282 return invalid();
283 }
284 }
285 /* Distinct directory identities must not reinterpret overlapping table bytes. */
286 for (size_t index = 0; index < EXIF_DIRECTORY_COUNT; ++index) {
287 if (!candidate.directories[index]) {
288 continue;
289 }
290 const size_t count = read_short(tiff + candidate.directories[index], little);
291 const size_t extent =
293 for (size_t other = 0; other < index; ++other) {
294 if (!candidate.directories[other]) {
295 continue;
296 }
297 const size_t other_count = read_short(tiff + candidate.directories[other], little);
298 const size_t other_extent =
300 if (candidate.directories[index] < candidate.directories[other] + other_extent &&
301 candidate.directories[other] < candidate.directories[index] + extent) {
302 return invalid();
303 }
304 }
305 }
306 *view = candidate;
307 return 0;
308}
309
310bool exif_get(const struct exif_view *view, enum exif_directory directory, uint16_t tag,
311 struct exif_value *value)
312{
313 if (!value) {
314 return false;
315 }
316 *value = (struct exif_value){0};
317 if (!view || !view->tiff || (unsigned)directory >= EXIF_DIRECTORY_COUNT) {
318 return false;
319 }
320 const size_t offset = view->directories[directory];
321 if (!offset || !range(view->size, offset, TIFF_DIRECTORY_COUNT_SIZE)) {
322 return false;
323 }
324 const size_t count = read_short(view->tiff + offset, view->little_endian);
326 !range(view->size, offset + TIFF_DIRECTORY_COUNT_SIZE,
328 return false;
329 }
330 for (size_t index = 0; index < count; ++index) {
331 const size_t entry = offset + TIFF_DIRECTORY_COUNT_SIZE + index * TIFF_ENTRY_SIZE;
332 if (read_short(view->tiff + entry, view->little_endian) == tag) {
333 return entry_value(view, entry, value);
334 }
335 }
336 return false;
337}
338
339bool exif_value_unsigned(const struct exif_value *value, size_t index, uint32_t *result)
340{
341 if (!value || !value->data || !result || index >= value->count) {
342 return false;
343 }
344 switch (value->format) {
345 case EXIF_BYTE:
346 if (index >= value->size) {
347 return false;
348 }
349 *result = value->data[index];
350 break;
351
352 case EXIF_SHORT:
353 if (index >= value->size / 2) {
354 return false;
355 }
356 *result = read_short(value->data + index * 2, value->little_endian);
357 break;
358
359 case EXIF_LONG:
360 if (index >= value->size / 4) {
361 return false;
362 }
363 *result = read_long(value->data + index * 4, value->little_endian);
364 break;
365
366 default:
367 return false;
368 }
369 return true;
370}
371
372/** @brief Interpret a TIFF signed component without an implementation-defined cast.
373 * @param[in] value Unsigned bit representation of a 32-bit signed integer.
374 * @return Its signed mathematical value, exactly representable as a double.
375 * @details Subtracting 2^32 handles negative values, including INT32_MIN, without
376 * signed overflow. This keeps signed rational handling portable between compilers.
377 */
378static double signed_long(uint32_t value)
379{
380 return value <= INT32_MAX ? (double)value : (double)value - 4294967296.0;
381}
382
383bool exif_value_rational(const struct exif_value *value, size_t index, double *result)
384{
385 if (!value || !value->data || !result || index >= value->count || index >= value->size / 8 ||
386 (value->format != EXIF_RATIONAL && value->format != EXIF_SRATIONAL)) {
387 return false;
388 }
389 const uint32_t numerator = read_long(value->data + index * 8, value->little_endian);
390 const uint32_t denominator = read_long(value->data + index * 8 + 4, value->little_endian);
391 if (!denominator) {
392 return false;
393 }
394 *result = value->format == EXIF_SRATIONAL ? signed_long(numerator) / signed_long(denominator)
395 : (double)numerator / denominator;
396 return true;
397}
398
399size_t exif_text_length(const struct exif_value *value)
400{
401 if (!value || !value->data || (value->format != EXIF_ASCII && value->format != EXIF_UNDEFINED)) {
402 return 0;
403 }
404 size_t size = value->size;
405 /* Trim only the end: UserComment's encoding prefix contains meaningful embedded NULs. */
406 while (size && value->data[size - 1] == 0) {
407 --size;
408 }
409 return size;
410}
411
412void exif_document_init(struct exif_document *document)
413{
414 if (!document) {
415 return;
416 }
417 document->count = 0;
418 document->used = 0;
419 /* These fixed defaults fit an empty document by construction. Clear only the
420 * active bookkeeping; reservations initialize the bytes we actually expose. */
421 unsigned char *data =
423 exif_encode_short(data, 1);
427 exif_encode_short(data, 2);
429 data[0] = '0';
430 data[1] = '2';
431 data[2] = '3';
432 data[3] = '2';
434 data[0] = '0';
435 data[1] = '1';
436 data[2] = '0';
437 data[3] = '0';
439 4);
440 data[0] = 1;
441 data[1] = 2;
442 data[2] = 3;
444 exif_encode_short(data, 1);
445}
446
447bool exif_document_get(const struct exif_document *document, enum exif_directory directory,
448 uint16_t tag, struct exif_value *value)
449{
450 if (!value) {
451 return false;
452 }
453 *value = (struct exif_value){0};
454 if (!document || document->count > EXIF_MAX_ENTRIES || document->used > sizeof(document->data) ||
455 (unsigned)directory >= EXIF_DIRECTORY_COUNT) {
456 return false;
457 }
458 for (size_t index = 0; index < document->count; ++index) {
459 const struct exif_item *entry = &document->entries[index];
460 if (entry->directory == directory && entry->tag == tag &&
461 range(document->used, entry->offset, entry->size)) {
462 *value = (struct exif_value){.data = document->data + entry->offset,
463 .size = entry->size,
464 .count = entry->count,
465 .format = entry->format,
466 .little_endian = true};
467 return true;
468 }
469 }
470 return false;
471}
472
473int exif_document_remove(struct exif_document *document, enum exif_directory directory,
474 uint16_t tag)
475{
476 if (!document || document->count > EXIF_MAX_ENTRIES || document->used > sizeof(document->data) ||
477 (unsigned)directory >= EXIF_DIRECTORY_COUNT) {
478 return invalid();
479 }
480 for (size_t index = 0; index < document->count; ++index) {
481 const struct exif_item entry = document->entries[index];
482 if (entry.directory != directory || entry.tag != tag) {
483 continue;
484 }
485 if (!range(document->used, entry.offset, entry.size)) {
486 return invalid();
487 }
488 /* Forward copying is safe because each source byte lies above its destination.
489 * Reclaiming holes lets repeated metadata updates reuse the same fixed buffer. */
490 for (size_t position = entry.offset; position < document->used - entry.size; ++position) {
491 document->data[position] = document->data[position + entry.size];
492 }
493 document->used -= entry.size;
494 for (size_t other = 0; other < document->count; ++other) {
495 if (document->entries[other].offset > entry.offset) {
496 document->entries[other].offset -= entry.size;
497 }
498 }
499 for (size_t other = index; other + 1 < document->count; ++other) {
500 document->entries[other] = document->entries[other + 1];
501 }
502 --document->count;
503 break;
504 }
505 return 0;
506}
507
508unsigned char *exif_document_reserve(struct exif_document *document, enum exif_directory directory,
509 uint16_t tag, enum exif_format format, uint32_t count)
510{
511 const size_t unit = format_size((uint16_t)format);
512 if (!document || (unsigned)directory >= EXIF_DIRECTORY_COUNT || !unit || !count ||
514 document->count > EXIF_MAX_ENTRIES || document->used > sizeof(document->data)) {
515 invalid();
516 return NULL;
517 }
518 const size_t size = unit * count;
519 struct exif_value previous;
520 const bool replacing = exif_document_get(document, directory, tag, &previous);
521 /* Account for the old value before removing it: a full document can still
522 * replace a field, and a capacity error must not erase the old value. */
523 if ((!replacing && document->count == EXIF_MAX_ENTRIES) ||
524 size > sizeof(document->data) - document->used + (replacing ? previous.size : 0)) {
525 errno = ENOSPC;
526 return NULL;
527 }
528 if (exif_document_remove(document, directory, tag) != 0) {
529 return NULL;
530 }
531 unsigned char *data = document->data + document->used;
532 document->entries[document->count++] = (struct exif_item){.offset = (uint32_t)document->used,
533 .size = (uint32_t)size,
534 .count = count,
535 .tag = tag,
536 .format = (uint16_t)format,
537 .directory = (unsigned char)directory};
538 document->used += size;
539 memset(data, 0, size);
540 return data;
541}
542
543int exif_document_ascii(struct exif_document *document, enum exif_directory directory, uint16_t tag,
544 const char *text)
545{
546 if (!document || !text || overlaps(document, sizeof(*document), text, 1)) {
547 return invalid();
548 }
549 /* Never scan into the document and then compact that same storage while copying. */
550 size_t length = 0;
551 while (length < EXIF_MAX_PAYLOAD && text[length]) {
552 ++length;
553 }
554 if (length == EXIF_MAX_PAYLOAD) {
555 errno = ENOSPC;
556 return -1;
557 }
558 if (overlaps(document, sizeof(*document), text, length + 1)) {
559 return invalid();
560 }
561 unsigned char *data =
562 exif_document_reserve(document, directory, tag, EXIF_ASCII, (uint32_t)length + 1);
563 if (!data) {
564 return -1;
565 }
566 for (size_t index = 0; index < length; ++index) {
567 data[index] = (unsigned char)text[index];
568 }
569 return 0;
570}
571
572int exif_document_rational(struct exif_document *document, enum exif_directory directory,
573 uint16_t tag, uint32_t numerator, uint32_t denominator)
574{
575 if (!denominator) {
576 return invalid();
577 }
578 unsigned char *data = exif_document_reserve(document, directory, tag, EXIF_RATIONAL, 1);
579 if (!data) {
580 return -1;
581 }
582 exif_encode_long(data, numerator);
583 exif_encode_long(data + 4, denominator);
584 return 0;
585}
586
587/** @brief Select standard fields retained by the default import policy.
588 * @param[in] directory Directory containing the field.
589 * @param[in] tag Directory-local tag identifier.
590 * @return True when the field belongs in an imported writer document.
591 * @details Byte-for-byte copying is not enough for vendor records with private
592 * offsets. An explicit allowlist keeps imports small and avoids pretending to
593 * preserve structures we neither interpret nor need. Defaults are rebuilt separately.
594 */
595static bool supported(enum exif_directory directory, uint16_t tag)
596{
597 if (directory == EXIF_PRIMARY) {
598 return tag == EXIF_DOCUMENT_NAME || tag == EXIF_IMAGE_DESCRIPTION || tag == EXIF_ORIENTATION ||
599 tag == EXIF_SOFTWARE;
600 }
601 if (directory == EXIF_CAMERA) {
602 return tag == EXIF_EXPOSURE_TIME || tag == EXIF_FNUMBER || tag == EXIF_EXPOSURE_BIAS ||
605 }
606 return tag <= EXIF_GPS_ALTITUDE || (tag >= EXIF_GPS_SPEED_REF && tag <= EXIF_GPS_DIRECTION);
607}
608
609/** @brief Copy supported fields from one directory into writer storage.
610 * @param[in,out] document Initialized destination document.
611 * @param[in] view Source bytes and input byte order.
612 * @param[in] directory Directory whose fields should be imported.
613 * @param[in] select Optional caller selection for additional fields.
614 * @param[in] context Borrowed selection state.
615 * @return True on success, false when the caller must reset the partial import.
616 * @details Keeping rollback in the public wrapper makes this routine responsible
617 * only for traversal and byte-order conversion, not document lifecycle.
618 */
619static bool import_directory(struct exif_document *document, const struct exif_view *view,
620 enum exif_directory directory, exif_tag_selector select, void *context)
621{
622 const size_t offset = view->directories[directory];
623 if (offset == 0) {
624 return true;
625 }
626 if (!range(view->size, offset, TIFF_DIRECTORY_COUNT_SIZE)) {
627 return false;
628 }
629
630 const size_t count = read_short(view->tiff + offset, view->little_endian);
632 !range(view->size, offset + TIFF_DIRECTORY_COUNT_SIZE,
634 return false;
635 }
636
637 for (size_t index = 0; index < count; ++index) {
638 const size_t location = offset + TIFF_DIRECTORY_COUNT_SIZE + index * TIFF_ENTRY_SIZE;
639 const uint16_t tag = read_short(view->tiff + location, view->little_endian);
640 if (!supported(directory, tag) && (!select || !select(context, directory, tag))) {
641 continue;
642 }
643
644 struct exif_value value;
645 if (!entry_value(view, location, &value)) {
646 return false;
647 }
648
649 unsigned char *data = exif_document_reserve(document, directory, tag,
650 (enum exif_format)value.format, value.count);
651 if (data == NULL) {
652 return false;
653 }
654
655 size_t unit = format_size(value.format);
656 /* A rational contains two 32-bit integers. Reverse each integer, not the
657 * whole eight-byte pair, or numerator and denominator would trade places. */
658 if (value.format == EXIF_RATIONAL || value.format == EXIF_SRATIONAL) {
659 unit = 4;
660 }
661 for (size_t position = 0; position < value.size; ++position) {
662 const size_t source = !value.little_endian && unit > 1
663 ? position / unit * unit + unit - 1 - position % unit
664 : position;
665 data[position] = value.data[source];
666 }
667 }
668 return true;
669}
670
671int exif_document_import_custom(struct exif_document *document, const struct exif_view *view,
672 exif_tag_selector select, void *context)
673{
674 if (!document || !view || !view->tiff || view->size > EXIF_MAX_PAYLOAD - sizeof(exif_signature) ||
675 overlaps(document, sizeof(*document), view->tiff, view->size) ||
676 overlaps(document, sizeof(*document), view, sizeof(*view))) {
677 return invalid();
678 }
679 exif_document_init(document);
680 for (size_t directory = 0; directory < EXIF_DIRECTORY_COUNT; ++directory) {
681 if (!import_directory(document, view, (enum exif_directory)directory, select, context)) {
682 /* A failed import must not leave a plausible-looking half-copied record. */
683 exif_document_init(document);
684 return invalid();
685 }
686 }
687 return 0;
688}
689
690int exif_document_import(struct exif_document *document, const struct exif_view *view)
691{
692 return exif_document_import_custom(document, view, NULL, NULL);
693}
694
695/** @brief Validate a writer field before calculating offsets or touching output.
696 * @param[in] document Source document whose storage has already been bounded.
697 * @param[in] entry Field descriptor to check against that storage.
698 * @return True when the representation can be serialized safely.
699 */
700static bool valid_document_entry(const struct exif_document *document,
701 const struct exif_item *entry)
702{
703 const size_t unit = format_size(entry->format);
704 if (entry->directory >= EXIF_DIRECTORY_COUNT || unit == 0 || entry->count == 0 ||
705 entry->count > EXIF_MAX_PAYLOAD / unit || entry->size != unit * entry->count ||
706 !range(document->used, entry->offset, entry->size) || entry->tag == EXIF_CAMERA_POINTER ||
707 entry->tag == EXIF_GPS_POINTER) {
708 return false;
709 }
710
711 const unsigned char *data = document->data + entry->offset;
712 if (entry->format == EXIF_ASCII && data[entry->size - 1] != 0) {
713 return false;
714 }
715 if (entry->format == EXIF_RATIONAL || entry->format == EXIF_SRATIONAL) {
716 for (size_t component = 0; component < entry->count; ++component) {
717 if (read_long(data + component * 8 + 4, true) == 0) {
718 return false;
719 }
720 }
721 }
722 return true;
723}
724
725/** @brief Compare the wire ordering of two directory-local fields.
726 * @param[in] first Candidate field.
727 * @param[in] second Field currently ahead of the candidate.
728 * @return True when the candidate belongs before the existing field.
729 */
730static bool entry_precedes(const struct exif_item *first, const struct exif_item *second)
731{
732 return first->directory < second->directory ||
733 (first->directory == second->directory && first->tag < second->tag);
734}
735
736int exif_serialize(const struct exif_document *document, unsigned char *payload, size_t capacity,
737 size_t *size)
738{
739 /* Check the size-output alias before clearing it; it could otherwise corrupt
740 * the document we are about to validate. Ordinary failures report zero bytes. */
741 if (!size || (document && overlaps(document, sizeof(*document), size, sizeof(*size))) ||
742 (payload && overlaps(payload, capacity, size, sizeof(*size)))) {
743 return invalid();
744 }
745 *size = 0;
746 if (!document || !payload || document->count > EXIF_MAX_ENTRIES ||
747 document->used > sizeof(document->data) ||
748 overlaps(document, sizeof(*document), payload, capacity)) {
749 return invalid();
750 }
751 size_t counts[EXIF_DIRECTORY_COUNT] = {0};
752 size_t order[EXIF_MAX_ENTRIES];
753 /* First pass: validate and sort only indices. The caller's document stays
754 * unchanged, and the small entry budget makes insertion sort inexpensive. */
755 for (size_t index = 0; index < document->count; ++index) {
756 const struct exif_item *entry = &document->entries[index];
757 if (!valid_document_entry(document, entry)) {
758 return invalid();
759 }
760 ++counts[entry->directory];
761 size_t position = index;
762 while (position && entry_precedes(entry, &document->entries[order[position - 1]])) {
763 order[position] = order[position - 1];
764 --position;
765 }
766 order[position] = index;
767 if (position && document->entries[order[position - 1]].directory == entry->directory &&
768 document->entries[order[position - 1]].tag == entry->tag) {
769 return invalid();
770 }
771 }
772 counts[EXIF_PRIMARY] += (counts[EXIF_CAMERA] ? 1U : 0U) + (counts[EXIF_GPS] ? 1U : 0U);
773 /* Reserve the TIFF header and all directory tables before placing value bytes.
774 * Directory links are generated here, never accepted as caller-provided values. */
775 size_t offsets[EXIF_DIRECTORY_COUNT] = {TIFF_HEADER_SIZE, 0, 0};
776 size_t extent = TIFF_HEADER_SIZE;
777 for (size_t directory = 0; directory < EXIF_DIRECTORY_COUNT; ++directory) {
778 if (directory && !counts[directory]) {
779 continue;
780 }
781 offsets[directory] = extent;
782 extent +=
784 }
785
786 for (size_t index = 0; index < document->count; ++index) {
787 if (document->entries[index].size > TIFF_INLINE_SIZE) {
788 extent += document->entries[index].size + (document->entries[index].size & 1U);
789 }
790 }
791 if (extent > EXIF_MAX_PAYLOAD - sizeof(exif_signature) ||
792 capacity < extent + sizeof(exif_signature)) {
793 errno = ENOSPC;
794 return -1;
795 }
796 /* Only now touch output. Zeroing supplies next-IFD terminators, unused inline
797 * value bytes and padding without leaking old workspace contents into photos. */
798 memset(payload, 0, extent + sizeof(exif_signature));
799 for (size_t index = 0; index < sizeof(exif_signature); ++index) {
800 payload[index] = exif_signature[index];
801 }
802 unsigned char *tiff = payload + sizeof(exif_signature);
803 tiff[0] = 'I';
804 tiff[1] = 'I';
805 exif_encode_short(tiff + 2, 42);
807 size_t cursors[EXIF_DIRECTORY_COUNT];
808 size_t tail = TIFF_HEADER_SIZE;
809 for (size_t directory = 0; directory < EXIF_DIRECTORY_COUNT; ++directory) {
810 cursors[directory] = offsets[directory] + TIFF_DIRECTORY_COUNT_SIZE;
811 if (directory && !counts[directory]) {
812 continue;
813 }
814 exif_encode_short(tiff + offsets[directory], (uint16_t)counts[directory]);
815 tail +=
817 }
818 for (size_t index = 0; index < document->count; ++index) {
819 const struct exif_item *entry = &document->entries[order[index]];
820 unsigned char *output = tiff + cursors[entry->directory];
821 cursors[entry->directory] += TIFF_ENTRY_SIZE;
823 exif_encode_short(output + 2, entry->format);
824 exif_encode_long(output + 4, entry->count);
825 unsigned char *destination = output + 8;
826 if (entry->size > TIFF_INLINE_SIZE) {
827 /* External values start on two-byte boundaries; padding is already zero. */
828 exif_encode_long(output + 8, (uint32_t)tail);
829 destination = tiff + tail;
830 tail += entry->size + (entry->size & 1U);
831 }
832 for (size_t position = 0; position < entry->size; ++position) {
833 destination[position] = document->data[entry->offset + position];
834 }
835 }
836
838 if (!counts[directory]) {
839 continue;
840 }
841 unsigned char *entry = tiff + cursors[EXIF_PRIMARY];
842 cursors[EXIF_PRIMARY] += TIFF_ENTRY_SIZE;
844 exif_encode_short(entry + 2, EXIF_LONG);
845 exif_encode_long(entry + 4, 1);
846 exif_encode_long(entry + 8, (uint32_t)offsets[directory]);
847 }
848 /* Child pointers were appended after ordinary entries. Sort the primary table
849 * again so those generated tags obey TIFF ordering even for custom high tags. */
850 for (size_t index = 1; index < counts[EXIF_PRIMARY]; ++index) {
851 unsigned char saved[TIFF_ENTRY_SIZE];
852 const size_t origin =
854 for (size_t byte = 0; byte < TIFF_ENTRY_SIZE; ++byte) {
855 saved[byte] = tiff[origin + byte];
856 }
857 size_t position = index;
858 while (position && read_short(tiff + offsets[EXIF_PRIMARY] + TIFF_DIRECTORY_COUNT_SIZE +
859 (position - 1) * TIFF_ENTRY_SIZE,
860 true) > read_short(saved, true)) {
861 const size_t target =
863 for (size_t byte = 0; byte < TIFF_ENTRY_SIZE; ++byte) {
864 tiff[target + byte] = tiff[target - TIFF_ENTRY_SIZE + byte];
865 }
866 --position;
867 }
868 for (size_t byte = 0; byte < TIFF_ENTRY_SIZE; ++byte) {
869 tiff[offsets[EXIF_PRIMARY] + TIFF_DIRECTORY_COUNT_SIZE + position * TIFF_ENTRY_SIZE + byte] =
870 saved[byte];
871 }
872 }
873
874 *size = extent + sizeof(exif_signature);
875 return 0;
876}
877
878/** @brief Read an entire declared span or report truncation.
879 * @param[in,out] input Readable stream at the span's first byte.
880 * @param[out] buffer Storage for at least @p size bytes.
881 * @param[in] size Exact byte count required.
882 * @return True only when every requested byte was read.
883 */
884static bool read_exact(FILE *input, unsigned char *buffer, size_t size)
885{
886 return fread(buffer, 1, size, input) == size;
887}
888
889/** @brief Consume unwanted bytes without trusting a seek past end-of-file.
890 * @param[in,out] input Readable stream positioned before the unwanted span.
891 * @param[in] size Bytes that must actually exist.
892 * @return True after consuming the span, false for a short read.
893 * @details A seek can succeed beyond EOF; reading bounded chunks makes a truncated
894 * JPEG segment fail instead of hiding the missing bytes from the header parser.
895 */
896static bool skip_exact(FILE *input, size_t size)
897{
898 unsigned char buffer[1024];
899 while (size) {
900 const size_t chunk = size < sizeof(buffer) ? size : sizeof(buffer);
901 if (!read_exact(input, buffer, chunk)) {
902 return false;
903 }
904 size -= chunk;
905 }
906 return true;
907}
908
909/** @brief Extract the unique EXIF payload from a caller-owned JPEG stream.
910 * @param[in,out] input Readable stream at start-of-image; not closed here.
911 * @param[out] payload Destination for the selected APP1 payload.
912 * @param[in] capacity Writable payload capacity in bytes.
913 * @param[out] size Selected payload length; the public wrapper clears it on failure.
914 * @return Zero on success, otherwise -1 with errno describing the parse failure.
915 * @details Ownership stays with the wrapper so every parse exit can be a plain
916 * return, while file closing and error preservation remain in one place.
917 */
918static int read_exif_stream(FILE *input, unsigned char *payload, size_t capacity, size_t *size)
919{
920 unsigned char header[2];
921 bool found = false;
922 if (!read_exact(input, header, 2) || header[0] != 0xff || header[1] != 0xd8) {
923 return invalid();
924 }
925
926 size_t inspected = 2;
927 /* Metadata lives before the first scan. Bound header work rather than walking
928 * an arbitrarily large file when a malformed producer never supplies a scan. */
929 for (size_t segments = 0; segments < JPEG_MAX_HEADER_SEGMENTS; ++segments) {
930 const int prefix = fgetc(input);
931 if (prefix != 0xff) return invalid();
932 int marker = fgetc(input);
933 if (marker == EOF) {
934 return invalid();
935 }
936 size_t fill = 0;
937 while (marker == 0xff) {
938 if (++fill > EXIF_MAX_PAYLOAD) {
939 return invalid();
940 }
941 marker = fgetc(input);
942 }
943
944 if (marker == EOF || marker == 0 || marker == 0xd8 || (marker >= 0xd0 && marker <= 0xd7)) {
945 return invalid();
946 }
947 if (marker == 0xd9) {
948 if (found) {
949 return 0;
950 }
951 errno = ENODATA;
952 return -1;
953 }
954
955 if (marker == 1) {
956 continue;
957 }
958 if (!read_exact(input, header, 2)) {
959 return invalid();
960 }
961 const size_t length = (size_t)header[0] * 256 + header[1];
962 if (length < 2) {
963 return invalid();
964 }
965 inspected += length + 2;
966 if (inspected > JPEG_MAX_HEADER_BYTES) {
967 errno = EFBIG;
968 return -1;
969 }
970 const size_t remaining = length - 2;
971 unsigned char signature[sizeof(exif_signature)];
972 if (marker == 0xe1 && remaining >= sizeof(signature)) {
973 if (!read_exact(input, signature, sizeof(signature))) {
974 return invalid();
975 }
976 if (memcmp(signature, exif_signature, sizeof(signature)) == 0) {
977 /* A second EXIF record is ambiguous; keep callers from silently mixing records. */
978 if (found) {
979 return invalid();
980 }
981 if (remaining > capacity) {
982 errno = ENOSPC;
983 return -1;
984 }
985 for (size_t index = 0; index < sizeof(signature); ++index) {
986 payload[index] = signature[index];
987 }
988 if (!read_exact(input, payload + sizeof(signature), remaining - sizeof(signature))) {
989 return invalid();
990 }
991 *size = remaining;
992 found = true;
993 } else if (!skip_exact(input, remaining - sizeof(signature))) {
994 return invalid();
995 }
996 } else if (!skip_exact(input, remaining)) {
997 return invalid();
998 }
999 if (marker == 0xda) {
1000 if (remaining < 4) {
1001 return invalid();
1002 }
1003 if (found) {
1004 return 0;
1005 }
1006 errno = ENODATA;
1007 return -1;
1008 }
1009 }
1010 return invalid();
1011}
1012
1013int exif_read_stream(FILE *input, unsigned char *payload, size_t capacity, size_t *size)
1014{
1015 if (!input || !payload || !size || overlaps(payload, capacity, size, sizeof(*size))) return invalid();
1016 *size = 0;
1017 const int result = read_exif_stream(input, payload, capacity, size);
1018 if (result) *size = 0;
1019 return result;
1020}
1021
1022int exif_read_jpeg(const char *filename, unsigned char *payload, size_t capacity, size_t *size)
1023{
1024 if (size != NULL) {
1025 *size = 0;
1026 }
1027 if (filename == NULL || payload == NULL || size == NULL) {
1028 return invalid();
1029 }
1030
1031 FILE *input = fopen(filename, "rb");
1032 if (input == NULL) {
1033 return -1;
1034 }
1035
1036 int result = exif_read_stream(input, payload, capacity, size);
1037 if (result != 0 && ferror(input)) {
1038 errno = EIO;
1039 }
1040 /* Preserve the parse/read error across successful cleanup, but report a real
1041 * close failure rather than returning a payload whose I/O did not finish cleanly. */
1042 const int saved_errno = errno;
1043 if (fclose(input) != 0) {
1044 result = -1;
1045 } else if (result != 0) {
1046 errno = saved_errno;
1047 }
1048 if (result != 0) {
1049 *size = 0;
1050 }
1051 return result;
1052}
1053
1054/** @brief Original-file interval occupied by one discarded EXIF segment. */
1056 off_t start; /**< First marker fill byte, inclusive. */
1057 off_t end; /**< First byte after the payload, exclusive. */
1058};
1059
1060/** @brief Bounded edit list produced by the same parser used for streaming rewrites.
1061 * @details Only offsets are retained, never image data. Rejecting an excessive
1062 * number of EXIF segments before mutation prevents input-controlled storage growth.
1063 */
1065 off_t insertion; /**< Replacement location after leading JFIF/APP0 segments. */
1066 size_t count; /**< Number of ordered, nonoverlapping removal intervals. */
1067 struct jpeg_removal removals[JPEG_MAX_HEADER_SEGMENTS]; /**< Original EXIF spans. */
1068};
1069
1070/** @brief One bounded read-ahead buffer shared by JPEG inspection and rewriting.
1071 * @details Cursor-based consumption lets entropy runs be copied in chunks rather
1072 * than one stdio call per image byte. NULL output makes preflight write-free.
1073 */
1075 FILE *input; /**< Caller-owned source consumed through the read-ahead buffer. */
1076 FILE *output; /**< Destination, or NULL for inspection and validation-only walks. */
1077 struct jpeg_edit_plan *plan; /**< Optional edit offsets collected without output. */
1078 size_t position; /**< Cursor of the next unread byte in the buffer. */
1079 size_t size; /**< Number of valid bytes currently in the buffer. */
1081 unsigned char
1082 buffer[JPEG_STREAM_CAPACITY]; /**< Fixed workspace, independent of image dimensions. */
1083};
1084
1085/** @brief Refill only after buffered bytes have been consumed.
1086 * @param[in,out] stream Read-ahead state.
1087 * @return True when at least one byte remains, false on EOF or read error.
1088 * @details Callers distinguish EOF from I/O failure with ferror() where needed.
1089 */
1090static bool stream_fill(struct jpeg_stream *stream)
1091{
1092 if (stream->position < stream->size) {
1093 return true;
1094 }
1095 if (ferror(stream->input) || feof(stream->input)) return false;
1096 stream->size = fread(stream->buffer, 1, sizeof(stream->buffer), stream->input);
1097 stream->position = 0;
1098 return stream->size != 0;
1099}
1100
1101/** @brief Read a marker/header byte while preserving buffered cursor ownership.
1102 * @param[in,out] stream Read-ahead state.
1103 * @return Next unsigned byte as an int, or EOF when no byte is available.
1104 */
1105static int stream_byte(struct jpeg_stream *stream)
1106{
1107 return stream_fill(stream) ? stream->buffer[stream->position++] : EOF;
1108}
1109
1110/** @brief Share byte emission between real rewrites and write-free validation.
1111 * @param[in,out] stream Parser state with optional output.
1112 * @param[in] data Bytes to emit only when an output exists.
1113 * @param[in] size Accessible byte count.
1114 * @return True on complete emission or validation-only traversal.
1115 */
1116static bool stream_write(struct jpeg_stream *stream, const unsigned char *data, size_t size)
1117{
1118 return stream->output == NULL || fwrite(data, 1, size, stream->output) == size;
1119}
1120
1121/** @brief Emit one framing byte, or do nothing during preflight.
1122 * @param[in,out] stream Parser state with optional output.
1123 * @param[in] byte Byte value to emit.
1124 * @return True on successful emission or validation-only traversal.
1125 */
1126static bool stream_put_byte(struct jpeg_stream *stream, int byte)
1127{
1128 return stream->output == NULL || fputc(byte, stream->output) != EOF;
1129}
1130
1131/** @brief Recover the logical offset rather than the read-ahead descriptor offset.
1132 * @param[in] stream Parser state for a seekable regular file.
1133 * @return Offset of the next unconsumed byte, or -1 on a positioning error.
1134 */
1135static off_t stream_offset(const struct jpeg_stream *stream)
1136{
1137 const off_t position = ftello(stream->input);
1138 return position < 0 ? -1 : position - (off_t)(stream->size - stream->position);
1139}
1140
1141/** @brief Copy or discard exactly one declared span in bounded chunks.
1142 * @param[in,out] stream Input cursor and optional writable output stream.
1143 * @param[in] size Bytes to consume; short input is an error.
1144 * @param[in] emit True to write bytes, false to discard an old EXIF segment.
1145 * @return True after consuming the full span, false on read/write failure.
1146 * @details Both paths consume existing read-ahead first, so changing from marker
1147 * parsing to bulk copying never loses or reads the same bytes twice.
1148 */
1149static bool stream_copy(struct jpeg_stream *stream, size_t size, bool emit)
1150{
1151 while (size) {
1152 if (!stream_fill(stream)) {
1153 return false;
1154 }
1155 size_t chunk = stream->size - stream->position;
1156 if (chunk > size) {
1157 chunk = size;
1158 }
1159 if (emit && !stream_write(stream, stream->buffer + stream->position, chunk)) {
1160 return false;
1161 }
1162 stream->position += chunk;
1163 size -= chunk;
1164 }
1165 return true;
1166}
1167
1168/** @brief Emit a marker together with its original fill-byte count.
1169 * @param[in,out] stream State containing a writable output stream.
1170 * @param[in] count Number of leading 0xff bytes, including the marker prefix.
1171 * @param[in] marker Marker code, or stuffed zero when copying scan data.
1172 * @return True when all bytes were written.
1173 * @details Retaining legal fill bytes avoids unnecessary changes to unrelated
1174 * JPEG framing while replacement EXIF gets its own single-prefix marker.
1175 */
1176static bool marker_prefix(struct jpeg_stream *stream, size_t count, int marker)
1177{
1178 if (stream->output == NULL) {
1179 return true;
1180 }
1181 for (size_t index = 0; index < count; ++index) {
1182 if (fputc(0xff, stream->output) == EOF) {
1183 return false;
1184 }
1185 }
1186 return fputc(marker, stream->output) != EOF;
1187}
1188
1189/** @brief Find a structural marker, optionally copying preceding entropy bytes.
1190 * @param[in,out] stream Buffered cursor; entropy mode requires a writable output.
1191 * @param[in] entropy True inside a scan, false between marker segments.
1192 * @param[out] prefix Marker-prefix/fill count for the caller to retain or discard.
1193 * @param[out] marker Structural marker code, not yet emitted.
1194 * @return True on a marker, false on malformed framing or I/O failure.
1195 * @details Inside scans, 0xff/0x00 is a stuffed data byte and restart markers
1196 * do not end the scan. Handle these here so the rewrite loop sees only markers
1197 * whose segments it must inspect. Prefix reads may cross buffer boundaries.
1198 */
1199static bool stream_marker(struct jpeg_stream *stream, bool entropy, size_t *prefix, int *marker)
1200{
1201 for (;;) {
1202 if (entropy) {
1203 if (!stream_fill(stream)) {
1204 return false;
1205 }
1206 const size_t start = stream->position;
1207 while (stream->position < stream->size && stream->buffer[stream->position] != 0xff) {
1208 ++stream->position;
1209 }
1210 const size_t length = stream->position - start;
1211 if (!stream_write(stream, stream->buffer + start, length)) {
1212 return false;
1213 }
1214 if (stream->position == stream->size) {
1215 continue;
1216 }
1217 }
1218 if (stream_byte(stream) != 0xff) {
1219 return false;
1220 }
1221 *prefix = 1;
1222 do {
1223 *marker = stream_byte(stream);
1224 if (*marker == 0xff && ++*prefix > EXIF_MAX_PAYLOAD) {
1225 return false;
1226 }
1227 } while (*marker == 0xff);
1228 if (*marker == EOF) {
1229 return false;
1230 }
1231 if (entropy && (*marker == 0 || *marker == 1 || (*marker >= 0xd0 && *marker <= 0xd7))) {
1232 if (!marker_prefix(stream, *prefix, *marker)) {
1233 return false;
1234 }
1235 continue;
1236 }
1237 return *marker != 0;
1238 }
1239}
1240
1241/** @brief Recognize SOF markers while excluding other codes in the same range.
1242 * @param[in] marker JPEG marker code without its 0xff prefix.
1243 * @return True for a start-of-frame marker.
1244 * @details DHT, JPG and DAC share the 0xc0..0xcf range but do not carry dimensions.
1245 */
1246static bool frame_marker(int marker)
1247{
1248 return marker >= 0xc0 && marker <= 0xcf && marker != 0xc4 && marker != 0xc8 && marker != 0xcc;
1249}
1250
1251/** @brief Read a short fixed-size header across read-ahead buffer boundaries.
1252 * @param[in,out] stream Buffered source state.
1253 * @param[out] data Storage for at least the requested byte count.
1254 * @param[in] size Exact byte count to read.
1255 * @return True when the complete header was available.
1256 */
1257static bool stream_read(struct jpeg_stream *stream, unsigned char *data, size_t size)
1258{
1259 for (size_t index = 0; index < size; ++index) {
1260 const int byte = stream_byte(stream);
1261 if (byte == EOF) {
1262 return false;
1263 }
1264 data[index] = (unsigned char)byte;
1265 }
1266 return true;
1267}
1268
1269/** @brief Read and validate the common six-byte start-of-frame header.
1270 * @param[in,out] stream Source cursor immediately after the segment length.
1271 * @param[in] payload_size Full frame payload length, including component descriptors.
1272 * @param[out] header Precision, height, width and component count bytes.
1273 * @return True for the bounded frame representation supported by this module.
1274 * @details Inspection and rewriting use the same checks so they cannot disagree
1275 * about which dimensions or component counts are safe to publish.
1276 */
1277static bool stream_frame_header(struct jpeg_stream *stream, size_t payload_size,
1278 unsigned char header[6])
1279{
1280 if (payload_size < 6 || !stream_read(stream, header, 6)) {
1281 return false;
1282 }
1283
1284 const uint32_t height = (uint32_t)header[1] * 256 + header[2];
1285 const uint32_t width = (uint32_t)header[3] * 256 + header[4];
1286 const unsigned components = header[5];
1287
1288 return header[0] > 0 && header[0] <= 16 && width > 0 && height > 0 && components > 0 &&
1289 components <= 4 && payload_size == 6U + 3U * components;
1290}
1291
1292/** @brief Emit a segment prefix and its two-byte big-endian JPEG length.
1293 * @param[in,out] stream State containing a writable output stream.
1294 * @param[in] prefix Number of prefix/fill bytes to preserve.
1295 * @param[in] marker Segment marker code.
1296 * @param[in] payload_size Segment bytes excluding the two length bytes.
1297 * @return True when the complete framing was written.
1298 * @pre Payload length is already bounded by the JPEG segment limit.
1299 */
1300static bool stream_segment_header(struct jpeg_stream *stream, size_t prefix, int marker,
1301 size_t payload_size)
1302{
1303 const size_t length = payload_size + 2;
1304 return marker_prefix(stream, prefix, marker) &&
1305 stream_put_byte(stream, (int)(length >> 8)) &&
1306 stream_put_byte(stream, (int)(length & 255));
1307}
1308
1309int exif_jpeg_dimensions(FILE *input, uint32_t *width, uint32_t *height, unsigned *components)
1310{
1311 if (!input || !width || !height || !components) {
1312 return invalid();
1313 }
1314 *width = 0;
1315 *height = 0;
1316 *components = 0;
1317 /* Read the frame's own dimensions; pre-existing EXIF may describe another image. */
1318 struct jpeg_stream stream = {.input = input};
1319 if (stream_byte(&stream) != 0xff || stream_byte(&stream) != 0xd8) {
1320 return invalid();
1321 }
1322 size_t inspected = 2;
1323 for (size_t segment = 0; segment < JPEG_MAX_HEADER_SEGMENTS; ++segment) {
1324 int marker;
1325 size_t prefix;
1326 if (!stream_marker(&stream, false, &prefix, &marker) || marker == 0xda || marker == 0xd9 ||
1327 marker == 0xd8 || (marker >= 0xd0 && marker <= 0xd7)) {
1328 return invalid();
1329 }
1330 inspected += prefix + 1;
1331 if (marker == 1) {
1332 continue;
1333 }
1334 const int high = stream_byte(&stream);
1335 const int low = stream_byte(&stream);
1336 if (high == EOF || low == EOF) {
1337 return invalid();
1338 }
1339 const size_t length = (size_t)high * 256 + (unsigned)low;
1340 if (length < 2) {
1341 return invalid();
1342 }
1343 inspected += length;
1344 if (inspected > JPEG_MAX_HEADER_BYTES) {
1345 errno = EFBIG;
1346 return -1;
1347 }
1348 size_t remaining = length - 2;
1349 if (frame_marker(marker)) {
1350 unsigned char header[6];
1351 if (!stream_frame_header(&stream, remaining, header) ||
1352 !stream_copy(&stream, remaining - 6, false)) {
1353 return invalid();
1354 }
1355 const uint32_t frame_width = (uint32_t)header[3] * 256 + header[4];
1356 const uint32_t frame_height = (uint32_t)header[1] * 256 + header[2];
1357 *width = frame_width;
1358 *height = frame_height;
1359 *components = header[5];
1360 return 0;
1361 }
1362 if (!stream_copy(&stream, remaining, false)) {
1363 return invalid();
1364 }
1365 }
1366 errno = EFBIG;
1367 return -1;
1368}
1369
1370/** @brief Rewrite JPEG framing using caller-owned streams and validated EXIF.
1371 * @param[in,out] stream Buffered source and destination state.
1372 * @param[in] payload Validated replacement APP1 bytes.
1373 * @param[in] size Replacement payload length.
1374 * @return True after a complete frame/scan/EOI stream, false on framing or I/O failure.
1375 * @details This routine owns no resources. Early returns keep the scan-state
1376 * transitions visible; the public wrapper supplies one error-classification path.
1377 */
1378static bool rewrite_jpeg_stream(struct jpeg_stream *stream, const unsigned char *payload,
1379 size_t size)
1380{
1381 bool exif_written = false;
1382 bool inside_scan = false;
1383 bool frame_seen = false;
1384 bool scan_seen = false;
1385
1386 if (stream_byte(stream) != 0xff || stream_byte(stream) != 0xd8 ||
1387 !marker_prefix(stream, 1, 0xd8)) {
1388 return false;
1389 }
1390
1391 for (;;) {
1392 size_t prefix;
1393 int marker;
1394 if (!stream_marker(stream, inside_scan, &prefix, &marker)) {
1395 return false;
1396 }
1397 inside_scan = false;
1398 if (marker == 0xd8 || (marker >= 0xd0 && marker <= 0xd7)) {
1399 return false;
1400 }
1401
1402 off_t marker_start = 0;
1403 if (stream->plan != NULL) {
1404 const off_t position = stream_offset(stream);
1405 if (position < 0 || (uintmax_t)position < prefix + 1) {
1406 return false;
1407 }
1408 marker_start = position - (off_t)(prefix + 1);
1409 }
1410
1411 if (!exif_written && marker != 0xe0) {
1412 if (stream->plan != NULL) {
1413 stream->plan->insertion = marker_start;
1414 }
1415 /* Leave leading APP0/JFIF segments first, then publish exactly one EXIF APP1. */
1416 if (!stream_segment_header(stream, 1, 0xe1, size) ||
1417 !stream_write(stream, payload, size)) {
1418 return false;
1419 }
1420 exif_written = true;
1421 }
1422
1423 if (marker == 0xd9) {
1424 /* Reaching EOF is not enough: require a frame, a scan and an actual EOI.
1425 * Bytes after EOI may carry another application's data, so retain them. */
1426 if (!frame_seen || !scan_seen || !marker_prefix(stream, prefix, marker)) {
1427 return false;
1428 }
1429 while (stream_fill(stream)) {
1430 if (!stream_copy(stream, stream->size - stream->position, true)) {
1431 return false;
1432 }
1433 }
1434 return !ferror(stream->input) && (stream->output == NULL || !ferror(stream->output));
1435 }
1436
1437 if (marker == 1) {
1438 if (!marker_prefix(stream, prefix, marker)) {
1439 return false;
1440 }
1441 continue;
1442 }
1443
1444 const int high = stream_byte(stream);
1445 const int low = stream_byte(stream);
1446 if (high == EOF || low == EOF) {
1447 return false;
1448 }
1449 const size_t length = (size_t)high * 256 + (unsigned)low;
1450 if (length < 2) {
1451 return false;
1452 }
1453
1454 const size_t remaining = length - 2;
1455 unsigned char signature[6];
1456 size_t inspected = 0;
1457 if (marker == 0xe1 && remaining >= sizeof(signature)) {
1458 if (!stream_read(stream, signature, sizeof(signature))) {
1459 return false;
1460 }
1461 inspected = sizeof(signature);
1462 if (memcmp(signature, exif_signature, sizeof(exif_signature)) == 0) {
1463 /* APP1 also carries XMP. Drop only the exact EXIF signature, not every APP1. */
1464 if (!stream_copy(stream, remaining - inspected, false)) {
1465 return false;
1466 }
1467 if (stream->plan != NULL) {
1468 struct jpeg_edit_plan *plan = stream->plan;
1469 if (plan->count == JPEG_MAX_HEADER_SEGMENTS) {
1470 stream->error = EFBIG;
1471 errno = EFBIG;
1472 return false;
1473 }
1474 const off_t end = stream_offset(stream);
1475 if (end < marker_start) {
1476 return false;
1477 }
1478 plan->removals[plan->count++] = (struct jpeg_removal){marker_start, end};
1479 }
1480 continue;
1481 }
1482 }
1483
1484 if (!stream_segment_header(stream, prefix, marker, remaining) ||
1485 (inspected != 0 && !stream_write(stream, signature, inspected))) {
1486 return false;
1487 }
1488
1489 if (frame_marker(marker)) {
1490 /* This is framing validation, not a JPEG decoder. One bounded frame covers
1491 * our camera files; hierarchical and delayed-height streams are out of scope. */
1492 if (frame_seen || !stream_frame_header(stream, remaining, signature) ||
1493 !stream_write(stream, signature, sizeof(signature))) {
1494 return false;
1495 }
1496 inspected = sizeof(signature);
1497 frame_seen = true;
1498 }
1499
1500 if (marker == 0xda) {
1501 const int components = stream_byte(stream);
1502 if (!frame_seen || components < 1 || components > 4 ||
1503 remaining != 4U + 2U * (unsigned)components || !stream_put_byte(stream, components)) {
1504 return false;
1505 }
1506 inspected = 1;
1507 inside_scan = true;
1508 scan_seen = true;
1509 }
1510
1511 /* The next iteration may return another SOS, as in a progressive JPEG. */
1512 if (!stream_copy(stream, remaining - inspected, true)) {
1513 return false;
1514 }
1515 }
1516}
1517
1518int exif_rewrite_jpeg(FILE *input, FILE *output, const unsigned char *payload, size_t size)
1519{
1520 struct exif_view view;
1521 /* Validate replacement metadata before touching the output. Original EXIF
1522 * bodies need only correct segment framing: they are being discarded anyway. */
1523 if (input == NULL || output == NULL || input == output || exif_parse(&view, payload, size) != 0) {
1524 return invalid();
1525 }
1526
1527 struct jpeg_stream stream = {.input = input, .output = output};
1528 if (!rewrite_jpeg_stream(&stream, payload, size)) {
1529 errno = ferror(input) || ferror(output) ? EIO : EINVAL;
1530 return -1;
1531 }
1532 return 0;
1533}
1534
1535/** @brief Move one retained interval without overwriting its unread source bytes.
1536 * @param[in] descriptor Open read/write regular file.
1537 * @param[in] start Original interval start, inclusive.
1538 * @param[in] end Original interval end, exclusive.
1539 * @param[in] displacement Signed destination offset relative to the source.
1540 * @return Zero on success, otherwise -1 with errno set.
1541 * @details Growth copies backward; shrinkage copies forward. Positional I/O avoids
1542 * stream seeks per block. Short transfers and EINTR are handled without assuming
1543 * that one system call completes the block. A zero-byte transfer is an I/O error.
1544 */
1545static int relocate_jpeg_range(int descriptor, off_t start, off_t end, off_t displacement)
1546{
1547 if (start < 0 || end < start) {
1548 return invalid();
1549 }
1550 unsigned char buffer[JPEG_STREAM_CAPACITY];
1551 while (start < end) {
1552 const uintmax_t remaining = (uintmax_t)end - (uintmax_t)start;
1553 const size_t chunk = remaining > sizeof(buffer) ? sizeof(buffer) : (size_t)remaining;
1554 const off_t source = displacement > 0 ? end - (off_t)chunk : start;
1555 size_t transferred = 0;
1556 while (transferred < chunk) {
1557 const size_t requested = chunk - transferred;
1558 if (requested > sizeof(buffer) || transferred >= sizeof(buffer) ||
1559 requested > sizeof(buffer) - transferred) {
1560 errno = EIO;
1561 return -1;
1562 }
1563 const ssize_t count = pread(descriptor, buffer + transferred, requested,
1564 source + (off_t)transferred);
1565 if (count < 0 && errno == EINTR) {
1566 continue;
1567 }
1568 if (count <= 0 || (size_t)count > requested) {
1569 if (count >= 0) errno = EIO;
1570 return -1;
1571 }
1572 transferred += (size_t)count;
1573 }
1574 transferred = 0;
1575 while (transferred < chunk) {
1576 const size_t requested = chunk - transferred;
1577 if (requested > sizeof(buffer) || transferred >= sizeof(buffer) ||
1578 requested > sizeof(buffer) - transferred) {
1579 errno = EIO;
1580 return -1;
1581 }
1582 const ssize_t count = pwrite(descriptor, buffer + transferred, requested,
1583 source + displacement + (off_t)transferred);
1584 if (count < 0 && errno == EINTR) {
1585 continue;
1586 }
1587 if (count <= 0 || (size_t)count > requested) {
1588 if (count >= 0) errno = EIO;
1589 return -1;
1590 }
1591 transferred += (size_t)count;
1592 }
1593 if (displacement > 0) {
1594 end -= (off_t)chunk;
1595 } else {
1596 start += (off_t)chunk;
1597 }
1598 }
1599 return 0;
1600}
1601
1602/** @brief Move only the spans whose final positions differ from their originals.
1603 * @param[in] descriptor Open read/write regular file.
1604 * @param[in] plan Validated ordered removal intervals and insertion location.
1605 * @param[in] original_size Original file size, including bytes after EOI.
1606 * @param[in] inserted_size Replacement segment size, including marker and length.
1607 * @param[in] backwards True for right-shifted spans, false for left-shifted spans.
1608 * @return Zero on success, otherwise -1 with errno set.
1609 * @details After the one insertion, displacement only decreases as old EXIF is
1610 * removed. Right-shifted spans therefore precede left-shifted spans. Copying the
1611 * former from the end and the latter from the start protects every unread span,
1612 * even when EXIF occurs between progressive scans and displacement changes sign.
1613 * Zero-displacement spans need no writes; this is the cheap repeated-update path.
1614 */
1616 off_t original_size, off_t inserted_size, bool backwards)
1617{
1618 off_t removed_size = 0;
1619 if (backwards) {
1620 for (size_t index = 0; index < plan->count; ++index) {
1621 removed_size += plan->removals[index].end - plan->removals[index].start;
1622 }
1623 }
1624 off_t start = plan->insertion;
1625 off_t end = original_size;
1626 for (size_t step = 0; step <= plan->count; ++step) {
1627 const size_t index = backwards ? plan->count - step : step;
1628 if (backwards) {
1629 start = index == 0 ? plan->insertion : plan->removals[index - 1].end;
1630 } else {
1631 end = index == plan->count ? original_size : plan->removals[index].start;
1632 }
1633 const off_t displacement = inserted_size - removed_size;
1634 if (((backwards && displacement > 0) || (!backwards && displacement < 0)) &&
1635 relocate_jpeg_range(descriptor, start, end, displacement) != 0) {
1636 return -1;
1637 }
1638 if (index < plan->count && !backwards) {
1639 removed_size += plan->removals[index].end - plan->removals[index].start;
1640 start = plan->removals[index].end;
1641 } else if (index > 0 && backwards) {
1642 removed_size -= plan->removals[index - 1].end - plan->removals[index - 1].start;
1643 end = plan->removals[index - 1].start;
1644 }
1645 }
1646 return 0;
1647}
1648
1649int exif_update_jpeg(FILE *file, const unsigned char *payload, size_t size)
1650{
1651 struct exif_view view;
1652 if (file == NULL || exif_parse(&view, payload, size) != 0) {
1653 return invalid();
1654 }
1655 struct stat original;
1656 if (fstat(fileno(file), &original) != 0) {
1657 return -1;
1658 }
1659 if (!S_ISREG(original.st_mode) || original.st_size < 0 || ftello(file) != 0) {
1660 return invalid();
1661 }
1662 struct jpeg_edit_plan plan = {0};
1663 struct jpeg_stream stream = {.input = file, .plan = &plan};
1664 errno = 0;
1665 if (!rewrite_jpeg_stream(&stream, payload, size)) {
1666 errno = stream.error ? stream.error : ferror(file) ? EIO : EINVAL;
1667 return -1;
1668 }
1669 struct stat current;
1670 if (fstat(fileno(file), &current) != 0) {
1671 return -1;
1672 }
1673 if (original.st_size != current.st_size || original.st_mtim.tv_sec != current.st_mtim.tv_sec ||
1674 original.st_mtim.tv_nsec != current.st_mtim.tv_nsec || ftello(file) != original.st_size) {
1675 errno = ESTALE;
1676 return -1;
1677 }
1678 off_t removed_size = 0;
1679 for (size_t index = 0; index < plan.count; ++index) {
1680 removed_size += plan.removals[index].end - plan.removals[index].start;
1681 }
1682 const off_t retained_size = original.st_size - removed_size;
1683 const uintmax_t offset_max = (UINTMAX_C(1) << (sizeof(off_t) * CHAR_BIT - 1)) - 1;
1684 const off_t inserted_size = (off_t)(size + 4);
1685 if ((uintmax_t)retained_size > offset_max - (uintmax_t)inserted_size) {
1686 errno = EOVERFLOW;
1687 return -1;
1688 }
1689 const off_t final_size = retained_size + inserted_size;
1690 if (fseeko(file, 0, SEEK_SET) != 0) {
1691 return -1;
1692 }
1693 if (final_size > original.st_size && ftruncate(fileno(file), final_size) != 0) {
1694 return -1;
1695 }
1696 if (relocate_jpeg_spans(fileno(file), &plan, original.st_size, inserted_size, true) != 0 ||
1697 relocate_jpeg_spans(fileno(file), &plan, original.st_size, inserted_size, false) != 0) {
1698 return -1;
1699 }
1700 const unsigned char header[] = {0xff, 0xe1, (unsigned char)((size + 2) >> 8),
1701 (unsigned char)(size + 2)};
1702 if (fseeko(file, plan.insertion, SEEK_SET) != 0 ||
1703 fwrite(header, 1, sizeof(header), file) != sizeof(header) ||
1704 fwrite(payload, 1, size, file) != size || fflush(file) != 0) {
1705 return -1;
1706 }
1707 return final_size < original.st_size ? ftruncate(fileno(file), final_size) : 0;
1708}
static unsigned capacity[COVERAGE_CAMERAS]
size_t size
Definition chdk_pipe.c:143
int descriptor
Definition chdk_pipe.c:142
static bool start(uint32_t session)
Admit a nonzero session and discard correlation from the previous one.
static bool stream_segment_header(struct jpeg_stream *stream, size_t prefix, int marker, size_t payload_size)
Emit a segment prefix and its two-byte big-endian JPEG length.
Definition exifite.c:1300
static bool rewrite_jpeg_stream(struct jpeg_stream *stream, const unsigned char *payload, size_t size)
Rewrite JPEG framing using caller-owned streams and validated EXIF.
Definition exifite.c:1378
static size_t format_size(uint16_t format)
Map TIFF's numbered representations to their component byte widths.
Definition exifite.c:119
#define EXIF_CAMERA_POINTER
Standard primary-IFD link to the camera/EXIF directory.
Definition exifite.c:38
static bool read_exact(FILE *input, unsigned char *buffer, size_t size)
Read an entire declared span or report truncation.
Definition exifite.c:884
static int relocate_jpeg_range(int descriptor, off_t start, off_t end, off_t displacement)
Move one retained interval without overwriting its unread source bytes.
Definition exifite.c:1545
static uint32_t read_long(const unsigned char *data, bool little)
Read four checked bytes; casts precede shifts to avoid signed promotion.
Definition exifite.c:91
static bool validate_directory(struct exif_view *view, enum exif_directory directory)
Validate one bounded IFD and discover the two supported child links.
Definition exifite.c:213
static int stream_byte(struct jpeg_stream *stream)
Read a marker/header byte while preserving buffered cursor ownership.
Definition exifite.c:1105
static off_t stream_offset(const struct jpeg_stream *stream)
Recover the logical offset rather than the read-ahead descriptor offset.
Definition exifite.c:1135
static bool valid_document_entry(const struct exif_document *document, const struct exif_item *entry)
Validate a writer field before calculating offsets or touching output.
Definition exifite.c:700
#define JPEG_MAX_HEADER_SEGMENTS
Limit on JPEG header segments inspected before reaching image data.
Definition exifite.c:57
static bool overlaps(const void *first, size_t first_size, const void *second, size_t second_size)
Detect caller-buffer aliasing without adding lengths to addresses.
Definition exifite.c:147
static uint16_t read_short(const unsigned char *data, bool little)
Read two already-checked bytes without alignment or host-endian assumptions.
Definition exifite.c:80
static int read_exif_stream(FILE *input, unsigned char *payload, size_t capacity, size_t *size)
Extract the unique EXIF payload from a caller-owned JPEG stream.
Definition exifite.c:918
#define TIFF_DIRECTORY_NEXT_SIZE
Bytes occupied by the next-directory link after an entry table.
Definition exifite.c:55
#define TIFF_ENTRY_SIZE
Bytes occupied by one TIFF directory entry.
Definition exifite.c:49
static bool stream_frame_header(struct jpeg_stream *stream, size_t payload_size, unsigned char header[6])
Read and validate the common six-byte start-of-frame header.
Definition exifite.c:1277
static bool marker_prefix(struct jpeg_stream *stream, size_t count, int marker)
Emit a marker together with its original fill-byte count.
Definition exifite.c:1176
#define JPEG_MAX_HEADER_BYTES
Limit on ordinary JPEG header segment bytes inspected.
Definition exifite.c:59
static bool stream_put_byte(struct jpeg_stream *stream, int byte)
Emit one framing byte, or do nothing during preflight.
Definition exifite.c:1126
static bool frame_marker(int marker)
Recognize SOF markers while excluding other codes in the same range.
Definition exifite.c:1246
#define EXIF_MAX_INPUT_ENTRIES
Bounds validation work and its stack-based duplicate-tag table.
Definition exifite.c:44
static int invalid(void)
Use one predictable error for invalid arguments and malformed values.
Definition exifite.c:69
static double signed_long(uint32_t value)
Interpret a TIFF signed component without an implementation-defined cast.
Definition exifite.c:378
static bool stream_fill(struct jpeg_stream *stream)
Refill only after buffered bytes have been consumed.
Definition exifite.c:1090
static bool stream_read(struct jpeg_stream *stream, unsigned char *data, size_t size)
Read a short fixed-size header across read-ahead buffer boundaries.
Definition exifite.c:1257
#define EXIF_GPS_POINTER
Standard primary-IFD link to the GPS directory.
Definition exifite.c:40
#define TIFF_HEADER_SIZE
Fixed TIFF layout widths, expressed separately from JPEG framing.
Definition exifite.c:47
#define JPEG_STREAM_CAPACITY
Read-ahead capacity independent of image dimensions.
Definition exifite.c:61
#define TIFF_DIRECTORY_COUNT_SIZE
Bytes occupied by a TIFF directory's entry count.
Definition exifite.c:53
static bool stream_marker(struct jpeg_stream *stream, bool entropy, size_t *prefix, int *marker)
Find a structural marker, optionally copying preceding entropy bytes.
Definition exifite.c:1199
static bool stream_write(struct jpeg_stream *stream, const unsigned char *data, size_t size)
Share byte emission between real rewrites and write-free validation.
Definition exifite.c:1116
static bool import_directory(struct exif_document *document, const struct exif_view *view, enum exif_directory directory, exif_tag_selector select, void *context)
Copy supported fields from one directory into writer storage.
Definition exifite.c:619
#define TIFF_INLINE_SIZE
Maximum TIFF value length stored directly in a directory entry.
Definition exifite.c:51
static bool range(size_t total, size_t offset, size_t length)
Check a byte span without forming a potentially overflowing end offset.
Definition exifite.c:133
static bool entry_value(const struct exif_view *view, size_t offset, struct exif_value *value)
Resolve one TIFF entry into checked, borrowed value bytes.
Definition exifite.c:167
static bool stream_copy(struct jpeg_stream *stream, size_t size, bool emit)
Copy or discard exactly one declared span in bounded chunks.
Definition exifite.c:1149
static const unsigned char exif_signature[]
APP1 identifier; its terminators are part of the on-disk signature.
Definition exifite.c:64
static bool entry_precedes(const struct exif_item *first, const struct exif_item *second)
Compare the wire ordering of two directory-local fields.
Definition exifite.c:730
static bool supported(enum exif_directory directory, uint16_t tag)
Select standard fields retained by the default import policy.
Definition exifite.c:595
static int relocate_jpeg_spans(int descriptor, const struct jpeg_edit_plan *plan, off_t original_size, off_t inserted_size, bool backwards)
Move only the spans whose final positions differ from their originals.
Definition exifite.c:1615
static bool skip_exact(FILE *input, size_t size)
Consume unwanted bytes without trusting a seek past end-of-file.
Definition exifite.c:896
Bounded C11 EXIF metadata and JPEG streaming interfaces.
int exif_document_import(struct exif_document *document, const struct exif_view *view)
Rebuild a writable document from supported Sensoraia fields.
Definition exifite.c:690
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
bool exif_value_unsigned(const struct exif_value *value, size_t index, uint32_t *result)
Decode one BYTE, SHORT or LONG component without an unaligned load.
Definition exifite.c:339
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
int exif_document_remove(struct exif_document *document, enum exif_directory directory, uint16_t tag)
Remove a tag and reclaim its packed value storage.
Definition exifite.c:473
exif_directory
Directory identities, not on-disk tag numbers or offsets.
Definition exifite.h:59
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_tag_selector)(void *context, enum exif_directory directory, uint16_t tag)
Caller policy for additional, directory-local fields to import.
Definition exifite.h:247
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
#define EXIF_MAX_ENTRIES
Writer entry budget, including the standard initialization tags.
Definition exifite.h:54
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_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
bool exif_value_rational(const struct exif_value *value, size_t index, double *result)
Decode one unsigned or signed rational component as a double.
Definition exifite.c:383
int exif_document_import_custom(struct exif_document *document, const struct exif_view *view, exif_tag_selector select, void *context)
Import standard fields plus additional tags selected by the caller.
Definition exifite.c:671
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
void exif_encode_short(unsigned char *data, uint16_t value)
Encode a 16-bit value in the writer's little-endian representation.
Definition exifite.c:99
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_SHORT
Definition exifite.h:67
@ EXIF_SRATIONAL
Definition exifite.h:72
@ 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_DIRECTORY_COUNT
Definition exifite.h:59
@ EXIF_PRIMARY
Definition exifite.h:59
@ EXIF_GPS
Definition exifite.h:59
@ EXIF_EXPOSURE_BIAS
Definition exifite.h:91
@ EXIF_GPS_SPEED_REF
Definition exifite.h:108
@ EXIF_FOCAL_LENGTH
Definition exifite.h:92
@ EXIF_Y_RESOLUTION
Definition exifite.h:83
@ EXIF_COMPONENTS_CONFIGURATION
Definition exifite.h:90
@ EXIF_VERSION
Definition exifite.h:89
@ EXIF_DOCUMENT_NAME
Definition exifite.h:79
@ EXIF_FLASHPIX_VERSION
Definition exifite.h:94
@ EXIF_EXPOSURE_TIME
Definition exifite.h:86
@ EXIF_PIXEL_Y_DIMENSION
Definition exifite.h:97
@ EXIF_LENS_MODEL
Definition exifite.h:99
@ EXIF_GPS_ALTITUDE
Definition exifite.h:107
@ EXIF_X_RESOLUTION
Definition exifite.h:82
@ EXIF_PIXEL_X_DIMENSION
Definition exifite.h:96
@ EXIF_IMAGE_DESCRIPTION
Definition exifite.h:80
@ EXIF_SOFTWARE
Definition exifite.h:85
@ EXIF_USER_COMMENT
Definition exifite.h:93
@ EXIF_ORIENTATION
Definition exifite.h:81
@ EXIF_RESOLUTION_UNIT
Definition exifite.h:84
@ EXIF_COLOR_SPACE
Definition exifite.h:95
@ EXIF_FNUMBER
Definition exifite.h:87
@ EXIF_GPS_DIRECTION
Definition exifite.h:113
uint8_t marker[LWIR_THERMAL_HEADER_BYTES+LWIR_THERMAL_CHUNK_CAPACITY]
Definition lwir_image.c:62
static const char header[]
Definition pose_log.c:87
static size_t count
Definition pose_log.c:79
static FILE * output
Definition pose_log.c:77
Caller-owned bounded writer with no heap allocation.
Definition exifite.h:156
size_t count
Definition exifite.h:159
unsigned char data[EXIF_MAX_PAYLOAD]
Definition exifite.h:162
struct exif_item entries[EXIF_MAX_ENTRIES]
Definition exifite.h:157
size_t used
Definition exifite.h:160
Writer bookkeeping for one field inside the document's value storage.
Definition exifite.h:142
uint32_t size
Definition exifite.h:144
uint32_t offset
Definition exifite.h:143
uint16_t format
Definition exifite.h:147
unsigned char directory
Definition exifite.h:148
uint16_t tag
Definition exifite.h:146
uint32_t count
Definition exifite.h:145
Borrowed bytes plus enough type information for safe interpretation.
Definition exifite.h:119
bool little_endian
Definition exifite.h:124
const unsigned char * data
Definition exifite.h:120
size_t size
Definition exifite.h:121
uint32_t count
Definition exifite.h:122
uint16_t format
Definition exifite.h:123
Borrowed view of a validated APP1 payload.
Definition exifite.h:131
bool little_endian
Definition exifite.h:135
uint32_t directories[EXIF_DIRECTORY_COUNT]
Definition exifite.h:134
const unsigned char * tiff
Definition exifite.h:132
size_t size
Definition exifite.h:133
Bounded edit list produced by the same parser used for streaming rewrites.
Definition exifite.c:1064
off_t insertion
Definition exifite.c:1065
struct jpeg_removal removals[JPEG_MAX_HEADER_SEGMENTS]
Definition exifite.c:1067
Original-file interval occupied by one discarded EXIF segment.
Definition exifite.c:1055
off_t start
Definition exifite.c:1056
One bounded read-ahead buffer shared by JPEG inspection and rewriting.
Definition exifite.c:1074
size_t position
Definition exifite.c:1078
unsigned char buffer[JPEG_STREAM_CAPACITY]
Definition exifite.c:1082
size_t size
Definition exifite.c:1079
struct jpeg_edit_plan * plan
Definition exifite.c:1077
FILE * output
Definition exifite.c:1076
FILE * input
Definition exifite.c:1075
struct usher_control_result result
Definition usher.c:377