Allocation-free EXIF parsing, serialization and bounded JPEG streaming. More...
#include "exifite.h"#include <errno.h>#include <limits.h>#include <stdio.h>#include <string.h>#include <sys/stat.h>#include <unistd.h>
Go to the source code of this file.
Data Structures | |
| struct | jpeg_removal |
| Original-file interval occupied by one discarded EXIF segment. More... | |
| struct | jpeg_edit_plan |
| Bounded edit list produced by the same parser used for streaming rewrites. More... | |
| struct | jpeg_stream |
| One bounded read-ahead buffer shared by JPEG inspection and rewriting. More... | |
Macros | |
| #define | EXIF_CAMERA_POINTER 0x8769U |
| Standard primary-IFD link to the camera/EXIF directory. | |
| #define | EXIF_GPS_POINTER 0x8825U |
| Standard primary-IFD link to the GPS directory. | |
| #define | EXIF_MAX_INPUT_ENTRIES 256U |
| Bounds validation work and its stack-based duplicate-tag table. | |
| #define | TIFF_HEADER_SIZE 8U |
| Fixed TIFF layout widths, expressed separately from JPEG framing. | |
| #define | TIFF_ENTRY_SIZE 12U |
| Bytes occupied by one TIFF directory entry. | |
| #define | TIFF_INLINE_SIZE 4U |
| Maximum TIFF value length stored directly in a directory entry. | |
| #define | TIFF_DIRECTORY_COUNT_SIZE 2U |
| Bytes occupied by a TIFF directory's entry count. | |
| #define | TIFF_DIRECTORY_NEXT_SIZE 4U |
| Bytes occupied by the next-directory link after an entry table. | |
| #define | JPEG_MAX_HEADER_SEGMENTS 1024U |
| Limit on JPEG header segments inspected before reaching image data. | |
| #define | JPEG_MAX_HEADER_BYTES (4U * 1024U * 1024U) |
| Limit on ordinary JPEG header segment bytes inspected. | |
| #define | JPEG_STREAM_CAPACITY 8192U |
| Read-ahead capacity independent of image dimensions. | |
Functions | |
| static int | invalid (void) |
| Use one predictable error for invalid arguments and malformed values. | |
| static uint16_t | read_short (const unsigned char *data, bool little) |
| Read two already-checked bytes without alignment or host-endian assumptions. | |
| static uint32_t | read_long (const unsigned char *data, bool little) |
| Read four checked bytes; casts precede shifts to avoid signed promotion. | |
| void | exif_encode_short (unsigned char *data, uint16_t value) |
| Encode a 16-bit value in the writer's little-endian representation. | |
| void | exif_encode_long (unsigned char *data, uint32_t value) |
| Encode a 32-bit value in the writer's little-endian representation. | |
| static size_t | format_size (uint16_t format) |
| Map TIFF's numbered representations to their component byte widths. | |
| static bool | range (size_t total, size_t offset, size_t length) |
| Check a byte span without forming a potentially overflowing end offset. | |
| 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. | |
| 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. | |
| static bool | validate_directory (struct exif_view *view, enum exif_directory directory) |
| Validate one bounded IFD and discover the two supported child links. | |
| int | exif_parse (struct exif_view *view, const unsigned char *payload, size_t size) |
| Validate an EXIF APP1 payload and create a borrowed view. | |
| 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. | |
| 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. | |
| static double | signed_long (uint32_t value) |
| Interpret a TIFF signed component without an implementation-defined cast. | |
| bool | exif_value_rational (const struct exif_value *value, size_t index, double *result) |
| Decode one unsigned or signed rational component as a double. | |
| size_t | exif_text_length (const struct exif_value *value) |
| Count text bytes after trimming trailing NUL padding only. | |
| void | exif_document_init (struct exif_document *document) |
| Start a fresh upright sRGB/Y-Cb-Cr document with EXIF 2.32 defaults. | |
| 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. | |
| int | exif_document_remove (struct exif_document *document, enum exif_directory directory, uint16_t tag) |
| Remove a tag and reclaim its packed value storage. | |
| 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. | |
| 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. | |
| 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. | |
| static bool | supported (enum exif_directory directory, uint16_t tag) |
| Select standard fields retained by the default import policy. | |
| 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. | |
| 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. | |
| int | exif_document_import (struct exif_document *document, const struct exif_view *view) |
| Rebuild a writable document from supported Sensoraia fields. | |
| 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. | |
| static bool | entry_precedes (const struct exif_item *first, const struct exif_item *second) |
| Compare the wire ordering of two directory-local fields. | |
| 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. | |
| static bool | read_exact (FILE *input, unsigned char *buffer, size_t size) |
| Read an entire declared span or report truncation. | |
| static bool | skip_exact (FILE *input, size_t size) |
| Consume unwanted bytes without trusting a seek past end-of-file. | |
| 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. | |
| 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. | |
| 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. | |
| static bool | stream_fill (struct jpeg_stream *stream) |
| Refill only after buffered bytes have been consumed. | |
| static int | stream_byte (struct jpeg_stream *stream) |
| Read a marker/header byte while preserving buffered cursor ownership. | |
| 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. | |
| static bool | stream_put_byte (struct jpeg_stream *stream, int byte) |
| Emit one framing byte, or do nothing during preflight. | |
| static off_t | stream_offset (const struct jpeg_stream *stream) |
| Recover the logical offset rather than the read-ahead descriptor offset. | |
| static bool | stream_copy (struct jpeg_stream *stream, size_t size, bool emit) |
| Copy or discard exactly one declared span in bounded chunks. | |
| static bool | marker_prefix (struct jpeg_stream *stream, size_t count, int marker) |
| Emit a marker together with its original fill-byte count. | |
| static bool | stream_marker (struct jpeg_stream *stream, bool entropy, size_t *prefix, int *marker) |
| Find a structural marker, optionally copying preceding entropy bytes. | |
| static bool | frame_marker (int marker) |
| Recognize SOF markers while excluding other codes in the same range. | |
| 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. | |
| 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. | |
| 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. | |
| int | exif_jpeg_dimensions (FILE *input, uint32_t *width, uint32_t *height, unsigned *components) |
| Inspect the frame header without allocating or decoding image pixels. | |
| 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. | |
| 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. | |
| 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. | |
| 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. | |
| int | exif_update_jpeg (FILE *file, const unsigned char *payload, size_t size) |
| Replace EXIF in a regular JPEG file without a temporary file. | |
Variables | |
| static const unsigned char | exif_signature [] = {'E', 'x', 'i', 'f', 0, 0} |
| APP1 identifier; its terminators are part of the on-disk signature. | |
Detailed Description
Allocation-free EXIF parsing, serialization and bounded JPEG streaming.
The implementation keeps three jobs separate: validate borrowed TIFF bytes, collect caller-owned values, then stream JPEG markers around a serialized APP1 payload. That separation lets us check each boundary without allocating image-sized buffers or interpreting manufacturer-specific pointer structures.
- See also
- exifite.h for public contracts and storage ownership.
Definition in file exifite.c.
Macro Definition Documentation
◆ EXIF_CAMERA_POINTER
| #define EXIF_CAMERA_POINTER 0x8769U |
◆ EXIF_GPS_POINTER
| #define EXIF_GPS_POINTER 0x8825U |
◆ EXIF_MAX_INPUT_ENTRIES
| #define EXIF_MAX_INPUT_ENTRIES 256U |
◆ JPEG_MAX_HEADER_BYTES
| #define JPEG_MAX_HEADER_BYTES (4U * 1024U * 1024U) |
◆ JPEG_MAX_HEADER_SEGMENTS
| #define JPEG_MAX_HEADER_SEGMENTS 1024U |
◆ JPEG_STREAM_CAPACITY
| #define JPEG_STREAM_CAPACITY 8192U |
◆ TIFF_DIRECTORY_COUNT_SIZE
| #define TIFF_DIRECTORY_COUNT_SIZE 2U |
◆ TIFF_DIRECTORY_NEXT_SIZE
| #define TIFF_DIRECTORY_NEXT_SIZE 4U |
◆ TIFF_ENTRY_SIZE
| #define TIFF_ENTRY_SIZE 12U |
◆ TIFF_HEADER_SIZE
| #define TIFF_HEADER_SIZE 8U |
◆ TIFF_INLINE_SIZE
| #define TIFF_INLINE_SIZE 4U |
Function Documentation
◆ entry_precedes()
◆ entry_value()
|
static |
Resolve one TIFF entry into checked, borrowed value bytes.
- Parameters
-
[in] view TIFF storage and declared byte order. [in] offset TIFF-relative offset of the twelve-byte directory entry. [out] value Field descriptor; use only when validation succeeds.
- Returns
- True for a supported, fully accessible representation.
TIFF stores values of at most four bytes directly in the entry; larger values use an offset relative to the TIFF header. Count validation precedes multiplication, so an untrusted component count cannot overflow.
◆ format_size()
|
static |
Map TIFF's numbered representations to their component byte widths.
- Parameters
-
[in] format On-disk TIFF type identifier.
- Returns
- Component width, or zero for an unsupported type.
The table includes ordinary TIFF types beyond our named enum values so unknown but structurally valid input fields can be checked and then ignored.
◆ frame_marker()
|
static |
◆ import_directory()
|
static |
Copy supported fields from one directory into writer storage.
- Parameters
-
[in,out] document Initialized destination document. [in] view Source bytes and input byte order. [in] directory Directory whose fields should be imported. [in] select Optional caller selection for additional fields. [in] context Borrowed selection state.
- Returns
- True on success, false when the caller must reset the partial import.
Keeping rollback in the public wrapper makes this routine responsible only for traversal and byte-order conversion, not document lifecycle.
◆ invalid()
|
static |
◆ marker_prefix()
|
static |
Emit a marker together with its original fill-byte count.
- Parameters
-
[in,out] stream State containing a writable output stream. [in] count Number of leading 0xff bytes, including the marker prefix. [in] marker Marker code, or stuffed zero when copying scan data.
- Returns
- True when all bytes were written.
Retaining legal fill bytes avoids unnecessary changes to unrelated JPEG framing while replacement EXIF gets its own single-prefix marker.
◆ overlaps()
|
static |
Detect caller-buffer aliasing without adding lengths to addresses.
- Parameters
-
[in] first First storage address. [in] first_size First storage length in bytes. [in] second Second storage address. [in] second_size Second storage length in bytes.
- Returns
- True for overlapping nonempty spans.
Address differences avoid wraparound at the end of an address space. This uses the flat uintptr_t address representation of our Linux targets.
◆ range()
|
static |
Check a byte span without forming a potentially overflowing end offset.
- Parameters
-
[in] total Accessible bytes in the enclosing storage. [in] offset Proposed starting offset. [in] length Proposed span length.
- Returns
- True when the entire span fits.
Check the start first; only then is the subtraction safe. Keep this order when extending the parser with another field or pointer check.
◆ read_exact()
|
static |
◆ read_exif_stream()
|
static |
Extract the unique EXIF payload from a caller-owned JPEG stream.
- Parameters
-
[in,out] input Readable stream at start-of-image; not closed here. [out] payload Destination for the selected APP1 payload. [in] capacity Writable payload capacity in bytes. [out] size Selected payload length; the public wrapper clears it on failure.
- Returns
- Zero on success, otherwise -1 with errno describing the parse failure.
Ownership stays with the wrapper so every parse exit can be a plain return, while file closing and error preservation remain in one place.
◆ read_long()
|
static |
◆ read_short()
|
static |
◆ relocate_jpeg_range()
|
static |
Move one retained interval without overwriting its unread source bytes.
- Parameters
-
[in] descriptor Open read/write regular file. [in] start Original interval start, inclusive. [in] end Original interval end, exclusive. [in] displacement Signed destination offset relative to the source.
- Returns
- Zero on success, otherwise -1 with errno set.
Growth copies backward; shrinkage copies forward. Positional I/O avoids stream seeks per block. Short transfers and EINTR are handled without assuming that one system call completes the block. A zero-byte transfer is an I/O error.
◆ relocate_jpeg_spans()
|
static |
Move only the spans whose final positions differ from their originals.
- Parameters
-
[in] descriptor Open read/write regular file. [in] plan Validated ordered removal intervals and insertion location. [in] original_size Original file size, including bytes after EOI. [in] inserted_size Replacement segment size, including marker and length. [in] backwards True for right-shifted spans, false for left-shifted spans.
- Returns
- Zero on success, otherwise -1 with errno set.
After the one insertion, displacement only decreases as old EXIF is removed. Right-shifted spans therefore precede left-shifted spans. Copying the former from the end and the latter from the start protects every unread span, even when EXIF occurs between progressive scans and displacement changes sign. Zero-displacement spans need no writes; this is the cheap repeated-update path.
◆ rewrite_jpeg_stream()
|
static |
Rewrite JPEG framing using caller-owned streams and validated EXIF.
- Parameters
-
[in,out] stream Buffered source and destination state. [in] payload Validated replacement APP1 bytes. [in] size Replacement payload length.
- Returns
- True after a complete frame/scan/EOI stream, false on framing or I/O failure.
This routine owns no resources. Early returns keep the scan-state transitions visible; the public wrapper supplies one error-classification path.
◆ signed_long()
|
static |
Interpret a TIFF signed component without an implementation-defined cast.
- Parameters
-
[in] value Unsigned bit representation of a 32-bit signed integer.
- Returns
- Its signed mathematical value, exactly representable as a double.
Subtracting 2^32 handles negative values, including INT32_MIN, without signed overflow. This keeps signed rational handling portable between compilers.
◆ skip_exact()
|
static |
Consume unwanted bytes without trusting a seek past end-of-file.
- Parameters
-
[in,out] input Readable stream positioned before the unwanted span. [in] size Bytes that must actually exist.
- Returns
- True after consuming the span, false for a short read.
A seek can succeed beyond EOF; reading bounded chunks makes a truncated JPEG segment fail instead of hiding the missing bytes from the header parser.
◆ stream_byte()
|
static |
◆ stream_copy()
|
static |
Copy or discard exactly one declared span in bounded chunks.
- Parameters
-
[in,out] stream Input cursor and optional writable output stream. [in] size Bytes to consume; short input is an error. [in] emit True to write bytes, false to discard an old EXIF segment.
- Returns
- True after consuming the full span, false on read/write failure.
Both paths consume existing read-ahead first, so changing from marker parsing to bulk copying never loses or reads the same bytes twice.
◆ stream_fill()
|
static |
◆ stream_frame_header()
|
static |
Read and validate the common six-byte start-of-frame header.
- Parameters
-
[in,out] stream Source cursor immediately after the segment length. [in] payload_size Full frame payload length, including component descriptors. [out] header Precision, height, width and component count bytes.
- Returns
- True for the bounded frame representation supported by this module.
Inspection and rewriting use the same checks so they cannot disagree about which dimensions or component counts are safe to publish.
◆ stream_marker()
|
static |
Find a structural marker, optionally copying preceding entropy bytes.
- Parameters
-
[in,out] stream Buffered cursor; entropy mode requires a writable output. [in] entropy True inside a scan, false between marker segments. [out] prefix Marker-prefix/fill count for the caller to retain or discard. [out] marker Structural marker code, not yet emitted.
- Returns
- True on a marker, false on malformed framing or I/O failure.
Inside scans, 0xff/0x00 is a stuffed data byte and restart markers do not end the scan. Handle these here so the rewrite loop sees only markers whose segments it must inspect. Prefix reads may cross buffer boundaries.
◆ stream_offset()
|
static |
◆ stream_put_byte()
|
static |
◆ stream_read()
|
static |
Read a short fixed-size header across read-ahead buffer boundaries.
- Parameters
-
[in,out] stream Buffered source state. [out] data Storage for at least the requested byte count. [in] size Exact byte count to read.
- Returns
- True when the complete header was available.
◆ stream_segment_header()
|
static |
Emit a segment prefix and its two-byte big-endian JPEG length.
- Parameters
-
[in,out] stream State containing a writable output stream. [in] prefix Number of prefix/fill bytes to preserve. [in] marker Segment marker code. [in] payload_size Segment bytes excluding the two length bytes.
- Returns
- True when the complete framing was written.
- Precondition
- Payload length is already bounded by the JPEG segment limit.
◆ stream_write()
|
static |
Share byte emission between real rewrites and write-free validation.
- Parameters
-
[in,out] stream Parser state with optional output. [in] data Bytes to emit only when an output exists. [in] size Accessible byte count.
- Returns
- True on complete emission or validation-only traversal.
◆ supported()
|
static |
Select standard fields retained by the default import policy.
- Parameters
-
[in] directory Directory containing the field. [in] tag Directory-local tag identifier.
- Returns
- True when the field belongs in an imported writer document.
Byte-for-byte copying is not enough for vendor records with private offsets. An explicit allowlist keeps imports small and avoids pretending to preserve structures we neither interpret nor need. Defaults are rebuilt separately.
◆ valid_document_entry()
|
static |
Validate a writer field before calculating offsets or touching output.
- Parameters
-
[in] document Source document whose storage has already been bounded. [in] entry Field descriptor to check against that storage.
- Returns
- True when the representation can be serialized safely.
◆ validate_directory()
|
static |
Validate one bounded IFD and discover the two supported child links.
- Parameters
-
[in,out] view Candidate view; primary-directory links fill child offsets. [in] directory Directory identity to validate.
- Returns
- True for an absent directory or a valid directory table and its values.
Duplicate tags are ambiguous, so reject them rather than let readers disagree over which value wins. A small bounded scan avoids heap-backed sets and does not assume that camera entries arrive sorted.