@@ -826,6 +826,17 @@ This is discussed: [https://github.com/Exiv2/exiv2/issues/1230](https://github.c
Access to the BMFF code is guarded by the CMake option: `-DEXIV2_ENABLE_BMFF=ON` (enabled by default).
+Existing item-based HEIF/HEIC files support primary-image Exif and XMP writing,
+including growth, replacement and removal. The native writer preserves encoded
+image payloads and compacts obsolete metadata storage without an image codec
+dependency. AVIF, CR3 and JPEG XL writing remain unsupported. Unsupported layouts
+and edits conflicting with shared item data are rejected before source transfer.
+
+See [HEIF and HEIC metadata writing](exiv2.md#heif-and-heic-metadata-writing) for
+the supported structures, metadata-removal scope, build options and transfer
+failure limitations. Use `ImageFactory::open()` to obtain the HEIF writer; the
+factory reports `ImageType::heif`, while the general `BmffImage` remains read-only.
+
[TOC](#TOC)
diff --git a/exiv2.md b/exiv2.md
index 149f53b809..45e8dd00d0 100644
--- a/exiv2.md
+++ b/exiv2.md
@@ -80,8 +80,8 @@ DNG | Read/Write | Read/Write | Read/Write | - | Read/Write | Rea
EPS | - | - | Read/Write | | - | -
EXV | Read/Write | Read/Write | Read/Write | Read/Write | Read/Write | Read/Write
GIF | - | - | - | - | - | -
-HEIC | Read | Read | Read | - | - | Read
-HEIF | Read | Read | Read | - | - | Read
+HEIC | Read/Write | Read | Read/Write | - | Read | Read
+HEIF | Read/Write | Read | Read/Write | - | Read | Read
JP2 | Read/Write | Read/Write | Read/Write | - | Read/Write | Read/Write
JPEG | Read/Write | Read/Write | Read/Write | Read/Write | Read/Write | Read/Write
JXL | Read | Read | Read | - | - | Read
@@ -121,6 +121,52 @@ and see if `enable_bmff=1`.
rudimentary support to read metadata from quicktime, matroska and riff based video files (e.g.
.MOV/.MP4, .MKV, .AVI, .WAV, .ASF).
+### HEIF and HEIC metadata writing
+
+With BMFF support enabled, Exiv2 can add, replace and remove Exif and XMP for
+the primary image of an existing item-based HEIF/HEIC file. This includes
+growing and shortening values, deleting individual tags, clearing a category,
+and extracting/reinserting metadata through `.exv` files. Encoded images are
+copied without decoding or recompression; no image codec library is required.
+
+Writing supports the `heic`, `heix` and `mif1` major brands, self-contained
+`mdat` and `idat` item storage, and primary coded or derived images (including
+grids). Thumbnails, auxiliary images, other image items, their properties,
+and ICC profiles are preserved. Capability reporting describes potential
+operations; each write checks the actual container before changing the source.
+AVIF, CR3 and JPEG XL writing remain unsupported. Timed sequences, protected
+items, external data references, item construction method 2, compressed XMP,
+and unknown structures whose offsets cannot be safely relocated are rejected.
+Creating a new HEIF image, editing ICC profiles, and standalone IPTC changes
+are unsupported. Embedded IPTC is preserved during unrelated Exif edits.
+
+Changed metadata is serialized afresh and the output is compacted. Successful
+deletion or replacement removes the targeted obsolete metadata payloads and
+unused storage from the new file, including shortened/deleted TIFF values,
+old media gaps and padding. If those bytes are also required by another item,
+the edit is rejected before source replacement. Independent active metadata
+belonging to other images remains. This operation does not erase backups,
+older copies, filesystem history or information encoded in image pixels.
+An explicit clear performs cleanup even when the decoded category is empty;
+an unchanged write with no pending cleanup preserves the file byte for byte.
+
+Exif byte order is retained. Known MakerNotes and embedded thumbnail data are
+reconstructed and checked for preservation; unsupported serialization changes
+fail before transfer. Canon autofocus fields derived from `AFInfo` are read-only.
+Repeated edits do not accumulate superseded payloads or duplicate image data.
+
+Without the XMP toolkit, Exif edits and raw XMP packet preservation, replacement
+and removal remain available. Structured XMP edits and Exif edits that require
+merging distinct primary XMP packets need the toolkit and are rejected without
+it. An explicit XMP replacement or clear can replace those packets together.
+
+Structural parsing and metadata sizes are bounded independently of image size.
+Limits include 16 MiB of parsed structural data, 65,536 items, 100,000 boxes,
+16 levels of nesting, and 64 MiB of combined Exif/XMP input payloads. Large
+encoded image ranges are copied in bounded chunks. Local file writes prepare
+and validate a temporary file before transfer; failure before transfer leaves
+the source unchanged. A failure or crash during final transfer can leave an
+incomplete destination. Replacement is not guaranteed to be atomic.
[TOC](#TOC)
diff --git a/fuzz/README.md b/fuzz/README.md
index 7d0fb59657..b2b74af929 100644
--- a/fuzz/README.md
+++ b/fuzz/README.md
@@ -28,6 +28,48 @@ Alternatively, a simple script is provided for running the fuzzer in a continuou
../fuzz/fuzzloop.sh
```
+### HEIF metadata writing
+
+Both `fuzz-read-write` and `fuzz-read-print-write` exercise HEIF edits after
+their initial unchanged write. The input size modulo four selects an Exif
+description update, Exif removal, XMP removal, or removal of both categories.
+After a successful edit, the result is read again through the public image API.
+
+For a focused run, build with BMFF support and Clang's sanitizers. From the
+repository root, with the [build dependencies](../README.md#dependencies)
+installed:
+
+```bash
+cmake -S . -B build-heif-fuzz -DCMAKE_BUILD_TYPE=Debug \
+ -DCMAKE_C_COMPILER=clang -DCMAKE_CXX_COMPILER=clang++ \
+ -DEXIV2_ENABLE_BMFF=ON -DEXIV2_BUILD_FUZZ_TESTS=ON \
+ -DEXIV2_TEAM_USE_SANITIZERS=ON
+cmake --build build-heif-fuzz --parallel 4 \
+ --target fuzz-read-write fuzz-read-print-write
+```
+
+The following existing fixtures select all four edit operations. Copy them
+into the build directory and use a separate writable corpus for each target.
+The 2 MiB input limit accommodates these HEIF seeds, including files larger
+than the limits in the general examples. Each target runs for about 30 seconds.
+
+```bash
+(
+ set -e
+ cd build-heif-fuzz
+ mkdir -p heif-seeds
+ cp ../test/data/Canon.HIF ../test/data/Stonehenge.heic \
+ ../test/data/heic.heic ../test/data/issue_9292_sony_8_left-bottom.HIF heif-seeds/
+ for target in fuzz-read-write fuzz-read-print-write; do
+ mkdir -p "heif-corpus-$target"
+ LSAN_OPTIONS=suppressions=../fuzz/knownleaks.txt \
+ "./bin/$target" "heif-corpus-$target" heif-seeds \
+ -dict=../fuzz/exiv2.dict -max_len=2097152 -max_total_time=30 \
+ -timeout=10 -rss_limit_mb=2048 -artifact_prefix="heif-corpus-$target/"
+ done
+)
+```
+
## Generating a dictionary
Fuzzers perform better with a [dictionary](https://llvm.org/docs/LibFuzzer.html#dictionaries). For example, suppose the code contains a condition like [this](https://github.com/Exiv2/exiv2/blob/15098f4ef50cc721ad0018218acab2ff06e60beb/src/xmpsidecar.cpp#L177-L179):
diff --git a/fuzz/fuzz-heif-write.hpp b/fuzz/fuzz-heif-write.hpp
new file mode 100644
index 0000000000..167e27c696
--- /dev/null
+++ b/fuzz/fuzz-heif-write.hpp
@@ -0,0 +1,41 @@
+// SPDX-License-Identifier: GPL-2.0-or-later
+
+#ifndef FUZZ_HEIF_WRITE_HPP
+#define FUZZ_HEIF_WRITE_HPP
+
+#include
+
+/*!
+ @brief Exercise HEIF serialization and compaction after the drivers' unchanged write.
+ @param image Image backed by the fuzz driver's owned MemIo; other image types are ignored.
+ @param selector Select an Exif update or metadata removal deterministically from input size.
+
+ A successful write is read back to exercise the emitted container. Exceptions
+ propagate to the fuzz driver's existing invalid-input handler.
+ */
+inline void fuzzHeifWrite(Exiv2::Image& image, size_t selector) {
+ if (image.imageType() != Exiv2::ImageType::heif)
+ return;
+
+ // Mutate metadata so valid seeds reach the rewrite path rather than only a no-op.
+ switch (selector % 4) {
+ case 0:
+ image.exifData()["Exif.Image.ImageDescription"] = "HEIF fuzz metadata";
+ break;
+ case 1:
+ image.clearExifData();
+ break;
+ case 2:
+ image.clearXmpData();
+ break;
+ case 3:
+ image.clearMetadata();
+ break;
+ }
+
+ // Parse the result through the public API as well as exercising its serialization.
+ image.writeMetadata();
+ image.readMetadata();
+}
+
+#endif
diff --git a/fuzz/fuzz-read-print-write.cpp b/fuzz/fuzz-read-print-write.cpp
index cbe77d9850..4fe375fcd1 100644
--- a/fuzz/fuzz-read-print-write.cpp
+++ b/fuzz/fuzz-read-print-write.cpp
@@ -1,5 +1,7 @@
#include
+#include "fuzz-heif-write.hpp"
+
#include
#include
#include
@@ -44,6 +46,7 @@ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
image->printStructure(buffer, Exiv2::kpsIptcErase);
image->writeMetadata();
+ fuzzHeifWrite(*image, size);
} catch (...) {
// Exiv2 throws an exception if the metadata is invalid.
diff --git a/fuzz/fuzz-read-write.cpp b/fuzz/fuzz-read-write.cpp
index bc4b706599..7cf88690ee 100644
--- a/fuzz/fuzz-read-write.cpp
+++ b/fuzz/fuzz-read-write.cpp
@@ -1,5 +1,7 @@
#include
+#include "fuzz-heif-write.hpp"
+
#include
#include
#include
@@ -15,6 +17,7 @@ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
image->readMetadata();
image->writeMetadata();
+ fuzzHeifWrite(*image, size);
} catch (...) {
// Exiv2 throws an exception if the metadata is invalid.
diff --git a/include/exiv2/bmffimage.hpp b/include/exiv2/bmffimage.hpp
index 8590d6d7b9..e88511eefb 100644
--- a/include/exiv2/bmffimage.hpp
+++ b/include/exiv2/bmffimage.hpp
@@ -20,6 +20,11 @@ namespace Exiv2 {
#ifdef EXV_ENABLE_BMFF
namespace Exiv2 {
+namespace Internal {
+//! @brief Private adapter for legacy metadata interpretation over shared box traversal.
+class BmffLegacyReader;
+} // namespace Internal
+
struct Iloc {
explicit Iloc(uint32_t ID = 0, uint32_t start = 0, uint32_t length = 0) : ID_(ID), start_(start), length_(length) {
}
@@ -36,6 +41,12 @@ struct Iloc {
/*!
@brief Class to access BMFF images.
+
+ This general BMFF class provides read access. Use ImageFactory::open() for
+ HEIF/HEIC editing: the factory selects a private specialization and reports
+ ImageType::heif. Its Exif/XMP write capability is subject to validation of the
+ file's item layout; unsupported layouts fail before source replacement.
+ Direct construction of BmffImage does not enable HEIF writing.
*/
class EXIV2API BmffImage : public Image {
public:
@@ -117,6 +128,8 @@ class EXIV2API BmffImage : public Image {
static constexpr Exiv2::ByteOrder endian_{Exiv2::bigEndian};
private:
+ friend class Internal::BmffLegacyReader;
+
void openOrThrow() const;
/*!
@brief recursiveBoxHandler
diff --git a/include/exiv2/image.hpp b/include/exiv2/image.hpp
index d87a52a0b1..48fcf5cf39 100644
--- a/include/exiv2/image.hpp
+++ b/include/exiv2/image.hpp
@@ -462,6 +462,9 @@ class EXIV2API Image {
/*!
@brief Returns the access mode, i.e., the metadata functions, which
this image supports for the metadata type \em metadataId.
+ @note This reports format capabilities. writeMetadata() validates the
+ particular file layout and requested edits, and may reject an operation
+ even when write access is reported.
@param metadataId The metadata identifier.
@return Access mode for the requested image type and metadata identifier.
*/
@@ -541,6 +544,13 @@ using IsThisTypeFct = bool (*)(BasicIo& iIo, bool advance);
@brief Returns an Image instance of the specified type.
The factory is implemented as a static class.
+
+ @note With BMFF support enabled, HEIF/HEIC files recognized by the HEIF probe
+ report ImageType::heif. open() returns a private HEIF implementation with
+ Exif/XMP writing support, subject to validation of the file's layout and
+ requested edits. Direct construction of BmffImage retains its read-only
+ behavior; use this factory to obtain HEIF writing support.
+ @see BmffImage
*/
class EXIV2API ImageFactory {
friend bool Image::good() const;
@@ -673,6 +683,9 @@ class EXIV2API ImageFactory {
/*!
@brief Returns the access mode or supported metadata functions for an
image type and a metadata type.
+ @note This reports format capabilities, without inspecting a file.
+ Image::writeMetadata() validates the particular file layout and requested
+ edits, and may reject an operation even when write access is reported.
@param type The image type.
@param metadataId The metadata identifier.
@return Access mode for the requested image type and metadata identifier.
diff --git a/include/exiv2/image_types.hpp b/include/exiv2/image_types.hpp
index f4bcabd569..3345141856 100644
--- a/include/exiv2/image_types.hpp
+++ b/include/exiv2/image_types.hpp
@@ -38,6 +38,7 @@ enum class ImageType {
qtime,
riff,
mkv,
+ heif, //!< Item-based HEIF/HEIC; writing depends on the file layout.
};
} // namespace Exiv2
diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt
index a2541a8687..b85361b283 100644
--- a/src/CMakeLists.txt
+++ b/src/CMakeLists.txt
@@ -4,6 +4,22 @@ include_directories(${CMAKE_CURRENT_BINARY_DIR})
add_library(
exiv2lib_int OBJECT
+ bmffbox_int.cpp
+ bmffbox_int.hpp
+ bmffsample_int.cpp
+ bmffsample_int.hpp
+ cr3preview_int.cpp
+ cr3preview_int.hpp
+ bmffitem_int.cpp
+ bmffitem_int.hpp
+ bmffitemwrite_int.cpp
+ bmffitemwrite_int.hpp
+ bmfflayout_int.cpp
+ bmfflayout_int.hpp
+ heifstructure_int.cpp
+ heifstructure_int.hpp
+ heifwrite_int.cpp
+ heifwrite_int.hpp
canonmn_int.cpp
canonmn_int.hpp
casiomn_int.cpp
@@ -105,6 +121,8 @@ add_library(
asfvideo.cpp
basicio.cpp
bmffimage.cpp
+ heifimage_int.cpp
+ heifimage_int.hpp
bmpimage.cpp
convert.cpp
cr2image.cpp
diff --git a/src/README-BMFF.md b/src/README-BMFF.md
new file mode 100644
index 0000000000..2100925553
--- /dev/null
+++ b/src/README-BMFF.md
@@ -0,0 +1,117 @@
+# BMFF internal layers {#bmff_internals}
+
+The BMFF implementation uses private, composable layers. Sharing box mechanics
+does not make every BMFF format writable: factory routing is unchanged, HEIF
+edits still require layout and metadata checks, and AVIF, CR3 and JPEG XL remain
+read-only. QuickTime and JPEG 2000 use their existing readers.
+
+## Responsibilities
+
+| Files | Responsibility |
+| --- | --- |
+| `bmffbox_int.hpp/.cpp` | Checked box headers, source intervals, bounded field cursors, sibling traversal and explicit resource limits. |
+| `bmffsample_int.hpp/.cpp` | Standard single-sample/single-chunk table resolution, independent of brands and codecs. |
+| `cr3preview_int.hpp/.cpp` | Optional Canon CRAW/JPEG track interpretation and full-size native-preview discovery. |
+| `bmffitem_int.hpp/.cpp` | Standard item descriptions, locations, references, properties and extent resolution. |
+| `bmfflayout_int.hpp/.cpp` | Output measurement, placement, approved source relocation maps, bounded streaming and byte verification. |
+| `bmffitemwrite_int.hpp/.cpp` | Item-location encoding, file/idat coordinates, offset-width promotion and layout convergence. |
+| `heifstructure_int.hpp/.cpp` | HEIF admission, primary metadata selection, brands, Canon extensions, media ownership and relocation allowlists. |
+| `heifwrite_int.hpp/.cpp` | HEIF edit selection, shared-data rejection, retained/discarded ranges, compaction and structural verification. |
+| `heifimage_int.hpp/.cpp` | Private image implementation, TIFF/XMP interpretation and serialization, metadata precedence, fallback, no-op detection, semantic verification and final transfer. |
+| `bmffimage.cpp` | Legacy metadata interpretation and structure printing through the private `BmffLegacyReader` adapter. |
+
+The shared headers are implementation details in `src`, not installed APIs.
+`BmffImage` retains its public class layout and existing entry points; its private
+friend adapter borrows state without adding members. The existing `boxHandler`
+entry point delegates to the adapter for ABI compatibility.
+
+## Reading and ownership
+
+`BmffReader` borrows an open, seekable `BasicIo` and snapshots its size. The input
+must remain unchanged and outlive the reader and its cursors. Cursors share the
+reader's counters; reading fields can reposition the stream. `BmffSpan` uses
+absolute input coordinates and owns no payload bytes. Parsed boxes retain both
+the original encoded size field and the physical header length, including a
+UUID user type, so structure printing can preserve its original representation.
+
+The box layer requires neither `ftyp` nor `meta`. An adapter recognizes a
+container, consumes any format-specific prefix, and visits the remaining child
+range. Unknown boxes stay opaque. Size-zero boxes extend to file end, so their
+containing range must also end there. Limits are supplied by each caller:
+native HEIF uses `HeifLimits`, while the legacy adapter retains its per-root
+visit and recursion limits rather than adopting the HEIF budgets.
+
+The native HEIF path calls `parseHeif`, which composes `BmffReader` with
+`parseBmffItems` and a HEIF policy. The standard item model needs no brand,
+picture handler or primary image. It supports local file-relative and
+idat-relative extents, explicit nonzero lengths and the implemented table
+versions; it is not a decoder for every item-storage mode. `resolveBmffItems`
+checks links and computes absolute spans after source ranges are known.
+`readBmffItem` gathers only the selected payload under a caller-supplied limit.
+
+Legacy `BmffImage` reads, structure printing and HEIF fallback all use
+`BmffReader` framing and traversal. Legacy field interpretation remains in its
+adapter because item-table heuristics, traversal order, Canon UUID/CMT handling,
+JPEG XL boxes and optional Brotli decoding have compatibility rules different
+from the strict item model. FullBox bit decoding is shared; field admission and
+metadata precedence remain with the respective adapters.
+
+CR3 full-size JPEG discovery makes a separate bounded pass over the same box
+primitives. The standard sample helper resolves version-zero `stsc`, `stsz` and
+`stco`/`co64` tables for one sample in one chunk. It returns an absolute source
+range and a one-based description index; it knows neither codecs nor media
+ownership. The Canon adapter validates the indexed `CRAW` description, its
+`JPEG` child, local data reference and complete containment in a top-level
+`mdat`. It reads only the JPEG start marker, leaving extraction to the existing
+native-preview loader. The largest eligible track supplements THMB/PRVW when a
+native slot is available; ties retain file order. CR3 metadata reads rebuild the
+preview list, while structure printing leaves it unchanged.
+
+This optional pass is limited to 4096 headers, 1 MiB of structural reads and the
+caller's nesting limit. Malformed/unsupported tracks or exhausted limits omit
+the additional preview without hiding existing metadata; underlying I/O errors
+propagate. Multi-sample tracks, external references, raw/protected descriptions
+and HEVC previews are unsupported. This is still-image JPEG extraction, not a
+movie demuxer or a CR3 writer. Canon field interpretation follows
+[Laurent Clévy's CR3 research](https://github.com/lclevy/canon_cr3/tree/151c1a965775ef409ace17714c24ed491cfcf9c4).
+
+## Preparing writes
+
+HEIF selects metadata and retained ranges before constructing output. It rejects
+unsupported relocation and edits to shared metadata, and excludes obsolete
+metadata bytes from compacted payloads. Moving an opaque box always requires
+adapter approval: the generic engine cannot know whether it contains offsets.
+
+`BmffOutputBox` owns its prefix and child nodes. Its segments borrow unchanged
+source ranges or immutable replacement vectors; those inputs must outlive
+measurement, emission and verification. Input spans and output positions use
+separate absolute coordinate systems. `BmffRelocations` translates only ranges
+explicitly approved by the adapter.
+
+`layoutBmff` measures nodes, promotes box headers and places them. The item
+layer's `layoutBmffItems` regenerates `iloc` fields, converts absolute positions
+back to file/idat coordinates and converges after any offset-width promotion.
+The generic engine knows no item IDs, brands, codecs or metadata semantics.
+
+`writeBmffLayout` emits to a distinct, empty staging stream with requests bounded
+to 64 KiB. `verifyBmffLayout` compares all generated and retained bytes. HEIF
+then reparses the prepared output and checks its intended metadata before the
+image implementation performs the existing final transfer. The engine does not
+transfer or replace the source. A true unchanged write bypasses rewriting in
+the image implementation.
+
+## Maintaining the boundaries
+
+Add format recognition, payload interpretation and write eligibility to an
+adapter. Add common field mechanics to the item layer only when their semantics
+agree; preserve legacy compatibility rules explicitly. Do not infer relocation
+safety from successful parsing or silently apply HEIF limits to another reader.
+
+The focused unit suites cover box mechanics, item tables, output layout, legacy
+compatibility and HEIF integration. For commands, see the HEIF metadata writing
+section of `tests/README-TESTS.md` and the instructions in `fuzz/README.md`.
+Include `:*Cr3*` in the focused unit-test filter for CR3 track previews. The
+`test_issue_2854.py` CLI regression exercises generated full-size JPEG tracks;
+`test_issue_1893.py` retains THMB/PRVW listing and extraction coverage.
+The legacy hardening tests separately cover malformed container/UUID boundaries
+and underlying I/O failures.
diff --git a/src/bmffbox_int.cpp b/src/bmffbox_int.cpp
new file mode 100644
index 0000000000..b55c49ba63
--- /dev/null
+++ b/src/bmffbox_int.cpp
@@ -0,0 +1,128 @@
+// SPDX-License-Identifier: GPL-2.0-or-later
+
+#include "bmffbox_int.hpp"
+
+#ifdef EXV_ENABLE_BMFF
+
+#include "basicio.hpp"
+#include "enforce.hpp"
+#include "error.hpp"
+
+#include
+
+namespace Exiv2::Internal {
+namespace {
+
+// Report malformed boundaries and exhausted budgets consistently.
+void require(bool condition) {
+ enforce(condition, ErrorCode::kerCorruptedMetadata);
+}
+
+// Bound cumulative work before adding to a counter.
+void consume(uint64_t& used, uint64_t amount, uint64_t limit) {
+ require(used <= limit && amount <= limit - used);
+ used += amount;
+}
+
+} // namespace
+
+BmffSpan BmffBox::payload() const {
+ require(headerSize <= span.size && span.size <= std::numeric_limits::max() - span.offset);
+ return {span.offset + headerSize, span.size - headerSize};
+}
+
+BmffCursor::BmffCursor(BmffReader& reader, BmffSpan range) :
+ reader_(reader), position_(range.offset), end_(range.offset + range.size) {
+}
+
+void BmffCursor::advance(uint64_t count) {
+ require(count <= remaining());
+ position_ += count;
+}
+
+void BmffCursor::read(uint8_t* bytes, size_t size) {
+ require(size <= remaining());
+ reader_.read(position_, bytes, size);
+ position_ += size;
+}
+
+uint64_t BmffCursor::number(unsigned width) {
+ require(width <= 8);
+ std::array bytes{};
+ if (width != 0)
+ read(bytes.data(), width);
+
+ uint64_t result = 0;
+ for (unsigned i = 0; i < width; ++i)
+ result = (result << 8) | bytes.at(i);
+ return result;
+}
+
+void BmffCursor::finish() const {
+ require(remaining() == 0);
+}
+
+BmffReader::BmffReader(BasicIo& io, BmffReadLimits limits) : io_(io), limits_(limits), fileSize_(0) {
+ require(io.isopen());
+ fileSize_ = io.size();
+ require(fileSize_ <= static_cast(std::numeric_limits::max()));
+}
+
+BmffCursor BmffReader::cursor(BmffSpan range) {
+ require(range.offset <= fileSize_ && range.size <= fileSize_ - range.offset);
+ return BmffCursor(*this, range);
+}
+
+void BmffReader::read(uint64_t offset, uint8_t* bytes, size_t size) {
+ consume(bytes_, size, limits_.maxBytesRead);
+ if (size == 0)
+ return;
+
+ io_.seekOrThrow(static_cast(offset), BasicIo::beg, ErrorCode::kerInputDataReadFailed);
+ io_.readOrThrow(bytes, size, ErrorCode::kerInputDataReadFailed);
+ if (io_.error())
+ throw Error(ErrorCode::kerInputDataReadFailed);
+}
+
+BmffBox BmffReader::readBox(BmffCursor& input) {
+ require(&input.reader_ == this);
+ consume(boxes_, 1, limits_.maxBoxes);
+ require(input.remaining() >= 8);
+
+ BmffBox box;
+ box.span.offset = input.position();
+ const auto available = input.remaining();
+ box.size32 = static_cast(input.number(4));
+ box.span.size = box.size32;
+ box.type = static_cast(input.number(4));
+ box.headerSize = 8;
+
+ // Resolve extended and terminal sizes against the immediate containing range.
+ if (box.size32 == 1) {
+ box.span.size = input.number(8);
+ box.headerSize = 16;
+ } else if (box.size32 == 0) {
+ require(input.end() == fileSize_);
+ box.span.size = available;
+ box.extendsToEnd = true;
+ }
+
+ // UUID user types are header bytes, not part of the adapter's payload cursor.
+ if (box.type == bmffType("uuid")) {
+ box.headerSize += 16;
+ require(box.span.size >= box.headerSize && box.span.size <= available);
+ input.read(box.userType.data(), box.userType.size());
+ }
+
+ // Parent progress is independent of reads through the child payload cursor.
+ require(box.span.size >= box.headerSize && box.span.size <= available);
+ input.advance(box.span.size - box.headerSize);
+ return box;
+}
+
+void BmffReader::checkTraversal(const BmffCursor& input, unsigned depth) const {
+ require(&input.reader_ == this && depth <= limits_.maxDepth);
+}
+
+} // namespace Exiv2::Internal
+#endif // EXV_ENABLE_BMFF
diff --git a/src/bmffbox_int.hpp b/src/bmffbox_int.hpp
new file mode 100644
index 0000000000..f70ed73a11
--- /dev/null
+++ b/src/bmffbox_int.hpp
@@ -0,0 +1,214 @@
+// SPDX-License-Identifier: GPL-2.0-or-later
+
+#ifndef BMFFBOX_INT_HPP
+#define BMFFBOX_INT_HPP
+
+#include "config.h"
+
+#ifdef EXV_ENABLE_BMFF
+
+#include
+#include
+#include
+#include
+#include
+
+namespace Exiv2 {
+class BasicIo;
+}
+
+namespace Exiv2::Internal {
+
+//! @brief Pack a four-character box/item code into its big-endian integer representation.
+constexpr uint32_t bmffType(const char (&name)[5]) {
+ return (uint32_t{static_cast(name[0])} << 24) | (uint32_t{static_cast(name[1])} << 16) |
+ (uint32_t{static_cast(name[2])} << 8) | uint32_t{static_cast(name[3])};
+}
+
+//! @brief A validated interval in the original input. Payloads are never owned by the model.
+struct BmffSpan {
+ uint64_t offset{}; //!< Absolute byte offset from the start of the input.
+ uint64_t size{}; //!< Length of the interval in bytes.
+
+ //! @brief Compare the absolute offset and length of two input intervals.
+ bool operator==(const BmffSpan&) const = default;
+};
+
+//! @brief Version and flags decoded from the common FullBox prefix.
+struct BmffFullBox {
+ uint8_t version{}; //!< FullBox version selecting its field layout.
+ uint32_t flags{}; //!< Low 24 flag bits of the FullBox prefix.
+};
+
+//! @brief Split a FullBox field without imposing an adapter's version or flag restrictions.
+constexpr BmffFullBox decodeBmffFullBox(uint32_t value) {
+ return {static_cast(value >> 24), value & 0xffffff};
+}
+
+//! @brief Input box boundaries and decoded children, with opaque payloads left in the input.
+struct BmffBox {
+ uint32_t type{}; //!< Packed four-character box code.
+ uint32_t size32{}; //!< Original size field: 0 for EOF, 1 for an extended size.
+ BmffSpan span; //!< Complete original box interval, including its header.
+ uint8_t headerSize{}; //!< Includes a UUID user type, but excludes FullBox version/flags.
+ bool extendsToEnd{}; //!< True when the original size field extends to end of file.
+ std::array userType{}; //!< UUID user type, populated only for uuid boxes.
+ std::optional fullBox; //!< Decoded version and flags for recognized FullBox layouts.
+ std::vector children; //!< Decoded immediate children in original file order.
+
+ //! @brief Return the absolute payload interval, excluding the box header and UUID user type.
+ [[nodiscard]] BmffSpan payload() const;
+};
+
+//! @brief File framing only; adapters decide which boxes contain children and what they mean.
+struct BmffFile {
+ uint64_t size{}; //!< Source file length in bytes.
+ std::vector boxes; //!< Top-level boxes in file order, retaining source ranges.
+};
+
+//! @brief Caller-selected limits for one reader; no image-format policy is implied.
+struct BmffReadLimits {
+ uint64_t maxBoxes; //!< Maximum aggregate headers decoded, including repeated visits.
+ uint64_t maxBytesRead; //!< Maximum aggregate field bytes read, excluding skipped payloads.
+ unsigned maxDepth; //!< Maximum child nesting below the root sibling range at depth zero.
+};
+
+class BmffReader;
+
+/*!
+ @brief A bounded field cursor borrowing its reader and unchanged input.
+
+ Obtain cursors from BmffReader::cursor(). The reader and its input must outlive
+ all cursors. Independent cursors share the reader's budgets and may reposition
+ the underlying stream on every read. No method writes to the input.
+ */
+class BmffCursor {
+ public:
+ //! @brief Return the absolute input offset of the next field.
+ [[nodiscard]] uint64_t position() const {
+ return position_;
+ }
+
+ //! @brief Return the bytes still available within this interval.
+ [[nodiscard]] uint64_t remaining() const {
+ return end_ - position_;
+ }
+
+ //! @brief Return the exclusive absolute end of the containing interval.
+ [[nodiscard]] uint64_t end() const {
+ return end_;
+ }
+
+ //! @brief Skip bytes within this interval, throwing Error if count exceeds its remainder.
+ void advance(uint64_t count);
+
+ /*!
+ @brief Read an exact field and charge its size to the shared structural budget.
+ @param bytes Writable storage for at least size bytes; may be null only for size zero.
+ @param size Number of bytes to read within the cursor's remaining interval.
+ @throws Error For an invalid range, exhausted budget, or failed seek/read.
+
+ The underlying stream is repositioned. The cursor advances only after success.
+ */
+ void read(uint8_t* bytes, size_t size);
+
+ //! @brief Decode up to eight big-endian bytes; width zero returns zero without I/O.
+ uint64_t number(unsigned width);
+
+ //! @brief Reject trailing fields with Error unless the interval is exhausted.
+ void finish() const;
+
+ private:
+ friend class BmffReader;
+
+ //! @brief Borrow a reader and an interval whose bounds it has already validated.
+ BmffCursor(BmffReader& reader, BmffSpan range);
+
+ BmffReader& reader_;
+ uint64_t position_;
+ uint64_t end_;
+};
+
+/*!
+ @brief Decode and traverse bounded BMFF box ranges without interpreting their payloads.
+
+ The reader borrows an open, seekable BasicIo that must remain unchanged and
+ outlive the reader and its cursors. Limits apply across all cursors and visits.
+ It neither requires image-format boxes nor guesses which payloads are containers.
+ Malformed ranges and exhausted limits throw kerCorruptedMetadata; failed I/O
+ throws kerInputDataReadFailed. The underlying stream position may change.
+ */
+class BmffReader {
+ public:
+ /*!
+ @brief Borrow an open input and snapshot its length and caller-selected limits.
+ @param io Open, seekable input; ownership is retained by the caller.
+ @param limits Bounds on aggregate structural work and nesting.
+ @throws Error If the input is closed or its size exceeds signed seek offsets.
+ */
+ BmffReader(BasicIo& io, BmffReadLimits limits);
+
+ //! @brief Return the unchanged input length captured at construction.
+ [[nodiscard]] uint64_t fileSize() const {
+ return fileSize_;
+ }
+
+ //! @brief Create a field cursor, rejecting intervals extending beyond the input.
+ [[nodiscard]] BmffCursor cursor(BmffSpan range);
+
+ /*!
+ @brief Validate one header and advance input past its entire box.
+ @param input A cursor belonging to this reader, positioned at a box boundary.
+ @return Box boundaries and original size/UUID fields, with no decoded children.
+ @throws Error For incomplete headers, invalid sizes, exceeded limits, or failed I/O.
+
+ Size-zero boxes extend to EOF; their containing interval must end at EOF.
+ Skipping the payload does not read or charge its bytes. Failure may consume
+ header bytes; callers must not resume parsing after an error.
+ */
+ BmffBox readBox(BmffCursor& input);
+
+ /*!
+ @brief Visit sibling boxes in order, leaving container recognition to the adapter.
+ @param input A cursor belonging to this reader, bounding the sibling range.
+ @param depth Nesting depth; root is zero and recursive child visits add one.
+ @param visitor Callback taking a mutable BmffBox and bounded payload cursor.
+ @param count Maximum sibling boxes to visit; defaults to the entire range.
+ @throws Error For invalid structure, depth, exhausted budgets, or failed I/O.
+
+ The callback may read a prefix and recursively visit the remaining payload
+ with depth + 1, populate children, or leave the payload opaque. It must not
+ retain references to the callback arguments. Unconsumed payload bytes are
+ skipped; input reaches its end or the requested count on success. Callback
+ exceptions propagate. Counted format tables validate their expected count.
+ */
+ template
+ void visit(BmffCursor& input, unsigned depth, Visitor&& visitor, uint64_t count = UINT64_MAX) {
+ checkTraversal(input, depth);
+ while (input.remaining() != 0 && count != 0) {
+ --count;
+ auto box = readBox(input);
+ auto fields = cursor(box.payload());
+ visitor(box, fields);
+ }
+ }
+
+ private:
+ friend class BmffCursor;
+
+ //! @brief Read an already bounded field and update the aggregate byte budget.
+ void read(uint64_t offset, uint8_t* bytes, size_t size);
+
+ //! @brief Validate cursor ownership and nesting before a sibling traversal.
+ void checkTraversal(const BmffCursor& input, unsigned depth) const;
+
+ BasicIo& io_;
+ BmffReadLimits limits_;
+ uint64_t fileSize_;
+ uint64_t boxes_{};
+ uint64_t bytes_{};
+};
+
+} // namespace Exiv2::Internal
+#endif // EXV_ENABLE_BMFF
+#endif // BMFFBOX_INT_HPP
diff --git a/src/bmffimage.cpp b/src/bmffimage.cpp
index afeb4fb560..df4ed3e213 100644
--- a/src/bmffimage.cpp
+++ b/src/bmffimage.cpp
@@ -4,7 +4,9 @@
#include "bmffimage.hpp"
#include "basicio.hpp"
+#include "bmffbox_int.hpp"
#include "config.h"
+#include "cr3preview_int.hpp"
#include "enforce.hpp"
#include "error.hpp"
#include "futils.hpp"
@@ -22,9 +24,11 @@
#endif
// + standard includes
+#include
#include
#include
#include
+#include
#include
enum TAG {
@@ -113,7 +117,7 @@ bool BmffImage::fullBox(uint32_t box) {
static bool skipBox(uint32_t box) {
// Allows boxHandler() to optimise the reading of files by identifying
// box types that we're not interested in. Box types listed here must
- // not appear in the cases in switch (box_type) in boxHandler().
+ // not appear in the legacy adapter's switch (box_type).
return box == 0 || box == TAG::mdat; // mdat is where the main image lives and can be huge
}
@@ -223,181 +227,215 @@ void BmffImage::brotliUncompress(const byte* compressedBuf, size_t compressedBuf
}
#endif
-uint64_t BmffImage::boxHandler(std::ostream& out /* = std::cout*/, Exiv2::PrintStructureOption option /* = kpsNone */,
- uint64_t pbox_end, size_t depth) {
- const size_t address = io_->tell();
- // never visit a box twice!
- if (depth == 0)
- visits_.clear();
- if (visits_.contains(address) || visits_.size() > visits_max_ || depth >= max_recursion_depth_) {
- throw Error(ErrorCode::kerCorruptedMetadata);
+namespace Internal {
+
+/*!
+ @brief Preserve legacy metadata interpretation while borrowing the shared box reader.
+
+ The image and its open input must outlive this adapter. Friendship grants state
+ access without adding BmffImage members or exported methods. Aggregate core
+ budgets are unrestricted; legacy per-root visit and recursion limits apply.
+ */
+class BmffLegacyReader {
+ public:
+ //! @brief Borrow the image and retain its existing per-root visit and recursion limits.
+ explicit BmffLegacyReader(BmffImage& image) :
+ image_(image),
+ reader_(*image.io_, {std::numeric_limits::max(), std::numeric_limits::max(),
+ std::numeric_limits::max()}) {
}
- visits_.insert(address);
-#ifdef EXIV2_DEBUG_MESSAGES
- bool bTrace = true;
-#else
- bool bTrace = option == kpsBasic || option == kpsRecursive;
-#endif
-
- // 8-byte buffer for parsing the box length and type.
- byte hdrbuf[2 * sizeof(uint32_t)];
-
- size_t hdrsize = sizeof(hdrbuf);
- Internal::enforce(hdrsize <= static_cast(pbox_end - address), Exiv2::ErrorCode::kerCorruptedMetadata);
- if (io_->read(hdrbuf, sizeof(hdrbuf)) != sizeof(hdrbuf))
- return pbox_end;
-
- // The box length is encoded as a uint32_t by default, but the special value 1 means
- // that it's a uint64_t.
- uint64_t box_length = getULong(&hdrbuf[0], endian_);
- uint32_t box_type = getULong(&hdrbuf[sizeof(uint32_t)], endian_);
- bool bLF = true;
-
- if (bTrace) {
- bLF = true;
- out << Internal::indent(depth) << "Exiv2::BmffImage::boxHandler: " << toAscii(box_type)
- << stringFormat(" {:8}->{} ", address, box_length);
+ //! @brief Visit all top-level boxes, preserving stream position at the end of the file.
+ void all(std::ostream& out, PrintStructureOption option, size_t depth) {
+ readingMetadata_ = option == kpsNone;
+ auto input = reader_.cursor({0, reader_.fileSize()});
+ walk(input, out, option, depth);
+
+ // Track previews supplement Canon's existing thumbnail/preview slots on metadata reads only.
+ if (readingMetadata_ && image_.fileType_ == TAG::crx && image_.nativePreviews_.size() < 4) {
+ const auto preview = findCr3JpegPreview(*image_.io_, image_.max_recursion_depth_);
+ if (preview &&
+ std::none_of(image_.nativePreviews_.begin(), image_.nativePreviews_.end(), [&](const NativePreview& current) {
+ return current.position_ == preview->position_ && current.size_ == preview->size_;
+ }))
+ image_.nativePreviews_.push_back(*preview);
+ image_.io_->seekOrThrow(static_cast(reader_.fileSize()), BasicIo::beg,
+ ErrorCode::kerInputDataReadFailed);
+ }
}
- if (box_length == 1) {
- // The box size is encoded as a uint64_t, so we need to read another 8 bytes.
- hdrsize += 8;
- Internal::enforce(hdrsize <= static_cast(pbox_end - address), Exiv2::ErrorCode::kerCorruptedMetadata);
- DataBuf data(8);
- io_->read(data.data(), data.size());
- box_length = data.read_uint64(0, endian_);
+ //! @brief Preserve the exported boxHandler entry point for one subtree at the current position.
+ uint64_t one(std::ostream& out, PrintStructureOption option, uint64_t parentEnd, size_t depth) {
+ // Direct subtree callers retain the historical metadata/preview side effects.
+ readingMetadata_ = true;
+ const auto start = image_.io_->tell();
+ enforce(start <= parentEnd, ErrorCode::kerCorruptedMetadata);
+ auto input = reader_.cursor({start, parentEnd - start});
+ auto box = reader_.readBox(input);
+ auto fields = reader_.cursor(box.payload());
+ handle(box, fields, out, option, depth);
+ return box.span.offset + box.span.size;
}
- if (box_length == 0) {
- // Zero length is also valid and indicates box extends to the end of file.
- box_length = pbox_end - address;
+ private:
+ // Use the core's sibling traversal; counted iinf children may leave trailing bytes opaque.
+ void walk(BmffCursor& input, std::ostream& out, PrintStructureOption option, size_t depth,
+ uint64_t count = std::numeric_limits::max()) {
+ enforce(depth <= std::numeric_limits::max(), ErrorCode::kerCorruptedMetadata);
+ uint64_t visited = 0;
+ reader_.visit(
+ input, static_cast(depth),
+ [&](BmffBox& box, BmffCursor& fields) {
+ handle(box, fields, out, option, depth);
+ ++visited;
+ },
+ count);
+ enforce(count == std::numeric_limits::max() || visited == count, ErrorCode::kerCorruptedMetadata);
+ image_.io_->seekOrThrow(static_cast(input.position()), BasicIo::beg, ErrorCode::kerInputDataReadFailed);
}
- // read data in box and restore file position
- const size_t restore = io_->tell();
- Internal::enforce(box_length >= hdrsize, Exiv2::ErrorCode::kerCorruptedMetadata);
- Internal::enforce(box_length - hdrsize <= pbox_end - restore, Exiv2::ErrorCode::kerCorruptedMetadata);
+ // Decode fields in the historical order; policy and compatibility heuristics stay here.
+ void handle(const BmffBox& box, BmffCursor& fields, std::ostream& out, PrintStructureOption option, size_t depth) {
+ const auto previewCount = image_.nativePreviews_.size();
+ const auto address = box.span.offset;
+ if (depth == 0)
+ image_.visits_.clear();
+ if (image_.visits_.contains(address) || image_.visits_.size() > image_.visits_max_ ||
+ depth >= image_.max_recursion_depth_)
+ throw Error(ErrorCode::kerCorruptedMetadata);
+ image_.visits_.insert(address);
- const auto buffer_size = box_length - hdrsize;
- if (skipBox(box_type)) {
+#ifdef EXIV2_DEBUG_MESSAGES
+ const bool bTrace = true;
+#else
+ const bool bTrace = option == kpsBasic || option == kpsRecursive;
+#endif
+ const auto box_type = box.type;
+ const auto box_length = box.span.size;
+ bool bLF = true;
if (bTrace) {
- out << '\n';
+ out << Internal::indent(depth) << "Exiv2::BmffImage::boxHandler: " << image_.toAscii(box_type)
+ << stringFormat(" {:8}->{} ", address, box.size32);
}
- // The enforce() above checks that restore + buffer_size won't
- // exceed pbox_end, and by implication, won't exceed LONG_MAX
- return restore + buffer_size;
- }
-
- DataBuf data(static_cast(buffer_size));
- const size_t box_end = restore + data.size();
- io_->read(data.data(), data.size());
- io_->seek(restore, BasicIo::beg);
-
- size_t skip = 0; // read position in data.pData_
- uint8_t version = 0;
- uint32_t flags = 0;
- if (fullBox(box_type)) {
- Internal::enforce(data.size() - skip >= 4, Exiv2::ErrorCode::kerCorruptedMetadata);
- flags = data.read_uint32(skip, endian_); // version/flags
- version = static_cast(flags >> 24);
- flags &= 0x00ffffff;
- skip += 4;
- }
-
- switch (box_type) {
- // See notes in skipBox()
- case TAG::ftyp: {
- Internal::enforce(data.size() >= 4, Exiv2::ErrorCode::kerCorruptedMetadata);
- fileType_ = data.read_uint32(0, endian_);
- if (bTrace) {
- out << "brand: " << toAscii(fileType_);
- }
- } break;
-
- // 8.11.6.1
- case TAG::iinf: {
- if (bTrace) {
+ // Legacy field and preview offsets exclude the size/type header, but include UUID bytes.
+ const auto headerSize = box.headerSize - (box_type == TAG::uuid ? 16 : 0);
+ const auto restore = box.span.offset + headerSize;
+ const auto buffer_size = box.span.size - headerSize;
+ if (skipBox(box_type)) {
+ if (bTrace)
out << '\n';
- bLF = false;
- }
+ return;
+ }
- Internal::enforce(data.size() - skip >= 2, Exiv2::ErrorCode::kerCorruptedMetadata);
- uint16_t n = data.read_uint16(skip, endian_);
- skip += 2;
+ // Preserve legacy whole-box field buffers while using checked source reads.
+ enforce(buffer_size <= std::numeric_limits::max(), ErrorCode::kerCorruptedMetadata);
+ DataBuf data(static_cast(buffer_size));
+ auto payload = reader_.cursor({restore, buffer_size});
+ payload.read(data.data(), data.size());
+ image_.io_->seekOrThrow(static_cast(restore), BasicIo::beg, ErrorCode::kerInputDataReadFailed);
+ size_t skip = 0; // read position in data.pData_
+ uint8_t version = 0;
+
+ if (image_.fullBox(box_type)) {
+ Internal::enforce(data.size() - skip >= 4, Exiv2::ErrorCode::kerCorruptedMetadata);
+ const auto full = decodeBmffFullBox(data.read_uint32(skip, BmffImage::endian_));
+ version = full.version;
+ skip += 4;
+ }
- io_->seek(skip, BasicIo::cur);
- while (n-- > 0) {
- io_->seek(boxHandler(out, option, box_end, depth + 1), BasicIo::beg);
- }
- } break;
+ switch (box_type) {
+ // See notes in skipBox()
+ case TAG::ftyp: {
+ Internal::enforce(data.size() >= 4, Exiv2::ErrorCode::kerCorruptedMetadata);
+ image_.fileType_ = data.read_uint32(0, BmffImage::endian_);
+ // Repeated CR3 reads replace the exposed preview view, including changed backing input.
+ if (readingMetadata_ && depth == 0 && image_.fileType_ == TAG::crx)
+ image_.nativePreviews_.clear();
+ if (bTrace) {
+ out << "brand: " << image_.toAscii(image_.fileType_);
+ }
+ } break;
- // 8.11.6.2
- case TAG::infe: { // .__._.__hvc1_ 2 0 0 1 0 1 0 0 104 118 99 49 0
- Internal::enforce(data.size() - skip >= 8, Exiv2::ErrorCode::kerCorruptedMetadata);
- /* getULong (data.pData_+skip,endian_) ; */ skip += 4;
- uint16_t ID = data.read_uint16(skip, endian_);
- skip += 2;
- /* getShort(data.pData_+skip,endian_) ; */ skip += 2; // protection
- std::string id;
- // Check that the string has a '\0' terminator.
- const char* str = data.c_str(skip);
- const size_t maxlen = data.size() - skip;
- Internal::enforce(maxlen > 0 && strnlen(str, maxlen) < maxlen, Exiv2::ErrorCode::kerCorruptedMetadata);
- std::string name(str);
- if (Internal::contains(name, "Exif")) { // "Exif" or "ExifExif"
- exifID_ = ID;
- id = " *** Exif ***";
- } else if (Internal::contains(name, "mime\0xmp") || Internal::contains(name, "mime\0application/rdf+xml")) {
- xmpID_ = ID;
- id = " *** XMP ***";
- }
- if (bTrace) {
- out << stringFormat("ID = {:3} {} {}", ID, name, id);
- }
- } break;
+ // 8.11.6.1
+ case TAG::iinf: {
+ if (bTrace) {
+ out << '\n';
+ bLF = false;
+ }
- case TAG::moov:
- case TAG::iprp:
- case TAG::ipco:
- case TAG::meta: {
- if (bTrace) {
- out << '\n';
- bLF = false;
- }
- io_->seek(skip, BasicIo::cur);
- while (io_->tell() < box_end) {
- io_->seek(boxHandler(out, option, box_end, depth + 1), BasicIo::beg);
- }
- // post-process meta box to recover Exif and XMP
- if (box_type == TAG::meta) {
- auto ilo = ilocs_.find(exifID_);
- if (ilo != ilocs_.end()) {
- const Iloc& iloc = ilo->second;
- if (bTrace) {
- out << Internal::indent(depth) << "Exiv2::BMFF Exif: " << iloc.toString() << '\n';
- }
- parseTiff(Internal::Tag::root, iloc.length_, iloc.start_);
+ Internal::enforce(data.size() - skip >= 2, Exiv2::ErrorCode::kerCorruptedMetadata);
+ // The legacy reader uses a 16-bit count even for newer iinf versions.
+ uint16_t n = data.read_uint16(skip, BmffImage::endian_);
+ skip += 2;
+
+ auto children = reader_.cursor({restore + skip, buffer_size - skip});
+ walk(children, out, option, depth + 1, n);
+ } break;
+
+ // 8.11.6.2
+ case TAG::infe: { // .__._.__hvc1_ 2 0 0 1 0 1 0 0 104 118 99 49 0
+ Internal::enforce(data.size() - skip >= 8, Exiv2::ErrorCode::kerCorruptedMetadata);
+ /* getULong (data.pData_+skip,BmffImage::endian_) ; */ skip += 4;
+ uint16_t ID = data.read_uint16(skip, BmffImage::endian_);
+ skip += 2;
+ /* getShort(data.pData_+skip,BmffImage::endian_) ; */ skip += 2; // protection
+ std::string id;
+ // Check that the string has a '\0' terminator.
+ const char* str = data.c_str(skip);
+ const size_t maxlen = data.size() - skip;
+ Internal::enforce(maxlen > 0 && strnlen(str, maxlen) < maxlen, Exiv2::ErrorCode::kerCorruptedMetadata);
+ std::string name(str);
+ if (Internal::contains(name, "Exif")) { // "Exif" or "ExifExif"
+ image_.exifID_ = ID;
+ id = " *** Exif ***";
+ } else if (Internal::contains(name, "mime\0xmp") || Internal::contains(name, "mime\0application/rdf+xml")) {
+ image_.xmpID_ = ID;
+ id = " *** XMP ***";
}
- ilo = ilocs_.find(xmpID_);
- if (ilo != ilocs_.end()) {
- const Iloc& iloc = ilo->second;
- if (bTrace) {
- out << Internal::indent(depth) << "Exiv2::BMFF XMP: " << iloc.toString() << '\n';
- }
- parseXmp(iloc.length_, iloc.start_);
+ if (bTrace) {
+ out << stringFormat("ID = {:3} {} {}", ID, name, id);
}
- ilocs_.clear();
- }
- } break;
+ } break;
- // 8.11.3.1
- case TAG::iloc: {
- Internal::enforce(data.size() - skip >= 2, Exiv2::ErrorCode::kerCorruptedMetadata);
- uint8_t u = data.read_uint8(skip++);
- uint16_t offsetSize = u >> 4;
- uint16_t lengthSize = u & 0xF;
+ case TAG::moov:
+ case TAG::iprp:
+ case TAG::ipco:
+ case TAG::meta: {
+ if (bTrace) {
+ out << '\n';
+ bLF = false;
+ }
+ auto children = reader_.cursor({restore + skip, buffer_size - skip});
+ walk(children, out, option, depth + 1);
+ // post-process meta box to recover Exif and XMP
+ if (box_type == TAG::meta) {
+ auto ilo = image_.ilocs_.find(image_.exifID_);
+ if (ilo != image_.ilocs_.end()) {
+ const Iloc& iloc = ilo->second;
+ if (bTrace) {
+ out << Internal::indent(depth) << "Exiv2::BMFF Exif: " << iloc.toString() << '\n';
+ }
+ image_.parseTiff(Internal::Tag::root, iloc.length_, iloc.start_);
+ }
+ ilo = image_.ilocs_.find(image_.xmpID_);
+ if (ilo != image_.ilocs_.end()) {
+ const Iloc& iloc = ilo->second;
+ if (bTrace) {
+ out << Internal::indent(depth) << "Exiv2::BMFF XMP: " << iloc.toString() << '\n';
+ }
+ image_.parseXmp(iloc.length_, iloc.start_);
+ }
+ image_.ilocs_.clear();
+ }
+ } break;
+
+ // Retain legacy fixed-stride iloc heuristics separately from strict item validation.
+ case TAG::iloc: {
+ Internal::enforce(data.size() - skip >= 2, Exiv2::ErrorCode::kerCorruptedMetadata);
+ uint8_t u = data.read_uint8(skip++);
+ uint16_t offsetSize = u >> 4;
+ uint16_t lengthSize = u & 0xF;
#if 0
uint16_t indexSize = 0 ;
u = data.read_uint8(skip++);
@@ -405,179 +443,193 @@ uint64_t BmffImage::boxHandler(std::ostream& out /* = std::cout*/, Exiv2::PrintS
indexSize = u & 0xF ;
}
#else
- skip++;
+ skip++;
#endif
- Internal::enforce(data.size() - skip >= (version < 2u ? 2u : 4u), Exiv2::ErrorCode::kerCorruptedMetadata);
- uint32_t itemCount = version < 2 ? data.read_uint16(skip, endian_) : data.read_uint32(skip, endian_);
- skip += version < 2 ? 2 : 4;
- if (itemCount && itemCount < box_length / 14 && offsetSize == 4 && lengthSize == 4 &&
- ((box_length - 16) % itemCount) == 0) {
- if (bTrace) {
- out << '\n';
- bLF = false;
- }
- auto step = (static_cast(box_length) - 16) / itemCount; // length of data per item.
- size_t base = skip;
- for (uint32_t i = 0; i < itemCount; i++) {
- skip = base + (i * step); // move in 14, 16 or 18 byte steps
- Internal::enforce(data.size() - skip >= (version > 2u ? 4u : 2u), Exiv2::ErrorCode::kerCorruptedMetadata);
- Internal::enforce(data.size() - skip >= step, Exiv2::ErrorCode::kerCorruptedMetadata);
- uint32_t ID = version > 2 ? data.read_uint32(skip, endian_) : data.read_uint16(skip, endian_);
- auto offset = [&data, skip, step] {
- if (step == 14 || step == 16)
- return data.read_uint32(skip + step - 8, endian_);
- if (step == 18)
- return data.read_uint32(skip + 4, endian_);
- return 0u;
- }();
-
- uint32_t ldata = data.read_uint32(skip + step - 4, endian_);
+ Internal::enforce(data.size() - skip >= (version < 2u ? 2u : 4u), Exiv2::ErrorCode::kerCorruptedMetadata);
+ uint32_t itemCount =
+ version < 2 ? data.read_uint16(skip, BmffImage::endian_) : data.read_uint32(skip, BmffImage::endian_);
+ skip += version < 2 ? 2 : 4;
+ if (itemCount && itemCount < box_length / 14 && offsetSize == 4 && lengthSize == 4 &&
+ ((box_length - 16) % itemCount) == 0) {
if (bTrace) {
- out << Internal::indent(depth)
- << stringFormat("{:8} | {:8} | ID | {:4} | {:6},{:6}\n", address + skip, step, ID, offset, ldata);
+ out << '\n';
+ bLF = false;
}
- // save data for post-processing in meta box
- if (offset && ldata && ID != unknownID_) {
- ilocs_[ID] = Iloc{ID, offset, ldata};
+ auto step = (static_cast(box_length) - 16) / itemCount; // length of data per item.
+ size_t base = skip;
+ for (uint32_t i = 0; i < itemCount; i++) {
+ skip = base + (i * step); // move in 14, 16 or 18 byte steps
+ Internal::enforce(data.size() - skip >= (version > 2u ? 4u : 2u), Exiv2::ErrorCode::kerCorruptedMetadata);
+ Internal::enforce(data.size() - skip >= step, Exiv2::ErrorCode::kerCorruptedMetadata);
+ uint32_t ID =
+ version > 2 ? data.read_uint32(skip, BmffImage::endian_) : data.read_uint16(skip, BmffImage::endian_);
+ auto offset = [&data, skip, step] {
+ if (step == 14 || step == 16)
+ return data.read_uint32(skip + step - 8, BmffImage::endian_);
+ if (step == 18)
+ return data.read_uint32(skip + 4, BmffImage::endian_);
+ return 0u;
+ }();
+
+ uint32_t ldata = data.read_uint32(skip + step - 4, BmffImage::endian_);
+ if (bTrace) {
+ out << Internal::indent(depth)
+ << stringFormat("{:8} | {:8} | ID | {:4} | {:6},{:6}\n", address + skip, step, ID, offset, ldata);
+ }
+ // save data for post-processing in meta box
+ if (offset && ldata && ID != image_.unknownID_) {
+ image_.ilocs_[ID] = Iloc{ID, offset, ldata};
+ }
}
}
- }
- } break;
-
- case TAG::ispe: {
- Internal::enforce(data.size() - skip >= 12, Exiv2::ErrorCode::kerCorruptedMetadata);
- skip += 4;
- uint32_t width = data.read_uint32(skip, endian_);
- skip += 4;
- uint32_t height = data.read_uint32(skip, endian_);
- skip += 4;
- if (bTrace) {
- out << stringFormat("pixelWidth_, pixelHeight_ = {}, {}", width, height);
- }
- // HEIC files can have multiple ispe records
- // Store largest width/height
- if (width > pixelWidth_ && height > pixelHeight_) {
- pixelWidth_ = width;
- pixelHeight_ = height;
- }
- } break;
+ } break;
- // 12.1.5.2
- case TAG::colr: {
- if (data.size() >= (skip + 4 + 8)) { // .____.HLino..__mntrR 2 0 0 0 0 12 72 76 105 110 111 2 16 ...
- // https://www.ics.uci.edu/~dan/class/267/papers/jpeg2000.pdf
- uint8_t meth = data.read_uint8(skip + 0);
- uint8_t prec = data.read_uint8(skip + 1);
- uint8_t approx = data.read_uint8(skip + 2);
- auto colour_type = std::string(data.c_str(), 4);
+ case TAG::ispe: {
+ Internal::enforce(data.size() - skip >= 12, Exiv2::ErrorCode::kerCorruptedMetadata);
skip += 4;
- if (colour_type == "rICC" || colour_type == "prof") {
- DataBuf profile(data.c_data(skip), data.size() - skip);
- setIccProfile(std::move(profile));
- } else if (meth == 2 && prec == 0 && approx == 0) {
- // JP2000 files have a 3 byte head // 2 0 0 icc......
- skip -= 1;
- DataBuf profile(data.c_data(skip), data.size() - skip);
- setIccProfile(std::move(profile));
+ uint32_t width = data.read_uint32(skip, BmffImage::endian_);
+ skip += 4;
+ uint32_t height = data.read_uint32(skip, BmffImage::endian_);
+ skip += 4;
+ if (bTrace) {
+ out << stringFormat("pixelWidth_, pixelHeight_ = {}, {}", width, height);
}
- }
- } break;
-
- case TAG::uuid: {
- DataBuf uuid(16);
- io_->read(uuid.data(), uuid.size());
- std::string name = uuidName(uuid);
- if (bTrace) {
- out << " uuidName " << name << '\n';
- bLF = false;
- }
- if (name == "cano" || name == "canp") {
- if (name == "canp") {
- // based on
- // https://github.com/lclevy/canon_cr3/blob/7be75d6/parse_cr3.py#L271
- io_->seek(8, BasicIo::cur);
+ // HEIC files can have multiple ispe records
+ // Store largest width/height
+ if (width > image_.pixelWidth_ && height > image_.pixelHeight_) {
+ image_.pixelWidth_ = width;
+ image_.pixelHeight_ = height;
}
- while (io_->tell() < box_end) {
- io_->seek(boxHandler(out, option, box_end, depth + 1), BasicIo::beg);
+ } break;
+
+ // 12.1.5.2
+ case TAG::colr: {
+ if (data.size() >= (skip + 4 + 8)) { // .____.HLino..__mntrR 2 0 0 0 0 12 72 76 105 110 111 2 16 ...
+ // https://www.ics.uci.edu/~dan/class/267/papers/jpeg2000.pdf
+ uint8_t meth = data.read_uint8(skip + 0);
+ uint8_t prec = data.read_uint8(skip + 1);
+ uint8_t approx = data.read_uint8(skip + 2);
+ auto colour_type = std::string(data.c_str(), 4);
+ skip += 4;
+ if (colour_type == "rICC" || colour_type == "prof") {
+ DataBuf profile(data.c_data(skip), data.size() - skip);
+ image_.setIccProfile(std::move(profile));
+ } else if (meth == 2 && prec == 0 && approx == 0) {
+ // JP2000 files have a 3 byte head // 2 0 0 icc......
+ skip -= 1;
+ DataBuf profile(data.c_data(skip), data.size() - skip);
+ image_.setIccProfile(std::move(profile));
+ }
}
- } else if (name == "xmp") {
- parseXmp(box_length, io_->tell());
- }
- } break;
+ } break;
- case TAG::cmt1:
- parseTiff(Internal::Tag::root, box_length);
- break;
- case TAG::cmt2:
- parseTiff(Internal::Tag::cmt2, box_length);
- break;
- case TAG::cmt3:
- parseTiff(Internal::Tag::cmt3, box_length);
- break;
- case TAG::cmt4:
- parseTiff(Internal::Tag::cmt4, box_length);
- break;
- case TAG::exif:
- parseTiff(Internal::Tag::root, buffer_size, io_->tell());
- break;
- case TAG::xml:
- parseXmp(buffer_size, io_->tell());
- break;
- case TAG::brob: {
- Internal::enforce(data.size() >= 4, Exiv2::ErrorCode::kerCorruptedMetadata);
- uint32_t realType = data.read_uint32(0, endian_);
- if (bTrace) {
- out << "type: " << toAscii(realType);
- }
+ case TAG::uuid: {
+ DataBuf uuid(box.userType.data(), box.userType.size());
+ image_.io_->seekOrThrow(static_cast(fields.position()), BasicIo::beg,
+ ErrorCode::kerInputDataReadFailed);
+ std::string name = image_.uuidName(uuid);
+ if (bTrace) {
+ out << " uuidName " << name << '\n';
+ bLF = false;
+ }
+ if (name == "cano" || name == "canp") {
+ if (name == "canp") {
+ // based on
+ // https://github.com/lclevy/canon_cr3/blob/7be75d6/parse_cr3.py#L271
+ fields.advance(8);
+ }
+ walk(fields, out, option, depth + 1);
+ } else if (name == "xmp") {
+ // Preserve the legacy UUID packet length and its existing decoding errors.
+ image_.parseXmp(box_length, image_.io_->tell());
+ }
+ } break;
+
+ case TAG::cmt1:
+ image_.parseTiff(Internal::Tag::root, box_length);
+ break;
+ case TAG::cmt2:
+ image_.parseTiff(Internal::Tag::cmt2, box_length);
+ break;
+ case TAG::cmt3:
+ image_.parseTiff(Internal::Tag::cmt3, box_length);
+ break;
+ case TAG::cmt4:
+ image_.parseTiff(Internal::Tag::cmt4, box_length);
+ break;
+ case TAG::exif:
+ image_.parseTiff(Internal::Tag::root, buffer_size, image_.io_->tell());
+ break;
+ case TAG::xml:
+ image_.parseXmp(buffer_size, image_.io_->tell());
+ break;
+ case TAG::brob: {
+ Internal::enforce(data.size() >= 4, Exiv2::ErrorCode::kerCorruptedMetadata);
+ uint32_t realType = data.read_uint32(0, BmffImage::endian_);
+ if (bTrace) {
+ out << "type: " << image_.toAscii(realType);
+ }
#ifdef EXV_HAVE_BROTLI
- DataBuf arr;
- brotliUncompress(data.c_data(4), data.size() - 4, arr);
- const DecodeParams dp(max_recursion_depth_);
- if (realType == TAG::exif) {
- uint32_t offset = Safe::add(arr.read_uint32(0, endian_), 4u);
- Internal::enforce(Safe::add(offset, 4u) < arr.size(), Exiv2::ErrorCode::kerCorruptedMetadata);
- Internal::TiffParserWorker::decode(exifData(), iptcData(), xmpData(), arr.c_data(offset), arr.size() - offset,
- Internal::Tag::root, Internal::TiffMapping::findDecoder, dp);
- } else if (realType == TAG::xml) {
- try {
- Exiv2::XmpParser::decode(xmpData(), std::string(arr.c_str(), arr.size()), dp);
- } catch (...) {
- throw Error(ErrorCode::kerFailedToReadImageData);
+ DataBuf arr;
+ image_.brotliUncompress(data.c_data(4), data.size() - 4, arr);
+ const DecodeParams dp(image_.max_recursion_depth_);
+ if (realType == TAG::exif) {
+ uint32_t offset = Safe::add(arr.read_uint32(0, BmffImage::endian_), 4u);
+ Internal::enforce(Safe::add(offset, 4u) < arr.size(), Exiv2::ErrorCode::kerCorruptedMetadata);
+ Internal::TiffParserWorker::decode(image_.exifData(), image_.iptcData(), image_.xmpData(), arr.c_data(offset),
+ arr.size() - offset, Internal::Tag::root,
+ Internal::TiffMapping::findDecoder, dp);
+ } else if (realType == TAG::xml) {
+ try {
+ Exiv2::XmpParser::decode(image_.xmpData(), std::string(arr.c_str(), arr.size()), dp);
+ } catch (...) {
+ throw Error(ErrorCode::kerFailedToReadImageData);
+ }
}
- }
#endif
- } break;
- case TAG::thmb:
- switch (version) {
- case 0: // JPEG
- parseCr3Preview(data, out, bTrace, version, skip, skip + 2, skip + 4, skip + 12);
- break;
- case 1: // HDR
- parseCr3Preview(data, out, bTrace, version, skip + 2, skip + 4, skip + 8, skip + 12);
- break;
- default:
- break;
- }
- break;
- case TAG::prvw:
- switch (version) {
- case 0: // JPEG
- case 1: // HDR
- parseCr3Preview(data, out, bTrace, version, skip + 2, skip + 4, skip + 8, skip + 12);
- break;
- default:
- break;
- }
- break;
+ } break;
+ case TAG::thmb:
+ switch (version) {
+ case 0: // JPEG
+ image_.parseCr3Preview(data, out, bTrace, version, skip, skip + 2, skip + 4, skip + 12);
+ break;
+ case 1: // HDR
+ image_.parseCr3Preview(data, out, bTrace, version, skip + 2, skip + 4, skip + 8, skip + 12);
+ break;
+ default:
+ break;
+ }
+ break;
+ case TAG::prvw:
+ switch (version) {
+ case 0: // JPEG
+ case 1: // HDR
+ image_.parseCr3Preview(data, out, bTrace, version, skip + 2, skip + 4, skip + 8, skip + 12);
+ break;
+ default:
+ break;
+ }
+ break;
- default:
- break; /* do nothing */
+ default:
+ break; /* do nothing */
+ }
+ if (bLF && bTrace)
+ out << '\n';
+
+ // Structure printing retains its text while avoiding duplicate Canon preview entries.
+ if (!readingMetadata_ && image_.fileType_ == TAG::crx && (box_type == TAG::thmb || box_type == TAG::prvw))
+ image_.nativePreviews_.resize(previewCount);
}
- if (bLF && bTrace)
- out << '\n';
- // return address of next box
- return box_end;
+ BmffImage& image_;
+ BmffReader reader_;
+ bool readingMetadata_{};
+};
+} // namespace Internal
+
+uint64_t BmffImage::boxHandler(std::ostream& out, PrintStructureOption option, uint64_t pbox_end, size_t depth) {
+ return Internal::BmffLegacyReader(*this).one(out, option, pbox_end, depth);
}
void BmffImage::parseTiff(uint32_t root_tag, uint64_t length, uint64_t start) {
@@ -717,12 +769,7 @@ void BmffImage::readMetadata() {
exifID_ = unknownID_;
xmpID_ = unknownID_;
- uint64_t address = 0;
- const auto file_end = io_->size();
- while (address < file_end) {
- io_->seek(address, BasicIo::beg);
- address = boxHandler(std::cout, kpsNone, file_end, 0);
- }
+ Internal::BmffLegacyReader(*this).all(std::cout, kpsNone, 0);
bReadMetadata_ = true;
} // BmffImage::readMetadata
@@ -752,12 +799,7 @@ void BmffImage::printStructure(std::ostream& out, Exiv2::PrintStructureOption op
openOrThrow();
IoCloser closer(*io_);
- uint64_t address = 0;
- const auto file_end = io_->size();
- while (address < file_end) {
- io_->seek(address, BasicIo::beg);
- address = boxHandler(out, option, file_end, depth);
- }
+ Internal::BmffLegacyReader(*this).all(out, option, depth);
} break;
}
}
diff --git a/src/bmffitem_int.cpp b/src/bmffitem_int.cpp
new file mode 100644
index 0000000000..987e10ff14
--- /dev/null
+++ b/src/bmffitem_int.cpp
@@ -0,0 +1,453 @@
+// SPDX-License-Identifier: GPL-2.0-or-later
+
+#include "bmffitem_int.hpp"
+
+#ifdef EXV_ENABLE_BMFF
+
+#include "basicio.hpp"
+#include "enforce.hpp"
+#include "error.hpp"
+
+#include
+#include
+#include
+#include
+#include
+
+namespace Exiv2::Internal {
+namespace {
+
+// Report malformed structure through the common metadata error code.
+void require(bool condition) {
+ enforce(condition, ErrorCode::kerCorruptedMetadata);
+}
+
+// Charge aggregate work without overflowing the counter or its limit.
+void consume(uint64_t& used, uint64_t amount, uint64_t limit) {
+ require(used <= limit && amount <= limit - used);
+ used += amount;
+}
+
+// Shared counters bound work across all nested boxes in one parse.
+struct Budget {
+ const BmffItemLimits& limits;
+ uint64_t extents{};
+ uint64_t references{};
+ uint64_t associations{};
+ uint64_t strings{};
+};
+
+using Cursor = BmffCursor;
+
+// Interpret child box types according to their immediate container.
+enum class Context { meta, info, properties, propertyList, references, dataInfo, dataRefs };
+
+// Build a range-backed item graph, then validate links after all boxes are known.
+class Parser {
+ public:
+ //! @brief Borrow the enclosing reader, item budgets and format policy for one meta box.
+ Parser(BmffReader& reader, const BmffItemLimits& limits, const BmffItemPolicy& policy) :
+ reader_(reader), budget_{limits}, policy_(policy) {
+ }
+
+ //! @brief Decode tables while leaving range and cross-table validation to resolveBmffItems.
+ BmffItemModel parse(BmffBox& box, Cursor& fields, unsigned childDepth) {
+ fullBox(box, fields, 0);
+ box.children = children(fields, Context::meta, childDepth);
+ policy_.checkMeta(box);
+ return std::move(model_);
+ }
+
+ private:
+ // Delegate unsupported-syntax diagnostics without putting format names in the parser.
+ void supported(bool condition, std::string_view feature) const {
+ if (!condition)
+ policy_.unsupported(feature);
+ }
+
+ // Check whether a container includes a required child type.
+ static bool has(const std::vector& boxes, uint32_t type) {
+ return std::any_of(boxes.begin(), boxes.end(), [type](const auto& box) { return box.type == type; });
+ }
+
+ // Decode item strings while retaining the adapter's per-string and aggregate budgets.
+ std::string string(Cursor& input) {
+ std::string result;
+ while (true) {
+ require(input.remaining() != 0);
+ const auto c = static_cast(input.number(1));
+ consume(budget_.strings, 1, budget_.limits.maxStringBytes);
+ if (c == '\0')
+ return result;
+
+ require(result.size() < budget_.limits.maxStringLength);
+ result.push_back(c);
+ }
+ }
+
+ // Decode version/flags while rejecting unsupported versions and reserved bits.
+ BmffFullBox fullBox(BmffBox& box, Cursor& input, uint8_t maxVersion, uint32_t allowedFlags = 0) {
+ const auto full = decodeBmffFullBox(static_cast(input.number(4)));
+ supported(full.version <= maxVersion, "box version");
+ require((full.flags & ~allowedFlags) == 0);
+ box.fullBox = full;
+ return full;
+ }
+
+ // Find or create an item shared by its independently ordered info/location records.
+ BmffItem& item(uint32_t id) {
+ require(id != 0);
+ const auto found = model_.items.find(id);
+ if (found != model_.items.end())
+ return found->second;
+
+ require(model_.items.size() < budget_.limits.maxItems);
+ return model_.items.try_emplace(id).first->second;
+ }
+
+ // Traverse children with context-specific decoding and a shared nesting budget.
+ std::vector children(Cursor& input, Context context, unsigned depth, uint8_t version = 0) {
+ std::vector boxes;
+ std::set singletons;
+
+ // Singleton checks apply within each immediate container, not globally.
+ reader_.visit(input, depth, [&](BmffBox& box, Cursor& fields) {
+ auto unique = [&] { require(singletons.insert(box.type).second); };
+
+ switch (context) {
+ case Context::meta:
+ if (box.type == bmffType("hdlr")) {
+ unique();
+ fullBox(box, fields, 0);
+ require(fields.number(4) == 0);
+ model_.handler = static_cast(fields.number(4));
+ policy_.checkHandler(model_.handler);
+ for (unsigned i = 0; i < 3; ++i)
+ require(fields.number(4) == 0);
+ // The optional handler name is opaque and stays in its original box.
+ } else if (box.type == bmffType("pitm")) {
+ unique();
+ const auto full = fullBox(box, fields, 1);
+ model_.primaryItem = static_cast(fields.number(full.version == 0 ? 2 : 4));
+ model_.hasPrimaryItem = true;
+ fields.finish();
+ } else if (box.type == bmffType("iinf")) {
+ unique();
+ const auto full = fullBox(box, fields, 2);
+ const auto count = fields.number(full.version == 0 ? 2 : 4);
+ require(count <= budget_.limits.maxItems && count <= fields.remaining() / 8);
+ box.children = children(fields, Context::info, depth + 1);
+ require(box.children.size() == count);
+ } else if (box.type == bmffType("iloc")) {
+ unique();
+ locations(box, fields);
+ } else if (box.type == bmffType("iref")) {
+ unique();
+ const auto full = fullBox(box, fields, 1);
+ box.children = children(fields, Context::references, depth + 1, full.version);
+ } else if (box.type == bmffType("iprp")) {
+ unique();
+ box.children = children(fields, Context::properties, depth + 1);
+ require(has(box.children, bmffType("ipco")));
+ } else if (box.type == bmffType("idat")) {
+ unique();
+ model_.itemData = box.payload();
+ } else if (box.type == bmffType("dinf")) {
+ unique();
+ box.children = children(fields, Context::dataInfo, depth + 1);
+ require(has(box.children, bmffType("dref")));
+ } else {
+ policy_.parseExtension(reader_, box, fields, depth + 1);
+ }
+ break;
+ case Context::info:
+ supported(box.type == bmffType("infe"), "non-infe item info entry");
+ info(box, fields);
+ break;
+ case Context::properties:
+ if (box.type == bmffType("ipco")) {
+ unique();
+ box.children = children(fields, Context::propertyList, depth + 1);
+ model_.properties = box.children;
+ } else if (box.type == bmffType("ipma")) {
+ associations(box, fields);
+ }
+ break;
+ case Context::propertyList:
+ // Property bodies stay opaque. The write gate checks their relocation support.
+ break;
+ case Context::references:
+ reference(box, fields, version);
+ break;
+ case Context::dataInfo:
+ if (box.type == bmffType("dref")) {
+ unique();
+ fullBox(box, fields, 0);
+ const auto count = fields.number(4);
+ require(count <= budget_.limits.maxEntries && count <= fields.remaining() / 8);
+ box.children = children(fields, Context::dataRefs, depth + 1);
+ require(box.children.size() == count);
+ }
+ break;
+ case Context::dataRefs:
+ if (box.type == bmffType("url ")) {
+ const auto full = fullBox(box, fields, 0, 1);
+ supported(full.flags == 1, "external data reference");
+ if (fields.remaining() != 0)
+ require(string(fields).empty());
+ fields.finish();
+ }
+ break;
+ }
+
+ boxes.push_back(std::move(box));
+ });
+ return boxes;
+ }
+
+ // Decode one item description, retaining its original span and MIME details.
+ void info(BmffBox& box, Cursor& input) {
+ const auto full = fullBox(box, input, 3, 1);
+ supported(full.version >= 2, "legacy item info entry");
+
+ // Item info and location records may arrive in either order; IDs join them later.
+ const auto id = static_cast(input.number(full.version == 2 ? 2 : 4));
+ require(infoIds_.insert(id).second);
+ auto& info = item(id).info;
+ info.box = box.span;
+ info.version = full.version;
+ info.flags = full.flags;
+ info.protectionIndex = static_cast(input.number(2));
+ policy_.checkProtection(info.protectionIndex);
+ info.type = static_cast(input.number(4));
+ info.name = string(input);
+
+ // Only MIME and URI items append type-specific strings to the common entry.
+ if (info.type == bmffType("mime")) {
+ info.contentType = string(input);
+ if (input.remaining() != 0)
+ info.contentEncoding = string(input);
+ } else if (info.type == bmffType("uri ")) {
+ info.uriType = string(input);
+ }
+
+ input.finish();
+ model_.infoOrder.push_back(id);
+ }
+
+ // Read iloc field widths and extents; absolute ranges are resolved after parsing.
+ void locations(BmffBox& box, Cursor& input) {
+ const auto full = fullBox(box, input, 2);
+ auto& format = model_.locationFormat;
+ format.box = box.span;
+ format.version = full.version;
+
+ // The four width nibbles control every subsequent location field.
+ const auto widths = input.number(2);
+ format.offsetSize = static_cast(widths >> 12);
+ format.lengthSize = static_cast((widths >> 8) & 15);
+ format.baseOffsetSize = static_cast((widths >> 4) & 15);
+ format.indexSize = static_cast(widths & 15);
+ if (full.version == 0)
+ require(format.indexSize == 0);
+ for (const auto width : {format.offsetSize, format.lengthSize, format.baseOffsetSize, format.indexSize})
+ supported(width == 0 || width == 4 || width == 8, "item location field width");
+ supported(format.lengthSize != 0, "implicit extent length");
+
+ // Bound the item count using the smallest possible record before allocating.
+ const unsigned idWidth = full.version < 2 ? 2 : 4;
+ const auto count = input.number(idWidth);
+ const auto minimum = idWidth + (full.version == 0 ? 0 : 2) + 2 + format.baseOffsetSize + 2;
+ require(count <= budget_.limits.maxItems && count <= input.remaining() / minimum);
+
+ for (uint64_t i = 0; i < count; ++i) {
+ const auto id = static_cast(input.number(idWidth));
+ require(locationIds_.insert(id).second);
+ auto& location = item(id).location;
+ if (full.version != 0) {
+ const auto method = input.number(2);
+ require((method & 0xfff0) == 0);
+ location.constructionMethod = static_cast(method);
+ }
+ supported(location.constructionMethod <= 1, "item construction method");
+ location.dataReferenceIndex = static_cast(input.number(2));
+ supported(location.dataReferenceIndex == 0, "external item location");
+ location.baseOffset = input.number(format.baseOffsetSize);
+
+ // Explicit nonempty extents are required; defer their coordinate conversion.
+ const auto extents = input.number(2);
+ consume(budget_.extents, extents, budget_.limits.maxExtents);
+ require(extents != 0 &&
+ extents <= input.remaining() / (format.indexSize + format.offsetSize + format.lengthSize));
+ location.extents.reserve(static_cast(extents));
+ for (uint64_t j = 0; j < extents; ++j) {
+ BmffExtent extent;
+ extent.index = input.number(format.indexSize);
+ extent.offset = input.number(format.offsetSize);
+ extent.length = input.number(format.lengthSize);
+ supported(extent.length != 0, "implicit extent length");
+ location.extents.push_back(extent);
+ }
+ model_.locationOrder.push_back(id);
+ }
+
+ input.finish();
+ }
+
+ // Retain a directed item relationship using the enclosing iref ID width.
+ void reference(const BmffBox& box, Cursor& input, uint8_t version) {
+ BmffReference ref;
+ ref.box = box.span;
+ ref.type = box.type;
+
+ // The parent iref version controls both source and destination ID widths.
+ const unsigned width = version == 0 ? 2 : 4;
+ ref.from = static_cast(input.number(width));
+ const auto count = input.number(2);
+ consume(budget_.references, count + 1, budget_.limits.maxReferences);
+ require(count <= input.remaining() / width);
+ ref.to.reserve(static_cast(count));
+ for (uint64_t i = 0; i < count; ++i)
+ ref.to.push_back(static_cast(input.number(width)));
+
+ input.finish();
+ model_.references.push_back(std::move(ref));
+ }
+
+ // Read property indices and their essential flags without interpreting properties.
+ void associations(BmffBox& box, Cursor& input) {
+ const auto full = fullBox(box, input, 1, 1);
+ const unsigned idWidth = full.version == 0 ? 2 : 4;
+ const unsigned propertyWidth = (full.flags & 1) ? 2 : 1;
+ const auto count = input.number(4);
+ consume(budget_.associations, count, budget_.limits.maxAssociations);
+ require(count <= input.remaining() / (idWidth + 1));
+
+ // An item may occur once per ipma box; property zero is checked after parsing.
+ std::set ids;
+ for (uint64_t i = 0; i < count; ++i) {
+ BmffAssociationEntry entry;
+ entry.box = box.span;
+ entry.itemId = static_cast(input.number(idWidth));
+ require(ids.insert(entry.itemId).second);
+ const auto n = input.number(1);
+ consume(budget_.associations, n, budget_.limits.maxAssociations);
+ require(n <= input.remaining() / propertyWidth);
+ entry.properties.reserve(static_cast(n));
+ for (uint64_t j = 0; j < n; ++j) {
+ const auto value = input.number(propertyWidth);
+ const unsigned essential = propertyWidth == 1 ? 0x80 : 0x8000;
+ entry.properties.push_back({static_cast(value & (essential - 1)), (value & essential) != 0});
+ }
+ model_.associations.push_back(std::move(entry));
+ }
+
+ input.finish();
+ }
+
+ BmffReader& reader_;
+ Budget budget_;
+ const BmffItemPolicy& policy_;
+ BmffItemModel model_;
+ std::set infoIds_;
+ std::set locationIds_;
+};
+
+} // namespace
+
+void BmffItemPolicy::unsupported(std::string_view feature) const {
+ throw Error(ErrorCode::kerErrorMessage, std::string("Unsupported BMFF item layout: ") + std::string(feature));
+}
+
+void BmffItemPolicy::checkHandler(uint32_t) const {
+}
+
+void BmffItemPolicy::checkProtection(uint16_t) const {
+}
+
+void BmffItemPolicy::checkMeta(const BmffBox&) const {
+}
+
+void BmffItemPolicy::checkItems(const BmffItemModel&) const {
+}
+
+void BmffItemPolicy::checkExtent(const BmffItemLocation&, const BmffExtent&) const {
+}
+
+void BmffItemPolicy::parseExtension(BmffReader&, BmffBox&, BmffCursor&, unsigned) const {
+}
+
+BmffItemModel parseBmffItems(BmffReader& reader, BmffBox& box, BmffCursor& fields, unsigned childDepth,
+ const BmffItemLimits& limits, const BmffItemPolicy& policy) {
+ return Parser(reader, limits, policy).parse(box, fields, childDepth);
+}
+
+void resolveBmffItems(BmffItemModel& model, uint64_t fileSize, const BmffItemPolicy& policy) {
+ require(fileSize <= static_cast(std::numeric_limits::max()));
+ require(model.infoOrder.size() == model.items.size() && model.locationOrder.size() == model.items.size());
+ policy.checkItems(model);
+ if (model.hasPrimaryItem)
+ require(model.items.contains(model.primaryItem));
+
+ // Method 0 uses file offsets; method 1 uses offsets from the idat payload.
+ for (auto& [id, item] : model.items) {
+ auto& location = item.location;
+ location.dataSize = 0;
+ for (auto& extent : location.extents) {
+ BmffSpan enclosing{0, fileSize};
+ if (location.constructionMethod == 1) {
+ require(model.itemData.has_value());
+ enclosing = *model.itemData;
+ }
+
+ // Check each relative addition against the containing interval before resolving it.
+ require(location.baseOffset <= enclosing.size && extent.offset <= enclosing.size - location.baseOffset);
+ const auto relative = location.baseOffset + extent.offset;
+ require(extent.length <= enclosing.size - relative);
+ extent.source = {enclosing.offset + relative, extent.length};
+
+ policy.checkExtent(location, extent);
+ consume(location.dataSize, extent.length, std::numeric_limits::max());
+ }
+ }
+
+ // Validate graph endpoints after every item has a complete description and location.
+ for (const auto& ref : model.references) {
+ require(model.items.contains(ref.from));
+ for (const auto id : ref.to)
+ require(model.items.contains(id));
+ }
+
+ // Property indices are one-based; an essential property cannot use the zero sentinel.
+ for (const auto& entry : model.associations) {
+ require(model.items.contains(entry.itemId));
+ for (const auto& property : entry.properties) {
+ require(property.index <= model.properties.size());
+ require(property.index != 0 || !property.essential);
+ }
+ }
+}
+
+std::vector readBmffItem(BasicIo& input, const BmffItem& item, uint64_t limit) {
+ enforce(item.location.dataSize <= limit && item.location.dataSize <= std::numeric_limits::max(),
+ ErrorCode::kerErrorMessage, "BMFF item exceeds the allocation limit");
+
+ // Gather the requested item only after bounding its aggregate allocation.
+ std::vector bytes(static_cast(item.location.dataSize));
+ size_t position = 0;
+ for (const auto& extent : item.location.extents) {
+ require(extent.source.size <= bytes.size() - position);
+ require(extent.source.offset <= static_cast(std::numeric_limits::max()) &&
+ extent.source.size <= static_cast(std::numeric_limits::max()) - extent.source.offset);
+ input.seekOrThrow(static_cast(extent.source.offset), BasicIo::beg, ErrorCode::kerInputDataReadFailed);
+ input.readOrThrow(bytes.data() + position, static_cast(extent.source.size),
+ ErrorCode::kerInputDataReadFailed);
+ enforce(!input.error(), ErrorCode::kerInputDataReadFailed);
+ position += static_cast(extent.source.size);
+ }
+ require(position == bytes.size());
+ return bytes;
+}
+
+} // namespace Exiv2::Internal
+#endif // EXV_ENABLE_BMFF
diff --git a/src/bmffitem_int.hpp b/src/bmffitem_int.hpp
new file mode 100644
index 0000000000..76ccd67807
--- /dev/null
+++ b/src/bmffitem_int.hpp
@@ -0,0 +1,205 @@
+// SPDX-License-Identifier: GPL-2.0-or-later
+
+#ifndef BMFFITEM_INT_HPP
+#define BMFFITEM_INT_HPP
+
+#include "config.h"
+
+#ifdef EXV_ENABLE_BMFF
+
+#include
+#include