From b033e51f8d1598b5518c1e658d19096805c6392c Mon Sep 17 00:00:00 2001 From: Vaclav Haisman Date: Fri, 9 Oct 2026 22:23:18 +0200 Subject: [PATCH 01/40] [bmff] Add a bounded item-based container model Represent boxes, item locations, references, and properties as checked ranges in seekable input without copying encoded image payloads. Retain all item IDs and extents, including file-relative and idat-relative data. Bound structural work and reject malformed addressing and relationships. Keep write eligibility separate so opaque content can be inspected while unsupported layouts are rejected before future rewriting. Register the private model in CMake and Meson; leave production writing disabled. --- src/CMakeLists.txt | 2 + src/bmffimage_int.cpp | 576 ++++++++++++++++++++++++++++++++++++++++++ src/bmffimage_int.hpp | 160 ++++++++++++ src/meson.build | 1 + 4 files changed, 739 insertions(+) create mode 100644 src/bmffimage_int.cpp create mode 100644 src/bmffimage_int.hpp diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index a2541a8687..aef2b0ad01 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -4,6 +4,8 @@ include_directories(${CMAKE_CURRENT_BINARY_DIR}) add_library( exiv2lib_int OBJECT + bmffimage_int.cpp + bmffimage_int.hpp canonmn_int.cpp canonmn_int.hpp casiomn_int.cpp diff --git a/src/bmffimage_int.cpp b/src/bmffimage_int.cpp new file mode 100644 index 0000000000..c62b7eedb6 --- /dev/null +++ b/src/bmffimage_int.cpp @@ -0,0 +1,576 @@ +// SPDX-License-Identifier: GPL-2.0-or-later + +#include "bmffimage_int.hpp" + +#ifdef EXV_ENABLE_BMFF + +#include "basicio.hpp" +#include "enforce.hpp" +#include "error.hpp" + +#include +#include +#include +#include +#include + +namespace Exiv2::Internal { +namespace { + +constexpr std::array canonUuid{0x85, 0xc0, 0xb6, 0x87, 0x82, 0x0f, 0x11, 0xe0, + 0x81, 0x11, 0xf4, 0xce, 0x46, 0x2b, 0x6a, 0x48}; + +void require(bool condition) { + enforce(condition, ErrorCode::kerCorruptedMetadata); +} + +void supported(bool condition, std::string_view feature) { + if (!condition) + throw Error(ErrorCode::kerErrorMessage, std::string("Unsupported HEIF layout: ") + std::string(feature)); +} + +void consume(uint64_t& used, uint64_t amount, uint64_t limit) { + require(used <= limit && amount <= limit - used); + used += amount; +} + +struct Budget { + const BmffLimits& limits; + uint64_t boxes{}; + uint64_t extents{}; + uint64_t references{}; + uint64_t associations{}; + uint64_t strings{}; + uint64_t bytes{}; +}; + +//! Every field read is checked against its immediate box, not merely the file. +class Cursor { + public: + Cursor(BasicIo& io, BmffSpan range, Budget& budget) : + io_(io), position_(range.offset), end_(range.offset + range.size), budget_(budget) { + } + + uint64_t position() const { + return position_; + } + uint64_t remaining() const { + return end_ - position_; + } + uint64_t end() const { + return end_; + } + void advance(uint64_t count) { + require(count <= remaining()); + position_ += count; + } + void read(byte* bytes, size_t size) { + require(size <= remaining()); + consume(budget_.bytes, size, budget_.limits.maxBytesRead); + io_.seekOrThrow(static_cast(position_), BasicIo::beg, ErrorCode::kerInputDataReadFailed); + io_.readOrThrow(bytes, size, ErrorCode::kerInputDataReadFailed); + if (io_.error()) + throw Error(ErrorCode::kerInputDataReadFailed); + position_ += size; + } + uint64_t 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[i]; + return result; + } + std::string string() { + std::string result; + while (true) { + require(remaining() != 0); + const auto c = static_cast(number(1)); + consume(budget_.strings, 1, budget_.limits.maxStringBytes); + if (c == '\0') + return result; + require(result.size() < budget_.limits.maxStringLength); + result.push_back(c); + } + } + void finish() const { + require(remaining() == 0); + } + + private: + BasicIo& io_; + uint64_t position_; + uint64_t end_; + Budget& budget_; +}; + +enum class Context { file, meta, info, properties, propertyList, references, dataInfo, dataRefs, canon }; + +class Parser { + public: + Parser(BasicIo& io, const BmffLimits& limits) : io_(io), budget_{limits} { + require(io.isopen()); + document_.fileSize = io.size(); + require(document_.fileSize <= static_cast(std::numeric_limits::max())); + } + + BmffDocument parse() { + Cursor input(io_, {0, document_.fileSize}, budget_); + document_.boxes = children(input, Context::file, 0); + require(!document_.boxes.empty() && document_.boxes.front().type == bmffType("ftyp")); + require(has(document_.boxes, bmffType("ftyp")) && has(document_.boxes, bmffType("meta"))); + validateItems(); + return std::move(document_); + } + + private: + 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; }); + } + + BmffBox header(Cursor& input) { + consume(budget_.boxes, 1, budget_.limits.maxBoxes); + require(input.remaining() >= 8); + BmffBox box; + box.span.offset = input.position(); + const auto available = input.remaining(); + box.span.size = input.number(4); + box.type = static_cast(input.number(4)); + box.headerSize = 8; + if (box.span.size == 1) { + box.span.size = input.number(8); + box.headerSize = 16; + } else if (box.span.size == 0) { + // A size-zero box extends to EOF, even when it is nested. + require(input.end() == document_.fileSize); + box.span.size = available; + box.extendsToEnd = true; + } + 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()); + } + require(box.span.size >= box.headerSize && box.span.size <= available); + input.advance(box.span.size - box.headerSize); + return box; + } + + BmffFullBox fullBox(BmffBox& box, Cursor& input, uint8_t maxVersion, uint32_t allowedFlags = 0) { + const auto value = static_cast(input.number(4)); + BmffFullBox full{static_cast(value >> 24), value & 0xffffff}; + supported(full.version <= maxVersion, "box version"); + require((full.flags & ~allowedFlags) == 0); + box.fullBox = full; + return full; + } + + BmffItem& item(uint32_t id) { + require(id != 0); + const auto found = document_.items.find(id); + if (found != document_.items.end()) + return found->second; + require(document_.items.size() < budget_.limits.maxItems); + return document_.items.try_emplace(id).first->second; + } + + std::vector children(Cursor& input, Context context, unsigned depth, uint8_t version = 0) { + require(depth <= budget_.limits.maxDepth); + std::vector boxes; + std::set singletons; + while (input.remaining() != 0) { + auto box = header(input); + Cursor fields(io_, box.payload(), budget_); + auto unique = [&] { require(singletons.insert(box.type).second); }; + switch (context) { + case Context::file: + if (box.type == bmffType("ftyp")) { + unique(); + require(fields.remaining() >= 8 && fields.remaining() % 4 == 0); + document_.majorBrand = static_cast(fields.number(4)); + document_.minorVersion = static_cast(fields.number(4)); + require(fields.remaining() / 4 <= budget_.limits.maxBoxes); + while (fields.remaining() != 0) + document_.compatibleBrands.push_back(static_cast(fields.number(4))); + } else if (box.type == bmffType("meta")) { + unique(); + fullBox(box, fields, 0); + box.children = children(fields, Context::meta, depth + 1); + for (const auto required : + {bmffType("hdlr"), bmffType("pitm"), bmffType("iinf"), bmffType("iloc"), bmffType("iprp")}) + require(has(box.children, required)); + } else if (box.type == bmffType("mdat")) { + document_.mediaData.push_back(box.payload()); + } + break; + case Context::meta: + if (box.type == bmffType("hdlr")) { + unique(); + fullBox(box, fields, 0); + require(fields.number(4) == 0); + supported(fields.number(4) == bmffType("pict"), "non-picture 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); + document_.primaryItem = static_cast(fields.number(full.version == 0 ? 2 : 4)); + 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(); + document_.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 if (box.type == bmffType("uuid") && box.userType == canonUuid) { + box.children = children(fields, Context::canon, 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); + document_.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.maxBoxes && 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(fields.string().empty()); + fields.finish(); + } + break; + case Context::canon: + unique(); + break; + } + boxes.push_back(std::move(box)); + } + return boxes; + } + + void info(BmffBox& box, Cursor& input) { + const auto full = fullBox(box, input, 3, 1); + supported(full.version >= 2, "legacy item info entry"); + 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)); + supported(info.protectionIndex == 0, "protected item"); + info.type = static_cast(input.number(4)); + info.name = input.string(); + if (info.type == bmffType("mime")) { + info.contentType = input.string(); + if (input.remaining() != 0) + info.contentEncoding = input.string(); + } else if (info.type == bmffType("uri ")) { + info.uriType = input.string(); + } + input.finish(); + document_.infoOrder.push_back(id); + } + + void locations(BmffBox& box, Cursor& input) { + const auto full = fullBox(box, input, 2); + auto& format = document_.locationFormat; + format.box = box.span; + format.version = full.version; + 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"); + 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); + 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); + } + document_.locationOrder.push_back(id); + } + input.finish(); + } + + void reference(const BmffBox& box, Cursor& input, uint8_t version) { + BmffReference ref; + ref.box = box.span; + ref.type = box.type; + 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(); + document_.references.push_back(std::move(ref)); + } + + 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)); + 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}); + } + document_.associations.push_back(std::move(entry)); + } + input.finish(); + } + + void validateItems() { + require(infoIds_ == locationIds_ && !infoIds_.empty()); + require(document_.items.contains(document_.primaryItem)); + for (auto& [id, item] : document_.items) { + auto& location = item.location; + for (auto& extent : location.extents) { + BmffSpan enclosing{0, document_.fileSize}; + if (location.constructionMethod == 1) { + require(document_.itemData.has_value()); + enclosing = *document_.itemData; + } + 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}; + if (location.constructionMethod == 0) { + auto media = std::upper_bound(document_.mediaData.begin(), document_.mediaData.end(), extent.source.offset, + [](uint64_t offset, const BmffSpan& range) { return offset < range.offset; }); + require(media != document_.mediaData.begin()); + --media; + const auto offset = extent.source.offset - media->offset; + require(offset <= media->size && extent.length <= media->size - offset); + } + consume(location.dataSize, extent.length, std::numeric_limits::max()); + } + } + for (const auto& ref : document_.references) { + require(document_.items.contains(ref.from)); + for (const auto id : ref.to) + require(document_.items.contains(id)); + } + for (const auto& entry : document_.associations) { + require(document_.items.contains(entry.itemId)); + for (const auto& property : entry.properties) { + require(property.index <= document_.properties.size()); + require(property.index != 0 || !property.essential); + } + } + } + + BasicIo& io_; + Budget budget_; + BmffDocument document_; + std::set infoIds_; + std::set locationIds_; +}; + +bool padding(uint32_t type) { + return type == bmffType("free") || type == bmffType("skip"); +} + +void checkRelocation(const std::vector& boxes, Context context) { + static constexpr auto propertyTypes = + std::array{bmffType("hvcC"), bmffType("av1C"), bmffType("ispe"), bmffType("pixi"), bmffType("colr"), + bmffType("irot"), bmffType("imir"), bmffType("clap"), bmffType("pasp"), bmffType("auxC"), + bmffType("rloc"), bmffType("clli"), bmffType("mdcv"), bmffType("cclv")}; + for (const auto& box : boxes) { + if (padding(box.type)) + continue; + switch (context) { + case Context::file: + if (box.type == bmffType("meta")) + checkRelocation(box.children, Context::meta); + else + supported(box.type == bmffType("ftyp") || box.type == bmffType("mdat"), "unmodeled top-level box"); + break; + case Context::meta: + switch (box.type) { + case bmffType("hdlr"): + case bmffType("pitm"): + case bmffType("iloc"): + case bmffType("idat"): + case bmffType("iinf"): + case bmffType("iref"): + break; + case bmffType("iprp"): + checkRelocation(box.children, Context::properties); + break; + case bmffType("dinf"): + checkRelocation(box.children, Context::dataInfo); + break; + case bmffType("uuid"): + supported( + box.userType == canonUuid && box.children.size() == 1 && box.children.front().type == bmffType("CNCV"), + "unmodeled UUID"); + break; + default: + supported(false, "unmodeled metadata box"); + } + break; + case Context::properties: + if (box.type == bmffType("ipco")) + checkRelocation(box.children, Context::propertyList); + else + supported(box.type == bmffType("ipma"), "unmodeled property container"); + break; + case Context::propertyList: + supported(std::find(propertyTypes.begin(), propertyTypes.end(), box.type) != propertyTypes.end(), + "unmodeled item property"); + break; + case Context::dataInfo: + supported(box.type == bmffType("dref"), "unmodeled data information"); + checkRelocation(box.children, Context::dataRefs); + break; + case Context::dataRefs: + supported(box.type == bmffType("url "), "unmodeled data reference"); + break; + default: + supported(false, "unmodeled container"); + } + } +} + +} // namespace + +BmffSpan BmffBox::payload() const { + require(headerSize <= span.size && span.size <= std::numeric_limits::max() - span.offset); + return {span.offset + headerSize, span.size - headerSize}; +} + +std::vector BmffDocument::metadataItems(uint32_t type) const { + std::set describing; + for (const auto& reference : references) { + if (reference.type == bmffType("cdsc") && + std::find(reference.to.begin(), reference.to.end(), primaryItem) != reference.to.end()) + describing.insert(reference.from); + } + std::vector result; + for (const auto id : infoOrder) { + const auto& info = items.at(id).info; + if (describing.contains(id) && info.type == type && + (type != bmffType("mime") || info.contentType == "application/rdf+xml")) + result.push_back(id); + } + return result; +} + +BmffDocument parseBmff(BasicIo& io, const BmffLimits& limits) { + return Parser(io, limits).parse(); +} + +void enforceHeifWriteSupport(const BmffDocument& document) { + supported(document.majorBrand == bmffType("heic") || document.majorBrand == bmffType("heix") || + document.majorBrand == bmffType("mif1"), + "file brand"); + // A generic mif1 brand can accompany an AVIF or another deferred codec. + supported(std::find(document.compatibleBrands.begin(), document.compatibleBrands.end(), bmffType("avif")) == + document.compatibleBrands.end() && + std::find(document.compatibleBrands.begin(), document.compatibleBrands.end(), bmffType("avis")) == + document.compatibleBrands.end(), + "AVIF writing is deferred"); + const auto primaryType = document.items.at(document.primaryItem).info.type; + supported(primaryType == bmffType("hvc1") || primaryType == bmffType("grid") || primaryType == bmffType("iden") || + primaryType == bmffType("iovl"), + "primary image type"); + for (const auto id : document.metadataItems(bmffType("mime"))) + supported(document.items.at(id).info.contentEncoding.empty(), "compressed primary XMP"); + checkRelocation(document.boxes, Context::file); +} + +} // namespace Exiv2::Internal +#endif // EXV_ENABLE_BMFF diff --git a/src/bmffimage_int.hpp b/src/bmffimage_int.hpp new file mode 100644 index 0000000000..62a017a4dc --- /dev/null +++ b/src/bmffimage_int.hpp @@ -0,0 +1,160 @@ +// SPDX-License-Identifier: GPL-2.0-or-later + +#ifndef BMFFIMAGE_INT_HPP +#define BMFFIMAGE_INT_HPP + +#include "config.h" + +#ifdef EXV_ENABLE_BMFF + +#include +#include +#include +#include +#include +#include + +namespace Exiv2 { +class BasicIo; +} + +namespace Exiv2::Internal { + +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])}; +} + +//! A validated interval in the original input. Payloads are never owned by the model. +struct BmffSpan { + uint64_t offset{}; + uint64_t size{}; + bool operator==(const BmffSpan&) const = default; +}; + +struct BmffFullBox { + uint8_t version{}; + uint32_t flags{}; +}; + +struct BmffBox { + uint32_t type{}; + BmffSpan span; + uint8_t headerSize{}; //!< Includes a UUID user type, but excludes FullBox version/flags. + bool extendsToEnd{}; + std::array userType{}; + std::optional fullBox; + std::vector children; + + [[nodiscard]] BmffSpan payload() const; +}; + +struct BmffItemInfo { + BmffSpan box; + uint8_t version{}; + uint32_t flags{}; + uint32_t type{}; + uint16_t protectionIndex{}; + std::string name; + std::string contentType; + std::string contentEncoding; + std::string uriType; +}; + +struct BmffExtent { + uint64_t index{}; + uint64_t offset{}; + uint64_t length{}; + BmffSpan source; +}; + +struct BmffItemLocation { + uint8_t constructionMethod{}; + uint16_t dataReferenceIndex{}; + uint64_t baseOffset{}; + uint64_t dataSize{}; + std::vector extents; +}; + +struct BmffItem { + BmffItemInfo info; + BmffItemLocation location; +}; + +struct BmffLocationFormat { + BmffSpan box; + uint8_t version{}; + uint8_t offsetSize{}; + uint8_t lengthSize{}; + uint8_t baseOffsetSize{}; + uint8_t indexSize{}; +}; + +struct BmffReference { + BmffSpan box; + uint32_t type{}; + uint32_t from{}; + std::vector to; +}; + +struct BmffPropertyAssociation { + uint16_t index{}; //!< One-based property index; zero denotes no association. + bool essential{}; +}; + +struct BmffAssociationEntry { + BmffSpan box; + uint32_t itemId{}; + std::vector properties; +}; + +//! Limits apply to aggregate structural work, independently of encoded image size. +struct BmffLimits { + uint64_t maxBoxes{100000}; + uint64_t maxItems{65536}; + uint64_t maxExtents{1000000}; + uint64_t maxReferences{1000000}; + uint64_t maxAssociations{1000000}; + uint64_t maxStringBytes{1024 * 1024}; + uint64_t maxStringLength{65536}; + uint64_t maxBytesRead{16 * 1024 * 1024}; + unsigned maxDepth{16}; +}; + +//! Checked item-based BMFF structure, independent of BmffImage's metadata state. +struct BmffDocument { + uint64_t fileSize{}; + uint32_t majorBrand{}; + uint32_t minorVersion{}; + std::vector compatibleBrands; + std::vector boxes; + uint32_t primaryItem{}; + BmffLocationFormat locationFormat; + std::map items; + std::vector infoOrder; + std::vector locationOrder; + std::vector references; + std::vector properties; + std::vector associations; + std::vector mediaData; + std::optional itemData; + + //! Exif or XMP items describing the primary image, in iinf order. + [[nodiscard]] std::vector metadataItems(uint32_t type) const; +}; + +/*! + @brief Parse an open, seekable BasicIo without reading image payloads or writing. + The input must stay unchanged while its returned ranges are used. The stream + position may change. Malformed input throws kerCorruptedMetadata; unsupported + syntax throws an explicit unsupported-layout error. Parsing alone does not + authorize rewriting: call enforceHeifWriteSupport before using a rewrite path. + */ +BmffDocument parseBmff(BasicIo& io, const BmffLimits& limits = {}); + +//! Reject deferred brands and opaque structures whose relocation is not supported. +void enforceHeifWriteSupport(const BmffDocument& document); + +} // namespace Exiv2::Internal +#endif // EXV_ENABLE_BMFF +#endif // BMFFIMAGE_INT_HPP diff --git a/src/meson.build b/src/meson.build index 6cfc2d7a5c..4582388b8c 100644 --- a/src/meson.build +++ b/src/meson.build @@ -44,6 +44,7 @@ if get_option('video') endif int_lib = files( + 'bmffimage_int.cpp', 'canonmn_int.cpp', 'casiomn_int.cpp', 'cr2header_int.cpp', From 32f3808b526c4579d232c85368232d92a38a7da0 Mon Sep 17 00:00:00 2001 From: Vaclav Haisman Date: Fri, 9 Oct 2026 22:23:36 +0200 Subject: [PATCH 02/40] [tests] Cover BMFF item model preservation and rejection Add 41 synthetic and corpus cases covering supported field widths and versions, references, properties, shared ranges, malformed boundaries, resource limits, I/O failures, and an 8 GiB sparse input. Check real HEIF and AVIF fixtures against expectations from an independent inventory. Verify that deferred formats and unsafe layouts are rejected and that production metadata writing remains disabled. Register the tests in CMake and Meson, linking the private library for Meson unit tests. --- unitTests/CMakeLists.txt | 1 + unitTests/meson.build | 3 +- unitTests/test_bmffimage_int.cpp | 805 +++++++++++++++++++++++++++++++ 3 files changed, 808 insertions(+), 1 deletion(-) create mode 100644 unitTests/test_bmffimage_int.cpp diff --git a/unitTests/CMakeLists.txt b/unitTests/CMakeLists.txt index 7902d671b3..6fc33f8724 100644 --- a/unitTests/CMakeLists.txt +++ b/unitTests/CMakeLists.txt @@ -12,6 +12,7 @@ endif() add_executable( unit_tests test_basicio.cpp + test_bmffimage_int.cpp test_bmpimage.cpp test_cr2header_int.cpp test_datasets.cpp diff --git a/unitTests/meson.build b/unitTests/meson.build index 6baeb0b3f8..866a48c380 100644 --- a/unitTests/meson.build +++ b/unitTests/meson.build @@ -14,6 +14,7 @@ test_sources = files( 'test_TimeValue.cpp', 'test_XmpKey.cpp', 'test_basicio.cpp', + 'test_bmffimage_int.cpp', 'test_bmpimage.cpp', 'test_cr2header_int.cpp', 'test_datasets.cpp', @@ -60,7 +61,7 @@ unit_tests = executable( 'unit_tests', test_sources, cpp_args: t_args, - dependencies: [exiv2_dep, gtest_dep], + dependencies: [exiv2_dep, exiv2int_dep, gtest_dep], include_directories: exiv2inc, ) diff --git a/unitTests/test_bmffimage_int.cpp b/unitTests/test_bmffimage_int.cpp new file mode 100644 index 0000000000..2f7b5ddaa5 --- /dev/null +++ b/unitTests/test_bmffimage_int.cpp @@ -0,0 +1,805 @@ +// SPDX-License-Identifier: GPL-2.0-or-later + +#include "bmffimage_int.hpp" + +#ifdef EXV_ENABLE_BMFF + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "unittest_utils.hpp" + +using namespace Exiv2; +using namespace Exiv2::Internal; + +namespace { +using Bytes = std::vector; + +void integer(Bytes& output, uint64_t value, unsigned width) { + for (unsigned i = width; i != 0; --i) + output.push_back(static_cast(value >> ((i - 1) * 8))); +} + +void append(Bytes& output, const Bytes& value) { + output.insert(output.end(), value.begin(), value.end()); +} + +void string(Bytes& output, std::string_view value) { + output.insert(output.end(), value.begin(), value.end()); + output.push_back(0); +} + +Bytes box(uint32_t type, const Bytes& payload, bool extended = false, bool toEnd = false) { + Bytes result; + integer(result, toEnd ? 0 : extended ? 1 : payload.size() + 8, 4); + integer(result, type, 4); + if (extended) + integer(result, payload.size() + 16, 8); + append(result, payload); + return result; +} + +Bytes full(uint8_t version = 0, uint32_t flags = 0) { + Bytes result; + integer(result, (uint32_t{version} << 24) | flags, 4); + return result; +} + +size_t position(const Bytes& bytes, std::string_view type) { + const auto found = std::search(bytes.begin(), bytes.end(), type.begin(), type.end()); + if (type.size() != 4 || found == bytes.end() || found - bytes.begin() < 4) + throw std::runtime_error("missing fixture box"); + return static_cast(found - bytes.begin()) - 4; +} + +void patch(Bytes& bytes, size_t offset, uint64_t value, unsigned width) { + Bytes encoded; + integer(encoded, value, width); + if (offset > bytes.size() || width > bytes.size() - offset) + throw std::runtime_error("invalid fixture patch"); + std::copy(encoded.begin(), encoded.end(), bytes.begin() + offset); +} + +struct Options { + uint32_t brand{bmffType("heic")}; + uint32_t idBase{}; + uint8_t locationVersion{}; + uint8_t infoVersion{}; + uint8_t entryVersion{2}; + uint8_t primaryVersion{}; + uint8_t referenceVersion{}; + uint8_t associationVersion{}; + uint8_t offsetWidth{4}; + uint8_t lengthWidth{4}; + uint8_t baseWidth{}; + uint8_t indexWidth{}; + bool wideProperties{}; + bool extended{}; + bool terminal{}; + bool idat{}; + bool noMetadata{}; + bool noReferences{}; + bool sharedMetadata{}; + bool locationFirst{}; + uint16_t propertyCount{2}; + uint32_t propertyType{bmffType("ispe")}; + std::string encoding; + Bytes extraMeta; + Bytes extraRoot; +}; + +//! Synthetic bytes are independently assembled from the format's field layout. +//! Image and metadata payloads deliberately need no decoder for structural tests. +Bytes fixture(const Options& opt = {}) { + Bytes fileType; + integer(fileType, opt.brand, 4); + integer(fileType, 0, 4); + integer(fileType, bmffType("mif1"), 4); + integer(fileType, opt.brand, 4); + auto ftyp = box(bmffType("ftyp"), fileType, opt.extended); + const Bytes payload{'A', 'B', 'e', 'x', 'i', 'f', 'C', 'D', 'x', 'm', 'p'}; + const unsigned count = opt.noMetadata ? 1 : 3; + const unsigned headerSize = opt.extended ? 16 : 8; + + auto meta = [&](uint64_t mediaStart) { + auto result = full(); + auto handler = full(); + integer(handler, 0, 4); + integer(handler, bmffType("pict"), 4); + for (int i = 0; i < 3; ++i) + integer(handler, 0, 4); + string(handler, ""); + append(result, box(bmffType("hdlr"), handler, opt.extended)); + auto primary = full(opt.primaryVersion); + integer(primary, opt.idBase + 1, opt.primaryVersion == 0 ? 2 : 4); + append(result, box(bmffType("pitm"), primary, opt.extended)); + auto info = full(opt.infoVersion); + integer(info, count, opt.infoVersion == 0 ? 2 : 4); + for (unsigned i = 1; i <= count; ++i) { + auto entry = full(opt.entryVersion, i == 1 ? 0 : 1); + integer(entry, opt.idBase + i, opt.entryVersion == 2 ? 2 : 4); + integer(entry, 0, 2); + integer(entry, i == 1 ? bmffType("hvc1") : i == 2 ? bmffType("Exif") : bmffType("mime"), 4); + string(entry, i == 1 ? "image" : i == 2 ? "exif" : "xmp"); + if (i == 3) { + string(entry, "application/rdf+xml"); + string(entry, opt.encoding); + } + append(info, box(bmffType("infe"), entry, opt.extended)); + } + auto locations = full(opt.locationVersion); + integer(locations, (opt.offsetWidth << 4) | opt.lengthWidth, 1); + integer(locations, (opt.baseWidth << 4) | opt.indexWidth, 1); + integer(locations, count, opt.locationVersion < 2 ? 2 : 4); + for (unsigned i = 1; i <= count; ++i) { + const bool inIdat = opt.idat && i == 1; + const uint64_t source = inIdat ? 0 : mediaStart; + const uint64_t itemOffset = i == 1 ? 0 : i == 2 ? 2 : 8; + integer(locations, opt.idBase + i, opt.locationVersion < 2 ? 2 : 4); + if (opt.locationVersion != 0) + integer(locations, inIdat ? 1 : 0, 2); + integer(locations, 0, 2); + integer(locations, opt.offsetWidth == 0 ? source + itemOffset : source, opt.baseWidth); + const bool fragmented = i == 1 && opt.offsetWidth != 0; + integer(locations, fragmented ? 2 : 1, 2); + integer(locations, 0, opt.indexWidth); + integer(locations, (opt.baseWidth == 0 ? source : 0) + itemOffset, opt.offsetWidth); + integer(locations, i == 1 ? (fragmented ? 2 : 8) : i == 2 ? 4 : 3, opt.lengthWidth); + if (fragmented) { + integer(locations, 0, opt.indexWidth); + integer(locations, (opt.baseWidth == 0 ? source : 0) + 6, opt.offsetWidth); + integer(locations, 2, opt.lengthWidth); + } + } + auto iloc = box(bmffType("iloc"), locations, opt.extended); + auto iinf = box(bmffType("iinf"), info, opt.extended); + append(result, opt.locationFirst ? iloc : iinf); + append(result, opt.locationFirst ? iinf : iloc); + if (!opt.noReferences && !opt.noMetadata) { + auto references = full(opt.referenceVersion); + for (unsigned i = 2; i <= count; ++i) { + Bytes ref; + const unsigned width = opt.referenceVersion == 0 ? 2 : 4; + integer(ref, opt.idBase + i, width); + integer(ref, opt.sharedMetadata && i == 2 ? 2 : 1, 2); + integer(ref, opt.idBase + 1, width); + if (opt.sharedMetadata && i == 2) + integer(ref, opt.idBase + 3, width); + append(references, box(bmffType("cdsc"), ref, opt.extended)); + } + append(result, box(bmffType("iref"), references, opt.extended)); + } + Bytes properties; + for (unsigned i = 0; i < opt.propertyCount; ++i) { + auto value = full(); + integer(value, 32, 4); + integer(value, 16, 4); + append(properties, box(opt.propertyType, value, opt.extended)); + } + auto iprp = box(bmffType("ipco"), properties, opt.extended); + auto associations = full(opt.associationVersion, opt.wideProperties ? 1 : 0); + integer(associations, 1, 4); + integer(associations, opt.idBase + 1, opt.associationVersion == 0 ? 2 : 4); + integer(associations, 2, 1); + integer(associations, (opt.wideProperties ? 0x8000 : 0x80) | 1, opt.wideProperties ? 2 : 1); + integer(associations, opt.propertyCount, opt.wideProperties ? 2 : 1); + append(iprp, box(bmffType("ipma"), associations, opt.extended)); + append(result, box(bmffType("iprp"), iprp, opt.extended)); + if (opt.idat) + append(result, box(bmffType("idat"), payload, opt.extended)); + append(result, opt.extraMeta); + return box(bmffType("meta"), result, opt.extended); + }; + auto metadata = meta(0); + metadata = meta(ftyp.size() + metadata.size() + opt.extraRoot.size() + headerSize); + append(ftyp, metadata); + append(ftyp, opt.extraRoot); + append(ftyp, box(bmffType("mdat"), payload, opt.extended, opt.terminal)); + return ftyp; +} + +BmffDocument parse(const Bytes& bytes, const BmffLimits& limits = {}) { + MemIo input(bytes.data(), bytes.size()); + return parseBmff(input, limits); +} + +void rejects(const Bytes& bytes) { + EXPECT_THROW(parse(bytes), Error); +} + +Bytes payload(const Bytes& file, const BmffItem& item) { + Bytes result; + for (const auto& extent : item.location.extents) { + if (extent.source.offset > file.size() || extent.source.size > file.size() - extent.source.offset) + throw std::runtime_error("out-of-bounds model range"); + result.insert(result.end(), file.begin() + extent.source.offset, + file.begin() + extent.source.offset + extent.source.size); + } + return result; +} + +} // namespace + +TEST(BmffModel, retainsAllItemsExtentsAndMetadataAssociations) { + const auto bytes = fixture(); + const auto document = parse(bytes); + EXPECT_NO_THROW(enforceHeifWriteSupport(document)); + ASSERT_EQ(document.items.size(), 3u); + EXPECT_EQ(document.primaryItem, 1u); + EXPECT_EQ(document.majorBrand, bmffType("heic")); + EXPECT_EQ(document.infoOrder, (std::vector{1, 2, 3})); + EXPECT_EQ(document.locationOrder, document.infoOrder); + EXPECT_EQ(document.metadataItems(bmffType("Exif")), (std::vector{2})); + EXPECT_EQ(document.metadataItems(bmffType("mime")), (std::vector{3})); + EXPECT_EQ(document.items.at(3).info.contentType, "application/rdf+xml"); + EXPECT_EQ(document.items.at(2).info.flags, 1u); + EXPECT_EQ(document.items.at(1).location.extents.size(), 2u); + EXPECT_EQ(document.items.at(1).location.dataSize, 4u); + EXPECT_EQ(payload(bytes, document.items.at(1)), (Bytes{'A', 'B', 'C', 'D'})); + EXPECT_EQ(payload(bytes, document.items.at(2)), (Bytes{'e', 'x', 'i', 'f'})); + EXPECT_EQ(payload(bytes, document.items.at(3)), (Bytes{'x', 'm', 'p'})); + ASSERT_EQ(document.associations.size(), 1u); + EXPECT_EQ(document.associations.front().properties.front().index, 1u); + EXPECT_TRUE(document.associations.front().properties.front().essential); + EXPECT_FALSE(document.associations.front().properties.back().essential); +} + +TEST(BmffModel, acceptsLocationBeforeInfoAndExplicitBaseOffsets) { + Options opt; + opt.locationFirst = true; + opt.baseWidth = 4; + const auto bytes = fixture(opt); + const auto document = parse(bytes); + EXPECT_GT(document.items.at(1).location.baseOffset, 0u); + EXPECT_EQ(payload(bytes, document.items.at(1)), (Bytes{'A', 'B', 'C', 'D'})); +} + +TEST(BmffModel, resolvesIdatRelativeDataWithoutConfusingItWithFileOffsets) { + Options opt; + opt.idat = true; + opt.locationVersion = 1; + const auto bytes = fixture(opt); + const auto document = parse(bytes); + ASSERT_TRUE(document.itemData.has_value()); + EXPECT_EQ(document.items.at(1).location.constructionMethod, 1u); + EXPECT_EQ(document.items.at(1).location.extents.front().source.offset, document.itemData->offset); + EXPECT_EQ(payload(bytes, document.items.at(1)), (Bytes{'A', 'B', 'C', 'D'})); + EXPECT_NO_THROW(enforceHeifWriteSupport(document)); +} + +TEST(BmffModel, retains32BitIds64BitFieldsAndWidePropertyIndices) { + Options opt; + opt.idBase = 65536; + opt.locationVersion = 2; + opt.infoVersion = 1; + opt.entryVersion = 3; + opt.primaryVersion = 1; + opt.referenceVersion = 1; + opt.associationVersion = 1; + opt.offsetWidth = opt.lengthWidth = opt.baseWidth = opt.indexWidth = 8; + opt.wideProperties = true; + opt.propertyCount = 130; + const auto document = parse(fixture(opt)); + EXPECT_EQ(document.primaryItem, 65537u); + EXPECT_EQ(document.metadataItems(bmffType("Exif")), (std::vector{65538})); + EXPECT_EQ(document.locationFormat.indexSize, 8u); + EXPECT_EQ(document.associations.front().properties.back().index, 130u); + EXPECT_EQ(document.items.at(65537).info.version, 3u); +} + +TEST(BmffModel, acceptsZeroOffsetWidthAndNonzeroBaseOffsets) { + Options opt; + opt.offsetWidth = 0; + opt.baseWidth = 8; + const auto bytes = fixture(opt); + const auto document = parse(bytes); + EXPECT_EQ(document.locationFormat.offsetSize, 0u); + EXPECT_EQ(payload(bytes, document.items.at(2)), (Bytes{'e', 'x', 'i', 'f'})); +} + +TEST(BmffModel, preservesExtendedHeadersAndTerminalMediaBox) { + Options opt; + opt.extended = true; + auto bytes = fixture(opt); + auto document = parse(bytes); + EXPECT_EQ(document.boxes.front().headerSize, 16u); + EXPECT_EQ(payload(bytes, document.items.at(1)), (Bytes{'A', 'B', 'C', 'D'})); + opt.extended = false; + opt.terminal = true; + bytes = fixture(opt); + document = parse(bytes); + EXPECT_TRUE(document.boxes.back().extendsToEnd); + EXPECT_EQ(document.boxes.back().span.size, 19u); +} + +TEST(BmffModel, acceptsMetadataFreeFilesAndMissingReferences) { + Options opt; + opt.noMetadata = true; + auto document = parse(fixture(opt)); + EXPECT_EQ(document.items.size(), 1u); + EXPECT_TRUE(document.metadataItems(bmffType("Exif")).empty()); + EXPECT_NO_THROW(enforceHeifWriteSupport(document)); + opt.noMetadata = false; + opt.noReferences = true; + document = parse(fixture(opt)); + EXPECT_EQ(document.items.size(), 3u); + EXPECT_TRUE(document.metadataItems(bmffType("Exif")).empty()); +} + +TEST(BmffModel, preservesSharedMetadataAndReferenceDirection) { + Options opt; + opt.sharedMetadata = true; + auto bytes = fixture(opt); + auto document = parse(bytes); + EXPECT_EQ(document.references.front().from, 2u); + EXPECT_EQ(document.references.front().to, (std::vector{1, 3})); + EXPECT_EQ(document.metadataItems(bmffType("Exif")), (std::vector{2})); + const auto cdsc = position(bytes, "cdsc"); + patch(bytes, cdsc + 8, 1, 2); + patch(bytes, cdsc + 12, 2, 2); + document = parse(bytes); + EXPECT_TRUE(document.metadataItems(bmffType("Exif")).empty()); +} + +TEST(BmffModel, retainsOpaqueBoxesButRejectsUnprovedRelocation) { + Options opt; + opt.extraMeta = box(bmffType("zzzz"), {'k', 'e', 'e', 'p'}); + auto bytes = fixture(opt); + auto document = parse(bytes); + const auto& opaque = document.boxes.at(1).children.back(); + EXPECT_EQ(opaque.type, bmffType("zzzz")); + EXPECT_EQ(opaque.span.offset, position(bytes, "zzzz")); + EXPECT_EQ(opaque.span.size, 12u); + EXPECT_THROW(enforceHeifWriteSupport(document), Error); + opt.extraMeta.clear(); + opt.extraRoot = box(bmffType("zzzz"), {1, 2, 3}); + EXPECT_THROW(enforceHeifWriteSupport(parse(fixture(opt))), Error); + opt.extraRoot = box(bmffType("free"), {1, 2, 3}); + EXPECT_NO_THROW(enforceHeifWriteSupport(parse(fixture(opt)))); + opt.extraRoot.clear(); + opt.propertyType = bmffType("zzzz"); + document = parse(fixture(opt)); + EXPECT_EQ(document.properties.front().type, bmffType("zzzz")); + EXPECT_THROW(enforceHeifWriteSupport(document), Error); +} + +TEST(BmffModel, rejectsDeferredBrandsAndCompressedPrimaryXmp) { + for (const auto brand : {bmffType("avif"), bmffType("avis"), bmffType("crx "), bmffType("jxl ")}) { + Options opt; + opt.brand = brand; + EXPECT_THROW(enforceHeifWriteSupport(parse(fixture(opt))), Error); + } + Options opt; + opt.encoding = "gzip"; + auto document = parse(fixture(opt)); + EXPECT_EQ(document.items.at(3).info.contentEncoding, "gzip"); + EXPECT_THROW(enforceHeifWriteSupport(document), Error); +} + +TEST(BmffModel, rejectsEveryTruncatedPrefix) { + const auto complete = fixture(); + for (size_t length = 0; length < complete.size(); ++length) { + SCOPED_TRACE(length); + rejects(Bytes(complete.begin(), complete.begin() + length)); + } +} + +TEST(BmffModel, rejectsInvalidHeadersAndContainerBounds) { + const auto complete = fixture(); + for (const auto size : {uint64_t{2}, uint64_t{7}, uint64_t{0xffffffff}}) { + auto bytes = complete; + patch(bytes, 0, size, 4); + rejects(bytes); + } + auto bytes = complete; + patch(bytes, position(bytes, "infe"), bytes.size(), 4); + rejects(bytes); + bytes = complete; + patch(bytes, position(bytes, "infe"), 0, 4); + rejects(bytes); + Options opt; + opt.extended = true; + bytes = fixture(opt); + patch(bytes, 8, std::numeric_limits::max(), 8); + rejects(bytes); +} + +TEST(BmffModel, rejectsUnsupportedVersionsAndReservedFlags) { + for (const auto* type : {"meta", "pitm", "iinf", "infe", "iloc", "iref", "ipma", "hdlr"}) { + auto bytes = fixture(); + const auto offset = position(bytes, type); + patch(bytes, offset + 8, 255, 1); + rejects(bytes); + } + auto bytes = fixture(); + patch(bytes, position(bytes, "iloc") + 11, 128, 1); + rejects(bytes); +} + +TEST(BmffModel, rejectsMissingMandatoryBoxesAndDuplicateSingletons) { + for (const auto* type : {"ftyp", "meta", "hdlr", "pitm", "iinf", "iloc", "iprp", "ipco"}) { + auto bytes = fixture(); + const auto offset = position(bytes, type); + patch(bytes, offset + 4, bmffType("free"), 4); + rejects(bytes); + } + Options opt; + auto duplicate = full(); + integer(duplicate, 1, 2); + opt.extraMeta = box(bmffType("pitm"), duplicate); + rejects(fixture(opt)); + opt.extraMeta.clear(); + opt.extraRoot = box(bmffType("ftyp"), Bytes(8)); + rejects(fixture(opt)); +} + +TEST(BmffModel, rejectsDuplicateMissingAndZeroItemIds) { + for (const auto id : {0, 1, 42}) { + auto bytes = fixture(); + const auto firstInfo = position(bytes, "infe"); + patch(bytes, firstInfo + 12, id, 2); + if (id == 1) { + const auto firstLocation = position(bytes, "iloc"); + patch(bytes, firstLocation + 38, 1, 2); // Second location follows two primary extents. + } + rejects(bytes); + } +} + +TEST(BmffModel, rejectsDanglingPrimaryReferencesAndProperties) { + auto bytes = fixture(); + patch(bytes, position(bytes, "pitm") + 12, 42, 2); + rejects(bytes); + bytes = fixture(); + patch(bytes, position(bytes, "cdsc") + 8, 42, 2); + rejects(bytes); + bytes = fixture(); + patch(bytes, position(bytes, "cdsc") + 12, 42, 2); + rejects(bytes); + bytes = fixture(); + patch(bytes, position(bytes, "ipma") + 16, 42, 2); + rejects(bytes); + bytes = fixture(); + patch(bytes, position(bytes, "ipma") + 19, 127, 1); + rejects(bytes); + bytes = fixture(); + patch(bytes, position(bytes, "ipma") + 19, 0x80, 1); + rejects(bytes); +} + +TEST(BmffModel, rejectsHugeCountsAndCountDisagreement) { + for (const auto count : {0u, 2u, 4u, 65535u}) { + auto bytes = fixture(); + patch(bytes, position(bytes, "iinf") + 12, count, 2); + rejects(bytes); + } + auto bytes = fixture(); + patch(bytes, position(bytes, "iloc") + 14, 65535, 2); + rejects(bytes); + bytes = fixture(); + patch(bytes, position(bytes, "iloc") + 20, 65535, 2); + rejects(bytes); + bytes = fixture(); + patch(bytes, position(bytes, "ipma") + 12, 0xffffffff, 4); + rejects(bytes); + bytes = fixture(); + patch(bytes, position(bytes, "cdsc") + 10, 65535, 2); + rejects(bytes); +} + +TEST(BmffModel, rejectsExternalProtectedAndUnsupportedItemConstruction) { + auto bytes = fixture(); + patch(bytes, position(bytes, "infe") + 14, 1, 2); + rejects(bytes); + bytes = fixture(); + patch(bytes, position(bytes, "iloc") + 18, 1, 2); + rejects(bytes); + for (const auto method : {2u, 15u, 0x1001u}) { + Options opt; + opt.locationVersion = 1; + bytes = fixture(opt); + patch(bytes, position(bytes, "iloc") + 18, method, 2); + rejects(bytes); + } + Options opt; + opt.idat = true; + opt.locationVersion = 1; + bytes = fixture(opt); + patch(bytes, position(bytes, "idat") + 4, bmffType("free"), 4); + rejects(bytes); +} + +TEST(BmffModel, rejectsInvalidWidthsZeroLengthsAndExtentBounds) { + for (const auto width : {0u, 1u, 3u, 5u, 9u, 15u}) { + auto bytes = fixture(); + patch(bytes, position(bytes, "iloc") + 12, 0x40 | width, 1); + rejects(bytes); + } + for (const auto length : {uint64_t{0}, uint64_t{0xffffffff}}) { + auto bytes = fixture(); + patch(bytes, position(bytes, "iloc") + 26, length, 4); + rejects(bytes); + } + auto bytes = fixture(); + patch(bytes, position(bytes, "iloc") + 22, 0, 4); // Into the ftyp header, not media. + rejects(bytes); + Options opt; + opt.baseWidth = 8; + opt.offsetWidth = 8; + bytes = fixture(opt); + patch(bytes, position(bytes, "iloc") + 20, std::numeric_limits::max(), 8); + rejects(bytes); +} + +TEST(BmffModel, boundsAggregateResourcesAndStrings) { + const auto bytes = fixture(); + for (unsigned limit = 0; limit < 8; ++limit) { + BmffLimits limits; + switch (limit) { + case 0: + limits.maxBoxes = 2; + break; + case 1: + limits.maxItems = 2; + break; + case 2: + limits.maxExtents = 1; + break; + case 3: + limits.maxReferences = 1; + break; + case 4: + limits.maxAssociations = 1; + break; + case 5: + limits.maxStringBytes = 2; + break; + case 6: + limits.maxBytesRead = 8; + break; + case 7: + limits.maxDepth = 1; + break; + } + EXPECT_THROW(parse(bytes, limits), Error) << limit; + } + BmffLimits limits; + limits.maxStringLength = 2; + EXPECT_THROW(parse(bytes, limits), Error); + auto malformed = bytes; + const auto entry = position(malformed, "infe"); + patch(malformed, entry + 25, 'x', 1); // Remove the image-name terminator. + rejects(malformed); +} + +TEST(BmffModel, ioFailuresPropagateWithoutWriting) { + class FailingIo : public MemIo { + public: + using MemIo::read; + explicit FailingIo(const Bytes& bytes) : MemIo(bytes.data(), bytes.size()) { + } + bool failSeek{}; + int seek(int64_t offset, Position position) override { + return failSeek ? 1 : MemIo::seek(offset, position); + } + size_t read(byte*, size_t) override { + return 0; + } + }; + const auto bytes = fixture(); + FailingIo input(bytes); + EXPECT_THROW(parseBmff(input), Error); + input.failSeek = true; + EXPECT_THROW(parseBmff(input), Error); + EXPECT_EQ(input.size(), bytes.size()); + EXPECT_EQ(std::memcmp(input.mmap(), bytes.data(), bytes.size()), 0); +} + +TEST(BmffModel, resolvesSparse64BitFileWithoutReadingMediaOrAllocatingItsSize) { + if (sizeof(size_t) < 8) + GTEST_SKIP() << "BasicIo size() cannot represent this input on a 32-bit host"; + class SparseIo : public MemIo { + public: + using MemIo::read; + Bytes prefix; + Bytes mediaHeader; + uint64_t mediaOffset{uint64_t{1} << 33}; + uint64_t cursor{}; + size_t bytesRead{}; + bool forbiddenRead{}; + + size_t size() const override { + return static_cast(mediaOffset + 19); + } + int seek(int64_t offset, Position origin) override { + if (origin != beg || offset < 0 || static_cast(offset) > size()) + return 1; + cursor = static_cast(offset); + return 0; + } + size_t read(byte* output, size_t count) override { + const auto relative = cursor >= mediaOffset ? cursor - mediaOffset : cursor; + const auto& region = cursor >= mediaOffset ? mediaHeader : prefix; + if (relative > region.size() || count > region.size() - relative) { + forbiddenRead = true; + return 0; + } + std::copy_n(region.begin() + relative, count, output); + cursor += count; + bytesRead += count; + return count; + } + } input; + Options opt; + opt.noMetadata = true; + opt.baseWidth = 8; + input.prefix = fixture(opt); + input.prefix.resize(position(input.prefix, "mdat")); + patch(input.prefix, position(input.prefix, "iloc") + 20, input.mediaOffset + 8, 8); + const auto gap = input.mediaOffset - input.prefix.size(); + integer(input.prefix, 1, 4); + integer(input.prefix, bmffType("free"), 4); + integer(input.prefix, gap, 8); + integer(input.mediaHeader, 19, 4); + integer(input.mediaHeader, bmffType("mdat"), 4); + const auto document = parseBmff(input); + EXPECT_NO_THROW(enforceHeifWriteSupport(document)); + EXPECT_EQ(document.fileSize, input.mediaOffset + 19); + EXPECT_EQ(document.items.at(1).location.extents.at(0).source, (BmffSpan{input.mediaOffset + 8, 2})); + EXPECT_EQ(document.items.at(1).location.extents.at(1).source, (BmffSpan{input.mediaOffset + 14, 2})); + EXPECT_EQ(document.boxes.at(2).headerSize, 16u); + EXPECT_EQ(document.boxes.at(2).span.size, gap); + EXPECT_FALSE(input.forbiddenRead); + EXPECT_LT(input.bytesRead, 1024u); +} + +TEST(BmffModel, validatesUuidHeadersAndKnownCanonContainer) { + Options opt; + const Bytes uuid{0x85, 0xc0, 0xb6, 0x87, 0x82, 0x0f, 0x11, 0xe0, 0x81, 0x11, 0xf4, 0xce, 0x46, 0x2b, 0x6a, 0x48}; + Bytes content = uuid; + append(content, box(bmffType("CNCV"), {'v', '1', 0})); + opt.extraMeta = box(bmffType("uuid"), content, true); + const auto document = parse(fixture(opt)); + const auto& canon = document.boxes.at(1).children.back(); + EXPECT_EQ(canon.headerSize, 32u); + EXPECT_EQ(canon.children.size(), 1u); + EXPECT_EQ(canon.payload().size, 11u); + EXPECT_NO_THROW(enforceHeifWriteSupport(document)); + // An unknown UUID stays opaque, even if its content resembles boxes. + content[0] = 0; + opt.extraMeta = box(bmffType("uuid"), content); + auto unknown = parse(fixture(opt)); + EXPECT_TRUE(unknown.boxes.at(1).children.back().children.empty()); + EXPECT_THROW(enforceHeifWriteSupport(unknown), Error); + opt.extraMeta = box(bmffType("uuid"), Bytes(15)); + rejects(fixture(opt)); + content = uuid; + append(content, box(bmffType("zzzz"), {})); + opt.extraMeta = box(bmffType("uuid"), content); + EXPECT_THROW(enforceHeifWriteSupport(parse(fixture(opt))), Error); +} + +TEST(BmffModel, acceptsSelfContainedDataReferenceAndRejectsExternalReferences) { + Options opt; + auto dataReferences = full(); + integer(dataReferences, 1, 4); + append(dataReferences, box(bmffType("url "), full(0, 1))); + opt.extraMeta = box(bmffType("dinf"), box(bmffType("dref"), dataReferences)); + auto bytes = fixture(opt); + EXPECT_NO_THROW(enforceHeifWriteSupport(parse(bytes))); + patch(bytes, position(bytes, "url ") + 11, 0, 1); + rejects(bytes); + bytes = fixture(opt); + patch(bytes, position(bytes, "dref") + 12, 2, 4); + rejects(bytes); +} + +TEST(BmffModel, acceptsSharedPayloadRangesButRejectsRangesCrossingDataBounds) { + Options opt; + opt.baseWidth = 4; + auto bytes = fixture(opt); + const auto loc = position(bytes, "iloc"); + // Give the second primary extent the same range as the first. + patch(bytes, loc + 34, 0, 4); + auto document = parse(bytes); + EXPECT_EQ(document.items.at(1).location.extents.at(0).source, document.items.at(1).location.extents.at(1).source); + EXPECT_EQ(payload(bytes, document.items.at(1)), (Bytes{'A', 'B', 'A', 'B'})); + opt.idat = true; + opt.locationVersion = 1; + bytes = fixture(opt); + patch(bytes, position(bytes, "iloc") + 28, 10, 4); // length 2 crosses idat's 11 bytes. + rejects(bytes); + bytes = fixture(); + // Even an extent inside the file must stay within its own mdat payload. + patch(bytes, position(bytes, "iloc") + 22, position(bytes, "mdat") + 7, 4); + rejects(bytes); +} + +TEST(BmffModel, validatesSpanArithmeticIndependentlyOfInputSize) { + BmffBox box; + box.headerSize = 8; + box.span = {std::numeric_limits::max() - 4, 8}; + EXPECT_THROW(static_cast(box.payload()), Error); + box.span = {0, 7}; + EXPECT_THROW(static_cast(box.payload()), Error); + box.span = {100, 8}; + EXPECT_EQ(box.payload(), (BmffSpan{108, 0})); +} + +TEST(BmffModel, leavesProductionBmffWriterDisabled) { + const auto bytes = fixture(); + auto input = std::make_unique(bytes.data(), bytes.size()); + BmffImage image(std::move(input), defaultImageCtorParams(false)); + EXPECT_EQ(image.checkMode(mdExif), amRead); + EXPECT_EQ(image.checkMode(mdXmp), amRead); + EXPECT_THROW(image.writeMetadata(), Error); + EXPECT_EQ(image.io().size(), bytes.size()); + EXPECT_EQ(std::memcmp(image.io().mmap(), bytes.data(), bytes.size()), 0); +} + +struct CorpusCase { + const char* file; + uint32_t primary; + size_t count; + uint32_t exif; + uint32_t xmp; + bool heif; +}; + +class BmffCorpus : public testing::TestWithParam {}; + +TEST_P(BmffCorpus, agreesWithIndependentItemInventory) { + const auto& expected = GetParam(); + FileIo input(std::string(TESTDATA_PATH) + "/" + expected.file); + ASSERT_EQ(input.open("rb"), 0); + const auto document = parseBmff(input); + EXPECT_EQ(document.primaryItem, expected.primary); + EXPECT_EQ(document.items.size(), expected.count); + EXPECT_EQ(document.infoOrder.size(), expected.count); + EXPECT_EQ(document.locationOrder.size(), expected.count); + const auto exif = document.metadataItems(bmffType("Exif")); + const auto xmp = document.metadataItems(bmffType("mime")); + EXPECT_EQ(exif, expected.exif ? std::vector{expected.exif} : std::vector{}); + EXPECT_EQ(xmp, expected.xmp ? std::vector{expected.xmp} : std::vector{}); + if (expected.heif) { + EXPECT_NO_THROW(enforceHeifWriteSupport(document)); + } else { + EXPECT_THROW(enforceHeifWriteSupport(document), Error); + } +} + +INSTANTIATE_TEST_SUITE_P( + ExistingFixtures, BmffCorpus, + testing::Values(CorpusCase{"Stonehenge.heic", 1, 3, 2, 3, true}, CorpusCase{"IMG_3578.heic", 49, 51, 51, 0, true}, + CorpusCase{"2021-02-13-1929.heic", 49, 51, 51, 0, true}, + CorpusCase{"Canon.HIF", 1, 8, 768, 769, true}, CorpusCase{"Sony.HIF", 10, 15, 14, 15, true}, + CorpusCase{"heic.heic", 20004, 4, 0, 0, true}, + CorpusCase{"issue_9292_sony_1_top_left.HIF", 1, 3, 2, 3, true}, + CorpusCase{"issue_9292_sony_3_bottom_right.HIF", 1, 3, 2, 3, true}, + CorpusCase{"issue_9292_sony_6_right_top.HIF", 1, 3, 2, 3, true}, + CorpusCase{"issue_9292_sony_8_left-bottom.HIF", 1, 3, 2, 3, true}, + CorpusCase{"avif.avif", 1, 2, 2, 0, false}, CorpusCase{"avif_exif_xmp.avif", 1, 3, 2, 3, false}, + CorpusCase{"avif_metadata2.avif", 1, 3, 2, 3, false})); + +TEST(BmffModel, rejectsNonItemFormatsAndMalformedRegressionFiles) { + for (const auto* file : {"Canon-R6-pruned.CR3", "Reagan.jxl", "issue_2233_poc1.jxl", "issue_2233_poc2.jxl", + "issue_1793_poc.heic", "pr_2612_poc.heic"}) { + SCOPED_TRACE(file); + FileIo input(std::string(TESTDATA_PATH) + "/" + file); + ASSERT_EQ(input.open("rb"), 0); + EXPECT_THROW(parseBmff(input), Error); + } +} + +#endif // EXV_ENABLE_BMFF From 22eb0f2e18b9b2509b388068347dba66b4641a23 Mon Sep 17 00:00:00 2001 From: Vaclav Haisman Date: Fri, 9 Oct 2026 23:53:05 +0200 Subject: [PATCH 03/40] [bmff] Add compact HEIF container rewriting Rebuild item tables and relocate streamed payload ranges while removing obsolete primary metadata, unused media bytes, and padding. Reject shared metadata edits, ambiguous XMP MIME types, and unsupported relocation before writing, then verify the prepared output. Related to #2349. This private engine adds no image codec dependency. --- src/CMakeLists.txt | 2 + src/bmffimage_int.cpp | 21 +- src/bmffwrite_int.cpp | 647 ++++++++++++++++++++++++++++++++++++++++++ src/bmffwrite_int.hpp | 36 +++ src/meson.build | 1 + 5 files changed, 705 insertions(+), 2 deletions(-) create mode 100644 src/bmffwrite_int.cpp create mode 100644 src/bmffwrite_int.hpp diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index aef2b0ad01..37b080ad94 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -6,6 +6,8 @@ add_library( exiv2lib_int OBJECT bmffimage_int.cpp bmffimage_int.hpp + bmffwrite_int.cpp + bmffwrite_int.hpp canonmn_int.cpp canonmn_int.hpp casiomn_int.cpp diff --git a/src/bmffimage_int.cpp b/src/bmffimage_int.cpp index c62b7eedb6..176ee80eaf 100644 --- a/src/bmffimage_int.cpp +++ b/src/bmffimage_int.cpp @@ -567,8 +567,25 @@ void enforceHeifWriteSupport(const BmffDocument& document) { supported(primaryType == bmffType("hvc1") || primaryType == bmffType("grid") || primaryType == bmffType("iden") || primaryType == bmffType("iovl"), "primary image type"); - for (const auto id : document.metadataItems(bmffType("mime"))) - supported(document.items.at(id).info.contentEncoding.empty(), "compressed primary XMP"); + for (const auto& reference : document.references) { + if (reference.type != bmffType("cdsc") || + std::find(reference.to.begin(), reference.to.end(), document.primaryItem) == reference.to.end()) + continue; + const auto& info = document.items.at(reference.from).info; + if (info.type != bmffType("mime")) + continue; + auto type = info.contentType.substr(0, info.contentType.find(';')); + std::transform(type.begin(), type.end(), type.begin(), + [](unsigned char c) { return static_cast(c >= 'A' && c <= 'Z' ? c + ('a' - 'A') : c); }); + const auto first = type.find_first_not_of(" \t"); + const auto last = type.find_last_not_of(" \t"); + if (first != std::string::npos) + type = type.substr(first, last - first + 1); + if (type == "application/rdf+xml") { + supported(info.contentType == "application/rdf+xml", "ambiguous primary XMP MIME type"); + supported(info.contentEncoding.empty(), "compressed primary XMP"); + } + } checkRelocation(document.boxes, Context::file); } diff --git a/src/bmffwrite_int.cpp b/src/bmffwrite_int.cpp new file mode 100644 index 0000000000..cb0668b2ee --- /dev/null +++ b/src/bmffwrite_int.cpp @@ -0,0 +1,647 @@ +// SPDX-License-Identifier: GPL-2.0-or-later + +#include "bmffwrite_int.hpp" + +#ifdef EXV_ENABLE_BMFF + +#include "basicio.hpp" +#include "enforce.hpp" +#include "error.hpp" + +#include +#include +#include +#include +#include + +namespace Exiv2::Internal { +namespace { +using Bytes = std::vector; +constexpr uint64_t maxPosition = std::numeric_limits::max(); +constexpr uint64_t max32 = std::numeric_limits::max(); +constexpr uint32_t max16 = std::numeric_limits::max(); +constexpr size_t copyBufferSize = 64 * 1024; + +void require(bool condition) { + enforce(condition, ErrorCode::kerCorruptedMetadata); +} + +void supported(bool condition, std::string_view reason) { + if (!condition) + throw Error(ErrorCode::kerErrorMessage, std::string("Unsupported HEIF edit: ") + std::string(reason)); +} + +uint64_t add(uint64_t a, uint64_t b) { + require(a <= maxPosition && b <= maxPosition - a); + return a + b; +} + +uint64_t end(BmffSpan span) { + return add(span.offset, span.size); +} + +void number(Bytes& bytes, uint64_t value, unsigned width) { + require(width <= 8 && (width == 8 || value < (uint64_t{1} << (width * 8)))); + require(bytes.size() <= BmffLimits{}.maxBytesRead - width); + for (unsigned i = width; i != 0; --i) + bytes.push_back(static_cast(value >> ((i - 1) * 8))); +} + +void string(Bytes& bytes, std::string_view value) { + require(value.size() < BmffLimits{}.maxBytesRead && bytes.size() < BmffLimits{}.maxBytesRead - value.size()); + bytes.insert(bytes.end(), value.begin(), value.end()); + bytes.push_back(0); +} + +Bytes full(uint8_t version, uint32_t flags = 0) { + Bytes bytes; + number(bytes, (uint32_t{version} << 24) | flags, 4); + return bytes; +} + +bool padding(uint32_t type) { + return type == bmffType("free") || type == bmffType("skip"); +} + +void read(BasicIo& input, uint64_t offset, byte* data, size_t size) { + require(offset <= maxPosition && size <= maxPosition - offset); + input.seekOrThrow(static_cast(offset), BasicIo::beg, ErrorCode::kerInputDataReadFailed); + input.readOrThrow(data, size, ErrorCode::kerInputDataReadFailed); + enforce(!input.error(), ErrorCode::kerInputDataReadFailed); +} + +void write(BasicIo& output, const byte* data, size_t size) { + if (size != 0) + enforce(output.write(data, size) == size && !output.error(), ErrorCode::kerImageWriteFailed); +} + +struct Chunk { + BmffSpan source; + const Bytes* bytes{}; + uint32_t item{}; + uint64_t position{}; + + uint64_t size() const { + return bytes ? bytes->size() : source.size; + } +}; + +struct Box { + uint32_t type{}; + bool extended{}; + std::array uuid{}; + Bytes prefix; + std::vector children; + std::vector chunks; + uint64_t position{}; + uint64_t size{}; + uint8_t header{}; +}; + +struct Relocation { + BmffSpan source; + uint64_t destination{}; +}; + +void measure(Box& box) { + uint64_t payload = box.prefix.size(); + for (auto& child : box.children) { + measure(child); + payload = add(payload, child.size); + } + for (const auto& chunk : box.chunks) + payload = add(payload, chunk.size()); + const unsigned uuidSize = box.type == bmffType("uuid") ? 16 : 0; + box.extended |= add(payload, 8 + uuidSize) > max32; + box.header = static_cast((box.extended ? 16 : 8) + uuidSize); + box.size = add(box.header, payload); +} + +//! Unite only ranges from the same source payload. Original item boundaries stay in iloc. +void mergeRanges(std::vector& spans) { + std::sort(spans.begin(), spans.end(), [](auto a, auto b) { return a.offset < b.offset; }); + size_t count = 0; + for (const auto span : spans) { + if (count && span.offset <= end(spans[count - 1])) { + auto& previous = spans[count - 1]; + previous.size = std::max(end(previous), end(span)) - previous.offset; + } else { + spans[count++] = span; + } + } + spans.resize(count); +} + +class Rewrite { + public: + Rewrite(BasicIo& input, BasicIo& output, const BmffDocument& original) : + input_(input), output_(output), original_(original), document_(original) { + } + + void run(const BmffMetadataUpdate& update) { + require(&input_ != &output_ && input_.isopen() && output_.isopen() && output_.size() == 0); + require(input_.size() == original_.fileSize); + enforceHeifWriteSupport(original_); + select(bmffType("Exif"), update.exif); + select(bmffType("mime"), update.xmp); + validateReferences(); + collectRanges(); + applyUpdates(); + for (const auto& entry : document_.associations) + associations_[entry.box.offset].push_back(&entry); + indexBoxes(original_.boxes); + normalizeLocations(); + + // Only offset width can change after locating the output; it promotes 4 -> 8 once. + for (unsigned pass = 0; pass < 2; ++pass) { + auto boxes = build(); + const auto size = locate(boxes); + if (relocate()) + continue; + boxes = build(); + require(locate(boxes) == size); + output_.seekOrThrow(0, BasicIo::beg, ErrorCode::kerImageWriteFailed); + for (const auto& box : boxes) + emit(box); + require(output_.size() == size); + verify(boxes); + return; + } + throw Error(ErrorCode::kerCorruptedMetadata); + } + + private: + void select(uint32_t type, const std::optional& value) { + if (!value) + return; + supported(value->size() <= bmffMetadataLimit, "metadata exceeds the allocation limit"); + const auto ids = original_.metadataItems(type); + removed_.insert(ids.begin(), ids.end()); + if (!value->empty()) + additions_.emplace(type, &*value); + } + + void validateReferences() const { + for (const auto& ref : original_.references) { + if (removed_.contains(ref.from)) { + supported(ref.type == bmffType("cdsc") && + std::all_of(ref.to.begin(), ref.to.end(), [&](auto id) { return id == original_.primaryItem; }), + "selected metadata is shared or has other relationships"); + } else { + for (const auto id : ref.to) + supported(!removed_.contains(id), "selected metadata is referenced by another item"); + } + } + } + + uint64_t container(const BmffItem& item, BmffSpan span) const { + if (item.location.constructionMethod == 1) { + require(original_.itemData.has_value()); + const auto data = *original_.itemData; + require(span.offset >= data.offset && end(span) <= end(data)); + return data.offset; + } + auto found = std::upper_bound(original_.mediaData.begin(), original_.mediaData.end(), span.offset, + [](uint64_t offset, auto range) { return offset < range.offset; }); + require(found != original_.mediaData.begin()); + --found; + require(span.offset >= found->offset && end(span) <= end(*found)); + return found->offset; + } + + void collectRanges() { + std::vector discarded; + for (const auto& [id, item] : original_.items) { + for (const auto& extent : item.location.extents) { + if (removed_.contains(id)) + discarded.push_back(extent.source); + else + ranges_[container(item, extent.source)].push_back(extent.source); + } + } + std::vector retained; + for (auto& [offset, spans] : ranges_) { + mergeRanges(spans); + retained.insert(retained.end(), spans.begin(), spans.end()); + } + mergeRanges(discarded); + size_t next = 0; + for (const auto span : discarded) { + while (next < retained.size() && end(retained[next]) <= span.offset) + ++next; + supported(next == retained.size() || retained[next].offset >= end(span), + "removed metadata overlaps a retained item"); + } + } + + uint32_t allocateId() const { + require(!document_.items.empty()); + const auto greatest = document_.items.rbegin()->first; + if (greatest != max32) + return greatest + 1; + uint32_t id = 1; + for (const auto& [used, item] : document_.items) { + if (used != id) + return id; + supported(id != max32, "no unused item ID"); + ++id; + } + return id; + } + + void applyUpdates() { + for (const auto id : removed_) + document_.items.erase(id); + std::erase_if(document_.infoOrder, [&](auto id) { return removed_.contains(id); }); + std::erase_if(document_.locationOrder, [&](auto id) { return removed_.contains(id); }); + std::erase_if(document_.references, [&](const auto& ref) { return removed_.contains(ref.from); }); + std::erase_if(document_.associations, [&](const auto& entry) { return removed_.contains(entry.itemId); }); + for (const auto& [type, bytes] : additions_) { + require(document_.items.size() < BmffLimits{}.maxItems); + const auto id = allocateId(); + BmffItem item; + item.info.version = id > max16 ? 3 : 2; + item.info.flags = 1; + item.info.type = type; + item.info.name = type == bmffType("Exif") ? "Exif" : "XMP"; + if (type == bmffType("mime")) + item.info.contentType = "application/rdf+xml"; + item.location.dataSize = bytes->size(); + item.location.extents.push_back({0, 0, bytes->size(), {}}); + document_.items.emplace(id, std::move(item)); + document_.infoOrder.push_back(id); + document_.locationOrder.push_back(id); + document_.references.push_back({{}, bmffType("cdsc"), id, {document_.primaryItem}}); + newItems_.emplace(id, bytes); + } + } + + void indexBoxes(const std::vector& boxes) { + for (const auto& box : boxes) { + originalBoxes_.emplace(box.span.offset, &box); + indexBoxes(box.children); + } + } + + void normalizeLocations() { + auto& format = document_.locationFormat; + format.offsetSize = 4; + format.lengthSize = 4; + format.baseOffsetSize = 0; + if (document_.items.rbegin()->first > max16 || document_.items.size() > max16) + format.version = 2; + for (auto& [id, item] : document_.items) { + item.location.baseOffset = 0; + if (item.location.constructionMethod == 1) + format.version = std::max(format.version, 1); + for (const auto& extent : item.location.extents) + if (extent.length > max32) + format.lengthSize = 8; + } + } + + Box itemInfo(uint32_t id) const { + const auto& info = document_.items.at(id).info; + if (info.box.size) + return opaque(*originalBoxes_.at(info.box.offset)); + Box box; + box.type = bmffType("infe"); + box.prefix = full(info.version, info.flags); + number(box.prefix, id, info.version == 2 ? 2 : 4); + number(box.prefix, 0, 2); + number(box.prefix, info.type, 4); + string(box.prefix, info.name); + if (info.type == bmffType("mime")) { + string(box.prefix, info.contentType); + string(box.prefix, info.contentEncoding); + } + return box; + } + + Bytes locations() const { + const auto& format = document_.locationFormat; + auto bytes = full(format.version); + number(bytes, (format.offsetSize << 4) | format.lengthSize, 1); + number(bytes, format.indexSize, 1); + const unsigned width = format.version == 2 ? 4 : 2; + number(bytes, document_.items.size(), width); + for (const auto id : document_.locationOrder) { + const auto& loc = document_.items.at(id).location; + number(bytes, id, width); + if (format.version) + number(bytes, loc.constructionMethod, 2); + number(bytes, 0, 2); + number(bytes, loc.extents.size(), 2); + for (const auto& extent : loc.extents) { + if (format.version && format.indexSize) + number(bytes, extent.index, format.indexSize); + // The first layout pass measures fields whose relocated offsets are not known yet. + number(bytes, format.offsetSize == 4 && extent.offset > max32 ? 0 : extent.offset, format.offsetSize); + number(bytes, extent.length, format.lengthSize); + } + } + return bytes; + } + + Box references(const BmffBox* original = nullptr) const { + Box box; + box.type = bmffType("iref"); + box.extended = original && original->headerSize == 16; + uint8_t version = original ? original->fullBox->version : 0; + if (document_.items.rbegin()->first > max16) + version = 1; + box.prefix = full(version); + for (const auto& ref : document_.references) { + Box child; + child.type = ref.type; + if (ref.box.size) + child.extended = originalBoxes_.at(ref.box.offset)->headerSize == 16; + number(child.prefix, ref.from, version ? 4 : 2); + number(child.prefix, ref.to.size(), 2); + for (const auto id : ref.to) + number(child.prefix, id, version ? 4 : 2); + box.children.push_back(std::move(child)); + } + return box; + } + + static Box opaque(const BmffBox& original) { + Box box; + box.type = original.type; + box.extended = original.headerSize == (original.type == bmffType("uuid") ? 32 : 16); + box.uuid = original.userType; + box.chunks.push_back({original.payload()}); + return box; + } + + std::optional rebuild(const BmffBox& original, bool property = false) const { + auto box = opaque(original); + if (padding(box.type)) { + if (!property) + return {}; + box.chunks.clear(); // Keep indexed property slots; discard their padding bytes. + } else if (box.type == bmffType("mdat") || box.type == bmffType("idat")) { + box.chunks.clear(); + const auto found = ranges_.find(original.payload().offset); + if (found == ranges_.end()) + return {}; + for (const auto range : found->second) + box.chunks.push_back({range}); + } else if (box.type == bmffType("iloc")) { + box.chunks.clear(); + box.prefix = locations(); + } else if (box.type == bmffType("iinf")) { + box.chunks.clear(); + auto version = original.fullBox->version; + if (document_.items.size() > max16) + version = std::max(version, 1); + box.prefix = full(version); + number(box.prefix, document_.items.size(), version ? 4 : 2); + for (const auto id : document_.infoOrder) + box.children.push_back(itemInfo(id)); + } else if (box.type == bmffType("iref")) { + box = references(&original); + } else if (box.type == bmffType("ipma")) { + box.chunks.clear(); + const auto format = *original.fullBox; + box.prefix = full(format.version, format.flags); + const auto found = associations_.find(original.span.offset); + number(box.prefix, found == associations_.end() ? 0 : found->second.size(), 4); + if (found == associations_.end()) + return box; + for (const auto* pointer : found->second) { + const auto& entry = *pointer; + + number(box.prefix, entry.itemId, format.version ? 4 : 2); + number(box.prefix, entry.properties.size(), 1); + for (const auto& prop : entry.properties) + number(box.prefix, prop.index | (prop.essential ? (format.flags & 1 ? 0x8000 : 0x80) : 0), + format.flags & 1 ? 2 : 1); + } + } else if (!original.children.empty() || box.type == bmffType("ipco")) { + box.chunks.clear(); + if (original.fullBox) + box.prefix = full(original.fullBox->version, original.fullBox->flags); + bool hasReferences = false; + for (const auto& child : original.children) { + hasReferences |= child.type == bmffType("iref"); + if (auto rebuilt = rebuild(child, box.type == bmffType("ipco"))) + box.children.push_back(std::move(*rebuilt)); + } + if (box.type == bmffType("meta") && !hasReferences && !document_.references.empty()) + box.children.push_back(references()); + if (box.type == bmffType("dref")) + number(box.prefix, box.children.size(), 4); + } + return box; + } + + std::vector build() const { + std::vector boxes; + for (const auto& box : original_.boxes) + if (auto rebuilt = rebuild(box)) + boxes.push_back(std::move(*rebuilt)); + if (!newItems_.empty()) { + Box box; + box.type = bmffType("mdat"); + for (const auto& [id, bytes] : newItems_) + box.chunks.push_back({{}, bytes, id}); + boxes.push_back(std::move(box)); + } + return boxes; + } + + uint64_t locate(Box& box, uint64_t offset) { + box.position = offset; + auto position = add(add(offset, box.header), box.prefix.size()); + if (box.type == bmffType("idat")) + idatPosition_ = add(offset, box.header); + for (auto& child : box.children) + position = locate(child, position); + for (auto& chunk : box.chunks) { + chunk.position = position; + if (chunk.bytes) + newPositions_.emplace(chunk.item, position); + else if (box.type == bmffType("mdat") || box.type == bmffType("idat")) + relocations_.push_back({chunk.source, position}); + position = add(position, chunk.size()); + } + require(position == add(offset, box.size)); + return position; + } + + uint64_t locate(std::vector& boxes) { + relocations_.clear(); + newPositions_.clear(); + idatPosition_ = 0; + uint64_t offset = 0; + for (auto& box : boxes) { + measure(box); + offset = locate(box, offset); + } + std::sort(relocations_.begin(), relocations_.end(), + [](const auto& a, const auto& b) { return a.source.offset < b.source.offset; }); + return offset; + } + + bool relocate() { + bool promoted = false; + for (auto& [id, item] : document_.items) { + auto& location = item.location; + for (auto& extent : location.extents) { + uint64_t position = 0; + if (newItems_.contains(id)) { + position = newPositions_.at(id); + } else { + auto found = std::upper_bound(relocations_.begin(), relocations_.end(), extent.source.offset, + [](auto offset, const auto& map) { return offset < map.source.offset; }); + require(found != relocations_.begin()); + --found; + require(extent.source.offset >= found->source.offset && end(extent.source) <= end(found->source)); + position = add(found->destination, extent.source.offset - found->source.offset); + } + const auto base = location.constructionMethod == 1 ? idatPosition_ : 0; + require(position >= base); + extent.offset = position - base; + if (extent.offset > max32 && document_.locationFormat.offsetSize != 8) { + document_.locationFormat.offsetSize = 8; + promoted = true; + } + } + } + return promoted; + } + + void emit(const Box& box) { + require(output_.tell() == box.position); + Bytes header; + number(header, box.extended ? 1 : box.size, 4); + number(header, box.type, 4); + if (box.extended) + number(header, box.size, 8); + if (box.type == bmffType("uuid")) + header.insert(header.end(), box.uuid.begin(), box.uuid.end()); + write(output_, header.data(), header.size()); + write(output_, box.prefix.data(), box.prefix.size()); + for (const auto& child : box.children) + emit(child); + auto& buffer = copyBuffer_; + for (const auto& chunk : box.chunks) { + require(output_.tell() == chunk.position); + for (uint64_t done = 0; done < chunk.size();) { + const auto count = static_cast(std::min(buffer.size(), chunk.size() - done)); + if (chunk.bytes) { + write(output_, chunk.bytes->data() + done, count); + } else { + read(input_, add(chunk.source.offset, done), buffer.data(), count); + write(output_, buffer.data(), count); + } + done += count; + } + } + } + + void verifyBytes(const Box& box) { + for (const auto& child : box.children) + verifyBytes(child); + auto& a = copyBuffer_; + auto& b = verifyBuffer_; + for (const auto& chunk : box.chunks) { + for (uint64_t done = 0; done < chunk.size();) { + const auto count = static_cast(std::min(a.size(), chunk.size() - done)); + read(output_, add(chunk.position, done), b.data(), count); + if (chunk.bytes) { + require(std::equal(b.begin(), b.begin() + count, chunk.bytes->begin() + done)); + } else { + read(input_, add(chunk.source.offset, done), a.data(), count); + require(std::equal(a.begin(), a.begin() + count, b.begin())); + } + done += count; + } + } + } + + void verify(const std::vector& boxes) { + const auto parsed = parseBmff(output_); + enforceHeifWriteSupport(parsed); + require(parsed.majorBrand == document_.majorBrand && parsed.minorVersion == document_.minorVersion && + parsed.compatibleBrands == document_.compatibleBrands && parsed.primaryItem == document_.primaryItem && + parsed.infoOrder == document_.infoOrder && parsed.locationOrder == document_.locationOrder && + parsed.items.size() == document_.items.size()); + for (const auto& [id, item] : document_.items) { + const auto& actual = parsed.items.at(id); + const auto& info = item.info; + require(actual.info.type == info.type && actual.info.name == info.name && actual.info.flags == info.flags && + actual.info.contentType == info.contentType && actual.info.contentEncoding == info.contentEncoding && + actual.info.uriType == info.uriType); + const auto& expected = item.location; + require(actual.location.constructionMethod == expected.constructionMethod && actual.location.baseOffset == 0 && + actual.location.dataSize == expected.dataSize && + actual.location.extents.size() == expected.extents.size()); + for (size_t i = 0; i < expected.extents.size(); ++i) { + const auto& a = actual.location.extents[i]; + const auto& e = expected.extents[i]; + require(a.index == e.index && a.offset == e.offset && a.length == e.length); + } + } + require(parsed.references.size() == document_.references.size() && + parsed.associations.size() == document_.associations.size() && + parsed.properties.size() == document_.properties.size()); + for (size_t i = 0; i < document_.references.size(); ++i) { + const auto& a = parsed.references[i]; + const auto& e = document_.references[i]; + require(a.type == e.type && a.from == e.from && a.to == e.to); + } + for (size_t i = 0; i < document_.associations.size(); ++i) { + const auto& a = parsed.associations[i]; + const auto& e = document_.associations[i]; + require(a.itemId == e.itemId && a.properties.size() == e.properties.size()); + for (size_t j = 0; j < a.properties.size(); ++j) + require(a.properties[j].index == e.properties[j].index && + a.properties[j].essential == e.properties[j].essential); + } + for (size_t i = 0; i < document_.properties.size(); ++i) + require(parsed.properties[i].type == document_.properties[i].type); + for (const auto& box : boxes) + verifyBytes(box); + } + + BasicIo& input_; + BasicIo& output_; + const BmffDocument& original_; + BmffDocument document_; + std::set removed_; + std::map additions_; + std::map newItems_; + std::map> ranges_; + std::map originalBoxes_; + std::vector relocations_; + std::map> associations_; + std::array copyBuffer_{}; + std::array verifyBuffer_{}; + std::map newPositions_; + uint64_t idatPosition_{}; +}; + +} // namespace + +std::vector readBmffItem(BasicIo& input, const BmffItem& item, uint64_t limit) { + supported(item.location.dataSize <= limit && item.location.dataSize <= std::numeric_limits::max(), + "metadata exceeds the allocation limit"); + Bytes bytes(static_cast(item.location.dataSize)); + size_t position = 0; + for (const auto& extent : item.location.extents) { + require(extent.source.size <= bytes.size() - position); + read(input, extent.source.offset, bytes.data() + position, static_cast(extent.source.size)); + position += static_cast(extent.source.size); + } + require(position == bytes.size()); + return bytes; +} + +void rewriteBmff(BasicIo& input, BasicIo& output, const BmffDocument& original, const BmffMetadataUpdate& update) { + Rewrite(input, output, original).run(update); +} + +} // namespace Exiv2::Internal +#endif diff --git a/src/bmffwrite_int.hpp b/src/bmffwrite_int.hpp new file mode 100644 index 0000000000..f9d44472b6 --- /dev/null +++ b/src/bmffwrite_int.hpp @@ -0,0 +1,36 @@ +// SPDX-License-Identifier: GPL-2.0-or-later + +#ifndef BMFFWRITE_INT_HPP +#define BMFFWRITE_INT_HPP + +#include "bmffimage_int.hpp" + +#ifdef EXV_ENABLE_BMFF + +namespace Exiv2::Internal { + +//! Metadata buffers are bounded independently of the encoded image size. +inline constexpr uint64_t bmffMetadataLimit = 64 * 1024 * 1024; + +struct BmffMetadataUpdate { + //! No value preserves the category; an empty value removes it from the primary image. + std::optional> exif; + std::optional> xmp; +}; + +//! Gather a checked item's extents, with an explicit metadata allocation limit. +std::vector readBmffItem(BasicIo& input, const BmffItem& item, uint64_t limit = bmffMetadataLimit); + +/*! + @brief Compact an item-based HEIF into a fresh, open, seekable output. + Input must remain unchanged and must not alias output. No transfer to the input + is performed. The output may contain partial data after an I/O failure and must + then be discarded. On success its parsed structure and copied bytes have been + verified. Unknown relocation, shared-metadata edits and conflicting overlap are + rejected before any output is written. This function does not serialize TIFF/XMP. + */ +void rewriteBmff(BasicIo& input, BasicIo& output, const BmffDocument& original, const BmffMetadataUpdate& update = {}); + +} // namespace Exiv2::Internal +#endif +#endif diff --git a/src/meson.build b/src/meson.build index 4582388b8c..ef7eadc37c 100644 --- a/src/meson.build +++ b/src/meson.build @@ -45,6 +45,7 @@ endif int_lib = files( 'bmffimage_int.cpp', + 'bmffwrite_int.cpp', 'canonmn_int.cpp', 'casiomn_int.cpp', 'cr2header_int.cpp', From 369c377a6b34c6952dee41ac9f2ee19dc1d7ad68 Mon Sep 17 00:00:00 2001 From: Vaclav Haisman Date: Fri, 9 Oct 2026 23:53:24 +0200 Subject: [PATCH 04/40] [heif] Enable native Exif and XMP metadata editing Register supported HEIF files through a private BmffImage subclass. Use fresh metadata serialization and compact rewriting for primary Exif/XMP updates and removal, with byte-identical no-ops and preservation checks. Keep AVIF, CR3, and JPEG XL writing disabled. Prepare local file output on disk before transfer; final replacement retains the existing BasicIo failure contract and is not atomic. Related to #2349. --- include/exiv2/image_types.hpp | 1 + src/CMakeLists.txt | 2 + src/heifimage_int.cpp | 605 ++++++++++++++++++++++++++++++++++ src/heifimage_int.hpp | 16 + src/image.cpp | 2 + src/meson.build | 1 + 6 files changed, 627 insertions(+) create mode 100644 src/heifimage_int.cpp create mode 100644 src/heifimage_int.hpp 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 37b080ad94..66b4de0b01 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -109,6 +109,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/heifimage_int.cpp b/src/heifimage_int.cpp new file mode 100644 index 0000000000..997ca9647a --- /dev/null +++ b/src/heifimage_int.cpp @@ -0,0 +1,605 @@ +// SPDX-License-Identifier: GPL-2.0-or-later + +#include "heifimage_int.hpp" + +#ifdef EXV_ENABLE_BMFF +#include "basicio.hpp" +#include "bmffimage.hpp" +#include "bmffwrite_int.hpp" +#include "enforce.hpp" +#include "error.hpp" +#include "futils.hpp" +#include "tags.hpp" +#include "tiffimage.hpp" +#include "value.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef EXV_ENABLE_FILESYSTEM +#include +#include +#endif + +namespace Exiv2::Internal { +namespace { +using Bytes = std::vector; + +void supported(bool condition, std::string_view reason) { + if (!condition) + throw Error(ErrorCode::kerErrorMessage, std::string("Unsupported HEIF edit: ") + std::string(reason)); +} + +Bytes readRange(BasicIo& io, BmffSpan span) { + supported(span.size <= bmffMetadataLimit, "metadata exceeds the allocation limit"); + Bytes bytes(static_cast(span.size)); + io.seekOrThrow(static_cast(span.offset), BasicIo::beg, ErrorCode::kerInputDataReadFailed); + io.readOrThrow(bytes.data(), bytes.size(), ErrorCode::kerInputDataReadFailed); + return bytes; +} + +std::string encodeXmp(const XmpData& data) { + if (data.empty()) + return {}; + std::string packet; + enforce(XmpParser::encode(packet, data, XmpParser::useCompactFormat | XmpParser::omitAllFormatting) == 0, + ErrorCode::kerInvalidXMP); + supported(packet.size() <= bmffMetadataLimit, "XMP exceeds the allocation limit"); + return packet; +} + +void merge(ExifData& target, const ExifData& source) { + std::set keys; + for (const auto& datum : source) + keys.insert(datum.key()); + target.erase(std::remove_if(target.begin(), target.end(), [&](const auto& d) { return keys.contains(d.key()); }), + target.end()); + for (const auto& datum : source) + target.add(datum); +} + +void merge(XmpData& target, const XmpData& source) { + for (const auto& datum : source) { + auto found = target.findKey(XmpKey(datum.key())); + if (found != target.end()) + target.erase(found); + target.add(datum); + } +} + +// Compare raw values, preserving duplicate tags and attached thumbnail data. +template +bool sameData(const Data& a, const Data& b) { + if (a.count() != b.count()) + return false; + auto snapshot = [](const Data& data) { + std::multimap> values; + uint64_t total = 0; + for (const auto& datum : data) { + supported(datum.size() <= bmffMetadataLimit - total, "metadata exceeds the allocation limit"); + total += datum.size(); + Bytes bytes(datum.size()); + if (!bytes.empty()) + datum.copy(bytes.data(), littleEndian); + supported(datum.value().sizeDataArea() <= bmffMetadataLimit - total, "metadata exceeds the allocation limit"); + auto area = datum.value().dataArea(); + total += area.size(); + if (!area.empty()) + bytes.insert(bytes.end(), area.c_data(), area.c_data() + area.size()); + values.emplace(datum.key(), std::pair(datum.typeId(), std::move(bytes))); + } + return values; + }; + return snapshot(a) == snapshot(b); +} + +struct Metadata { + ExifData exif; + IptcData iptc; + XmpData xmp; + XmpData embeddedXmp; + std::string packet; + ByteOrder order{littleEndian}; + DataBuf icc; + uint32_t width{}, height{}; +}; + +Metadata readMetadata(BasicIo& io, const BmffDocument& document, const DecodeParams& params) { + Metadata metadata; + uint64_t total = 0; + auto read = [&](uint32_t id) { + auto bytes = readBmffItem(io, document.items.at(id), bmffMetadataLimit - total); + total += bytes.size(); + return bytes; + }; + for (auto id : document.metadataItems(bmffType("Exif"))) { + auto bytes = read(id); + enforce(bytes.size() >= 12, ErrorCode::kerCorruptedMetadata); + const auto offset = getULong(bytes.data(), bigEndian); + enforce(offset <= bytes.size() - 12, ErrorCode::kerCorruptedMetadata); + ExifData exif; + IptcData iptc; + XmpData xmp; + auto order = TiffParser::decode(exif, iptc, xmp, bytes.data() + 4 + offset, bytes.size() - 4 - offset, params); + enforce(order != invalidByteOrder, ErrorCode::kerCorruptedMetadata); + metadata.order = order; + merge(metadata.exif, exif); + for (const auto& datum : iptc) + metadata.iptc.add(datum); + merge(metadata.embeddedXmp, xmp); + } + metadata.xmp = metadata.embeddedXmp; + auto xmpIds = document.metadataItems(bmffType("mime")); + for (auto id : xmpIds) { + supported(document.items.at(id).info.contentEncoding.empty(), "compressed primary XMP"); + auto bytes = read(id); + std::string packet(bytes.begin(), bytes.end()); + XmpData xmp; + enforce(XmpParser::decode(xmp, packet, params) == 0, ErrorCode::kerInvalidXMP); + merge(metadata.xmp, xmp); + metadata.packet = std::move(packet); + } + if (xmpIds.size() != 1 || !metadata.embeddedXmp.empty()) + metadata.packet = encodeXmp(metadata.xmp); + + std::set properties; + for (const auto& entry : document.associations) { + if (entry.itemId == document.primaryItem) { + for (const auto& association : entry.properties) + if (association.index != 0) + properties.insert(association.index); + } + } + for (auto index : properties) { + const auto& property = document.properties.at(index - 1); + if (property.type != bmffType("ispe") && property.type != bmffType("colr")) + continue; + auto bytes = readRange(io, property.payload()); + if (property.type == bmffType("ispe")) { + enforce(bytes.size() == 12, ErrorCode::kerCorruptedMetadata); + metadata.width = getULong(bytes.data() + 4, bigEndian); + metadata.height = getULong(bytes.data() + 8, bigEndian); + } else if (bytes.size() >= 4 && (getULong(bytes.data(), bigEndian) == bmffType("prof") || + getULong(bytes.data(), bigEndian) == bmffType("rICC"))) { + metadata.icc = DataBuf(bytes.data() + 4, bytes.size() - 4); + } + } + return metadata; +} + +void eraseTag(ExifData& exif, std::string_view key) { + exif.erase(std::remove_if(exif.begin(), exif.end(), [&](const auto& d) { return d.key() == key; }), exif.end()); +} + +bool canonDerived(const Exifdatum& datum) { + // These values are synthesized by decodeCanonAFInfo from Canon's 0x0026 + // record. ExifParser filters the same read-only fields for JPEG writing. + return datum.groupName() == "Canon" && ((datum.tag() >= 0x2600 && datum.tag() <= 0x260e) || datum.tag() == 0x2611); +} + +ExifData derivedCanonData(const ExifData& data) { + ExifData derived; + for (const auto& datum : data) + if (canonDerived(datum)) + derived.add(datum); + return derived; +} + +ExifData exifValues(ExifData data) { + const bool decodedMakerNote = data.findKey(ExifKey("Exif.MakerNote.ByteOrder")) != data.end(); + data.erase(std::remove_if(data.begin(), data.end(), + [&](const auto& datum) { + const auto key = datum.key(); + return key == "Exif.Image.ExifTag" || key == "Exif.Image.GPSTag" || + key == "Exif.Photo.InteroperabilityTag" || key == "Exif.MakerNote.Offset" || + key == "Exif.Thumbnail.JPEGInterchangeFormat" || + key == "Exif.Thumbnail.StripOffsets" || + (decodedMakerNote && key == "Exif.Photo.MakerNote"); + }), + data.end()); + return data; +} + +Bytes encodeExif(ExifData exif, const IptcData& iptc, XmpData embedded, ByteOrder order, const DecodeParams& params) { + // A fresh tree excludes original TIFF gaps, shortened values and tail bytes. + // The serializer reconstructs known MakerNotes and copies retained data areas. + const auto requested = exifValues(exif); + exif.erase(std::remove_if(exif.begin(), exif.end(), canonDerived), exif.end()); + MemIo output; + uint64_t total = 0; + for (const auto& datum : exif) { + supported(datum.size() <= bmffMetadataLimit - total, "Exif exceeds the allocation limit"); + total += datum.size(); + supported(datum.value().sizeDataArea() <= bmffMetadataLimit - total, "Exif exceeds the allocation limit"); + total += datum.value().sizeDataArea(); + } + TiffParser::encode(output, nullptr, 0, order, exif, iptc, embedded); + supported(output.size() <= bmffMetadataLimit - 4, "Exif exceeds the allocation limit"); + Bytes bytes(4 + output.size(), 0); + output.seekOrThrow(0, BasicIo::beg, ErrorCode::kerInputDataReadFailed); + output.readOrThrow(bytes.data() + 4, bytes.size() - 4); + ExifData checked; + IptcData checkedIptc; + XmpData checkedXmp; + enforce(TiffParser::decode(checked, checkedIptc, checkedXmp, bytes.data() + 4, bytes.size() - 4, params) == order, + ErrorCode::kerCorruptedMetadata); + supported(sameData(requested, exifValues(checked)), "TIFF serializer cannot preserve requested Exif values"); + supported(sameData(iptc, checkedIptc), "TIFF serializer cannot preserve embedded IPTC"); + supported(encodeXmp(embedded) == encodeXmp(checkedXmp), "TIFF serializer cannot preserve embedded XMP"); + return bytes; +} + +bool hasOrphanedMedia(const BmffDocument& document) { + std::vector spans; + for (const auto& [id, item] : document.items) + for (const auto& extent : item.location.extents) + spans.push_back(extent.source); + std::sort(spans.begin(), spans.end(), [](auto a, auto b) { return a.offset < b.offset; }); + uint64_t covered = 0, previousEnd = 0; + for (const auto span : spans) { + const auto end = span.offset + span.size; + if (end > previousEnd) { + covered += end - std::max(previousEnd, span.offset); + previousEnd = end; + } + } + uint64_t available = document.itemData ? document.itemData->size : 0; + for (const auto span : document.mediaData) + available += span.size; + return covered != available; +} + +// Expose staged file bytes through BasicIo's generic transfer contract. The +// existing FileIo-to-FileIo optimization mistakes filesystem::remove's boolean +// success for an error. Keep that independent FileIo repair outside this writer. +class TransferSource final : public BasicIo { + public: + explicit TransferSource(BasicIo& io) : io_(io) { + } + int open() override { + return io_.isopen() ? io_.seek(0, BasicIo::beg) : io_.open(); + } + int close() override { + return io_.close(); + } + size_t write(const byte*, size_t) override { + throw Error(ErrorCode::kerImageWriteFailed); + } + size_t write(BasicIo&) override { + throw Error(ErrorCode::kerImageWriteFailed); + } + int putb(byte) override { + throw Error(ErrorCode::kerImageWriteFailed); + } + DataBuf read(size_t count) override { + return io_.read(count); + } + size_t read(byte* data, size_t count) override { + return io_.read(data, count); + } + int getb() override { + return io_.getb(); + } + void transfer(BasicIo&) override { + throw Error(ErrorCode::kerImageWriteFailed); + } + int seek(int64_t offset, Position position) override { + return io_.seek(offset, position); + } + byte* mmap(bool = false) override { + throw Error(ErrorCode::kerImageWriteFailed); + } + int munmap() override { + return 0; + } + size_t tell() const override { + return io_.tell(); + } + size_t size() const override { + return io_.size(); + } + bool isopen() const override { + return io_.isopen(); + } + int error() const override { + return io_.error(); + } + bool eof() const override { + return io_.eof(); + } + const std::string& path() const noexcept override { + return io_.path(); + } + void populateFakeData() override { + throw Error(ErrorCode::kerImageWriteFailed); + } + + private: + BasicIo& io_; +}; + +class PreparedOutput { + public: + explicit PreparedOutput(BasicIo& source) { +#ifdef EXV_ENABLE_FILESYSTEM + if (dynamic_cast(&source)) { + // Exclusive create keeps an existing path or symlink from being followed. + // The open FileIo is retained until validation and final transfer. + const auto parent = std::filesystem::path(reinterpret_cast(source.path().c_str())).parent_path(); + std::random_device random; + for (unsigned attempt = 0; attempt != 32; ++attempt) { + auto name = parent / (".exiv2-heif-" + std::to_string(random()) + "-" + std::to_string(random())); +#ifdef _WIN32 + auto file = std::make_unique(name.wstring()); +#else + auto file = std::make_unique(name.string()); +#endif + if (file->open("w+bx") == 0) { + std::error_code error; + std::filesystem::permissions(name, std::filesystem::perms::owner_read | std::filesystem::perms::owner_write, + std::filesystem::perm_options::replace, error); + if (error) { + file.reset(); + std::filesystem::remove(name, error); + throw Error(ErrorCode::kerImageWriteFailed); + } + path_ = name; + io_ = std::move(file); + return; + } + if (errno != EEXIST) + throw Error(ErrorCode::kerDataSourceOpenFailed, source.path(), strError()); + } + throw Error(ErrorCode::kerImageWriteFailed); + } +#else + (void)source; +#endif + io_ = std::make_unique(); + } + + ~PreparedOutput() { + io_.reset(); +#ifdef EXV_ENABLE_FILESYSTEM + if (!path_.empty()) { + std::error_code error; + std::filesystem::remove(path_, error); + } +#endif + } + BasicIo& io() { + return *io_; + } + + private: + BasicIo::UniquePtr io_; +#ifdef EXV_ENABLE_FILESYSTEM + std::filesystem::path path_; +#endif +}; + +// Private subclass supplies edit intent without changing BmffImage's public ABI. +class HeifImage final : public BmffImage { + public: + HeifImage(BasicIo::UniquePtr io, const ImageCtorParams& params) : BmffImage(std::move(io), params) { + setTypeSupported(ImageType::heif, mdExif | mdIptc | mdXmp); + } + + std::string mimeType() const override { + return brand_ == bmffType("mif1") ? "image/heif" : "image/heic"; + } + + void readMetadata() override { + enforce(io_->open() == 0, ErrorCode::kerDataSourceOpenFailed, io_->path(), strError()); + IoCloser closer(*io_); + BmffDocument document; + try { + document = parseBmff(*io_); + assign(Internal::readMetadata(*io_, document, DecodeParams(max_recursion_depth_))); + brand_ = document.majorBrand; + } catch (const Error&) { + // Deferred layouts retain the existing reader. Writing still reparses and rejects. + BmffImage::readMetadata(); + loaded_ = true; + removeExif_ = removeXmp_ = false; + return; + } + } + + void setExifData(const ExifData& exif) override { + Image::setExifData(exif); + removeExif_ = exif.empty(); + } + void clearExifData() override { + Image::clearExifData(); + removeExif_ = true; + } + void setXmpData(const XmpData& xmp) override { + Image::setXmpData(xmp); + removeXmp_ = xmp.empty(); + } + void clearXmpData() override { + Image::clearXmpData(); + removeXmp_ = true; + } + void setXmpPacket(const std::string& packet) override { + supported(packet.size() <= bmffMetadataLimit, "XMP exceeds the allocation limit"); + Image::setXmpPacket(packet); + writeXmpFromPacket(true); + removeXmp_ = packet.empty(); + } + void clearXmpPacket() override { + Image::clearXmpPacket(); + removeXmp_ = true; + } + void clearMetadata() override { + clearExifData(); + clearXmpPacket(); + clearXmpData(); + // Only the writable categories are cleared; standalone IPTC/ICC edits are unsupported. + } + + void writeMetadata() override { + supported(dynamic_cast(io_.get()) == nullptr, "remote I/O"); + enforce(io_->open() == 0, ErrorCode::kerDataSourceOpenFailed, io_->path(), strError()); + IoCloser closer(*io_); + auto document = parseBmff(*io_); + enforceHeifWriteSupport(document); + const DecodeParams params(max_recursion_depth_); + auto original = Internal::readMetadata(*io_, document, params); + if (loaded_ || !iccProfile_.empty()) + supported(iccProfile_.size() == original.icc.size() && + (iccProfile_.empty() || + std::memcmp(iccProfile_.c_data(), original.icc.c_data(), iccProfile_.size()) == 0), + "ICC profile editing"); + if (loaded_ || !iptcData_.empty()) + supported(sameData(iptcData_, original.iptc) || (exifData_.empty() && iptcData_.empty()), + "standalone IPTC editing"); + supported(comment_.empty(), "image comments"); + + auto exif = exifData_; + if (original.exif.findKey(ExifKey("Exif.Photo.MakerNote")) != original.exif.end() && + exif.findKey(ExifKey("Exif.Photo.MakerNote")) == exif.end()) { + exif.erase(std::remove_if(exif.begin(), exif.end(), + [](const auto& datum) { + return ExifTags::isMakerGroup(datum.groupName()) || datum.groupName() == "MakerNote"; + }), + exif.end()); + } + auto packet = writeXmpFromPacket() ? xmpPacket_ : encodeXmp(xmpData_); + supported(packet.size() <= bmffMetadataLimit, "XMP exceeds the allocation limit"); + const bool xmpChanged = + removeXmp_ || (writeXmpFromPacket() ? packet != original.packet : packet != encodeXmp(original.xmp)); + const bool exifChanged = removeExif_ || !sameData(exif, original.exif); + BmffMetadataUpdate update; + if (xmpChanged || (exifChanged && exif.empty() && !original.embeddedXmp.empty())) + update.xmp = Bytes(packet.begin(), packet.end()); + // A separate MIME item becomes authoritative when XMP is edited. Remove its + // old embedded TIFF copy so it cannot reappear after removing the MIME item. + auto embedded = original.embeddedXmp; + auto xml = exif.findKey(ExifKey("Exif.Image.XMLPacket")); + // Even without a live XMLPacket tag, prior XMP may survive in TIFF slack. + const bool embeddedChanged = xmpChanged && !exif.empty(); + if (xmpChanged) { + eraseTag(exif, "Exif.Image.XMLPacket"); + embedded.clear(); + } else if (exifChanged) { + // The Exif API can also delete or replace the embedded XMLPacket tag. + // Honor its current value instead of restoring the old decoded packet. + embedded.clear(); + if (xml != exif.end()) { + supported(xml->size() <= bmffMetadataLimit, "embedded XMP exceeds the allocation limit"); + Bytes bytes(xml->size()); + xml->copy(bytes.data(), original.order); + enforce(XmpParser::decode(embedded, std::string(bytes.begin(), bytes.end()), params) == 0, + ErrorCode::kerInvalidXMP); + } + } + if (exifChanged || embeddedChanged) { + if (exif.findKey(ExifKey("Exif.Canon.AFInfo")) != exif.end() && + original.exif.findKey(ExifKey("Exif.Canon.AFInfo")) != original.exif.end()) { + supported(sameData(derivedCanonData(exif), derivedCanonData(original.exif)), + "Canon synthesized autofocus fields are read-only"); + } + if (exif.empty()) + update.exif = Bytes{}; + else + update.exif = encodeExif(exif, original.iptc, embedded, original.order, params); + } + if (!update.exif && !update.xmp && !hasOrphanedMedia(document)) + return; + + PreparedOutput prepared(*io_); + rewriteBmff(*io_, prepared.io(), document, update); + auto verified = Internal::readMetadata(prepared.io(), parseBmff(prepared.io()), params); + const auto preparedSize = prepared.io().size(); +#ifdef EXV_ENABLE_FILESYSTEM + if (dynamic_cast(io_.get())) { + TransferSource source(prepared.io()); + io_->transfer(source); + } else +#endif + { + io_->transfer(prepared.io()); + } + enforce(io_->size() == preparedSize, ErrorCode::kerTransferFailed, io_->path(), "short prepared-output transfer"); + assign(std::move(verified)); + brand_ = document.majorBrand; + } + + void printStructure(std::ostream& out, PrintStructureOption option, size_t depth) override { + if (!loaded_) + readMetadata(); + if (option == kpsXMP) { + std::string packet; + enforce(XmpParser::encode(packet, xmpData_) == 0, ErrorCode::kerInvalidXMP); + out << packet; + } else if (option == kpsIccProfile) + out.write(iccProfile_.c_str(), iccProfile_.size()); + else if (option == kpsBasic || option == kpsRecursive) { + // The legacy trace reader owns its traversal limits and metadata state. + // Give it a borrowed read-only view, preserving this object's pending edits. + BmffImage printer(std::make_unique(*io_), ImageCtorParams(false, max_recursion_depth_)); + printer.printStructure(out, option, depth); + } + } + + private: + void assign(Metadata metadata) { + exifData_ = std::move(metadata.exif); + iptcData_ = std::move(metadata.iptc); + xmpData_ = std::move(metadata.xmp); + xmpPacket_ = std::move(metadata.packet); + iccProfile_ = std::move(metadata.icc); + pixelWidth_ = metadata.width; + pixelHeight_ = metadata.height; + setByteOrder(metadata.order); + writeXmpFromPacket(false); + loaded_ = true; + removeExif_ = removeXmp_ = false; + } + uint32_t brand_{bmffType("heic")}; + bool loaded_{}, removeExif_{}, removeXmp_{}; +}; +} // namespace + +bool isHeifType(BasicIo& io, bool advance) { + const auto start = io.tell(); + std::array header{}; + bool matched = io.read(header.data(), 8) == 8 && getULong(header.data() + 4, bigEndian) == bmffType("ftyp"); + uint64_t size = matched ? getULong(header.data(), bigEndian) : 0; + unsigned headerSize = 8; + if (matched && size == 1) { + matched = io.read(header.data() + 8, 8) == 8; + size = matched ? getULongLong(header.data() + 8, bigEndian) : 0; + headerSize = 16; + } + matched = matched && size >= headerSize + 8 && size <= BmffLimits{}.maxBytesRead && size <= io.size() - start && + (size - headerSize) % 4 == 0; + if (matched) { + matched = io.read(header.data(), 8) == 8; + const auto brand = getULong(header.data(), bigEndian); + matched = matched && (brand == bmffType("heic") || brand == bmffType("heix") || brand == bmffType("mif1")); + for (uint64_t offset = headerSize + 8; matched && offset < size; offset += 4) { + matched = io.read(header.data(), 4) == 4; + const auto compatible = getULong(header.data(), bigEndian); + matched = matched && compatible != bmffType("avif") && compatible != bmffType("avis"); + } + } + if (!advance || !matched) + io.seek(static_cast(start), BasicIo::beg); + return matched; +} + +Image::UniquePtr newHeifInstance(std::unique_ptr io, const ImageCtorParams& params) { + auto image = std::make_unique(std::move(io), params); + return image->good() ? std::move(image) : nullptr; +} +} // namespace Exiv2::Internal +#endif diff --git a/src/heifimage_int.hpp b/src/heifimage_int.hpp new file mode 100644 index 0000000000..b97c4a723c --- /dev/null +++ b/src/heifimage_int.hpp @@ -0,0 +1,16 @@ +// SPDX-License-Identifier: GPL-2.0-or-later + +#ifndef HEIFIMAGE_INT_HPP +#define HEIFIMAGE_INT_HPP + +#include "config.h" + +#ifdef EXV_ENABLE_BMFF +#include "image.hpp" + +namespace Exiv2::Internal { +Image::UniquePtr newHeifInstance(std::unique_ptr io, const ImageCtorParams& params); +bool isHeifType(BasicIo& io, bool advance); +} // namespace Exiv2::Internal +#endif +#endif diff --git a/src/image.cpp b/src/image.cpp index c0370e95fb..73e9b2e917 100644 --- a/src/image.cpp +++ b/src/image.cpp @@ -14,6 +14,7 @@ #ifdef EXV_ENABLE_BMFF #include "bmffimage.hpp" +#include "heifimage_int.hpp" #endif // EXV_ENABLE_BMFF #include "cr2image.hpp" @@ -117,6 +118,7 @@ constexpr Registry registry[] = { {ImageType::mkv, newMkvInstance, isMkvType, amRead, amNone, amRead, amNone}, #endif // EXV_ENABLE_VIDEO #ifdef EXV_ENABLE_BMFF + {ImageType::heif, Internal::newHeifInstance, Internal::isHeifType, amReadWrite, amRead, amReadWrite, amNone}, {ImageType::bmff, newBmffInstance, isBmffType, amRead, amRead, amRead, amNone}, #endif // EXV_ENABLE_BMFF }; diff --git a/src/meson.build b/src/meson.build index ef7eadc37c..54941223b0 100644 --- a/src/meson.build +++ b/src/meson.build @@ -1,6 +1,7 @@ base_lib = files( 'basicio.cpp', 'bmffimage.cpp', + 'heifimage_int.cpp', 'bmpimage.cpp', 'convert.cpp', 'cr2image.cpp', From d1f5daf2b4e3f29e4b02834c2c3e672447c4d4a2 Mon Sep 17 00:00:00 2001 From: Vaclav Haisman Date: Fri, 9 Oct 2026 23:53:45 +0200 Subject: [PATCH 05/40] [tests] Cover HEIF writing and physical metadata removal Exercise compact rewriting, public metadata APIs, and CLI operations with synthetic containers and existing HEIF fixtures. Check obsolete-byte absence, repeated edits, retained payloads, large offsets, and failures. Related to #2349. --- .../github/test_issue_2349_heif_write.py | 98 ++ unitTests/test_bmffimage_int.cpp | 903 +++++++++++++++++- 2 files changed, 990 insertions(+), 11 deletions(-) create mode 100644 tests/bugfixes/github/test_issue_2349_heif_write.py diff --git a/tests/bugfixes/github/test_issue_2349_heif_write.py b/tests/bugfixes/github/test_issue_2349_heif_write.py new file mode 100644 index 0000000000..e5f587c826 --- /dev/null +++ b/tests/bugfixes/github/test_issue_2349_heif_write.py @@ -0,0 +1,98 @@ +# -*- coding: utf-8 -*- + +import hashlib +import os +from pathlib import Path +import shutil +import subprocess +import tempfile +import unittest + +import system_tests + + +@unittest.skipUnless(system_tests.BT.verbose_version().get("enable_bmff") == "1", + "requires BMFF support") +class HeifMetadataWriting(unittest.TestCase): + def setUp(self): + self.directory = tempfile.TemporaryDirectory(prefix="exiv2-heif-", dir=system_tests.tmp_path) + self.addCleanup(self.directory.cleanup) + self.root = Path(self.directory.name) + self.exiv2 = str(Path(system_tests.BT.Config.bin_dir) / "exiv2") + + def copy(self, filename): + target = self.root / filename + shutil.copyfile(Path(system_tests.data_path) / filename, target) + return target + + def run_exiv2(self, *args, success=True): + result = subprocess.run([self.exiv2, *map(str, args)], capture_output=True, timeout=30) + if success: + self.assertEqual(result.returncode, 0, result.stderr.decode(errors="replace")) + else: + self.assertNotEqual(result.returncode, 0) + return result.stdout + + def test_extract_clear_and_insert_metadata(self): + target = self.copy("Stonehenge.heic") + self.run_exiv2("-M", "set Exif.Image.Artist HEIF_EXIF_CANARY_627c", + "-M", "set Xmp.dc.source HEIF_XMP_CANARY_691d", target) + self.run_exiv2("-ea", target) + self.assertTrue(target.with_suffix(".exv").exists()) + self.run_exiv2("-de", target) + self.run_exiv2("-dx", target) + data = target.read_bytes() + self.assertNotIn(b"HEIF_EXIF_CANARY_627c", data) + self.assertNotIn(b"HEIF_XMP_CANARY_691d", data) + self.run_exiv2("-ia", target) + self.assertEqual(self.run_exiv2("-K", "Exif.Image.Artist", "-Pv", target), + b"HEIF_EXIF_CANARY_627c\n") + self.assertEqual(self.run_exiv2("-K", "Xmp.dc.source", "-Pv", target), + b"HEIF_XMP_CANARY_691d\n") + self.assertFalse(list(self.root.glob(".exiv2-heif-*"))) + + def test_makernote_values_shrink_and_disappear(self): + target = self.copy("Canon.HIF") + canary = "PRIVATE_CANON_OWNER_44bea7" + self.run_exiv2("-M", "set Exif.Canon.OwnerName " + "x" * 1000 + canary, target) + self.assertIn(canary.encode(), target.read_bytes()) + self.run_exiv2("-M", "set Exif.Canon.OwnerName owner", target) + self.assertNotIn(canary.encode(), target.read_bytes()) + self.run_exiv2("-M", "set Exif.Canon.OwnerName " + canary, target) + self.run_exiv2("-M", "del Exif.Canon.OwnerName", target) + self.assertNotIn(canary.encode(), target.read_bytes()) + self.run_exiv2("-M", "set Exif.Canon.OwnerName " + canary, target) + self.run_exiv2("-M", "del Exif.Photo.MakerNote", target) + self.assertNotIn(canary.encode(), target.read_bytes()) + self.assertFalse(list(self.root.glob(".exiv2-heif-*"))) + + def test_read_only_fields_and_formats_do_not_change_source(self): + for filename, key in [("Canon.HIF", "Exif.Canon.AFNumPoints"), + ("Canon-R6-pruned.CR3", "Exif.Image.Artist"), + ("Reagan.jxl", "Exif.Image.Artist"), + ("avif_exif_xmp.avif", "Exif.Image.Artist")]: + with self.subTest(filename=filename): + target = self.copy(filename) + before = hashlib.sha256(target.read_bytes()).digest() + self.run_exiv2("-M", "set " + key + " 123", target, success=False) + self.assertEqual(hashlib.sha256(target.read_bytes()).digest(), before) + self.assertFalse(list(self.root.glob(".exiv2-heif-*"))) + + @unittest.skipUnless(os.name == "posix" and getattr(os, "geteuid", lambda: 0)() != 0, + "requires an unprivileged POSIX process") + def test_staging_and_destination_open_failures_preserve_source(self): + target = self.copy("Stonehenge.heic") + before = target.read_bytes() + self.root.chmod(0o500) + try: + self.run_exiv2("-M", "set Exif.Image.Artist pending", target, success=False) + self.assertEqual(target.read_bytes(), before) + finally: + self.root.chmod(0o700) + target.chmod(0o400) + try: + self.run_exiv2("-M", "set Exif.Image.Artist pending", target, success=False) + self.assertEqual(target.read_bytes(), before) + finally: + target.chmod(0o600) + self.assertFalse(list(self.root.glob(".exiv2-heif-*"))) diff --git a/unitTests/test_bmffimage_int.cpp b/unitTests/test_bmffimage_int.cpp index 2f7b5ddaa5..d905e340ec 100644 --- a/unitTests/test_bmffimage_int.cpp +++ b/unitTests/test_bmffimage_int.cpp @@ -1,6 +1,7 @@ // SPDX-License-Identifier: GPL-2.0-or-later #include "bmffimage_int.hpp" +#include "bmffwrite_int.hpp" #ifdef EXV_ENABLE_BMFF @@ -8,11 +9,13 @@ #include #include #include +#include #include #include #include #include +#include #include #include #include @@ -72,6 +75,10 @@ void patch(Bytes& bytes, size_t offset, uint64_t value, unsigned width) { } struct Options { + std::optional exifPayload, xmpPayload; + bool secondExif{}, metadataIdat{}; + std::string mimeType{"application/rdf+xml"}; + std::string auxiliaryType; uint32_t brand{bmffType("heic")}; uint32_t idBase{}; uint8_t locationVersion{}; @@ -108,7 +115,12 @@ Bytes fixture(const Options& opt = {}) { integer(fileType, bmffType("mif1"), 4); integer(fileType, opt.brand, 4); auto ftyp = box(bmffType("ftyp"), fileType, opt.extended); - const Bytes payload{'A', 'B', 'e', 'x', 'i', 'f', 'C', 'D', 'x', 'm', 'p'}; + const auto exifPayload = opt.exifPayload.value_or(Bytes{'e', 'x', 'i', 'f'}); + const auto xmpPayload = opt.xmpPayload.value_or(Bytes{'x', 'm', 'p'}); + Bytes payload{'A', 'B'}; + append(payload, exifPayload); + append(payload, Bytes{'C', 'D'}); + append(payload, xmpPayload); const unsigned count = opt.noMetadata ? 1 : 3; const unsigned headerSize = opt.extended ? 16 : 8; @@ -130,10 +142,10 @@ Bytes fixture(const Options& opt = {}) { auto entry = full(opt.entryVersion, i == 1 ? 0 : 1); integer(entry, opt.idBase + i, opt.entryVersion == 2 ? 2 : 4); integer(entry, 0, 2); - integer(entry, i == 1 ? bmffType("hvc1") : i == 2 ? bmffType("Exif") : bmffType("mime"), 4); + integer(entry, i == 1 ? bmffType("hvc1") : i == 2 || opt.secondExif ? bmffType("Exif") : bmffType("mime"), 4); string(entry, i == 1 ? "image" : i == 2 ? "exif" : "xmp"); - if (i == 3) { - string(entry, "application/rdf+xml"); + if (i == 3 && !opt.secondExif) { + string(entry, opt.mimeType); string(entry, opt.encoding); } append(info, box(bmffType("infe"), entry, opt.extended)); @@ -143,9 +155,9 @@ Bytes fixture(const Options& opt = {}) { integer(locations, (opt.baseWidth << 4) | opt.indexWidth, 1); integer(locations, count, opt.locationVersion < 2 ? 2 : 4); for (unsigned i = 1; i <= count; ++i) { - const bool inIdat = opt.idat && i == 1; + const bool inIdat = opt.idat && (i == 1 || opt.metadataIdat); const uint64_t source = inIdat ? 0 : mediaStart; - const uint64_t itemOffset = i == 1 ? 0 : i == 2 ? 2 : 8; + const uint64_t itemOffset = i == 1 ? 0 : i == 2 ? 2 : 4 + exifPayload.size(); integer(locations, opt.idBase + i, opt.locationVersion < 2 ? 2 : 4); if (opt.locationVersion != 0) integer(locations, inIdat ? 1 : 0, 2); @@ -155,10 +167,14 @@ Bytes fixture(const Options& opt = {}) { integer(locations, fragmented ? 2 : 1, 2); integer(locations, 0, opt.indexWidth); integer(locations, (opt.baseWidth == 0 ? source : 0) + itemOffset, opt.offsetWidth); - integer(locations, i == 1 ? (fragmented ? 2 : 8) : i == 2 ? 4 : 3, opt.lengthWidth); + integer(locations, + i == 1 ? (fragmented ? 2 : 4 + exifPayload.size()) + : i == 2 ? exifPayload.size() + : xmpPayload.size(), + opt.lengthWidth); if (fragmented) { integer(locations, 0, opt.indexWidth); - integer(locations, (opt.baseWidth == 0 ? source : 0) + 6, opt.offsetWidth); + integer(locations, (opt.baseWidth == 0 ? source : 0) + 2 + exifPayload.size(), opt.offsetWidth); integer(locations, 2, opt.lengthWidth); } } @@ -185,14 +201,24 @@ Bytes fixture(const Options& opt = {}) { auto value = full(); integer(value, 32, 4); integer(value, 16, 4); - append(properties, box(opt.propertyType, value, opt.extended)); + if (i == 1 && !opt.auxiliaryType.empty()) { + value = full(); + string(value, opt.auxiliaryType); + append(properties, box(bmffType("auxC"), value, opt.extended)); + } else { + append(properties, box(opt.propertyType, value, opt.extended)); + } } auto iprp = box(bmffType("ipco"), properties, opt.extended); auto associations = full(opt.associationVersion, opt.wideProperties ? 1 : 0); - integer(associations, 1, 4); + integer(associations, opt.auxiliaryType.empty() ? 1 : 2, 4); integer(associations, opt.idBase + 1, opt.associationVersion == 0 ? 2 : 4); - integer(associations, 2, 1); + integer(associations, opt.auxiliaryType.empty() ? 2 : 1, 1); integer(associations, (opt.wideProperties ? 0x8000 : 0x80) | 1, opt.wideProperties ? 2 : 1); + if (!opt.auxiliaryType.empty()) { + integer(associations, opt.idBase + 2, opt.associationVersion == 0 ? 2 : 4); + integer(associations, 1, 1); + } integer(associations, opt.propertyCount, opt.wideProperties ? 2 : 1); append(iprp, box(bmffType("ipma"), associations, opt.extended)); append(result, box(bmffType("iprp"), iprp, opt.extended)); @@ -802,4 +828,859 @@ TEST(BmffModel, rejectsNonItemFormatsAndMalformedRegressionFiles) { } } +namespace { + +Bytes rewritten(const Bytes& bytes, const BmffMetadataUpdate& update = {}) { + MemIo input(bytes.data(), bytes.size()); + MemIo output; + rewriteBmff(input, output, parseBmff(input), update); + EXPECT_EQ(input.size(), bytes.size()); + EXPECT_EQ(std::memcmp(input.mmap(), bytes.data(), bytes.size()), 0); + return Bytes(output.mmap(), output.mmap() + output.size()); +} + +bool contains(const Bytes& bytes, std::string_view text) { + return std::search(bytes.begin(), bytes.end(), text.begin(), text.end()) != bytes.end(); +} + +Bytes withOrphanedBytes(Bytes bytes) { + const std::string_view canary = "UNREACHABLE_PRIVATE_METADATA_296bc8"; + const auto media = position(bytes, "mdat"); + bytes.insert(bytes.end(), canary.begin(), canary.end()); + patch(bytes, media, bytes.size() - media, 4); + return bytes; +} + +void rejectsRewrite(const Bytes& bytes, const BmffMetadataUpdate& update = {}) { + MemIo input(bytes.data(), bytes.size()); + MemIo output; + const auto document = parseBmff(input); + EXPECT_THROW(rewriteBmff(input, output, document, update), Error); + EXPECT_EQ(output.size(), 0u); + EXPECT_EQ(input.size(), bytes.size()); + EXPECT_EQ(std::memcmp(input.mmap(), bytes.data(), bytes.size()), 0); +} + +} // namespace + +TEST(BmffRewrite, compactsOrphansAndPaddingWhilePreservingEveryRetainedItem) { + Options opt; + opt.extraMeta = box(bmffType("free"), {'P', 'R', 'I', 'V', 'A', 'T', 'E'}); + opt.extraRoot = box(bmffType("skip"), {'S', 'E', 'C', 'R', 'E', 'T'}); + const auto source = withOrphanedBytes(fixture(opt)); + const auto original = parse(source); + const auto bytes = rewritten(source); + const auto output = parse(bytes); + EXPECT_LT(bytes.size(), source.size()); + EXPECT_FALSE(contains(bytes, "UNREACHABLE_PRIVATE_METADATA_296bc8")); + EXPECT_FALSE(contains(bytes, "PRIVATE")); + EXPECT_FALSE(contains(bytes, "SECRET")); + EXPECT_EQ(output.primaryItem, original.primaryItem); + for (const auto& [id, item] : original.items) + EXPECT_EQ(payload(source, item), payload(bytes, output.items.at(id))); + EXPECT_EQ(rewritten(bytes), bytes); +} + +TEST(BmffRewrite, removesMetadataPayloadsAndTheirReferences) { + const auto source = withOrphanedBytes(fixture()); + BmffMetadataUpdate update; + update.exif = Bytes{}; + update.xmp = Bytes{}; + const auto bytes = rewritten(source, update); + const auto output = parse(bytes); + ASSERT_EQ(output.items.size(), 1u); + EXPECT_TRUE(output.references.empty()); + EXPECT_TRUE(output.metadataItems(bmffType("Exif")).empty()); + EXPECT_TRUE(output.metadataItems(bmffType("mime")).empty()); + EXPECT_EQ(payload(bytes, output.items.at(1)), (Bytes{'A', 'B', 'C', 'D'})); + ASSERT_EQ(output.mediaData.size(), 1u); + EXPECT_EQ(output.mediaData.front().size, 4u); + EXPECT_FALSE(contains(bytes, "exif")); + EXPECT_FALSE(contains(bytes, "xmp")); + EXPECT_FALSE(contains(bytes, "UNREACHABLE_PRIVATE_METADATA_296bc8")); +} + +TEST(BmffRewrite, repacksIdatAndRemovesUnreferencedMediaCopies) { + Options opt; + opt.idat = true; + opt.locationVersion = 1; + auto source = fixture(opt); + const auto loc = position(source, "iloc"); + patch(source, loc + 42, 1, 2); // Exif construction method. + patch(source, loc + 48, 2, 4); // Exif offset into idat. + patch(source, loc + 58, 1, 2); // XMP construction method. + patch(source, loc + 64, 8, 4); // XMP offset into idat. + BmffMetadataUpdate update; + update.exif = Bytes{}; + update.xmp = Bytes{}; + const auto bytes = rewritten(source, update); + const auto output = parse(bytes); + ASSERT_TRUE(output.itemData.has_value()); + EXPECT_EQ(output.itemData->size, 4u); + EXPECT_TRUE(output.mediaData.empty()); + const auto& image = output.items.at(1); + EXPECT_EQ(image.location.constructionMethod, 1u); + EXPECT_EQ(image.location.extents.at(0).offset, 0u); + EXPECT_EQ(image.location.extents.at(1).offset, 2u); + EXPECT_EQ(payload(bytes, image), (Bytes{'A', 'B', 'C', 'D'})); + EXPECT_FALSE(contains(bytes, "exif")); + EXPECT_FALSE(contains(bytes, "xmp")); +} + +TEST(BmffRewrite, insertsIntoMetadataFreeFilesAndPreservesUnassociatedItems) { + Options opt; + opt.noMetadata = true; + BmffMetadataUpdate update; + update.exif = Bytes{'n', 'e', 'w', 'e', 'x', 'i', 'f'}; + update.xmp = Bytes{'n', 'e', 'w', 'x', 'm', 'p'}; + auto bytes = rewritten(fixture(opt), update); + auto document = parse(bytes); + ASSERT_EQ(document.items.size(), 3u); + ASSERT_EQ(document.metadataItems(bmffType("Exif")).size(), 1u); + ASSERT_EQ(document.metadataItems(bmffType("mime")).size(), 1u); + EXPECT_EQ(payload(bytes, document.items.at(document.metadataItems(bmffType("Exif")).front())), *update.exif); + EXPECT_EQ(payload(bytes, document.items.at(document.metadataItems(bmffType("mime")).front())), *update.xmp); + opt.noMetadata = false; + opt.noReferences = true; + bytes = rewritten(fixture(opt), update); + document = parse(bytes); + EXPECT_EQ(document.items.size(), 5u); + EXPECT_EQ(payload(bytes, document.items.at(2)), (Bytes{'e', 'x', 'i', 'f'})); + EXPECT_EQ(payload(bytes, document.items.at(3)), (Bytes{'x', 'm', 'p'})); +} + +TEST(BmffRewrite, replacesGrowsAndShrinksWithoutRetainingEarlierPayloads) { + const auto original = fixture(); + auto current = original; + size_t smallSize = 0; + for (unsigned iteration = 0; iteration < 8; ++iteration) { + const auto previous = "PRIVATE_OLD_VALUE_" + std::to_string(iteration); + BmffMetadataUpdate update; + update.exif = Bytes(70000, 'q'); + update.exif->insert(update.exif->end(), previous.begin(), previous.end()); + current = rewritten(current, update); + EXPECT_TRUE(contains(current, previous)); + update.exif = Bytes{'n', 'e', 'w'}; + current = rewritten(current, update); + EXPECT_FALSE(contains(current, previous)); + const auto output = parse(current); + EXPECT_EQ(payload(current, output.items.at(1)), (Bytes{'A', 'B', 'C', 'D'})); + if (iteration == 0) + smallSize = current.size(); + else + EXPECT_EQ(current.size(), smallSize); + } +} + +TEST(BmffRewrite, rejectsSharedMetadataAndOverlappingRetainedDataBeforeWriting) { + Options opt; + opt.sharedMetadata = true; + BmffMetadataUpdate update; + update.exif = Bytes{}; + rejectsRewrite(fixture(opt), update); + update.exif = Bytes{'n', 'e', 'w'}; + rejectsRewrite(fixture(opt), update); + auto source = fixture(); + const auto loc = position(source, "iloc"); + patch(source, loc + 44, position(source, "mdat") + 8, 4); // Exif overlaps first image extent. + rejectsRewrite(source, update); + // Unmodified sharing is representable and compacted without duplicating bytes. + const auto bytes = rewritten(source); + EXPECT_EQ(payload(bytes, parse(bytes).items.at(1)), (Bytes{'A', 'B', 'C', 'D'})); +} + +TEST(BmffRewrite, handlesWideIdsFieldsExtendedAndTerminalHeaders) { + Options opt; + opt.idBase = 65536; + opt.locationVersion = 2; + opt.infoVersion = 2; + opt.entryVersion = 3; + opt.primaryVersion = 1; + opt.referenceVersion = 1; + opt.associationVersion = 1; + opt.offsetWidth = opt.lengthWidth = opt.baseWidth = opt.indexWidth = 8; + opt.extended = true; + opt.wideProperties = true; + BmffMetadataUpdate update; + update.exif = Bytes{'r', 'e', 'p', 'l', 'a', 'c', 'e'}; + auto bytes = rewritten(fixture(opt), update); + auto output = parse(bytes); + EXPECT_EQ(output.primaryItem, 65537u); + EXPECT_EQ(output.locationFormat.version, 2u); + EXPECT_EQ(output.items.at(65537).location.baseOffset, 0u); + EXPECT_EQ(output.locationFormat.indexSize, 8u); + EXPECT_EQ(payload(bytes, output.items.at(65537)), (Bytes{'A', 'B', 'C', 'D'})); + opt = Options{}; + opt.terminal = true; + bytes = rewritten(fixture(opt), update); + output = parse(bytes); + EXPECT_FALSE(output.boxes.back().extendsToEnd); + EXPECT_EQ(output.mediaData.size(), 2u); +} + +TEST(BmffRewrite, reusesAvailableIdWhenLargestIdIsOccupied) { + Options opt; + opt.noMetadata = true; + opt.idBase = std::numeric_limits::max() - 1; + opt.locationVersion = 2; + opt.entryVersion = 3; + opt.primaryVersion = 1; + opt.associationVersion = 1; + BmffMetadataUpdate update; + update.exif = Bytes{'n', 'e', 'w'}; + const auto bytes = rewritten(fixture(opt), update); + const auto output = parse(bytes); + EXPECT_EQ(output.primaryItem, std::numeric_limits::max()); + EXPECT_EQ(output.metadataItems(bmffType("Exif")), (std::vector{1})); +} + +TEST(BmffRewrite, keepsIndexedPaddingSlotsButDiscardsTheirBodies) { + Options opt; + opt.propertyType = bmffType("free"); + const auto bytes = rewritten(fixture(opt)); + const auto output = parse(bytes); + ASSERT_EQ(output.properties.size(), 2u); + EXPECT_EQ(output.properties.front().payload().size, 0u); + EXPECT_EQ(output.associations.front().properties.back().index, 2u); +} + +TEST(BmffRewrite, propagatesShortWritesAndReadFailuresWithoutMutatingSource) { + class ShortOutput : public MemIo { + public: + using MemIo::write; + size_t remaining{70}; + size_t write(const byte* bytes, size_t count) override { + const auto n = std::min(count, remaining); + remaining -= n; + return MemIo::write(bytes, n); + } + } output; + const auto source = fixture(); + MemIo input(source.data(), source.size()); + const auto document = parseBmff(input); + EXPECT_THROW(rewriteBmff(input, output, document), Error); + EXPECT_EQ(input.size(), source.size()); + EXPECT_EQ(std::memcmp(input.mmap(), source.data(), source.size()), 0); + class ShortInput : public MemIo { + public: + using MemIo::read; + explicit ShortInput(const Bytes& bytes) : MemIo(bytes.data(), bytes.size()) { + } + size_t read(byte*, size_t) override { + return 0; + } + } failing(source); + MemIo other; + EXPECT_THROW(rewriteBmff(failing, other, document), Error); + EXPECT_EQ(std::memcmp(failing.mmap(), source.data(), source.size()), 0); +} + +TEST(BmffRewrite, detectsCorruptedPreparedOutput) { + class CorruptOutput : public MemIo { + public: + using MemIo::write; + size_t write(const byte* bytes, size_t count) override { + Bytes data(bytes, bytes + count); + if (contains(data, "ABexifCDxmp")) + data.back() ^= 1; + return MemIo::write(data.data(), data.size()); + } + } output; + const auto source = fixture(); + MemIo input(source.data(), source.size()); + EXPECT_THROW(rewriteBmff(input, output, parseBmff(input)), Error); + EXPECT_EQ(std::memcmp(input.mmap(), source.data(), source.size()), 0); +} + +TEST(BmffRewrite, promotesOutputOffsetsAndStreamsLargePayloadsWithBoundedIo) { + if (sizeof(size_t) < 8) + GTEST_SKIP() << "BasicIo size() cannot represent this input on a 32-bit host"; + class SparseIo : public MemIo { + public: + using MemIo::read; + using MemIo::write; + std::map segments; + uint64_t length{}; + uint64_t position{}; + size_t largestWrite{}; + size_t writeCalls{}; + + size_t size() const override { + return static_cast(length); + } + size_t tell() const override { + return static_cast(position); + } + int seek(int64_t offset, Position origin) override { + if (origin != beg || offset < 0 || static_cast(offset) > length) + return 1; + position = static_cast(offset); + return 0; + } + size_t read(byte* output, size_t count) override { + if (position > length || count > length - position) + return 0; + std::memset(output, 0, count); + auto it = segments.upper_bound(position); + if (it != segments.begin()) + --it; + for (; it != segments.end() && it->first < position + count; ++it) { + const auto start = std::max(position, it->first); + const auto end = std::min(position + count, it->first + it->second.size()); + if (start < end) + std::memcpy(output + start - position, it->second.data() + start - it->first, end - start); + } + position += count; + return count; + } + size_t write(const byte* data, size_t count) override { + largestWrite = std::max(largestWrite, count); + ++writeCalls; + // Only the large zero-filled media payload uses full 64 KiB chunks here. + // Store all structural and short payload writes for the output reparse. + if (count != 64 * 1024) + segments.emplace(position, Bytes(data, data + count)); + else if (data[0] != 0 || data[count - 1] != 0) + throw std::runtime_error("unexpected nonzero virtual media"); + position += count; + length = std::max(length, position); + return count; + } + } input, output; + Options opt; + opt.noMetadata = true; + opt.offsetWidth = 0; + opt.lengthWidth = opt.baseWidth = 8; + auto prefix = fixture(opt); + const auto media = position(prefix, "mdat"); + prefix.resize(media); + const uint64_t imageSize = (uint64_t{5} << 30) + 7; + patch(prefix, position(prefix, "iloc") + 20, media + 16, 8); + patch(prefix, position(prefix, "iloc") + 30, imageSize, 8); + integer(prefix, 1, 4); + integer(prefix, bmffType("mdat"), 4); + integer(prefix, imageSize + 16, 8); + input.length = prefix.size() + imageSize; + input.segments.emplace(0, prefix); + const auto original = parseBmff(input); + BmffMetadataUpdate update; + update.exif = Bytes{'n', 'e', 'w', '6', '4'}; + rewriteBmff(input, output, original, update); + const auto document = parseBmff(output); + EXPECT_EQ(document.locationFormat.offsetSize, 8u); + EXPECT_EQ(document.locationFormat.lengthSize, 8u); + EXPECT_EQ(document.items.at(1).location.dataSize, imageSize); + const auto exif = document.metadataItems(bmffType("Exif")).front(); + EXPECT_GT(document.items.at(exif).location.extents.front().offset, std::numeric_limits::max()); + EXPECT_EQ(readBmffItem(output, document.items.at(exif)), *update.exif); + EXPECT_LE(output.largestWrite, 64u * 1024); + EXPECT_EQ(input.writeCalls, 0u); + EXPECT_LT(output.segments.size(), 100u); + + // A source that fits the seek contract can still overflow after metadata growth. + const auto maximum = static_cast(std::numeric_limits::max()); + patch(prefix, position(prefix, "iloc") + 30, maximum - prefix.size(), 8); + patch(prefix, media + 8, maximum - media, 8); + input.segments.at(0) = prefix; + input.length = maximum; + const auto tooLarge = parseBmff(input); + SparseIo untouched; + EXPECT_THROW(rewriteBmff(input, untouched, tooLarge, update), Error); + EXPECT_EQ(untouched.writeCalls, 0u); + EXPECT_EQ(input.writeCalls, 0u); +} + +TEST(BmffRewrite, rejectsUnsupportedLayoutsAndNonemptySinksBeforeWriting) { + Options opt; + opt.extraMeta = box(bmffType("zzzz"), {1, 2, 3}); + rejectsRewrite(fixture(opt)); + opt.extraMeta.clear(); + opt.brand = bmffType("avif"); + rejectsRewrite(fixture(opt)); + auto source = fixture(); + MemIo input(source.data(), source.size()); + MemIo output(source.data(), source.size()); + const auto document = parseBmff(input); + EXPECT_THROW(rewriteBmff(input, input, document), Error); + EXPECT_THROW(rewriteBmff(input, output, document), Error); + EXPECT_EQ(std::memcmp(input.mmap(), source.data(), source.size()), 0); + EXPECT_EQ(std::memcmp(output.mmap(), source.data(), source.size()), 0); +} + +TEST_P(BmffCorpus, preservesOrRejectsCorpusAccordingToWriteEnvelope) { + const auto& expected = GetParam(); + FileIo input(std::string(TESTDATA_PATH) + "/" + expected.file); + ASSERT_EQ(input.open("rb"), 0); + const auto original = parseBmff(input); + MemIo output; + if (!expected.heif) { + EXPECT_THROW(rewriteBmff(input, output, original), Error); + EXPECT_EQ(output.size(), 0u); + return; + } + rewriteBmff(input, output, original); + const auto document = parseBmff(output); + for (const auto& [id, item] : original.items) + EXPECT_EQ(readBmffItem(input, item), readBmffItem(output, document.items.at(id))) << id; + BmffMetadataUpdate update; + update.exif = Bytes{}; + update.xmp = Bytes{}; + MemIo stripped; + rewriteBmff(input, stripped, original, update); + const auto cleaned = parseBmff(stripped); + EXPECT_TRUE(cleaned.metadataItems(bmffType("Exif")).empty()); + EXPECT_TRUE(cleaned.metadataItems(bmffType("mime")).empty()); + for (const auto& [id, item] : cleaned.items) + EXPECT_EQ(readBmffItem(input, original.items.at(id)), readBmffItem(stripped, item)) << id; +} + +namespace { +Bytes tiffItem(ExifData exif, const XmpData& xmp = {}, ByteOrder order = littleEndian) { + MemIo output; + TiffParser::encode(output, nullptr, 0, order, exif, IptcData{}, xmp); + Bytes bytes(4, 0); + bytes.insert(bytes.end(), output.mmap(), output.mmap() + output.size()); + return bytes; +} + +Bytes heifWithMetadata(const ExifData& exif = {}, std::string_view xmp = {}, ByteOrder order = littleEndian) { + Options options; + options.noMetadata = true; + BmffMetadataUpdate update; + if (!exif.empty()) + update.exif = tiffItem(exif, {}, order); + if (!xmp.empty()) + update.xmp = Bytes(xmp.begin(), xmp.end()); + return rewritten(fixture(options), update); +} + +Image::UniquePtr openHeif(const Bytes& bytes) { + auto owned = std::make_unique(); + owned->write(bytes.data(), bytes.size()); + auto image = ImageFactory::open(std::move(owned)); + if (image->imageType() != ImageType::heif) + throw std::runtime_error("HEIF was not classified separately"); + image->readMetadata(); + return image; +} + +Bytes imageBytes(Image& image) { + auto& io = image.io(); + io.open(); + auto data = io.read(io.size()); + return Bytes(data.c_data(), data.c_data() + data.size()); +} + +} // namespace + +TEST(HeifImage, addsGrowsShrinksDeletesAndPreservesEncodedImage) { + auto image = openHeif(heifWithMetadata()); + EXPECT_EQ(image->checkMode(mdExif), amReadWrite); + EXPECT_EQ(image->checkMode(mdXmp), amReadWrite); + EXPECT_EQ(image->checkMode(mdIptc), amRead); + size_t smallSize = 0; + for (unsigned cycle = 0; cycle < 4; ++cycle) { + const auto canary = "PRIVATE_HEIF_DESCRIPTION_" + std::to_string(cycle); + image->exifData()["Exif.Image.ImageDescription"] = std::string(70000, 'v') + canary; + image->xmpData()["Xmp.dc.source"] = "Příliš žluťoučký kůň — " + canary; + ASSERT_NO_THROW(image->writeMetadata()); + auto large = imageBytes(*image); + EXPECT_TRUE(contains(large, canary)); + image->exifData()["Exif.Image.ImageDescription"] = "short"; + image->xmpData()["Xmp.dc.source"] = "short"; + ASSERT_NO_THROW(image->writeMetadata()); + auto small = imageBytes(*image); + EXPECT_FALSE(contains(small, canary)); + auto parsed = parse(small); + EXPECT_EQ(payload(small, parsed.items.at(parsed.primaryItem)), (Bytes{'A', 'B', 'C', 'D'})); + if (cycle != 0) { + EXPECT_EQ(small.size(), smallSize); + } + smallSize = small.size(); + } + image->clearMetadata(); + ASSERT_NO_THROW(image->writeMetadata()); + auto clean = imageBytes(*image); + EXPECT_FALSE(contains(clean, "short")); + EXPECT_TRUE(parse(clean).metadataItems(bmffType("Exif")).empty()); + EXPECT_TRUE(parse(clean).metadataItems(bmffType("mime")).empty()); +} + +TEST(HeifImage, preservesNoOpAndCleansExplicitEmptyRemoval) { + ExifData exif; + exif["Exif.Image.Artist"] = "original"; + auto bytes = heifWithMetadata(exif); + auto image = openHeif(bytes); + image->writeMetadata(); + EXPECT_EQ(imageBytes(*image), bytes); + bytes = withOrphanedBytes(heifWithMetadata()); + image = openHeif(bytes); + image->clearExifData(); + image->clearXmpPacket(); + image->writeMetadata(); + EXPECT_FALSE(contains(imageBytes(*image), "UNREACHABLE_PRIVATE_METADATA_296bc8")); +} + +TEST(HeifImage, removesDeletedTagsAndOriginalTiffSlack) { + ExifData exif; + exif["Exif.Image.Artist"] = "KEEP_ARTIST"; + exif["Exif.Photo.UserComment"] = "charset=Ascii PRIVATE_REMOVED_USER_COMMENT_841bb0"; + auto item = tiffItem(exif, {}, bigEndian); + const std::string slack = "PRIVATE_UNUSED_TIFF_STORAGE_2223f1"; + item.insert(item.end(), slack.begin(), slack.end()); + BmffMetadataUpdate update; + update.exif = item; + auto image = openHeif(rewritten(heifWithMetadata(), update)); + image->exifData().erase(image->exifData().findKey(ExifKey("Exif.Photo.UserComment"))); + image->writeMetadata(); + auto bytes = imageBytes(*image); + EXPECT_FALSE(contains(bytes, slack)); + EXPECT_FALSE(contains(bytes, "PRIVATE_REMOVED_USER_COMMENT_841bb0")); + EXPECT_TRUE(contains(bytes, "KEEP_ARTIST")); + auto doc = parse(bytes); + auto tiff = payload(bytes, doc.items.at(doc.metadataItems(bmffType("Exif")).front())); + ASSERT_GT(tiff.size(), 8u); + EXPECT_EQ(tiff[4], 'M'); + EXPECT_EQ(tiff[5], 'M'); +} + +TEST(HeifImage, clearsEmbeddedXmpAndPreservesItWhenOnlyExifIsRemoved) { + ExifData exif; + exif["Exif.Image.Artist"] = "keep artist"; + XmpData xmp; + xmp["Xmp.dc.source"] = "PRIVATE_EMBEDDED_XMP_350597"; + BmffMetadataUpdate update; + update.exif = tiffItem(exif, xmp); + auto bytes = rewritten(heifWithMetadata(), update); + auto image = openHeif(bytes); + ASSERT_FALSE(image->xmpData().empty()); + image->clearXmpPacket(); + image->writeMetadata(); + auto cleaned = imageBytes(*image); + EXPECT_FALSE(contains(cleaned, "PRIVATE_EMBEDDED_XMP_350597")); + EXPECT_TRUE(contains(cleaned, "keep artist")); + image = openHeif(bytes); + auto xml = image->exifData().findKey(ExifKey("Exif.Image.XMLPacket")); + ASSERT_NE(xml, image->exifData().end()); + image->exifData().erase(xml); + image->writeMetadata(); + EXPECT_FALSE(contains(imageBytes(*image), "PRIVATE_EMBEDDED_XMP_350597")); + image = openHeif(bytes); + image->clearExifData(); + image->writeMetadata(); + EXPECT_EQ(image->xmpData()["Xmp.dc.source"].toString(), "PRIVATE_EMBEDDED_XMP_350597"); + EXPECT_TRUE(image->exifData().empty()); +} + +TEST(HeifImage, usesRawXmpPacketsSetMetadataAndRejectsUnsupportedCategories) { + auto source = openHeif(heifWithMetadata()); + XmpData xmp; + xmp["Xmp.dc.source"] = "RAW_XMP_říční"; + std::string packet; + ASSERT_EQ(XmpParser::encode(packet, xmp), 0); + source->setXmpPacket(packet); + source->exifData()["Exif.Image.Artist"] = "copied"; + source->writeMetadata(); + auto bytes = imageBytes(*source); + auto doc = parse(bytes); + EXPECT_EQ(payload(bytes, doc.items.at(doc.metadataItems(bmffType("mime")).front())), + Bytes(packet.begin(), packet.end())); + auto target = openHeif(heifWithMetadata()); + target->setMetadata(*source); + target->writeMetadata(); + EXPECT_EQ(target->exifData()["Exif.Image.Artist"].toString(), "copied"); + EXPECT_EQ(target->xmpData()["Xmp.dc.source"].toString(), "RAW_XMP_říční"); + EXPECT_THROW(target->setIptcData(IptcData{}), Error); + EXPECT_THROW(target->setComment("comment"), Error); + target->clearXmpData(); + target->writeMetadata(); + EXPECT_TRUE(target->xmpData().empty()); + EXPECT_FALSE(contains(imageBytes(*target), "RAW_XMP")); +} + +TEST(HeifImage, failsBeforeTransferAndDoesNotOverwritePendingEdits) { + class TransferIo : public MemIo { + public: + explicit TransferIo(const Bytes& bytes) : MemIo(bytes.data(), bytes.size()) { + } + void transfer(BasicIo&) override { + transferred = true; + throw Error(ErrorCode::kerImageWriteFailed); + } + bool transferred{}; + }; + auto bytes = heifWithMetadata(); + auto source = std::make_unique(bytes); + auto* observer = source.get(); + auto image = ImageFactory::open(std::move(source)); + image->readMetadata(); + image->exifData()["Exif.Image.Artist"] = "pending"; + EXPECT_THROW(image->writeMetadata(), Error); + EXPECT_TRUE(observer->transferred); + EXPECT_EQ(imageBytes(*image), bytes); + EXPECT_EQ(image->exifData()["Exif.Image.Artist"].toString(), "pending"); + append(bytes, box(bmffType("moov"), {})); + source = std::make_unique(bytes); + observer = source.get(); + image = ImageFactory::open(std::move(source)); + image->exifData()["Exif.Image.Artist"] = "pending"; + EXPECT_THROW(image->writeMetadata(), Error); + EXPECT_FALSE(observer->transferred); + EXPECT_EQ(imageBytes(*image), bytes); +} + +TEST_P(BmffCorpus, editsThroughPublicApiAndKeepsOtherItems) { + const auto& expected = GetParam(); + FileIo original(std::string(TESTDATA_PATH) + "/" + expected.file); + ASSERT_EQ(original.open(), 0); + auto data = original.read(original.size()); + Bytes bytes(data.c_data(), data.c_data() + data.size()); + auto image = ImageFactory::open(bytes.data(), bytes.size()); + if (!expected.heif) { + EXPECT_EQ(image->imageType(), ImageType::bmff); + EXPECT_THROW(image->writeMetadata(), Error); + return; + } + ASSERT_EQ(image->imageType(), ImageType::heif); + image->readMetadata(); + image->exifData()["Exif.Image.ImageDescription"] = "PUBLIC_API_CANARY_6f9326"; + image->xmpData()["Xmp.dc.source"] = "PUBLIC_API_CANARY_6f9326"; + ASSERT_NO_THROW(image->writeMetadata()); + auto output = imageBytes(*image); + auto before = parse(bytes), after = parse(output); + auto exif = before.metadataItems(bmffType("Exif")); + auto xmp = before.metadataItems(bmffType("mime")); + for (const auto& [id, item] : before.items) { + if (std::find(exif.begin(), exif.end(), id) != exif.end() || std::find(xmp.begin(), xmp.end(), id) != xmp.end()) + continue; + ASSERT_TRUE(after.items.contains(id)); + EXPECT_EQ(payload(bytes, item), payload(output, after.items.at(id))); + } + auto first = output; + image->writeMetadata(); + EXPECT_EQ(imageBytes(*image), first); + const auto tagCount = image->exifData().count(); + size_t steadySize = 0; + for (unsigned cycle = 0; cycle != 3; ++cycle) { + image->exifData()["Exif.Image.ImageDescription"] = "PUBLIC_API_CANARY_6f9327"; + image->writeMetadata(); + image->exifData()["Exif.Image.ImageDescription"] = "PUBLIC_API_CANARY_6f9326"; + image->writeMetadata(); + EXPECT_EQ(image->exifData().count(), tagCount); + const auto currentSize = imageBytes(*image).size(); + // Editing Exif alone may separate it from retained XMP into one more mdat. + EXPECT_LE(currentSize, first.size() + 8); + if (cycle != 0) { + EXPECT_EQ(currentSize, steadySize); + } + steadySize = currentSize; + } + image->clearMetadata(); + ASSERT_NO_THROW(image->writeMetadata()); + EXPECT_FALSE(contains(imageBytes(*image), "PUBLIC_API_CANARY_6f9326")); +} + +TEST(HeifImage, readsAndReplacesMultiplePrimaryMetadataItems) { + ExifData first, second; + first["Exif.Image.Artist"] = "PRIVATE_FIRST_PRIMARY_450a"; + first["Exif.Photo.DateTimeOriginal"] = "2001:02:03 04:05:06"; + second["Exif.Image.Artist"] = "PRIVATE_SECOND_PRIMARY_917a"; + Options options; + options.exifPayload = tiffItem(first); + options.xmpPayload = tiffItem(second); + options.secondExif = true; + auto source = fixture(options); + auto image = openHeif(source); + EXPECT_EQ(image->exifData()["Exif.Image.Artist"].toString(), "PRIVATE_SECOND_PRIMARY_917a"); + EXPECT_EQ(image->exifData()["Exif.Photo.DateTimeOriginal"].toString(), "2001:02:03 04:05:06"); + image->exifData()["Exif.Image.Artist"] = "replacement"; + image->writeMetadata(); + auto bytes = imageBytes(*image); + EXPECT_EQ(parse(bytes).metadataItems(bmffType("Exif")).size(), 1u); + EXPECT_FALSE(contains(bytes, "PRIVATE_FIRST_PRIMARY_450a")); + EXPECT_FALSE(contains(bytes, "PRIVATE_SECOND_PRIMARY_917a")); + options.sharedMetadata = true; + source = fixture(options); + image = openHeif(source); + image->clearExifData(); + EXPECT_THROW(image->writeMetadata(), Error); + EXPECT_EQ(imageBytes(*image), source); +} + +TEST(HeifImage, updatesIdatMetadataAndWideItemIds) { + ExifData exif; + exif["Exif.Image.Artist"] = "PRIVATE_IDAT_METADATA_7703"; + Options options; + options.idat = options.metadataIdat = true; + options.exifPayload = tiffItem(exif); + options.xmpPayload = tiffItem(exif); + options.secondExif = true; + options.idBase = 70000; + options.locationVersion = 2; + options.entryVersion = 3; + options.primaryVersion = options.referenceVersion = options.associationVersion = 1; + auto image = openHeif(fixture(options)); + image->exifData()["Exif.Image.Artist"] = "new"; + image->writeMetadata(); + auto bytes = imageBytes(*image); + auto document = parse(bytes); + EXPECT_FALSE(contains(bytes, "PRIVATE_IDAT_METADATA_7703")); + EXPECT_EQ(document.primaryItem, 70001u); + EXPECT_EQ(payload(bytes, document.items.at(70001)), (Bytes{'A', 'B', 'C', 'D'})); + EXPECT_EQ(document.items.at(70001).location.constructionMethod, 1u); +} + +TEST(HeifImage, preservesIndependentMetadataAndRejectsGenericAvifBrand) { + ExifData exif; + exif["Exif.Image.Artist"] = "INDEPENDENT_METADATA_f880"; + Options options; + options.exifPayload = tiffItem(exif); + options.xmpPayload = tiffItem(exif); + options.secondExif = true; + options.noReferences = true; + auto bytes = fixture(options); + auto image = openHeif(bytes); + EXPECT_TRUE(image->exifData().empty()); + image->clearExifData(); + image->writeMetadata(); + auto result = imageBytes(*image); + EXPECT_EQ(payload(bytes, parse(bytes).items.at(2)), payload(result, parse(result).items.at(2))); + image->exifData()["Exif.Image.Artist"] = "primary metadata"; + image->writeMetadata(); + result = imageBytes(*image); + EXPECT_TRUE(contains(result, "INDEPENDENT_METADATA_f880")); + EXPECT_EQ(parse(result).metadataItems(bmffType("Exif")).size(), 1u); + bytes = heifWithMetadata(); + patch(bytes, 8, bmffType("mif1"), 4); + patch(bytes, 16, bmffType("avif"), 4); + image = ImageFactory::open(bytes.data(), bytes.size()); + EXPECT_EQ(image->imageType(), ImageType::bmff); + EXPECT_EQ(image->checkMode(mdExif), amRead); + EXPECT_THROW(image->writeMetadata(), Error); +} + +TEST(HeifImage, preservesEmbeddedIptcAndThumbnailDataOnExifEdits) { + ExifData exif; + exif["Exif.Image.Artist"] = "original"; + const Bytes thumbnail{0xff, 0xd8, 1, 2, 3, 4, 0xff, 0xd9}; + ExifThumb(exif).setJpegThumbnail(thumbnail.data(), thumbnail.size()); + IptcData iptc; + iptc["Iptc.Application2.Caption"] = "retained IPTC"; + MemIo output; + TiffParser::encode(output, nullptr, 0, littleEndian, exif, iptc, XmpData{}); + BmffMetadataUpdate update; + update.exif = Bytes(4, 0); + update.exif->insert(update.exif->end(), output.mmap(), output.mmap() + output.size()); + auto image = openHeif(rewritten(heifWithMetadata(), update)); + image->exifData()["Exif.Image.Artist"] = "new"; + image->writeMetadata(); + EXPECT_EQ(image->iptcData()["Iptc.Application2.Caption"].toString(), "retained IPTC"); + auto copied = ExifThumbC(image->exifData()).copy(); + EXPECT_EQ(Bytes(copied.c_data(), copied.c_data() + copied.size()), thumbnail); + auto before = imageBytes(*image); + image->iptcData()["Iptc.Application2.Caption"] = "unsupported"; + EXPECT_THROW(image->writeMetadata(), Error); + EXPECT_EQ(imageBytes(*image), before); +} + +TEST(HeifImage, clearsOrphanedEmbeddedXmpAndPrintsWithoutDiscardingEdits) { + ExifData exif; + exif["Exif.Image.Artist"] = "original"; + auto item = tiffItem(exif); + const std::string canary = "PRIVATE_ORPHANED_TIFF_XMP_9c1f"; + item.insert(item.end(), canary.begin(), canary.end()); + BmffMetadataUpdate update; + update.exif = item; + auto image = openHeif(rewritten(heifWithMetadata(), update)); + image->exifData()["Exif.Image.Artist"] = "pending"; + std::ostringstream trace; + EXPECT_NO_THROW(image->printStructure(trace, kpsBasic, 0)); + EXPECT_EQ(image->exifData()["Exif.Image.Artist"].toString(), "pending"); + image->clearXmpPacket(); + image->writeMetadata(); + EXPECT_FALSE(contains(imageBytes(*image), canary)); +} + +TEST(HeifImage, rejectsAmbiguousPrimaryXmpEncodingsBeforeTransfer) { + ExifData exif; + exif["Exif.Image.Artist"] = "original"; + Options options; + options.exifPayload = tiffItem(exif); + const std::string packet = + ""; + options.xmpPayload = Bytes(packet.begin(), packet.end()); + for (const auto* type : {"APPLICATION/RDF+XML", "application/rdf+xml; charset=utf-8", " application/rdf+xml "}) { + options.mimeType = type; + auto bytes = fixture(options); + auto image = ImageFactory::open(bytes.data(), bytes.size()); + image->clearXmpData(); + EXPECT_THROW(image->writeMetadata(), Error); + EXPECT_EQ(imageBytes(*image), bytes); + } +} + +TEST(HeifImage, removesUnicodeUserCommentsInBothTiffByteOrders) { + const std::string canary = "PRIVATE_UNICODE_COMMENT_7ead"; + Bytes big, little; + for (unsigned char c : canary) { + integer(big, c, 2); + little.push_back(c); + little.push_back(0); + } + auto has = [](const Bytes& data, const Bytes& needle) { + return std::search(data.begin(), data.end(), needle.begin(), needle.end()) != data.end(); + }; + for (const auto order : {littleEndian, bigEndian}) { + ExifData exif; + exif["Exif.Image.Artist"] = "retained"; + exif["Exif.Photo.UserComment"] = "charset=Unicode " + canary + " žluťoučký"; + auto bytes = heifWithMetadata(exif, {}, order); + ASSERT_TRUE(has(bytes, big) || has(bytes, little)); + auto image = openHeif(bytes); + image->exifData().erase(image->exifData().findKey(ExifKey("Exif.Photo.UserComment"))); + image->writeMetadata(); + bytes = imageBytes(*image); + EXPECT_FALSE(has(bytes, big)); + EXPECT_FALSE(has(bytes, little)); + } +} + +TEST(HeifImage, preservesAuxiliaryAndThumbnailGraphsAsOpaqueImageData) { + // A structural fixture: compressed-image decoding is intentionally outside + // this test. The writer must preserve every image item and relationship. + for (const auto* uri : {"urn:mpeg:hevc:2015:auxid:1", "urn:mpeg:hevc:2015:auxid:2"}) { + Options options; + options.secondExif = true; + options.auxiliaryType = uri; + options.exifPayload = Bytes{'A', 'L', 'P', 'H', 'A'}; + options.xmpPayload = Bytes{'T', 'H', 'U', 'M', 'B'}; + auto bytes = fixture(options); + auto before = parse(bytes); + for (const auto id : {2, 3}) { + const auto& info = before.items.at(id).info; + patch(bytes, info.box.offset + 16, bmffType("hvc1"), 4); + } + for (const auto& ref : before.references) + patch(bytes, ref.box.offset + 4, ref.from == 2 ? bmffType("auxl") : bmffType("thmb"), 4); + before = parse(bytes); + auto image = openHeif(bytes); + EXPECT_TRUE(image->exifData().empty()); + image->exifData()["Exif.Image.Artist"] = "new metadata"; + image->writeMetadata(); + auto output = imageBytes(*image); + const auto after = parse(output); + for (const auto& [id, item] : before.items) + EXPECT_EQ(payload(bytes, item), payload(output, after.items.at(id))); + ASSERT_EQ(after.references.size(), before.references.size() + 1); + for (size_t i = 0; i != before.references.size(); ++i) { + EXPECT_EQ(after.references[i].type, before.references[i].type); + EXPECT_EQ(after.references[i].from, before.references[i].from); + EXPECT_EQ(after.references[i].to, before.references[i].to); + } + EXPECT_EQ(after.associations.size(), before.associations.size()); + EXPECT_TRUE(contains(output, uri)); + } +} + #endif // EXV_ENABLE_BMFF From ecfbe155644a130425c3f4ca79704b62d2e9a3ea Mon Sep 17 00:00:00 2001 From: Vaclav Haisman Date: Sat, 10 Oct 2026 00:37:20 +0200 Subject: [PATCH 06/40] [heif] Preserve raw XMP when the toolkit is disabled Keep MIME and embedded XMP packets available during Exif edits without the XMP toolkit. Reject structured edits and ambiguous packet merges, while allowing explicit raw replacement and removal. Clear cached raw packets with structured XMP data to avoid restoring removed metadata. --- src/heifimage_int.cpp | 51 ++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 50 insertions(+), 1 deletion(-) diff --git a/src/heifimage_int.cpp b/src/heifimage_int.cpp index 997ca9647a..fce93bd993 100644 --- a/src/heifimage_int.cpp +++ b/src/heifimage_int.cpp @@ -105,6 +105,7 @@ struct Metadata { XmpData xmp; XmpData embeddedXmp; std::string packet; + bool hasEmbeddedXmp{}, needsXmpToolkit{}; ByteOrder order{littleEndian}; DataBuf icc; uint32_t width{}, height{}; @@ -118,6 +119,16 @@ Metadata readMetadata(BasicIo& io, const BmffDocument& document, const DecodePar total += bytes.size(); return bytes; }; +#ifndef EXV_HAVE_XMP_TOOLKIT + // Without a toolkit, preserve packets exactly. Different packets cannot be + // merged when several primary metadata items must become one new Exif item. + auto rememberPacket = [&](const std::string& packet) { + if (packet.empty()) + return; + metadata.needsXmpToolkit |= !metadata.packet.empty() && metadata.packet != packet; + metadata.packet = packet; + }; +#endif for (auto id : document.metadataItems(bmffType("Exif"))) { auto bytes = read(id); enforce(bytes.size() >= 12, ErrorCode::kerCorruptedMetadata); @@ -129,6 +140,14 @@ Metadata readMetadata(BasicIo& io, const BmffDocument& document, const DecodePar auto order = TiffParser::decode(exif, iptc, xmp, bytes.data() + 4 + offset, bytes.size() - 4 - offset, params); enforce(order != invalidByteOrder, ErrorCode::kerCorruptedMetadata); metadata.order = order; + if (auto xml = exif.findKey(ExifKey("Exif.Image.XMLPacket")); xml != exif.end()) { + metadata.hasEmbeddedXmp = true; +#ifndef EXV_HAVE_XMP_TOOLKIT + Bytes packet(xml->size()); + xml->copy(packet.data(), order); + rememberPacket(std::string(packet.begin(), packet.end())); +#endif + } merge(metadata.exif, exif); for (const auto& datum : iptc) metadata.iptc.add(datum); @@ -140,13 +159,19 @@ Metadata readMetadata(BasicIo& io, const BmffDocument& document, const DecodePar supported(document.items.at(id).info.contentEncoding.empty(), "compressed primary XMP"); auto bytes = read(id); std::string packet(bytes.begin(), bytes.end()); +#ifdef EXV_HAVE_XMP_TOOLKIT XmpData xmp; enforce(XmpParser::decode(xmp, packet, params) == 0, ErrorCode::kerInvalidXMP); merge(metadata.xmp, xmp); metadata.packet = std::move(packet); +#else + rememberPacket(packet); +#endif } +#ifdef EXV_HAVE_XMP_TOOLKIT if (xmpIds.size() != 1 || !metadata.embeddedXmp.empty()) metadata.packet = encodeXmp(metadata.xmp); +#endif std::set properties; for (const auto& entry : document.associations) { @@ -421,16 +446,27 @@ class HeifImage final : public BmffImage { removeExif_ = true; } void setXmpData(const XmpData& xmp) override { +#ifndef EXV_HAVE_XMP_TOOLKIT + supported(xmp.empty(), "structured XMP editing requires the XMP toolkit"); +#endif + if (xmp.empty()) + Image::clearXmpPacket(); Image::setXmpData(xmp); removeXmp_ = xmp.empty(); } void clearXmpData() override { + Image::clearXmpPacket(); Image::clearXmpData(); removeXmp_ = true; } void setXmpPacket(const std::string& packet) override { supported(packet.size() <= bmffMetadataLimit, "XMP exceeds the allocation limit"); +#ifdef EXV_HAVE_XMP_TOOLKIT Image::setXmpPacket(packet); +#else + xmpPacket_ = packet; + xmpData_.clear(); +#endif writeXmpFromPacket(true); removeXmp_ = packet.empty(); } @@ -472,18 +508,25 @@ class HeifImage final : public BmffImage { }), exif.end()); } +#ifndef EXV_HAVE_XMP_TOOLKIT + supported(xmpData_.empty(), "structured XMP editing requires the XMP toolkit"); +#endif auto packet = writeXmpFromPacket() ? xmpPacket_ : encodeXmp(xmpData_); supported(packet.size() <= bmffMetadataLimit, "XMP exceeds the allocation limit"); const bool xmpChanged = removeXmp_ || (writeXmpFromPacket() ? packet != original.packet : packet != encodeXmp(original.xmp)); const bool exifChanged = removeExif_ || !sameData(exif, original.exif); + supported(!original.needsXmpToolkit || xmpChanged || !exifChanged, + "merging different primary XMP packets requires the XMP toolkit"); BmffMetadataUpdate update; - if (xmpChanged || (exifChanged && exif.empty() && !original.embeddedXmp.empty())) + if (xmpChanged || (exifChanged && exif.empty() && original.hasEmbeddedXmp)) update.xmp = Bytes(packet.begin(), packet.end()); // A separate MIME item becomes authoritative when XMP is edited. Remove its // old embedded TIFF copy so it cannot reappear after removing the MIME item. auto embedded = original.embeddedXmp; +#ifdef EXV_HAVE_XMP_TOOLKIT auto xml = exif.findKey(ExifKey("Exif.Image.XMLPacket")); +#endif // Even without a live XMLPacket tag, prior XMP may survive in TIFF slack. const bool embeddedChanged = xmpChanged && !exif.empty(); if (xmpChanged) { @@ -493,6 +536,7 @@ class HeifImage final : public BmffImage { // The Exif API can also delete or replace the embedded XMLPacket tag. // Honor its current value instead of restoring the old decoded packet. embedded.clear(); +#ifdef EXV_HAVE_XMP_TOOLKIT if (xml != exif.end()) { supported(xml->size() <= bmffMetadataLimit, "embedded XMP exceeds the allocation limit"); Bytes bytes(xml->size()); @@ -500,6 +544,7 @@ class HeifImage final : public BmffImage { enforce(XmpParser::decode(embedded, std::string(bytes.begin(), bytes.end()), params) == 0, ErrorCode::kerInvalidXMP); } +#endif } if (exifChanged || embeddedChanged) { if (exif.findKey(ExifKey("Exif.Canon.AFInfo")) != exif.end() && @@ -537,9 +582,13 @@ class HeifImage final : public BmffImage { if (!loaded_) readMetadata(); if (option == kpsXMP) { +#ifdef EXV_HAVE_XMP_TOOLKIT std::string packet; enforce(XmpParser::encode(packet, xmpData_) == 0, ErrorCode::kerInvalidXMP); out << packet; +#else + out << xmpPacket_; +#endif } else if (option == kpsIccProfile) out.write(iccProfile_.c_str(), iccProfile_.size()); else if (option == kpsBasic || option == kpsRecursive) { From 9a63a3ada7aa62d4dc28f86f6d63f928f85a4734 Mon Sep 17 00:00:00 2001 From: Vaclav Haisman Date: Sat, 10 Oct 2026 00:37:27 +0200 Subject: [PATCH 07/40] [tests] Cover HEIF writing without the XMP toolkit Exercise raw packet preservation, replacement, embedded XMP promotion and physical removal. Check rejection of ambiguous packet merges and structured edits. Use raw packets for applicable feature-disabled tests and skip only cases that require structured XMP decoding. --- .../github/test_issue_2349_heif_write.py | 2 + unitTests/test_bmffimage_int.cpp | 105 +++++++++++++++++- 2 files changed, 104 insertions(+), 3 deletions(-) diff --git a/tests/bugfixes/github/test_issue_2349_heif_write.py b/tests/bugfixes/github/test_issue_2349_heif_write.py index e5f587c826..bfb458c4a9 100644 --- a/tests/bugfixes/github/test_issue_2349_heif_write.py +++ b/tests/bugfixes/github/test_issue_2349_heif_write.py @@ -33,6 +33,8 @@ def run_exiv2(self, *args, success=True): self.assertNotEqual(result.returncode, 0) return result.stdout + @unittest.skipUnless(system_tests.BT.verbose_version().get("have_xmptoolkit") == "1", + "requires structured XMP editing") def test_extract_clear_and_insert_metadata(self): target = self.copy("Stonehenge.heic") self.run_exiv2("-M", "set Exif.Image.Artist HEIF_EXIF_CANARY_627c", diff --git a/unitTests/test_bmffimage_int.cpp b/unitTests/test_bmffimage_int.cpp index d905e340ec..cd58b02184 100644 --- a/unitTests/test_bmffimage_int.cpp +++ b/unitTests/test_bmffimage_int.cpp @@ -1264,6 +1264,22 @@ Image::UniquePtr openHeif(const Bytes& bytes) { return image; } +std::string rawXmpSource(std::string_view value) { + return "" + ""; +} + +void setHeifXmpSource(Image& image, const std::string& value) { +#ifdef EXV_HAVE_XMP_TOOLKIT + image.xmpData()["Xmp.dc.source"] = value; +#else + image.setXmpPacket(rawXmpSource(value)); +#endif +} + Bytes imageBytes(Image& image) { auto& io = image.io(); io.open(); @@ -1282,12 +1298,12 @@ TEST(HeifImage, addsGrowsShrinksDeletesAndPreservesEncodedImage) { for (unsigned cycle = 0; cycle < 4; ++cycle) { const auto canary = "PRIVATE_HEIF_DESCRIPTION_" + std::to_string(cycle); image->exifData()["Exif.Image.ImageDescription"] = std::string(70000, 'v') + canary; - image->xmpData()["Xmp.dc.source"] = "Příliš žluťoučký kůň — " + canary; + setHeifXmpSource(*image, "Příliš žluťoučký kůň — " + canary); ASSERT_NO_THROW(image->writeMetadata()); auto large = imageBytes(*image); EXPECT_TRUE(contains(large, canary)); image->exifData()["Exif.Image.ImageDescription"] = "short"; - image->xmpData()["Xmp.dc.source"] = "short"; + setHeifXmpSource(*image, "short"); ASSERT_NO_THROW(image->writeMetadata()); auto small = imageBytes(*image); EXPECT_FALSE(contains(small, canary)); @@ -1345,6 +1361,9 @@ TEST(HeifImage, removesDeletedTagsAndOriginalTiffSlack) { } TEST(HeifImage, clearsEmbeddedXmpAndPreservesItWhenOnlyExifIsRemoved) { +#ifndef EXV_HAVE_XMP_TOOLKIT + GTEST_SKIP() << "requires structured XMP decoding; raw packet behavior is tested separately"; +#endif ExifData exif; exif["Exif.Image.Artist"] = "keep artist"; XmpData xmp; @@ -1373,6 +1392,9 @@ TEST(HeifImage, clearsEmbeddedXmpAndPreservesItWhenOnlyExifIsRemoved) { } TEST(HeifImage, usesRawXmpPacketsSetMetadataAndRejectsUnsupportedCategories) { +#ifndef EXV_HAVE_XMP_TOOLKIT + GTEST_SKIP() << "requires structured XMP decoding; raw packet behavior is tested separately"; +#endif auto source = openHeif(heifWithMetadata()); XmpData xmp; xmp["Xmp.dc.source"] = "RAW_XMP_říční"; @@ -1444,7 +1466,7 @@ TEST_P(BmffCorpus, editsThroughPublicApiAndKeepsOtherItems) { ASSERT_EQ(image->imageType(), ImageType::heif); image->readMetadata(); image->exifData()["Exif.Image.ImageDescription"] = "PUBLIC_API_CANARY_6f9326"; - image->xmpData()["Xmp.dc.source"] = "PUBLIC_API_CANARY_6f9326"; + setHeifXmpSource(*image, "PUBLIC_API_CANARY_6f9326"); ASSERT_NO_THROW(image->writeMetadata()); auto output = imageBytes(*image); auto before = parse(bytes), after = parse(output); @@ -1683,4 +1705,81 @@ TEST(HeifImage, preservesAuxiliaryAndThumbnailGraphsAsOpaqueImageData) { } } +TEST(HeifImage, preservesRawXmpDuringExifEditsAndClearsItsStorage) { + ExifData exif; + exif["Exif.Image.Artist"] = "artist"; + const auto packet = rawXmpSource("PRIVATE_RAW_PACKET_594e"); + auto image = openHeif(heifWithMetadata(exif, packet)); +#ifdef EXV_HAVE_XMP_TOOLKIT + EXPECT_EQ(image->xmpData()["Xmp.dc.source"].toString(), "PRIVATE_RAW_PACKET_594e"); +#else + EXPECT_EQ(image->xmpPacket(), packet); +#endif + auto before = imageBytes(*image); + image->writeMetadata(); + EXPECT_EQ(imageBytes(*image), before); + image->exifData()["Exif.Image.Artist"] = "edited"; + ASSERT_NO_THROW(image->writeMetadata()); + auto bytes = imageBytes(*image); + auto document = parse(bytes); + const auto ids = document.metadataItems(bmffType("mime")); + ASSERT_EQ(ids.size(), 1u); + EXPECT_EQ(payload(bytes, document.items.at(ids.front())), Bytes(packet.begin(), packet.end())); + image->setXmpPacket(rawXmpSource("PRIVATE_REPLACEMENT_PACKET_653c")); + image->writeMetadata(); + EXPECT_FALSE(contains(imageBytes(*image), "PRIVATE_RAW_PACKET_594e")); + image->clearXmpData(); + image->writeMetadata(); + EXPECT_FALSE(contains(imageBytes(*image), "PRIVATE_REPLACEMENT_PACKET_653c")); + EXPECT_TRUE(image->xmpPacket().empty()); + image->setXmpPacket(packet); + image->writeMetadata(); + image->setXmpData(XmpData{}); + image->writeMetadata(); + EXPECT_FALSE(contains(imageBytes(*image), "PRIVATE_RAW_PACKET_594e")); +} + +#ifndef EXV_HAVE_XMP_TOOLKIT +TEST(HeifImage, preservesEmbeddedRawXmpWithoutToolkitAndRejectsUnmergeablePackets) { + ExifData exif; + exif["Exif.Image.Artist"] = "artist"; + const auto packet = rawXmpSource("PRIVATE_EMBEDDED_RAW_819c"); + auto value = Value::create(unsignedByte); + value->read(reinterpret_cast(packet.data()), packet.size(), invalidByteOrder); + exif.add(ExifKey("Exif.Image.XMLPacket"), value.get()); + auto image = openHeif(heifWithMetadata(exif)); + EXPECT_EQ(image->xmpPacket(), packet); + image->exifData()["Exif.Image.Artist"] = "edited"; + ASSERT_NO_THROW(image->writeMetadata()); + EXPECT_EQ(image->xmpPacket(), packet); + image->clearExifData(); + image->writeMetadata(); + auto bytes = imageBytes(*image); + auto document = parse(bytes); + EXPECT_TRUE(document.metadataItems(bmffType("Exif")).empty()); + ASSERT_EQ(document.metadataItems(bmffType("mime")).size(), 1u); + EXPECT_EQ(image->xmpPacket(), packet); + image->clearXmpData(); + image->writeMetadata(); + EXPECT_FALSE(contains(imageBytes(*image), "PRIVATE_EMBEDDED_RAW_819c")); + + const auto other = rawXmpSource("PRIVATE_DIFFERENT_RAW_0551"); + bytes = heifWithMetadata(exif, other); + image = openHeif(bytes); + image->writeMetadata(); + EXPECT_EQ(imageBytes(*image), bytes); + image->exifData()["Exif.Image.Artist"] = "pending"; + EXPECT_THROW(image->writeMetadata(), Error); + EXPECT_EQ(imageBytes(*image), bytes); + image->clearXmpData(); + ASSERT_NO_THROW(image->writeMetadata()); + EXPECT_FALSE(contains(imageBytes(*image), "PRIVATE_EMBEDDED_RAW_819c")); + EXPECT_FALSE(contains(imageBytes(*image), "PRIVATE_DIFFERENT_RAW_0551")); + image->xmpData()["Xmp.dc.source"] = "requires toolkit"; + bytes = imageBytes(*image); + EXPECT_THROW(image->writeMetadata(), Error); + EXPECT_EQ(imageBytes(*image), bytes); +} +#endif + #endif // EXV_ENABLE_BMFF From c46208c79ee132d81dbf913dd64d313bae72c4f0 Mon Sep 17 00:00:00 2001 From: Vaclav Haisman Date: Sat, 10 Oct 2026 00:37:35 +0200 Subject: [PATCH 08/40] [heif] Avoid repeated scans when merging metadata items Index metadata keys while keeping ordered values. Preserve last-item precedence and duplicate Exif tags within the winning item without repeatedly scanning every previously decoded tag. --- src/heifimage_int.cpp | 65 ++++++++++++++++++++++++++++++------------- 1 file changed, 45 insertions(+), 20 deletions(-) diff --git a/src/heifimage_int.cpp b/src/heifimage_int.cpp index fce93bd993..a8f4a4c9e0 100644 --- a/src/heifimage_int.cpp +++ b/src/heifimage_int.cpp @@ -17,6 +17,8 @@ #include #include #include +#include +#include #include #include #include @@ -54,24 +56,39 @@ std::string encodeXmp(const XmpData& data) { return packet; } -void merge(ExifData& target, const ExifData& source) { - std::set keys; - for (const auto& datum : source) - keys.insert(datum.key()); - target.erase(std::remove_if(target.begin(), target.end(), [&](const auto& d) { return keys.contains(d.key()); }), - target.end()); - for (const auto& datum : source) - target.add(datum); -} +// Keep last-item precedence without rescanning all previously decoded tags for +// each item. The list preserves file order; the index removes superseded groups. +template +class MetadataMerger { + public: + void add(const Data& source, bool preserveDuplicates = false) { + std::set seen; + for (const auto& datum : source) { + const auto key = datum.key(); + if (!preserveDuplicates || seen.insert(key).second) { + if (auto found = index_.find(key); found != index_.end()) { + for (auto entry : found->second) + values_.erase(entry); + index_.erase(found); + } + } + values_.push_back(datum); + index_[key].push_back(std::prev(values_.end())); + } + } -void merge(XmpData& target, const XmpData& source) { - for (const auto& datum : source) { - auto found = target.findKey(XmpKey(datum.key())); - if (found != target.end()) - target.erase(found); - target.add(datum); + Data data() const { + Data result; + for (const auto& datum : values_) + result.add(datum); + return result; } -} + + private: + using Datum = typename std::iterator_traits::value_type; + std::list values_; + std::map::iterator>> index_; +}; // Compare raw values, preserving duplicate tags and attached thumbnail data. template @@ -113,6 +130,8 @@ struct Metadata { Metadata readMetadata(BasicIo& io, const BmffDocument& document, const DecodeParams& params) { Metadata metadata; + MetadataMerger exifMerger; + MetadataMerger embeddedMerger; uint64_t total = 0; auto read = [&](uint32_t id) { auto bytes = readBmffItem(io, document.items.at(id), bmffMetadataLimit - total); @@ -148,12 +167,17 @@ Metadata readMetadata(BasicIo& io, const BmffDocument& document, const DecodePar rememberPacket(std::string(packet.begin(), packet.end())); #endif } - merge(metadata.exif, exif); + exifMerger.add(exif, true); for (const auto& datum : iptc) metadata.iptc.add(datum); - merge(metadata.embeddedXmp, xmp); + embeddedMerger.add(xmp); } - metadata.xmp = metadata.embeddedXmp; + metadata.exif = exifMerger.data(); + metadata.embeddedXmp = embeddedMerger.data(); +#ifdef EXV_HAVE_XMP_TOOLKIT + MetadataMerger xmpMerger; + xmpMerger.add(metadata.embeddedXmp); +#endif auto xmpIds = document.metadataItems(bmffType("mime")); for (auto id : xmpIds) { supported(document.items.at(id).info.contentEncoding.empty(), "compressed primary XMP"); @@ -162,13 +186,14 @@ Metadata readMetadata(BasicIo& io, const BmffDocument& document, const DecodePar #ifdef EXV_HAVE_XMP_TOOLKIT XmpData xmp; enforce(XmpParser::decode(xmp, packet, params) == 0, ErrorCode::kerInvalidXMP); - merge(metadata.xmp, xmp); + xmpMerger.add(xmp); metadata.packet = std::move(packet); #else rememberPacket(packet); #endif } #ifdef EXV_HAVE_XMP_TOOLKIT + metadata.xmp = xmpMerger.data(); if (xmpIds.size() != 1 || !metadata.embeddedXmp.empty()) metadata.packet = encodeXmp(metadata.xmp); #endif From 84948141450e27a7ea1a839ad3d819e84405e735 Mon Sep 17 00:00:00 2001 From: Vaclav Haisman Date: Sat, 10 Oct 2026 00:37:42 +0200 Subject: [PATCH 09/40] [tests] Verify duplicate Exif group precedence across HEIF items Check that the last item replaces a duplicate tag group while retaining unrelated fields and both duplicate values from the winning item. --- unitTests/test_bmffimage_int.cpp | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/unitTests/test_bmffimage_int.cpp b/unitTests/test_bmffimage_int.cpp index cd58b02184..0b52b92151 100644 --- a/unitTests/test_bmffimage_int.cpp +++ b/unitTests/test_bmffimage_int.cpp @@ -1529,6 +1529,31 @@ TEST(HeifImage, readsAndReplacesMultiplePrimaryMetadataItems) { EXPECT_EQ(imageBytes(*image), source); } +TEST(HeifImage, mergesDuplicateExifGroupsInFileOrder) { + ExifData first, second; + first["Exif.Image.Make"] = "retained"; + first["Exif.Image.Artist"] = "old first"; + auto value = Value::create(asciiString); + value->read("old second"); + first.add(ExifKey("Exif.Image.Artist"), value.get()); + second["Exif.Image.Model"] = "new model"; + second["Exif.Image.Artist"] = "new first"; + value->read("new second"); + second.add(ExifKey("Exif.Image.Artist"), value.get()); + Options options; + options.secondExif = true; + options.exifPayload = tiffItem(first); + options.xmpPayload = tiffItem(second); + auto image = openHeif(fixture(options)); + std::vector artists; + for (const auto& datum : image->exifData()) + if (datum.key() == "Exif.Image.Artist") + artists.push_back(datum.toString()); + EXPECT_EQ(artists, (std::vector{"new first", "new second"})); + EXPECT_EQ(image->exifData()["Exif.Image.Make"].toString(), "retained"); + EXPECT_EQ(image->exifData()["Exif.Image.Model"].toString(), "new model"); +} + TEST(HeifImage, updatesIdatMetadataAndWideItemIds) { ExifData exif; exif["Exif.Image.Artist"] = "PRIVATE_IDAT_METADATA_7703"; From e0bbc9fe008cd8cd0db0d316394f8a7c8513c611 Mon Sep 17 00:00:00 2001 From: Vaclav Haisman Date: Sat, 10 Oct 2026 00:37:49 +0200 Subject: [PATCH 10/40] [fuzz] Exercise HEIF metadata edits and compaction Extend both read/write fuzz drivers with deterministic Exif updates and metadata clears, followed by a reread. This exercises serialization and compaction in addition to unchanged writes on owned MemIo inputs. --- fuzz/fuzz-heif-write.hpp | 31 +++++++++++++++++++++++++++++++ fuzz/fuzz-read-print-write.cpp | 3 +++ fuzz/fuzz-read-write.cpp | 3 +++ 3 files changed, 37 insertions(+) create mode 100644 fuzz/fuzz-heif-write.hpp diff --git a/fuzz/fuzz-heif-write.hpp b/fuzz/fuzz-heif-write.hpp new file mode 100644 index 0000000000..de3cdd288d --- /dev/null +++ b/fuzz/fuzz-heif-write.hpp @@ -0,0 +1,31 @@ +// SPDX-License-Identifier: GPL-2.0-or-later + +#ifndef FUZZ_HEIF_WRITE_HPP +#define FUZZ_HEIF_WRITE_HPP + +#include + +// The ordinary write keeps metadata unchanged and may take the HEIF no-op +// path. Exercise serialization and compaction as well, on the owned MemIo. +inline void fuzzHeifWrite(Exiv2::Image& image, size_t selector) { + if (image.imageType() != Exiv2::ImageType::heif) + return; + 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; + } + 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. From 0cbbe1dcff9de0371eb114bffa282d9a21ec412a Mon Sep 17 00:00:00 2001 From: Vaclav Haisman Date: Sat, 10 Oct 2026 00:38:10 +0200 Subject: [PATCH 11/40] [docs] Describe HEIF metadata writing and its limits Update format capabilities and document supported layouts, physical metadata removal, shared-data rejection, feature-disabled behavior and final-transfer limitations. Explain factory selection of the writer. Related to #2349; CR3 writing remains outside this HEIF change. --- README.md | 11 ++++++++ exiv2.md | 50 +++++++++++++++++++++++++++++++++++-- include/exiv2/bmffimage.hpp | 6 +++++ 3 files changed, 65 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index a87c92e534..947d2064d7 100644 --- a/README.md +++ b/README.md @@ -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/include/exiv2/bmffimage.hpp b/include/exiv2/bmffimage.hpp index 8590d6d7b9..8747253d47 100644 --- a/include/exiv2/bmffimage.hpp +++ b/include/exiv2/bmffimage.hpp @@ -36,6 +36,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: From 2e07feb7cbcc97d309ffa6ad6f49243a0adec765 Mon Sep 17 00:00:00 2001 From: Vaclav Haisman Date: Sat, 10 Oct 2026 01:20:21 +0200 Subject: [PATCH 12/40] [docs] Document the internal BMFF model and parser contract Describe shared structures, field coordinates, parsing limits and payload ownership. Document parser and write-eligibility interfaces. --- src/bmffimage_int.hpp | 182 ++++++++++++++++++++++++------------------ 1 file changed, 106 insertions(+), 76 deletions(-) diff --git a/src/bmffimage_int.hpp b/src/bmffimage_int.hpp index 62a017a4dc..54381e09c2 100644 --- a/src/bmffimage_int.hpp +++ b/src/bmffimage_int.hpp @@ -20,131 +20,154 @@ 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])}; } -//! A validated interval in the original input. Payloads are never owned by the model. +//! @brief A validated interval in the original input. Payloads are never owned by the model. struct BmffSpan { - uint64_t offset{}; - uint64_t size{}; + 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{}; - uint32_t flags{}; + uint8_t version{}; //!< FullBox version selecting its field layout. + uint32_t flags{}; //!< Low 24 flag bits of the FullBox prefix. }; +//! @brief Input box boundaries and decoded children, with opaque payloads left in the input. struct BmffBox { - uint32_t type{}; - BmffSpan span; - uint8_t headerSize{}; //!< Includes a UUID user type, but excludes FullBox version/flags. - bool extendsToEnd{}; - std::array userType{}; - std::optional fullBox; - std::vector children; - + uint32_t type{}; //!< Packed four-character box code. + 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 Item description and its original infe span, retained for lossless rewriting. struct BmffItemInfo { - BmffSpan box; - uint8_t version{}; - uint32_t flags{}; - uint32_t type{}; - uint16_t protectionIndex{}; - std::string name; - std::string contentType; - std::string contentEncoding; - std::string uriType; + BmffSpan box; //!< Original infe interval, used to preserve unchanged descriptions. + uint8_t version{}; //!< Item info version selecting the ID width. + uint32_t flags{}; //!< Item info flags retained when rewriting. + uint32_t type{}; //!< Packed four-character item type. + uint16_t protectionIndex{}; //!< Zero for supported unprotected items. + std::string name; //!< Decoded null-terminated item name. + std::string contentType; //!< MIME content type, present only for mime items. + std::string contentEncoding; //!< Optional MIME content encoding. + std::string uriType; //!< URI type string, present only for uri items. }; +//! @brief An iloc extent with its original fields and resolved absolute source interval. struct BmffExtent { - uint64_t index{}; - uint64_t offset{}; - uint64_t length{}; - BmffSpan source; + uint64_t index{}; //!< Original extent index, retained without interpreting it. + uint64_t offset{}; //!< Offset relative to the item base in its construction method. + uint64_t length{}; //!< Explicit nonzero extent length. + BmffSpan source; //!< Validated absolute input interval for these bytes. }; +//! @brief Item addressing and aggregate size; method 0 is file-relative, method 1 idat-relative. struct BmffItemLocation { - uint8_t constructionMethod{}; - uint16_t dataReferenceIndex{}; - uint64_t baseOffset{}; - uint64_t dataSize{}; - std::vector extents; + uint8_t constructionMethod{}; //!< Zero selects mdat/file addressing; one selects idat-relative addressing. + uint16_t dataReferenceIndex{}; //!< Zero selects local storage; external references are unsupported. + uint64_t baseOffset{}; //!< Base offset added to each extent in the selected coordinate system. + uint64_t dataSize{}; //!< Sum of declared extent lengths, including any repeated bytes. + std::vector extents; //!< Ordered extents comprising the item payload. }; +//! @brief Join an item's independently ordered info and location records by ID. struct BmffItem { - BmffItemInfo info; - BmffItemLocation location; + BmffItemInfo info; //!< Description from the item information table. + BmffItemLocation location; //!< Addressing from the item location table. }; +//! @brief Version and field widths shared by all records in an iloc box. struct BmffLocationFormat { - BmffSpan box; - uint8_t version{}; - uint8_t offsetSize{}; - uint8_t lengthSize{}; - uint8_t baseOffsetSize{}; - uint8_t indexSize{}; + BmffSpan box; //!< Original iloc box interval. + uint8_t version{}; //!< Location version selecting ID and construction fields. + uint8_t offsetSize{}; //!< Extent offset field width in bytes. + uint8_t lengthSize{}; //!< Extent length field width in bytes. + uint8_t baseOffsetSize{}; //!< Item base-offset field width in bytes. + uint8_t indexSize{}; //!< Extent index field width in bytes. }; +//! @brief A directed item relationship, retaining destination order and its original box span. struct BmffReference { - BmffSpan box; - uint32_t type{}; - uint32_t from{}; - std::vector to; + BmffSpan box; //!< Original reference child box interval. + uint32_t type{}; //!< Packed reference type, such as cdsc or auxl. + uint32_t from{}; //!< Source item ID. + std::vector to; //!< Destination item IDs in their declared order. }; +//! @brief One property index and whether it is essential to interpreting the associated item. struct BmffPropertyAssociation { uint16_t index{}; //!< One-based property index; zero denotes no association. - bool essential{}; + bool essential{}; //!< True when understanding this property is required for the item. }; +//! @brief Ordered properties associated with one item in a particular ipma box. struct BmffAssociationEntry { - BmffSpan box; - uint32_t itemId{}; - std::vector properties; + BmffSpan box; //!< Containing ipma box interval. + uint32_t itemId{}; //!< Item to which these properties apply. + std::vector properties; //!< Associations in their declared order. }; -//! Limits apply to aggregate structural work, independently of encoded image size. +//! @brief Limits apply to aggregate structural work, independently of encoded image size. struct BmffLimits { - uint64_t maxBoxes{100000}; - uint64_t maxItems{65536}; - uint64_t maxExtents{1000000}; - uint64_t maxReferences{1000000}; - uint64_t maxAssociations{1000000}; - uint64_t maxStringBytes{1024 * 1024}; - uint64_t maxStringLength{65536}; - uint64_t maxBytesRead{16 * 1024 * 1024}; - unsigned maxDepth{16}; + uint64_t maxBoxes{100000}; //!< Maximum number of boxes across all containers. + uint64_t maxItems{65536}; //!< Maximum number of distinct item IDs. + uint64_t maxExtents{1000000}; //!< Maximum aggregate number of item extents. + uint64_t maxReferences{1000000}; //!< Maximum aggregate number of reference destinations. + uint64_t maxAssociations{1000000}; //!< Budget for association records and their property entries. + uint64_t maxStringBytes{1024 * 1024}; //!< Maximum aggregate bytes consumed by strings, including terminators. + uint64_t maxStringLength{65536}; //!< Maximum bytes in one string, excluding its terminator. + uint64_t maxBytesRead{16 * 1024 * 1024}; //!< Maximum structural bytes read, independent of media size. + unsigned maxDepth{16}; //!< Maximum child-box nesting depth below the file context. }; -//! Checked item-based BMFF structure, independent of BmffImage's metadata state. +//! @brief Checked item-based BMFF structure, independent of BmffImage's metadata state. struct BmffDocument { - uint64_t fileSize{}; - uint32_t majorBrand{}; - uint32_t minorVersion{}; - std::vector compatibleBrands; - std::vector boxes; - uint32_t primaryItem{}; - BmffLocationFormat locationFormat; - std::map items; - std::vector infoOrder; - std::vector locationOrder; - std::vector references; - std::vector properties; - std::vector associations; - std::vector mediaData; - std::optional itemData; - - //! Exif or XMP items describing the primary image, in iinf order. + uint64_t fileSize{}; //!< Original input length in bytes. + uint32_t majorBrand{}; //!< Major brand from ftyp. + uint32_t minorVersion{}; //!< Minor version from ftyp. + std::vector compatibleBrands; //!< Compatible brands in their original order. + std::vector boxes; //!< Top-level boxes in original file order. + uint32_t primaryItem{}; //!< Primary image item ID from pitm. + BmffLocationFormat locationFormat; //!< Shared iloc version and field widths. + std::map items; //!< Checked item descriptions and locations keyed by ID. + std::vector infoOrder; //!< Item IDs in original iinf order, defining metadata merge precedence. + std::vector locationOrder; //!< Item IDs in original iloc order. + std::vector references; //!< Directed relationships in original traversal order. + std::vector properties; //!< Property boxes in one-based index order. + std::vector associations; //!< Item-to-property associations in original traversal order. + std::vector mediaData; //!< Absolute mdat payload intervals in file order. + std::optional itemData; //!< Absolute idat payload interval when present. + + /*! + @brief Select Exif or XMP items describing the primary image, in iinf order. + @param type Exif item type or MIME item type; MIME selection requires application/rdf+xml. + @return IDs whose cdsc references include the primary item. + */ [[nodiscard]] std::vector metadataItems(uint32_t type) const; }; /*! @brief Parse an open, seekable BasicIo without reading image payloads or writing. + @param io Borrowed input, already open and seekable. + @param limits Bounds on aggregate structural work and nesting. + @return An owning structural model whose payload ranges refer to the original input. + @throws Error For malformed or unsupported structure, exceeded limits, or failed I/O. + The input must stay unchanged while its returned ranges are used. The stream position may change. Malformed input throws kerCorruptedMetadata; unsupported syntax throws an explicit unsupported-layout error. Parsing alone does not @@ -152,7 +175,14 @@ struct BmffDocument { */ BmffDocument parseBmff(BasicIo& io, const BmffLimits& limits = {}); -//! Reject deferred brands and opaque structures whose relocation is not supported. +/*! + @brief Reject deferred brands and opaque structures whose relocation is not supported. + @param document A validated model returned by parseBmff(). + @throws Error If the modeled layout is outside the HEIF write envelope. + + This checks layout eligibility only. The rewriter must still validate the + requested changes against shared metadata references and overlapping extents. + */ void enforceHeifWriteSupport(const BmffDocument& document); } // namespace Exiv2::Internal From 0a3cc0771909338d7d5e8b5f0b89e0c7d330cf23 Mon Sep 17 00:00:00 2001 From: Vaclav Haisman Date: Sat, 10 Oct 2026 01:20:21 +0200 Subject: [PATCH 13/40] [docs] Explain BMFF parsing and validation steps Describe parser helpers and separate boundary, resource-budget and item graph checks with comments and spacing. --- src/bmffimage_int.cpp | 100 +++++++++++++++++++++++++++++++++++++++++- 1 file changed, 99 insertions(+), 1 deletion(-) diff --git a/src/bmffimage_int.cpp b/src/bmffimage_int.cpp index 176ee80eaf..e3d311dff3 100644 --- a/src/bmffimage_int.cpp +++ b/src/bmffimage_int.cpp @@ -20,20 +20,24 @@ namespace { constexpr std::array canonUuid{0x85, 0xc0, 0xb6, 0x87, 0x82, 0x0f, 0x11, 0xe0, 0x81, 0x11, 0xf4, 0xce, 0x46, 0x2b, 0x6a, 0x48}; +// Report malformed structure through the common metadata error code. void require(bool condition) { enforce(condition, ErrorCode::kerCorruptedMetadata); } +// Distinguish unsupported layouts from corrupt container data. void supported(bool condition, std::string_view feature) { if (!condition) throw Error(ErrorCode::kerErrorMessage, std::string("Unsupported HEIF layout: ") + std::string(feature)); } +// 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 BmffLimits& limits; uint64_t boxes{}; @@ -44,45 +48,62 @@ struct Budget { uint64_t bytes{}; }; -//! Every field read is checked against its immediate box, not merely the file. +//! @brief Every field read is checked against its immediate box, not merely the file. class Cursor { public: + //! @brief Borrow a previously bounded input interval and the enclosing parser budget. Cursor(BasicIo& io, BmffSpan range, Budget& budget) : io_(io), position_(range.offset), end_(range.offset + range.size), budget_(budget) { } + //! @brief Return the absolute input offset of the next field. uint64_t position() const { return position_; } + + //! @brief Return the bytes still available within this interval. uint64_t remaining() const { return end_ - position_; } + + //! @brief Return the exclusive absolute end of the containing interval. uint64_t end() const { return end_; } + + //! @brief Skip bytes within the interval without reading their contents. void advance(uint64_t count) { require(count <= remaining()); position_ += count; } + + //! @brief Read an exact field, charging its bytes to the shared structural budget. void read(byte* bytes, size_t size) { require(size <= remaining()); consume(budget_.bytes, size, budget_.limits.maxBytesRead); + io_.seekOrThrow(static_cast(position_), BasicIo::beg, ErrorCode::kerInputDataReadFailed); io_.readOrThrow(bytes, size, ErrorCode::kerInputDataReadFailed); if (io_.error()) throw Error(ErrorCode::kerInputDataReadFailed); + position_ += size; } + + //! @brief Decode an unsigned big-endian field; a zero-width field has value zero. uint64_t 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[i]; return result; } + + //! @brief Read a terminated string subject to per-string and aggregate limits. std::string string() { std::string result; while (true) { @@ -91,10 +112,13 @@ class Cursor { consume(budget_.strings, 1, budget_.limits.maxStringBytes); if (c == '\0') return result; + require(result.size() < budget_.limits.maxStringLength); result.push_back(c); } } + + //! @brief Reject trailing fields where the supported box layout must be exhausted. void finish() const { require(remaining() == 0); } @@ -106,39 +130,51 @@ class Cursor { Budget& budget_; }; +// Interpret child box types according to their immediate container. enum class Context { file, meta, info, properties, propertyList, references, dataInfo, dataRefs, canon }; +// Build a range-backed item graph, then validate links after all boxes are known. class Parser { public: + //! @brief Borrow an open input and limits for the duration of parsing. Parser(BasicIo& io, const BmffLimits& limits) : io_(io), budget_{limits} { require(io.isopen()); document_.fileSize = io.size(); require(document_.fileSize <= static_cast(std::numeric_limits::max())); } + //! @brief Parse structure and resolve item ranges without copying encoded image data. BmffDocument parse() { + // Collect structure before checking relationships that may point to later boxes. Cursor input(io_, {0, document_.fileSize}, budget_); document_.boxes = children(input, Context::file, 0); require(!document_.boxes.empty() && document_.boxes.front().type == bmffType("ftyp")); require(has(document_.boxes, bmffType("ftyp")) && has(document_.boxes, bmffType("meta"))); + + // Cross-check item records only after both iinf and iloc have been read. validateItems(); return std::move(document_); } private: + // 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; }); } + // Validate a box header and advance the parent cursor past the entire box. BmffBox header(Cursor& input) { consume(budget_.boxes, 1, budget_.limits.maxBoxes); require(input.remaining() >= 8); + BmffBox box; box.span.offset = input.position(); const auto available = input.remaining(); box.span.size = input.number(4); box.type = static_cast(input.number(4)); box.headerSize = 8; + + // Resolve extended sizes and EOF-sized boxes before bounding the payload. if (box.span.size == 1) { box.span.size = input.number(8); box.headerSize = 16; @@ -148,16 +184,21 @@ class Parser { box.span.size = available; box.extendsToEnd = true; } + + // UUID user types belong to the header, so exclude them from the payload span. 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()); } + + // The child cursor will read fields independently of this parent position. require(box.span.size >= box.headerSize && box.span.size <= available); input.advance(box.span.size - box.headerSize); return box; } + // 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 value = static_cast(input.number(4)); BmffFullBox full{static_cast(value >> 24), value & 0xffffff}; @@ -167,23 +208,29 @@ class Parser { 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 = document_.items.find(id); if (found != document_.items.end()) return found->second; + require(document_.items.size() < budget_.limits.maxItems); return document_.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) { require(depth <= budget_.limits.maxDepth); std::vector boxes; std::set singletons; + + // Singleton checks apply within each immediate container, not globally. while (input.remaining() != 0) { auto box = header(input); Cursor fields(io_, box.payload(), budget_); auto unique = [&] { require(singletons.insert(box.type).second); }; + switch (context) { case Context::file: if (box.type == bmffType("ftyp")) { @@ -198,6 +245,8 @@ class Parser { unique(); fullBox(box, fields, 0); box.children = children(fields, Context::meta, depth + 1); + + // A picture meta box must provide the tables needed to resolve its primary item. for (const auto required : {bmffType("hdlr"), bmffType("pitm"), bmffType("iinf"), bmffType("iloc"), bmffType("iprp")}) require(has(box.children, required)); @@ -290,14 +339,18 @@ class Parser { unique(); 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; @@ -308,6 +361,8 @@ class Parser { supported(info.protectionIndex == 0, "protected item"); info.type = static_cast(input.number(4)); info.name = input.string(); + + // Only MIME and URI items append type-specific strings to the common entry. if (info.type == bmffType("mime")) { info.contentType = input.string(); if (input.remaining() != 0) @@ -315,15 +370,19 @@ class Parser { } else if (info.type == bmffType("uri ")) { info.uriType = input.string(); } + input.finish(); document_.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 = document_.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); @@ -334,10 +393,13 @@ class Parser { 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); @@ -351,6 +413,8 @@ class Parser { 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 && @@ -366,13 +430,17 @@ class Parser { } document_.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); @@ -381,10 +449,12 @@ class Parser { 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(); document_.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; @@ -392,6 +462,8 @@ class Parser { 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; @@ -409,12 +481,16 @@ class Parser { } document_.associations.push_back(std::move(entry)); } + input.finish(); } + // Resolve addressing and reject incomplete items, invalid ranges, and dangling links. void validateItems() { require(infoIds_ == locationIds_ && !infoIds_.empty()); require(document_.items.contains(document_.primaryItem)); + + // Method 0 uses file offsets; method 1 uses offsets from the idat payload. for (auto& [id, item] : document_.items) { auto& location = item.location; for (auto& extent : location.extents) { @@ -423,10 +499,14 @@ class Parser { require(document_.itemData.has_value()); enclosing = *document_.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}; + + // File-relative extents must lie wholly within a single mdat payload. if (location.constructionMethod == 0) { auto media = std::upper_bound(document_.mediaData.begin(), document_.mediaData.end(), extent.source.offset, [](uint64_t offset, const BmffSpan& range) { return offset < range.offset; }); @@ -438,11 +518,15 @@ class Parser { 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 : document_.references) { require(document_.items.contains(ref.from)); for (const auto id : ref.to) require(document_.items.contains(id)); } + + // Property indices are one-based; an essential property cannot use the zero sentinel. for (const auto& entry : document_.associations) { require(document_.items.contains(entry.itemId)); for (const auto& property : entry.properties) { @@ -459,15 +543,19 @@ class Parser { std::set locationIds_; }; +// Recognize padding that can be discarded or regenerated during rewriting. bool padding(uint32_t type) { return type == bmffType("free") || type == bmffType("skip"); } +// Reject opaque structures unless their payloads are known to be safe to relocate. void checkRelocation(const std::vector& boxes, Context context) { static constexpr auto propertyTypes = std::array{bmffType("hvcC"), bmffType("av1C"), bmffType("ispe"), bmffType("pixi"), bmffType("colr"), bmffType("irot"), bmffType("imir"), bmffType("clap"), bmffType("pasp"), bmffType("auxC"), bmffType("rloc"), bmffType("clli"), bmffType("mdcv"), bmffType("cclv")}; + + // Reading preserves unknown boxes, but moving them requires an explicit safe case. for (const auto& box : boxes) { if (padding(box.type)) continue; @@ -533,12 +621,15 @@ BmffSpan BmffBox::payload() const { } std::vector BmffDocument::metadataItems(uint32_t type) const { + // cdsc points from the metadata item to the image it describes. std::set describing; for (const auto& reference : references) { if (reference.type == bmffType("cdsc") && std::find(reference.to.begin(), reference.to.end(), primaryItem) != reference.to.end()) describing.insert(reference.from); } + + // Keep iinf order so later metadata items have deterministic merge precedence. std::vector result; for (const auto id : infoOrder) { const auto& info = items.at(id).info; @@ -546,6 +637,7 @@ std::vector BmffDocument::metadataItems(uint32_t type) const { (type != bmffType("mime") || info.contentType == "application/rdf+xml")) result.push_back(id); } + return result; } @@ -557,16 +649,20 @@ void enforceHeifWriteSupport(const BmffDocument& document) { supported(document.majorBrand == bmffType("heic") || document.majorBrand == bmffType("heix") || document.majorBrand == bmffType("mif1"), "file brand"); + // A generic mif1 brand can accompany an AVIF or another deferred codec. supported(std::find(document.compatibleBrands.begin(), document.compatibleBrands.end(), bmffType("avif")) == document.compatibleBrands.end() && std::find(document.compatibleBrands.begin(), document.compatibleBrands.end(), bmffType("avis")) == document.compatibleBrands.end(), "AVIF writing is deferred"); + const auto primaryType = document.items.at(document.primaryItem).info.type; supported(primaryType == bmffType("hvc1") || primaryType == bmffType("grid") || primaryType == bmffType("iden") || primaryType == bmffType("iovl"), "primary image type"); + + // Recognize near-matching XMP MIME labels so they cannot evade removal checks. for (const auto& reference : document.references) { if (reference.type != bmffType("cdsc") || std::find(reference.to.begin(), reference.to.end(), document.primaryItem) == reference.to.end()) @@ -586,6 +682,8 @@ void enforceHeifWriteSupport(const BmffDocument& document) { supported(info.contentEncoding.empty(), "compressed primary XMP"); } } + + // Finally reject any retained opaque box whose internal offsets are unknown. checkRelocation(document.boxes, Context::file); } From 446656676bcee8af6beb43548e3a1e32f73de1e7 Mon Sep 17 00:00:00 2001 From: Vaclav Haisman Date: Sat, 10 Oct 2026 01:20:21 +0200 Subject: [PATCH 14/40] [docs] Document BMFF rewrite and item-reader contracts Explain preserve/remove/replace requests, stream ownership and positioning, allocation limits and prepared-output failure handling. --- src/bmffwrite_int.hpp | 26 ++++++++++++++++++++++---- 1 file changed, 22 insertions(+), 4 deletions(-) diff --git a/src/bmffwrite_int.hpp b/src/bmffwrite_int.hpp index f9d44472b6..c89538ad23 100644 --- a/src/bmffwrite_int.hpp +++ b/src/bmffwrite_int.hpp @@ -9,22 +9,40 @@ namespace Exiv2::Internal { -//! Metadata buffers are bounded independently of the encoded image size. +//! @brief Metadata buffers are bounded independently of the encoded image size. inline constexpr uint64_t bmffMetadataLimit = 64 * 1024 * 1024; +//! @brief Serialized primary metadata requests, with distinct preserve, remove, and replace states. struct BmffMetadataUpdate { - //! No value preserves the category; an empty value removes it from the primary image. + //! @brief No value preserves the category; an empty value removes it from the primary image. std::optional> exif; + + //! @brief Raw MIME XMP packet, with the same preserve/remove/replace semantics as exif. std::optional> xmp; }; -//! Gather a checked item's extents, with an explicit metadata allocation limit. +/*! + @brief Gather a checked item's extents in their declared order. + @param input Open, seekable input from which the item's source ranges were parsed. + @param item Item with validated absolute extents and aggregate data size. + @param limit Maximum number of bytes to allocate for the assembled metadata. + @return An owned contiguous copy of the item payload. + @throws Error If the allocation limit is exceeded, ranges disagree, or input I/O fails. + + The input must remain unchanged since parsing; its stream position may change. + */ std::vector readBmffItem(BasicIo& input, const BmffItem& item, uint64_t limit = bmffMetadataLimit); /*! @brief Compact an item-based HEIF into a fresh, open, seekable output. + @param input Borrowed source stream used to parse original; it must remain unchanged. + @param output Borrowed, empty staging stream, distinct from input. + @param original Validated structure and source ranges returned by parseBmff(). + @param update Serialized primary Exif/XMP updates; absent entries preserve their category. + @throws Error For unsupported edits, invalid layout, I/O failure, or failed verification. + Input must remain unchanged and must not alias output. No transfer to the input - is performed. The output may contain partial data after an I/O failure and must + is performed. Both stream positions may change. The output may contain partial data after an I/O failure and must then be discarded. On success its parsed structure and copied bytes have been verified. Unknown relocation, shared-metadata edits and conflicting overlap are rejected before any output is written. This function does not serialize TIFF/XMP. From 9cd746dd5a60784ba00ff34e8eee8ffde7989520 Mon Sep 17 00:00:00 2001 From: Vaclav Haisman Date: Sat, 10 Oct 2026 01:20:21 +0200 Subject: [PATCH 15/40] [docs] Explain BMFF metadata rewriting and verification Describe range ownership, shared-data rejection, layout promotion and prepared-output verification. Separate the main rewriting steps. --- src/bmffwrite_int.cpp | 108 +++++++++++++++++++++++++++++++++++++++++- 1 file changed, 107 insertions(+), 1 deletion(-) diff --git a/src/bmffwrite_int.cpp b/src/bmffwrite_int.cpp index cb0668b2ee..a213e5700d 100644 --- a/src/bmffwrite_int.cpp +++ b/src/bmffwrite_int.cpp @@ -22,47 +22,57 @@ constexpr uint64_t max32 = std::numeric_limits::max(); constexpr uint32_t max16 = std::numeric_limits::max(); constexpr size_t copyBufferSize = 64 * 1024; +// Reject inconsistent layout state through the common metadata error code. void require(bool condition) { enforce(condition, ErrorCode::kerCorruptedMetadata); } +// Explain why an otherwise parsed input cannot support the requested edit. void supported(bool condition, std::string_view reason) { if (!condition) throw Error(ErrorCode::kerErrorMessage, std::string("Unsupported HEIF edit: ") + std::string(reason)); } +// Add positions within the signed seek range supported by BasicIo. uint64_t add(uint64_t a, uint64_t b) { require(a <= maxPosition && b <= maxPosition - a); return a + b; } +// Return the checked exclusive end of an input or output span. uint64_t end(BmffSpan span) { return add(span.offset, span.size); } +// Append a bounded big-endian field, rejecting values that do not fit its width. void number(Bytes& bytes, uint64_t value, unsigned width) { require(width <= 8 && (width == 8 || value < (uint64_t{1} << (width * 8)))); require(bytes.size() <= BmffLimits{}.maxBytesRead - width); + for (unsigned i = width; i != 0; --i) bytes.push_back(static_cast(value >> ((i - 1) * 8))); } +// Append a terminated string within the structural serialization budget. void string(Bytes& bytes, std::string_view value) { require(value.size() < BmffLimits{}.maxBytesRead && bytes.size() < BmffLimits{}.maxBytesRead - value.size()); bytes.insert(bytes.end(), value.begin(), value.end()); bytes.push_back(0); } +// Construct the version/flags prefix shared by FullBox records. Bytes full(uint8_t version, uint32_t flags = 0) { Bytes bytes; number(bytes, (uint32_t{version} << 24) | flags, 4); return bytes; } +// Identify padding whose old bytes must not survive compaction. bool padding(uint32_t type) { return type == bmffType("free") || type == bmffType("skip"); } +// Read an exact source range and propagate seek, short-read, and I/O errors. void read(BasicIo& input, uint64_t offset, byte* data, size_t size) { require(offset <= maxPosition && size <= maxPosition - offset); input.seekOrThrow(static_cast(offset), BasicIo::beg, ErrorCode::kerInputDataReadFailed); @@ -70,22 +80,27 @@ void read(BasicIo& input, uint64_t offset, byte* data, size_t size) { enforce(!input.error(), ErrorCode::kerInputDataReadFailed); } +// Write an exact buffer, rejecting short writes before verification proceeds. void write(BasicIo& output, const byte* data, size_t size) { if (size != 0) enforce(output.write(data, size) == size && !output.error(), ErrorCode::kerImageWriteFailed); } +// A borrowed source span or replacement buffer, with its absolute output position. +// Replacement buffers outlive the rewrite; chunks never own encoded image data. struct Chunk { BmffSpan source; const Bytes* bytes{}; uint32_t item{}; uint64_t position{}; + //! @brief Return the serialized length of the selected span or replacement buffer. uint64_t size() const { return bytes ? bytes->size() : source.size; } }; +// Output layout node owning small prefixes and child nodes, but borrowing payloads. struct Box { uint32_t type{}; bool extended{}; @@ -98,11 +113,13 @@ struct Box { uint8_t header{}; }; +// Map a retained input interval to its absolute position in the compact output. struct Relocation { BmffSpan source; uint64_t destination{}; }; +// Measure descendants first, promoting box headers when a 32-bit size cannot fit. void measure(Box& box) { uint64_t payload = box.prefix.size(); for (auto& child : box.children) { @@ -111,15 +128,18 @@ void measure(Box& box) { } for (const auto& chunk : box.chunks) payload = add(payload, chunk.size()); + + // Header promotion is monotonic, including the extra UUID header bytes. const unsigned uuidSize = box.type == bmffType("uuid") ? 16 : 0; box.extended |= add(payload, 8 + uuidSize) > max32; box.header = static_cast((box.extended ? 16 : 8) + uuidSize); box.size = add(box.header, payload); } -//! Unite only ranges from the same source payload. Original item boundaries stay in iloc. +//! @brief Unite only ranges from the same source payload. Original item boundaries stay in iloc. void mergeRanges(std::vector& spans) { std::sort(spans.begin(), spans.end(), [](auto a, auto b) { return a.offset < b.offset; }); + size_t count = 0; for (const auto span : spans) { if (count && span.offset <= end(spans[count - 1])) { @@ -129,24 +149,32 @@ void mergeRanges(std::vector& spans) { spans[count++] = span; } } + spans.resize(count); } +// Prepare, emit, and verify a compact container without transferring it to the source. class Rewrite { public: + //! @brief Borrow both streams and the original model; keep a separate model for the edit. Rewrite(BasicIo& input, BasicIo& output, const BmffDocument& original) : input_(input), output_(output), original_(original), document_(original) { } + //! @brief Validate the edit, converge its layout, and verify the prepared output. void run(const BmffMetadataUpdate& update) { require(&input_ != &output_ && input_.isopen() && output_.isopen() && output_.size() == 0); require(input_.size() == original_.fileSize); enforceHeifWriteSupport(original_); + + // Check graph and byte ownership before preparing any output. select(bmffType("Exif"), update.exif); select(bmffType("mime"), update.xmp); validateReferences(); collectRanges(); applyUpdates(); + + // Index retained structures and normalize field widths before layout iteration. for (const auto& entry : document_.associations) associations_[entry.box.offset].push_back(&entry); indexBoxes(original_.boxes); @@ -158,8 +186,12 @@ class Rewrite { const auto size = locate(boxes); if (relocate()) continue; + + // Rebuild offset-bearing boxes with the now-resolved positions. boxes = build(); require(locate(boxes) == size); + + // Only a stable layout may be emitted and compared with the requested result. output_.seekOrThrow(0, BasicIo::beg, ErrorCode::kerImageWriteFailed); for (const auto& box : boxes) emit(box); @@ -167,13 +199,16 @@ class Rewrite { verify(boxes); return; } + throw Error(ErrorCode::kerCorruptedMetadata); } private: + // Preserve absent updates; otherwise remove old primary items and retain any replacement. void select(uint32_t type, const std::optional& value) { if (!value) return; + supported(value->size() <= bmffMetadataLimit, "metadata exceeds the allocation limit"); const auto ids = original_.metadataItems(type); removed_.insert(ids.begin(), ids.end()); @@ -181,6 +216,7 @@ class Rewrite { additions_.emplace(type, &*value); } + // Reject removal of metadata that also participates in retained relationships. void validateReferences() const { for (const auto& ref : original_.references) { if (removed_.contains(ref.from)) { @@ -194,6 +230,7 @@ class Rewrite { } } + // Find the owning media payload, keyed by its absolute start in the input. uint64_t container(const BmffItem& item, BmffSpan span) const { if (item.location.constructionMethod == 1) { require(original_.itemData.has_value()); @@ -201,6 +238,8 @@ class Rewrite { require(span.offset >= data.offset && end(span) <= end(data)); return data.offset; } + + // Method 0 extents belong to the last mdat payload starting at or before them. auto found = std::upper_bound(original_.mediaData.begin(), original_.mediaData.end(), span.offset, [](uint64_t offset, auto range) { return offset < range.offset; }); require(found != original_.mediaData.begin()); @@ -209,6 +248,7 @@ class Rewrite { return found->offset; } + // Collect retained byte unions and prove they do not overlap discarded metadata. void collectRanges() { std::vector discarded; for (const auto& [id, item] : original_.items) { @@ -219,11 +259,15 @@ class Rewrite { ranges_[container(item, extent.source)].push_back(extent.source); } } + + // Copy each retained byte once, even when several items share that byte. std::vector retained; for (auto& [offset, spans] : ranges_) { mergeRanges(spans); retained.insert(retained.end(), spans.begin(), spans.end()); } + + // Removal is impossible when another item still needs any discarded byte. mergeRanges(discarded); size_t next = 0; for (const auto span : discarded) { @@ -234,11 +278,14 @@ class Rewrite { } } + // Prefer an ID above the existing set, falling back to its first gap at the limit. uint32_t allocateId() const { require(!document_.items.empty()); const auto greatest = document_.items.rbegin()->first; if (greatest != max32) return greatest + 1; + + // At the maximum ID, search existing gaps rather than wrapping the counter. uint32_t id = 1; for (const auto& [used, item] : document_.items) { if (used != id) @@ -249,13 +296,17 @@ class Rewrite { return id; } + // Remove old metadata records and create primary-image descriptions for replacements. void applyUpdates() { + // Drop the removed items and all structures owned by those metadata items. for (const auto id : removed_) document_.items.erase(id); std::erase_if(document_.infoOrder, [&](auto id) { return removed_.contains(id); }); std::erase_if(document_.locationOrder, [&](auto id) { return removed_.contains(id); }); std::erase_if(document_.references, [&](const auto& ref) { return removed_.contains(ref.from); }); std::erase_if(document_.associations, [&](const auto& entry) { return removed_.contains(entry.itemId); }); + + // Every replacement gets a new description and a cdsc link to the primary image. for (const auto& [type, bytes] : additions_) { require(document_.items.size() < BmffLimits{}.maxItems); const auto id = allocateId(); @@ -266,6 +317,7 @@ class Rewrite { item.info.name = type == bmffType("Exif") ? "Exif" : "XMP"; if (type == bmffType("mime")) item.info.contentType = "application/rdf+xml"; + item.location.dataSize = bytes->size(); item.location.extents.push_back({0, 0, bytes->size(), {}}); document_.items.emplace(id, std::move(item)); @@ -276,6 +328,7 @@ class Rewrite { } } + // Index original spans for preserving unchanged box headers and payloads. void indexBoxes(const std::vector& boxes) { for (const auto& box : boxes) { originalBoxes_.emplace(box.span.offset, &box); @@ -283,6 +336,7 @@ class Rewrite { } } + // Normalize base offsets and choose widths/versions before measuring output layout. void normalizeLocations() { auto& format = document_.locationFormat; format.offsetSize = 4; @@ -290,6 +344,8 @@ class Rewrite { format.baseOffsetSize = 0; if (document_.items.rbegin()->first > max16 || document_.items.size() > max16) format.version = 2; + + // Preserve idat addressing, but eliminate per-item base offsets in the new layout. for (auto& [id, item] : document_.items) { item.location.baseOffset = 0; if (item.location.constructionMethod == 1) @@ -300,10 +356,12 @@ class Rewrite { } } + // Preserve existing infe entries or serialize a description for a new metadata item. Box itemInfo(uint32_t id) const { const auto& info = document_.items.at(id).info; if (info.box.size) return opaque(*originalBoxes_.at(info.box.offset)); + Box box; box.type = bmffType("infe"); box.prefix = full(info.version, info.flags); @@ -315,9 +373,11 @@ class Rewrite { string(box.prefix, info.contentType); string(box.prefix, info.contentEncoding); } + return box; } + // Serialize current item locations with the widths selected for this layout pass. Bytes locations() const { const auto& format = document_.locationFormat; auto bytes = full(format.version); @@ -325,6 +385,8 @@ class Rewrite { number(bytes, format.indexSize, 1); const unsigned width = format.version == 2 ? 4 : 2; number(bytes, document_.items.size(), width); + + // Retain location-table order while writing normalized extent coordinates. for (const auto id : document_.locationOrder) { const auto& loc = document_.items.at(id).location; number(bytes, id, width); @@ -340,9 +402,11 @@ class Rewrite { number(bytes, extent.length, format.lengthSize); } } + return bytes; } + // Rebuild directed references, widening IDs while retaining original child ordering. Box references(const BmffBox* original = nullptr) const { Box box; box.type = bmffType("iref"); @@ -351,6 +415,8 @@ class Rewrite { if (document_.items.rbegin()->first > max16) version = 1; box.prefix = full(version); + + // Relationships retain their direction and destination order. for (const auto& ref : document_.references) { Box child; child.type = ref.type; @@ -362,9 +428,11 @@ class Rewrite { number(child.prefix, id, version ? 4 : 2); box.children.push_back(std::move(child)); } + return box; } + // Represent an unchanged payload as a borrowed range rather than an allocated copy. static Box opaque(const BmffBox& original) { Box box; box.type = original.type; @@ -374,6 +442,7 @@ class Rewrite { return box; } + // Rebuild modeled structures; preserve opaque bytes only after the write gate accepts them. std::optional rebuild(const BmffBox& original, bool property = false) const { auto box = opaque(original); if (padding(box.type)) { @@ -381,6 +450,7 @@ class Rewrite { return {}; box.chunks.clear(); // Keep indexed property slots; discard their padding bytes. } else if (box.type == bmffType("mdat") || box.type == bmffType("idat")) { + // Build media solely from retained ranges, excluding old metadata and gaps. box.chunks.clear(); const auto found = ranges_.find(original.payload().offset); if (found == ranges_.end()) @@ -402,6 +472,7 @@ class Rewrite { } else if (box.type == bmffType("iref")) { box = references(&original); } else if (box.type == bmffType("ipma")) { + // Keep property slots stable while removing associations owned by deleted items. box.chunks.clear(); const auto format = *original.fullBox; box.prefix = full(format.version, format.flags); @@ -422,6 +493,8 @@ class Rewrite { box.chunks.clear(); if (original.fullBox) box.prefix = full(original.fullBox->version, original.fullBox->flags); + + // Recurse in original order and add an iref box only if the edit first needs one. bool hasReferences = false; for (const auto& child : original.children) { hasReferences |= child.type == bmffType("iref"); @@ -433,14 +506,18 @@ class Rewrite { if (box.type == bmffType("dref")) number(box.prefix, box.children.size(), 4); } + return box; } + // Preserve top-level ordering and append one media box for replacement metadata. std::vector build() const { std::vector boxes; for (const auto& box : original_.boxes) if (auto rebuilt = rebuild(box)) boxes.push_back(std::move(*rebuilt)); + + // New metadata lives in one appended mdat; existing image bytes are not duplicated. if (!newItems_.empty()) { Box box; box.type = bmffType("mdat"); @@ -448,9 +525,11 @@ class Rewrite { box.chunks.push_back({{}, bytes, id}); boxes.push_back(std::move(box)); } + return boxes; } + // Assign absolute output positions and collect mappings for retained media ranges. uint64_t locate(Box& box, uint64_t offset) { box.position = offset; auto position = add(add(offset, box.header), box.prefix.size()); @@ -459,6 +538,7 @@ class Rewrite { for (auto& child : box.children) position = locate(child, position); for (auto& chunk : box.chunks) { + // Remember new metadata positions separately from retained source-range mappings. chunk.position = position; if (chunk.bytes) newPositions_.emplace(chunk.item, position); @@ -466,24 +546,30 @@ class Rewrite { relocations_.push_back({chunk.source, position}); position = add(position, chunk.size()); } + require(position == add(offset, box.size)); return position; } + // Measure the whole output and rebuild its source-to-destination lookup tables. uint64_t locate(std::vector& boxes) { relocations_.clear(); newPositions_.clear(); idatPosition_ = 0; uint64_t offset = 0; + for (auto& box : boxes) { measure(box); offset = locate(box, offset); } + + // A sorted mapping lets each retained extent find its containing interval. std::sort(relocations_.begin(), relocations_.end(), [](const auto& a, const auto& b) { return a.source.offset < b.source.offset; }); return offset; } + // Update iloc offsets from the layout; report whether widening requires another pass. bool relocate() { bool promoted = false; for (auto& [id, item] : document_.items) { @@ -500,6 +586,8 @@ class Rewrite { require(extent.source.offset >= found->source.offset && end(extent.source) <= end(found->source)); position = add(found->destination, extent.source.offset - found->source.offset); } + + // Convert absolute output positions back to the coordinate system required by iloc. const auto base = location.constructionMethod == 1 ? idatPosition_ : 0; require(position >= base); extent.offset = position - base; @@ -509,11 +597,14 @@ class Rewrite { } } } + return promoted; } + // Stream a measured box using bounded buffers for all borrowed payload ranges. void emit(const Box& box) { require(output_.tell() == box.position); + Bytes header; number(header, box.extended ? 1 : box.size, 4); number(header, box.type, 4); @@ -525,6 +616,8 @@ class Rewrite { write(output_, box.prefix.data(), box.prefix.size()); for (const auto& child : box.children) emit(child); + + // After writing structure, stream payload chunks without loading entire images. auto& buffer = copyBuffer_; for (const auto& chunk : box.chunks) { require(output_.tell() == chunk.position); @@ -541,9 +634,11 @@ class Rewrite { } } + // Compare emitted payloads to their source ranges or replacement buffers in bounded chunks. void verifyBytes(const Box& box) { for (const auto& child : box.children) verifyBytes(child); + auto& a = copyBuffer_; auto& b = verifyBuffer_; for (const auto& chunk : box.chunks) { @@ -561,13 +656,18 @@ class Rewrite { } } + // Reparse the output and check item identity, relocated addressing, relationships, and bytes. void verify(const std::vector& boxes) { const auto parsed = parseBmff(output_); + + // The prepared structure must describe the same retained images and item ordering. enforceHeifWriteSupport(parsed); require(parsed.majorBrand == document_.majorBrand && parsed.minorVersion == document_.minorVersion && parsed.compatibleBrands == document_.compatibleBrands && parsed.primaryItem == document_.primaryItem && parsed.infoOrder == document_.infoOrder && parsed.locationOrder == document_.locationOrder && parsed.items.size() == document_.items.size()); + + // Check every item description and each relocated extent against the planned model. for (const auto& [id, item] : document_.items) { const auto& actual = parsed.items.at(id); const auto& info = item.info; @@ -584,6 +684,8 @@ class Rewrite { require(a.index == e.index && a.offset == e.offset && a.length == e.length); } } + + // Relationships and property associations must survive with identical meanings. require(parsed.references.size() == document_.references.size() && parsed.associations.size() == document_.associations.size() && parsed.properties.size() == document_.properties.size()); @@ -602,6 +704,8 @@ class Rewrite { } for (size_t i = 0; i < document_.properties.size(); ++i) require(parsed.properties[i].type == document_.properties[i].type); + + // Structural agreement alone is insufficient; verify every copied or generated byte. for (const auto& box : boxes) verifyBytes(box); } @@ -628,6 +732,8 @@ class Rewrite { std::vector readBmffItem(BasicIo& input, const BmffItem& item, uint64_t limit) { supported(item.location.dataSize <= limit && item.location.dataSize <= std::numeric_limits::max(), "metadata exceeds the allocation limit"); + + // Gather the requested item only after bounding its aggregate allocation. Bytes bytes(static_cast(item.location.dataSize)); size_t position = 0; for (const auto& extent : item.location.extents) { From c7964e45da73526c60d344839e641a1e3c833b10 Mon Sep 17 00:00:00 2001 From: Vaclav Haisman Date: Sat, 10 Oct 2026 01:20:21 +0200 Subject: [PATCH 16/40] [docs] Document the internal HEIF factory and type probe Describe factory ownership and probe positioning without promising that a recognized container supports metadata writing. --- src/heifimage_int.hpp | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/src/heifimage_int.hpp b/src/heifimage_int.hpp index b97c4a723c..070c7ede30 100644 --- a/src/heifimage_int.hpp +++ b/src/heifimage_int.hpp @@ -9,7 +9,24 @@ #include "image.hpp" namespace Exiv2::Internal { + +/*! + @brief Create the private HEIF image implementation for the image factory. + @param io Source stream whose ownership passes to the returned image. + @param params Image construction and metadata decoding parameters. + @return An owning image pointer, or nullptr if the image's initial good() check fails. + */ Image::UniquePtr newHeifInstance(std::unique_ptr io, const ImageCtorParams& params); + +/*! + @brief Probe the leading ftyp box for a supported HEIF major brand, excluding AVIF. + @param io Borrowed, open, seekable input positioned at the candidate ftyp header. + @param advance Keep the consumed position on a match; otherwise seek back to the starting position. + @return True for a complete, bounded brand table accepted by the HEIF factory probe. + + A failed match also seeks back. This probe does not validate the complete item + layout or promise that a later metadata write will be supported. + */ bool isHeifType(BasicIo& io, bool advance); } // namespace Exiv2::Internal #endif From e4be78efb21fb604e829c1294b63c8c686d73b07 Mon Sep 17 00:00:00 2001 From: Vaclav Haisman Date: Sat, 10 Oct 2026 01:20:21 +0200 Subject: [PATCH 17/40] [docs] Explain HEIF metadata editing and transfer steps Describe metadata precedence, embedded XMP handling, fresh serialization and staging lifetime. Clarify cleanup intent and final-transfer limits. --- src/heifimage_int.cpp | 153 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 153 insertions(+) diff --git a/src/heifimage_int.cpp b/src/heifimage_int.cpp index a8f4a4c9e0..237b667f3d 100644 --- a/src/heifimage_int.cpp +++ b/src/heifimage_int.cpp @@ -33,11 +33,13 @@ namespace Exiv2::Internal { namespace { using Bytes = std::vector; +// Reject unsupported edits before they can replace the source stream. void supported(bool condition, std::string_view reason) { if (!condition) throw Error(ErrorCode::kerErrorMessage, std::string("Unsupported HEIF edit: ") + std::string(reason)); } +// Read a bounded property payload from a validated absolute input span. Bytes readRange(BasicIo& io, BmffSpan span) { supported(span.size <= bmffMetadataLimit, "metadata exceeds the allocation limit"); Bytes bytes(static_cast(span.size)); @@ -46,9 +48,11 @@ Bytes readRange(BasicIo& io, BmffSpan span) { return bytes; } +// Serialize structured XMP compactly; empty data denotes an absent packet. std::string encodeXmp(const XmpData& data) { if (data.empty()) return {}; + std::string packet; enforce(XmpParser::encode(packet, data, XmpParser::useCompactFormat | XmpParser::omitAllFormatting) == 0, ErrorCode::kerInvalidXMP); @@ -61,9 +65,11 @@ std::string encodeXmp(const XmpData& data) { template class MetadataMerger { public: + //! @brief Merge the next item, retaining duplicate Exif values within its winning key group. void add(const Data& source, bool preserveDuplicates = false) { std::set seen; for (const auto& datum : source) { + // Remove a superseded group once, but preserve duplicates within the incoming Exif item. const auto key = datum.key(); if (!preserveDuplicates || seen.insert(key).second) { if (auto found = index_.find(key); found != index_.end()) { @@ -72,11 +78,13 @@ class MetadataMerger { index_.erase(found); } } + values_.push_back(datum); index_[key].push_back(std::prev(values_.end())); } } + //! @brief Materialize the accumulated metadata in its surviving file order. Data data() const { Data result; for (const auto& datum : values_) @@ -95,6 +103,8 @@ template bool sameData(const Data& a, const Data& b) { if (a.count() != b.count()) return false; + + // Compare canonical raw values and attached data areas, independent of container offsets. auto snapshot = [](const Data& data) { std::multimap> values; uint64_t total = 0; @@ -104,7 +114,9 @@ bool sameData(const Data& a, const Data& b) { Bytes bytes(datum.size()); if (!bytes.empty()) datum.copy(bytes.data(), littleEndian); + supported(datum.value().sizeDataArea() <= bmffMetadataLimit - total, "metadata exceeds the allocation limit"); + auto area = datum.value().dataArea(); total += area.size(); if (!area.empty()) @@ -113,9 +125,11 @@ bool sameData(const Data& a, const Data& b) { } return values; }; + return snapshot(a) == snapshot(b); } +// Decoded primary metadata plus the raw packet and image properties needed for preservation. struct Metadata { ExifData exif; IptcData iptc; @@ -128,16 +142,20 @@ struct Metadata { uint32_t width{}, height{}; }; +// Decode primary-image items in file order and retain the state needed for later writes. Metadata readMetadata(BasicIo& io, const BmffDocument& document, const DecodeParams& params) { Metadata metadata; MetadataMerger exifMerger; MetadataMerger embeddedMerger; uint64_t total = 0; + + // Charge all Exif and XMP payloads to one aggregate allocation budget. auto read = [&](uint32_t id) { auto bytes = readBmffItem(io, document.items.at(id), bmffMetadataLimit - total); total += bytes.size(); return bytes; }; + #ifndef EXV_HAVE_XMP_TOOLKIT // Without a toolkit, preserve packets exactly. Different packets cannot be // merged when several primary metadata items must become one new Exif item. @@ -149,6 +167,7 @@ Metadata readMetadata(BasicIo& io, const BmffDocument& document, const DecodePar }; #endif for (auto id : document.metadataItems(bmffType("Exif"))) { + // Exif offsets are relative to the byte after the four-byte HEIF prefix. auto bytes = read(id); enforce(bytes.size() >= 12, ErrorCode::kerCorruptedMetadata); const auto offset = getULong(bytes.data(), bigEndian); @@ -159,6 +178,8 @@ Metadata readMetadata(BasicIo& io, const BmffDocument& document, const DecodePar auto order = TiffParser::decode(exif, iptc, xmp, bytes.data() + 4 + offset, bytes.size() - 4 - offset, params); enforce(order != invalidByteOrder, ErrorCode::kerCorruptedMetadata); metadata.order = order; + + // Remember embedded packets even when structured XMP decoding is unavailable. if (auto xml = exif.findKey(ExifKey("Exif.Image.XMLPacket")); xml != exif.end()) { metadata.hasEmbeddedXmp = true; #ifndef EXV_HAVE_XMP_TOOLKIT @@ -167,6 +188,8 @@ Metadata readMetadata(BasicIo& io, const BmffDocument& document, const DecodePar rememberPacket(std::string(packet.begin(), packet.end())); #endif } + + // Later Exif items replace earlier keys while retaining their own duplicate values. exifMerger.add(exif, true); for (const auto& datum : iptc) metadata.iptc.add(datum); @@ -174,6 +197,8 @@ Metadata readMetadata(BasicIo& io, const BmffDocument& document, const DecodePar } metadata.exif = exifMerger.data(); metadata.embeddedXmp = embeddedMerger.data(); + + // Separate MIME XMP takes precedence over the XMP embedded in Exif. #ifdef EXV_HAVE_XMP_TOOLKIT MetadataMerger xmpMerger; xmpMerger.add(metadata.embeddedXmp); @@ -192,12 +217,14 @@ Metadata readMetadata(BasicIo& io, const BmffDocument& document, const DecodePar rememberPacket(packet); #endif } + #ifdef EXV_HAVE_XMP_TOOLKIT metadata.xmp = xmpMerger.data(); if (xmpIds.size() != 1 || !metadata.embeddedXmp.empty()) metadata.packet = encodeXmp(metadata.xmp); #endif + // Read dimensions and ICC only from properties associated with the primary item. std::set properties; for (const auto& entry : document.associations) { if (entry.itemId == document.primaryItem) { @@ -220,19 +247,23 @@ Metadata readMetadata(BasicIo& io, const BmffDocument& document, const DecodePar metadata.icc = DataBuf(bytes.data() + 4, bytes.size() - 4); } } + return metadata; } +// Remove every occurrence of a tag, including duplicates from merged metadata. void eraseTag(ExifData& exif, std::string_view key) { exif.erase(std::remove_if(exif.begin(), exif.end(), [&](const auto& d) { return d.key() == key; }), exif.end()); } +// Identify synthesized Canon autofocus fields that cannot be edited independently. bool canonDerived(const Exifdatum& datum) { // These values are synthesized by decodeCanonAFInfo from Canon's 0x0026 // record. ExifParser filters the same read-only fields for JPEG writing. return datum.groupName() == "Canon" && ((datum.tag() >= 0x2600 && datum.tag() <= 0x260e) || datum.tag() == 0x2611); } +// Isolate synthesized autofocus values for read-only consistency checks. ExifData derivedCanonData(const ExifData& data) { ExifData derived; for (const auto& datum : data) @@ -241,6 +272,7 @@ ExifData derivedCanonData(const ExifData& data) { return derived; } +// Exclude regenerated offsets and raw decoded MakerNotes from semantic comparisons. ExifData exifValues(ExifData data) { const bool decodedMakerNote = data.findKey(ExifKey("Exif.MakerNote.ByteOrder")) != data.end(); data.erase(std::remove_if(data.begin(), data.end(), @@ -256,11 +288,13 @@ ExifData exifValues(ExifData data) { return data; } +// Encode a fresh HEIF Exif item and reject serializers that lose requested values. Bytes encodeExif(ExifData exif, const IptcData& iptc, XmpData embedded, ByteOrder order, const DecodeParams& params) { // A fresh tree excludes original TIFF gaps, shortened values and tail bytes. // The serializer reconstructs known MakerNotes and copies retained data areas. const auto requested = exifValues(exif); exif.erase(std::remove_if(exif.begin(), exif.end(), canonDerived), exif.end()); + MemIo output; uint64_t total = 0; for (const auto& datum : exif) { @@ -269,11 +303,17 @@ Bytes encodeExif(ExifData exif, const IptcData& iptc, XmpData embedded, ByteOrde supported(datum.value().sizeDataArea() <= bmffMetadataLimit - total, "Exif exceeds the allocation limit"); total += datum.value().sizeDataArea(); } + + // Use no original TIFF backing buffer, so deleted values cannot survive in slack. TiffParser::encode(output, nullptr, 0, order, exif, iptc, embedded); supported(output.size() <= bmffMetadataLimit - 4, "Exif exceeds the allocation limit"); + + // A zero HEIF Exif offset places the TIFF header immediately after the prefix. Bytes bytes(4 + output.size(), 0); output.seekOrThrow(0, BasicIo::beg, ErrorCode::kerInputDataReadFailed); output.readOrThrow(bytes.data() + 4, bytes.size() - 4); + + // Decode the new item to catch unsupported MakerNote or metadata transformations. ExifData checked; IptcData checkedIptc; XmpData checkedXmp; @@ -282,15 +322,20 @@ Bytes encodeExif(ExifData exif, const IptcData& iptc, XmpData embedded, ByteOrde supported(sameData(requested, exifValues(checked)), "TIFF serializer cannot preserve requested Exif values"); supported(sameData(iptc, checkedIptc), "TIFF serializer cannot preserve embedded IPTC"); supported(encodeXmp(embedded) == encodeXmp(checkedXmp), "TIFF serializer cannot preserve embedded XMP"); + return bytes; } +// Detect media bytes that no current item owns, including stale metadata from older edits. bool hasOrphanedMedia(const BmffDocument& document) { std::vector spans; for (const auto& [id, item] : document.items) for (const auto& extent : item.location.extents) spans.push_back(extent.source); + std::sort(spans.begin(), spans.end(), [](auto a, auto b) { return a.offset < b.offset; }); + + // Measure the union so shared extents do not disguise unreferenced media bytes. uint64_t covered = 0, previousEnd = 0; for (const auto span : spans) { const auto end = span.offset + span.size; @@ -299,6 +344,8 @@ bool hasOrphanedMedia(const BmffDocument& document) { previousEnd = end; } } + + // A gap in either mdat or idat requires compaction even without a metadata edit. uint64_t available = document.itemData ? document.itemData->size : 0; for (const auto span : document.mediaData) available += span.size; @@ -310,62 +357,101 @@ bool hasOrphanedMedia(const BmffDocument& document) { // success for an error. Keep that independent FileIo repair outside this writer. class TransferSource final : public BasicIo { public: + //! @brief Borrow prepared bytes without exposing FileIo-specific transfer behavior. explicit TransferSource(BasicIo& io) : io_(io) { } + + //! @brief Open or rewind the borrowed source for a complete transfer. int open() override { return io_.isopen() ? io_.seek(0, BasicIo::beg) : io_.open(); } + + //! @brief Close the borrowed stream when its transfer consumer finishes. int close() override { return io_.close(); } + + //! @brief Reject direct writes through this read-only view. size_t write(const byte*, size_t) override { throw Error(ErrorCode::kerImageWriteFailed); } + + //! @brief Reject copying another stream into the prepared source. size_t write(BasicIo&) override { throw Error(ErrorCode::kerImageWriteFailed); } + + //! @brief Reject single-byte writes through this view. int putb(byte) override { throw Error(ErrorCode::kerImageWriteFailed); } + + //! @brief Read an owned buffer from the borrowed source. DataBuf read(size_t count) override { return io_.read(count); } + + //! @brief Read into the caller buffer using the borrowed source. size_t read(byte* data, size_t count) override { return io_.read(data, count); } + + //! @brief Read one byte from the borrowed source. int getb() override { return io_.getb(); } + + //! @brief Reject replacing the prepared source through this view. void transfer(BasicIo&) override { throw Error(ErrorCode::kerImageWriteFailed); } + + //! @brief Seek the borrowed source using BasicIo positioning semantics. int seek(int64_t offset, Position position) override { return io_.seek(offset, position); } + + //! @brief Reject mapping, which would expose mutable prepared bytes. byte* mmap(bool = false) override { throw Error(ErrorCode::kerImageWriteFailed); } + + //! @brief Report success because this view never creates a mapping. int munmap() override { return 0; } + + //! @brief Return the borrowed stream position. size_t tell() const override { return io_.tell(); } + + //! @brief Return the prepared byte count. size_t size() const override { return io_.size(); } + + //! @brief Report whether the borrowed stream is open. bool isopen() const override { return io_.isopen(); } + + //! @brief Forward the borrowed stream error state. int error() const override { return io_.error(); } + + //! @brief Forward the borrowed stream end-of-file state. bool eof() const override { return io_.eof(); } + + //! @brief Return the borrowed source path without copying it. const std::string& path() const noexcept override { return io_.path(); } + + //! @brief Reject creation of synthetic contents in a prepared source. void populateFakeData() override { throw Error(ErrorCode::kerImageWriteFailed); } @@ -374,8 +460,10 @@ class TransferSource final : public BasicIo { BasicIo& io_; }; +// Own staging storage and remove any temporary file when preparation or transfer ends. class PreparedOutput { public: + //! @brief Use a private sibling temporary file for FileIo, otherwise an owned MemIo. explicit PreparedOutput(BasicIo& source) { #ifdef EXV_ENABLE_FILESYSTEM if (dynamic_cast(&source)) { @@ -391,6 +479,7 @@ class PreparedOutput { auto file = std::make_unique(name.string()); #endif if (file->open("w+bx") == 0) { + // Restrict staging permissions before retaining the temporary path. std::error_code error; std::filesystem::permissions(name, std::filesystem::perms::owner_read | std::filesystem::perms::owner_write, std::filesystem::perm_options::replace, error); @@ -399,10 +488,12 @@ class PreparedOutput { std::filesystem::remove(name, error); throw Error(ErrorCode::kerImageWriteFailed); } + path_ = name; io_ = std::move(file); return; } + if (errno != EEXIST) throw Error(ErrorCode::kerDataSourceOpenFailed, source.path(), strError()); } @@ -411,9 +502,12 @@ class PreparedOutput { #else (void)source; #endif + + // Memory-backed and filesystem-disabled builds use the same preparation contract. io_ = std::make_unique(); } + //! @brief Close staging storage before removing its temporary path, including on failure. ~PreparedOutput() { io_.reset(); #ifdef EXV_ENABLE_FILESYSTEM @@ -423,6 +517,8 @@ class PreparedOutput { } #endif } + + //! @brief Borrow the open staging stream while this owner remains alive. BasicIo& io() { return *io_; } @@ -437,17 +533,21 @@ class PreparedOutput { // Private subclass supplies edit intent without changing BmffImage's public ABI. class HeifImage final : public BmffImage { public: + //! @brief Own the source stream and register the HEIF metadata capabilities. HeifImage(BasicIo::UniquePtr io, const ImageCtorParams& params) : BmffImage(std::move(io), params) { setTypeSupported(ImageType::heif, mdExif | mdIptc | mdXmp); } + //! @brief Report the MIME type corresponding to the most recently read major brand. std::string mimeType() const override { return brand_ == bmffType("mif1") ? "image/heif" : "image/heic"; } + //! @brief Load the native item model, falling back to the legacy reader for deferred layouts. void readMetadata() override { enforce(io_->open() == 0, ErrorCode::kerDataSourceOpenFailed, io_->path(), strError()); IoCloser closer(*io_); + BmffDocument document; try { document = parseBmff(*io_); @@ -462,28 +562,39 @@ class HeifImage final : public BmffImage { } } + //! @brief Replace Exif data, treating an empty replacement as an explicit removal request. void setExifData(const ExifData& exif) override { Image::setExifData(exif); removeExif_ = exif.empty(); } + + //! @brief Request physical Exif removal even when the decoded view is already empty. void clearExifData() override { Image::clearExifData(); removeExif_ = true; } + + //! @brief Replace structured XMP, or request removal when the replacement is empty. void setXmpData(const XmpData& xmp) override { #ifndef EXV_HAVE_XMP_TOOLKIT supported(xmp.empty(), "structured XMP editing requires the XMP toolkit"); #endif + if (xmp.empty()) Image::clearXmpPacket(); + Image::setXmpData(xmp); removeXmp_ = xmp.empty(); } + + //! @brief Clear both XMP views so a cached packet cannot restore removed metadata. void clearXmpData() override { Image::clearXmpPacket(); Image::clearXmpData(); removeXmp_ = true; } + + //! @brief Select a bounded raw XMP replacement without requiring structured editing support. void setXmpPacket(const std::string& packet) override { supported(packet.size() <= bmffMetadataLimit, "XMP exceeds the allocation limit"); #ifdef EXV_HAVE_XMP_TOOLKIT @@ -492,13 +603,18 @@ class HeifImage final : public BmffImage { xmpPacket_ = packet; xmpData_.clear(); #endif + writeXmpFromPacket(true); removeXmp_ = packet.empty(); } + + //! @brief Request removal of the primary XMP packet from the rewritten output. void clearXmpPacket() override { Image::clearXmpPacket(); removeXmp_ = true; } + + //! @brief Clear writable Exif/XMP categories while retaining unsupported standalone IPTC/ICC state. void clearMetadata() override { clearExifData(); clearXmpPacket(); @@ -506,7 +622,9 @@ class HeifImage final : public BmffImage { // Only the writable categories are cleared; standalone IPTC/ICC edits are unsupported. } + //! @brief Prepare and verify a compact edit before transfer; final transfer is not guaranteed atomic. void writeMetadata() override { + // Reparse current source bytes before deciding whether any edit can be supported. supported(dynamic_cast(io_.get()) == nullptr, "remote I/O"); enforce(io_->open() == 0, ErrorCode::kerDataSourceOpenFailed, io_->path(), strError()); IoCloser closer(*io_); @@ -514,6 +632,8 @@ class HeifImage final : public BmffImage { enforceHeifWriteSupport(document); const DecodeParams params(max_recursion_depth_); auto original = Internal::readMetadata(*io_, document, params); + + // Reject changes to categories that the HEIF writer only preserves. if (loaded_ || !iccProfile_.empty()) supported(iccProfile_.size() == original.icc.size() && (iccProfile_.empty() || @@ -524,6 +644,7 @@ class HeifImage final : public BmffImage { "standalone IPTC editing"); supported(comment_.empty(), "image comments"); + // Deleting the MakerNote also removes its decoded vendor fields from the fresh TIFF tree. auto exif = exifData_; if (original.exif.findKey(ExifKey("Exif.Photo.MakerNote")) != original.exif.end() && exif.findKey(ExifKey("Exif.Photo.MakerNote")) == exif.end()) { @@ -533,6 +654,8 @@ class HeifImage final : public BmffImage { }), exif.end()); } + + // Determine effective edit intent from both explicit clears and mutable metadata views. #ifndef EXV_HAVE_XMP_TOOLKIT supported(xmpData_.empty(), "structured XMP editing requires the XMP toolkit"); #endif @@ -543,15 +666,19 @@ class HeifImage final : public BmffImage { const bool exifChanged = removeExif_ || !sameData(exif, original.exif); supported(!original.needsXmpToolkit || xmpChanged || !exifChanged, "merging different primary XMP packets requires the XMP toolkit"); + + // Promote embedded XMP to its own item when Exif removal would otherwise discard it. BmffMetadataUpdate update; if (xmpChanged || (exifChanged && exif.empty() && original.hasEmbeddedXmp)) update.xmp = Bytes(packet.begin(), packet.end()); + // A separate MIME item becomes authoritative when XMP is edited. Remove its // old embedded TIFF copy so it cannot reappear after removing the MIME item. auto embedded = original.embeddedXmp; #ifdef EXV_HAVE_XMP_TOOLKIT auto xml = exif.findKey(ExifKey("Exif.Image.XMLPacket")); #endif + // Even without a live XMLPacket tag, prior XMP may survive in TIFF slack. const bool embeddedChanged = xmpChanged && !exif.empty(); if (xmpChanged) { @@ -571,24 +698,32 @@ class HeifImage final : public BmffImage { } #endif } + + // Rebuild Exif when its values change or when old embedded XMP must be scrubbed. if (exifChanged || embeddedChanged) { if (exif.findKey(ExifKey("Exif.Canon.AFInfo")) != exif.end() && original.exif.findKey(ExifKey("Exif.Canon.AFInfo")) != original.exif.end()) { supported(sameData(derivedCanonData(exif), derivedCanonData(original.exif)), "Canon synthesized autofocus fields are read-only"); } + if (exif.empty()) update.exif = Bytes{}; else update.exif = encodeExif(exif, original.iptc, embedded, original.order, params); } + + // Preserve byte identity only when neither an edit nor orphaned-media cleanup is pending. if (!update.exif && !update.xmp && !hasOrphanedMedia(document)) return; + // Prepare and decode the complete result before touching the original destination. PreparedOutput prepared(*io_); rewriteBmff(*io_, prepared.io(), document, update); auto verified = Internal::readMetadata(prepared.io(), parseBmff(prepared.io()), params); const auto preparedSize = prepared.io().size(); + + // The final BasicIo transfer can still fail after preparation; it is not an atomic replacement. #ifdef EXV_ENABLE_FILESYSTEM if (dynamic_cast(io_.get())) { TransferSource source(prepared.io()); @@ -598,14 +733,18 @@ class HeifImage final : public BmffImage { { io_->transfer(prepared.io()); } + + // Publish the verified in-memory state only after the transfer reports the expected size. enforce(io_->size() == preparedSize, ErrorCode::kerTransferFailed, io_->path(), "short prepared-output transfer"); assign(std::move(verified)); brand_ = document.majorBrand; } + //! @brief Print metadata or delegate structural tracing without changing pending edits. void printStructure(std::ostream& out, PrintStructureOption option, size_t depth) override { if (!loaded_) readMetadata(); + if (option == kpsXMP) { #ifdef EXV_HAVE_XMP_TOOLKIT std::string packet; @@ -625,6 +764,7 @@ class HeifImage final : public BmffImage { } private: + // Adopt verified metadata and reset edit intent after a successful read or write. void assign(Metadata metadata) { exifData_ = std::move(metadata.exif); iptcData_ = std::move(metadata.iptc); @@ -634,40 +774,53 @@ class HeifImage final : public BmffImage { pixelWidth_ = metadata.width; pixelHeight_ = metadata.height; setByteOrder(metadata.order); + + // The adopted state becomes the new baseline for detecting the next edit. writeXmpFromPacket(false); loaded_ = true; removeExif_ = removeXmp_ = false; } + uint32_t brand_{bmffType("heic")}; bool loaded_{}, removeExif_{}, removeXmp_{}; }; } // namespace bool isHeifType(BasicIo& io, bool advance) { + // Probe only the leading ftyp box, without constructing a metadata reader. const auto start = io.tell(); std::array header{}; bool matched = io.read(header.data(), 8) == 8 && getULong(header.data() + 4, bigEndian) == bmffType("ftyp"); uint64_t size = matched ? getULong(header.data(), bigEndian) : 0; unsigned headerSize = 8; + if (matched && size == 1) { matched = io.read(header.data() + 8, 8) == 8; size = matched ? getULongLong(header.data() + 8, bigEndian) : 0; headerSize = 16; } + + // Accept complete bounded brand tables, including the extended-size header form. matched = matched && size >= headerSize + 8 && size <= BmffLimits{}.maxBytesRead && size <= io.size() - start && (size - headerSize) % 4 == 0; + if (matched) { matched = io.read(header.data(), 8) == 8; const auto brand = getULong(header.data(), bigEndian); matched = matched && (brand == bmffType("heic") || brand == bmffType("heix") || brand == bmffType("mif1")); + + // An AVIF compatible brand keeps generic mif1 files on the read-only path. for (uint64_t offset = headerSize + 8; matched && offset < size; offset += 4) { matched = io.read(header.data(), 4) == 4; const auto compatible = getULong(header.data(), bigEndian); matched = matched && compatible != bmffType("avif") && compatible != bmffType("avis"); } } + + // Failed probes and non-advancing probes restore the caller position. if (!advance || !matched) io.seek(static_cast(start), BasicIo::beg); + return matched; } From 25f9079d36ea03f9a488485943e5d149252aabd3 Mon Sep 17 00:00:00 2001 From: Vaclav Haisman Date: Sat, 10 Oct 2026 01:20:21 +0200 Subject: [PATCH 18/40] [tests] Document BMFF and HEIF test intent Explain fixture layouts, I/O doubles, mutations and preservation checks. Separate setup, editing and assertions without changing test behavior. --- unitTests/test_bmffimage_int.cpp | 418 +++++++++++++++++++++++++++++++ 1 file changed, 418 insertions(+) diff --git a/unitTests/test_bmffimage_int.cpp b/unitTests/test_bmffimage_int.cpp index 0b52b92151..209bd10ddd 100644 --- a/unitTests/test_bmffimage_int.cpp +++ b/unitTests/test_bmffimage_int.cpp @@ -29,36 +29,44 @@ using namespace Exiv2::Internal; namespace { using Bytes = std::vector; +// Append a big-endian field without using the production serializer. void integer(Bytes& output, uint64_t value, unsigned width) { for (unsigned i = width; i != 0; --i) output.push_back(static_cast(value >> ((i - 1) * 8))); } +// Append independently assembled fixture bytes. void append(Bytes& output, const Bytes& value) { output.insert(output.end(), value.begin(), value.end()); } +// Append a null-terminated format string. void string(Bytes& output, std::string_view value) { output.insert(output.end(), value.begin(), value.end()); output.push_back(0); } +// Construct a box with a normal, extended, or end-of-file size header. Bytes box(uint32_t type, const Bytes& payload, bool extended = false, bool toEnd = false) { Bytes result; integer(result, toEnd ? 0 : extended ? 1 : payload.size() + 8, 4); integer(result, type, 4); + if (extended) integer(result, payload.size() + 16, 8); + append(result, payload); return result; } +// Construct the version and flags prefix of a FullBox. Bytes full(uint8_t version = 0, uint32_t flags = 0) { Bytes result; integer(result, (uint32_t{version} << 24) | flags, 4); return result; } +// Locate the first fixture box by its four-character type or fail the test setup. size_t position(const Bytes& bytes, std::string_view type) { const auto found = std::search(bytes.begin(), bytes.end(), type.begin(), type.end()); if (type.size() != 4 || found == bytes.end() || found - bytes.begin() < 4) @@ -66,14 +74,17 @@ size_t position(const Bytes& bytes, std::string_view type) { return static_cast(found - bytes.begin()) - 4; } +// Overwrite a bounded fixture field to construct a specific input mutation. void patch(Bytes& bytes, size_t offset, uint64_t value, unsigned width) { Bytes encoded; integer(encoded, value, width); if (offset > bytes.size() || width > bytes.size() - offset) throw std::runtime_error("invalid fixture patch"); + std::copy(encoded.begin(), encoded.end(), bytes.begin() + offset); } +// Select independently encoded fixture layouts, payloads, and malformed variants. struct Options { std::optional exifPayload, xmpPayload; bool secondExif{}, metadataIdat{}; @@ -115,6 +126,8 @@ Bytes fixture(const Options& opt = {}) { integer(fileType, bmffType("mif1"), 4); integer(fileType, opt.brand, 4); auto ftyp = box(bmffType("ftyp"), fileType, opt.extended); + + // Interleave metadata with two primary-image extents to exercise compaction. const auto exifPayload = opt.exifPayload.value_or(Bytes{'e', 'x', 'i', 'f'}); const auto xmpPayload = opt.xmpPayload.value_or(Bytes{'x', 'm', 'p'}); Bytes payload{'A', 'B'}; @@ -124,6 +137,7 @@ Bytes fixture(const Options& opt = {}) { const unsigned count = opt.noMetadata ? 1 : 3; const unsigned headerSize = opt.extended ? 16 : 8; + // Build meta twice so file-relative media offsets include its final encoded size. auto meta = [&](uint64_t mediaStart) { auto result = full(); auto handler = full(); @@ -133,9 +147,13 @@ Bytes fixture(const Options& opt = {}) { integer(handler, 0, 4); string(handler, ""); append(result, box(bmffType("hdlr"), handler, opt.extended)); + + // Select the primary item using the version-dependent ID width. auto primary = full(opt.primaryVersion); integer(primary, opt.idBase + 1, opt.primaryVersion == 0 ? 2 : 4); append(result, box(bmffType("pitm"), primary, opt.extended)); + + // Describe image, Exif, and XMP items independently of their location table. auto info = full(opt.infoVersion); integer(info, count, opt.infoVersion == 0 ? 2 : 4); for (unsigned i = 1; i <= count; ++i) { @@ -150,6 +168,8 @@ Bytes fixture(const Options& opt = {}) { } append(info, box(bmffType("infe"), entry, opt.extended)); } + + // Encode iloc using the requested widths and coordinate origins. auto locations = full(opt.locationVersion); integer(locations, (opt.offsetWidth << 4) | opt.lengthWidth, 1); integer(locations, (opt.baseWidth << 4) | opt.indexWidth, 1); @@ -163,6 +183,8 @@ Bytes fixture(const Options& opt = {}) { integer(locations, inIdat ? 1 : 0, 2); integer(locations, 0, 2); integer(locations, opt.offsetWidth == 0 ? source + itemOffset : source, opt.baseWidth); + + // Split the primary image around metadata when the offset fields allow it. const bool fragmented = i == 1 && opt.offsetWidth != 0; integer(locations, fragmented ? 2 : 1, 2); integer(locations, 0, opt.indexWidth); @@ -178,10 +200,14 @@ Bytes fixture(const Options& opt = {}) { integer(locations, 2, opt.lengthWidth); } } + + // Allow either table order to catch parsers that require info before locations. auto iloc = box(bmffType("iloc"), locations, opt.extended); auto iinf = box(bmffType("iinf"), info, opt.extended); append(result, opt.locationFirst ? iloc : iinf); append(result, opt.locationFirst ? iinf : iloc); + + // Associate metadata with the primary image, optionally sharing it with another item. if (!opt.noReferences && !opt.noMetadata) { auto references = full(opt.referenceVersion); for (unsigned i = 2; i <= count; ++i) { @@ -196,6 +222,8 @@ Bytes fixture(const Options& opt = {}) { } append(result, box(bmffType("iref"), references, opt.extended)); } + + // Construct image properties and optional auxiliary-image type information. Bytes properties; for (unsigned i = 0; i < opt.propertyCount; ++i) { auto value = full(); @@ -209,6 +237,8 @@ Bytes fixture(const Options& opt = {}) { append(properties, box(opt.propertyType, value, opt.extended)); } } + + // Keep property associations one-based, including the optional wide index form. auto iprp = box(bmffType("ipco"), properties, opt.extended); auto associations = full(opt.associationVersion, opt.wideProperties ? 1 : 0); integer(associations, opt.auxiliaryType.empty() ? 1 : 2, 4); @@ -222,11 +252,15 @@ Bytes fixture(const Options& opt = {}) { integer(associations, opt.propertyCount, opt.wideProperties ? 2 : 1); append(iprp, box(bmffType("ipma"), associations, opt.extended)); append(result, box(bmffType("iprp"), iprp, opt.extended)); + + // Embed idat storage only for fixtures using method-1 construction. if (opt.idat) append(result, box(bmffType("idat"), payload, opt.extended)); append(result, opt.extraMeta); return box(bmffType("meta"), result, opt.extended); }; + + // Measure meta before supplying the absolute start of the mdat payload. auto metadata = meta(0); metadata = meta(ftyp.size() + metadata.size() + opt.extraRoot.size() + headerSize); append(ftyp, metadata); @@ -235,15 +269,18 @@ Bytes fixture(const Options& opt = {}) { return ftyp; } +// Parse borrowed fixture bytes with optional resource limits. BmffDocument parse(const Bytes& bytes, const BmffLimits& limits = {}) { MemIo input(bytes.data(), bytes.size()); return parseBmff(input, limits); } +// Assert that a malformed fixture is rejected by the container parser. void rejects(const Bytes& bytes) { EXPECT_THROW(parse(bytes), Error); } +// Gather item bytes independently from their checked absolute source ranges. Bytes payload(const Bytes& file, const BmffItem& item) { Bytes result; for (const auto& extent : item.location.extents) { @@ -257,6 +294,7 @@ Bytes payload(const Bytes& file, const BmffItem& item) { } // namespace +// Retain the complete item graph and fragmented payload coordinates. TEST(BmffModel, retainsAllItemsExtentsAndMetadataAssociations) { const auto bytes = fixture(); const auto document = parse(bytes); @@ -270,6 +308,7 @@ TEST(BmffModel, retainsAllItemsExtentsAndMetadataAssociations) { EXPECT_EQ(document.metadataItems(bmffType("mime")), (std::vector{3})); EXPECT_EQ(document.items.at(3).info.contentType, "application/rdf+xml"); EXPECT_EQ(document.items.at(2).info.flags, 1u); + EXPECT_EQ(document.items.at(1).location.extents.size(), 2u); EXPECT_EQ(document.items.at(1).location.dataSize, 4u); EXPECT_EQ(payload(bytes, document.items.at(1)), (Bytes{'A', 'B', 'C', 'D'})); @@ -281,6 +320,7 @@ TEST(BmffModel, retainsAllItemsExtentsAndMetadataAssociations) { EXPECT_FALSE(document.associations.front().properties.back().essential); } +// Resolve item records independently of box order and explicit base offsets. TEST(BmffModel, acceptsLocationBeforeInfoAndExplicitBaseOffsets) { Options opt; opt.locationFirst = true; @@ -288,9 +328,11 @@ TEST(BmffModel, acceptsLocationBeforeInfoAndExplicitBaseOffsets) { const auto bytes = fixture(opt); const auto document = parse(bytes); EXPECT_GT(document.items.at(1).location.baseOffset, 0u); + EXPECT_EQ(payload(bytes, document.items.at(1)), (Bytes{'A', 'B', 'C', 'D'})); } +// Resolve idat extents from the payload origin, distinct from file offsets. TEST(BmffModel, resolvesIdatRelativeDataWithoutConfusingItWithFileOffsets) { Options opt; opt.idat = true; @@ -299,11 +341,13 @@ TEST(BmffModel, resolvesIdatRelativeDataWithoutConfusingItWithFileOffsets) { const auto document = parse(bytes); ASSERT_TRUE(document.itemData.has_value()); EXPECT_EQ(document.items.at(1).location.constructionMethod, 1u); + EXPECT_EQ(document.items.at(1).location.extents.front().source.offset, document.itemData->offset); EXPECT_EQ(payload(bytes, document.items.at(1)), (Bytes{'A', 'B', 'C', 'D'})); EXPECT_NO_THROW(enforceHeifWriteSupport(document)); } +// Preserve version-dependent wide IDs, offsets, and property indices. TEST(BmffModel, retains32BitIds64BitFieldsAndWidePropertyIndices) { Options opt; opt.idBase = 65536; @@ -316,6 +360,7 @@ TEST(BmffModel, retains32BitIds64BitFieldsAndWidePropertyIndices) { opt.offsetWidth = opt.lengthWidth = opt.baseWidth = opt.indexWidth = 8; opt.wideProperties = true; opt.propertyCount = 130; + const auto document = parse(fixture(opt)); EXPECT_EQ(document.primaryItem, 65537u); EXPECT_EQ(document.metadataItems(bmffType("Exif")), (std::vector{65538})); @@ -324,23 +369,29 @@ TEST(BmffModel, retains32BitIds64BitFieldsAndWidePropertyIndices) { EXPECT_EQ(document.items.at(65537).info.version, 3u); } +// Allow item locations expressed entirely through their base offsets. TEST(BmffModel, acceptsZeroOffsetWidthAndNonzeroBaseOffsets) { Options opt; opt.offsetWidth = 0; opt.baseWidth = 8; const auto bytes = fixture(opt); + const auto document = parse(bytes); EXPECT_EQ(document.locationFormat.offsetSize, 0u); EXPECT_EQ(payload(bytes, document.items.at(2)), (Bytes{'e', 'x', 'i', 'f'})); } +// Retain both extended-size and end-of-file box representations. TEST(BmffModel, preservesExtendedHeadersAndTerminalMediaBox) { Options opt; opt.extended = true; auto bytes = fixture(opt); + auto document = parse(bytes); EXPECT_EQ(document.boxes.front().headerSize, 16u); EXPECT_EQ(payload(bytes, document.items.at(1)), (Bytes{'A', 'B', 'C', 'D'})); + + // A terminal mdat consumes the remainder of the file without an explicit size. opt.extended = false; opt.terminal = true; bytes = fixture(opt); @@ -349,13 +400,17 @@ TEST(BmffModel, preservesExtendedHeadersAndTerminalMediaBox) { EXPECT_EQ(document.boxes.back().span.size, 19u); } +// Accept images without metadata and retain metadata lacking primary associations. TEST(BmffModel, acceptsMetadataFreeFilesAndMissingReferences) { Options opt; opt.noMetadata = true; auto document = parse(fixture(opt)); + EXPECT_EQ(document.items.size(), 1u); EXPECT_TRUE(document.metadataItems(bmffType("Exif")).empty()); EXPECT_NO_THROW(enforceHeifWriteSupport(document)); + + // Unassociated metadata remains readable even without an iref box. opt.noMetadata = false; opt.noReferences = true; document = parse(fixture(opt)); @@ -363,14 +418,18 @@ TEST(BmffModel, acceptsMetadataFreeFilesAndMissingReferences) { EXPECT_TRUE(document.metadataItems(bmffType("Exif")).empty()); } +// Keep shared metadata and interpret cdsc references in their declared direction. TEST(BmffModel, preservesSharedMetadataAndReferenceDirection) { Options opt; opt.sharedMetadata = true; auto bytes = fixture(opt); auto document = parse(bytes); + EXPECT_EQ(document.references.front().from, 2u); EXPECT_EQ(document.references.front().to, (std::vector{1, 3})); EXPECT_EQ(document.metadataItems(bmffType("Exif")), (std::vector{2})); + + // Reverse cdsc to ensure an image-to-metadata edge is not mistaken for metadata. const auto cdsc = position(bytes, "cdsc"); patch(bytes, cdsc + 8, 1, 2); patch(bytes, cdsc + 12, 2, 2); @@ -378,6 +437,7 @@ TEST(BmffModel, preservesSharedMetadataAndReferenceDirection) { EXPECT_TRUE(document.metadataItems(bmffType("Exif")).empty()); } +// Read opaque structures while refusing to assume they are safe to move. TEST(BmffModel, retainsOpaqueBoxesButRejectsUnprovedRelocation) { Options opt; opt.extraMeta = box(bmffType("zzzz"), {'k', 'e', 'e', 'p'}); @@ -386,13 +446,16 @@ TEST(BmffModel, retainsOpaqueBoxesButRejectsUnprovedRelocation) { const auto& opaque = document.boxes.at(1).children.back(); EXPECT_EQ(opaque.type, bmffType("zzzz")); EXPECT_EQ(opaque.span.offset, position(bytes, "zzzz")); + EXPECT_EQ(opaque.span.size, 12u); EXPECT_THROW(enforceHeifWriteSupport(document), Error); + opt.extraMeta.clear(); opt.extraRoot = box(bmffType("zzzz"), {1, 2, 3}); EXPECT_THROW(enforceHeifWriteSupport(parse(fixture(opt))), Error); opt.extraRoot = box(bmffType("free"), {1, 2, 3}); EXPECT_NO_THROW(enforceHeifWriteSupport(parse(fixture(opt)))); + opt.extraRoot.clear(); opt.propertyType = bmffType("zzzz"); document = parse(fixture(opt)); @@ -400,12 +463,16 @@ TEST(BmffModel, retainsOpaqueBoxesButRejectsUnprovedRelocation) { EXPECT_THROW(enforceHeifWriteSupport(document), Error); } +// Exclude unsupported brands and compressed primary XMP from the write envelope. TEST(BmffModel, rejectsDeferredBrandsAndCompressedPrimaryXmp) { for (const auto brand : {bmffType("avif"), bmffType("avis"), bmffType("crx "), bmffType("jxl ")}) { Options opt; opt.brand = brand; + EXPECT_THROW(enforceHeifWriteSupport(parse(fixture(opt))), Error); } + + // A compressed XMP packet is readable structurally but cannot be rewritten safely. Options opt; opt.encoding = "gzip"; auto document = parse(fixture(opt)); @@ -413,6 +480,7 @@ TEST(BmffModel, rejectsDeferredBrandsAndCompressedPrimaryXmp) { EXPECT_THROW(enforceHeifWriteSupport(document), Error); } +// Reject every incomplete prefix of an otherwise valid container. TEST(BmffModel, rejectsEveryTruncatedPrefix) { const auto complete = fixture(); for (size_t length = 0; length < complete.size(); ++length) { @@ -421,6 +489,7 @@ TEST(BmffModel, rejectsEveryTruncatedPrefix) { } } +// Reject malformed sizes before a child can escape its containing box. TEST(BmffModel, rejectsInvalidHeadersAndContainerBounds) { const auto complete = fixture(); for (const auto size : {uint64_t{2}, uint64_t{7}, uint64_t{0xffffffff}}) { @@ -428,12 +497,16 @@ TEST(BmffModel, rejectsInvalidHeadersAndContainerBounds) { patch(bytes, 0, size, 4); rejects(bytes); } + + // Mutate child bounds independently of top-level size validation. auto bytes = complete; patch(bytes, position(bytes, "infe"), bytes.size(), 4); rejects(bytes); + bytes = complete; patch(bytes, position(bytes, "infe"), 0, 4); rejects(bytes); + Options opt; opt.extended = true; bytes = fixture(opt); @@ -441,6 +514,7 @@ TEST(BmffModel, rejectsInvalidHeadersAndContainerBounds) { rejects(bytes); } +// Reject unimplemented versions and nonzero reserved flags. TEST(BmffModel, rejectsUnsupportedVersionsAndReservedFlags) { for (const auto* type : {"meta", "pitm", "iinf", "infe", "iloc", "iref", "ipma", "hdlr"}) { auto bytes = fixture(); @@ -448,11 +522,14 @@ TEST(BmffModel, rejectsUnsupportedVersionsAndReservedFlags) { patch(bytes, offset + 8, 255, 1); rejects(bytes); } + + // Reserved flags are rejected even when the version is supported. auto bytes = fixture(); patch(bytes, position(bytes, "iloc") + 11, 128, 1); rejects(bytes); } +// Enforce required structure and singleton constraints within each container. TEST(BmffModel, rejectsMissingMandatoryBoxesAndDuplicateSingletons) { for (const auto* type : {"ftyp", "meta", "hdlr", "pitm", "iinf", "iloc", "iprp", "ipco"}) { auto bytes = fixture(); @@ -460,16 +537,20 @@ TEST(BmffModel, rejectsMissingMandatoryBoxesAndDuplicateSingletons) { patch(bytes, offset + 4, bmffType("free"), 4); rejects(bytes); } + + // Duplicate singleton boxes must fail at both nested and root levels. Options opt; auto duplicate = full(); integer(duplicate, 1, 2); opt.extraMeta = box(bmffType("pitm"), duplicate); rejects(fixture(opt)); + opt.extraMeta.clear(); opt.extraRoot = box(bmffType("ftyp"), Bytes(8)); rejects(fixture(opt)); } +// Require unique nonzero IDs with both description and location records. TEST(BmffModel, rejectsDuplicateMissingAndZeroItemIds) { for (const auto id : {0, 1, 42}) { auto bytes = fixture(); @@ -483,54 +564,70 @@ TEST(BmffModel, rejectsDuplicateMissingAndZeroItemIds) { } } +// Validate every item reference and property index after parsing. TEST(BmffModel, rejectsDanglingPrimaryReferencesAndProperties) { auto bytes = fixture(); patch(bytes, position(bytes, "pitm") + 12, 42, 2); rejects(bytes); + bytes = fixture(); patch(bytes, position(bytes, "cdsc") + 8, 42, 2); rejects(bytes); + bytes = fixture(); patch(bytes, position(bytes, "cdsc") + 12, 42, 2); rejects(bytes); + bytes = fixture(); patch(bytes, position(bytes, "ipma") + 16, 42, 2); rejects(bytes); + bytes = fixture(); patch(bytes, position(bytes, "ipma") + 19, 127, 1); rejects(bytes); + bytes = fixture(); patch(bytes, position(bytes, "ipma") + 19, 0x80, 1); rejects(bytes); } +// Reject declared counts that exceed bounded input or disagree with its contents. TEST(BmffModel, rejectsHugeCountsAndCountDisagreement) { for (const auto count : {0u, 2u, 4u, 65535u}) { auto bytes = fixture(); patch(bytes, position(bytes, "iinf") + 12, count, 2); rejects(bytes); } + + // Exercise count mismatches in each independently decoded table. auto bytes = fixture(); patch(bytes, position(bytes, "iloc") + 14, 65535, 2); rejects(bytes); + bytes = fixture(); patch(bytes, position(bytes, "iloc") + 20, 65535, 2); rejects(bytes); + bytes = fixture(); patch(bytes, position(bytes, "ipma") + 12, 0xffffffff, 4); rejects(bytes); + bytes = fixture(); patch(bytes, position(bytes, "cdsc") + 10, 65535, 2); rejects(bytes); } +// Reject external, protected, and unsupported item storage. TEST(BmffModel, rejectsExternalProtectedAndUnsupportedItemConstruction) { auto bytes = fixture(); patch(bytes, position(bytes, "infe") + 14, 1, 2); rejects(bytes); + + // Nonzero data references and unsupported construction methods cannot resolve locally. bytes = fixture(); patch(bytes, position(bytes, "iloc") + 18, 1, 2); rejects(bytes); + for (const auto method : {2u, 15u, 0x1001u}) { Options opt; opt.locationVersion = 1; @@ -538,6 +635,7 @@ TEST(BmffModel, rejectsExternalProtectedAndUnsupportedItemConstruction) { patch(bytes, position(bytes, "iloc") + 18, method, 2); rejects(bytes); } + Options opt; opt.idat = true; opt.locationVersion = 1; @@ -546,20 +644,25 @@ TEST(BmffModel, rejectsExternalProtectedAndUnsupportedItemConstruction) { rejects(bytes); } +// Reject illegal field widths, empty extents, and out-of-range addressing. TEST(BmffModel, rejectsInvalidWidthsZeroLengthsAndExtentBounds) { for (const auto width : {0u, 1u, 3u, 5u, 9u, 15u}) { auto bytes = fixture(); patch(bytes, position(bytes, "iloc") + 12, 0x40 | width, 1); rejects(bytes); } + for (const auto length : {uint64_t{0}, uint64_t{0xffffffff}}) { auto bytes = fixture(); patch(bytes, position(bytes, "iloc") + 26, length, 4); rejects(bytes); } + + // An extent must stay within media, including when addition would overflow. auto bytes = fixture(); patch(bytes, position(bytes, "iloc") + 22, 0, 4); // Into the ftyp header, not media. rejects(bytes); + Options opt; opt.baseWidth = 8; opt.offsetWidth = 8; @@ -568,6 +671,7 @@ TEST(BmffModel, rejectsInvalidWidthsZeroLengthsAndExtentBounds) { rejects(bytes); } +// Enforce aggregate parsing budgets and bounded terminated strings. TEST(BmffModel, boundsAggregateResourcesAndStrings) { const auto bytes = fixture(); for (unsigned limit = 0; limit < 8; ++limit) { @@ -600,6 +704,8 @@ TEST(BmffModel, boundsAggregateResourcesAndStrings) { } EXPECT_THROW(parse(bytes, limits), Error) << limit; } + + // Check per-string limits and missing terminators separately from aggregate budgets. BmffLimits limits; limits.maxStringLength = 2; EXPECT_THROW(parse(bytes, limits), Error); @@ -609,32 +715,47 @@ TEST(BmffModel, boundsAggregateResourcesAndStrings) { rejects(malformed); } +// Propagate read and seek failures without modifying the borrowed input. TEST(BmffModel, ioFailuresPropagateWithoutWriting) { + // Borrow fixture bytes and inject either a short read or a failed seek. class FailingIo : public MemIo { public: using MemIo::read; + + // Keep the fixture storage borrowed for the lifetime of this test double. explicit FailingIo(const Bytes& bytes) : MemIo(bytes.data(), bytes.size()) { } bool failSeek{}; + + //! @brief Optionally fail seeks before delegating normal positioning to MemIo. int seek(int64_t offset, Position position) override { return failSeek ? 1 : MemIo::seek(offset, position); } + + //! @brief Inject a short read regardless of the requested field. size_t read(byte*, size_t) override { return 0; } }; + const auto bytes = fixture(); FailingIo input(bytes); EXPECT_THROW(parseBmff(input), Error); + + // Exercise seek failure separately from the injected short read. input.failSeek = true; EXPECT_THROW(parseBmff(input), Error); + EXPECT_EQ(input.size(), bytes.size()); EXPECT_EQ(std::memcmp(input.mmap(), bytes.data(), bytes.size()), 0); } +// Parse a virtual large file using only bounded structural reads. TEST(BmffModel, resolvesSparse64BitFileWithoutReadingMediaOrAllocatingItsSize) { if (sizeof(size_t) < 8) GTEST_SKIP() << "BasicIo size() cannot represent this input on a 32-bit host"; + + // Expose an 8 GiB virtual file and detect reads outside its stored structure. class SparseIo : public MemIo { public: using MemIo::read; @@ -645,15 +766,20 @@ TEST(BmffModel, resolvesSparse64BitFileWithoutReadingMediaOrAllocatingItsSize) { size_t bytesRead{}; bool forbiddenRead{}; + //! @brief Report the virtual length without allocating the media payload. size_t size() const override { return static_cast(mediaOffset + 19); } + + //! @brief Accept bounded absolute seeks within the virtual file. int seek(int64_t offset, Position origin) override { if (origin != beg || offset < 0 || static_cast(offset) > size()) return 1; cursor = static_cast(offset); return 0; } + + //! @brief Serve only stored structure and record any attempted media read. size_t read(byte* output, size_t count) override { const auto relative = cursor >= mediaOffset ? cursor - mediaOffset : cursor; const auto& region = cursor >= mediaOffset ? mediaHeader : prefix; @@ -667,6 +793,8 @@ TEST(BmffModel, resolvesSparse64BitFileWithoutReadingMediaOrAllocatingItsSize) { return count; } } input; + + // Place media beyond an extended-size sparse gap exceeding 32-bit offsets. Options opt; opt.noMetadata = true; opt.baseWidth = 8; @@ -679,6 +807,8 @@ TEST(BmffModel, resolvesSparse64BitFileWithoutReadingMediaOrAllocatingItsSize) { integer(input.prefix, gap, 8); integer(input.mediaHeader, 19, 4); integer(input.mediaHeader, bmffType("mdat"), 4); + + // Parse only structural bytes and resolve the large absolute media position. const auto document = parseBmff(input); EXPECT_NO_THROW(enforceHeifWriteSupport(document)); EXPECT_EQ(document.fileSize, input.mediaOffset + 19); @@ -686,10 +816,12 @@ TEST(BmffModel, resolvesSparse64BitFileWithoutReadingMediaOrAllocatingItsSize) { EXPECT_EQ(document.items.at(1).location.extents.at(1).source, (BmffSpan{input.mediaOffset + 14, 2})); EXPECT_EQ(document.boxes.at(2).headerSize, 16u); EXPECT_EQ(document.boxes.at(2).span.size, gap); + EXPECT_FALSE(input.forbiddenRead); EXPECT_LT(input.bytesRead, 1024u); } +// Check UUID header sizes and the known Canon container structure. TEST(BmffModel, validatesUuidHeadersAndKnownCanonContainer) { Options opt; const Bytes uuid{0x85, 0xc0, 0xb6, 0x87, 0x82, 0x0f, 0x11, 0xe0, 0x81, 0x11, 0xf4, 0xce, 0x46, 0x2b, 0x6a, 0x48}; @@ -708,14 +840,17 @@ TEST(BmffModel, validatesUuidHeadersAndKnownCanonContainer) { auto unknown = parse(fixture(opt)); EXPECT_TRUE(unknown.boxes.at(1).children.back().children.empty()); EXPECT_THROW(enforceHeifWriteSupport(unknown), Error); + opt.extraMeta = box(bmffType("uuid"), Bytes(15)); rejects(fixture(opt)); + content = uuid; append(content, box(bmffType("zzzz"), {})); opt.extraMeta = box(bmffType("uuid"), content); EXPECT_THROW(enforceHeifWriteSupport(parse(fixture(opt))), Error); } +// Accept local data references while rejecting external storage and bad counts. TEST(BmffModel, acceptsSelfContainedDataReferenceAndRejectsExternalReferences) { Options opt; auto dataReferences = full(); @@ -724,13 +859,17 @@ TEST(BmffModel, acceptsSelfContainedDataReferenceAndRejectsExternalReferences) { opt.extraMeta = box(bmffType("dinf"), box(bmffType("dref"), dataReferences)); auto bytes = fixture(opt); EXPECT_NO_THROW(enforceHeifWriteSupport(parse(bytes))); + + // Flip the self-contained flag to turn the same reference into external storage. patch(bytes, position(bytes, "url ") + 11, 0, 1); rejects(bytes); + bytes = fixture(opt); patch(bytes, position(bytes, "dref") + 12, 2, 4); rejects(bytes); } +// Allow shared bytes on read while enforcing individual data-box boundaries. TEST(BmffModel, acceptsSharedPayloadRangesButRejectsRangesCrossingDataBounds) { Options opt; opt.baseWidth = 4; @@ -741,28 +880,35 @@ TEST(BmffModel, acceptsSharedPayloadRangesButRejectsRangesCrossingDataBounds) { auto document = parse(bytes); EXPECT_EQ(document.items.at(1).location.extents.at(0).source, document.items.at(1).location.extents.at(1).source); EXPECT_EQ(payload(bytes, document.items.at(1)), (Bytes{'A', 'B', 'A', 'B'})); + + // Reject extents crossing either idat or mdat boundaries. opt.idat = true; opt.locationVersion = 1; bytes = fixture(opt); patch(bytes, position(bytes, "iloc") + 28, 10, 4); // length 2 crosses idat's 11 bytes. rejects(bytes); + bytes = fixture(); // Even an extent inside the file must stay within its own mdat payload. patch(bytes, position(bytes, "iloc") + 22, position(bytes, "mdat") + 7, 4); rejects(bytes); } +// Check span arithmetic at boundary values without allocating a large file. TEST(BmffModel, validatesSpanArithmeticIndependentlyOfInputSize) { BmffBox box; box.headerSize = 8; box.span = {std::numeric_limits::max() - 4, 8}; EXPECT_THROW(static_cast(box.payload()), Error); + box.span = {0, 7}; EXPECT_THROW(static_cast(box.payload()), Error); + box.span = {100, 8}; EXPECT_EQ(box.payload(), (BmffSpan{108, 0})); } +// Keep the generic BMFF image interface read-only. TEST(BmffModel, leavesProductionBmffWriterDisabled) { const auto bytes = fixture(); auto input = std::make_unique(bytes.data(), bytes.size()); @@ -774,6 +920,7 @@ TEST(BmffModel, leavesProductionBmffWriterDisabled) { EXPECT_EQ(std::memcmp(image.io().mmap(), bytes.data(), bytes.size()), 0); } +// Describe a real-file item inventory used independently of the parser output. struct CorpusCase { const char* file; uint32_t primary; @@ -783,21 +930,27 @@ struct CorpusCase { bool heif; }; +// Run the same structural and editing checks over each corpus inventory. class BmffCorpus : public testing::TestWithParam {}; +// Match real-file item inventories independently recorded for the corpus. TEST_P(BmffCorpus, agreesWithIndependentItemInventory) { const auto& expected = GetParam(); FileIo input(std::string(TESTDATA_PATH) + "/" + expected.file); ASSERT_EQ(input.open("rb"), 0); + const auto document = parseBmff(input); EXPECT_EQ(document.primaryItem, expected.primary); EXPECT_EQ(document.items.size(), expected.count); EXPECT_EQ(document.infoOrder.size(), expected.count); EXPECT_EQ(document.locationOrder.size(), expected.count); + const auto exif = document.metadataItems(bmffType("Exif")); const auto xmp = document.metadataItems(bmffType("mime")); EXPECT_EQ(exif, expected.exif ? std::vector{expected.exif} : std::vector{}); EXPECT_EQ(xmp, expected.xmp ? std::vector{expected.xmp} : std::vector{}); + + // Compare write eligibility with the independent format classification. if (expected.heif) { EXPECT_NO_THROW(enforceHeifWriteSupport(document)); } else { @@ -805,6 +958,7 @@ TEST_P(BmffCorpus, agreesWithIndependentItemInventory) { } } +// Use existing corpus files with independently recorded item counts and IDs. INSTANTIATE_TEST_SUITE_P( ExistingFixtures, BmffCorpus, testing::Values(CorpusCase{"Stonehenge.heic", 1, 3, 2, 3, true}, CorpusCase{"IMG_3578.heic", 49, 51, 51, 0, true}, @@ -818,6 +972,7 @@ INSTANTIATE_TEST_SUITE_P( CorpusCase{"avif.avif", 1, 2, 2, 0, false}, CorpusCase{"avif_exif_xmp.avif", 1, 3, 2, 3, false}, CorpusCase{"avif_metadata2.avif", 1, 3, 2, 3, false})); +// Reject non-item formats and malformed inputs from the regression corpus. TEST(BmffModel, rejectsNonItemFormatsAndMalformedRegressionFiles) { for (const auto* file : {"Canon-R6-pruned.CR3", "Reagan.jxl", "issue_2233_poc1.jxl", "issue_2233_poc2.jxl", "issue_1793_poc.heic", "pr_2612_poc.heic"}) { @@ -830,31 +985,38 @@ TEST(BmffModel, rejectsNonItemFormatsAndMalformedRegressionFiles) { namespace { +// Rewrite into separate memory and verify the borrowed source remains unchanged. Bytes rewritten(const Bytes& bytes, const BmffMetadataUpdate& update = {}) { MemIo input(bytes.data(), bytes.size()); MemIo output; rewriteBmff(input, output, parseBmff(input), update); + EXPECT_EQ(input.size(), bytes.size()); EXPECT_EQ(std::memcmp(input.mmap(), bytes.data(), bytes.size()), 0); return Bytes(output.mmap(), output.mmap() + output.size()); } +// Search all file bytes for a canary, including unreferenced storage. bool contains(const Bytes& bytes, std::string_view text) { return std::search(bytes.begin(), bytes.end(), text.begin(), text.end()) != bytes.end(); } +// Append unreachable media bytes to test physical cleanup during rewriting. Bytes withOrphanedBytes(Bytes bytes) { const std::string_view canary = "UNREACHABLE_PRIVATE_METADATA_296bc8"; + const auto media = position(bytes, "mdat"); bytes.insert(bytes.end(), canary.begin(), canary.end()); patch(bytes, media, bytes.size() - media, 4); return bytes; } +// Assert rejection occurs before output is written or source bytes change. void rejectsRewrite(const Bytes& bytes, const BmffMetadataUpdate& update = {}) { MemIo input(bytes.data(), bytes.size()); MemIo output; const auto document = parseBmff(input); + EXPECT_THROW(rewriteBmff(input, output, document, update), Error); EXPECT_EQ(output.size(), 0u); EXPECT_EQ(input.size(), bytes.size()); @@ -863,83 +1025,114 @@ void rejectsRewrite(const Bytes& bytes, const BmffMetadataUpdate& update = {}) { } // namespace +// Discard unreachable bytes and padding while preserving all retained payloads. TEST(BmffRewrite, compactsOrphansAndPaddingWhilePreservingEveryRetainedItem) { Options opt; opt.extraMeta = box(bmffType("free"), {'P', 'R', 'I', 'V', 'A', 'T', 'E'}); opt.extraRoot = box(bmffType("skip"), {'S', 'E', 'C', 'R', 'E', 'T'}); + const auto source = withOrphanedBytes(fixture(opt)); const auto original = parse(source); + const auto bytes = rewritten(source); const auto output = parse(bytes); + + // Check canaries across the entire output, then compare every retained payload. EXPECT_LT(bytes.size(), source.size()); EXPECT_FALSE(contains(bytes, "UNREACHABLE_PRIVATE_METADATA_296bc8")); EXPECT_FALSE(contains(bytes, "PRIVATE")); EXPECT_FALSE(contains(bytes, "SECRET")); + EXPECT_EQ(output.primaryItem, original.primaryItem); + for (const auto& [id, item] : original.items) EXPECT_EQ(payload(source, item), payload(bytes, output.items.at(id))); + + // A second compaction must be byte-for-byte stable. EXPECT_EQ(rewritten(bytes), bytes); } +// Remove primary metadata records, references, and obsolete payload bytes. TEST(BmffRewrite, removesMetadataPayloadsAndTheirReferences) { const auto source = withOrphanedBytes(fixture()); + BmffMetadataUpdate update; update.exif = Bytes{}; update.xmp = Bytes{}; + const auto bytes = rewritten(source, update); const auto output = parse(bytes); + + // Check both graph removal and absence of the discarded payload bytes. ASSERT_EQ(output.items.size(), 1u); EXPECT_TRUE(output.references.empty()); EXPECT_TRUE(output.metadataItems(bmffType("Exif")).empty()); EXPECT_TRUE(output.metadataItems(bmffType("mime")).empty()); + EXPECT_EQ(payload(bytes, output.items.at(1)), (Bytes{'A', 'B', 'C', 'D'})); ASSERT_EQ(output.mediaData.size(), 1u); EXPECT_EQ(output.mediaData.front().size, 4u); + EXPECT_FALSE(contains(bytes, "exif")); EXPECT_FALSE(contains(bytes, "xmp")); EXPECT_FALSE(contains(bytes, "UNREACHABLE_PRIVATE_METADATA_296bc8")); } +// Compact idat and discard stale copies from unreferenced media ranges. TEST(BmffRewrite, repacksIdatAndRemovesUnreferencedMediaCopies) { Options opt; opt.idat = true; opt.locationVersion = 1; auto source = fixture(opt); + const auto loc = position(source, "iloc"); patch(source, loc + 42, 1, 2); // Exif construction method. patch(source, loc + 48, 2, 4); // Exif offset into idat. patch(source, loc + 58, 1, 2); // XMP construction method. patch(source, loc + 64, 8, 4); // XMP offset into idat. + + // Clear both metadata categories while keeping the idat-backed image. BmffMetadataUpdate update; update.exif = Bytes{}; update.xmp = Bytes{}; + const auto bytes = rewritten(source, update); const auto output = parse(bytes); + ASSERT_TRUE(output.itemData.has_value()); EXPECT_EQ(output.itemData->size, 4u); EXPECT_TRUE(output.mediaData.empty()); + const auto& image = output.items.at(1); EXPECT_EQ(image.location.constructionMethod, 1u); EXPECT_EQ(image.location.extents.at(0).offset, 0u); EXPECT_EQ(image.location.extents.at(1).offset, 2u); EXPECT_EQ(payload(bytes, image), (Bytes{'A', 'B', 'C', 'D'})); + EXPECT_FALSE(contains(bytes, "exif")); EXPECT_FALSE(contains(bytes, "xmp")); } +// Insert primary metadata without discarding independent unassociated items. TEST(BmffRewrite, insertsIntoMetadataFreeFilesAndPreservesUnassociatedItems) { Options opt; opt.noMetadata = true; + BmffMetadataUpdate update; update.exif = Bytes{'n', 'e', 'w', 'e', 'x', 'i', 'f'}; update.xmp = Bytes{'n', 'e', 'w', 'x', 'm', 'p'}; + auto bytes = rewritten(fixture(opt), update); auto document = parse(bytes); + + // Check newly allocated primary metadata records and their payloads. ASSERT_EQ(document.items.size(), 3u); ASSERT_EQ(document.metadataItems(bmffType("Exif")).size(), 1u); ASSERT_EQ(document.metadataItems(bmffType("mime")).size(), 1u); EXPECT_EQ(payload(bytes, document.items.at(document.metadataItems(bmffType("Exif")).front())), *update.exif); EXPECT_EQ(payload(bytes, document.items.at(document.metadataItems(bmffType("mime")).front())), *update.xmp); + + // Keep unassociated original metadata when inserting a new primary association. opt.noMetadata = false; opt.noReferences = true; bytes = rewritten(fixture(opt), update); @@ -949,22 +1142,28 @@ TEST(BmffRewrite, insertsIntoMetadataFreeFilesAndPreservesUnassociatedItems) { EXPECT_EQ(payload(bytes, document.items.at(3)), (Bytes{'x', 'm', 'p'})); } +// Keep repeated metadata edits compact and remove earlier payload canaries. TEST(BmffRewrite, replacesGrowsAndShrinksWithoutRetainingEarlierPayloads) { const auto original = fixture(); auto current = original; size_t smallSize = 0; for (unsigned iteration = 0; iteration < 8; ++iteration) { + // Grow metadata with unique canaries, then shrink it in the same edit cycle. const auto previous = "PRIVATE_OLD_VALUE_" + std::to_string(iteration); BmffMetadataUpdate update; update.exif = Bytes(70000, 'q'); update.exif->insert(update.exif->end(), previous.begin(), previous.end()); current = rewritten(current, update); EXPECT_TRUE(contains(current, previous)); + update.exif = Bytes{'n', 'e', 'w'}; current = rewritten(current, update); EXPECT_FALSE(contains(current, previous)); + + // Earlier payloads must disappear without cumulative file growth. const auto output = parse(current); EXPECT_EQ(payload(current, output.items.at(1)), (Bytes{'A', 'B', 'C', 'D'})); + if (iteration == 0) smallSize = current.size(); else @@ -972,14 +1171,19 @@ TEST(BmffRewrite, replacesGrowsAndShrinksWithoutRetainingEarlierPayloads) { } } +// Reject edits whose discarded bytes are still owned by another item. TEST(BmffRewrite, rejectsSharedMetadataAndOverlappingRetainedDataBeforeWriting) { Options opt; opt.sharedMetadata = true; + BmffMetadataUpdate update; update.exif = Bytes{}; rejectsRewrite(fixture(opt), update); + update.exif = Bytes{'n', 'e', 'w'}; rejectsRewrite(fixture(opt), update); + + // A retained image sharing the removed metadata bytes also prevents the edit. auto source = fixture(); const auto loc = position(source, "iloc"); patch(source, loc + 44, position(source, "mdat") + 8, 4); // Exif overlaps first image extent. @@ -989,6 +1193,7 @@ TEST(BmffRewrite, rejectsSharedMetadataAndOverlappingRetainedDataBeforeWriting) EXPECT_EQ(payload(bytes, parse(bytes).items.at(1)), (Bytes{'A', 'B', 'C', 'D'})); } +// Rewrite wide fields and unusual box headers without losing item identities. TEST(BmffRewrite, handlesWideIdsFieldsExtendedAndTerminalHeaders) { Options opt; opt.idBase = 65536; @@ -1001,15 +1206,21 @@ TEST(BmffRewrite, handlesWideIdsFieldsExtendedAndTerminalHeaders) { opt.offsetWidth = opt.lengthWidth = opt.baseWidth = opt.indexWidth = 8; opt.extended = true; opt.wideProperties = true; + BmffMetadataUpdate update; update.exif = Bytes{'r', 'e', 'p', 'l', 'a', 'c', 'e'}; + auto bytes = rewritten(fixture(opt), update); auto output = parse(bytes); + + // Verify wide IDs and field widths remain consistent after replacement. EXPECT_EQ(output.primaryItem, 65537u); EXPECT_EQ(output.locationFormat.version, 2u); EXPECT_EQ(output.items.at(65537).location.baseOffset, 0u); EXPECT_EQ(output.locationFormat.indexSize, 8u); EXPECT_EQ(payload(bytes, output.items.at(65537)), (Bytes{'A', 'B', 'C', 'D'})); + + // Exercise a terminal media box separately from extended-size headers. opt = Options{}; opt.terminal = true; bytes = rewritten(fixture(opt), update); @@ -1018,6 +1229,7 @@ TEST(BmffRewrite, handlesWideIdsFieldsExtendedAndTerminalHeaders) { EXPECT_EQ(output.mediaData.size(), 2u); } +// Find an unused metadata ID even when the highest ID is already occupied. TEST(BmffRewrite, reusesAvailableIdWhenLargestIdIsOccupied) { Options opt; opt.noMetadata = true; @@ -1034,51 +1246,71 @@ TEST(BmffRewrite, reusesAvailableIdWhenLargestIdIsOccupied) { EXPECT_EQ(output.metadataItems(bmffType("Exif")), (std::vector{1})); } +// Preserve property index positions while removing padding payload bytes. TEST(BmffRewrite, keepsIndexedPaddingSlotsButDiscardsTheirBodies) { Options opt; opt.propertyType = bmffType("free"); const auto bytes = rewritten(fixture(opt)); + const auto output = parse(bytes); ASSERT_EQ(output.properties.size(), 2u); EXPECT_EQ(output.properties.front().payload().size, 0u); EXPECT_EQ(output.associations.front().properties.back().index, 2u); } +// Stop on staging I/O failures and preserve the original source bytes. TEST(BmffRewrite, propagatesShortWritesAndReadFailuresWithoutMutatingSource) { + // Limit staging capacity to force a short write during serialization. class ShortOutput : public MemIo { public: using MemIo::write; size_t remaining{70}; + + //! @brief Accept only the bytes that fit in the simulated output capacity. size_t write(const byte* bytes, size_t count) override { const auto n = std::min(count, remaining); remaining -= n; return MemIo::write(bytes, n); } } output; + const auto source = fixture(); MemIo input(source.data(), source.size()); const auto document = parseBmff(input); + EXPECT_THROW(rewriteBmff(input, output, document), Error); EXPECT_EQ(input.size(), source.size()); EXPECT_EQ(std::memcmp(input.mmap(), source.data(), source.size()), 0); + + // Borrow valid fixture bytes but fail payload reads during rewriting. class ShortInput : public MemIo { public: using MemIo::read; + + // Keep the source fixture borrowed for this failure test. explicit ShortInput(const Bytes& bytes) : MemIo(bytes.data(), bytes.size()) { } + + //! @brief Inject an empty read instead of returning the requested source bytes. size_t read(byte*, size_t) override { return 0; } } failing(source); + + // Repeat the failure check with unreadable source payloads and an empty sink. MemIo other; EXPECT_THROW(rewriteBmff(failing, other, document), Error); EXPECT_EQ(std::memcmp(failing.mmap(), source.data(), source.size()), 0); } +// Reject a prepared output whose copied payload differs from the source. TEST(BmffRewrite, detectsCorruptedPreparedOutput) { + // Corrupt a staged payload to exercise post-write byte verification. class CorruptOutput : public MemIo { public: using MemIo::write; + + //! @brief Flip a byte in the recognized payload before storing the output chunk. size_t write(const byte* bytes, size_t count) override { Bytes data(bytes, bytes + count); if (contains(data, "ABexifCDxmp")) @@ -1086,15 +1318,20 @@ TEST(BmffRewrite, detectsCorruptedPreparedOutput) { return MemIo::write(data.data(), data.size()); } } output; + const auto source = fixture(); MemIo input(source.data(), source.size()); + EXPECT_THROW(rewriteBmff(input, output, parseBmff(input)), Error); EXPECT_EQ(std::memcmp(input.mmap(), source.data(), source.size()), 0); } +// Promote offsets beyond 32 bits while bounding copy buffers and allocation. TEST(BmffRewrite, promotesOutputOffsetsAndStreamsLargePayloadsWithBoundedIo) { if (sizeof(size_t) < 8) GTEST_SKIP() << "BasicIo size() cannot represent this input on a 32-bit host"; + + // Represent a large seekable file as stored segments with implicit zero-filled gaps. class SparseIo : public MemIo { public: using MemIo::read; @@ -1105,21 +1342,30 @@ TEST(BmffRewrite, promotesOutputOffsetsAndStreamsLargePayloadsWithBoundedIo) { size_t largestWrite{}; size_t writeCalls{}; + //! @brief Report the virtual file length without materializing its gaps. size_t size() const override { return static_cast(length); } + + //! @brief Return the current absolute position in the virtual file. size_t tell() const override { return static_cast(position); } + + //! @brief Accept bounded absolute seeks in the sparse stream. int seek(int64_t offset, Position origin) override { if (origin != beg || offset < 0 || static_cast(offset) > length) return 1; position = static_cast(offset); return 0; } + + //! @brief Read stored segments over a zero-filled representation of sparse gaps. size_t read(byte* output, size_t count) override { if (position > length || count > length - position) return 0; + + // Fill gaps with zeros, then overlay only intersecting stored segments. std::memset(output, 0, count); auto it = segments.upper_bound(position); if (it != segments.begin()) @@ -1130,9 +1376,12 @@ TEST(BmffRewrite, promotesOutputOffsetsAndStreamsLargePayloadsWithBoundedIo) { if (start < end) std::memcpy(output + start - position, it->second.data() + start - it->first, end - start); } + position += count; return count; } + + //! @brief Track write bounds and retain only chunks needed to reparse the output. size_t write(const byte* data, size_t count) override { largestWrite = std::max(largestWrite, count); ++writeCalls; @@ -1142,11 +1391,14 @@ TEST(BmffRewrite, promotesOutputOffsetsAndStreamsLargePayloadsWithBoundedIo) { segments.emplace(position, Bytes(data, data + count)); else if (data[0] != 0 || data[count - 1] != 0) throw std::runtime_error("unexpected nonzero virtual media"); + position += count; length = std::max(length, position); return count; } } input, output; + + // Construct a small prefix describing a virtual image larger than 4 GiB. Options opt; opt.noMetadata = true; opt.offsetWidth = 0; @@ -1154,6 +1406,7 @@ TEST(BmffRewrite, promotesOutputOffsetsAndStreamsLargePayloadsWithBoundedIo) { auto prefix = fixture(opt); const auto media = position(prefix, "mdat"); prefix.resize(media); + const uint64_t imageSize = (uint64_t{5} << 30) + 7; patch(prefix, position(prefix, "iloc") + 20, media + 16, 8); patch(prefix, position(prefix, "iloc") + 30, imageSize, 8); @@ -1162,17 +1415,24 @@ TEST(BmffRewrite, promotesOutputOffsetsAndStreamsLargePayloadsWithBoundedIo) { integer(prefix, imageSize + 16, 8); input.length = prefix.size() + imageSize; input.segments.emplace(0, prefix); + const auto original = parseBmff(input); + + // Place new metadata beyond the image so output offsets must widen. BmffMetadataUpdate update; update.exif = Bytes{'n', 'e', 'w', '6', '4'}; rewriteBmff(input, output, original, update); + const auto document = parseBmff(output); + + // Verify promoted locations and bounded streaming without allocating the image. EXPECT_EQ(document.locationFormat.offsetSize, 8u); EXPECT_EQ(document.locationFormat.lengthSize, 8u); EXPECT_EQ(document.items.at(1).location.dataSize, imageSize); const auto exif = document.metadataItems(bmffType("Exif")).front(); EXPECT_GT(document.items.at(exif).location.extents.front().offset, std::numeric_limits::max()); EXPECT_EQ(readBmffItem(output, document.items.at(exif)), *update.exif); + EXPECT_LE(output.largestWrite, 64u * 1024); EXPECT_EQ(input.writeCalls, 0u); EXPECT_LT(output.segments.size(), 100u); @@ -1190,13 +1450,17 @@ TEST(BmffRewrite, promotesOutputOffsetsAndStreamsLargePayloadsWithBoundedIo) { EXPECT_EQ(input.writeCalls, 0u); } +// Reject unsupported layouts and unsafe output streams before writing. TEST(BmffRewrite, rejectsUnsupportedLayoutsAndNonemptySinksBeforeWriting) { Options opt; opt.extraMeta = box(bmffType("zzzz"), {1, 2, 3}); rejectsRewrite(fixture(opt)); + opt.extraMeta.clear(); opt.brand = bmffType("avif"); rejectsRewrite(fixture(opt)); + + // Reject both aliased input/output and a separate nonempty staging stream. auto source = fixture(); MemIo input(source.data(), source.size()); MemIo output(source.data(), source.size()); @@ -1207,6 +1471,7 @@ TEST(BmffRewrite, rejectsUnsupportedLayoutsAndNonemptySinksBeforeWriting) { EXPECT_EQ(std::memcmp(output.mmap(), source.data(), source.size()), 0); } +// Preserve corpus payloads on supported rewrites and reject other formats. TEST_P(BmffCorpus, preservesOrRejectsCorpusAccordingToWriteEnvelope) { const auto& expected = GetParam(); FileIo input(std::string(TESTDATA_PATH) + "/" + expected.file); @@ -1218,35 +1483,47 @@ TEST_P(BmffCorpus, preservesOrRejectsCorpusAccordingToWriteEnvelope) { EXPECT_EQ(output.size(), 0u); return; } + + // A preserving rewrite must keep every independently inventoried item payload. rewriteBmff(input, output, original); const auto document = parseBmff(output); for (const auto& [id, item] : original.items) EXPECT_EQ(readBmffItem(input, item), readBmffItem(output, document.items.at(id))) << id; + + // Clear metadata and compare every remaining item against the original stream. BmffMetadataUpdate update; update.exif = Bytes{}; update.xmp = Bytes{}; MemIo stripped; + rewriteBmff(input, stripped, original, update); const auto cleaned = parseBmff(stripped); + EXPECT_TRUE(cleaned.metadataItems(bmffType("Exif")).empty()); EXPECT_TRUE(cleaned.metadataItems(bmffType("mime")).empty()); + for (const auto& [id, item] : cleaned.items) EXPECT_EQ(readBmffItem(input, original.items.at(id)), readBmffItem(stripped, item)) << id; } namespace { + +// Encode fresh TIFF metadata behind the HEIF Exif item offset prefix. Bytes tiffItem(ExifData exif, const XmpData& xmp = {}, ByteOrder order = littleEndian) { MemIo output; TiffParser::encode(output, nullptr, 0, order, exif, IptcData{}, xmp); + Bytes bytes(4, 0); bytes.insert(bytes.end(), output.mmap(), output.mmap() + output.size()); return bytes; } +// Build a metadata-free HEIF fixture, then add independently selected metadata. Bytes heifWithMetadata(const ExifData& exif = {}, std::string_view xmp = {}, ByteOrder order = littleEndian) { Options options; options.noMetadata = true; BmffMetadataUpdate update; + if (!exif.empty()) update.exif = tiffItem(exif, {}, order); if (!xmp.empty()) @@ -1254,6 +1531,7 @@ Bytes heifWithMetadata(const ExifData& exif = {}, std::string_view xmp = {}, Byt return rewritten(fixture(options), update); } +// Open owned fixture storage through ImageFactory and read its metadata. Image::UniquePtr openHeif(const Bytes& bytes) { auto owned = std::make_unique(); owned->write(bytes.data(), bytes.size()); @@ -1264,6 +1542,7 @@ Image::UniquePtr openHeif(const Bytes& bytes) { return image; } +// Construct a minimal raw XMP packet containing a controlled source value. std::string rawXmpSource(std::string_view value) { return "" @@ -1272,6 +1551,7 @@ std::string rawXmpSource(std::string_view value) { std::string(value) + "'/>"; } +// Set equivalent XMP data with or without the structured XMP toolkit. void setHeifXmpSource(Image& image, const std::string& value) { #ifdef EXV_HAVE_XMP_TOOLKIT image.xmpData()["Xmp.dc.source"] = value; @@ -1280,40 +1560,51 @@ void setHeifXmpSource(Image& image, const std::string& value) { #endif } +// Read the complete current image stream for preservation and canary checks. Bytes imageBytes(Image& image) { auto& io = image.io(); io.open(); auto data = io.read(io.size()); + return Bytes(data.c_data(), data.c_data() + data.size()); } } // namespace +// Exercise public metadata edits while preserving encoded image bytes. TEST(HeifImage, addsGrowsShrinksDeletesAndPreservesEncodedImage) { auto image = openHeif(heifWithMetadata()); EXPECT_EQ(image->checkMode(mdExif), amReadWrite); EXPECT_EQ(image->checkMode(mdXmp), amReadWrite); EXPECT_EQ(image->checkMode(mdIptc), amRead); + size_t smallSize = 0; for (unsigned cycle = 0; cycle < 4; ++cycle) { + // Grow metadata using a unique canary for each iteration. const auto canary = "PRIVATE_HEIF_DESCRIPTION_" + std::to_string(cycle); image->exifData()["Exif.Image.ImageDescription"] = std::string(70000, 'v') + canary; setHeifXmpSource(*image, "Příliš žluťoučký kůň — " + canary); ASSERT_NO_THROW(image->writeMetadata()); auto large = imageBytes(*image); EXPECT_TRUE(contains(large, canary)); + + // Shrink the same metadata and require the earlier bytes to disappear. image->exifData()["Exif.Image.ImageDescription"] = "short"; setHeifXmpSource(*image, "short"); ASSERT_NO_THROW(image->writeMetadata()); auto small = imageBytes(*image); EXPECT_FALSE(contains(small, canary)); + auto parsed = parse(small); EXPECT_EQ(payload(small, parsed.items.at(parsed.primaryItem)), (Bytes{'A', 'B', 'C', 'D'})); + if (cycle != 0) { EXPECT_EQ(small.size(), smallSize); } smallSize = small.size(); } + + // Clear both categories and verify that the image payload remains intact. image->clearMetadata(); ASSERT_NO_THROW(image->writeMetadata()); auto clean = imageBytes(*image); @@ -1322,13 +1613,17 @@ TEST(HeifImage, addsGrowsShrinksDeletesAndPreservesEncodedImage) { EXPECT_TRUE(parse(clean).metadataItems(bmffType("mime")).empty()); } +// Preserve a true no-op but compact stale bytes after explicit empty removal. TEST(HeifImage, preservesNoOpAndCleansExplicitEmptyRemoval) { ExifData exif; exif["Exif.Image.Artist"] = "original"; + auto bytes = heifWithMetadata(exif); auto image = openHeif(bytes); image->writeMetadata(); EXPECT_EQ(imageBytes(*image), bytes); + + // An explicit empty removal must compact orphaned bytes even without active metadata. bytes = withOrphanedBytes(heifWithMetadata()); image = openHeif(bytes); image->clearExifData(); @@ -1337,22 +1632,30 @@ TEST(HeifImage, preservesNoOpAndCleansExplicitEmptyRemoval) { EXPECT_FALSE(contains(imageBytes(*image), "UNREACHABLE_PRIVATE_METADATA_296bc8")); } +// Serialize fresh TIFF data so removed tags and original slack disappear. TEST(HeifImage, removesDeletedTagsAndOriginalTiffSlack) { ExifData exif; exif["Exif.Image.Artist"] = "KEEP_ARTIST"; exif["Exif.Photo.UserComment"] = "charset=Ascii PRIVATE_REMOVED_USER_COMMENT_841bb0"; auto item = tiffItem(exif, {}, bigEndian); + + // Plant a canary in TIFF slack that a fresh serialization must discard. const std::string slack = "PRIVATE_UNUSED_TIFF_STORAGE_2223f1"; item.insert(item.end(), slack.begin(), slack.end()); BmffMetadataUpdate update; update.exif = item; auto image = openHeif(rewritten(heifWithMetadata(), update)); + + // Delete a tag and check the full output for both active and stale private bytes. image->exifData().erase(image->exifData().findKey(ExifKey("Exif.Photo.UserComment"))); image->writeMetadata(); auto bytes = imageBytes(*image); + EXPECT_FALSE(contains(bytes, slack)); EXPECT_FALSE(contains(bytes, "PRIVATE_REMOVED_USER_COMMENT_841bb0")); EXPECT_TRUE(contains(bytes, "KEEP_ARTIST")); + + // Verify that fresh serialization preserves the original big-endian TIFF order. auto doc = parse(bytes); auto tiff = payload(bytes, doc.items.at(doc.metadataItems(bmffType("Exif")).front())); ASSERT_GT(tiff.size(), 8u); @@ -1360,6 +1663,7 @@ TEST(HeifImage, removesDeletedTagsAndOriginalTiffSlack) { EXPECT_EQ(tiff[5], 'M'); } +// Apply XMP removal consistently across separate and embedded storage. TEST(HeifImage, clearsEmbeddedXmpAndPreservesItWhenOnlyExifIsRemoved) { #ifndef EXV_HAVE_XMP_TOOLKIT GTEST_SKIP() << "requires structured XMP decoding; raw packet behavior is tested separately"; @@ -1373,17 +1677,23 @@ TEST(HeifImage, clearsEmbeddedXmpAndPreservesItWhenOnlyExifIsRemoved) { auto bytes = rewritten(heifWithMetadata(), update); auto image = openHeif(bytes); ASSERT_FALSE(image->xmpData().empty()); + + // Clear XMP through the image API and check both possible storage forms. image->clearXmpPacket(); image->writeMetadata(); auto cleaned = imageBytes(*image); EXPECT_FALSE(contains(cleaned, "PRIVATE_EMBEDDED_XMP_350597")); EXPECT_TRUE(contains(cleaned, "keep artist")); + + // Deleting the embedded XML tag must also remove its serialized packet. image = openHeif(bytes); auto xml = image->exifData().findKey(ExifKey("Exif.Image.XMLPacket")); ASSERT_NE(xml, image->exifData().end()); image->exifData().erase(xml); image->writeMetadata(); EXPECT_FALSE(contains(imageBytes(*image), "PRIVATE_EMBEDDED_XMP_350597")); + + // Removing only Exif must preserve embedded XMP as separate metadata. image = openHeif(bytes); image->clearExifData(); image->writeMetadata(); @@ -1391,6 +1701,7 @@ TEST(HeifImage, clearsEmbeddedXmpAndPreservesItWhenOnlyExifIsRemoved) { EXPECT_TRUE(image->exifData().empty()); } +// Support raw XMP and metadata copying while rejecting unsupported categories. TEST(HeifImage, usesRawXmpPacketsSetMetadataAndRejectsUnsupportedCategories) { #ifndef EXV_HAVE_XMP_TOOLKIT GTEST_SKIP() << "requires structured XMP decoding; raw packet behavior is tested separately"; @@ -1400,11 +1711,14 @@ TEST(HeifImage, usesRawXmpPacketsSetMetadataAndRejectsUnsupportedCategories) { xmp["Xmp.dc.source"] = "RAW_XMP_říční"; std::string packet; ASSERT_EQ(XmpParser::encode(packet, xmp), 0); + source->setXmpPacket(packet); source->exifData()["Exif.Image.Artist"] = "copied"; source->writeMetadata(); auto bytes = imageBytes(*source); auto doc = parse(bytes); + + // Check raw packet handling and metadata copying through the public API. EXPECT_EQ(payload(bytes, doc.items.at(doc.metadataItems(bmffType("mime")).front())), Bytes(packet.begin(), packet.end())); auto target = openHeif(heifWithMetadata()); @@ -1412,35 +1726,48 @@ TEST(HeifImage, usesRawXmpPacketsSetMetadataAndRejectsUnsupportedCategories) { target->writeMetadata(); EXPECT_EQ(target->exifData()["Exif.Image.Artist"].toString(), "copied"); EXPECT_EQ(target->xmpData()["Xmp.dc.source"].toString(), "RAW_XMP_říční"); + + // Unsupported metadata categories must fail without altering the source. EXPECT_THROW(target->setIptcData(IptcData{}), Error); EXPECT_THROW(target->setComment("comment"), Error); + target->clearXmpData(); target->writeMetadata(); EXPECT_TRUE(target->xmpData().empty()); EXPECT_FALSE(contains(imageBytes(*target), "RAW_XMP")); } +// Preserve pending edits on transfer failure and reject unsafe layouts earlier. TEST(HeifImage, failsBeforeTransferAndDoesNotOverwritePendingEdits) { + // Record final-transfer attempts and inject a failure before source replacement. class TransferIo : public MemIo { public: + // Borrow the fixture bytes used to detect any premature source mutation. explicit TransferIo(const Bytes& bytes) : MemIo(bytes.data(), bytes.size()) { } + + //! @brief Record the transfer boundary and fail without copying prepared bytes. void transfer(BasicIo&) override { transferred = true; throw Error(ErrorCode::kerImageWriteFailed); } bool transferred{}; }; + auto bytes = heifWithMetadata(); auto source = std::make_unique(bytes); auto* observer = source.get(); auto image = ImageFactory::open(std::move(source)); image->readMetadata(); + image->exifData()["Exif.Image.Artist"] = "pending"; + EXPECT_THROW(image->writeMetadata(), Error); EXPECT_TRUE(observer->transferred); EXPECT_EQ(imageBytes(*image), bytes); EXPECT_EQ(image->exifData()["Exif.Image.Artist"].toString(), "pending"); + + // An unsupported container must fail before the final transfer is attempted. append(bytes, box(bmffType("moov"), {})); source = std::make_unique(bytes); observer = source.get(); @@ -1451,6 +1778,7 @@ TEST(HeifImage, failsBeforeTransferAndDoesNotOverwritePendingEdits) { EXPECT_EQ(imageBytes(*image), bytes); } +// Exercise public HEIF editing against the corpus without changing other items. TEST_P(BmffCorpus, editsThroughPublicApiAndKeepsOtherItems) { const auto& expected = GetParam(); FileIo original(std::string(TESTDATA_PATH) + "/" + expected.file); @@ -1458,16 +1786,20 @@ TEST_P(BmffCorpus, editsThroughPublicApiAndKeepsOtherItems) { auto data = original.read(original.size()); Bytes bytes(data.c_data(), data.c_data() + data.size()); auto image = ImageFactory::open(bytes.data(), bytes.size()); + if (!expected.heif) { EXPECT_EQ(image->imageType(), ImageType::bmff); EXPECT_THROW(image->writeMetadata(), Error); return; } + + // Edit primary metadata and compare each unrelated item with the original. ASSERT_EQ(image->imageType(), ImageType::heif); image->readMetadata(); image->exifData()["Exif.Image.ImageDescription"] = "PUBLIC_API_CANARY_6f9326"; setHeifXmpSource(*image, "PUBLIC_API_CANARY_6f9326"); ASSERT_NO_THROW(image->writeMetadata()); + auto output = imageBytes(*image); auto before = parse(bytes), after = parse(output); auto exif = before.metadataItems(bmffType("Exif")); @@ -1478,9 +1810,13 @@ TEST_P(BmffCorpus, editsThroughPublicApiAndKeepsOtherItems) { ASSERT_TRUE(after.items.contains(id)); EXPECT_EQ(payload(bytes, item), payload(output, after.items.at(id))); } + + // A true no-op keeps the entire file byte-for-byte unchanged. auto first = output; image->writeMetadata(); EXPECT_EQ(imageBytes(*image), first); + + // Repeated large and small edits must not accumulate obsolete payload bytes. const auto tagCount = image->exifData().count(); size_t steadySize = 0; for (unsigned cycle = 0; cycle != 3; ++cycle) { @@ -1497,11 +1833,14 @@ TEST_P(BmffCorpus, editsThroughPublicApiAndKeepsOtherItems) { } steadySize = currentSize; } + + // Clear all supported metadata after the edit sequence. image->clearMetadata(); ASSERT_NO_THROW(image->writeMetadata()); EXPECT_FALSE(contains(imageBytes(*image), "PUBLIC_API_CANARY_6f9326")); } +// Merge primary metadata in file order and replace obsolete copies together. TEST(HeifImage, readsAndReplacesMultiplePrimaryMetadataItems) { ExifData first, second; first["Exif.Image.Artist"] = "PRIVATE_FIRST_PRIMARY_450a"; @@ -1513,14 +1852,20 @@ TEST(HeifImage, readsAndReplacesMultiplePrimaryMetadataItems) { options.secondExif = true; auto source = fixture(options); auto image = openHeif(source); + + // Later primary Exif items take precedence when their tags overlap. EXPECT_EQ(image->exifData()["Exif.Image.Artist"].toString(), "PRIVATE_SECOND_PRIMARY_917a"); EXPECT_EQ(image->exifData()["Exif.Photo.DateTimeOriginal"].toString(), "2001:02:03 04:05:06"); + image->exifData()["Exif.Image.Artist"] = "replacement"; image->writeMetadata(); auto bytes = imageBytes(*image); + EXPECT_EQ(parse(bytes).metadataItems(bmffType("Exif")).size(), 1u); EXPECT_FALSE(contains(bytes, "PRIVATE_FIRST_PRIMARY_450a")); EXPECT_FALSE(contains(bytes, "PRIVATE_SECOND_PRIMARY_917a")); + + // A metadata item shared with another image cannot be replaced independently. options.sharedMetadata = true; source = fixture(options); image = openHeif(source); @@ -1529,6 +1874,7 @@ TEST(HeifImage, readsAndReplacesMultiplePrimaryMetadataItems) { EXPECT_EQ(imageBytes(*image), source); } +// Preserve duplicate tag groups while later metadata items take precedence. TEST(HeifImage, mergesDuplicateExifGroupsInFileOrder) { ExifData first, second; first["Exif.Image.Make"] = "retained"; @@ -1536,27 +1882,35 @@ TEST(HeifImage, mergesDuplicateExifGroupsInFileOrder) { auto value = Value::create(asciiString); value->read("old second"); first.add(ExifKey("Exif.Image.Artist"), value.get()); + + // The later item replaces a whole duplicate-tag group while preserving its order. second["Exif.Image.Model"] = "new model"; second["Exif.Image.Artist"] = "new first"; value->read("new second"); second.add(ExifKey("Exif.Image.Artist"), value.get()); + Options options; options.secondExif = true; options.exifPayload = tiffItem(first); options.xmpPayload = tiffItem(second); auto image = openHeif(fixture(options)); + + // Collect merged values in iteration order to check duplicate preservation. std::vector artists; for (const auto& datum : image->exifData()) if (datum.key() == "Exif.Image.Artist") artists.push_back(datum.toString()); + EXPECT_EQ(artists, (std::vector{"new first", "new second"})); EXPECT_EQ(image->exifData()["Exif.Image.Make"].toString(), "retained"); EXPECT_EQ(image->exifData()["Exif.Image.Model"].toString(), "new model"); } +// Edit idat metadata with wide IDs through the public image interface. TEST(HeifImage, updatesIdatMetadataAndWideItemIds) { ExifData exif; exif["Exif.Image.Artist"] = "PRIVATE_IDAT_METADATA_7703"; + Options options; options.idat = options.metadataIdat = true; options.exifPayload = tiffItem(exif); @@ -1566,9 +1920,12 @@ TEST(HeifImage, updatesIdatMetadataAndWideItemIds) { options.locationVersion = 2; options.entryVersion = 3; options.primaryVersion = options.referenceVersion = options.associationVersion = 1; + + // Write through ImageFactory, then inspect the rewritten item locations directly. auto image = openHeif(fixture(options)); image->exifData()["Exif.Image.Artist"] = "new"; image->writeMetadata(); + auto bytes = imageBytes(*image); auto document = parse(bytes); EXPECT_FALSE(contains(bytes, "PRIVATE_IDAT_METADATA_7703")); @@ -1577,6 +1934,7 @@ TEST(HeifImage, updatesIdatMetadataAndWideItemIds) { EXPECT_EQ(document.items.at(70001).location.constructionMethod, 1u); } +// Preserve unrelated metadata and exclude AVIF with a generic compatible brand. TEST(HeifImage, preservesIndependentMetadataAndRejectsGenericAvifBrand) { ExifData exif; exif["Exif.Image.Artist"] = "INDEPENDENT_METADATA_f880"; @@ -1585,18 +1943,24 @@ TEST(HeifImage, preservesIndependentMetadataAndRejectsGenericAvifBrand) { options.xmpPayload = tiffItem(exif); options.secondExif = true; options.noReferences = true; + auto bytes = fixture(options); auto image = openHeif(bytes); EXPECT_TRUE(image->exifData().empty()); + + // Clearing primary metadata must retain independent unassociated metadata items. image->clearExifData(); image->writeMetadata(); auto result = imageBytes(*image); EXPECT_EQ(payload(bytes, parse(bytes).items.at(2)), payload(result, parse(result).items.at(2))); + image->exifData()["Exif.Image.Artist"] = "primary metadata"; image->writeMetadata(); result = imageBytes(*image); EXPECT_TRUE(contains(result, "INDEPENDENT_METADATA_f880")); EXPECT_EQ(parse(result).metadataItems(bmffType("Exif")).size(), 1u); + + // A generic compatible brand must not make an AVIF file writable as HEIF. bytes = heifWithMetadata(); patch(bytes, 8, bmffType("mif1"), 4); patch(bytes, 16, bmffType("avif"), 4); @@ -1606,48 +1970,65 @@ TEST(HeifImage, preservesIndependentMetadataAndRejectsGenericAvifBrand) { EXPECT_THROW(image->writeMetadata(), Error); } +// Retain embedded IPTC and thumbnail data during supported Exif edits. TEST(HeifImage, preservesEmbeddedIptcAndThumbnailDataOnExifEdits) { ExifData exif; exif["Exif.Image.Artist"] = "original"; + const Bytes thumbnail{0xff, 0xd8, 1, 2, 3, 4, 0xff, 0xd9}; ExifThumb(exif).setJpegThumbnail(thumbnail.data(), thumbnail.size()); + IptcData iptc; iptc["Iptc.Application2.Caption"] = "retained IPTC"; + + // Embed IPTC and thumbnail content in the original serialized Exif item. MemIo output; TiffParser::encode(output, nullptr, 0, littleEndian, exif, iptc, XmpData{}); BmffMetadataUpdate update; update.exif = Bytes(4, 0); update.exif->insert(update.exif->end(), output.mmap(), output.mmap() + output.size()); auto image = openHeif(rewritten(heifWithMetadata(), update)); + image->exifData()["Exif.Image.Artist"] = "new"; image->writeMetadata(); + + // Check preserved embedded content before trying an unsupported IPTC mutation. EXPECT_EQ(image->iptcData()["Iptc.Application2.Caption"].toString(), "retained IPTC"); auto copied = ExifThumbC(image->exifData()).copy(); EXPECT_EQ(Bytes(copied.c_data(), copied.c_data() + copied.size()), thumbnail); + auto before = imageBytes(*image); image->iptcData()["Iptc.Application2.Caption"] = "unsupported"; EXPECT_THROW(image->writeMetadata(), Error); EXPECT_EQ(imageBytes(*image), before); } +// Remove embedded XMP slack and preserve pending edits during structure printing. TEST(HeifImage, clearsOrphanedEmbeddedXmpAndPrintsWithoutDiscardingEdits) { ExifData exif; exif["Exif.Image.Artist"] = "original"; auto item = tiffItem(exif); + + // Leave an XMP canary in TIFF slack rather than an active XML tag. const std::string canary = "PRIVATE_ORPHANED_TIFF_XMP_9c1f"; item.insert(item.end(), canary.begin(), canary.end()); BmffMetadataUpdate update; update.exif = item; auto image = openHeif(rewritten(heifWithMetadata(), update)); + image->exifData()["Exif.Image.Artist"] = "pending"; std::ostringstream trace; + + // Printing structure must not discard pending in-memory metadata edits. EXPECT_NO_THROW(image->printStructure(trace, kpsBasic, 0)); EXPECT_EQ(image->exifData()["Exif.Image.Artist"].toString(), "pending"); + image->clearXmpPacket(); image->writeMetadata(); EXPECT_FALSE(contains(imageBytes(*image), canary)); } +// Reject ambiguous primary XMP encodings without replacing the source. TEST(HeifImage, rejectsAmbiguousPrimaryXmpEncodingsBeforeTransfer) { ExifData exif; exif["Exif.Image.Artist"] = "original"; @@ -1667,6 +2048,7 @@ TEST(HeifImage, rejectsAmbiguousPrimaryXmpEncodingsBeforeTransfer) { } } +// Remove Unicode comment bytes in both supported TIFF byte orders. TEST(HeifImage, removesUnicodeUserCommentsInBothTiffByteOrders) { const std::string canary = "PRIVATE_UNICODE_COMMENT_7ead"; Bytes big, little; @@ -1675,6 +2057,8 @@ TEST(HeifImage, removesUnicodeUserCommentsInBothTiffByteOrders) { little.push_back(c); little.push_back(0); } + + // Search raw bytes for either Unicode encoding, including unreferenced TIFF storage. auto has = [](const Bytes& data, const Bytes& needle) { return std::search(data.begin(), data.end(), needle.begin(), needle.end()) != data.end(); }; @@ -1683,16 +2067,21 @@ TEST(HeifImage, removesUnicodeUserCommentsInBothTiffByteOrders) { exif["Exif.Image.Artist"] = "retained"; exif["Exif.Photo.UserComment"] = "charset=Unicode " + canary + " žluťoučký"; auto bytes = heifWithMetadata(exif, {}, order); + ASSERT_TRUE(has(bytes, big) || has(bytes, little)); + + // Delete the user comment and require both raw encodings to disappear. auto image = openHeif(bytes); image->exifData().erase(image->exifData().findKey(ExifKey("Exif.Photo.UserComment"))); image->writeMetadata(); bytes = imageBytes(*image); + EXPECT_FALSE(has(bytes, big)); EXPECT_FALSE(has(bytes, little)); } } +// Preserve auxiliary and thumbnail relationships without decoding their images. TEST(HeifImage, preservesAuxiliaryAndThumbnailGraphsAsOpaqueImageData) { // A structural fixture: compressed-image decoding is intentionally outside // this test. The writer must preserve every image item and relationship. @@ -1704,17 +2093,23 @@ TEST(HeifImage, preservesAuxiliaryAndThumbnailGraphsAsOpaqueImageData) { options.xmpPayload = Bytes{'T', 'H', 'U', 'M', 'B'}; auto bytes = fixture(options); auto before = parse(bytes); + + // Repurpose the extra fixture items as opaque auxiliary and thumbnail images. for (const auto id : {2, 3}) { const auto& info = before.items.at(id).info; patch(bytes, info.box.offset + 16, bmffType("hvc1"), 4); } + for (const auto& ref : before.references) patch(bytes, ref.box.offset + 4, ref.from == 2 ? bmffType("auxl") : bmffType("thmb"), 4); before = parse(bytes); + + // Add primary metadata without changing the retained image graph or payloads. auto image = openHeif(bytes); EXPECT_TRUE(image->exifData().empty()); image->exifData()["Exif.Image.Artist"] = "new metadata"; image->writeMetadata(); + auto output = imageBytes(*image); const auto after = parse(output); for (const auto& [id, item] : before.items) @@ -1730,6 +2125,7 @@ TEST(HeifImage, preservesAuxiliaryAndThumbnailGraphsAsOpaqueImageData) { } } +// Preserve raw XMP during Exif edits and remove its bytes on explicit clearing. TEST(HeifImage, preservesRawXmpDuringExifEditsAndClearsItsStorage) { ExifData exif; exif["Exif.Image.Artist"] = "artist"; @@ -1740,9 +2136,13 @@ TEST(HeifImage, preservesRawXmpDuringExifEditsAndClearsItsStorage) { #else EXPECT_EQ(image->xmpPacket(), packet); #endif + + // An untouched image must preserve even the exact raw packet representation. auto before = imageBytes(*image); image->writeMetadata(); EXPECT_EQ(imageBytes(*image), before); + + // Changing Exif alone must retain the separate raw XMP packet. image->exifData()["Exif.Image.Artist"] = "edited"; ASSERT_NO_THROW(image->writeMetadata()); auto bytes = imageBytes(*image); @@ -1750,13 +2150,17 @@ TEST(HeifImage, preservesRawXmpDuringExifEditsAndClearsItsStorage) { const auto ids = document.metadataItems(bmffType("mime")); ASSERT_EQ(ids.size(), 1u); EXPECT_EQ(payload(bytes, document.items.at(ids.front())), Bytes(packet.begin(), packet.end())); + + // Replace the packet, then clear it and inspect all remaining file bytes. image->setXmpPacket(rawXmpSource("PRIVATE_REPLACEMENT_PACKET_653c")); image->writeMetadata(); EXPECT_FALSE(contains(imageBytes(*image), "PRIVATE_RAW_PACKET_594e")); + image->clearXmpData(); image->writeMetadata(); EXPECT_FALSE(contains(imageBytes(*image), "PRIVATE_REPLACEMENT_PACKET_653c")); EXPECT_TRUE(image->xmpPacket().empty()); + image->setXmpPacket(packet); image->writeMetadata(); image->setXmpData(XmpData{}); @@ -1765,6 +2169,8 @@ TEST(HeifImage, preservesRawXmpDuringExifEditsAndClearsItsStorage) { } #ifndef EXV_HAVE_XMP_TOOLKIT + +// Handle embedded raw XMP without the toolkit and reject ambiguous merges. TEST(HeifImage, preservesEmbeddedRawXmpWithoutToolkitAndRejectsUnmergeablePackets) { ExifData exif; exif["Exif.Image.Artist"] = "artist"; @@ -1774,9 +2180,13 @@ TEST(HeifImage, preservesEmbeddedRawXmpWithoutToolkitAndRejectsUnmergeablePacket exif.add(ExifKey("Exif.Image.XMLPacket"), value.get()); auto image = openHeif(heifWithMetadata(exif)); EXPECT_EQ(image->xmpPacket(), packet); + + // Preserve embedded raw XMP through Exif edits without parsing its XML. image->exifData()["Exif.Image.Artist"] = "edited"; ASSERT_NO_THROW(image->writeMetadata()); EXPECT_EQ(image->xmpPacket(), packet); + + // When Exif is removed, promote its embedded packet to a separate XMP item. image->clearExifData(); image->writeMetadata(); auto bytes = imageBytes(*image); @@ -1784,22 +2194,30 @@ TEST(HeifImage, preservesEmbeddedRawXmpWithoutToolkitAndRejectsUnmergeablePacket EXPECT_TRUE(document.metadataItems(bmffType("Exif")).empty()); ASSERT_EQ(document.metadataItems(bmffType("mime")).size(), 1u); EXPECT_EQ(image->xmpPacket(), packet); + image->clearXmpData(); image->writeMetadata(); EXPECT_FALSE(contains(imageBytes(*image), "PRIVATE_EMBEDDED_RAW_819c")); + // Distinct raw packets cannot be merged safely without the XMP toolkit. const auto other = rawXmpSource("PRIVATE_DIFFERENT_RAW_0551"); bytes = heifWithMetadata(exif, other); image = openHeif(bytes); + image->writeMetadata(); EXPECT_EQ(imageBytes(*image), bytes); + + // Reject an ambiguous edit but allow explicit removal of all XMP copies. image->exifData()["Exif.Image.Artist"] = "pending"; EXPECT_THROW(image->writeMetadata(), Error); EXPECT_EQ(imageBytes(*image), bytes); + image->clearXmpData(); ASSERT_NO_THROW(image->writeMetadata()); EXPECT_FALSE(contains(imageBytes(*image), "PRIVATE_EMBEDDED_RAW_819c")); EXPECT_FALSE(contains(imageBytes(*image), "PRIVATE_DIFFERENT_RAW_0551")); + + // Structured XMP requests remain unsupported when the toolkit is disabled. image->xmpData()["Xmp.dc.source"] = "requires toolkit"; bytes = imageBytes(*image); EXPECT_THROW(image->writeMetadata(), Error); From 98d967a05fd43291a09e27156019bd06d5e1446d Mon Sep 17 00:00:00 2001 From: Vaclav Haisman Date: Sat, 10 Oct 2026 01:20:21 +0200 Subject: [PATCH 19/40] [tests] Explain HEIF CLI edit and failure regressions Describe disposable fixtures, metadata round trips, obsolete-byte checks and staging or destination failures. Separate the edit sequences. --- .../github/test_issue_2349_heif_write.py | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/tests/bugfixes/github/test_issue_2349_heif_write.py b/tests/bugfixes/github/test_issue_2349_heif_write.py index bfb458c4a9..25b7370151 100644 --- a/tests/bugfixes/github/test_issue_2349_heif_write.py +++ b/tests/bugfixes/github/test_issue_2349_heif_write.py @@ -11,41 +11,53 @@ import system_tests +# Exercise public HEIF CLI editing on disposable copies of existing corpus files. @unittest.skipUnless(system_tests.BT.verbose_version().get("enable_bmff") == "1", "requires BMFF support") class HeifMetadataWriting(unittest.TestCase): + # Own a temporary fixture directory and locate the configured CLI binary. def setUp(self): self.directory = tempfile.TemporaryDirectory(prefix="exiv2-heif-", dir=system_tests.tmp_path) self.addCleanup(self.directory.cleanup) self.root = Path(self.directory.name) self.exiv2 = str(Path(system_tests.BT.Config.bin_dir) / "exiv2") + # Copy one corpus file into this test's temporary directory. def copy(self, filename): target = self.root / filename shutil.copyfile(Path(system_tests.data_path) / filename, target) return target + # Run the CLI with a timeout and check the expected success or failure status. def run_exiv2(self, *args, success=True): result = subprocess.run([self.exiv2, *map(str, args)], capture_output=True, timeout=30) + if success: self.assertEqual(result.returncode, 0, result.stderr.decode(errors="replace")) else: self.assertNotEqual(result.returncode, 0) return result.stdout + # Extract metadata, clear its physical storage, and insert it back from the sidecar. @unittest.skipUnless(system_tests.BT.verbose_version().get("have_xmptoolkit") == "1", "requires structured XMP editing") def test_extract_clear_and_insert_metadata(self): target = self.copy("Stonehenge.heic") self.run_exiv2("-M", "set Exif.Image.Artist HEIF_EXIF_CANARY_627c", "-M", "set Xmp.dc.source HEIF_XMP_CANARY_691d", target) + + # Save the edited metadata in a sidecar before removing both categories. self.run_exiv2("-ea", target) self.assertTrue(target.with_suffix(".exv").exists()) + + # Search the whole file for deleted canaries, including unreferenced storage. self.run_exiv2("-de", target) self.run_exiv2("-dx", target) data = target.read_bytes() self.assertNotIn(b"HEIF_EXIF_CANARY_627c", data) self.assertNotIn(b"HEIF_XMP_CANARY_691d", data) + + # Insert the saved metadata and verify both restored values through the CLI. self.run_exiv2("-ia", target) self.assertEqual(self.run_exiv2("-K", "Exif.Image.Artist", "-Pv", target), b"HEIF_EXIF_CANARY_627c\n") @@ -53,21 +65,28 @@ def test_extract_clear_and_insert_metadata(self): b"HEIF_XMP_CANARY_691d\n") self.assertFalse(list(self.root.glob(".exiv2-heif-*"))) + # Remove obsolete MakerNote bytes after shrinking, deleting a tag, and deleting the note. def test_makernote_values_shrink_and_disappear(self): target = self.copy("Canon.HIF") canary = "PRIVATE_CANON_OWNER_44bea7" self.run_exiv2("-M", "set Exif.Canon.OwnerName " + "x" * 1000 + canary, target) self.assertIn(canary.encode(), target.read_bytes()) + + # Shrink the value, then exercise deletion of the tag and its containing MakerNote. self.run_exiv2("-M", "set Exif.Canon.OwnerName owner", target) self.assertNotIn(canary.encode(), target.read_bytes()) + self.run_exiv2("-M", "set Exif.Canon.OwnerName " + canary, target) self.run_exiv2("-M", "del Exif.Canon.OwnerName", target) self.assertNotIn(canary.encode(), target.read_bytes()) + self.run_exiv2("-M", "set Exif.Canon.OwnerName " + canary, target) self.run_exiv2("-M", "del Exif.Photo.MakerNote", target) self.assertNotIn(canary.encode(), target.read_bytes()) + self.assertFalse(list(self.root.glob(".exiv2-heif-*"))) + # Verify unsupported fields and read-only formats leave the original bytes unchanged. def test_read_only_fields_and_formats_do_not_change_source(self): for filename, key in [("Canon.HIF", "Exif.Canon.AFNumPoints"), ("Canon-R6-pruned.CR3", "Exif.Image.Artist"), @@ -76,25 +95,33 @@ def test_read_only_fields_and_formats_do_not_change_source(self): with self.subTest(filename=filename): target = self.copy(filename) before = hashlib.sha256(target.read_bytes()).digest() + self.run_exiv2("-M", "set " + key + " 123", target, success=False) + self.assertEqual(hashlib.sha256(target.read_bytes()).digest(), before) self.assertFalse(list(self.root.glob(".exiv2-heif-*"))) + # Verify staging and destination-open failures preserve the source and clean temporary files. @unittest.skipUnless(os.name == "posix" and getattr(os, "geteuid", lambda: 0)() != 0, "requires an unprivileged POSIX process") def test_staging_and_destination_open_failures_preserve_source(self): target = self.copy("Stonehenge.heic") before = target.read_bytes() + + # Prevent staging-file creation by making the containing directory read-only. self.root.chmod(0o500) try: self.run_exiv2("-M", "set Exif.Image.Artist pending", target, success=False) self.assertEqual(target.read_bytes(), before) finally: self.root.chmod(0o700) + + # Allow staging again but prevent the final destination from opening for writing. target.chmod(0o400) try: self.run_exiv2("-M", "set Exif.Image.Artist pending", target, success=False) self.assertEqual(target.read_bytes(), before) finally: target.chmod(0o600) + self.assertFalse(list(self.root.glob(".exiv2-heif-*"))) From 16fe150d32c1af4f09fa8c2239733b92cec0b252 Mon Sep 17 00:00:00 2001 From: Vaclav Haisman Date: Sat, 10 Oct 2026 01:20:21 +0200 Subject: [PATCH 20/40] [fuzz] Document HEIF metadata edit coverage Describe helper inputs and error propagation, and explain how metadata mutation exercises serialization, compaction and the subsequent reread. --- fuzz/fuzz-heif-write.hpp | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/fuzz/fuzz-heif-write.hpp b/fuzz/fuzz-heif-write.hpp index de3cdd288d..167e27c696 100644 --- a/fuzz/fuzz-heif-write.hpp +++ b/fuzz/fuzz-heif-write.hpp @@ -5,11 +5,19 @@ #include -// The ordinary write keeps metadata unchanged and may take the HEIF no-op -// path. Exercise serialization and compaction as well, on the owned MemIo. +/*! + @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"; @@ -24,6 +32,8 @@ inline void fuzzHeifWrite(Exiv2::Image& image, size_t selector) { image.clearMetadata(); break; } + + // Parse the result through the public API as well as exercising its serialization. image.writeMetadata(); image.readMetadata(); } From a1a0c6126db679ce73da8cebda0c0ec2d030696e Mon Sep 17 00:00:00 2001 From: Vaclav Haisman Date: Sat, 10 Oct 2026 08:45:57 +0200 Subject: [PATCH 21/40] [heif] Preserve raw XMP when copying metadata without the toolkit --- src/heifimage_int.cpp | 24 ++++++++ unitTests/test_bmffimage_int.cpp | 95 ++++++++++++++++++++++++++++++++ 2 files changed, 119 insertions(+) diff --git a/src/heifimage_int.cpp b/src/heifimage_int.cpp index 237b667f3d..77fd95fb45 100644 --- a/src/heifimage_int.cpp +++ b/src/heifimage_int.cpp @@ -562,6 +562,30 @@ class HeifImage final : public BmffImage { } } + /*! + @brief Copy writable Exif/XMP metadata, preserving raw packets without the XMP toolkit. + @param image Source image; self-copy is supported and source buffers are not retained. + @throws Error If structured XMP needs an unavailable toolkit or a packet exceeds the size limit. + + The copy changes buffered metadata only. An empty source XMP packet requests + removal when the toolkit is unavailable, just as an explicit clear does. + */ + void setMetadata(const Image& image) override { +#ifdef EXV_HAVE_XMP_TOOLKIT + Image::setMetadata(image); +#else + supported(image.xmpData().empty(), "structured XMP editing requires the XMP toolkit"); + const auto& sourcePacket = image.xmpPacket(); + supported(sourcePacket.size() <= bmffMetadataLimit, "XMP exceeds the allocation limit"); + + // Snapshot both views before changing this image, which may also be the source. + const auto exif = image.exifData(); + const auto packet = sourcePacket; + setExifData(exif); + setXmpPacket(packet); +#endif + } + //! @brief Replace Exif data, treating an empty replacement as an explicit removal request. void setExifData(const ExifData& exif) override { Image::setExifData(exif); diff --git a/unitTests/test_bmffimage_int.cpp b/unitTests/test_bmffimage_int.cpp index 209bd10ddd..a58c787760 100644 --- a/unitTests/test_bmffimage_int.cpp +++ b/unitTests/test_bmffimage_int.cpp @@ -2170,6 +2170,101 @@ TEST(HeifImage, preservesRawXmpDuringExifEditsAndClearsItsStorage) { #ifndef EXV_HAVE_XMP_TOOLKIT +// Copy raw XMP and Exif together without mistaking an absent structured view for removal. +TEST(HeifImage, copiesRawXmpMetadataWithoutToolkit) { + ExifData exif; + exif["Exif.Image.Artist"] = "copied artist"; + const auto packet = rawXmpSource("COPIED_RAW_XMP_8cd372"); + auto source = openHeif(heifWithMetadata(exif, packet)); + ASSERT_TRUE(source->xmpData().empty()); + + auto target = openHeif(heifWithMetadata({}, rawXmpSource("REPLACED_RAW_XMP_246da7"))); + target->setMetadata(*source); + EXPECT_EQ(target->xmpPacket(), packet); + ASSERT_NO_THROW(target->writeMetadata()); + + // Inspect the stored item and reopen it independently of the writer's cached state. + auto bytes = imageBytes(*target); + auto document = parse(bytes); + const auto ids = document.metadataItems(bmffType("mime")); + ASSERT_EQ(ids.size(), 1u); + EXPECT_EQ(payload(bytes, document.items.at(ids.front())), Bytes(packet.begin(), packet.end())); + EXPECT_FALSE(contains(bytes, "REPLACED_RAW_XMP_246da7")); + target = openHeif(bytes); + EXPECT_EQ(target->xmpPacket(), packet); + EXPECT_EQ(target->exifData()["Exif.Image.Artist"].toString(), "copied artist"); + + // Self-copy must retain the packet and remain a byte-for-byte no-op on disk. + target->setMetadata(*target); + ASSERT_NO_THROW(target->writeMetadata()); + EXPECT_EQ(imageBytes(*target), bytes); +} + +// Remove copied raw XMP through empty-source copying and each explicit clearing API. +TEST(HeifImage, clearsCopiedRawXmpWithoutToolkit) { + ExifData exif; + exif["Exif.Image.Artist"] = "retained artist"; + auto source = openHeif(heifWithMetadata(exif, rawXmpSource("REMOVED_COPIED_XMP_08c4a1"))); + auto emptySource = openHeif(heifWithMetadata(exif)); + + for (unsigned method = 0; method != 4; ++method) { + SCOPED_TRACE(method); + auto target = openHeif(heifWithMetadata()); + target->setMetadata(*source); + target->writeMetadata(); + ASSERT_TRUE(contains(imageBytes(*target), "REMOVED_COPIED_XMP_08c4a1")); + + // These requests all explicitly replace the source's XMP with an empty value. + switch (method) { + case 0: + target->setMetadata(*emptySource); + break; + case 1: + target->setXmpData(XmpData{}); + break; + case 2: + target->clearXmpData(); + break; + case 3: + target->clearXmpPacket(); + break; + } + ASSERT_NO_THROW(target->writeMetadata()); + + auto bytes = imageBytes(*target); + EXPECT_FALSE(contains(bytes, "REMOVED_COPIED_XMP_08c4a1")); + EXPECT_TRUE(parse(bytes).metadataItems(bmffType("mime")).empty()); + target = openHeif(bytes); + EXPECT_TRUE(target->xmpPacket().empty()); + EXPECT_EQ(target->exifData()["Exif.Image.Artist"].toString(), "retained artist"); + } +} + +// Reject unsupported structured data and oversized packets before changing the destination. +TEST(HeifImage, rejectsUnsupportedMetadataCopyWithoutToolkit) { + ExifData exif; + exif["Exif.Image.Artist"] = "retained artist"; + const auto packet = rawXmpSource("RETAINED_RAW_XMP_933fe4"); + auto target = openHeif(heifWithMetadata(exif, packet)); + const auto before = imageBytes(*target); + auto source = openHeif(heifWithMetadata()); + source->exifData()["Exif.Image.Artist"] = "unsupported copy"; + source->xmpData()["Xmp.dc.source"] = "requires toolkit"; + + EXPECT_THROW(target->setMetadata(*source), Error); + EXPECT_EQ(target->exifData()["Exif.Image.Artist"].toString(), "retained artist"); + EXPECT_EQ(target->xmpPacket(), packet); + EXPECT_EQ(imageBytes(*target), before); + + // The mutable packet accessor can bypass setter limits; copying must still enforce them. + source->clearXmpData(); + source->xmpPacket().assign(static_cast(bmffMetadataLimit) + 1, 'x'); + EXPECT_THROW(target->setMetadata(*source), Error); + EXPECT_EQ(target->exifData()["Exif.Image.Artist"].toString(), "retained artist"); + EXPECT_EQ(target->xmpPacket(), packet); + EXPECT_EQ(imageBytes(*target), before); +} + // Handle embedded raw XMP without the toolkit and reject ambiguous merges. TEST(HeifImage, preservesEmbeddedRawXmpWithoutToolkitAndRejectsUnmergeablePackets) { ExifData exif; From 152d1712a20e214fb0ece59d5ff66d4b86c4827b Mon Sep 17 00:00:00 2001 From: Vaclav Haisman Date: Sat, 10 Oct 2026 08:46:26 +0200 Subject: [PATCH 22/40] [heif] Restore legacy Adobe UUID XMP reading --- src/heifimage_int.cpp | 32 +++++++++--- unitTests/test_bmffimage_int.cpp | 83 +++++++++++++++++++++++++++++++- 2 files changed, 106 insertions(+), 9 deletions(-) diff --git a/src/heifimage_int.cpp b/src/heifimage_int.cpp index 77fd95fb45..e983a1647f 100644 --- a/src/heifimage_int.cpp +++ b/src/heifimage_int.cpp @@ -33,6 +33,17 @@ namespace Exiv2::Internal { namespace { using Bytes = std::vector; +// Search validated headers only; UUID payloads and other opaque bytes remain unread. +bool hasAdobeXmpUuid(const std::vector& boxes) { + static constexpr std::array xmpUuid{0xbe, 0x7a, 0xcf, 0xcb, 0x97, 0xa9, 0x42, 0xe8, + 0x9c, 0x71, 0x99, 0x94, 0x91, 0xe3, 0xaf, 0xac}; + for (const auto& box : boxes) { + if ((box.type == bmffType("uuid") && box.userType == xmpUuid) || hasAdobeXmpUuid(box.children)) + return true; + } + return false; +} + // Reject unsupported edits before they can replace the source stream. void supported(bool condition, std::string_view reason) { if (!condition) @@ -548,18 +559,23 @@ class HeifImage final : public BmffImage { enforce(io_->open() == 0, ErrorCode::kerDataSourceOpenFailed, io_->path(), strError()); IoCloser closer(*io_); - BmffDocument document; try { - document = parseBmff(*io_); - assign(Internal::readMetadata(*io_, document, DecodeParams(max_recursion_depth_))); + const auto document = parseBmff(*io_); brand_ = document.majorBrand; + + // Opaque Adobe UUID packets need the legacy reader's traversal and precedence. + if (!hasAdobeXmpUuid(document.boxes)) { + assign(Internal::readMetadata(*io_, document, DecodeParams(max_recursion_depth_))); + return; + } } catch (const Error&) { - // Deferred layouts retain the existing reader. Writing still reparses and rejects. - BmffImage::readMetadata(); - loaded_ = true; - removeExif_ = removeXmp_ = false; - return; + // Deferred layouts also retain the existing reader and its failure behavior. } + + // Finalize either fallback only after reading succeeds. Writing still reparses and rejects. + BmffImage::readMetadata(); + loaded_ = true; + removeExif_ = removeXmp_ = false; } /*! diff --git a/unitTests/test_bmffimage_int.cpp b/unitTests/test_bmffimage_int.cpp index a58c787760..54a2dae575 100644 --- a/unitTests/test_bmffimage_int.cpp +++ b/unitTests/test_bmffimage_int.cpp @@ -106,6 +106,7 @@ struct Options { bool extended{}; bool terminal{}; bool idat{}; + bool singleImageExtent{}; bool noMetadata{}; bool noReferences{}; bool sharedMetadata{}; @@ -185,7 +186,7 @@ Bytes fixture(const Options& opt = {}) { integer(locations, opt.offsetWidth == 0 ? source + itemOffset : source, opt.baseWidth); // Split the primary image around metadata when the offset fields allow it. - const bool fragmented = i == 1 && opt.offsetWidth != 0; + const bool fragmented = i == 1 && opt.offsetWidth != 0 && !opt.singleImageExtent; integer(locations, fragmented ? 2 : 1, 2); integer(locations, 0, opt.indexWidth); integer(locations, (opt.baseWidth == 0 ? source : 0) + itemOffset, opt.offsetWidth); @@ -1551,6 +1552,33 @@ std::string rawXmpSource(std::string_view value) { std::string(value) + "'/>"; } +// Build a legacy-readable UUID layout, optionally with a competing item-based XMP packet. +Bytes heifWithUuidXmp(bool nested, bool extended, bool itemXmp, bool adobe = true) { + Bytes uuid{0xbe, 0x7a, 0xcf, 0xcb, 0x97, 0xa9, 0x42, 0xe8, 0x9c, 0x71, 0x99, 0x94, 0x91, 0xe3, 0xaf, 0xac}; + if (!adobe) + uuid.front() ^= 1; + const auto packet = rawXmpSource("UUID_XMP_579def"); + uuid.insert(uuid.end(), packet.begin(), packet.end()); + + Options options; + options.brand = bmffType("mif1"); + options.noMetadata = !itemXmp; + // The legacy iloc reader needs equal-sized records, with one extent per item. + options.singleImageExtent = true; + ExifData exif; + exif["Exif.Image.Artist"] = "retained UUID fixture artist"; + options.exifPayload = tiffItem(exif); + const auto itemPacket = rawXmpSource("ITEM_XMP_feb32d"); + options.xmpPayload = Bytes(itemPacket.begin(), itemPacket.end()); + auto& extra = nested ? options.extraMeta : options.extraRoot; + extra = box(bmffType("uuid"), uuid, extended); + + // The legacy UUID reader counts header bytes again when reading its packet. + // A valid following padding box keeps this fixture within its accepted layouts. + append(options.extraRoot, box(bmffType("free"), Bytes(24))); + return fixture(options); +} + // Set equivalent XMP data with or without the structured XMP toolkit. void setHeifXmpSource(Image& image, const std::string& value) { #ifdef EXV_HAVE_XMP_TOOLKIT @@ -1571,6 +1599,59 @@ Bytes imageBytes(Image& image) { } // namespace +// Restore legacy UUID reading and precedence without making these layouts writable. +TEST(HeifImage, readsAdobeUuidXmpThroughLegacyFallback) { + for (bool nested : {false, true}) { + for (bool extended : {false, true}) { + for (bool itemXmp : {false, true}) { + SCOPED_TRACE(::testing::Message() << "nested=" << nested << " extended=" << extended << " itemXmp=" << itemXmp); + const auto bytes = heifWithUuidXmp(nested, extended, itemXmp); + ASSERT_NO_THROW(parse(bytes)); + + // Compare with the reader that handled HEIF before the factory specialization. + BmffImage legacy(std::make_unique(bytes.data(), bytes.size()), defaultImageCtorParams(false)); + ASSERT_NO_THROW(legacy.readMetadata()); + auto image = openHeif(bytes); + EXPECT_EQ(image->mimeType(), "image/heif"); + EXPECT_EQ(image->xmpPacket(), legacy.xmpPacket()); + EXPECT_EQ(image->xmpData().count(), legacy.xmpData().count()); + EXPECT_EQ(image->exifData().count(), legacy.exifData().count()); +#ifdef EXV_HAVE_XMP_TOOLKIT + ASSERT_EQ(image->xmpData().count(), 1u); + EXPECT_EQ(image->xmpData()["Xmp.dc.source"].toString(), legacy.xmpData()["Xmp.dc.source"].toString()); +#endif + if (itemXmp) { + EXPECT_EQ(image->exifData()["Exif.Image.Artist"].toString(), "retained UUID fixture artist"); + } + + // Both an unchanged write and a requested edit must reject before touching the bytes. + EXPECT_THROW(image->writeMetadata(), Error); + EXPECT_EQ(imageBytes(*image), bytes); + image->exifData()["Exif.Image.Artist"] = "unsupported UUID edit"; + EXPECT_THROW(image->writeMetadata(), Error); + EXPECT_EQ(imageBytes(*image), bytes); + + // Reading again discards pending edits and reestablishes the same legacy view. + ASSERT_NO_THROW(image->readMetadata()); + EXPECT_EQ(image->xmpPacket(), legacy.xmpPacket()); + EXPECT_EQ(image->exifData().count(), legacy.exifData().count()); + } + } + } +} + +// Ignore unrelated opaque UUIDs while retaining the native reader's item metadata support. +TEST(HeifImage, keepsOtherUuidsOnTheNativeReadPath) { + auto image = openHeif(heifWithUuidXmp(false, false, true, false)); +#ifdef EXV_HAVE_XMP_TOOLKIT + EXPECT_EQ(image->xmpData()["Xmp.dc.source"].toString(), "ITEM_XMP_feb32d"); +#else + // The legacy reader cannot supply raw item packets without the toolkit. + EXPECT_EQ(image->xmpPacket(), rawXmpSource("ITEM_XMP_feb32d")); +#endif + EXPECT_EQ(image->exifData()["Exif.Image.Artist"].toString(), "retained UUID fixture artist"); +} + // Exercise public metadata edits while preserving encoded image bytes. TEST(HeifImage, addsGrowsShrinksDeletesAndPreservesEncodedImage) { auto image = openHeif(heifWithMetadata()); From 894d26ad77eaa1067967e17f9abf97054470ac13 Mon Sep 17 00:00:00 2001 From: Vaclav Haisman Date: Sat, 10 Oct 2026 10:32:53 +0200 Subject: [PATCH 23/40] [heif] Preserve merged embedded XMP during Exif edits Keep the merged embedded XMP when an unrelated Exif field changes. Honor explicit raw-packet edits and verify regenerated packets through their decoded properties. --- src/heifimage_int.cpp | 35 ++++-- unitTests/test_bmffimage_int.cpp | 176 +++++++++++++++++++++++++++++++ 2 files changed, 202 insertions(+), 9 deletions(-) diff --git a/src/heifimage_int.cpp b/src/heifimage_int.cpp index e983a1647f..235aeb88ec 100644 --- a/src/heifimage_int.cpp +++ b/src/heifimage_int.cpp @@ -267,6 +267,17 @@ void eraseTag(ExifData& exif, std::string_view key) { exif.erase(std::remove_if(exif.begin(), exif.end(), [&](const auto& d) { return d.key() == key; }), exif.end()); } +#ifdef EXV_HAVE_XMP_TOOLKIT +// Isolate all raw embedded packets so duplicate insertion and deletion count as edits. +ExifData xmlPacketData(const ExifData& exif) { + ExifData packets; + for (const auto& datum : exif) + if (datum.key() == "Exif.Image.XMLPacket") + packets.add(datum); + return packets; +} +#endif + // Identify synthesized Canon autofocus fields that cannot be edited independently. bool canonDerived(const Exifdatum& datum) { // These values are synthesized by decodeCanonAFInfo from Canon's 0x0026 @@ -285,6 +296,10 @@ ExifData derivedCanonData(const ExifData& data) { // Exclude regenerated offsets and raw decoded MakerNotes from semantic comparisons. ExifData exifValues(ExifData data) { +#ifdef EXV_HAVE_XMP_TOOLKIT + // Embedded XMP is regenerated and checked separately through its decoded properties. + eraseTag(data, "Exif.Image.XMLPacket"); +#endif const bool decodedMakerNote = data.findKey(ExifKey("Exif.MakerNote.ByteOrder")) != data.end(); data.erase(std::remove_if(data.begin(), data.end(), [&](const auto& datum) { @@ -303,6 +318,10 @@ ExifData exifValues(ExifData data) { Bytes encodeExif(ExifData exif, const IptcData& iptc, XmpData embedded, ByteOrder order, const DecodeParams& params) { // A fresh tree excludes original TIFF gaps, shortened values and tail bytes. // The serializer reconstructs known MakerNotes and copies retained data areas. +#ifdef EXV_HAVE_XMP_TOOLKIT + // Replace every raw packet, including duplicates, with the intended structured XMP. + eraseTag(exif, "Exif.Image.XMLPacket"); +#endif const auto requested = exifValues(exif); exif.erase(std::remove_if(exif.begin(), exif.end(), canonDerived), exif.end()); @@ -715,29 +734,27 @@ class HeifImage final : public BmffImage { // A separate MIME item becomes authoritative when XMP is edited. Remove its // old embedded TIFF copy so it cannot reappear after removing the MIME item. auto embedded = original.embeddedXmp; -#ifdef EXV_HAVE_XMP_TOOLKIT - auto xml = exif.findKey(ExifKey("Exif.Image.XMLPacket")); -#endif // Even without a live XMLPacket tag, prior XMP may survive in TIFF slack. const bool embeddedChanged = xmpChanged && !exif.empty(); if (xmpChanged) { eraseTag(exif, "Exif.Image.XMLPacket"); embedded.clear(); - } else if (exifChanged) { - // The Exif API can also delete or replace the embedded XMLPacket tag. - // Honor its current value instead of restoring the old decoded packet. - embedded.clear(); + } #ifdef EXV_HAVE_XMP_TOOLKIT - if (xml != exif.end()) { + else if (exifChanged && !sameData(xmlPacketData(exif), xmlPacketData(original.exif))) { + // An unrelated Exif edit retains the union of embedded packets. Only an + // explicit raw-tag edit replaces that union with the current first packet. + embedded.clear(); + if (auto xml = exif.findKey(ExifKey("Exif.Image.XMLPacket")); xml != exif.end()) { supported(xml->size() <= bmffMetadataLimit, "embedded XMP exceeds the allocation limit"); Bytes bytes(xml->size()); xml->copy(bytes.data(), original.order); enforce(XmpParser::decode(embedded, std::string(bytes.begin(), bytes.end()), params) == 0, ErrorCode::kerInvalidXMP); } -#endif } +#endif // Rebuild Exif when its values change or when old embedded XMP must be scrubbed. if (exifChanged || embeddedChanged) { diff --git a/unitTests/test_bmffimage_int.cpp b/unitTests/test_bmffimage_int.cpp index 54a2dae575..b7b89d0b8c 100644 --- a/unitTests/test_bmffimage_int.cpp +++ b/unitTests/test_bmffimage_int.cpp @@ -1552,6 +1552,33 @@ std::string rawXmpSource(std::string_view value) { std::string(value) + "'/>"; } +#ifdef EXV_HAVE_XMP_TOOLKIT +// Build two primary Exif items with disjoint and overlapping embedded XMP properties. +Bytes heifWithMergedEmbeddedXmp(bool separate = false) { + ExifData exif; + exif["Exif.Image.Artist"] = "original artist"; + XmpData first, second; + first["Xmp.dc.source"] = "FIRST_EMBEDDED_78b2"; + first["Xmp.xmp.Label"] = "FIRST_LABEL"; + second["Xmp.dc.format"] = "SECOND_EMBEDDED_4c19"; + second["Xmp.xmp.Label"] = "SECOND_LABEL"; + Options options; + options.secondExif = true; + options.exifPayload = tiffItem(exif, first); + options.xmpPayload = tiffItem(exif, second); + auto bytes = fixture(options); + + // A separate packet overrides the overlapping embedded source property. + if (separate) { + const auto packet = rawXmpSource("MIME_SOURCE"); + BmffMetadataUpdate update; + update.xmp = Bytes(packet.begin(), packet.end()); + bytes = rewritten(bytes, update); + } + return bytes; +} +#endif + // Build a legacy-readable UUID layout, optionally with a competing item-based XMP packet. Bytes heifWithUuidXmp(bool nested, bool extended, bool itemXmp, bool adobe = true) { Bytes uuid{0xbe, 0x7a, 0xcf, 0xcb, 0x97, 0xa9, 0x42, 0xe8, 0x9c, 0x71, 0x99, 0x94, 0x91, 0xe3, 0xaf, 0xac}; @@ -1921,6 +1948,155 @@ TEST_P(BmffCorpus, editsThroughPublicApiAndKeepsOtherItems) { EXPECT_FALSE(contains(imageBytes(*image), "PUBLIC_API_CANARY_6f9326")); } +#ifdef EXV_HAVE_XMP_TOOLKIT +// Preserve the union of embedded packets when an unrelated Exif field changes. +TEST(HeifImage, preservesMergedEmbeddedXmpOnExifEdits) { + for (bool separate : {false, true}) { + SCOPED_TRACE(separate); + auto source = heifWithMergedEmbeddedXmp(separate); + auto image = openHeif(source); + ASSERT_EQ(image->xmpData().count(), 3u); + EXPECT_EQ(image->xmpData()["Xmp.dc.source"].toString(), separate ? "MIME_SOURCE" : "FIRST_EMBEDDED_78b2"); + EXPECT_EQ(image->xmpData()["Xmp.xmp.Label"].toString(), "SECOND_LABEL"); + + image->exifData()["Exif.Image.Artist"] = "edited artist"; + ASSERT_NO_THROW(image->writeMetadata()); + const auto bytes = imageBytes(*image); + const auto document = parse(bytes); + const auto items = document.metadataItems(bmffType("Exif")); + ASSERT_EQ(items.size(), 1u); + + // Inspect the embedded packet independently so separate XMP cannot mask lost properties. + const auto tiff = payload(bytes, document.items.at(items.front())); + ExifData checkedExif; + IptcData checkedIptc; + XmpData checkedXmp; + ASSERT_EQ(TiffParser::decode(checkedExif, checkedIptc, checkedXmp, tiff.data() + 4, tiff.size() - 4, + DecodeParams(defaultImageCtorParams(false).max_recursion_depth())), + littleEndian); + ASSERT_EQ(checkedXmp.count(), 3u); + EXPECT_EQ(checkedXmp["Xmp.dc.source"].toString(), "FIRST_EMBEDDED_78b2"); + const auto original = parse(source); + EXPECT_EQ(payload(bytes, document.items.at(document.primaryItem)), + payload(source, original.items.at(original.primaryItem))); + image = openHeif(bytes); + + EXPECT_EQ(image->exifData()["Exif.Image.Artist"].toString(), "edited artist"); + ASSERT_EQ(image->xmpData().count(), 3u); + EXPECT_EQ(image->xmpData()["Xmp.dc.source"].toString(), separate ? "MIME_SOURCE" : "FIRST_EMBEDDED_78b2"); + EXPECT_EQ(image->xmpData()["Xmp.dc.format"].toString(), "SECOND_EMBEDDED_4c19"); + EXPECT_EQ(image->xmpData()["Xmp.xmp.Label"].toString(), "SECOND_LABEL"); + + // Once consolidated, a write without edits must preserve all source bytes. + ASSERT_NO_THROW(image->writeMetadata()); + EXPECT_EQ(imageBytes(*image), bytes); + } +} + +// Honor explicit packet edits and removals without resurrecting merged embedded properties. +TEST(HeifImage, honorsExplicitEditsToMergedEmbeddedXmp) { + for (unsigned operation = 0; operation < 4; ++operation) { + SCOPED_TRACE(operation); + auto image = openHeif(heifWithMergedEmbeddedXmp()); + ASSERT_EQ(image->xmpData().count(), 3u); + + // Replace or delete XMLPacket, clear all XMP, or remove only Exif. + if (operation < 2) { + auto& exif = image->exifData(); + exif.erase(exif.findKey(ExifKey("Exif.Image.XMLPacket"))); + if (operation == 0) { + const auto packet = rawXmpSource("REPLACEMENT_EMBEDDED_025f"); + auto value = Value::create(unsignedByte); + value->read(reinterpret_cast(packet.data()), packet.size(), invalidByteOrder); + exif.add(ExifKey("Exif.Image.XMLPacket"), value.get()); + } + } else if (operation == 2) { + image->clearXmpData(); + } else { + image->clearExifData(); + } + + ASSERT_NO_THROW(image->writeMetadata()); + const auto bytes = imageBytes(*image); + image = openHeif(bytes); + if (operation == 3) { + EXPECT_TRUE(image->exifData().empty()); + ASSERT_EQ(image->xmpData().count(), 3u); + EXPECT_EQ(image->xmpData()["Xmp.dc.source"].toString(), "FIRST_EMBEDDED_78b2"); + EXPECT_EQ(image->xmpData()["Xmp.dc.format"].toString(), "SECOND_EMBEDDED_4c19"); + EXPECT_EQ(parse(bytes).metadataItems(bmffType("mime")).size(), 1u); + } else { + EXPECT_FALSE(contains(bytes, "FIRST_EMBEDDED_78b2")); + EXPECT_FALSE(contains(bytes, "SECOND_EMBEDDED_4c19")); + if (operation == 0) { + ASSERT_EQ(image->xmpData().count(), 1u); + EXPECT_EQ(image->xmpData()["Xmp.dc.source"].toString(), "REPLACEMENT_EMBEDDED_025f"); + } else { + EXPECT_TRUE(image->xmpData().empty()); + } + } + } +} + +// Treat duplicate XMLPacket insertion as an explicit edit even if its first value is unchanged. +TEST(HeifImage, detectsChangesToDuplicateEmbeddedPacketGroups) { + auto image = openHeif(heifWithMergedEmbeddedXmp()); + auto& exif = image->exifData(); + const auto packet = exif.findKey(ExifKey("Exif.Image.XMLPacket"))->value().clone(); + exif.add(ExifKey("Exif.Image.XMLPacket"), packet.get()); + + ASSERT_NO_THROW(image->writeMetadata()); + const auto bytes = imageBytes(*image); + image = openHeif(bytes); + + // The existing first-packet interpretation applies to explicitly edited raw tags. + EXPECT_FALSE(contains(bytes, "FIRST_EMBEDDED_78b2")); + ASSERT_EQ(image->xmpData().count(), 2u); + EXPECT_EQ(image->xmpData()["Xmp.dc.format"].toString(), "SECOND_EMBEDDED_4c19"); + EXPECT_EQ(std::count_if(image->exifData().begin(), image->exifData().end(), + [](const auto& datum) { return datum.key() == "Exif.Image.XMLPacket"; }), + 1); +} +#else +// Reject an Exif edit requiring two different embedded packets to merge without the toolkit. +TEST(HeifImage, rejectsMergingMultipleEmbeddedPacketsWithoutToolkit) { + ExifData exif; + exif["Exif.Image.Artist"] = "original"; + Options options; + options.secondExif = true; + const auto first = rawXmpSource("FIRST_RAW_EMBEDDED_81f5"); + const auto second = rawXmpSource("SECOND_RAW_EMBEDDED_517a"); + auto value = Value::create(unsignedByte); + + // Build raw XML tags directly because structured serialization is unavailable. + value->read(reinterpret_cast(first.data()), first.size(), invalidByteOrder); + exif.add(ExifKey("Exif.Image.XMLPacket"), value.get()); + options.exifPayload = tiffItem(exif); + exif.erase(exif.findKey(ExifKey("Exif.Image.XMLPacket"))); + value->read(reinterpret_cast(second.data()), second.size(), invalidByteOrder); + exif.add(ExifKey("Exif.Image.XMLPacket"), value.get()); + options.xmpPayload = tiffItem(exif); + const auto bytes = fixture(options); + auto image = openHeif(bytes); + + ASSERT_NO_THROW(image->writeMetadata()); + EXPECT_EQ(imageBytes(*image), bytes); + image->exifData()["Exif.Image.Artist"] = "pending"; + EXPECT_THROW(image->writeMetadata(), Error); + EXPECT_EQ(imageBytes(*image), bytes); + + // Explicit removal resolves the ambiguity and physically removes both packets. + image->clearXmpData(); + ASSERT_NO_THROW(image->writeMetadata()); + const auto cleaned = imageBytes(*image); + EXPECT_FALSE(contains(cleaned, "FIRST_RAW_EMBEDDED_81f5")); + EXPECT_FALSE(contains(cleaned, "SECOND_RAW_EMBEDDED_517a")); + image = openHeif(cleaned); + EXPECT_TRUE(image->xmpPacket().empty()); + EXPECT_EQ(image->exifData()["Exif.Image.Artist"].toString(), "pending"); +} +#endif + // Merge primary metadata in file order and replace obsolete copies together. TEST(HeifImage, readsAndReplacesMultiplePrimaryMetadataItems) { ExifData first, second; From ef0552719a8bf2c6ff262c30e53129c73239d815 Mon Sep 17 00:00:00 2001 From: Vaclav Haisman Date: Sat, 10 Oct 2026 10:32:53 +0200 Subject: [PATCH 24/40] [heif] Clear buffered metadata before legacy fallback reads Clear all buffered metadata before invoking the legacy reader while retaining the narrower semantics of explicit HEIF metadata clears. --- src/heifimage_int.cpp | 3 + unitTests/test_bmffimage_int.cpp | 117 +++++++++++++++++++++++++++++++ 2 files changed, 120 insertions(+) diff --git a/src/heifimage_int.cpp b/src/heifimage_int.cpp index 235aeb88ec..ed1bfc89f5 100644 --- a/src/heifimage_int.cpp +++ b/src/heifimage_int.cpp @@ -591,6 +591,9 @@ class HeifImage final : public BmffImage { // Deferred layouts also retain the existing reader and its failure behavior. } + // Reading replaces all buffered categories, including those retained by a user clear. + Image::clearMetadata(); + // Finalize either fallback only after reading succeeds. Writing still reparses and rejects. BmffImage::readMetadata(); loaded_ = true; diff --git a/unitTests/test_bmffimage_int.cpp b/unitTests/test_bmffimage_int.cpp index b7b89d0b8c..5e9be3443f 100644 --- a/unitTests/test_bmffimage_int.cpp +++ b/unitTests/test_bmffimage_int.cpp @@ -1606,6 +1606,55 @@ Bytes heifWithUuidXmp(bool nested, bool extended, bool itemXmp, bool adobe = tru return fixture(options); } +// Build a profile satisfying the legacy reader's size validation with recognizable bytes. +Bytes fixtureIcc(byte marker) { + Bytes profile(128, marker); + patch(profile, 0, profile.size(), 4); + return profile; +} + +// Construct either fallback path, optionally with IPTC and ICC to reload from disk. +Bytes heifForFallback(bool uuid, bool metadata, uint32_t brand = bmffType("heic")) { + Options options; + options.brand = brand; + options.singleImageExtent = true; + options.noMetadata = !metadata; + ExifData exif; + exif["Exif.Image.Artist"] = "disk artist"; + IptcData iptc; + iptc["Iptc.Application2.Caption"] = "disk caption"; + MemIo tiff; + TiffParser::encode(tiff, nullptr, 0, littleEndian, exif, iptc, XmpData{}); + options.exifPayload = Bytes(4, 0); + options.exifPayload->insert(options.exifPayload->end(), tiff.mmap(), tiff.mmap() + tiff.size()); + const auto packet = rawXmpSource("DISK_FALLBACK_XMP"); + options.xmpPayload = Bytes(packet.begin(), packet.end()); + + if (uuid) { + // The validated tree contains Adobe XMP, selecting compatibility traversal. + Bytes data{0xbe, 0x7a, 0xcf, 0xcb, 0x97, 0xa9, 0x42, 0xe8, 0x9c, 0x71, 0x99, 0x94, 0x91, 0xe3, 0xaf, 0xac}; + data.insert(data.end(), packet.begin(), packet.end()); + options.extraRoot = box(bmffType("uuid"), data); + append(options.extraRoot, box(bmffType("free"), Bytes(24))); + } else { + // An unused external reference is rejected by the native parser, but ignored by legacy reading. + auto location = full(); + string(location, "external.heic"); + auto references = full(); + integer(references, 1, 4); + append(references, box(bmffType("url "), location)); + options.extraMeta = box(bmffType("dinf"), box(bmffType("dref"), references)); + } + + if (metadata) { + Bytes colour; + integer(colour, bmffType("prof"), 4); + append(colour, fixtureIcc(0x43)); + append(options.extraRoot, box(bmffType("colr"), colour)); + } + return fixture(options); +} + // Set equivalent XMP data with or without the structured XMP toolkit. void setHeifXmpSource(Image& image, const std::string& value) { #ifdef EXV_HAVE_XMP_TOOLKIT @@ -1626,6 +1675,74 @@ Bytes imageBytes(Image& image) { } // namespace +// A fallback reread must discard pending metadata and reload only the disk's values. +TEST(HeifImage, resetsAllMetadataBeforeLegacyFallback) { + for (bool uuid : {false, true}) { + for (bool metadata : {false, true}) { + SCOPED_TRACE(::testing::Message() << "uuid=" << uuid << " metadata=" << metadata); + const auto bytes = heifForFallback(uuid, metadata); + if (uuid) { + ASSERT_NO_THROW(parse(bytes)); + } else { + EXPECT_THROW(parse(bytes), Error); + } + BmffImage legacy(std::make_unique(bytes.data(), bytes.size()), defaultImageCtorParams(false)); + ASSERT_NO_THROW(legacy.readMetadata()); + ASSERT_EQ(legacy.iptcData().count(), metadata ? 1u : 0u); + ASSERT_EQ(legacy.iccProfileDefined(), metadata); + auto image = openHeif(bytes); + const auto pendingProfile = fixtureIcc(0x50); + + // Repeat to catch state surviving across more than one successful fallback. + for (unsigned pass = 0; pass < 2; ++pass) { + image->exifData()["Exif.Image.Artist"] = "pending artist"; + image->iptcData()["Iptc.Application2.Caption"] = "pending caption"; + image->setIccProfile(DataBuf(pendingProfile.data(), pendingProfile.size())); + // Seed the base buffer directly; BMFF's public comment setter rejects edits. + image->Image::setComment("pending comment"); + image->clearXmpData(); + ASSERT_NO_THROW(image->readMetadata()); + + EXPECT_EQ(image->exifData().count(), legacy.exifData().count()); + EXPECT_EQ(image->iptcData().count(), legacy.iptcData().count()); + EXPECT_EQ(image->xmpPacket(), legacy.xmpPacket()); + EXPECT_EQ(image->xmpData().count(), legacy.xmpData().count()); + EXPECT_EQ(image->comment(), legacy.comment()); + EXPECT_EQ(image->iccProfileDefined(), legacy.iccProfileDefined()); + if (metadata) { + EXPECT_EQ(image->exifData()["Exif.Image.Artist"].toString(), "disk artist"); + EXPECT_EQ(image->iptcData()["Iptc.Application2.Caption"].toString(), "disk caption"); + ASSERT_EQ(image->iccProfile().size(), legacy.iccProfile().size()); + EXPECT_EQ(std::memcmp(image->iccProfile().c_data(), legacy.iccProfile().c_data(), legacy.iccProfile().size()), + 0); + } + } + EXPECT_THROW(image->writeMetadata(), Error); + EXPECT_EQ(imageBytes(*image), bytes); + } + } +} + +// User clearing still retains categories for which standalone HEIF editing is unsupported. +TEST(HeifImage, retainsUnsupportedMetadataOnExplicitClear) { + auto image = openHeif(heifWithMetadata()); + image->exifData()["Exif.Image.Artist"] = "pending artist"; + setHeifXmpSource(*image, "pending XMP"); + image->iptcData()["Iptc.Application2.Caption"] = "retained caption"; + const auto profile = fixtureIcc(0x50); + image->setIccProfile(DataBuf(profile.data(), profile.size())); + + image->clearMetadata(); + + EXPECT_TRUE(image->exifData().empty()); + EXPECT_TRUE(image->xmpData().empty()); + EXPECT_TRUE(image->xmpPacket().empty()); + EXPECT_EQ(image->iptcData()["Iptc.Application2.Caption"].toString(), "retained caption"); + ASSERT_TRUE(image->iccProfileDefined()); + ASSERT_EQ(image->iccProfile().size(), profile.size()); + EXPECT_EQ(std::memcmp(image->iccProfile().c_data(), profile.data(), profile.size()), 0); +} + // Restore legacy UUID reading and precedence without making these layouts writable. TEST(HeifImage, readsAdobeUuidXmpThroughLegacyFallback) { for (bool nested : {false, true}) { From a3acc07df2c3b29eddf0048249b652589d1b018d Mon Sep 17 00:00:00 2001 From: Vaclav Haisman Date: Sat, 10 Oct 2026 10:32:53 +0200 Subject: [PATCH 25/40] [heif] Retain MIME types after legacy fallback reads Delegate MIME reporting to the successful legacy reader and reset that choice when adopting native metadata. --- src/heifimage_int.cpp | 5 +++ unitTests/test_bmffimage_int.cpp | 73 ++++++++++++++++++++++++++++++++ 2 files changed, 78 insertions(+) diff --git a/src/heifimage_int.cpp b/src/heifimage_int.cpp index ed1bfc89f5..5bb7c03ff0 100644 --- a/src/heifimage_int.cpp +++ b/src/heifimage_int.cpp @@ -570,6 +570,8 @@ class HeifImage final : public BmffImage { //! @brief Report the MIME type corresponding to the most recently read major brand. std::string mimeType() const override { + if (legacyRead_) + return BmffImage::mimeType(); return brand_ == bmffType("mif1") ? "image/heif" : "image/heic"; } @@ -596,6 +598,7 @@ class HeifImage final : public BmffImage { // Finalize either fallback only after reading succeeds. Writing still reparses and rejects. BmffImage::readMetadata(); + legacyRead_ = true; loaded_ = true; removeExif_ = removeXmp_ = false; } @@ -837,12 +840,14 @@ class HeifImage final : public BmffImage { // The adopted state becomes the new baseline for detecting the next edit. writeXmpFromPacket(false); + legacyRead_ = false; loaded_ = true; removeExif_ = removeXmp_ = false; } uint32_t brand_{bmffType("heic")}; bool loaded_{}, removeExif_{}, removeXmp_{}; + bool legacyRead_{}; //!< MIME reporting uses the brand read by the successful legacy traversal. }; } // namespace diff --git a/unitTests/test_bmffimage_int.cpp b/unitTests/test_bmffimage_int.cpp index 5e9be3443f..23ea6346c5 100644 --- a/unitTests/test_bmffimage_int.cpp +++ b/unitTests/test_bmffimage_int.cpp @@ -1743,6 +1743,79 @@ TEST(HeifImage, retainsUnsupportedMetadataOnExplicitClear) { EXPECT_EQ(std::memcmp(image->iccProfile().c_data(), profile.data(), profile.size()), 0); } +// Native and compatibility readers must report the major brand that was actually read. +TEST(HeifImage, reportsMimeTypeAfterNativeAndFallbackReads) { + for (auto brand : {bmffType("mif1"), bmffType("heic"), bmffType("heix")}) { + for (unsigned route = 0; route < 3; ++route) { + SCOPED_TRACE(::testing::Message() << "brand=" << brand << " route=" << route); + Options options; + options.noMetadata = true; + options.brand = brand; + const auto bytes = route == 0 ? fixture(options) : heifForFallback(route == 2, false, brand); + BmffImage legacy(std::make_unique(bytes.data(), bytes.size()), defaultImageCtorParams(false)); + ASSERT_NO_THROW(legacy.readMetadata()); + auto image = openHeif(bytes); + + EXPECT_EQ(image->mimeType(), brand == bmffType("mif1") ? "image/heif" : "image/heic"); + EXPECT_EQ(image->mimeType(), legacy.mimeType()); + ASSERT_NO_THROW(image->readMetadata()); + EXPECT_EQ(image->mimeType(), legacy.mimeType()); + if (route != 0) { + EXPECT_THROW(image->writeMetadata(), Error); + EXPECT_EQ(imageBytes(*image), bytes); + } + } + } +} + +// Switching a reused image between legacy and native storage must not retain an old MIME source. +TEST(HeifImage, updatesMimeTypeWhenReadPathChanges) { + auto image = openHeif(heifForFallback(false, false, bmffType("mif1"))); + EXPECT_EQ(image->mimeType(), "image/heif"); + + // Replace owned MemIo storage while keeping the same Image instance and cached state. + Options options; + options.noMetadata = true; + options.brand = bmffType("heix"); + auto bytes = fixture(options); + MemIo native(bytes.data(), bytes.size()); + image->io().transfer(native); + ASSERT_NO_THROW(image->readMetadata()); + EXPECT_EQ(image->mimeType(), "image/heic"); + + bytes = heifForFallback(true, false, bmffType("mif1")); + MemIo fallback(bytes.data(), bytes.size()); + image->io().transfer(fallback); + ASSERT_NO_THROW(image->readMetadata()); + EXPECT_EQ(image->mimeType(), "image/heif"); + + // A successful write also adopts native state, without requiring a prior native reread. + bytes = fixture(options); + MemIo writable(bytes.data(), bytes.size()); + image->io().transfer(writable); + image->clearMetadata(); + image->exifData()["Exif.Image.Artist"] = "native write"; + ASSERT_NO_THROW(image->writeMetadata()); + EXPECT_EQ(image->mimeType(), "image/heic"); + image = openHeif(imageBytes(*image)); + EXPECT_EQ(image->mimeType(), "image/heic"); + EXPECT_EQ(image->exifData()["Exif.Image.Artist"].toString(), "native write"); +} + +// A failed native parse must still propagate the legacy reader's error for malformed storage. +TEST(HeifImage, preservesErrorsFromLegacyFallback) { + auto image = openHeif(heifForFallback(false, false)); + auto bytes = heifForFallback(false, false); + patch(bytes, position(bytes, "meta"), bytes.size() + 1, 4); + BmffImage legacy(std::make_unique(bytes.data(), bytes.size()), defaultImageCtorParams(false)); + MemIo malformed(bytes.data(), bytes.size()); + image->io().transfer(malformed); + + EXPECT_THROW(legacy.readMetadata(), Error); + EXPECT_THROW(image->readMetadata(), Error); + EXPECT_EQ(imageBytes(*image), bytes); +} + // Restore legacy UUID reading and precedence without making these layouts writable. TEST(HeifImage, readsAdobeUuidXmpThroughLegacyFallback) { for (bool nested : {false, true}) { From 5d3173beec55882f2b632025cd384ed23131482b Mon Sep 17 00:00:00 2001 From: Vaclav Haisman Date: Sat, 10 Oct 2026 10:32:53 +0200 Subject: [PATCH 26/40] [heif] Reuse parsed Exif keys for metadata lookups Initialize XMLPacket and Canon AFInfo keys once on first use and reuse them for lookups. Keep string conversion outside metadata scan loops. --- src/heifimage_int.cpp | 34 ++++++++++++++++++++++---------- unitTests/test_bmffimage_int.cpp | 27 +++++++++++++++---------- 2 files changed, 41 insertions(+), 20 deletions(-) diff --git a/src/heifimage_int.cpp b/src/heifimage_int.cpp index 5bb7c03ff0..a3ccf83816 100644 --- a/src/heifimage_int.cpp +++ b/src/heifimage_int.cpp @@ -33,6 +33,18 @@ namespace Exiv2::Internal { namespace { using Bytes = std::vector; +// Construct the embedded-XMP lookup key once, on its first use. +const ExifKey& xmlPacketKey() { + static const ExifKey key("Exif.Image.XMLPacket"); + return key; +} + +// Construct the key for Canon's source autofocus record once, on its first use. +const ExifKey& canonAfInfoKey() { + static const ExifKey key("Exif.Canon.AFInfo"); + return key; +} + // Search validated headers only; UUID payloads and other opaque bytes remain unread. bool hasAdobeXmpUuid(const std::vector& boxes) { static constexpr std::array xmpUuid{0xbe, 0x7a, 0xcf, 0xcb, 0x97, 0xa9, 0x42, 0xe8, @@ -191,7 +203,7 @@ Metadata readMetadata(BasicIo& io, const BmffDocument& document, const DecodePar metadata.order = order; // Remember embedded packets even when structured XMP decoding is unavailable. - if (auto xml = exif.findKey(ExifKey("Exif.Image.XMLPacket")); xml != exif.end()) { + if (auto xml = exif.findKey(xmlPacketKey()); xml != exif.end()) { metadata.hasEmbeddedXmp = true; #ifndef EXV_HAVE_XMP_TOOLKIT Bytes packet(xml->size()); @@ -263,16 +275,18 @@ Metadata readMetadata(BasicIo& io, const BmffDocument& document, const DecodePar } // Remove every occurrence of a tag, including duplicates from merged metadata. -void eraseTag(ExifData& exif, std::string_view key) { - exif.erase(std::remove_if(exif.begin(), exif.end(), [&](const auto& d) { return d.key() == key; }), exif.end()); +void eraseTag(ExifData& exif, const ExifKey& key) { + const auto name = key.key(); + exif.erase(std::remove_if(exif.begin(), exif.end(), [&](const auto& d) { return d.key() == name; }), exif.end()); } #ifdef EXV_HAVE_XMP_TOOLKIT // Isolate all raw embedded packets so duplicate insertion and deletion count as edits. ExifData xmlPacketData(const ExifData& exif) { ExifData packets; + const auto name = xmlPacketKey().key(); for (const auto& datum : exif) - if (datum.key() == "Exif.Image.XMLPacket") + if (datum.key() == name) packets.add(datum); return packets; } @@ -298,7 +312,7 @@ ExifData derivedCanonData(const ExifData& data) { ExifData exifValues(ExifData data) { #ifdef EXV_HAVE_XMP_TOOLKIT // Embedded XMP is regenerated and checked separately through its decoded properties. - eraseTag(data, "Exif.Image.XMLPacket"); + eraseTag(data, xmlPacketKey()); #endif const bool decodedMakerNote = data.findKey(ExifKey("Exif.MakerNote.ByteOrder")) != data.end(); data.erase(std::remove_if(data.begin(), data.end(), @@ -320,7 +334,7 @@ Bytes encodeExif(ExifData exif, const IptcData& iptc, XmpData embedded, ByteOrde // The serializer reconstructs known MakerNotes and copies retained data areas. #ifdef EXV_HAVE_XMP_TOOLKIT // Replace every raw packet, including duplicates, with the intended structured XMP. - eraseTag(exif, "Exif.Image.XMLPacket"); + eraseTag(exif, xmlPacketKey()); #endif const auto requested = exifValues(exif); exif.erase(std::remove_if(exif.begin(), exif.end(), canonDerived), exif.end()); @@ -744,7 +758,7 @@ class HeifImage final : public BmffImage { // Even without a live XMLPacket tag, prior XMP may survive in TIFF slack. const bool embeddedChanged = xmpChanged && !exif.empty(); if (xmpChanged) { - eraseTag(exif, "Exif.Image.XMLPacket"); + eraseTag(exif, xmlPacketKey()); embedded.clear(); } #ifdef EXV_HAVE_XMP_TOOLKIT @@ -752,7 +766,7 @@ class HeifImage final : public BmffImage { // An unrelated Exif edit retains the union of embedded packets. Only an // explicit raw-tag edit replaces that union with the current first packet. embedded.clear(); - if (auto xml = exif.findKey(ExifKey("Exif.Image.XMLPacket")); xml != exif.end()) { + if (auto xml = exif.findKey(xmlPacketKey()); xml != exif.end()) { supported(xml->size() <= bmffMetadataLimit, "embedded XMP exceeds the allocation limit"); Bytes bytes(xml->size()); xml->copy(bytes.data(), original.order); @@ -764,8 +778,8 @@ class HeifImage final : public BmffImage { // Rebuild Exif when its values change or when old embedded XMP must be scrubbed. if (exifChanged || embeddedChanged) { - if (exif.findKey(ExifKey("Exif.Canon.AFInfo")) != exif.end() && - original.exif.findKey(ExifKey("Exif.Canon.AFInfo")) != original.exif.end()) { + if (exif.findKey(canonAfInfoKey()) != exif.end() && + original.exif.findKey(canonAfInfoKey()) != original.exif.end()) { supported(sameData(derivedCanonData(exif), derivedCanonData(original.exif)), "Canon synthesized autofocus fields are read-only"); } diff --git a/unitTests/test_bmffimage_int.cpp b/unitTests/test_bmffimage_int.cpp index 23ea6346c5..7b295fced8 100644 --- a/unitTests/test_bmffimage_int.cpp +++ b/unitTests/test_bmffimage_int.cpp @@ -29,6 +29,12 @@ using namespace Exiv2::Internal; namespace { using Bytes = std::vector; +// Construct the embedded-XMP lookup key once, on its first use. +const ExifKey& xmlPacketKey() { + static const ExifKey key("Exif.Image.XMLPacket"); + return key; +} + // Append a big-endian field without using the production serializer. void integer(Bytes& output, uint64_t value, unsigned width) { for (unsigned i = width; i != 0; --i) @@ -1985,7 +1991,7 @@ TEST(HeifImage, clearsEmbeddedXmpAndPreservesItWhenOnlyExifIsRemoved) { // Deleting the embedded XML tag must also remove its serialized packet. image = openHeif(bytes); - auto xml = image->exifData().findKey(ExifKey("Exif.Image.XMLPacket")); + auto xml = image->exifData().findKey(xmlPacketKey()); ASSERT_NE(xml, image->exifData().end()); image->exifData().erase(xml); image->writeMetadata(); @@ -2193,12 +2199,12 @@ TEST(HeifImage, honorsExplicitEditsToMergedEmbeddedXmp) { // Replace or delete XMLPacket, clear all XMP, or remove only Exif. if (operation < 2) { auto& exif = image->exifData(); - exif.erase(exif.findKey(ExifKey("Exif.Image.XMLPacket"))); + exif.erase(exif.findKey(xmlPacketKey())); if (operation == 0) { const auto packet = rawXmpSource("REPLACEMENT_EMBEDDED_025f"); auto value = Value::create(unsignedByte); value->read(reinterpret_cast(packet.data()), packet.size(), invalidByteOrder); - exif.add(ExifKey("Exif.Image.XMLPacket"), value.get()); + exif.add(xmlPacketKey(), value.get()); } } else if (operation == 2) { image->clearXmpData(); @@ -2232,8 +2238,8 @@ TEST(HeifImage, honorsExplicitEditsToMergedEmbeddedXmp) { TEST(HeifImage, detectsChangesToDuplicateEmbeddedPacketGroups) { auto image = openHeif(heifWithMergedEmbeddedXmp()); auto& exif = image->exifData(); - const auto packet = exif.findKey(ExifKey("Exif.Image.XMLPacket"))->value().clone(); - exif.add(ExifKey("Exif.Image.XMLPacket"), packet.get()); + const auto packet = exif.findKey(xmlPacketKey())->value().clone(); + exif.add(xmlPacketKey(), packet.get()); ASSERT_NO_THROW(image->writeMetadata()); const auto bytes = imageBytes(*image); @@ -2243,8 +2249,9 @@ TEST(HeifImage, detectsChangesToDuplicateEmbeddedPacketGroups) { EXPECT_FALSE(contains(bytes, "FIRST_EMBEDDED_78b2")); ASSERT_EQ(image->xmpData().count(), 2u); EXPECT_EQ(image->xmpData()["Xmp.dc.format"].toString(), "SECOND_EMBEDDED_4c19"); + const auto name = xmlPacketKey().key(); EXPECT_EQ(std::count_if(image->exifData().begin(), image->exifData().end(), - [](const auto& datum) { return datum.key() == "Exif.Image.XMLPacket"; }), + [&](const auto& datum) { return datum.key() == name; }), 1); } #else @@ -2260,11 +2267,11 @@ TEST(HeifImage, rejectsMergingMultipleEmbeddedPacketsWithoutToolkit) { // Build raw XML tags directly because structured serialization is unavailable. value->read(reinterpret_cast(first.data()), first.size(), invalidByteOrder); - exif.add(ExifKey("Exif.Image.XMLPacket"), value.get()); + exif.add(xmlPacketKey(), value.get()); options.exifPayload = tiffItem(exif); - exif.erase(exif.findKey(ExifKey("Exif.Image.XMLPacket"))); + exif.erase(exif.findKey(xmlPacketKey())); value->read(reinterpret_cast(second.data()), second.size(), invalidByteOrder); - exif.add(ExifKey("Exif.Image.XMLPacket"), value.get()); + exif.add(xmlPacketKey(), value.get()); options.xmpPayload = tiffItem(exif); const auto bytes = fixture(options); auto image = openHeif(bytes); @@ -2719,7 +2726,7 @@ TEST(HeifImage, preservesEmbeddedRawXmpWithoutToolkitAndRejectsUnmergeablePacket const auto packet = rawXmpSource("PRIVATE_EMBEDDED_RAW_819c"); auto value = Value::create(unsignedByte); value->read(reinterpret_cast(packet.data()), packet.size(), invalidByteOrder); - exif.add(ExifKey("Exif.Image.XMLPacket"), value.get()); + exif.add(xmlPacketKey(), value.get()); auto image = openHeif(heifWithMetadata(exif)); EXPECT_EQ(image->xmpPacket(), packet); From d6e68cac93b682a08a09ea3e3abd12d1ac9bc01a Mon Sep 17 00:00:00 2001 From: Vaclav Haisman Date: Sat, 10 Oct 2026 11:05:15 +0200 Subject: [PATCH 27/40] [docs] Document HEIF writing APIs, tests and fuzzing --- fuzz/README.md | 42 +++++++++++++++++++++++++++++++ include/exiv2/image.hpp | 13 ++++++++++ tests/README-TESTS.md | 55 +++++++++++++++++++++++++++++++++++++++++ 3 files changed, 110 insertions(+) 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/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/tests/README-TESTS.md b/tests/README-TESTS.md index 20378185b5..02dc9d1496 100644 --- a/tests/README-TESTS.md +++ b/tests/README-TESTS.md @@ -2,6 +2,7 @@ - [README-TESTS](#README-TESTS) - [Running the test suite](#running-the-test-suite) + - [HEIF metadata writing](#heif-metadata-writing) - [Writing new tests](#writing-new-tests) - [Test data](#test-data) - [Test suite](#test-suite) @@ -67,6 +68,60 @@ standard output. [TOC](#TOC) +
+ +### HEIF metadata writing + +Install the [build dependencies](../README.md#dependencies), including Google +Test for [unit tests](../README.md#unit-tests), and the Python requirements +listed above. These POSIX shell examples start at the repository root; see the +[build instructions](../README.md#build-install-use-exiv2-on-a-unix-like-system) +for general setup. + +Enable BMFF, unit tests and the CLI, then run the focused unit and CLI tests: + +```bash +cmake -S . -B build-heif-debug -DCMAKE_BUILD_TYPE=Debug \ + -DBUILD_TESTING=ON -DEXIV2_ENABLE_BMFF=ON \ + -DEXIV2_BUILD_UNIT_TESTS=ON -DEXIV2_BUILD_EXIV2_COMMAND=ON \ + -DEXIV2_ENABLE_XMP=ON -DEXIV2_ENABLE_EXTERNAL_XMP=OFF +cmake --build build-heif-debug --parallel 4 +./build-heif-debug/bin/unit_tests --gtest_filter='*Bmff*:*Heif*' +( + cd tests + EXIV2_BINDIR="$PWD/../build-heif-debug/bin" \ + python3 runner.py --verbose bugfixes/github/test_issue_2349_heif_write.py +) +``` + +The unit filter includes the parameterized corpus tests. The CLI regressions +cover metadata extraction/reinsertion, MakerNote removal, rejected writes, and +staging/transfer-open failures, using disposable fixture copies. + +Use a separate build to check raw XMP handling without either XMP toolkit: + +```bash +cmake -S . -B build-heif-no-xmp -DCMAKE_BUILD_TYPE=Debug \ + -DBUILD_TESTING=ON -DEXIV2_ENABLE_BMFF=ON \ + -DEXIV2_BUILD_UNIT_TESTS=ON -DEXIV2_BUILD_EXIV2_COMMAND=ON \ + -DEXIV2_ENABLE_XMP=OFF -DEXIV2_ENABLE_EXTERNAL_XMP=OFF +cmake --build build-heif-no-xmp --parallel 4 +./build-heif-no-xmp/bin/unit_tests --gtest_filter='*Bmff*:*Heif*' +( + cd tests + EXIV2_BINDIR="$PWD/../build-heif-no-xmp/bin" \ + python3 runner.py --verbose bugfixes/github/test_issue_2349_heif_write.py +) +``` + +Tests requiring structured XMP decoding are skipped when the toolkit is +disabled; raw-packet preservation, copying and removal have separate coverage. +The CLI permission-failure test requires an unprivileged POSIX process and is +skipped on other platforms or when run as root. A BMFF-disabled build omits +the BMFF/HEIF unit tests and skips the HEIF CLI tests. + +[TOC](#TOC) +
## Writing new tests From 555e424f6c7e8f2ab5da3e5b6d988fee5007060a Mon Sep 17 00:00:00 2001 From: Vaclav Haisman Date: Sat, 10 Oct 2026 12:27:08 +0200 Subject: [PATCH 28/40] [bmff] Extract shared box reader and traversal Move checked box headers, bounded cursors and read budgets into a private format-independent reader. Route the HEIF item parser through it without changing item validation or write eligibility. Add generic container tests and register the new code with CMake and Meson. --- src/CMakeLists.txt | 2 + src/bmffbox_int.cpp | 128 +++++++++++ src/bmffbox_int.hpp | 200 +++++++++++++++++ src/bmffimage_int.cpp | 160 +++----------- src/bmffimage_int.hpp | 37 +--- src/meson.build | 1 + unitTests/CMakeLists.txt | 1 + unitTests/meson.build | 1 + unitTests/test_bmffbox_int.cpp | 384 +++++++++++++++++++++++++++++++++ 9 files changed, 742 insertions(+), 172 deletions(-) create mode 100644 src/bmffbox_int.cpp create mode 100644 src/bmffbox_int.hpp create mode 100644 unitTests/test_bmffbox_int.cpp diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 66b4de0b01..56444a3a9a 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -4,6 +4,8 @@ include_directories(${CMAKE_CURRENT_BINARY_DIR}) add_library( exiv2lib_int OBJECT + bmffbox_int.cpp + bmffbox_int.hpp bmffimage_int.cpp bmffimage_int.hpp bmffwrite_int.cpp diff --git a/src/bmffbox_int.cpp b/src/bmffbox_int.cpp new file mode 100644 index 0000000000..9413d55f7f --- /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[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..bb6e606281 --- /dev/null +++ b/src/bmffbox_int.hpp @@ -0,0 +1,200 @@ +// 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 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 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. + @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 on success. Callback exceptions propagate. + */ + template + void visit(BmffCursor& input, unsigned depth, Visitor&& visitor) { + checkTraversal(input, depth); + while (input.remaining() != 0) { + 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_int.cpp b/src/bmffimage_int.cpp index e3d311dff3..2d35e7898e 100644 --- a/src/bmffimage_int.cpp +++ b/src/bmffimage_int.cpp @@ -40,95 +40,13 @@ void consume(uint64_t& used, uint64_t amount, uint64_t limit) { // Shared counters bound work across all nested boxes in one parse. struct Budget { const BmffLimits& limits; - uint64_t boxes{}; uint64_t extents{}; uint64_t references{}; uint64_t associations{}; uint64_t strings{}; - uint64_t bytes{}; }; -//! @brief Every field read is checked against its immediate box, not merely the file. -class Cursor { - public: - //! @brief Borrow a previously bounded input interval and the enclosing parser budget. - Cursor(BasicIo& io, BmffSpan range, Budget& budget) : - io_(io), position_(range.offset), end_(range.offset + range.size), budget_(budget) { - } - - //! @brief Return the absolute input offset of the next field. - uint64_t position() const { - return position_; - } - - //! @brief Return the bytes still available within this interval. - uint64_t remaining() const { - return end_ - position_; - } - - //! @brief Return the exclusive absolute end of the containing interval. - uint64_t end() const { - return end_; - } - - //! @brief Skip bytes within the interval without reading their contents. - void advance(uint64_t count) { - require(count <= remaining()); - position_ += count; - } - - //! @brief Read an exact field, charging its bytes to the shared structural budget. - void read(byte* bytes, size_t size) { - require(size <= remaining()); - consume(budget_.bytes, size, budget_.limits.maxBytesRead); - - io_.seekOrThrow(static_cast(position_), BasicIo::beg, ErrorCode::kerInputDataReadFailed); - io_.readOrThrow(bytes, size, ErrorCode::kerInputDataReadFailed); - if (io_.error()) - throw Error(ErrorCode::kerInputDataReadFailed); - - position_ += size; - } - - //! @brief Decode an unsigned big-endian field; a zero-width field has value zero. - uint64_t 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[i]; - return result; - } - - //! @brief Read a terminated string subject to per-string and aggregate limits. - std::string string() { - std::string result; - while (true) { - require(remaining() != 0); - const auto c = static_cast(number(1)); - consume(budget_.strings, 1, budget_.limits.maxStringBytes); - if (c == '\0') - return result; - - require(result.size() < budget_.limits.maxStringLength); - result.push_back(c); - } - } - - //! @brief Reject trailing fields where the supported box layout must be exhausted. - void finish() const { - require(remaining() == 0); - } - - private: - BasicIo& io_; - uint64_t position_; - uint64_t end_; - Budget& budget_; -}; +using Cursor = BmffCursor; // Interpret child box types according to their immediate container. enum class Context { file, meta, info, properties, propertyList, references, dataInfo, dataRefs, canon }; @@ -137,16 +55,15 @@ enum class Context { file, meta, info, properties, propertyList, references, dat class Parser { public: //! @brief Borrow an open input and limits for the duration of parsing. - Parser(BasicIo& io, const BmffLimits& limits) : io_(io), budget_{limits} { - require(io.isopen()); - document_.fileSize = io.size(); - require(document_.fileSize <= static_cast(std::numeric_limits::max())); + Parser(BasicIo& io, const BmffLimits& limits) : + reader_(io, {limits.maxBoxes, limits.maxBytesRead, limits.maxDepth}), budget_{limits} { + document_.fileSize = reader_.fileSize(); } //! @brief Parse structure and resolve item ranges without copying encoded image data. BmffDocument parse() { // Collect structure before checking relationships that may point to later boxes. - Cursor input(io_, {0, document_.fileSize}, budget_); + auto input = reader_.cursor({0, document_.fileSize}); document_.boxes = children(input, Context::file, 0); require(!document_.boxes.empty() && document_.boxes.front().type == bmffType("ftyp")); require(has(document_.boxes, bmffType("ftyp")) && has(document_.boxes, bmffType("meta"))); @@ -162,40 +79,19 @@ class Parser { return std::any_of(boxes.begin(), boxes.end(), [type](const auto& box) { return box.type == type; }); } - // Validate a box header and advance the parent cursor past the entire box. - BmffBox header(Cursor& input) { - consume(budget_.boxes, 1, budget_.limits.maxBoxes); - require(input.remaining() >= 8); - - BmffBox box; - box.span.offset = input.position(); - const auto available = input.remaining(); - box.span.size = input.number(4); - box.type = static_cast(input.number(4)); - box.headerSize = 8; - - // Resolve extended sizes and EOF-sized boxes before bounding the payload. - if (box.span.size == 1) { - box.span.size = input.number(8); - box.headerSize = 16; - } else if (box.span.size == 0) { - // A size-zero box extends to EOF, even when it is nested. - require(input.end() == document_.fileSize); - box.span.size = available; - box.extendsToEnd = true; - } + // 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; - // UUID user types belong to the header, so exclude them from the payload span. - 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()); + require(result.size() < budget_.limits.maxStringLength); + result.push_back(c); } - - // The child cursor will read fields independently of this parent position. - require(box.span.size >= box.headerSize && box.span.size <= available); - input.advance(box.span.size - box.headerSize); - return box; } // Decode version/flags while rejecting unsupported versions and reserved bits. @@ -221,14 +117,11 @@ class Parser { // Traverse children with context-specific decoding and a shared nesting budget. std::vector children(Cursor& input, Context context, unsigned depth, uint8_t version = 0) { - require(depth <= budget_.limits.maxDepth); std::vector boxes; std::set singletons; // Singleton checks apply within each immediate container, not globally. - while (input.remaining() != 0) { - auto box = header(input); - Cursor fields(io_, box.payload(), budget_); + reader_.visit(input, depth, [&](BmffBox& box, Cursor& fields) { auto unique = [&] { require(singletons.insert(box.type).second); }; switch (context) { @@ -331,7 +224,7 @@ class Parser { const auto full = fullBox(box, fields, 0, 1); supported(full.flags == 1, "external data reference"); if (fields.remaining() != 0) - require(fields.string().empty()); + require(string(fields).empty()); fields.finish(); } break; @@ -341,7 +234,7 @@ class Parser { } boxes.push_back(std::move(box)); - } + }); return boxes; } @@ -360,15 +253,15 @@ class Parser { info.protectionIndex = static_cast(input.number(2)); supported(info.protectionIndex == 0, "protected item"); info.type = static_cast(input.number(4)); - info.name = input.string(); + info.name = string(input); // Only MIME and URI items append type-specific strings to the common entry. if (info.type == bmffType("mime")) { - info.contentType = input.string(); + info.contentType = string(input); if (input.remaining() != 0) - info.contentEncoding = input.string(); + info.contentEncoding = string(input); } else if (info.type == bmffType("uri ")) { - info.uriType = input.string(); + info.uriType = string(input); } input.finish(); @@ -536,7 +429,7 @@ class Parser { } } - BasicIo& io_; + BmffReader reader_; Budget budget_; BmffDocument document_; std::set infoIds_; @@ -615,11 +508,6 @@ void checkRelocation(const std::vector& boxes, Context context) { } // namespace -BmffSpan BmffBox::payload() const { - require(headerSize <= span.size && span.size <= std::numeric_limits::max() - span.offset); - return {span.offset + headerSize, span.size - headerSize}; -} - std::vector BmffDocument::metadataItems(uint32_t type) const { // cdsc points from the metadata item to the image it describes. std::set describing; diff --git a/src/bmffimage_int.hpp b/src/bmffimage_int.hpp index 54381e09c2..cf85bbb6eb 100644 --- a/src/bmffimage_int.hpp +++ b/src/bmffimage_int.hpp @@ -7,12 +7,12 @@ #ifdef EXV_ENABLE_BMFF -#include #include #include #include #include #include +#include "bmffbox_int.hpp" namespace Exiv2 { class BasicIo; @@ -20,41 +20,6 @@ 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 Input box boundaries and decoded children, with opaque payloads left in the input. -struct BmffBox { - uint32_t type{}; //!< Packed four-character box code. - 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 Item description and its original infe span, retained for lossless rewriting. struct BmffItemInfo { BmffSpan box; //!< Original infe interval, used to preserve unchanged descriptions. diff --git a/src/meson.build b/src/meson.build index 54941223b0..325bf3afbe 100644 --- a/src/meson.build +++ b/src/meson.build @@ -45,6 +45,7 @@ if get_option('video') endif int_lib = files( + 'bmffbox_int.cpp', 'bmffimage_int.cpp', 'bmffwrite_int.cpp', 'canonmn_int.cpp', diff --git a/unitTests/CMakeLists.txt b/unitTests/CMakeLists.txt index 6fc33f8724..ccbdf45865 100644 --- a/unitTests/CMakeLists.txt +++ b/unitTests/CMakeLists.txt @@ -12,6 +12,7 @@ endif() add_executable( unit_tests test_basicio.cpp + test_bmffbox_int.cpp test_bmffimage_int.cpp test_bmpimage.cpp test_cr2header_int.cpp diff --git a/unitTests/meson.build b/unitTests/meson.build index 866a48c380..d8356e0fb2 100644 --- a/unitTests/meson.build +++ b/unitTests/meson.build @@ -14,6 +14,7 @@ test_sources = files( 'test_TimeValue.cpp', 'test_XmpKey.cpp', 'test_basicio.cpp', + 'test_bmffbox_int.cpp', 'test_bmffimage_int.cpp', 'test_bmpimage.cpp', 'test_cr2header_int.cpp', diff --git a/unitTests/test_bmffbox_int.cpp b/unitTests/test_bmffbox_int.cpp new file mode 100644 index 0000000000..e75c7140f6 --- /dev/null +++ b/unitTests/test_bmffbox_int.cpp @@ -0,0 +1,384 @@ +// SPDX-License-Identifier: GPL-2.0-or-later + +#include "bmffbox_int.hpp" + +#ifdef EXV_ENABLE_BMFF + +#include +#include +#include + +#include +#include +#include + +using namespace Exiv2; +using namespace Exiv2::Internal; + +namespace { +using Bytes = std::vector; +constexpr BmffReadLimits testLimits{100, 1024, 8}; + +// Encode fixture fields independently of the production reader. +void integer(Bytes& bytes, uint64_t value, unsigned width) { + for (unsigned i = width; i != 0; --i) + bytes.push_back(static_cast(value >> ((i - 1) * 8))); +} + +// Append fixture ranges without interpreting their contents. +void append(Bytes& bytes, const Bytes& suffix) { + bytes.insert(bytes.end(), suffix.begin(), suffix.end()); +} + +// Construct ordinary or extended boxes, optionally declaring a terminal size. +Bytes box(uint32_t type, const Bytes& payload = {}, bool extended = false, bool terminal = false) { + Bytes bytes; + integer(bytes, terminal ? 0 : extended ? 1 : payload.size() + 8, 4); + integer(bytes, type, 4); + if (extended) + integer(bytes, payload.size() + 16, 8); + append(bytes, payload); + return bytes; +} + +// Decode only the synthetic nest container's four-byte prefix and child range. +std::vector children(BmffReader& reader, BmffCursor& input, unsigned depth = 0) { + std::vector result; + reader.visit(input, depth, [&](BmffBox& current, BmffCursor& fields) { + if (current.type == bmffType("nest")) { + EXPECT_EQ(fields.number(4), 42u); + current.children = children(reader, fields, depth + 1); + } + result.push_back(std::move(current)); + }); + return result; +} + +// Wrap a child range in the test adapter's prefixed container. +Bytes nested(const Bytes& payload) { + Bytes prefix; + integer(prefix, 42, 4); + append(prefix, payload); + return box(bmffType("nest"), prefix); +} + +// Distinguish malformed structure from failures of the underlying I/O. +template +void expectError(ErrorCode code, Operation operation) { + try { + operation(); + FAIL() << "Expected an Exiv2::Error"; + } catch (const Error& error) { + EXPECT_EQ(error.code(), code); + } +} + +// Borrow fixture bytes and inject failures without permitting source mutation. +class FailingIo : public MemIo { + public: + using MemIo::read; + + // Retain borrowed fixture storage for this test double's lifetime. + explicit FailingIo(const Bytes& bytes) : MemIo(bytes.data(), bytes.size()) { + } + + bool failSeek{}; + bool reportError{}; + + //! @brief Fail selected seeks before any field read occurs. + int seek(int64_t offset, Position origin) override { + return failSeek ? 1 : MemIo::seek(offset, origin); + } + + //! @brief Return a short field unless testing an error after a complete read. + size_t read(byte* output, size_t size) override { + return MemIo::read(output, reportError ? size : size - 1); + } + + //! @brief Inject the stream's error flag independently of its returned byte count. + int error() const override { + return reportError ? 1 : MemIo::error(); + } +}; + +// Expose two stored headers separated by a virtual 8 GiB opaque payload. +class SparseIo : public MemIo { + public: + using MemIo::read; + + // Store a large extended box and a following terminal box, but no payload bytes. + SparseIo() { + integer(prefix, 1, 4); + integer(prefix, bmffType("skip"), 4); + integer(prefix, tailOffset, 8); + tail = box(bmffType("tail"), {}, false, true); + } + + static constexpr uint64_t tailOffset = uint64_t{1} << 33; + Bytes prefix; + Bytes tail; + uint64_t position{}; + size_t bytesRead{}; + bool forbiddenRead{}; + + //! @brief Report a virtual input length without allocating its contents. + size_t size() const override { + return static_cast(tailOffset + tail.size()); + } + + //! @brief Accept absolute seeks within the virtual input. + int seek(int64_t offset, Position origin) override { + if (origin != beg || offset < 0 || static_cast(offset) > size()) + return 1; + position = static_cast(offset); + return 0; + } + + //! @brief Serve only stored headers and detect accidental opaque-payload reads. + size_t read(byte* output, size_t size) override { + const auto& region = position >= tailOffset ? tail : prefix; + const auto relative = position >= tailOffset ? position - tailOffset : position; + if (relative > region.size() || size > region.size() - relative) { + forbiddenRead = true; + return 0; + } + std::copy_n(region.begin() + relative, size, output); + position += size; + bytesRead += size; + return size; + } +}; +} // namespace + +// Generic traversal accepts opaque boxes without requiring image-format markers. +TEST(BmffBoxReader, traversesNonImageBoxesWithoutInterpretingOpaquePayloads) { + auto bytes = box(bmffType("data"), box(bmffType("nest"), {0xff})); + append(bytes, box(bmffType("last"), {1, 2, 3})); + MemIo io(bytes.data(), bytes.size()); + BmffReader reader(io, {2, 16, 0}); + auto input = reader.cursor({0, reader.fileSize()}); + + const auto result = children(reader, input); + + ASSERT_EQ(result.size(), 2u); + EXPECT_EQ(result.front().type, bmffType("data")); + EXPECT_TRUE(result.front().children.empty()); + EXPECT_EQ(result.back().span.offset, result.front().span.size); + EXPECT_EQ(result.back().payload().size, 3u); + EXPECT_EQ(input.position(), bytes.size()); + EXPECT_NO_THROW(input.finish()); +} + +// Empty sibling ranges require neither header reads nor a minimum box count. +TEST(BmffBoxReader, acceptsAnEmptyRangeWithZeroBudgets) { + MemIo io; + BmffReader reader(io, {0, 0, 0}); + auto input = reader.cursor({0, 0}); + EXPECT_TRUE(children(reader, input).empty()); + EXPECT_EQ(input.number(0), 0u); + EXPECT_NO_THROW(input.read(nullptr, 0)); +} + +// Reject input states that cannot support the reader's absolute seek contract. +TEST(BmffBoxReader, rejectsClosedOrUnseekablyLargeInputs) { + // Simulate a closed stream independently of MemIo's always-open storage. + class ClosedIo : public MemIo { + public: + //! @brief Report that the underlying stream is unavailable. + bool isopen() const override { + return false; + } + } closed; + EXPECT_THROW(BmffReader(closed, testLimits), Error); + + if (sizeof(size_t) < 8) + GTEST_SKIP() << "BasicIo size() cannot exceed signed 64-bit offsets on this host"; + + // Report a length that cannot be converted safely to BasicIo's signed offsets. + class OversizedIo : public MemIo { + public: + //! @brief Expose an unrepresentable seek range without allocating storage. + size_t size() const override { + return std::numeric_limits::max(); + } + } oversized; + EXPECT_THROW(BmffReader(oversized, testLimits), Error); +} + +// Preserve encoded header fields while excluding UUID user types from payloads. +TEST(BmffBoxReader, retainsNormalExtendedAndTerminalUuidHeaders) { + for (unsigned mode = 0; mode < 3; ++mode) { + Bytes uuid(16); + for (unsigned i = 0; i < uuid.size(); ++i) + uuid[i] = static_cast(i); + auto payload = uuid; + append(payload, {0x12, 0x34}); + const auto bytes = box(bmffType("uuid"), payload, mode == 1, mode == 2); + MemIo io(bytes.data(), bytes.size()); + BmffReader reader(io, testLimits); + auto input = reader.cursor({0, reader.fileSize()}); + + const auto header = reader.readBox(input); + auto fields = reader.cursor(header.payload()); + + EXPECT_EQ(header.size32, mode == 1 ? 1u : mode == 2 ? 0u : bytes.size()); + EXPECT_EQ(header.headerSize, mode == 1 ? 32u : 24u); + EXPECT_EQ(header.extendsToEnd, mode == 2); + EXPECT_EQ(header.span, (BmffSpan{0, bytes.size()})); + EXPECT_TRUE(std::equal(uuid.begin(), uuid.end(), header.userType.begin())); + EXPECT_EQ(fields.number(2), 0x1234u); + EXPECT_NO_THROW(fields.finish()); + EXPECT_NO_THROW(input.finish()); + } +} + +// Truncating any ordinary, extended, or UUID header must fail before payload use. +TEST(BmffBoxReader, rejectsEveryTruncatedHeader) { + for (const auto type : {bmffType("data"), bmffType("uuid")}) { + for (const bool extended : {false, true}) { + const auto bytes = box(type, type == bmffType("uuid") ? Bytes(16) : Bytes{}, extended); + for (size_t size = 0; size < bytes.size(); ++size) { + SCOPED_TRACE(size); + MemIo io(bytes.data(), size); + BmffReader reader(io, testLimits); + auto input = reader.cursor({0, reader.fileSize()}); + expectError(ErrorCode::kerCorruptedMetadata, [&] { reader.readBox(input); }); + } + } + } +} + +// Check declared lengths against both physical headers and immediate parent ranges. +TEST(BmffBoxReader, rejectsInvalidSizesWithoutOverflowOrSiblingEscape) { + for (const bool extended : {false, true}) { + for (const uint64_t size : {2ULL, 7ULL, 15ULL, 17ULL, std::numeric_limits::max()}) { + Bytes bytes; + integer(bytes, extended ? 1 : size, 4); + integer(bytes, bmffType("data"), 4); + if (extended) + integer(bytes, size, 8); + append(bytes, Bytes(32)); + MemIo io(bytes.data(), bytes.size()); + BmffReader reader(io, testLimits); + auto input = reader.cursor({0, extended ? 16u : 8u}); + expectError(ErrorCode::kerCorruptedMetadata, [&] { reader.readBox(input); }); + } + } +} + +// Size-zero boxes are valid only in ranges that actually reach the end of the file. +TEST(BmffBoxReader, boundsTerminalBoxesByFileEnd) { + auto bytes = box(bmffType("data"), {}, false, true); + append(bytes, box(bmffType("tail"), {}, false, true)); + MemIo io(bytes.data(), bytes.size()); + BmffReader reader(io, testLimits); + auto truncatedParent = reader.cursor({0, 8}); + expectError(ErrorCode::kerCorruptedMetadata, [&] { reader.readBox(truncatedParent); }); + + auto finalChild = reader.cursor({8, 8}); + EXPECT_EQ(reader.readBox(finalChild).span, (BmffSpan{8, 8})); + auto complete = reader.cursor({0, reader.fileSize()}); + EXPECT_EQ(reader.readBox(complete).span.size, bytes.size()); +} + +// Cursor creation and field operations reject arithmetic overflow and range escape. +TEST(BmffBoxReader, checksCursorRangesAndFieldWidths) { + const Bytes bytes{0, 1, 2, 3, 4, 5, 6, 7}; + MemIo io(bytes.data(), bytes.size()); + BmffReader reader(io, testLimits); + EXPECT_THROW(static_cast(reader.cursor({9, 0})), Error); + EXPECT_THROW(static_cast(reader.cursor({1, std::numeric_limits::max()})), Error); + EXPECT_THROW(static_cast(reader.cursor({std::numeric_limits::max(), 2})), Error); + + auto input = reader.cursor({0, bytes.size()}); + EXPECT_THROW(input.number(9), Error); + EXPECT_THROW(input.advance(std::numeric_limits::max()), Error); + EXPECT_THROW(input.finish(), Error); + EXPECT_EQ(input.position(), 0u); + EXPECT_EQ(input.number(8), 0x0001020304050607ULL); + EXPECT_THROW(input.number(1), Error); + EXPECT_NO_THROW(input.finish()); +} + +// Only the adapter knows the container prefix and which boxes contain children. +TEST(BmffBoxReader, traversesAdapterSelectedChildrenAfterTheirPrefix) { + auto bytes = nested(nested(box(bmffType("leaf"), {1}))); + append(bytes, box(bmffType("last"))); + MemIo io(bytes.data(), bytes.size()); + BmffReader reader(io, testLimits); + auto input = reader.cursor({0, reader.fileSize()}); + + const auto result = children(reader, input); + + ASSERT_EQ(result.size(), 2u); + ASSERT_EQ(result[0].children.size(), 1u); + ASSERT_EQ(result[0].children[0].children.size(), 1u); + EXPECT_EQ(result[0].children[0].children[0].span.offset, 24u); + EXPECT_EQ(result[0].children[0].children[0].type, bmffType("leaf")); + EXPECT_EQ(result[1].type, bmffType("last")); +} + +// Byte and box budgets are cumulative across nested and newly obtained cursors. +TEST(BmffBoxReader, enforcesCallerBudgetsAcrossAllVisits) { + const auto bytes = nested(box(bmffType("leaf"))); + for (const auto limits : {BmffReadLimits{1, 20, 1}, BmffReadLimits{2, 19, 1}, BmffReadLimits{2, 20, 0}}) { + MemIo io(bytes.data(), bytes.size()); + BmffReader reader(io, limits); + auto input = reader.cursor({0, reader.fileSize()}); + EXPECT_THROW(children(reader, input), Error); + } + + MemIo io(bytes.data(), bytes.size()); + BmffReader reader(io, {2, 20, 1}); + auto input = reader.cursor({0, reader.fileSize()}); + EXPECT_NO_THROW(children(reader, input)); + auto revisit = reader.cursor({0, reader.fileSize()}); + EXPECT_THROW(reader.readBox(revisit), Error); +} + +// A cursor cannot charge another reader's budget or read that reader's input. +TEST(BmffBoxReader, rejectsCursorsFromAnotherReader) { + const auto bytes = box(bmffType("data")); + MemIo io(bytes.data(), bytes.size()); + BmffReader first(io, testLimits), second(io, testLimits); + auto input = first.cursor({0, first.fileSize()}); + EXPECT_THROW(second.readBox(input), Error); + EXPECT_THROW(children(second, input), Error); + EXPECT_EQ(input.position(), 0u); +} + +// Failed seeks, short reads, and stream errors remain I/O errors and never write. +TEST(BmffBoxReader, propagatesIoFailuresWithoutMutatingSource) { + const auto bytes = box(bmffType("data")); + for (unsigned mode = 0; mode < 3; ++mode) { + FailingIo io(bytes); + io.failSeek = mode == 1; + io.reportError = mode == 2; + BmffReader reader(io, testLimits); + auto input = reader.cursor({0, reader.fileSize()}); + expectError(ErrorCode::kerInputDataReadFailed, [&] { reader.readBox(input); }); + EXPECT_EQ(input.position(), 0u); + EXPECT_TRUE(std::equal(bytes.begin(), bytes.end(), io.mmap())); + } +} + +// Skip an extended opaque payload beyond 32-bit offsets using only header reads. +TEST(BmffBoxReader, traversesSparse64BitRangesWithoutPayloadReads) { + if (sizeof(size_t) < 8) + GTEST_SKIP() << "BasicIo size() cannot represent this input on a 32-bit host"; + SparseIo io; + BmffReader reader(io, {2, 24, 0}); + auto input = reader.cursor({0, reader.fileSize()}); + + const auto result = children(reader, input); + + ASSERT_EQ(result.size(), 2u); + EXPECT_EQ(result[0].size32, 1u); + EXPECT_EQ(result[0].span.size, SparseIo::tailOffset); + EXPECT_EQ(result[1].span.offset, SparseIo::tailOffset); + EXPECT_EQ(result[1].size32, 0u); + EXPECT_EQ(io.bytesRead, 24u); + EXPECT_FALSE(io.forbiddenRead); +} + +#endif // EXV_ENABLE_BMFF From 68f889f715aa4e28892fd2b1bec4d165de0b4e77 Mon Sep 17 00:00:00 2001 From: Vaclav Haisman Date: Sat, 10 Oct 2026 12:52:32 +0200 Subject: [PATCH 29/40] [bmff] Separate standard item mechanics from HEIF policy Extract a reusable item model and parser with explicit limits and format policy hooks. Keep HEIF admission, metadata selection, Canon handling and relocation rules in a dedicated adapter. Rename the HEIF-specific writer and update both build systems and tests. --- src/CMakeLists.txt | 10 +- src/bmffbox_int.hpp | 6 + src/bmffimage_int.hpp | 155 ------ src/{bmffimage_int.cpp => bmffitem_int.cpp} | 365 +++++-------- src/bmffitem_int.hpp | 205 +++++++ src/heifimage_int.cpp | 56 +- src/heifstructure_int.cpp | 285 ++++++++++ src/heifstructure_int.hpp | 83 +++ src/{bmffwrite_int.cpp => heifwrite_int.cpp} | 154 +++--- src/{bmffwrite_int.hpp => heifwrite_int.hpp} | 27 +- src/meson.build | 5 +- unitTests/test_bmffimage_int.cpp | 532 +++++++++++++------ 12 files changed, 1174 insertions(+), 709 deletions(-) delete mode 100644 src/bmffimage_int.hpp rename src/{bmffimage_int.cpp => bmffitem_int.cpp} (50%) create mode 100644 src/bmffitem_int.hpp create mode 100644 src/heifstructure_int.cpp create mode 100644 src/heifstructure_int.hpp rename src/{bmffwrite_int.cpp => heifwrite_int.cpp} (84%) rename src/{bmffwrite_int.hpp => heifwrite_int.hpp} (58%) diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 56444a3a9a..4dcd1e7ff6 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -6,10 +6,12 @@ add_library( exiv2lib_int OBJECT bmffbox_int.cpp bmffbox_int.hpp - bmffimage_int.cpp - bmffimage_int.hpp - bmffwrite_int.cpp - bmffwrite_int.hpp + bmffitem_int.cpp + bmffitem_int.hpp + heifstructure_int.cpp + heifstructure_int.hpp + heifwrite_int.cpp + heifwrite_int.hpp canonmn_int.cpp canonmn_int.hpp casiomn_int.cpp diff --git a/src/bmffbox_int.hpp b/src/bmffbox_int.hpp index bb6e606281..cca23a4216 100644 --- a/src/bmffbox_int.hpp +++ b/src/bmffbox_int.hpp @@ -55,6 +55,12 @@ struct BmffBox { [[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. diff --git a/src/bmffimage_int.hpp b/src/bmffimage_int.hpp deleted file mode 100644 index cf85bbb6eb..0000000000 --- a/src/bmffimage_int.hpp +++ /dev/null @@ -1,155 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0-or-later - -#ifndef BMFFIMAGE_INT_HPP -#define BMFFIMAGE_INT_HPP - -#include "config.h" - -#ifdef EXV_ENABLE_BMFF - -#include -#include -#include -#include -#include -#include "bmffbox_int.hpp" - -namespace Exiv2 { -class BasicIo; -} - -namespace Exiv2::Internal { - -//! @brief Item description and its original infe span, retained for lossless rewriting. -struct BmffItemInfo { - BmffSpan box; //!< Original infe interval, used to preserve unchanged descriptions. - uint8_t version{}; //!< Item info version selecting the ID width. - uint32_t flags{}; //!< Item info flags retained when rewriting. - uint32_t type{}; //!< Packed four-character item type. - uint16_t protectionIndex{}; //!< Zero for supported unprotected items. - std::string name; //!< Decoded null-terminated item name. - std::string contentType; //!< MIME content type, present only for mime items. - std::string contentEncoding; //!< Optional MIME content encoding. - std::string uriType; //!< URI type string, present only for uri items. -}; - -//! @brief An iloc extent with its original fields and resolved absolute source interval. -struct BmffExtent { - uint64_t index{}; //!< Original extent index, retained without interpreting it. - uint64_t offset{}; //!< Offset relative to the item base in its construction method. - uint64_t length{}; //!< Explicit nonzero extent length. - BmffSpan source; //!< Validated absolute input interval for these bytes. -}; - -//! @brief Item addressing and aggregate size; method 0 is file-relative, method 1 idat-relative. -struct BmffItemLocation { - uint8_t constructionMethod{}; //!< Zero selects mdat/file addressing; one selects idat-relative addressing. - uint16_t dataReferenceIndex{}; //!< Zero selects local storage; external references are unsupported. - uint64_t baseOffset{}; //!< Base offset added to each extent in the selected coordinate system. - uint64_t dataSize{}; //!< Sum of declared extent lengths, including any repeated bytes. - std::vector extents; //!< Ordered extents comprising the item payload. -}; - -//! @brief Join an item's independently ordered info and location records by ID. -struct BmffItem { - BmffItemInfo info; //!< Description from the item information table. - BmffItemLocation location; //!< Addressing from the item location table. -}; - -//! @brief Version and field widths shared by all records in an iloc box. -struct BmffLocationFormat { - BmffSpan box; //!< Original iloc box interval. - uint8_t version{}; //!< Location version selecting ID and construction fields. - uint8_t offsetSize{}; //!< Extent offset field width in bytes. - uint8_t lengthSize{}; //!< Extent length field width in bytes. - uint8_t baseOffsetSize{}; //!< Item base-offset field width in bytes. - uint8_t indexSize{}; //!< Extent index field width in bytes. -}; - -//! @brief A directed item relationship, retaining destination order and its original box span. -struct BmffReference { - BmffSpan box; //!< Original reference child box interval. - uint32_t type{}; //!< Packed reference type, such as cdsc or auxl. - uint32_t from{}; //!< Source item ID. - std::vector to; //!< Destination item IDs in their declared order. -}; - -//! @brief One property index and whether it is essential to interpreting the associated item. -struct BmffPropertyAssociation { - uint16_t index{}; //!< One-based property index; zero denotes no association. - bool essential{}; //!< True when understanding this property is required for the item. -}; - -//! @brief Ordered properties associated with one item in a particular ipma box. -struct BmffAssociationEntry { - BmffSpan box; //!< Containing ipma box interval. - uint32_t itemId{}; //!< Item to which these properties apply. - std::vector properties; //!< Associations in their declared order. -}; - -//! @brief Limits apply to aggregate structural work, independently of encoded image size. -struct BmffLimits { - uint64_t maxBoxes{100000}; //!< Maximum number of boxes across all containers. - uint64_t maxItems{65536}; //!< Maximum number of distinct item IDs. - uint64_t maxExtents{1000000}; //!< Maximum aggregate number of item extents. - uint64_t maxReferences{1000000}; //!< Maximum aggregate number of reference destinations. - uint64_t maxAssociations{1000000}; //!< Budget for association records and their property entries. - uint64_t maxStringBytes{1024 * 1024}; //!< Maximum aggregate bytes consumed by strings, including terminators. - uint64_t maxStringLength{65536}; //!< Maximum bytes in one string, excluding its terminator. - uint64_t maxBytesRead{16 * 1024 * 1024}; //!< Maximum structural bytes read, independent of media size. - unsigned maxDepth{16}; //!< Maximum child-box nesting depth below the file context. -}; - -//! @brief Checked item-based BMFF structure, independent of BmffImage's metadata state. -struct BmffDocument { - uint64_t fileSize{}; //!< Original input length in bytes. - uint32_t majorBrand{}; //!< Major brand from ftyp. - uint32_t minorVersion{}; //!< Minor version from ftyp. - std::vector compatibleBrands; //!< Compatible brands in their original order. - std::vector boxes; //!< Top-level boxes in original file order. - uint32_t primaryItem{}; //!< Primary image item ID from pitm. - BmffLocationFormat locationFormat; //!< Shared iloc version and field widths. - std::map items; //!< Checked item descriptions and locations keyed by ID. - std::vector infoOrder; //!< Item IDs in original iinf order, defining metadata merge precedence. - std::vector locationOrder; //!< Item IDs in original iloc order. - std::vector references; //!< Directed relationships in original traversal order. - std::vector properties; //!< Property boxes in one-based index order. - std::vector associations; //!< Item-to-property associations in original traversal order. - std::vector mediaData; //!< Absolute mdat payload intervals in file order. - std::optional itemData; //!< Absolute idat payload interval when present. - - /*! - @brief Select Exif or XMP items describing the primary image, in iinf order. - @param type Exif item type or MIME item type; MIME selection requires application/rdf+xml. - @return IDs whose cdsc references include the primary item. - */ - [[nodiscard]] std::vector metadataItems(uint32_t type) const; -}; - -/*! - @brief Parse an open, seekable BasicIo without reading image payloads or writing. - @param io Borrowed input, already open and seekable. - @param limits Bounds on aggregate structural work and nesting. - @return An owning structural model whose payload ranges refer to the original input. - @throws Error For malformed or unsupported structure, exceeded limits, or failed I/O. - - The input must stay unchanged while its returned ranges are used. The stream - position may change. Malformed input throws kerCorruptedMetadata; unsupported - syntax throws an explicit unsupported-layout error. Parsing alone does not - authorize rewriting: call enforceHeifWriteSupport before using a rewrite path. - */ -BmffDocument parseBmff(BasicIo& io, const BmffLimits& limits = {}); - -/*! - @brief Reject deferred brands and opaque structures whose relocation is not supported. - @param document A validated model returned by parseBmff(). - @throws Error If the modeled layout is outside the HEIF write envelope. - - This checks layout eligibility only. The rewriter must still validate the - requested changes against shared metadata references and overlapping extents. - */ -void enforceHeifWriteSupport(const BmffDocument& document); - -} // namespace Exiv2::Internal -#endif // EXV_ENABLE_BMFF -#endif // BMFFIMAGE_INT_HPP diff --git a/src/bmffimage_int.cpp b/src/bmffitem_int.cpp similarity index 50% rename from src/bmffimage_int.cpp rename to src/bmffitem_int.cpp index 2d35e7898e..c5d7d52b31 100644 --- a/src/bmffimage_int.cpp +++ b/src/bmffitem_int.cpp @@ -1,6 +1,6 @@ // SPDX-License-Identifier: GPL-2.0-or-later -#include "bmffimage_int.hpp" +#include "bmffitem_int.hpp" #ifdef EXV_ENABLE_BMFF @@ -17,20 +17,11 @@ namespace Exiv2::Internal { namespace { -constexpr std::array canonUuid{0x85, 0xc0, 0xb6, 0x87, 0x82, 0x0f, 0x11, 0xe0, - 0x81, 0x11, 0xf4, 0xce, 0x46, 0x2b, 0x6a, 0x48}; - // Report malformed structure through the common metadata error code. void require(bool condition) { enforce(condition, ErrorCode::kerCorruptedMetadata); } -// Distinguish unsupported layouts from corrupt container data. -void supported(bool condition, std::string_view feature) { - if (!condition) - throw Error(ErrorCode::kerErrorMessage, std::string("Unsupported HEIF layout: ") + std::string(feature)); -} - // 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); @@ -39,7 +30,7 @@ void consume(uint64_t& used, uint64_t amount, uint64_t limit) { // Shared counters bound work across all nested boxes in one parse. struct Budget { - const BmffLimits& limits; + const BmffItemLimits& limits; uint64_t extents{}; uint64_t references{}; uint64_t associations{}; @@ -49,31 +40,31 @@ struct Budget { using Cursor = BmffCursor; // Interpret child box types according to their immediate container. -enum class Context { file, meta, info, properties, propertyList, references, dataInfo, dataRefs, canon }; +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 an open input and limits for the duration of parsing. - Parser(BasicIo& io, const BmffLimits& limits) : - reader_(io, {limits.maxBoxes, limits.maxBytesRead, limits.maxDepth}), budget_{limits} { - document_.fileSize = reader_.fileSize(); + //! @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 Parse structure and resolve item ranges without copying encoded image data. - BmffDocument parse() { - // Collect structure before checking relationships that may point to later boxes. - auto input = reader_.cursor({0, document_.fileSize}); - document_.boxes = children(input, Context::file, 0); - require(!document_.boxes.empty() && document_.boxes.front().type == bmffType("ftyp")); - require(has(document_.boxes, bmffType("ftyp")) && has(document_.boxes, bmffType("meta"))); - - // Cross-check item records only after both iinf and iloc have been read. - validateItems(); - return std::move(document_); + //! @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; }); @@ -107,12 +98,12 @@ class Parser { // Find or create an item shared by its independently ordered info/location records. BmffItem& item(uint32_t id) { require(id != 0); - const auto found = document_.items.find(id); - if (found != document_.items.end()) + const auto found = model_.items.find(id); + if (found != model_.items.end()) return found->second; - require(document_.items.size() < budget_.limits.maxItems); - return document_.items.try_emplace(id).first->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. @@ -125,41 +116,21 @@ class Parser { auto unique = [&] { require(singletons.insert(box.type).second); }; switch (context) { - case Context::file: - if (box.type == bmffType("ftyp")) { - unique(); - require(fields.remaining() >= 8 && fields.remaining() % 4 == 0); - document_.majorBrand = static_cast(fields.number(4)); - document_.minorVersion = static_cast(fields.number(4)); - require(fields.remaining() / 4 <= budget_.limits.maxBoxes); - while (fields.remaining() != 0) - document_.compatibleBrands.push_back(static_cast(fields.number(4))); - } else if (box.type == bmffType("meta")) { - unique(); - fullBox(box, fields, 0); - box.children = children(fields, Context::meta, depth + 1); - - // A picture meta box must provide the tables needed to resolve its primary item. - for (const auto required : - {bmffType("hdlr"), bmffType("pitm"), bmffType("iinf"), bmffType("iloc"), bmffType("iprp")}) - require(has(box.children, required)); - } else if (box.type == bmffType("mdat")) { - document_.mediaData.push_back(box.payload()); - } - break; case Context::meta: if (box.type == bmffType("hdlr")) { unique(); fullBox(box, fields, 0); require(fields.number(4) == 0); - supported(fields.number(4) == bmffType("pict"), "non-picture handler"); + 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); - document_.primaryItem = static_cast(fields.number(full.version == 0 ? 2 : 4)); + model_.primaryItem = static_cast(fields.number(full.version == 0 ? 2 : 4)); + model_.hasPrimaryItem = true; fields.finish(); } else if (box.type == bmffType("iinf")) { unique(); @@ -181,13 +152,13 @@ class Parser { require(has(box.children, bmffType("ipco"))); } else if (box.type == bmffType("idat")) { unique(); - document_.itemData = box.payload(); + 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 if (box.type == bmffType("uuid") && box.userType == canonUuid) { - box.children = children(fields, Context::canon, depth + 1); + } else { + policy_.parseExtension(reader_, box, fields, depth + 1); } break; case Context::info: @@ -198,7 +169,7 @@ class Parser { if (box.type == bmffType("ipco")) { unique(); box.children = children(fields, Context::propertyList, depth + 1); - document_.properties = box.children; + model_.properties = box.children; } else if (box.type == bmffType("ipma")) { associations(box, fields); } @@ -214,7 +185,7 @@ class Parser { unique(); fullBox(box, fields, 0); const auto count = fields.number(4); - require(count <= budget_.limits.maxBoxes && count <= fields.remaining() / 8); + require(count <= budget_.limits.maxEntries && count <= fields.remaining() / 8); box.children = children(fields, Context::dataRefs, depth + 1); require(box.children.size() == count); } @@ -228,9 +199,6 @@ class Parser { fields.finish(); } break; - case Context::canon: - unique(); - break; } boxes.push_back(std::move(box)); @@ -251,7 +219,7 @@ class Parser { info.version = full.version; info.flags = full.flags; info.protectionIndex = static_cast(input.number(2)); - supported(info.protectionIndex == 0, "protected item"); + policy_.checkProtection(info.protectionIndex); info.type = static_cast(input.number(4)); info.name = string(input); @@ -265,13 +233,13 @@ class Parser { } input.finish(); - document_.infoOrder.push_back(id); + 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 = document_.locationFormat; + auto& format = model_.locationFormat; format.box = box.span; format.version = full.version; @@ -321,7 +289,7 @@ class Parser { supported(extent.length != 0, "implicit extent length"); location.extents.push_back(extent); } - document_.locationOrder.push_back(id); + model_.locationOrder.push_back(id); } input.finish(); @@ -344,7 +312,7 @@ class Parser { ref.to.push_back(static_cast(input.number(width))); input.finish(); - document_.references.push_back(std::move(ref)); + model_.references.push_back(std::move(ref)); } // Read property indices and their essential flags without interpreting properties. @@ -372,207 +340,114 @@ class Parser { const unsigned essential = propertyWidth == 1 ? 0x80 : 0x8000; entry.properties.push_back({static_cast(value & (essential - 1)), (value & essential) != 0}); } - document_.associations.push_back(std::move(entry)); + model_.associations.push_back(std::move(entry)); } input.finish(); } - // Resolve addressing and reject incomplete items, invalid ranges, and dangling links. - void validateItems() { - require(infoIds_ == locationIds_ && !infoIds_.empty()); - require(document_.items.contains(document_.primaryItem)); - - // Method 0 uses file offsets; method 1 uses offsets from the idat payload. - for (auto& [id, item] : document_.items) { - auto& location = item.location; - for (auto& extent : location.extents) { - BmffSpan enclosing{0, document_.fileSize}; - if (location.constructionMethod == 1) { - require(document_.itemData.has_value()); - enclosing = *document_.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}; - - // File-relative extents must lie wholly within a single mdat payload. - if (location.constructionMethod == 0) { - auto media = std::upper_bound(document_.mediaData.begin(), document_.mediaData.end(), extent.source.offset, - [](uint64_t offset, const BmffSpan& range) { return offset < range.offset; }); - require(media != document_.mediaData.begin()); - --media; - const auto offset = extent.source.offset - media->offset; - require(offset <= media->size && extent.length <= media->size - offset); - } - 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 : document_.references) { - require(document_.items.contains(ref.from)); - for (const auto id : ref.to) - require(document_.items.contains(id)); - } - - // Property indices are one-based; an essential property cannot use the zero sentinel. - for (const auto& entry : document_.associations) { - require(document_.items.contains(entry.itemId)); - for (const auto& property : entry.properties) { - require(property.index <= document_.properties.size()); - require(property.index != 0 || !property.essential); - } - } - } - - BmffReader reader_; + BmffReader& reader_; Budget budget_; - BmffDocument document_; + const BmffItemPolicy& policy_; + BmffItemModel model_; std::set infoIds_; std::set locationIds_; }; -// Recognize padding that can be discarded or regenerated during rewriting. -bool padding(uint32_t type) { - return type == bmffType("free") || type == bmffType("skip"); +} // namespace + +void BmffItemPolicy::unsupported(std::string_view feature) const { + throw Error(ErrorCode::kerErrorMessage, std::string("Unsupported BMFF item layout: ") + std::string(feature)); } -// Reject opaque structures unless their payloads are known to be safe to relocate. -void checkRelocation(const std::vector& boxes, Context context) { - static constexpr auto propertyTypes = - std::array{bmffType("hvcC"), bmffType("av1C"), bmffType("ispe"), bmffType("pixi"), bmffType("colr"), - bmffType("irot"), bmffType("imir"), bmffType("clap"), bmffType("pasp"), bmffType("auxC"), - bmffType("rloc"), bmffType("clli"), bmffType("mdcv"), bmffType("cclv")}; - - // Reading preserves unknown boxes, but moving them requires an explicit safe case. - for (const auto& box : boxes) { - if (padding(box.type)) - continue; - switch (context) { - case Context::file: - if (box.type == bmffType("meta")) - checkRelocation(box.children, Context::meta); - else - supported(box.type == bmffType("ftyp") || box.type == bmffType("mdat"), "unmodeled top-level box"); - break; - case Context::meta: - switch (box.type) { - case bmffType("hdlr"): - case bmffType("pitm"): - case bmffType("iloc"): - case bmffType("idat"): - case bmffType("iinf"): - case bmffType("iref"): - break; - case bmffType("iprp"): - checkRelocation(box.children, Context::properties); - break; - case bmffType("dinf"): - checkRelocation(box.children, Context::dataInfo); - break; - case bmffType("uuid"): - supported( - box.userType == canonUuid && box.children.size() == 1 && box.children.front().type == bmffType("CNCV"), - "unmodeled UUID"); - break; - default: - supported(false, "unmodeled metadata box"); - } - break; - case Context::properties: - if (box.type == bmffType("ipco")) - checkRelocation(box.children, Context::propertyList); - else - supported(box.type == bmffType("ipma"), "unmodeled property container"); - break; - case Context::propertyList: - supported(std::find(propertyTypes.begin(), propertyTypes.end(), box.type) != propertyTypes.end(), - "unmodeled item property"); - break; - case Context::dataInfo: - supported(box.type == bmffType("dref"), "unmodeled data information"); - checkRelocation(box.children, Context::dataRefs); - break; - case Context::dataRefs: - supported(box.type == bmffType("url "), "unmodeled data reference"); - break; - default: - supported(false, "unmodeled container"); - } - } +void BmffItemPolicy::checkHandler(uint32_t) const { } -} // namespace +void BmffItemPolicy::checkProtection(uint16_t) const { +} -std::vector BmffDocument::metadataItems(uint32_t type) const { - // cdsc points from the metadata item to the image it describes. - std::set describing; - for (const auto& reference : references) { - if (reference.type == bmffType("cdsc") && - std::find(reference.to.begin(), reference.to.end(), primaryItem) != reference.to.end()) - describing.insert(reference.from); - } +void BmffItemPolicy::checkMeta(const BmffBox&) const { +} - // Keep iinf order so later metadata items have deterministic merge precedence. - std::vector result; - for (const auto id : infoOrder) { - const auto& info = items.at(id).info; - if (describing.contains(id) && info.type == type && - (type != bmffType("mime") || info.contentType == "application/rdf+xml")) - result.push_back(id); - } +void BmffItemPolicy::checkItems(const BmffItemModel&) const { +} + +void BmffItemPolicy::checkExtent(const BmffItemLocation&, const BmffExtent&) const { +} - return result; +void BmffItemPolicy::parseExtension(BmffReader&, BmffBox&, BmffCursor&, unsigned) const { } -BmffDocument parseBmff(BasicIo& io, const BmffLimits& limits) { - return Parser(io, limits).parse(); +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 enforceHeifWriteSupport(const BmffDocument& document) { - supported(document.majorBrand == bmffType("heic") || document.majorBrand == bmffType("heix") || - document.majorBrand == bmffType("mif1"), - "file brand"); - - // A generic mif1 brand can accompany an AVIF or another deferred codec. - supported(std::find(document.compatibleBrands.begin(), document.compatibleBrands.end(), bmffType("avif")) == - document.compatibleBrands.end() && - std::find(document.compatibleBrands.begin(), document.compatibleBrands.end(), bmffType("avis")) == - document.compatibleBrands.end(), - "AVIF writing is deferred"); - - const auto primaryType = document.items.at(document.primaryItem).info.type; - supported(primaryType == bmffType("hvc1") || primaryType == bmffType("grid") || primaryType == bmffType("iden") || - primaryType == bmffType("iovl"), - "primary image type"); - - // Recognize near-matching XMP MIME labels so they cannot evade removal checks. - for (const auto& reference : document.references) { - if (reference.type != bmffType("cdsc") || - std::find(reference.to.begin(), reference.to.end(), document.primaryItem) == reference.to.end()) - continue; - const auto& info = document.items.at(reference.from).info; - if (info.type != bmffType("mime")) - continue; - auto type = info.contentType.substr(0, info.contentType.find(';')); - std::transform(type.begin(), type.end(), type.begin(), - [](unsigned char c) { return static_cast(c >= 'A' && c <= 'Z' ? c + ('a' - 'A') : c); }); - const auto first = type.find_first_not_of(" \t"); - const auto last = type.find_last_not_of(" \t"); - if (first != std::string::npos) - type = type.substr(first, last - first + 1); - if (type == "application/rdf+xml") { - supported(info.contentType == "application/rdf+xml", "ambiguous primary XMP MIME type"); - supported(info.contentEncoding.empty(), "compressed primary XMP"); +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); } } +} - // Finally reject any retained opaque box whose internal offsets are unknown. - checkRelocation(document.boxes, Context::file); +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 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 +#include +#include +#include +#include +#include "bmffbox_int.hpp" + +namespace Exiv2 { +class BasicIo; +} + +namespace Exiv2::Internal { + +//! @brief Item description and its original infe span, retained for lossless rewriting. +struct BmffItemInfo { + BmffSpan box; //!< Original infe interval, used to preserve unchanged descriptions. + uint8_t version{}; //!< Item info version selecting the ID width. + uint32_t flags{}; //!< Item info flags retained when rewriting. + uint32_t type{}; //!< Packed four-character item type. + uint16_t protectionIndex{}; //!< Protection scheme index; zero denotes an unprotected item. + std::string name; //!< Decoded null-terminated item name. + std::string contentType; //!< MIME content type, present only for mime items. + std::string contentEncoding; //!< Optional MIME content encoding. + std::string uriType; //!< URI type string, present only for uri items. +}; + +//! @brief An iloc extent with its original fields and resolved absolute source interval. +struct BmffExtent { + uint64_t index{}; //!< Original extent index, retained without interpreting it. + uint64_t offset{}; //!< Offset relative to the item base in its construction method. + uint64_t length{}; //!< Explicit nonzero extent length. + BmffSpan source; //!< Validated absolute input interval for these bytes. +}; + +//! @brief Item addressing and aggregate size; method 0 is file-relative, method 1 idat-relative. +struct BmffItemLocation { + uint8_t constructionMethod{}; //!< Zero selects file-relative addressing; one selects idat-relative addressing. + uint16_t dataReferenceIndex{}; //!< Zero selects local storage; external references are unsupported. + uint64_t baseOffset{}; //!< Base offset added to each extent in the selected coordinate system. + uint64_t dataSize{}; //!< Sum of declared extent lengths, including any repeated bytes. + std::vector extents; //!< Ordered extents comprising the item payload. +}; + +//! @brief Join an item's independently ordered info and location records by ID. +struct BmffItem { + BmffItemInfo info; //!< Description from the item information table. + BmffItemLocation location; //!< Addressing from the item location table. +}; + +//! @brief Version and field widths shared by all records in an iloc box. +struct BmffLocationFormat { + BmffSpan box; //!< Original iloc box interval. + uint8_t version{}; //!< Location version selecting ID and construction fields. + uint8_t offsetSize{}; //!< Extent offset field width in bytes. + uint8_t lengthSize{}; //!< Extent length field width in bytes. + uint8_t baseOffsetSize{}; //!< Item base-offset field width in bytes. + uint8_t indexSize{}; //!< Extent index field width in bytes. +}; + +//! @brief A directed item relationship, retaining destination order and its original box span. +struct BmffReference { + BmffSpan box; //!< Original reference child box interval. + uint32_t type{}; //!< Packed reference type, such as cdsc or auxl. + uint32_t from{}; //!< Source item ID. + std::vector to; //!< Destination item IDs in their declared order. +}; + +//! @brief One property index and whether it is essential to interpreting the associated item. +struct BmffPropertyAssociation { + uint16_t index{}; //!< One-based property index; zero denotes no association. + bool essential{}; //!< True when understanding this property is required for the item. +}; + +//! @brief Ordered properties associated with one item in a particular ipma box. +struct BmffAssociationEntry { + BmffSpan box; //!< Containing ipma box interval. + uint32_t itemId{}; //!< Item to which these properties apply. + std::vector properties; //!< Associations in their declared order. +}; + +//! @brief Explicit bounds for one item model; box I/O limits belong to BmffReader. +struct BmffItemLimits { + uint64_t maxItems; //!< Maximum number of distinct item IDs. + uint64_t maxExtents; //!< Maximum aggregate extent count. + uint64_t maxReferences; //!< Maximum aggregate reference endpoints. + uint64_t maxAssociations; //!< Maximum association records plus property entries. + uint64_t maxStringBytes; //!< Maximum aggregate string bytes including terminators. + uint64_t maxStringLength; //!< Maximum bytes in a string excluding its terminator. + uint64_t maxEntries; //!< Maximum declared data-reference entries. +}; + +//! @brief Standard tables in one meta box, independent of file brands and metadata interpretation. +struct BmffItemModel { + uint32_t handler{}; //!< Handler type from hdlr, when present. + uint32_t primaryItem{}; //!< Item ID from pitm; meaningful only when hasPrimaryItem is true. + bool hasPrimaryItem{}; //!< Distinguish an absent pitm from an invalid zero item ID. + BmffLocationFormat locationFormat; //!< Shared iloc version and field widths. + std::map items; //!< Item descriptions and locations keyed by ID. + std::vector infoOrder; //!< Item IDs in original iinf order. + std::vector locationOrder; //!< Item IDs in original iloc order. + std::vector references; //!< Directed relationships in traversal order. + std::vector properties; //!< Opaque property boxes in one-based index order. + std::vector associations; //!< Item-to-property associations in traversal order. + std::optional itemData; //!< Absolute idat payload interval when present. +}; + +/*! + @brief Optional format admission checks and extension traversal for the standard item parser. + + The default policy adds no format restrictions and leaves unknown boxes opaque. + Adapters may reject fields as they are decoded to retain their error precedence. + Borrowed policy and reader references must outlive each parse or resolution call. + */ +class BmffItemPolicy { + public: + //! @brief Destroy a format policy through its private shared interface. + virtual ~BmffItemPolicy() = default; + + //! @brief Report unsupported standard syntax; adapters may preserve their existing diagnostic. + [[noreturn]] virtual void unsupported(std::string_view feature) const; + + //! @brief Check a decoded handler before the remaining hdlr fields are consumed. + virtual void checkHandler(uint32_t handler) const; + + //! @brief Check the protection index before the remaining infe fields are consumed. + virtual void checkProtection(uint16_t index) const; + + //! @brief Check required children after the meta box has been parsed. + virtual void checkMeta(const BmffBox& box) const; + + //! @brief Check item admission after matching descriptions and locations, before range resolution. + virtual void checkItems(const BmffItemModel& model) const; + + //! @brief Check format-specific ownership of a resolved extent within the source file. + virtual void checkExtent(const BmffItemLocation& location, const BmffExtent& extent) const; + + /*! + @brief Optionally parse an unknown meta child using the same reader and resource counters. + @param reader Borrowed reader sharing the enclosing parse's I/O and nesting budgets. + @param box Header whose children may be populated by the adapter. + @param fields Cursor over this box's payload; prefixes may be consumed by the adapter. + @param childDepth Nesting depth to use when visiting children of this box. + + The default leaves the box opaque. The adapter must not inspect bytes outside + fields or restart resource counters when descending into a custom container. + */ + virtual void parseExtension(BmffReader& reader, BmffBox& box, BmffCursor& fields, unsigned childDepth) const; +}; + +/*! + @brief Parse one meta box's standard tables without interpreting codecs or metadata payloads. + @param reader Open, seekable source reader shared with the enclosing file adapter. + @param box Already decoded meta header; its full-box prefix and children are populated. + @param fields Cursor at the start of box's payload, including the version and flags. + @param childDepth Depth to use when visiting the meta children. + @param limits Explicit bounds for work within this model. + @param policy Borrowed format checks and extension traversal, or the neutral default policy. + @return An owning table model with unresolved extent source spans. + @throws Error For malformed tables, unsupported standard syntax, exceeded limits or I/O errors. + + No ftyp, brand, picture handler, primary item or property table is required. + Unknown children remain opaque. Call resolveBmffItems after all source ranges + are known, before reading payloads or using the model for rewriting. The input + must remain unchanged while any returned spans are used; its position may change. + */ +BmffItemModel parseBmffItems(BmffReader& reader, BmffBox& box, BmffCursor& fields, unsigned childDepth, + const BmffItemLimits& limits, const BmffItemPolicy& policy = {}); + +/*! + @brief Validate table links and resolve file-relative or idat-relative extents. + @param model Parsed item model, updated with absolute source spans and aggregate sizes. + @param fileSize Length of the unchanged source file, within BasicIo's signed seek range. + @param policy Additional item and extent checks supplied by the format adapter. + @throws Error For incomplete items, dangling references, invalid ranges or policy rejection. + + Method 0 may address any bytes in the source file. Adapters impose payload + ownership restrictions when needed. Repeated resolution recomputes sizes. + */ +void resolveBmffItems(BmffItemModel& model, uint64_t fileSize, const BmffItemPolicy& policy = {}); + +/*! + @brief Gather a resolved item's extents in their declared order, without interpreting the bytes. + @param input Open, seekable source, unchanged since parsing and resolution. + @param item Item with validated absolute extents and aggregate data size. + @param limit Maximum allocation size in bytes, chosen by the caller. + @return An owned contiguous copy of the item payload. + @throws Error If the allocation limit is exceeded, ranges disagree, or source I/O fails. + + The stream position may change. This function does not decode protection schemes. + */ +std::vector readBmffItem(BasicIo& input, const BmffItem& item, uint64_t limit); + +} // namespace Exiv2::Internal +#endif // EXV_ENABLE_BMFF +#endif // BMFFITEM_INT_HPP diff --git a/src/heifimage_int.cpp b/src/heifimage_int.cpp index a3ccf83816..9aae4f3aa0 100644 --- a/src/heifimage_int.cpp +++ b/src/heifimage_int.cpp @@ -5,10 +5,10 @@ #ifdef EXV_ENABLE_BMFF #include "basicio.hpp" #include "bmffimage.hpp" -#include "bmffwrite_int.hpp" #include "enforce.hpp" #include "error.hpp" #include "futils.hpp" +#include "heifwrite_int.hpp" #include "tags.hpp" #include "tiffimage.hpp" #include "value.hpp" @@ -64,7 +64,7 @@ void supported(bool condition, std::string_view reason) { // Read a bounded property payload from a validated absolute input span. Bytes readRange(BasicIo& io, BmffSpan span) { - supported(span.size <= bmffMetadataLimit, "metadata exceeds the allocation limit"); + supported(span.size <= heifMetadataLimit, "metadata exceeds the allocation limit"); Bytes bytes(static_cast(span.size)); io.seekOrThrow(static_cast(span.offset), BasicIo::beg, ErrorCode::kerInputDataReadFailed); io.readOrThrow(bytes.data(), bytes.size(), ErrorCode::kerInputDataReadFailed); @@ -79,7 +79,7 @@ std::string encodeXmp(const XmpData& data) { std::string packet; enforce(XmpParser::encode(packet, data, XmpParser::useCompactFormat | XmpParser::omitAllFormatting) == 0, ErrorCode::kerInvalidXMP); - supported(packet.size() <= bmffMetadataLimit, "XMP exceeds the allocation limit"); + supported(packet.size() <= heifMetadataLimit, "XMP exceeds the allocation limit"); return packet; } @@ -132,13 +132,13 @@ bool sameData(const Data& a, const Data& b) { std::multimap> values; uint64_t total = 0; for (const auto& datum : data) { - supported(datum.size() <= bmffMetadataLimit - total, "metadata exceeds the allocation limit"); + supported(datum.size() <= heifMetadataLimit - total, "metadata exceeds the allocation limit"); total += datum.size(); Bytes bytes(datum.size()); if (!bytes.empty()) datum.copy(bytes.data(), littleEndian); - supported(datum.value().sizeDataArea() <= bmffMetadataLimit - total, "metadata exceeds the allocation limit"); + supported(datum.value().sizeDataArea() <= heifMetadataLimit - total, "metadata exceeds the allocation limit"); auto area = datum.value().dataArea(); total += area.size(); @@ -166,7 +166,7 @@ struct Metadata { }; // Decode primary-image items in file order and retain the state needed for later writes. -Metadata readMetadata(BasicIo& io, const BmffDocument& document, const DecodeParams& params) { +Metadata readMetadata(BasicIo& io, const HeifDocument& document, const DecodeParams& params) { Metadata metadata; MetadataMerger exifMerger; MetadataMerger embeddedMerger; @@ -174,7 +174,7 @@ Metadata readMetadata(BasicIo& io, const BmffDocument& document, const DecodePar // Charge all Exif and XMP payloads to one aggregate allocation budget. auto read = [&](uint32_t id) { - auto bytes = readBmffItem(io, document.items.at(id), bmffMetadataLimit - total); + auto bytes = readHeifItem(io, document.meta.items.at(id), heifMetadataLimit - total); total += bytes.size(); return bytes; }; @@ -228,7 +228,7 @@ Metadata readMetadata(BasicIo& io, const BmffDocument& document, const DecodePar #endif auto xmpIds = document.metadataItems(bmffType("mime")); for (auto id : xmpIds) { - supported(document.items.at(id).info.contentEncoding.empty(), "compressed primary XMP"); + supported(document.meta.items.at(id).info.contentEncoding.empty(), "compressed primary XMP"); auto bytes = read(id); std::string packet(bytes.begin(), bytes.end()); #ifdef EXV_HAVE_XMP_TOOLKIT @@ -249,15 +249,15 @@ Metadata readMetadata(BasicIo& io, const BmffDocument& document, const DecodePar // Read dimensions and ICC only from properties associated with the primary item. std::set properties; - for (const auto& entry : document.associations) { - if (entry.itemId == document.primaryItem) { + for (const auto& entry : document.meta.associations) { + if (entry.itemId == document.meta.primaryItem) { for (const auto& association : entry.properties) if (association.index != 0) properties.insert(association.index); } } for (auto index : properties) { - const auto& property = document.properties.at(index - 1); + const auto& property = document.meta.properties.at(index - 1); if (property.type != bmffType("ispe") && property.type != bmffType("colr")) continue; auto bytes = readRange(io, property.payload()); @@ -342,15 +342,15 @@ Bytes encodeExif(ExifData exif, const IptcData& iptc, XmpData embedded, ByteOrde MemIo output; uint64_t total = 0; for (const auto& datum : exif) { - supported(datum.size() <= bmffMetadataLimit - total, "Exif exceeds the allocation limit"); + supported(datum.size() <= heifMetadataLimit - total, "Exif exceeds the allocation limit"); total += datum.size(); - supported(datum.value().sizeDataArea() <= bmffMetadataLimit - total, "Exif exceeds the allocation limit"); + supported(datum.value().sizeDataArea() <= heifMetadataLimit - total, "Exif exceeds the allocation limit"); total += datum.value().sizeDataArea(); } // Use no original TIFF backing buffer, so deleted values cannot survive in slack. TiffParser::encode(output, nullptr, 0, order, exif, iptc, embedded); - supported(output.size() <= bmffMetadataLimit - 4, "Exif exceeds the allocation limit"); + supported(output.size() <= heifMetadataLimit - 4, "Exif exceeds the allocation limit"); // A zero HEIF Exif offset places the TIFF header immediately after the prefix. Bytes bytes(4 + output.size(), 0); @@ -371,9 +371,9 @@ Bytes encodeExif(ExifData exif, const IptcData& iptc, XmpData embedded, ByteOrde } // Detect media bytes that no current item owns, including stale metadata from older edits. -bool hasOrphanedMedia(const BmffDocument& document) { +bool hasOrphanedMedia(const HeifDocument& document) { std::vector spans; - for (const auto& [id, item] : document.items) + for (const auto& [id, item] : document.meta.items) for (const auto& extent : item.location.extents) spans.push_back(extent.source); @@ -390,7 +390,7 @@ bool hasOrphanedMedia(const BmffDocument& document) { } // A gap in either mdat or idat requires compaction even without a metadata edit. - uint64_t available = document.itemData ? document.itemData->size : 0; + uint64_t available = document.meta.itemData ? document.meta.itemData->size : 0; for (const auto span : document.mediaData) available += span.size; return covered != available; @@ -595,11 +595,11 @@ class HeifImage final : public BmffImage { IoCloser closer(*io_); try { - const auto document = parseBmff(*io_); + const auto document = parseHeif(*io_); brand_ = document.majorBrand; // Opaque Adobe UUID packets need the legacy reader's traversal and precedence. - if (!hasAdobeXmpUuid(document.boxes)) { + if (!hasAdobeXmpUuid(document.file.boxes)) { assign(Internal::readMetadata(*io_, document, DecodeParams(max_recursion_depth_))); return; } @@ -631,7 +631,7 @@ class HeifImage final : public BmffImage { #else supported(image.xmpData().empty(), "structured XMP editing requires the XMP toolkit"); const auto& sourcePacket = image.xmpPacket(); - supported(sourcePacket.size() <= bmffMetadataLimit, "XMP exceeds the allocation limit"); + supported(sourcePacket.size() <= heifMetadataLimit, "XMP exceeds the allocation limit"); // Snapshot both views before changing this image, which may also be the source. const auto exif = image.exifData(); @@ -675,7 +675,7 @@ class HeifImage final : public BmffImage { //! @brief Select a bounded raw XMP replacement without requiring structured editing support. void setXmpPacket(const std::string& packet) override { - supported(packet.size() <= bmffMetadataLimit, "XMP exceeds the allocation limit"); + supported(packet.size() <= heifMetadataLimit, "XMP exceeds the allocation limit"); #ifdef EXV_HAVE_XMP_TOOLKIT Image::setXmpPacket(packet); #else @@ -707,7 +707,7 @@ class HeifImage final : public BmffImage { supported(dynamic_cast(io_.get()) == nullptr, "remote I/O"); enforce(io_->open() == 0, ErrorCode::kerDataSourceOpenFailed, io_->path(), strError()); IoCloser closer(*io_); - auto document = parseBmff(*io_); + auto document = parseHeif(*io_); enforceHeifWriteSupport(document); const DecodeParams params(max_recursion_depth_); auto original = Internal::readMetadata(*io_, document, params); @@ -739,7 +739,7 @@ class HeifImage final : public BmffImage { supported(xmpData_.empty(), "structured XMP editing requires the XMP toolkit"); #endif auto packet = writeXmpFromPacket() ? xmpPacket_ : encodeXmp(xmpData_); - supported(packet.size() <= bmffMetadataLimit, "XMP exceeds the allocation limit"); + supported(packet.size() <= heifMetadataLimit, "XMP exceeds the allocation limit"); const bool xmpChanged = removeXmp_ || (writeXmpFromPacket() ? packet != original.packet : packet != encodeXmp(original.xmp)); const bool exifChanged = removeExif_ || !sameData(exif, original.exif); @@ -747,7 +747,7 @@ class HeifImage final : public BmffImage { "merging different primary XMP packets requires the XMP toolkit"); // Promote embedded XMP to its own item when Exif removal would otherwise discard it. - BmffMetadataUpdate update; + HeifMetadataUpdate update; if (xmpChanged || (exifChanged && exif.empty() && original.hasEmbeddedXmp)) update.xmp = Bytes(packet.begin(), packet.end()); @@ -767,7 +767,7 @@ class HeifImage final : public BmffImage { // explicit raw-tag edit replaces that union with the current first packet. embedded.clear(); if (auto xml = exif.findKey(xmlPacketKey()); xml != exif.end()) { - supported(xml->size() <= bmffMetadataLimit, "embedded XMP exceeds the allocation limit"); + supported(xml->size() <= heifMetadataLimit, "embedded XMP exceeds the allocation limit"); Bytes bytes(xml->size()); xml->copy(bytes.data(), original.order); enforce(XmpParser::decode(embedded, std::string(bytes.begin(), bytes.end()), params) == 0, @@ -796,8 +796,8 @@ class HeifImage final : public BmffImage { // Prepare and decode the complete result before touching the original destination. PreparedOutput prepared(*io_); - rewriteBmff(*io_, prepared.io(), document, update); - auto verified = Internal::readMetadata(prepared.io(), parseBmff(prepared.io()), params); + rewriteHeif(*io_, prepared.io(), document, update); + auto verified = Internal::readMetadata(prepared.io(), parseHeif(prepared.io()), params); const auto preparedSize = prepared.io().size(); // The final BasicIo transfer can still fail after preparation; it is not an atomic replacement. @@ -880,7 +880,7 @@ bool isHeifType(BasicIo& io, bool advance) { } // Accept complete bounded brand tables, including the extended-size header form. - matched = matched && size >= headerSize + 8 && size <= BmffLimits{}.maxBytesRead && size <= io.size() - start && + matched = matched && size >= headerSize + 8 && size <= HeifLimits{}.boxes.maxBytesRead && size <= io.size() - start && (size - headerSize) % 4 == 0; if (matched) { diff --git a/src/heifstructure_int.cpp b/src/heifstructure_int.cpp new file mode 100644 index 0000000000..9f793368a1 --- /dev/null +++ b/src/heifstructure_int.cpp @@ -0,0 +1,285 @@ +// SPDX-License-Identifier: GPL-2.0-or-later + +#include "heifstructure_int.hpp" + +#ifdef EXV_ENABLE_BMFF + +#include "basicio.hpp" +#include "enforce.hpp" +#include "error.hpp" + +#include +#include +#include +#include +#include + +namespace Exiv2::Internal { +namespace { + +constexpr std::array canonUuid{0x85, 0xc0, 0xb6, 0x87, 0x82, 0x0f, 0x11, 0xe0, + 0x81, 0x11, 0xf4, 0xce, 0x46, 0x2b, 0x6a, 0x48}; + +// Report malformed structure through the common metadata error code. +void require(bool condition) { + enforce(condition, ErrorCode::kerCorruptedMetadata); +} + +// Distinguish unsupported layouts from corrupt container data. +void supported(bool condition, std::string_view feature) { + if (!condition) + throw Error(ErrorCode::kerErrorMessage, std::string("Unsupported HEIF layout: ") + std::string(feature)); +} + +// Test for a required child without imposing its meaning on generic traversal. +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; }); +} + +// Keep native HEIF admission and Canon extensions separate from standard item mechanics. +class HeifItemPolicy final : public BmffItemPolicy { + public: + //! @brief Borrow the document while framing fills its media ownership ranges. + explicit HeifItemPolicy(const HeifDocument& document) : document_(document) { + } + + //! @brief Preserve the HEIF diagnostic for unsupported standard item syntax. + [[noreturn]] void unsupported(std::string_view feature) const override { + throw Error(ErrorCode::kerErrorMessage, std::string("Unsupported HEIF layout: ") + std::string(feature)); + } + + //! @brief Admit only picture handlers to the native HEIF metadata path. + void checkHandler(uint32_t handler) const override { + supported(handler == bmffType("pict"), "non-picture handler"); + } + + //! @brief Keep protected items on the unsupported-layout path. + void checkProtection(uint16_t index) const override { + supported(index == 0, "protected item"); + } + + //! @brief Require the tables needed to resolve the primary image and its properties. + void checkMeta(const BmffBox& box) const override { + for (const auto required : + {bmffType("hdlr"), bmffType("pitm"), bmffType("iinf"), bmffType("iloc"), bmffType("iprp")}) + require(has(box.children, required)); + } + + //! @brief Preserve the native reader's nonempty primary-image requirement. + void checkItems(const BmffItemModel& model) const override { + require(!model.items.empty()); + require(model.items.contains(model.primaryItem)); + } + + //! @brief Require each file-relative extent to lie wholly in one mdat payload. + void checkExtent(const BmffItemLocation& location, const BmffExtent& extent) const override { + if (location.constructionMethod != 0) + return; + + const auto& ranges = document_.mediaData; + auto media = std::upper_bound(ranges.begin(), ranges.end(), extent.source.offset, + [](uint64_t offset, const BmffSpan& range) { return offset < range.offset; }); + require(media != ranges.begin()); + --media; + const auto offset = extent.source.offset - media->offset; + require(offset <= media->size && extent.length <= media->size - offset); + } + + //! @brief Expose Canon UUID child headers with the enclosing reader's limits and duplicate checks. + void parseExtension(BmffReader& reader, BmffBox& box, BmffCursor& fields, unsigned childDepth) const override { + if (box.type != bmffType("uuid") || box.userType != canonUuid) + return; + + std::set singletons; + reader.visit(fields, childDepth, [&](BmffBox& child, BmffCursor&) { + require(singletons.insert(child.type).second); + box.children.push_back(std::move(child)); + }); + } + + private: + const HeifDocument& document_; +}; + +// Relocation decisions depend on the HEIF container owning each box. +enum class Context { file, meta, properties, propertyList, dataInfo, dataRefs }; + +// Recognize padding that can be discarded or regenerated during rewriting. +bool padding(uint32_t type) { + return type == bmffType("free") || type == bmffType("skip"); +} + +// Reject opaque structures unless their payloads are known to be safe to relocate. +void checkRelocation(const std::vector& boxes, Context context) { + static constexpr auto propertyTypes = + std::array{bmffType("hvcC"), bmffType("av1C"), bmffType("ispe"), bmffType("pixi"), bmffType("colr"), + bmffType("irot"), bmffType("imir"), bmffType("clap"), bmffType("pasp"), bmffType("auxC"), + bmffType("rloc"), bmffType("clli"), bmffType("mdcv"), bmffType("cclv")}; + + // Reading preserves unknown boxes, but moving them requires an explicit safe case. + for (const auto& box : boxes) { + if (padding(box.type)) + continue; + switch (context) { + case Context::file: + if (box.type == bmffType("meta")) + checkRelocation(box.children, Context::meta); + else + supported(box.type == bmffType("ftyp") || box.type == bmffType("mdat"), "unmodeled top-level box"); + break; + case Context::meta: + switch (box.type) { + case bmffType("hdlr"): + case bmffType("pitm"): + case bmffType("iloc"): + case bmffType("idat"): + case bmffType("iinf"): + case bmffType("iref"): + break; + case bmffType("iprp"): + checkRelocation(box.children, Context::properties); + break; + case bmffType("dinf"): + checkRelocation(box.children, Context::dataInfo); + break; + case bmffType("uuid"): + supported( + box.userType == canonUuid && box.children.size() == 1 && box.children.front().type == bmffType("CNCV"), + "unmodeled UUID"); + break; + default: + supported(false, "unmodeled metadata box"); + } + break; + case Context::properties: + if (box.type == bmffType("ipco")) + checkRelocation(box.children, Context::propertyList); + else + supported(box.type == bmffType("ipma"), "unmodeled property container"); + break; + case Context::propertyList: + supported(std::find(propertyTypes.begin(), propertyTypes.end(), box.type) != propertyTypes.end(), + "unmodeled item property"); + break; + case Context::dataInfo: + supported(box.type == bmffType("dref"), "unmodeled data information"); + checkRelocation(box.children, Context::dataRefs); + break; + case Context::dataRefs: + supported(box.type == bmffType("url "), "unmodeled data reference"); + break; + default: + supported(false, "unmodeled container"); + } + } +} + +} // namespace + +std::vector HeifDocument::metadataItems(uint32_t type) const { + // cdsc points from the metadata item to the image it describes. + std::set describing; + for (const auto& reference : meta.references) { + if (reference.type == bmffType("cdsc") && + std::find(reference.to.begin(), reference.to.end(), meta.primaryItem) != reference.to.end()) + describing.insert(reference.from); + } + + // Keep iinf order so later metadata items have deterministic merge precedence. + std::vector result; + for (const auto id : meta.infoOrder) { + const auto& info = meta.items.at(id).info; + if (describing.contains(id) && info.type == type && + (type != bmffType("mime") || info.contentType == "application/rdf+xml")) + result.push_back(id); + } + + return result; +} + +HeifDocument parseHeif(BasicIo& io, const HeifLimits& limits) { + BmffReader reader(io, limits.boxes); + HeifDocument document; + document.file.size = reader.fileSize(); + const HeifItemPolicy policy(document); + auto input = reader.cursor({0, document.file.size}); + std::set singletons; + + // Frame the file while the item parser handles only the standard meta tables. + reader.visit(input, 0, [&](BmffBox& box, BmffCursor& fields) { + if (box.type == bmffType("ftyp")) { + require(singletons.insert(box.type).second); + require(fields.remaining() >= 8 && fields.remaining() % 4 == 0); + document.majorBrand = static_cast(fields.number(4)); + document.minorVersion = static_cast(fields.number(4)); + require(fields.remaining() / 4 <= limits.boxes.maxBoxes); + while (fields.remaining() != 0) + document.compatibleBrands.push_back(static_cast(fields.number(4))); + } else if (box.type == bmffType("meta")) { + require(singletons.insert(box.type).second); + auto itemLimits = limits.items; + itemLimits.maxEntries = std::min(itemLimits.maxEntries, limits.boxes.maxBoxes); + document.meta = parseBmffItems(reader, box, fields, 1, itemLimits, policy); + } else if (box.type == bmffType("mdat")) { + document.mediaData.push_back(box.payload()); + } + document.file.boxes.push_back(std::move(box)); + }); + + // Resolve ranges after framing discovers mdat payloads both before and after meta. + require(!document.file.boxes.empty() && document.file.boxes.front().type == bmffType("ftyp")); + require(has(document.file.boxes, bmffType("ftyp")) && has(document.file.boxes, bmffType("meta"))); + resolveBmffItems(document.meta, document.file.size, policy); + return document; +} + +void enforceHeifWriteSupport(const HeifDocument& document) { + supported(document.majorBrand == bmffType("heic") || document.majorBrand == bmffType("heix") || + document.majorBrand == bmffType("mif1"), + "file brand"); + + // A generic mif1 brand can accompany an AVIF or another deferred codec. + supported(std::find(document.compatibleBrands.begin(), document.compatibleBrands.end(), bmffType("avif")) == + document.compatibleBrands.end() && + std::find(document.compatibleBrands.begin(), document.compatibleBrands.end(), bmffType("avis")) == + document.compatibleBrands.end(), + "AVIF writing is deferred"); + + const auto primaryType = document.meta.items.at(document.meta.primaryItem).info.type; + supported(primaryType == bmffType("hvc1") || primaryType == bmffType("grid") || primaryType == bmffType("iden") || + primaryType == bmffType("iovl"), + "primary image type"); + + // Recognize near-matching XMP MIME labels so they cannot evade removal checks. + for (const auto& reference : document.meta.references) { + if (reference.type != bmffType("cdsc") || + std::find(reference.to.begin(), reference.to.end(), document.meta.primaryItem) == reference.to.end()) + continue; + const auto& info = document.meta.items.at(reference.from).info; + if (info.type != bmffType("mime")) + continue; + auto type = info.contentType.substr(0, info.contentType.find(';')); + std::transform(type.begin(), type.end(), type.begin(), + [](unsigned char c) { return static_cast(c >= 'A' && c <= 'Z' ? c + ('a' - 'A') : c); }); + const auto first = type.find_first_not_of(" \t"); + const auto last = type.find_last_not_of(" \t"); + if (first != std::string::npos) + type = type.substr(first, last - first + 1); + if (type == "application/rdf+xml") { + supported(info.contentType == "application/rdf+xml", "ambiguous primary XMP MIME type"); + supported(info.contentEncoding.empty(), "compressed primary XMP"); + } + } + + // Finally reject any retained opaque box whose internal offsets are unknown. + checkRelocation(document.file.boxes, Context::file); +} + +std::vector readHeifItem(BasicIo& input, const BmffItem& item, uint64_t limit) { + if (item.location.dataSize > limit || item.location.dataSize > std::numeric_limits::max()) + throw Error(ErrorCode::kerErrorMessage, "Unsupported HEIF edit: metadata exceeds the allocation limit"); + return readBmffItem(input, item, limit); +} + +} // namespace Exiv2::Internal +#endif // EXV_ENABLE_BMFF diff --git a/src/heifstructure_int.hpp b/src/heifstructure_int.hpp new file mode 100644 index 0000000000..c67b857f9e --- /dev/null +++ b/src/heifstructure_int.hpp @@ -0,0 +1,83 @@ +// SPDX-License-Identifier: GPL-2.0-or-later + +#ifndef HEIFSTRUCTURE_INT_HPP +#define HEIFSTRUCTURE_INT_HPP + +#include "bmffitem_int.hpp" + +#ifdef EXV_ENABLE_BMFF + +#include + +namespace Exiv2::Internal { + +//! @brief HEIF-specific defaults; other adapters choose their own reader and item budgets. +struct HeifLimits { + BmffReadLimits boxes{100000, 16 * 1024 * 1024, 16}; //!< Framing, I/O and nesting bounds. + + BmffItemLimits items{ + 65536, + 1000000, + 1000000, + 1000000, + 1024 * 1024, + 65536, + std::numeric_limits::max()}; //!< Item bounds; maxEntries is also capped by boxes.maxBoxes. +}; + +//! @brief HEIF framing and item tables with the policy context required for metadata edits. +struct HeifDocument { + BmffFile file; //!< Source framing, independent of item tables. + BmffItemModel meta; //!< Standard item tables from the single top-level meta box. + uint32_t majorBrand{}; //!< Major brand from ftyp. + uint32_t minorVersion{}; //!< Minor version from ftyp. + std::vector compatibleBrands; //!< Compatible brands in their original order. + std::vector mediaData; //!< Absolute mdat payload intervals allowed to own file-relative items. + + /*! + @brief Select primary Exif or XMP items in iinf order, preserving merge precedence. + @param type Exif or MIME item type; MIME selection requires application/rdf+xml. + @return IDs whose cdsc references include the primary image item. + */ + [[nodiscard]] std::vector metadataItems(uint32_t type) const; +}; + +//! @brief HEIF metadata allocations are bounded independently of encoded image size. +inline constexpr uint64_t heifMetadataLimit = 64 * 1024 * 1024; + +/*! + @brief Parse the item layout admitted by the HEIF adapter, without decoding image data. + @param io Borrowed input, already open and seekable; its position may change. + @param limits Bounds on structural I/O, nesting and item tables. + @return Owned framing and item tables whose source spans borrow the unchanged input bytes. + @throws Error For malformed or unsupported layout, exceeded limits or failed I/O. + + This preserves the native HEIF reader's admission rules. Parsing does not + authorize writing; enforceHeifWriteSupport also checks brands and relocation. + Legacy fallback interpretation remains in BmffImage, outside the standard item model. + */ +HeifDocument parseHeif(BasicIo& io, const HeifLimits& limits = {}); + +/*! + @brief Reject deferred brands and opaque structures whose relocation is not supported. + @param document Validated model returned by parseHeif(). + @throws Error If the layout is outside the HEIF write envelope. + + The rewriter must additionally validate requested edits against shared references + and overlapping ranges. No output is prepared by this check. + */ +void enforceHeifWriteSupport(const HeifDocument& document); + +/*! + @brief Read one resolved item with HEIF allocation limits and existing edit diagnostics. + @param input Open, seekable input, unchanged since parsing; its position may change. + @param item Item with validated extents and aggregate size. + @param limit Remaining allocation budget for metadata, in bytes. + @return Owned payload bytes, assembled in extent order. + @throws Error For an exceeded limit, inconsistent ranges or failed input I/O. + */ +std::vector readHeifItem(BasicIo& input, const BmffItem& item, uint64_t limit = heifMetadataLimit); + +} // namespace Exiv2::Internal +#endif // EXV_ENABLE_BMFF +#endif // HEIFSTRUCTURE_INT_HPP diff --git a/src/bmffwrite_int.cpp b/src/heifwrite_int.cpp similarity index 84% rename from src/bmffwrite_int.cpp rename to src/heifwrite_int.cpp index a213e5700d..03e88ad92c 100644 --- a/src/bmffwrite_int.cpp +++ b/src/heifwrite_int.cpp @@ -1,6 +1,6 @@ // SPDX-License-Identifier: GPL-2.0-or-later -#include "bmffwrite_int.hpp" +#include "heifwrite_int.hpp" #ifdef EXV_ENABLE_BMFF @@ -47,7 +47,7 @@ uint64_t end(BmffSpan span) { // Append a bounded big-endian field, rejecting values that do not fit its width. void number(Bytes& bytes, uint64_t value, unsigned width) { require(width <= 8 && (width == 8 || value < (uint64_t{1} << (width * 8)))); - require(bytes.size() <= BmffLimits{}.maxBytesRead - width); + require(bytes.size() <= HeifLimits{}.boxes.maxBytesRead - width); for (unsigned i = width; i != 0; --i) bytes.push_back(static_cast(value >> ((i - 1) * 8))); @@ -55,7 +55,8 @@ void number(Bytes& bytes, uint64_t value, unsigned width) { // Append a terminated string within the structural serialization budget. void string(Bytes& bytes, std::string_view value) { - require(value.size() < BmffLimits{}.maxBytesRead && bytes.size() < BmffLimits{}.maxBytesRead - value.size()); + require(value.size() < HeifLimits{}.boxes.maxBytesRead && + bytes.size() < HeifLimits{}.boxes.maxBytesRead - value.size()); bytes.insert(bytes.end(), value.begin(), value.end()); bytes.push_back(0); } @@ -157,14 +158,14 @@ void mergeRanges(std::vector& spans) { class Rewrite { public: //! @brief Borrow both streams and the original model; keep a separate model for the edit. - Rewrite(BasicIo& input, BasicIo& output, const BmffDocument& original) : + Rewrite(BasicIo& input, BasicIo& output, const HeifDocument& original) : input_(input), output_(output), original_(original), document_(original) { } //! @brief Validate the edit, converge its layout, and verify the prepared output. - void run(const BmffMetadataUpdate& update) { + void run(const HeifMetadataUpdate& update) { require(&input_ != &output_ && input_.isopen() && output_.isopen() && output_.size() == 0); - require(input_.size() == original_.fileSize); + require(input_.size() == original_.file.size); enforceHeifWriteSupport(original_); // Check graph and byte ownership before preparing any output. @@ -175,9 +176,9 @@ class Rewrite { applyUpdates(); // Index retained structures and normalize field widths before layout iteration. - for (const auto& entry : document_.associations) + for (const auto& entry : document_.meta.associations) associations_[entry.box.offset].push_back(&entry); - indexBoxes(original_.boxes); + indexBoxes(original_.file.boxes); normalizeLocations(); // Only offset width can change after locating the output; it promotes 4 -> 8 once. @@ -209,7 +210,7 @@ class Rewrite { if (!value) return; - supported(value->size() <= bmffMetadataLimit, "metadata exceeds the allocation limit"); + supported(value->size() <= heifMetadataLimit, "metadata exceeds the allocation limit"); const auto ids = original_.metadataItems(type); removed_.insert(ids.begin(), ids.end()); if (!value->empty()) @@ -218,11 +219,12 @@ class Rewrite { // Reject removal of metadata that also participates in retained relationships. void validateReferences() const { - for (const auto& ref : original_.references) { + for (const auto& ref : original_.meta.references) { if (removed_.contains(ref.from)) { - supported(ref.type == bmffType("cdsc") && - std::all_of(ref.to.begin(), ref.to.end(), [&](auto id) { return id == original_.primaryItem; }), - "selected metadata is shared or has other relationships"); + supported( + ref.type == bmffType("cdsc") && + std::all_of(ref.to.begin(), ref.to.end(), [&](auto id) { return id == original_.meta.primaryItem; }), + "selected metadata is shared or has other relationships"); } else { for (const auto id : ref.to) supported(!removed_.contains(id), "selected metadata is referenced by another item"); @@ -233,8 +235,8 @@ class Rewrite { // Find the owning media payload, keyed by its absolute start in the input. uint64_t container(const BmffItem& item, BmffSpan span) const { if (item.location.constructionMethod == 1) { - require(original_.itemData.has_value()); - const auto data = *original_.itemData; + require(original_.meta.itemData.has_value()); + const auto data = *original_.meta.itemData; require(span.offset >= data.offset && end(span) <= end(data)); return data.offset; } @@ -251,7 +253,7 @@ class Rewrite { // Collect retained byte unions and prove they do not overlap discarded metadata. void collectRanges() { std::vector discarded; - for (const auto& [id, item] : original_.items) { + for (const auto& [id, item] : original_.meta.items) { for (const auto& extent : item.location.extents) { if (removed_.contains(id)) discarded.push_back(extent.source); @@ -280,14 +282,14 @@ class Rewrite { // Prefer an ID above the existing set, falling back to its first gap at the limit. uint32_t allocateId() const { - require(!document_.items.empty()); - const auto greatest = document_.items.rbegin()->first; + require(!document_.meta.items.empty()); + const auto greatest = document_.meta.items.rbegin()->first; if (greatest != max32) return greatest + 1; // At the maximum ID, search existing gaps rather than wrapping the counter. uint32_t id = 1; - for (const auto& [used, item] : document_.items) { + for (const auto& [used, item] : document_.meta.items) { if (used != id) return id; supported(id != max32, "no unused item ID"); @@ -300,15 +302,15 @@ class Rewrite { void applyUpdates() { // Drop the removed items and all structures owned by those metadata items. for (const auto id : removed_) - document_.items.erase(id); - std::erase_if(document_.infoOrder, [&](auto id) { return removed_.contains(id); }); - std::erase_if(document_.locationOrder, [&](auto id) { return removed_.contains(id); }); - std::erase_if(document_.references, [&](const auto& ref) { return removed_.contains(ref.from); }); - std::erase_if(document_.associations, [&](const auto& entry) { return removed_.contains(entry.itemId); }); + document_.meta.items.erase(id); + std::erase_if(document_.meta.infoOrder, [&](auto id) { return removed_.contains(id); }); + std::erase_if(document_.meta.locationOrder, [&](auto id) { return removed_.contains(id); }); + std::erase_if(document_.meta.references, [&](const auto& ref) { return removed_.contains(ref.from); }); + std::erase_if(document_.meta.associations, [&](const auto& entry) { return removed_.contains(entry.itemId); }); // Every replacement gets a new description and a cdsc link to the primary image. for (const auto& [type, bytes] : additions_) { - require(document_.items.size() < BmffLimits{}.maxItems); + require(document_.meta.items.size() < HeifLimits{}.items.maxItems); const auto id = allocateId(); BmffItem item; item.info.version = id > max16 ? 3 : 2; @@ -320,10 +322,10 @@ class Rewrite { item.location.dataSize = bytes->size(); item.location.extents.push_back({0, 0, bytes->size(), {}}); - document_.items.emplace(id, std::move(item)); - document_.infoOrder.push_back(id); - document_.locationOrder.push_back(id); - document_.references.push_back({{}, bmffType("cdsc"), id, {document_.primaryItem}}); + document_.meta.items.emplace(id, std::move(item)); + document_.meta.infoOrder.push_back(id); + document_.meta.locationOrder.push_back(id); + document_.meta.references.push_back({{}, bmffType("cdsc"), id, {document_.meta.primaryItem}}); newItems_.emplace(id, bytes); } } @@ -338,15 +340,15 @@ class Rewrite { // Normalize base offsets and choose widths/versions before measuring output layout. void normalizeLocations() { - auto& format = document_.locationFormat; + auto& format = document_.meta.locationFormat; format.offsetSize = 4; format.lengthSize = 4; format.baseOffsetSize = 0; - if (document_.items.rbegin()->first > max16 || document_.items.size() > max16) + if (document_.meta.items.rbegin()->first > max16 || document_.meta.items.size() > max16) format.version = 2; // Preserve idat addressing, but eliminate per-item base offsets in the new layout. - for (auto& [id, item] : document_.items) { + for (auto& [id, item] : document_.meta.items) { item.location.baseOffset = 0; if (item.location.constructionMethod == 1) format.version = std::max(format.version, 1); @@ -358,7 +360,7 @@ class Rewrite { // Preserve existing infe entries or serialize a description for a new metadata item. Box itemInfo(uint32_t id) const { - const auto& info = document_.items.at(id).info; + const auto& info = document_.meta.items.at(id).info; if (info.box.size) return opaque(*originalBoxes_.at(info.box.offset)); @@ -379,16 +381,16 @@ class Rewrite { // Serialize current item locations with the widths selected for this layout pass. Bytes locations() const { - const auto& format = document_.locationFormat; + const auto& format = document_.meta.locationFormat; auto bytes = full(format.version); number(bytes, (format.offsetSize << 4) | format.lengthSize, 1); number(bytes, format.indexSize, 1); const unsigned width = format.version == 2 ? 4 : 2; - number(bytes, document_.items.size(), width); + number(bytes, document_.meta.items.size(), width); // Retain location-table order while writing normalized extent coordinates. - for (const auto id : document_.locationOrder) { - const auto& loc = document_.items.at(id).location; + for (const auto id : document_.meta.locationOrder) { + const auto& loc = document_.meta.items.at(id).location; number(bytes, id, width); if (format.version) number(bytes, loc.constructionMethod, 2); @@ -412,12 +414,12 @@ class Rewrite { box.type = bmffType("iref"); box.extended = original && original->headerSize == 16; uint8_t version = original ? original->fullBox->version : 0; - if (document_.items.rbegin()->first > max16) + if (document_.meta.items.rbegin()->first > max16) version = 1; box.prefix = full(version); // Relationships retain their direction and destination order. - for (const auto& ref : document_.references) { + for (const auto& ref : document_.meta.references) { Box child; child.type = ref.type; if (ref.box.size) @@ -463,11 +465,11 @@ class Rewrite { } else if (box.type == bmffType("iinf")) { box.chunks.clear(); auto version = original.fullBox->version; - if (document_.items.size() > max16) + if (document_.meta.items.size() > max16) version = std::max(version, 1); box.prefix = full(version); - number(box.prefix, document_.items.size(), version ? 4 : 2); - for (const auto id : document_.infoOrder) + number(box.prefix, document_.meta.items.size(), version ? 4 : 2); + for (const auto id : document_.meta.infoOrder) box.children.push_back(itemInfo(id)); } else if (box.type == bmffType("iref")) { box = references(&original); @@ -501,7 +503,7 @@ class Rewrite { if (auto rebuilt = rebuild(child, box.type == bmffType("ipco"))) box.children.push_back(std::move(*rebuilt)); } - if (box.type == bmffType("meta") && !hasReferences && !document_.references.empty()) + if (box.type == bmffType("meta") && !hasReferences && !document_.meta.references.empty()) box.children.push_back(references()); if (box.type == bmffType("dref")) number(box.prefix, box.children.size(), 4); @@ -513,7 +515,7 @@ class Rewrite { // Preserve top-level ordering and append one media box for replacement metadata. std::vector build() const { std::vector boxes; - for (const auto& box : original_.boxes) + for (const auto& box : original_.file.boxes) if (auto rebuilt = rebuild(box)) boxes.push_back(std::move(*rebuilt)); @@ -572,7 +574,7 @@ class Rewrite { // Update iloc offsets from the layout; report whether widening requires another pass. bool relocate() { bool promoted = false; - for (auto& [id, item] : document_.items) { + for (auto& [id, item] : document_.meta.items) { auto& location = item.location; for (auto& extent : location.extents) { uint64_t position = 0; @@ -591,8 +593,8 @@ class Rewrite { const auto base = location.constructionMethod == 1 ? idatPosition_ : 0; require(position >= base); extent.offset = position - base; - if (extent.offset > max32 && document_.locationFormat.offsetSize != 8) { - document_.locationFormat.offsetSize = 8; + if (extent.offset > max32 && document_.meta.locationFormat.offsetSize != 8) { + document_.meta.locationFormat.offsetSize = 8; promoted = true; } } @@ -658,18 +660,20 @@ class Rewrite { // Reparse the output and check item identity, relocated addressing, relationships, and bytes. void verify(const std::vector& boxes) { - const auto parsed = parseBmff(output_); + const auto parsed = parseHeif(output_); // The prepared structure must describe the same retained images and item ordering. enforceHeifWriteSupport(parsed); require(parsed.majorBrand == document_.majorBrand && parsed.minorVersion == document_.minorVersion && - parsed.compatibleBrands == document_.compatibleBrands && parsed.primaryItem == document_.primaryItem && - parsed.infoOrder == document_.infoOrder && parsed.locationOrder == document_.locationOrder && - parsed.items.size() == document_.items.size()); + parsed.compatibleBrands == document_.compatibleBrands && + parsed.meta.primaryItem == document_.meta.primaryItem && + parsed.meta.infoOrder == document_.meta.infoOrder && + parsed.meta.locationOrder == document_.meta.locationOrder && + parsed.meta.items.size() == document_.meta.items.size()); // Check every item description and each relocated extent against the planned model. - for (const auto& [id, item] : document_.items) { - const auto& actual = parsed.items.at(id); + for (const auto& [id, item] : document_.meta.items) { + const auto& actual = parsed.meta.items.at(id); const auto& info = item.info; require(actual.info.type == info.type && actual.info.name == info.name && actual.info.flags == info.flags && actual.info.contentType == info.contentType && actual.info.contentEncoding == info.contentEncoding && @@ -686,24 +690,24 @@ class Rewrite { } // Relationships and property associations must survive with identical meanings. - require(parsed.references.size() == document_.references.size() && - parsed.associations.size() == document_.associations.size() && - parsed.properties.size() == document_.properties.size()); - for (size_t i = 0; i < document_.references.size(); ++i) { - const auto& a = parsed.references[i]; - const auto& e = document_.references[i]; + require(parsed.meta.references.size() == document_.meta.references.size() && + parsed.meta.associations.size() == document_.meta.associations.size() && + parsed.meta.properties.size() == document_.meta.properties.size()); + for (size_t i = 0; i < document_.meta.references.size(); ++i) { + const auto& a = parsed.meta.references[i]; + const auto& e = document_.meta.references[i]; require(a.type == e.type && a.from == e.from && a.to == e.to); } - for (size_t i = 0; i < document_.associations.size(); ++i) { - const auto& a = parsed.associations[i]; - const auto& e = document_.associations[i]; + for (size_t i = 0; i < document_.meta.associations.size(); ++i) { + const auto& a = parsed.meta.associations[i]; + const auto& e = document_.meta.associations[i]; require(a.itemId == e.itemId && a.properties.size() == e.properties.size()); for (size_t j = 0; j < a.properties.size(); ++j) require(a.properties[j].index == e.properties[j].index && a.properties[j].essential == e.properties[j].essential); } - for (size_t i = 0; i < document_.properties.size(); ++i) - require(parsed.properties[i].type == document_.properties[i].type); + for (size_t i = 0; i < document_.meta.properties.size(); ++i) + require(parsed.meta.properties[i].type == document_.meta.properties[i].type); // Structural agreement alone is insufficient; verify every copied or generated byte. for (const auto& box : boxes) @@ -712,8 +716,8 @@ class Rewrite { BasicIo& input_; BasicIo& output_; - const BmffDocument& original_; - BmffDocument document_; + const HeifDocument& original_; + HeifDocument document_; std::set removed_; std::map additions_; std::map newItems_; @@ -729,23 +733,7 @@ class Rewrite { } // namespace -std::vector readBmffItem(BasicIo& input, const BmffItem& item, uint64_t limit) { - supported(item.location.dataSize <= limit && item.location.dataSize <= std::numeric_limits::max(), - "metadata exceeds the allocation limit"); - - // Gather the requested item only after bounding its aggregate allocation. - Bytes bytes(static_cast(item.location.dataSize)); - size_t position = 0; - for (const auto& extent : item.location.extents) { - require(extent.source.size <= bytes.size() - position); - read(input, extent.source.offset, bytes.data() + position, static_cast(extent.source.size)); - position += static_cast(extent.source.size); - } - require(position == bytes.size()); - return bytes; -} - -void rewriteBmff(BasicIo& input, BasicIo& output, const BmffDocument& original, const BmffMetadataUpdate& update) { +void rewriteHeif(BasicIo& input, BasicIo& output, const HeifDocument& original, const HeifMetadataUpdate& update) { Rewrite(input, output, original).run(update); } diff --git a/src/bmffwrite_int.hpp b/src/heifwrite_int.hpp similarity index 58% rename from src/bmffwrite_int.hpp rename to src/heifwrite_int.hpp index c89538ad23..fdfa37246d 100644 --- a/src/bmffwrite_int.hpp +++ b/src/heifwrite_int.hpp @@ -1,19 +1,16 @@ // SPDX-License-Identifier: GPL-2.0-or-later -#ifndef BMFFWRITE_INT_HPP -#define BMFFWRITE_INT_HPP +#ifndef HEIFWRITE_INT_HPP +#define HEIFWRITE_INT_HPP -#include "bmffimage_int.hpp" +#include "heifstructure_int.hpp" #ifdef EXV_ENABLE_BMFF namespace Exiv2::Internal { -//! @brief Metadata buffers are bounded independently of the encoded image size. -inline constexpr uint64_t bmffMetadataLimit = 64 * 1024 * 1024; - //! @brief Serialized primary metadata requests, with distinct preserve, remove, and replace states. -struct BmffMetadataUpdate { +struct HeifMetadataUpdate { //! @brief No value preserves the category; an empty value removes it from the primary image. std::optional> exif; @@ -21,23 +18,11 @@ struct BmffMetadataUpdate { std::optional> xmp; }; -/*! - @brief Gather a checked item's extents in their declared order. - @param input Open, seekable input from which the item's source ranges were parsed. - @param item Item with validated absolute extents and aggregate data size. - @param limit Maximum number of bytes to allocate for the assembled metadata. - @return An owned contiguous copy of the item payload. - @throws Error If the allocation limit is exceeded, ranges disagree, or input I/O fails. - - The input must remain unchanged since parsing; its stream position may change. - */ -std::vector readBmffItem(BasicIo& input, const BmffItem& item, uint64_t limit = bmffMetadataLimit); - /*! @brief Compact an item-based HEIF into a fresh, open, seekable output. @param input Borrowed source stream used to parse original; it must remain unchanged. @param output Borrowed, empty staging stream, distinct from input. - @param original Validated structure and source ranges returned by parseBmff(). + @param original Validated structure and source ranges returned by parseHeif(). @param update Serialized primary Exif/XMP updates; absent entries preserve their category. @throws Error For unsupported edits, invalid layout, I/O failure, or failed verification. @@ -47,7 +32,7 @@ std::vector readBmffItem(BasicIo& input, const BmffItem& item, uint64_t verified. Unknown relocation, shared-metadata edits and conflicting overlap are rejected before any output is written. This function does not serialize TIFF/XMP. */ -void rewriteBmff(BasicIo& input, BasicIo& output, const BmffDocument& original, const BmffMetadataUpdate& update = {}); +void rewriteHeif(BasicIo& input, BasicIo& output, const HeifDocument& original, const HeifMetadataUpdate& update = {}); } // namespace Exiv2::Internal #endif diff --git a/src/meson.build b/src/meson.build index 325bf3afbe..477e42b936 100644 --- a/src/meson.build +++ b/src/meson.build @@ -46,8 +46,9 @@ endif int_lib = files( 'bmffbox_int.cpp', - 'bmffimage_int.cpp', - 'bmffwrite_int.cpp', + 'bmffitem_int.cpp', + 'heifstructure_int.cpp', + 'heifwrite_int.cpp', 'canonmn_int.cpp', 'casiomn_int.cpp', 'cr2header_int.cpp', diff --git a/unitTests/test_bmffimage_int.cpp b/unitTests/test_bmffimage_int.cpp index 7b295fced8..153911af79 100644 --- a/unitTests/test_bmffimage_int.cpp +++ b/unitTests/test_bmffimage_int.cpp @@ -1,7 +1,7 @@ // SPDX-License-Identifier: GPL-2.0-or-later -#include "bmffimage_int.hpp" -#include "bmffwrite_int.hpp" +#include "heifstructure_int.hpp" +#include "heifwrite_int.hpp" #ifdef EXV_ENABLE_BMFF @@ -277,9 +277,33 @@ Bytes fixture(const Options& opt = {}) { } // Parse borrowed fixture bytes with optional resource limits. -BmffDocument parse(const Bytes& bytes, const BmffLimits& limits = {}) { +HeifDocument parse(const Bytes& bytes, const HeifLimits& limits = {}) { MemIo input(bytes.data(), bytes.size()); - return parseBmff(input, limits); + return parseHeif(input, limits); +} + +// Keep generic item test results separate from the HEIF document and its admission policy. +struct ItemFixture { + BmffFile file; + BmffItemModel model; +}; + +// Frame arbitrary fixture bytes and decode their meta tables with explicit neutral budgets. +ItemFixture parseItems(const Bytes& bytes) { + MemIo input(bytes.data(), bytes.size()); + BmffReader reader(input, {1000, 1024 * 1024, 16}); + const BmffItemLimits limits{100, 1000, 1000, 1000, 4096, 1024, 1000}; + ItemFixture result; + result.file.size = reader.fileSize(); + auto fields = reader.cursor({0, result.file.size}); + + reader.visit(fields, 0, [&](BmffBox& box, BmffCursor& payload) { + if (box.type == bmffType("meta")) + result.model = parseBmffItems(reader, box, payload, 1, limits); + result.file.boxes.push_back(std::move(box)); + }); + resolveBmffItems(result.model, result.file.size); + return result; } // Assert that a malformed fixture is rejected by the container parser. @@ -301,30 +325,178 @@ Bytes payload(const Bytes& file, const BmffItem& item) { } // namespace +// Resolve a standalone item container without a file brand, primary image, or property table. +TEST(BmffItems, resolvesStandaloneMetaWithoutHeifAdmission) { + Options opt; + opt.idat = opt.metadataIdat = true; + opt.locationVersion = 1; + const auto complete = fixture(opt); + const auto heif = parse(complete); + const auto span = heif.file.boxes.at(1).span; + Bytes bytes(complete.begin() + span.offset, complete.begin() + span.offset + span.size); + patch(bytes, position(bytes, "pitm") + 4, bmffType("free"), 4); + patch(bytes, position(bytes, "iprp") + 4, bmffType("free"), 4); + patch(bytes, position(bytes, "hdlr") + 16, bmffType("mdta"), 4); + + auto result = parseItems(bytes); + EXPECT_EQ(result.file.boxes.size(), 1u); + EXPECT_EQ(result.model.handler, bmffType("mdta")); + EXPECT_FALSE(result.model.hasPrimaryItem); + EXPECT_TRUE(result.model.properties.empty()); + EXPECT_EQ(result.model.infoOrder, (std::vector{1, 2, 3})); + ASSERT_TRUE(result.model.itemData); + EXPECT_EQ(result.model.items.at(1).location.extents.front().source.offset, result.model.itemData->offset); + + MemIo input(bytes.data(), bytes.size()); + EXPECT_EQ(readBmffItem(input, result.model.items.at(1), 4), (Bytes{'A', 'B', 'C', 'D'})); + EXPECT_EQ(readBmffItem(input, result.model.items.at(3), 3), (Bytes{'x', 'm', 'p'})); + EXPECT_THROW(readBmffItem(input, result.model.items.at(1), 3), Error); + resolveBmffItems(result.model, result.file.size); + EXPECT_EQ(result.model.items.at(1).location.dataSize, 4u); + EXPECT_THROW(parse(bytes), Error); +} + +// Item-free standard meta containers do not acquire a HEIF primary-image requirement. +TEST(BmffItems, acceptsEmptyStandardMetaWithoutPictureTables) { + const auto result = parseItems(box(bmffType("meta"), full())); + EXPECT_TRUE(result.model.items.empty()); + EXPECT_FALSE(result.model.hasPrimaryItem); + EXPECT_TRUE(result.file.boxes.front().children.empty()); +} + +// File-relative addressing is a standard mechanism; mdat ownership is HEIF policy. +TEST(BmffItems, separatesFileRelativeResolutionFromMediaOwnership) { + auto bytes = fixture(); + patch(bytes, position(bytes, "mdat") + 4, bmffType("data"), 4); + const auto result = parseItems(bytes); + + EXPECT_EQ(payload(bytes, result.model.items.at(1)), (Bytes{'A', 'B', 'C', 'D'})); + EXPECT_EQ(result.model.references.front().from, 2u); + EXPECT_EQ(result.model.references.front().to, (std::vector{1})); + EXPECT_THROW(parse(bytes), Error); + + // The generic resolver still enforces file boundaries without relying on the adapter. + patch(bytes, position(bytes, "iloc") + 22, bytes.size(), 4); + EXPECT_THROW(parseItems(bytes), Error); +} + +// Preserve standard field widths and opaque properties without any brand or codec policy. +TEST(BmffItems, retainsWideTablesAndOpaquePropertiesIndependentlyOfBrands) { + Options opt; + opt.brand = bmffType("avif"); + opt.idBase = 65536; + opt.locationVersion = 2; + opt.infoVersion = opt.primaryVersion = opt.referenceVersion = opt.associationVersion = 1; + opt.entryVersion = 3; + opt.offsetWidth = opt.lengthWidth = opt.baseWidth = opt.indexWidth = 8; + opt.wideProperties = opt.locationFirst = true; + opt.propertyCount = 130; + opt.propertyType = bmffType("cust"); + opt.mimeType = "application/custom"; + opt.encoding = "gzip"; + const auto bytes = fixture(opt); + const auto result = parseItems(bytes); + + EXPECT_EQ(result.model.primaryItem, 65537u); + EXPECT_EQ(result.model.locationFormat.indexSize, 8u); + EXPECT_EQ(result.model.associations.front().properties.back().index, 130u); + EXPECT_EQ(result.model.properties.front().type, bmffType("cust")); + EXPECT_EQ(result.model.items.at(65539).info.contentType, "application/custom"); + EXPECT_EQ(result.model.items.at(65539).info.contentEncoding, "gzip"); + EXPECT_EQ(payload(bytes, result.model.items.at(65537)), (Bytes{'A', 'B', 'C', 'D'})); + EXPECT_THROW(enforceHeifWriteSupport(parse(bytes)), Error); +} + +// Protection and handler admission belong to the adapter, with its original diagnostic order. +TEST(BmffItems, retainsFieldsWhileHeifRejectsAtTheOriginalCheckpoint) { + auto bytes = fixture(); + patch(bytes, position(bytes, "hdlr") + 16, bmffType("mdta"), 4); + EXPECT_EQ(parseItems(bytes).model.handler, bmffType("mdta")); + + // An invalid reserved field must not replace the earlier non-picture rejection. + patch(bytes, position(bytes, "hdlr") + 20, 1, 4); + try { + parse(bytes); + FAIL() << "HEIF accepted a non-picture handler"; + } catch (const Error& error) { + EXPECT_STREQ(error.what(), "Unsupported HEIF layout: non-picture handler"); + } + + bytes = fixture(); + patch(bytes, position(bytes, "infe") + 14, 1, 2); + EXPECT_EQ(parseItems(bytes).model.items.at(1).info.protectionIndex, 1u); + // An unsupported codec is irrelevant when protection has already rejected the item. + patch(bytes, position(bytes, "infe") + 16, bmffType("cust"), 4); + try { + parse(bytes); + FAIL() << "HEIF accepted a protected item"; + } catch (const Error& error) { + EXPECT_STREQ(error.what(), "Unsupported HEIF layout: protected item"); + } +} + +// The neutral parser never interprets Canon UUID payloads; HEIF retains its explicit exception. +TEST(BmffItems, leavesCanonExtensionTraversalToHeif) { + Options opt; + Bytes content{0x85, 0xc0, 0xb6, 0x87, 0x82, 0x0f, 0x11, 0xe0, 0x81, 0x11, 0xf4, 0xce, 0x46, 0x2b, 0x6a, 0x48}; + append(content, box(bmffType("CNCV"), {'v', '1', 0})); + opt.extraMeta = box(bmffType("uuid"), content, true); + auto bytes = fixture(opt); + const auto neutral = parseItems(bytes); + EXPECT_TRUE(neutral.file.boxes.at(1).children.back().children.empty()); + EXPECT_EQ(parse(bytes).file.boxes.at(1).children.back().children.size(), 1u); + EXPECT_NO_THROW(enforceHeifWriteSupport(parse(bytes))); + + append(content, box(bmffType("CNCV"), {})); + opt.extraMeta = box(bmffType("uuid"), content); + bytes = fixture(opt); + EXPECT_NO_THROW(parseItems(bytes)); + EXPECT_THROW(parse(bytes), Error); +} + +// Standard model validation rejects broken joins, graph endpoints and property indices on its own. +TEST(BmffItems, rejectsInvalidRelationsWithoutHeifPolicy) { + auto bytes = fixture(); + patch(bytes, position(bytes, "iloc") + 16, 4, 2); + EXPECT_THROW(parseItems(bytes), Error); + + bytes = fixture(); + patch(bytes, position(bytes, "cdsc") + 12, 7, 2); + EXPECT_THROW(parseItems(bytes), Error); + + bytes = fixture(); + patch(bytes, position(bytes, "ipma") + 19, 0x83, 1); + EXPECT_THROW(parseItems(bytes), Error); + + bytes = fixture(); + patch(bytes, position(bytes, "pitm") + 12, 0, 2); + EXPECT_THROW(parseItems(bytes), Error); +} + // Retain the complete item graph and fragmented payload coordinates. TEST(BmffModel, retainsAllItemsExtentsAndMetadataAssociations) { const auto bytes = fixture(); const auto document = parse(bytes); EXPECT_NO_THROW(enforceHeifWriteSupport(document)); - ASSERT_EQ(document.items.size(), 3u); - EXPECT_EQ(document.primaryItem, 1u); + ASSERT_EQ(document.meta.items.size(), 3u); + EXPECT_EQ(document.meta.primaryItem, 1u); EXPECT_EQ(document.majorBrand, bmffType("heic")); - EXPECT_EQ(document.infoOrder, (std::vector{1, 2, 3})); - EXPECT_EQ(document.locationOrder, document.infoOrder); + EXPECT_EQ(document.meta.infoOrder, (std::vector{1, 2, 3})); + EXPECT_EQ(document.meta.locationOrder, document.meta.infoOrder); EXPECT_EQ(document.metadataItems(bmffType("Exif")), (std::vector{2})); EXPECT_EQ(document.metadataItems(bmffType("mime")), (std::vector{3})); - EXPECT_EQ(document.items.at(3).info.contentType, "application/rdf+xml"); - EXPECT_EQ(document.items.at(2).info.flags, 1u); + EXPECT_EQ(document.meta.items.at(3).info.contentType, "application/rdf+xml"); + EXPECT_EQ(document.meta.items.at(2).info.flags, 1u); - EXPECT_EQ(document.items.at(1).location.extents.size(), 2u); - EXPECT_EQ(document.items.at(1).location.dataSize, 4u); - EXPECT_EQ(payload(bytes, document.items.at(1)), (Bytes{'A', 'B', 'C', 'D'})); - EXPECT_EQ(payload(bytes, document.items.at(2)), (Bytes{'e', 'x', 'i', 'f'})); - EXPECT_EQ(payload(bytes, document.items.at(3)), (Bytes{'x', 'm', 'p'})); - ASSERT_EQ(document.associations.size(), 1u); - EXPECT_EQ(document.associations.front().properties.front().index, 1u); - EXPECT_TRUE(document.associations.front().properties.front().essential); - EXPECT_FALSE(document.associations.front().properties.back().essential); + EXPECT_EQ(document.meta.items.at(1).location.extents.size(), 2u); + EXPECT_EQ(document.meta.items.at(1).location.dataSize, 4u); + EXPECT_EQ(payload(bytes, document.meta.items.at(1)), (Bytes{'A', 'B', 'C', 'D'})); + EXPECT_EQ(payload(bytes, document.meta.items.at(2)), (Bytes{'e', 'x', 'i', 'f'})); + EXPECT_EQ(payload(bytes, document.meta.items.at(3)), (Bytes{'x', 'm', 'p'})); + ASSERT_EQ(document.meta.associations.size(), 1u); + EXPECT_EQ(document.meta.associations.front().properties.front().index, 1u); + EXPECT_TRUE(document.meta.associations.front().properties.front().essential); + EXPECT_FALSE(document.meta.associations.front().properties.back().essential); } // Resolve item records independently of box order and explicit base offsets. @@ -334,9 +506,9 @@ TEST(BmffModel, acceptsLocationBeforeInfoAndExplicitBaseOffsets) { opt.baseWidth = 4; const auto bytes = fixture(opt); const auto document = parse(bytes); - EXPECT_GT(document.items.at(1).location.baseOffset, 0u); + EXPECT_GT(document.meta.items.at(1).location.baseOffset, 0u); - EXPECT_EQ(payload(bytes, document.items.at(1)), (Bytes{'A', 'B', 'C', 'D'})); + EXPECT_EQ(payload(bytes, document.meta.items.at(1)), (Bytes{'A', 'B', 'C', 'D'})); } // Resolve idat extents from the payload origin, distinct from file offsets. @@ -346,11 +518,11 @@ TEST(BmffModel, resolvesIdatRelativeDataWithoutConfusingItWithFileOffsets) { opt.locationVersion = 1; const auto bytes = fixture(opt); const auto document = parse(bytes); - ASSERT_TRUE(document.itemData.has_value()); - EXPECT_EQ(document.items.at(1).location.constructionMethod, 1u); + ASSERT_TRUE(document.meta.itemData.has_value()); + EXPECT_EQ(document.meta.items.at(1).location.constructionMethod, 1u); - EXPECT_EQ(document.items.at(1).location.extents.front().source.offset, document.itemData->offset); - EXPECT_EQ(payload(bytes, document.items.at(1)), (Bytes{'A', 'B', 'C', 'D'})); + EXPECT_EQ(document.meta.items.at(1).location.extents.front().source.offset, document.meta.itemData->offset); + EXPECT_EQ(payload(bytes, document.meta.items.at(1)), (Bytes{'A', 'B', 'C', 'D'})); EXPECT_NO_THROW(enforceHeifWriteSupport(document)); } @@ -369,11 +541,11 @@ TEST(BmffModel, retains32BitIds64BitFieldsAndWidePropertyIndices) { opt.propertyCount = 130; const auto document = parse(fixture(opt)); - EXPECT_EQ(document.primaryItem, 65537u); + EXPECT_EQ(document.meta.primaryItem, 65537u); EXPECT_EQ(document.metadataItems(bmffType("Exif")), (std::vector{65538})); - EXPECT_EQ(document.locationFormat.indexSize, 8u); - EXPECT_EQ(document.associations.front().properties.back().index, 130u); - EXPECT_EQ(document.items.at(65537).info.version, 3u); + EXPECT_EQ(document.meta.locationFormat.indexSize, 8u); + EXPECT_EQ(document.meta.associations.front().properties.back().index, 130u); + EXPECT_EQ(document.meta.items.at(65537).info.version, 3u); } // Allow item locations expressed entirely through their base offsets. @@ -384,8 +556,8 @@ TEST(BmffModel, acceptsZeroOffsetWidthAndNonzeroBaseOffsets) { const auto bytes = fixture(opt); const auto document = parse(bytes); - EXPECT_EQ(document.locationFormat.offsetSize, 0u); - EXPECT_EQ(payload(bytes, document.items.at(2)), (Bytes{'e', 'x', 'i', 'f'})); + EXPECT_EQ(document.meta.locationFormat.offsetSize, 0u); + EXPECT_EQ(payload(bytes, document.meta.items.at(2)), (Bytes{'e', 'x', 'i', 'f'})); } // Retain both extended-size and end-of-file box representations. @@ -395,16 +567,16 @@ TEST(BmffModel, preservesExtendedHeadersAndTerminalMediaBox) { auto bytes = fixture(opt); auto document = parse(bytes); - EXPECT_EQ(document.boxes.front().headerSize, 16u); - EXPECT_EQ(payload(bytes, document.items.at(1)), (Bytes{'A', 'B', 'C', 'D'})); + EXPECT_EQ(document.file.boxes.front().headerSize, 16u); + EXPECT_EQ(payload(bytes, document.meta.items.at(1)), (Bytes{'A', 'B', 'C', 'D'})); // A terminal mdat consumes the remainder of the file without an explicit size. opt.extended = false; opt.terminal = true; bytes = fixture(opt); document = parse(bytes); - EXPECT_TRUE(document.boxes.back().extendsToEnd); - EXPECT_EQ(document.boxes.back().span.size, 19u); + EXPECT_TRUE(document.file.boxes.back().extendsToEnd); + EXPECT_EQ(document.file.boxes.back().span.size, 19u); } // Accept images without metadata and retain metadata lacking primary associations. @@ -413,7 +585,7 @@ TEST(BmffModel, acceptsMetadataFreeFilesAndMissingReferences) { opt.noMetadata = true; auto document = parse(fixture(opt)); - EXPECT_EQ(document.items.size(), 1u); + EXPECT_EQ(document.meta.items.size(), 1u); EXPECT_TRUE(document.metadataItems(bmffType("Exif")).empty()); EXPECT_NO_THROW(enforceHeifWriteSupport(document)); @@ -421,7 +593,7 @@ TEST(BmffModel, acceptsMetadataFreeFilesAndMissingReferences) { opt.noMetadata = false; opt.noReferences = true; document = parse(fixture(opt)); - EXPECT_EQ(document.items.size(), 3u); + EXPECT_EQ(document.meta.items.size(), 3u); EXPECT_TRUE(document.metadataItems(bmffType("Exif")).empty()); } @@ -432,8 +604,8 @@ TEST(BmffModel, preservesSharedMetadataAndReferenceDirection) { auto bytes = fixture(opt); auto document = parse(bytes); - EXPECT_EQ(document.references.front().from, 2u); - EXPECT_EQ(document.references.front().to, (std::vector{1, 3})); + EXPECT_EQ(document.meta.references.front().from, 2u); + EXPECT_EQ(document.meta.references.front().to, (std::vector{1, 3})); EXPECT_EQ(document.metadataItems(bmffType("Exif")), (std::vector{2})); // Reverse cdsc to ensure an image-to-metadata edge is not mistaken for metadata. @@ -450,7 +622,7 @@ TEST(BmffModel, retainsOpaqueBoxesButRejectsUnprovedRelocation) { opt.extraMeta = box(bmffType("zzzz"), {'k', 'e', 'e', 'p'}); auto bytes = fixture(opt); auto document = parse(bytes); - const auto& opaque = document.boxes.at(1).children.back(); + const auto& opaque = document.file.boxes.at(1).children.back(); EXPECT_EQ(opaque.type, bmffType("zzzz")); EXPECT_EQ(opaque.span.offset, position(bytes, "zzzz")); @@ -466,7 +638,7 @@ TEST(BmffModel, retainsOpaqueBoxesButRejectsUnprovedRelocation) { opt.extraRoot.clear(); opt.propertyType = bmffType("zzzz"); document = parse(fixture(opt)); - EXPECT_EQ(document.properties.front().type, bmffType("zzzz")); + EXPECT_EQ(document.meta.properties.front().type, bmffType("zzzz")); EXPECT_THROW(enforceHeifWriteSupport(document), Error); } @@ -483,7 +655,7 @@ TEST(BmffModel, rejectsDeferredBrandsAndCompressedPrimaryXmp) { Options opt; opt.encoding = "gzip"; auto document = parse(fixture(opt)); - EXPECT_EQ(document.items.at(3).info.contentEncoding, "gzip"); + EXPECT_EQ(document.meta.items.at(3).info.contentEncoding, "gzip"); EXPECT_THROW(enforceHeifWriteSupport(document), Error); } @@ -682,39 +854,39 @@ TEST(BmffModel, rejectsInvalidWidthsZeroLengthsAndExtentBounds) { TEST(BmffModel, boundsAggregateResourcesAndStrings) { const auto bytes = fixture(); for (unsigned limit = 0; limit < 8; ++limit) { - BmffLimits limits; + HeifLimits limits; switch (limit) { case 0: - limits.maxBoxes = 2; + limits.boxes.maxBoxes = 2; break; case 1: - limits.maxItems = 2; + limits.items.maxItems = 2; break; case 2: - limits.maxExtents = 1; + limits.items.maxExtents = 1; break; case 3: - limits.maxReferences = 1; + limits.items.maxReferences = 1; break; case 4: - limits.maxAssociations = 1; + limits.items.maxAssociations = 1; break; case 5: - limits.maxStringBytes = 2; + limits.items.maxStringBytes = 2; break; case 6: - limits.maxBytesRead = 8; + limits.boxes.maxBytesRead = 8; break; case 7: - limits.maxDepth = 1; + limits.boxes.maxDepth = 1; break; } EXPECT_THROW(parse(bytes, limits), Error) << limit; } // Check per-string limits and missing terminators separately from aggregate budgets. - BmffLimits limits; - limits.maxStringLength = 2; + HeifLimits limits; + limits.items.maxStringLength = 2; EXPECT_THROW(parse(bytes, limits), Error); auto malformed = bytes; const auto entry = position(malformed, "infe"); @@ -747,11 +919,11 @@ TEST(BmffModel, ioFailuresPropagateWithoutWriting) { const auto bytes = fixture(); FailingIo input(bytes); - EXPECT_THROW(parseBmff(input), Error); + EXPECT_THROW(parseHeif(input), Error); // Exercise seek failure separately from the injected short read. input.failSeek = true; - EXPECT_THROW(parseBmff(input), Error); + EXPECT_THROW(parseHeif(input), Error); EXPECT_EQ(input.size(), bytes.size()); EXPECT_EQ(std::memcmp(input.mmap(), bytes.data(), bytes.size()), 0); @@ -816,13 +988,13 @@ TEST(BmffModel, resolvesSparse64BitFileWithoutReadingMediaOrAllocatingItsSize) { integer(input.mediaHeader, bmffType("mdat"), 4); // Parse only structural bytes and resolve the large absolute media position. - const auto document = parseBmff(input); + const auto document = parseHeif(input); EXPECT_NO_THROW(enforceHeifWriteSupport(document)); - EXPECT_EQ(document.fileSize, input.mediaOffset + 19); - EXPECT_EQ(document.items.at(1).location.extents.at(0).source, (BmffSpan{input.mediaOffset + 8, 2})); - EXPECT_EQ(document.items.at(1).location.extents.at(1).source, (BmffSpan{input.mediaOffset + 14, 2})); - EXPECT_EQ(document.boxes.at(2).headerSize, 16u); - EXPECT_EQ(document.boxes.at(2).span.size, gap); + EXPECT_EQ(document.file.size, input.mediaOffset + 19); + EXPECT_EQ(document.meta.items.at(1).location.extents.at(0).source, (BmffSpan{input.mediaOffset + 8, 2})); + EXPECT_EQ(document.meta.items.at(1).location.extents.at(1).source, (BmffSpan{input.mediaOffset + 14, 2})); + EXPECT_EQ(document.file.boxes.at(2).headerSize, 16u); + EXPECT_EQ(document.file.boxes.at(2).span.size, gap); EXPECT_FALSE(input.forbiddenRead); EXPECT_LT(input.bytesRead, 1024u); @@ -836,7 +1008,7 @@ TEST(BmffModel, validatesUuidHeadersAndKnownCanonContainer) { append(content, box(bmffType("CNCV"), {'v', '1', 0})); opt.extraMeta = box(bmffType("uuid"), content, true); const auto document = parse(fixture(opt)); - const auto& canon = document.boxes.at(1).children.back(); + const auto& canon = document.file.boxes.at(1).children.back(); EXPECT_EQ(canon.headerSize, 32u); EXPECT_EQ(canon.children.size(), 1u); EXPECT_EQ(canon.payload().size, 11u); @@ -845,7 +1017,7 @@ TEST(BmffModel, validatesUuidHeadersAndKnownCanonContainer) { content[0] = 0; opt.extraMeta = box(bmffType("uuid"), content); auto unknown = parse(fixture(opt)); - EXPECT_TRUE(unknown.boxes.at(1).children.back().children.empty()); + EXPECT_TRUE(unknown.file.boxes.at(1).children.back().children.empty()); EXPECT_THROW(enforceHeifWriteSupport(unknown), Error); opt.extraMeta = box(bmffType("uuid"), Bytes(15)); @@ -876,6 +1048,23 @@ TEST(BmffModel, acceptsSelfContainedDataReferenceAndRejectsExternalReferences) { rejects(bytes); } +// Honor the explicit item budget while retaining the HEIF adapter's aggregate box-count ceiling. +TEST(BmffItems, boundsDeclaredDataReferencesBeforeVisitingEntries) { + Options opt; + auto references = full(); + integer(references, 1, 4); + append(references, box(bmffType("url "), full(0, 1))); + opt.extraMeta = box(bmffType("dinf"), box(bmffType("dref"), references)); + const auto bytes = fixture(opt); + EXPECT_NO_THROW(parseItems(bytes)); + + HeifLimits limits; + limits.items.maxEntries = 0; + EXPECT_THROW(parse(bytes, limits), Error); + limits.items.maxEntries = 1; + EXPECT_NO_THROW(parse(bytes, limits)); +} + // Allow shared bytes on read while enforcing individual data-box boundaries. TEST(BmffModel, acceptsSharedPayloadRangesButRejectsRangesCrossingDataBounds) { Options opt; @@ -885,8 +1074,9 @@ TEST(BmffModel, acceptsSharedPayloadRangesButRejectsRangesCrossingDataBounds) { // Give the second primary extent the same range as the first. patch(bytes, loc + 34, 0, 4); auto document = parse(bytes); - EXPECT_EQ(document.items.at(1).location.extents.at(0).source, document.items.at(1).location.extents.at(1).source); - EXPECT_EQ(payload(bytes, document.items.at(1)), (Bytes{'A', 'B', 'A', 'B'})); + EXPECT_EQ(document.meta.items.at(1).location.extents.at(0).source, + document.meta.items.at(1).location.extents.at(1).source); + EXPECT_EQ(payload(bytes, document.meta.items.at(1)), (Bytes{'A', 'B', 'A', 'B'})); // Reject extents crossing either idat or mdat boundaries. opt.idat = true; @@ -946,11 +1136,11 @@ TEST_P(BmffCorpus, agreesWithIndependentItemInventory) { FileIo input(std::string(TESTDATA_PATH) + "/" + expected.file); ASSERT_EQ(input.open("rb"), 0); - const auto document = parseBmff(input); - EXPECT_EQ(document.primaryItem, expected.primary); - EXPECT_EQ(document.items.size(), expected.count); - EXPECT_EQ(document.infoOrder.size(), expected.count); - EXPECT_EQ(document.locationOrder.size(), expected.count); + const auto document = parseHeif(input); + EXPECT_EQ(document.meta.primaryItem, expected.primary); + EXPECT_EQ(document.meta.items.size(), expected.count); + EXPECT_EQ(document.meta.infoOrder.size(), expected.count); + EXPECT_EQ(document.meta.locationOrder.size(), expected.count); const auto exif = document.metadataItems(bmffType("Exif")); const auto xmp = document.metadataItems(bmffType("mime")); @@ -986,17 +1176,17 @@ TEST(BmffModel, rejectsNonItemFormatsAndMalformedRegressionFiles) { SCOPED_TRACE(file); FileIo input(std::string(TESTDATA_PATH) + "/" + file); ASSERT_EQ(input.open("rb"), 0); - EXPECT_THROW(parseBmff(input), Error); + EXPECT_THROW(parseHeif(input), Error); } } namespace { // Rewrite into separate memory and verify the borrowed source remains unchanged. -Bytes rewritten(const Bytes& bytes, const BmffMetadataUpdate& update = {}) { +Bytes rewritten(const Bytes& bytes, const HeifMetadataUpdate& update = {}) { MemIo input(bytes.data(), bytes.size()); MemIo output; - rewriteBmff(input, output, parseBmff(input), update); + rewriteHeif(input, output, parseHeif(input), update); EXPECT_EQ(input.size(), bytes.size()); EXPECT_EQ(std::memcmp(input.mmap(), bytes.data(), bytes.size()), 0); @@ -1019,12 +1209,12 @@ Bytes withOrphanedBytes(Bytes bytes) { } // Assert rejection occurs before output is written or source bytes change. -void rejectsRewrite(const Bytes& bytes, const BmffMetadataUpdate& update = {}) { +void rejectsRewrite(const Bytes& bytes, const HeifMetadataUpdate& update = {}) { MemIo input(bytes.data(), bytes.size()); MemIo output; - const auto document = parseBmff(input); + const auto document = parseHeif(input); - EXPECT_THROW(rewriteBmff(input, output, document, update), Error); + EXPECT_THROW(rewriteHeif(input, output, document, update), Error); EXPECT_EQ(output.size(), 0u); EXPECT_EQ(input.size(), bytes.size()); EXPECT_EQ(std::memcmp(input.mmap(), bytes.data(), bytes.size()), 0); @@ -1050,10 +1240,10 @@ TEST(BmffRewrite, compactsOrphansAndPaddingWhilePreservingEveryRetainedItem) { EXPECT_FALSE(contains(bytes, "PRIVATE")); EXPECT_FALSE(contains(bytes, "SECRET")); - EXPECT_EQ(output.primaryItem, original.primaryItem); + EXPECT_EQ(output.meta.primaryItem, original.meta.primaryItem); - for (const auto& [id, item] : original.items) - EXPECT_EQ(payload(source, item), payload(bytes, output.items.at(id))); + for (const auto& [id, item] : original.meta.items) + EXPECT_EQ(payload(source, item), payload(bytes, output.meta.items.at(id))); // A second compaction must be byte-for-byte stable. EXPECT_EQ(rewritten(bytes), bytes); @@ -1063,7 +1253,7 @@ TEST(BmffRewrite, compactsOrphansAndPaddingWhilePreservingEveryRetainedItem) { TEST(BmffRewrite, removesMetadataPayloadsAndTheirReferences) { const auto source = withOrphanedBytes(fixture()); - BmffMetadataUpdate update; + HeifMetadataUpdate update; update.exif = Bytes{}; update.xmp = Bytes{}; @@ -1071,12 +1261,12 @@ TEST(BmffRewrite, removesMetadataPayloadsAndTheirReferences) { const auto output = parse(bytes); // Check both graph removal and absence of the discarded payload bytes. - ASSERT_EQ(output.items.size(), 1u); - EXPECT_TRUE(output.references.empty()); + ASSERT_EQ(output.meta.items.size(), 1u); + EXPECT_TRUE(output.meta.references.empty()); EXPECT_TRUE(output.metadataItems(bmffType("Exif")).empty()); EXPECT_TRUE(output.metadataItems(bmffType("mime")).empty()); - EXPECT_EQ(payload(bytes, output.items.at(1)), (Bytes{'A', 'B', 'C', 'D'})); + EXPECT_EQ(payload(bytes, output.meta.items.at(1)), (Bytes{'A', 'B', 'C', 'D'})); ASSERT_EQ(output.mediaData.size(), 1u); EXPECT_EQ(output.mediaData.front().size, 4u); @@ -1099,18 +1289,18 @@ TEST(BmffRewrite, repacksIdatAndRemovesUnreferencedMediaCopies) { patch(source, loc + 64, 8, 4); // XMP offset into idat. // Clear both metadata categories while keeping the idat-backed image. - BmffMetadataUpdate update; + HeifMetadataUpdate update; update.exif = Bytes{}; update.xmp = Bytes{}; const auto bytes = rewritten(source, update); const auto output = parse(bytes); - ASSERT_TRUE(output.itemData.has_value()); - EXPECT_EQ(output.itemData->size, 4u); + ASSERT_TRUE(output.meta.itemData.has_value()); + EXPECT_EQ(output.meta.itemData->size, 4u); EXPECT_TRUE(output.mediaData.empty()); - const auto& image = output.items.at(1); + const auto& image = output.meta.items.at(1); EXPECT_EQ(image.location.constructionMethod, 1u); EXPECT_EQ(image.location.extents.at(0).offset, 0u); EXPECT_EQ(image.location.extents.at(1).offset, 2u); @@ -1125,7 +1315,7 @@ TEST(BmffRewrite, insertsIntoMetadataFreeFilesAndPreservesUnassociatedItems) { Options opt; opt.noMetadata = true; - BmffMetadataUpdate update; + HeifMetadataUpdate update; update.exif = Bytes{'n', 'e', 'w', 'e', 'x', 'i', 'f'}; update.xmp = Bytes{'n', 'e', 'w', 'x', 'm', 'p'}; @@ -1133,20 +1323,20 @@ TEST(BmffRewrite, insertsIntoMetadataFreeFilesAndPreservesUnassociatedItems) { auto document = parse(bytes); // Check newly allocated primary metadata records and their payloads. - ASSERT_EQ(document.items.size(), 3u); + ASSERT_EQ(document.meta.items.size(), 3u); ASSERT_EQ(document.metadataItems(bmffType("Exif")).size(), 1u); ASSERT_EQ(document.metadataItems(bmffType("mime")).size(), 1u); - EXPECT_EQ(payload(bytes, document.items.at(document.metadataItems(bmffType("Exif")).front())), *update.exif); - EXPECT_EQ(payload(bytes, document.items.at(document.metadataItems(bmffType("mime")).front())), *update.xmp); + EXPECT_EQ(payload(bytes, document.meta.items.at(document.metadataItems(bmffType("Exif")).front())), *update.exif); + EXPECT_EQ(payload(bytes, document.meta.items.at(document.metadataItems(bmffType("mime")).front())), *update.xmp); // Keep unassociated original metadata when inserting a new primary association. opt.noMetadata = false; opt.noReferences = true; bytes = rewritten(fixture(opt), update); document = parse(bytes); - EXPECT_EQ(document.items.size(), 5u); - EXPECT_EQ(payload(bytes, document.items.at(2)), (Bytes{'e', 'x', 'i', 'f'})); - EXPECT_EQ(payload(bytes, document.items.at(3)), (Bytes{'x', 'm', 'p'})); + EXPECT_EQ(document.meta.items.size(), 5u); + EXPECT_EQ(payload(bytes, document.meta.items.at(2)), (Bytes{'e', 'x', 'i', 'f'})); + EXPECT_EQ(payload(bytes, document.meta.items.at(3)), (Bytes{'x', 'm', 'p'})); } // Keep repeated metadata edits compact and remove earlier payload canaries. @@ -1157,7 +1347,7 @@ TEST(BmffRewrite, replacesGrowsAndShrinksWithoutRetainingEarlierPayloads) { for (unsigned iteration = 0; iteration < 8; ++iteration) { // Grow metadata with unique canaries, then shrink it in the same edit cycle. const auto previous = "PRIVATE_OLD_VALUE_" + std::to_string(iteration); - BmffMetadataUpdate update; + HeifMetadataUpdate update; update.exif = Bytes(70000, 'q'); update.exif->insert(update.exif->end(), previous.begin(), previous.end()); current = rewritten(current, update); @@ -1169,7 +1359,7 @@ TEST(BmffRewrite, replacesGrowsAndShrinksWithoutRetainingEarlierPayloads) { // Earlier payloads must disappear without cumulative file growth. const auto output = parse(current); - EXPECT_EQ(payload(current, output.items.at(1)), (Bytes{'A', 'B', 'C', 'D'})); + EXPECT_EQ(payload(current, output.meta.items.at(1)), (Bytes{'A', 'B', 'C', 'D'})); if (iteration == 0) smallSize = current.size(); @@ -1183,7 +1373,7 @@ TEST(BmffRewrite, rejectsSharedMetadataAndOverlappingRetainedDataBeforeWriting) Options opt; opt.sharedMetadata = true; - BmffMetadataUpdate update; + HeifMetadataUpdate update; update.exif = Bytes{}; rejectsRewrite(fixture(opt), update); @@ -1197,7 +1387,7 @@ TEST(BmffRewrite, rejectsSharedMetadataAndOverlappingRetainedDataBeforeWriting) rejectsRewrite(source, update); // Unmodified sharing is representable and compacted without duplicating bytes. const auto bytes = rewritten(source); - EXPECT_EQ(payload(bytes, parse(bytes).items.at(1)), (Bytes{'A', 'B', 'C', 'D'})); + EXPECT_EQ(payload(bytes, parse(bytes).meta.items.at(1)), (Bytes{'A', 'B', 'C', 'D'})); } // Rewrite wide fields and unusual box headers without losing item identities. @@ -1214,25 +1404,25 @@ TEST(BmffRewrite, handlesWideIdsFieldsExtendedAndTerminalHeaders) { opt.extended = true; opt.wideProperties = true; - BmffMetadataUpdate update; + HeifMetadataUpdate update; update.exif = Bytes{'r', 'e', 'p', 'l', 'a', 'c', 'e'}; auto bytes = rewritten(fixture(opt), update); auto output = parse(bytes); // Verify wide IDs and field widths remain consistent after replacement. - EXPECT_EQ(output.primaryItem, 65537u); - EXPECT_EQ(output.locationFormat.version, 2u); - EXPECT_EQ(output.items.at(65537).location.baseOffset, 0u); - EXPECT_EQ(output.locationFormat.indexSize, 8u); - EXPECT_EQ(payload(bytes, output.items.at(65537)), (Bytes{'A', 'B', 'C', 'D'})); + EXPECT_EQ(output.meta.primaryItem, 65537u); + EXPECT_EQ(output.meta.locationFormat.version, 2u); + EXPECT_EQ(output.meta.items.at(65537).location.baseOffset, 0u); + EXPECT_EQ(output.meta.locationFormat.indexSize, 8u); + EXPECT_EQ(payload(bytes, output.meta.items.at(65537)), (Bytes{'A', 'B', 'C', 'D'})); // Exercise a terminal media box separately from extended-size headers. opt = Options{}; opt.terminal = true; bytes = rewritten(fixture(opt), update); output = parse(bytes); - EXPECT_FALSE(output.boxes.back().extendsToEnd); + EXPECT_FALSE(output.file.boxes.back().extendsToEnd); EXPECT_EQ(output.mediaData.size(), 2u); } @@ -1245,11 +1435,11 @@ TEST(BmffRewrite, reusesAvailableIdWhenLargestIdIsOccupied) { opt.entryVersion = 3; opt.primaryVersion = 1; opt.associationVersion = 1; - BmffMetadataUpdate update; + HeifMetadataUpdate update; update.exif = Bytes{'n', 'e', 'w'}; const auto bytes = rewritten(fixture(opt), update); const auto output = parse(bytes); - EXPECT_EQ(output.primaryItem, std::numeric_limits::max()); + EXPECT_EQ(output.meta.primaryItem, std::numeric_limits::max()); EXPECT_EQ(output.metadataItems(bmffType("Exif")), (std::vector{1})); } @@ -1260,9 +1450,9 @@ TEST(BmffRewrite, keepsIndexedPaddingSlotsButDiscardsTheirBodies) { const auto bytes = rewritten(fixture(opt)); const auto output = parse(bytes); - ASSERT_EQ(output.properties.size(), 2u); - EXPECT_EQ(output.properties.front().payload().size, 0u); - EXPECT_EQ(output.associations.front().properties.back().index, 2u); + ASSERT_EQ(output.meta.properties.size(), 2u); + EXPECT_EQ(output.meta.properties.front().payload().size, 0u); + EXPECT_EQ(output.meta.associations.front().properties.back().index, 2u); } // Stop on staging I/O failures and preserve the original source bytes. @@ -1283,9 +1473,9 @@ TEST(BmffRewrite, propagatesShortWritesAndReadFailuresWithoutMutatingSource) { const auto source = fixture(); MemIo input(source.data(), source.size()); - const auto document = parseBmff(input); + const auto document = parseHeif(input); - EXPECT_THROW(rewriteBmff(input, output, document), Error); + EXPECT_THROW(rewriteHeif(input, output, document), Error); EXPECT_EQ(input.size(), source.size()); EXPECT_EQ(std::memcmp(input.mmap(), source.data(), source.size()), 0); @@ -1306,7 +1496,7 @@ TEST(BmffRewrite, propagatesShortWritesAndReadFailuresWithoutMutatingSource) { // Repeat the failure check with unreadable source payloads and an empty sink. MemIo other; - EXPECT_THROW(rewriteBmff(failing, other, document), Error); + EXPECT_THROW(rewriteHeif(failing, other, document), Error); EXPECT_EQ(std::memcmp(failing.mmap(), source.data(), source.size()), 0); } @@ -1329,7 +1519,7 @@ TEST(BmffRewrite, detectsCorruptedPreparedOutput) { const auto source = fixture(); MemIo input(source.data(), source.size()); - EXPECT_THROW(rewriteBmff(input, output, parseBmff(input)), Error); + EXPECT_THROW(rewriteHeif(input, output, parseHeif(input)), Error); EXPECT_EQ(std::memcmp(input.mmap(), source.data(), source.size()), 0); } @@ -1423,22 +1613,22 @@ TEST(BmffRewrite, promotesOutputOffsetsAndStreamsLargePayloadsWithBoundedIo) { input.length = prefix.size() + imageSize; input.segments.emplace(0, prefix); - const auto original = parseBmff(input); + const auto original = parseHeif(input); // Place new metadata beyond the image so output offsets must widen. - BmffMetadataUpdate update; + HeifMetadataUpdate update; update.exif = Bytes{'n', 'e', 'w', '6', '4'}; - rewriteBmff(input, output, original, update); + rewriteHeif(input, output, original, update); - const auto document = parseBmff(output); + const auto document = parseHeif(output); // Verify promoted locations and bounded streaming without allocating the image. - EXPECT_EQ(document.locationFormat.offsetSize, 8u); - EXPECT_EQ(document.locationFormat.lengthSize, 8u); - EXPECT_EQ(document.items.at(1).location.dataSize, imageSize); + EXPECT_EQ(document.meta.locationFormat.offsetSize, 8u); + EXPECT_EQ(document.meta.locationFormat.lengthSize, 8u); + EXPECT_EQ(document.meta.items.at(1).location.dataSize, imageSize); const auto exif = document.metadataItems(bmffType("Exif")).front(); - EXPECT_GT(document.items.at(exif).location.extents.front().offset, std::numeric_limits::max()); - EXPECT_EQ(readBmffItem(output, document.items.at(exif)), *update.exif); + EXPECT_GT(document.meta.items.at(exif).location.extents.front().offset, std::numeric_limits::max()); + EXPECT_EQ(readHeifItem(output, document.meta.items.at(exif)), *update.exif); EXPECT_LE(output.largestWrite, 64u * 1024); EXPECT_EQ(input.writeCalls, 0u); @@ -1450,9 +1640,9 @@ TEST(BmffRewrite, promotesOutputOffsetsAndStreamsLargePayloadsWithBoundedIo) { patch(prefix, media + 8, maximum - media, 8); input.segments.at(0) = prefix; input.length = maximum; - const auto tooLarge = parseBmff(input); + const auto tooLarge = parseHeif(input); SparseIo untouched; - EXPECT_THROW(rewriteBmff(input, untouched, tooLarge, update), Error); + EXPECT_THROW(rewriteHeif(input, untouched, tooLarge, update), Error); EXPECT_EQ(untouched.writeCalls, 0u); EXPECT_EQ(input.writeCalls, 0u); } @@ -1471,9 +1661,9 @@ TEST(BmffRewrite, rejectsUnsupportedLayoutsAndNonemptySinksBeforeWriting) { auto source = fixture(); MemIo input(source.data(), source.size()); MemIo output(source.data(), source.size()); - const auto document = parseBmff(input); - EXPECT_THROW(rewriteBmff(input, input, document), Error); - EXPECT_THROW(rewriteBmff(input, output, document), Error); + const auto document = parseHeif(input); + EXPECT_THROW(rewriteHeif(input, input, document), Error); + EXPECT_THROW(rewriteHeif(input, output, document), Error); EXPECT_EQ(std::memcmp(input.mmap(), source.data(), source.size()), 0); EXPECT_EQ(std::memcmp(output.mmap(), source.data(), source.size()), 0); } @@ -1483,34 +1673,34 @@ TEST_P(BmffCorpus, preservesOrRejectsCorpusAccordingToWriteEnvelope) { const auto& expected = GetParam(); FileIo input(std::string(TESTDATA_PATH) + "/" + expected.file); ASSERT_EQ(input.open("rb"), 0); - const auto original = parseBmff(input); + const auto original = parseHeif(input); MemIo output; if (!expected.heif) { - EXPECT_THROW(rewriteBmff(input, output, original), Error); + EXPECT_THROW(rewriteHeif(input, output, original), Error); EXPECT_EQ(output.size(), 0u); return; } // A preserving rewrite must keep every independently inventoried item payload. - rewriteBmff(input, output, original); - const auto document = parseBmff(output); - for (const auto& [id, item] : original.items) - EXPECT_EQ(readBmffItem(input, item), readBmffItem(output, document.items.at(id))) << id; + rewriteHeif(input, output, original); + const auto document = parseHeif(output); + for (const auto& [id, item] : original.meta.items) + EXPECT_EQ(readHeifItem(input, item), readHeifItem(output, document.meta.items.at(id))) << id; // Clear metadata and compare every remaining item against the original stream. - BmffMetadataUpdate update; + HeifMetadataUpdate update; update.exif = Bytes{}; update.xmp = Bytes{}; MemIo stripped; - rewriteBmff(input, stripped, original, update); - const auto cleaned = parseBmff(stripped); + rewriteHeif(input, stripped, original, update); + const auto cleaned = parseHeif(stripped); EXPECT_TRUE(cleaned.metadataItems(bmffType("Exif")).empty()); EXPECT_TRUE(cleaned.metadataItems(bmffType("mime")).empty()); - for (const auto& [id, item] : cleaned.items) - EXPECT_EQ(readBmffItem(input, original.items.at(id)), readBmffItem(stripped, item)) << id; + for (const auto& [id, item] : cleaned.meta.items) + EXPECT_EQ(readHeifItem(input, original.meta.items.at(id)), readHeifItem(stripped, item)) << id; } namespace { @@ -1529,7 +1719,7 @@ Bytes tiffItem(ExifData exif, const XmpData& xmp = {}, ByteOrder order = littleE Bytes heifWithMetadata(const ExifData& exif = {}, std::string_view xmp = {}, ByteOrder order = littleEndian) { Options options; options.noMetadata = true; - BmffMetadataUpdate update; + HeifMetadataUpdate update; if (!exif.empty()) update.exif = tiffItem(exif, {}, order); @@ -1577,7 +1767,7 @@ Bytes heifWithMergedEmbeddedXmp(bool separate = false) { // A separate packet overrides the overlapping embedded source property. if (separate) { const auto packet = rawXmpSource("MIME_SOURCE"); - BmffMetadataUpdate update; + HeifMetadataUpdate update; update.xmp = Bytes(packet.begin(), packet.end()); bytes = rewritten(bytes, update); } @@ -1900,7 +2090,7 @@ TEST(HeifImage, addsGrowsShrinksDeletesAndPreservesEncodedImage) { EXPECT_FALSE(contains(small, canary)); auto parsed = parse(small); - EXPECT_EQ(payload(small, parsed.items.at(parsed.primaryItem)), (Bytes{'A', 'B', 'C', 'D'})); + EXPECT_EQ(payload(small, parsed.meta.items.at(parsed.meta.primaryItem)), (Bytes{'A', 'B', 'C', 'D'})); if (cycle != 0) { EXPECT_EQ(small.size(), smallSize); @@ -1946,7 +2136,7 @@ TEST(HeifImage, removesDeletedTagsAndOriginalTiffSlack) { // Plant a canary in TIFF slack that a fresh serialization must discard. const std::string slack = "PRIVATE_UNUSED_TIFF_STORAGE_2223f1"; item.insert(item.end(), slack.begin(), slack.end()); - BmffMetadataUpdate update; + HeifMetadataUpdate update; update.exif = item; auto image = openHeif(rewritten(heifWithMetadata(), update)); @@ -1961,7 +2151,7 @@ TEST(HeifImage, removesDeletedTagsAndOriginalTiffSlack) { // Verify that fresh serialization preserves the original big-endian TIFF order. auto doc = parse(bytes); - auto tiff = payload(bytes, doc.items.at(doc.metadataItems(bmffType("Exif")).front())); + auto tiff = payload(bytes, doc.meta.items.at(doc.metadataItems(bmffType("Exif")).front())); ASSERT_GT(tiff.size(), 8u); EXPECT_EQ(tiff[4], 'M'); EXPECT_EQ(tiff[5], 'M'); @@ -1976,7 +2166,7 @@ TEST(HeifImage, clearsEmbeddedXmpAndPreservesItWhenOnlyExifIsRemoved) { exif["Exif.Image.Artist"] = "keep artist"; XmpData xmp; xmp["Xmp.dc.source"] = "PRIVATE_EMBEDDED_XMP_350597"; - BmffMetadataUpdate update; + HeifMetadataUpdate update; update.exif = tiffItem(exif, xmp); auto bytes = rewritten(heifWithMetadata(), update); auto image = openHeif(bytes); @@ -2023,7 +2213,7 @@ TEST(HeifImage, usesRawXmpPacketsSetMetadataAndRejectsUnsupportedCategories) { auto doc = parse(bytes); // Check raw packet handling and metadata copying through the public API. - EXPECT_EQ(payload(bytes, doc.items.at(doc.metadataItems(bmffType("mime")).front())), + EXPECT_EQ(payload(bytes, doc.meta.items.at(doc.metadataItems(bmffType("mime")).front())), Bytes(packet.begin(), packet.end())); auto target = openHeif(heifWithMetadata()); target->setMetadata(*source); @@ -2108,11 +2298,11 @@ TEST_P(BmffCorpus, editsThroughPublicApiAndKeepsOtherItems) { auto before = parse(bytes), after = parse(output); auto exif = before.metadataItems(bmffType("Exif")); auto xmp = before.metadataItems(bmffType("mime")); - for (const auto& [id, item] : before.items) { + for (const auto& [id, item] : before.meta.items) { if (std::find(exif.begin(), exif.end(), id) != exif.end() || std::find(xmp.begin(), xmp.end(), id) != xmp.end()) continue; - ASSERT_TRUE(after.items.contains(id)); - EXPECT_EQ(payload(bytes, item), payload(output, after.items.at(id))); + ASSERT_TRUE(after.meta.items.contains(id)); + EXPECT_EQ(payload(bytes, item), payload(output, after.meta.items.at(id))); } // A true no-op keeps the entire file byte-for-byte unchanged. @@ -2163,7 +2353,7 @@ TEST(HeifImage, preservesMergedEmbeddedXmpOnExifEdits) { ASSERT_EQ(items.size(), 1u); // Inspect the embedded packet independently so separate XMP cannot mask lost properties. - const auto tiff = payload(bytes, document.items.at(items.front())); + const auto tiff = payload(bytes, document.meta.items.at(items.front())); ExifData checkedExif; IptcData checkedIptc; XmpData checkedXmp; @@ -2173,8 +2363,8 @@ TEST(HeifImage, preservesMergedEmbeddedXmpOnExifEdits) { ASSERT_EQ(checkedXmp.count(), 3u); EXPECT_EQ(checkedXmp["Xmp.dc.source"].toString(), "FIRST_EMBEDDED_78b2"); const auto original = parse(source); - EXPECT_EQ(payload(bytes, document.items.at(document.primaryItem)), - payload(source, original.items.at(original.primaryItem))); + EXPECT_EQ(payload(bytes, document.meta.items.at(document.meta.primaryItem)), + payload(source, original.meta.items.at(original.meta.primaryItem))); image = openHeif(bytes); EXPECT_EQ(image->exifData()["Exif.Image.Artist"].toString(), "edited artist"); @@ -2383,9 +2573,9 @@ TEST(HeifImage, updatesIdatMetadataAndWideItemIds) { auto bytes = imageBytes(*image); auto document = parse(bytes); EXPECT_FALSE(contains(bytes, "PRIVATE_IDAT_METADATA_7703")); - EXPECT_EQ(document.primaryItem, 70001u); - EXPECT_EQ(payload(bytes, document.items.at(70001)), (Bytes{'A', 'B', 'C', 'D'})); - EXPECT_EQ(document.items.at(70001).location.constructionMethod, 1u); + EXPECT_EQ(document.meta.primaryItem, 70001u); + EXPECT_EQ(payload(bytes, document.meta.items.at(70001)), (Bytes{'A', 'B', 'C', 'D'})); + EXPECT_EQ(document.meta.items.at(70001).location.constructionMethod, 1u); } // Preserve unrelated metadata and exclude AVIF with a generic compatible brand. @@ -2406,7 +2596,7 @@ TEST(HeifImage, preservesIndependentMetadataAndRejectsGenericAvifBrand) { image->clearExifData(); image->writeMetadata(); auto result = imageBytes(*image); - EXPECT_EQ(payload(bytes, parse(bytes).items.at(2)), payload(result, parse(result).items.at(2))); + EXPECT_EQ(payload(bytes, parse(bytes).meta.items.at(2)), payload(result, parse(result).meta.items.at(2))); image->exifData()["Exif.Image.Artist"] = "primary metadata"; image->writeMetadata(); @@ -2438,7 +2628,7 @@ TEST(HeifImage, preservesEmbeddedIptcAndThumbnailDataOnExifEdits) { // Embed IPTC and thumbnail content in the original serialized Exif item. MemIo output; TiffParser::encode(output, nullptr, 0, littleEndian, exif, iptc, XmpData{}); - BmffMetadataUpdate update; + HeifMetadataUpdate update; update.exif = Bytes(4, 0); update.exif->insert(update.exif->end(), output.mmap(), output.mmap() + output.size()); auto image = openHeif(rewritten(heifWithMetadata(), update)); @@ -2466,7 +2656,7 @@ TEST(HeifImage, clearsOrphanedEmbeddedXmpAndPrintsWithoutDiscardingEdits) { // Leave an XMP canary in TIFF slack rather than an active XML tag. const std::string canary = "PRIVATE_ORPHANED_TIFF_XMP_9c1f"; item.insert(item.end(), canary.begin(), canary.end()); - BmffMetadataUpdate update; + HeifMetadataUpdate update; update.exif = item; auto image = openHeif(rewritten(heifWithMetadata(), update)); @@ -2550,11 +2740,11 @@ TEST(HeifImage, preservesAuxiliaryAndThumbnailGraphsAsOpaqueImageData) { // Repurpose the extra fixture items as opaque auxiliary and thumbnail images. for (const auto id : {2, 3}) { - const auto& info = before.items.at(id).info; + const auto& info = before.meta.items.at(id).info; patch(bytes, info.box.offset + 16, bmffType("hvc1"), 4); } - for (const auto& ref : before.references) + for (const auto& ref : before.meta.references) patch(bytes, ref.box.offset + 4, ref.from == 2 ? bmffType("auxl") : bmffType("thmb"), 4); before = parse(bytes); @@ -2566,15 +2756,15 @@ TEST(HeifImage, preservesAuxiliaryAndThumbnailGraphsAsOpaqueImageData) { auto output = imageBytes(*image); const auto after = parse(output); - for (const auto& [id, item] : before.items) - EXPECT_EQ(payload(bytes, item), payload(output, after.items.at(id))); - ASSERT_EQ(after.references.size(), before.references.size() + 1); - for (size_t i = 0; i != before.references.size(); ++i) { - EXPECT_EQ(after.references[i].type, before.references[i].type); - EXPECT_EQ(after.references[i].from, before.references[i].from); - EXPECT_EQ(after.references[i].to, before.references[i].to); + for (const auto& [id, item] : before.meta.items) + EXPECT_EQ(payload(bytes, item), payload(output, after.meta.items.at(id))); + ASSERT_EQ(after.meta.references.size(), before.meta.references.size() + 1); + for (size_t i = 0; i != before.meta.references.size(); ++i) { + EXPECT_EQ(after.meta.references[i].type, before.meta.references[i].type); + EXPECT_EQ(after.meta.references[i].from, before.meta.references[i].from); + EXPECT_EQ(after.meta.references[i].to, before.meta.references[i].to); } - EXPECT_EQ(after.associations.size(), before.associations.size()); + EXPECT_EQ(after.meta.associations.size(), before.meta.associations.size()); EXPECT_TRUE(contains(output, uri)); } } @@ -2603,7 +2793,7 @@ TEST(HeifImage, preservesRawXmpDuringExifEditsAndClearsItsStorage) { auto document = parse(bytes); const auto ids = document.metadataItems(bmffType("mime")); ASSERT_EQ(ids.size(), 1u); - EXPECT_EQ(payload(bytes, document.items.at(ids.front())), Bytes(packet.begin(), packet.end())); + EXPECT_EQ(payload(bytes, document.meta.items.at(ids.front())), Bytes(packet.begin(), packet.end())); // Replace the packet, then clear it and inspect all remaining file bytes. image->setXmpPacket(rawXmpSource("PRIVATE_REPLACEMENT_PACKET_653c")); @@ -2642,7 +2832,7 @@ TEST(HeifImage, copiesRawXmpMetadataWithoutToolkit) { auto document = parse(bytes); const auto ids = document.metadataItems(bmffType("mime")); ASSERT_EQ(ids.size(), 1u); - EXPECT_EQ(payload(bytes, document.items.at(ids.front())), Bytes(packet.begin(), packet.end())); + EXPECT_EQ(payload(bytes, document.meta.items.at(ids.front())), Bytes(packet.begin(), packet.end())); EXPECT_FALSE(contains(bytes, "REPLACED_RAW_XMP_246da7")); target = openHeif(bytes); EXPECT_EQ(target->xmpPacket(), packet); @@ -2712,7 +2902,7 @@ TEST(HeifImage, rejectsUnsupportedMetadataCopyWithoutToolkit) { // The mutable packet accessor can bypass setter limits; copying must still enforce them. source->clearXmpData(); - source->xmpPacket().assign(static_cast(bmffMetadataLimit) + 1, 'x'); + source->xmpPacket().assign(static_cast(heifMetadataLimit) + 1, 'x'); EXPECT_THROW(target->setMetadata(*source), Error); EXPECT_EQ(target->exifData()["Exif.Image.Artist"].toString(), "retained artist"); EXPECT_EQ(target->xmpPacket(), packet); From 27fbe178587d0600149f3702b02691181f1126d4 Mon Sep 17 00:00:00 2001 From: Vaclav Haisman Date: Sat, 10 Oct 2026 13:11:20 +0200 Subject: [PATCH 30/40] [bmff] Extract generic output layout and item relocation Separate box measurement, placement, relocation maps and bounded I/O from HEIF edit policy. Keep iloc encoding and layout convergence in the item layer, with HEIF retaining range ownership and metadata verification. Register the private layers in CMake and Meson and add focused layout, relocation, header-promotion and I/O regressions. --- src/CMakeLists.txt | 4 + src/bmffitemwrite_int.cpp | 132 ++++++++++ src/bmffitemwrite_int.hpp | 93 ++++++++ src/bmfflayout_int.cpp | 238 +++++++++++++++++++ src/bmfflayout_int.hpp | 114 +++++++++ src/heifwrite_int.cpp | 316 ++++-------------------- src/meson.build | 2 + unitTests/CMakeLists.txt | 1 + unitTests/meson.build | 1 + unitTests/test_bmfflayout_int.cpp | 383 ++++++++++++++++++++++++++++++ 10 files changed, 1008 insertions(+), 276 deletions(-) create mode 100644 src/bmffitemwrite_int.cpp create mode 100644 src/bmffitemwrite_int.hpp create mode 100644 src/bmfflayout_int.cpp create mode 100644 src/bmfflayout_int.hpp create mode 100644 unitTests/test_bmfflayout_int.cpp diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 4dcd1e7ff6..c70e296ce6 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -8,6 +8,10 @@ add_library( bmffbox_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 diff --git a/src/bmffitemwrite_int.cpp b/src/bmffitemwrite_int.cpp new file mode 100644 index 0000000000..ca80943546 --- /dev/null +++ b/src/bmffitemwrite_int.cpp @@ -0,0 +1,132 @@ +// SPDX-License-Identifier: GPL-2.0-or-later + +#include "bmffitemwrite_int.hpp" + +#ifdef EXV_ENABLE_BMFF + +#include "enforce.hpp" +#include "error.hpp" + +#include +#include +#include + +namespace Exiv2::Internal { +namespace { +using Bytes = std::vector; +constexpr uint64_t max32 = std::numeric_limits::max(); +constexpr uint32_t max16 = std::numeric_limits::max(); + +// Reject inconsistent item tables before encoding them. +void require(bool condition) { + enforce(condition, ErrorCode::kerCorruptedMetadata); +} + +// Encode a field within the adapter's explicit structural allocation budget. +void number(Bytes& bytes, uint64_t value, unsigned width, uint64_t maxBytes) { + require(width <= 8 && (width == 8 || value < (uint64_t{1} << (width * 8)))); + require(width <= maxBytes && bytes.size() <= maxBytes - width); + for (unsigned i = width; i != 0; --i) + bytes.push_back(static_cast(value >> ((i - 1) * 8))); +} +} // namespace + +std::vector layoutBmffItems(BmffItemModel& model, const BmffItemLayoutBuilder& builder) { + normalizeBmffLocations(model); + + // Only offset width can change after locating the output; it promotes 4 -> 8 once. + for (unsigned pass = 0; pass < 2; ++pass) { + auto boxes = builder.build(); + const auto size = layoutBmff(boxes); + auto positions = builder.positions(boxes); + if (relocateBmffItems(model, BmffRelocations(std::move(positions.retained)), positions.replacements, + positions.itemDataPosition)) + continue; + + // Rebuild offset-bearing boxes with the now-resolved positions. + boxes = builder.build(); + require(layoutBmff(boxes) == size); + return boxes; + } + + throw Error(ErrorCode::kerCorruptedMetadata); +} + +void normalizeBmffLocations(BmffItemModel& model) { + require(!model.items.empty()); + auto& format = model.locationFormat; + format.offsetSize = 4; + format.lengthSize = 4; + format.baseOffsetSize = 0; + if (model.items.rbegin()->first > max16 || model.items.size() > max16) + format.version = 2; + + // Preserve idat addressing, but eliminate per-item base offsets in the new layout. + for (auto& [id, item] : model.items) { + item.location.baseOffset = 0; + if (item.location.constructionMethod == 1) + format.version = std::max(format.version, 1); + for (const auto& extent : item.location.extents) + if (extent.length > max32) + format.lengthSize = 8; + } +} + +std::vector encodeBmffLocations(const BmffItemModel& model, uint64_t maxBytes) { + const auto& format = model.locationFormat; + Bytes bytes; + number(bytes, uint32_t{format.version} << 24, 4, maxBytes); + number(bytes, (format.offsetSize << 4) | format.lengthSize, 1, maxBytes); + number(bytes, format.indexSize, 1, maxBytes); + const unsigned width = format.version == 2 ? 4 : 2; + number(bytes, model.items.size(), width, maxBytes); + + // Retain location-table order while writing normalized extent coordinates. + for (const auto id : model.locationOrder) { + const auto& loc = model.items.at(id).location; + number(bytes, id, width, maxBytes); + if (format.version) + number(bytes, loc.constructionMethod, 2, maxBytes); + number(bytes, 0, 2, maxBytes); + number(bytes, loc.extents.size(), 2, maxBytes); + for (const auto& extent : loc.extents) { + if (format.version && format.indexSize) + number(bytes, extent.index, format.indexSize, maxBytes); + // The first layout pass measures fields whose relocated offsets are not known yet. + number(bytes, format.offsetSize == 4 && extent.offset > max32 ? 0 : extent.offset, format.offsetSize, maxBytes); + number(bytes, extent.length, format.lengthSize, maxBytes); + } + } + + return bytes; +} + +bool relocateBmffItems(BmffItemModel& model, const BmffRelocations& retained, + const std::map& replacements, uint64_t itemDataPosition) { + bool promoted = false; + for (auto& [id, item] : model.items) { + auto& location = item.location; + for (auto& extent : location.extents) { + uint64_t position = 0; + if (const auto found = replacements.find(id); found != replacements.end()) { + position = found->second; + } else { + position = retained.position(extent.source); + } + + // Convert absolute output positions back to the coordinate system required by iloc. + const auto base = location.constructionMethod == 1 ? itemDataPosition : 0; + require(position >= base); + extent.offset = position - base; + if (extent.offset > max32 && model.locationFormat.offsetSize != 8) { + model.locationFormat.offsetSize = 8; + promoted = true; + } + } + } + + return promoted; +} + +} // namespace Exiv2::Internal +#endif diff --git a/src/bmffitemwrite_int.hpp b/src/bmffitemwrite_int.hpp new file mode 100644 index 0000000000..5686c920ca --- /dev/null +++ b/src/bmffitemwrite_int.hpp @@ -0,0 +1,93 @@ +// SPDX-License-Identifier: GPL-2.0-or-later + +#ifndef BMFFITEMWRITE_INT_HPP +#define BMFFITEMWRITE_INT_HPP + +#include "bmffitem_int.hpp" +#include "bmfflayout_int.hpp" + +#ifdef EXV_ENABLE_BMFF + +namespace Exiv2::Internal { + +//! @brief Adapter-selected output positions for retained and replacement item data. +struct BmffItemPositions { + std::vector retained; //!< Approved source intervals and absolute destinations. + std::map replacements; //!< Absolute output positions of new single-extent items. + uint64_t itemDataPosition{}; //!< Absolute idat payload origin for method 1. +}; + +/*! + @brief Adapter hooks for building boxes and identifying approved item destinations. + + Implementations borrow the model passed to layoutBmffItems() and observe its + current field widths and offsets on each build. They retain ownership of all + payload buffers for the lifetime of the returned layout and its I/O operations. + */ +class BmffItemLayoutBuilder { + public: + //! @brief Destroy an adapter without affecting its borrowed model or payloads. + virtual ~BmffItemLayoutBuilder() = default; + + //! @brief Build output boxes for the current item model; throw Error for an unsupported layout. + virtual std::vector build() const = 0; + + //! @brief Identify approved item destinations in a measured layout without changing it. + virtual BmffItemPositions positions(const std::vector& boxes) const = 0; +}; + +/*! + @brief Normalize and converge item offsets before returning a measured output tree. + @param model Nonempty validated model, updated to the final iloc representation. + @param builder Adapter borrowing model and owning policy for retained and replacement data. + @return Measured boxes with regenerated item locations; payload buffers remain borrowed. + @throws Error For invalid mappings, overflow or a layout that fails to converge. + + Offset widths can promote from four to eight bytes once. Regenerate the boxes + after relocation so their encoded fields agree with their measured positions. + No I/O or transfer occurs; the caller emits and semantically verifies the result. + */ +std::vector layoutBmffItems(BmffItemModel& model, const BmffItemLayoutBuilder& builder); + +/*! + @brief Choose normalized iloc versions and field widths before output measurement. + @param model Nonempty, validated local item model; owned by the caller. + @throws Error If the model is empty. + + Retain construction methods and extent indices. Remove per-item base offsets, + choose four-byte offsets initially, and widen lengths or item IDs as needed. + Call once before iterating layout; subsequent offset promotion is monotonic. + */ +void normalizeBmffLocations(BmffItemModel& model); + +/*! + @brief Serialize the iloc FullBox prefix and item table in existing location order. + @param model Normalized item model, with widths chosen for this layout pass. + @param maxBytes Adapter-selected allocation limit for the complete encoded table. + @return Owned bytes excluding the outer box header. + @throws Error If a field cannot fit or the allocation budget is exceeded. + + Before the first relocation pass, out-of-range four-byte offsets are encoded + as zero placeholders. Only a converged layout may be emitted to a file. + */ +std::vector encodeBmffLocations(const BmffItemModel& model, uint64_t maxBytes); + +/*! + @brief Resolve iloc offsets from adapter-approved absolute output positions. + @param model Normalized model whose extent offsets and offset width are updated. + @param retained Relocations for retained source extents selected by the adapter. + @param replacements Absolute positions for newly supplied, single-extent items. + @param itemDataPosition Absolute output start of the idat payload, for method 1. + @return True if offsets widened to eight bytes, requiring another layout pass. + @throws Error For an unmapped extent or an output position preceding its origin. + + File-relative and idat-relative coordinates belong to this layer, not to the + generic layout engine. The caller must rebuild offset-bearing bytes after + relocation and remeasure until sizes converge before writing any output. + */ +bool relocateBmffItems(BmffItemModel& model, const BmffRelocations& retained, + const std::map& replacements, uint64_t itemDataPosition); + +} // namespace Exiv2::Internal +#endif +#endif diff --git a/src/bmfflayout_int.cpp b/src/bmfflayout_int.cpp new file mode 100644 index 0000000000..78dfb1bd18 --- /dev/null +++ b/src/bmfflayout_int.cpp @@ -0,0 +1,238 @@ +// SPDX-License-Identifier: GPL-2.0-or-later + +#include "bmfflayout_int.hpp" + +#ifdef EXV_ENABLE_BMFF + +#include "basicio.hpp" +#include "enforce.hpp" +#include "error.hpp" + +#include +#include +#include + +namespace Exiv2::Internal { +namespace { +constexpr uint64_t maxPosition = std::numeric_limits::max(); +constexpr uint64_t max32 = std::numeric_limits::max(); +constexpr size_t copyBufferSize = 64 * 1024; + +// Reject inconsistent layout state through the common metadata error code. +void require(bool condition) { + enforce(condition, ErrorCode::kerCorruptedMetadata); +} + +// Add positions within the signed seek range supported by BasicIo. +uint64_t add(uint64_t a, uint64_t b) { + require(a <= maxPosition && b <= maxPosition - a); + return a + b; +} + +// Return the checked exclusive end of a source interval. +uint64_t end(BmffSpan span) { + return add(span.offset, span.size); +} + +// Measure descendants before deciding whether the containing header must grow. +void measure(BmffOutputBox& box) { + uint64_t payload = box.prefix.size(); + for (auto& child : box.children) { + measure(child); + payload = add(payload, child.size); + } + for (const auto& segment : box.segments) { + if (!segment.bytes) + (void)end(segment.source); + payload = add(payload, segment.size()); + } + + // Header promotion is monotonic, including the extra UUID header bytes. + const unsigned uuidSize = box.type == bmffType("uuid") ? 16 : 0; + box.extended |= add(payload, 8 + uuidSize) > max32; + box.header = static_cast((box.extended ? 16 : 8) + uuidSize); + box.size = add(box.header, payload); +} + +// Assign absolute output coordinates without interpreting boxes or payloads. +uint64_t locate(BmffOutputBox& box, uint64_t offset) { + box.position = offset; + auto position = add(add(offset, box.header), box.prefix.size()); + for (auto& child : box.children) + position = locate(child, position); + for (auto& segment : box.segments) { + segment.position = position; + position = add(position, segment.size()); + } + + require(position == add(offset, box.size)); + return position; +} + +// Encode the at-most-32-byte framing independently of adapter-owned fields. +std::vector header(const BmffOutputBox& box) { + std::vector bytes; + // Only the standard size/type fields and optional UUID belong to the core. + const auto number = [&](uint64_t value, unsigned width) { + require(width == 8 || value <= max32); + for (unsigned i = width; i != 0; --i) + bytes.push_back(static_cast(value >> ((i - 1) * 8))); + }; + number(box.extended ? 1 : box.size, 4); + number(box.type, 4); + if (box.extended) + number(box.size, 8); + if (box.type == bmffType("uuid")) + bytes.insert(bytes.end(), box.uuid.begin(), box.uuid.end()); + require(bytes.size() == box.header); + return bytes; +} + +// Read an exact range and propagate seek, short-read and stream errors. +void read(BasicIo& input, uint64_t offset, byte* data, size_t size) { + (void)add(offset, size); + input.seekOrThrow(static_cast(offset), BasicIo::beg, ErrorCode::kerInputDataReadFailed); + input.readOrThrow(data, size, ErrorCode::kerInputDataReadFailed); + enforce(!input.error(), ErrorCode::kerInputDataReadFailed); +} + +// Reject short writes before proceeding to the next measured range. +void write(BasicIo& output, const byte* data, size_t size) { + if (size != 0) + enforce(output.write(data, size) == size && !output.error(), ErrorCode::kerImageWriteFailed); +} + +// Borrow both streams and reuse fixed buffers for emission and comparison. +class LayoutIo { + public: + // Keep source and destination ownership with the adapter. + LayoutIo(BasicIo& input, BasicIo& output) : input_(input), output_(output) { + require(&input != &output && input.isopen() && output.isopen()); + } + + // Emit framing and adapter-provided content in measured order. + void emit(const BmffOutputBox& box) { + require(output_.tell() == box.position); + const auto bytes = header(box); + emitMemory(bytes); + emitMemory(box.prefix); + for (const auto& child : box.children) + emit(child); + + // Stream borrowed source and memory segments with the same bounded requests. + for (const auto& segment : box.segments) { + require(output_.tell() == segment.position); + for (uint64_t done = 0; done < segment.size();) { + const auto count = static_cast(std::min(copy_.size(), segment.size() - done)); + if (segment.bytes) { + write(output_, segment.bytes->data() + done, count); + } else { + read(input_, add(segment.source.offset, done), copy_.data(), count); + write(output_, copy_.data(), count); + } + done += count; + } + } + require(output_.tell() == add(box.position, box.size)); + } + + // Verify every byte, including framing and prefixes generated by the adapter. + void verify(const BmffOutputBox& box) { + const auto bytes = header(box); + verifySegment({{}, &bytes, box.position}); + verifySegment({{}, &box.prefix, add(box.position, box.header)}); + for (const auto& child : box.children) + verify(child); + for (const auto& segment : box.segments) + verifySegment(segment); + } + + private: + // Bound writes of structural prefixes as well as payload buffers. + void emitMemory(const std::vector& bytes) { + for (size_t done = 0; done < bytes.size();) { + const auto count = std::min(copy_.size(), bytes.size() - done); + write(output_, bytes.data() + done, count); + done += count; + } + } + + // Compare prepared bytes to borrowed source ranges or immutable memory buffers. + void verifySegment(const BmffOutputSegment& segment) { + for (uint64_t done = 0; done < segment.size();) { + const auto count = static_cast(std::min(copy_.size(), segment.size() - done)); + read(output_, add(segment.position, done), verify_.data(), count); + if (segment.bytes) { + require(std::equal(verify_.begin(), verify_.begin() + count, segment.bytes->begin() + done)); + } else { + read(input_, add(segment.source.offset, done), copy_.data(), count); + require(std::equal(copy_.begin(), copy_.begin() + count, verify_.begin())); + } + done += count; + } + } + + BasicIo& input_; + BasicIo& output_; + std::array copy_{}; + std::array verify_{}; +}; + +// Return the final measured end, including the empty-layout case. +uint64_t outputSize(const std::vector& boxes) { + return boxes.empty() ? 0 : add(boxes.back().position, boxes.back().size); +} +} // namespace + +uint64_t BmffOutputSegment::size() const { + return bytes ? bytes->size() : source.size; +} + +BmffRelocations::BmffRelocations(std::vector ranges) : ranges_(std::move(ranges)) { + std::sort(ranges_.begin(), ranges_.end(), + [](const auto& a, const auto& b) { return a.source.offset < b.source.offset; }); + + uint64_t previousEnd = 0; + for (const auto& range : ranges_) { + require(range.source.offset >= previousEnd); + previousEnd = end(range.source); + (void)add(range.destination, range.source.size); + } +} + +uint64_t BmffRelocations::position(BmffSpan source) const { + auto found = std::upper_bound(ranges_.begin(), ranges_.end(), source.offset, + [](auto offset, const auto& map) { return offset < map.source.offset; }); + require(found != ranges_.begin()); + --found; + require(source.offset >= found->source.offset && end(source) <= end(found->source)); + return add(found->destination, source.offset - found->source.offset); +} + +uint64_t layoutBmff(std::vector& boxes) { + uint64_t position = 0; + for (auto& box : boxes) { + measure(box); + position = locate(box, position); + } + return position; +} + +void writeBmffLayout(BasicIo& input, BasicIo& output, const std::vector& boxes) { + LayoutIo io(input, output); + require(output.size() == 0); + output.seekOrThrow(0, BasicIo::beg, ErrorCode::kerImageWriteFailed); + for (const auto& box : boxes) + io.emit(box); + require(output.size() == outputSize(boxes)); +} + +void verifyBmffLayout(BasicIo& input, BasicIo& output, const std::vector& boxes) { + LayoutIo io(input, output); + require(output.size() == outputSize(boxes)); + for (const auto& box : boxes) + io.verify(box); +} + +} // namespace Exiv2::Internal +#endif diff --git a/src/bmfflayout_int.hpp b/src/bmfflayout_int.hpp new file mode 100644 index 0000000000..2dcf01d357 --- /dev/null +++ b/src/bmfflayout_int.hpp @@ -0,0 +1,114 @@ +// SPDX-License-Identifier: GPL-2.0-or-later + +#ifndef BMFFLAYOUT_INT_HPP +#define BMFFLAYOUT_INT_HPP + +#include "bmffbox_int.hpp" + +#ifdef EXV_ENABLE_BMFF + +namespace Exiv2::Internal { + +/*! + @brief Borrowed source bytes or an immutable memory buffer in an output layout. + + A non-null bytes pointer selects memory; otherwise source selects the input + interval. The input and every referenced vector must remain unchanged and + outlive measurement, emission and verification. No encoded payload is owned. + */ +struct BmffOutputSegment { + BmffSpan source; //!< Absolute interval in the original input. + const std::vector* bytes{}; //!< Borrowed replacement buffer, or null for source bytes. + uint64_t position{}; //!< Absolute output offset assigned by layoutBmff(). + + //! @brief Return the selected memory buffer's length or the source interval length. + [[nodiscard]] uint64_t size() const; +}; + +/*! + @brief Output box owning its prefix and children, and borrowing segment payloads. + + Serialization order is header, prefix, children, then segments. Adapters supply + all children and format-specific prefixes; unknown payloads are opaque. Only + the standard uuid header receives special framing. Header promotion is + monotonic, and terminal-size inputs are serialized with explicit lengths. + */ +struct BmffOutputBox { + uint32_t type{}; //!< Packed box code, with no admission policy. + bool extended{}; //!< Preserve or promote to a 64-bit size field. + std::array uuid{}; //!< User type for a uuid box. + std::vector prefix; //!< Owned bytes before any children or segments. + std::vector children; //!< Owned child nodes in output order. + std::vector segments; //!< Borrowed payloads in output order. + uint64_t position{}; //!< Absolute output offset assigned by layoutBmff(). + uint64_t size{}; //!< Measured size including the header. + uint8_t header{}; //!< Measured header length including any UUID. +}; + +//! @brief An adapter-approved source interval and its absolute output destination. +struct BmffRelocation { + BmffSpan source; //!< Retained interval in the original input. + uint64_t destination{}; //!< Absolute output position of the interval's first byte. +}; + +/*! + @brief An owned, sorted map of nonoverlapping retained source intervals. + + The adapter chooses which ranges can be relocated. Merely emitting an opaque + box does not establish that its embedded offsets can be changed safely. + */ +class BmffRelocations { + public: + //! @brief Sort and take ownership of approved ranges; throw Error for overlap or overflow. + explicit BmffRelocations(std::vector ranges); + + /*! + @brief Translate a source subrange into absolute output coordinates. + @param source Interval wholly contained in one approved range. + @return Output offset of the interval's first byte. + @throws Error If no single range contains the interval or arithmetic overflows. + */ + [[nodiscard]] uint64_t position(BmffSpan source) const; + + private: + std::vector ranges_; +}; + +/*! + @brief Measure boxes, promote headers and assign all positions starting at output offset zero. + @param boxes Adapter-built tree; owned prefixes and borrowed payloads must remain unchanged afterward. + @return Total serialized length within BasicIo's signed seek range. + @throws Error For sizes or source intervals outside the signed seek range. + + No I/O occurs. The caller bounds the number and nesting of nodes it constructs. + No format markers, item tables or metadata are required or interpreted. + */ +uint64_t layoutBmff(std::vector& boxes); + +/*! + @brief Stream a measured layout to a distinct, empty staging stream with bounded buffers. + @param input Borrowed, open, seekable source; it must remain unchanged and not alias output. + @param output Borrowed, open, empty, seekable staging stream. + @param boxes Unchanged tree already positioned by layoutBmff(). + @throws Error For inconsistent layout, overflow, failed I/O or short reads/writes. + + Stream positions change. No source transfer is performed. On failure the + partially written output must be discarded. Every I/O request is at most 64 KiB. + */ +void writeBmffLayout(BasicIo& input, BasicIo& output, const std::vector& boxes); + +/*! + @brief Compare all emitted headers, prefixes and payloads with the measured layout. + @param input Unchanged source borrowed during emission. + @param output Prepared output, distinct from input and open for reading. + @param boxes Unchanged layout with all borrowed buffers still alive. + @throws Error For a byte/size mismatch, invalid layout, or failed I/O. + + Both stream positions may change; neither stream is written. Comparisons use + two fixed 64 KiB buffers. Format-level semantic verification belongs to adapters. + */ +void verifyBmffLayout(BasicIo& input, BasicIo& output, const std::vector& boxes); + +} // namespace Exiv2::Internal +#endif +#endif diff --git a/src/heifwrite_int.cpp b/src/heifwrite_int.cpp index 03e88ad92c..09322ac8ba 100644 --- a/src/heifwrite_int.cpp +++ b/src/heifwrite_int.cpp @@ -5,11 +5,12 @@ #ifdef EXV_ENABLE_BMFF #include "basicio.hpp" +#include "bmffitemwrite_int.hpp" +#include "bmfflayout_int.hpp" #include "enforce.hpp" #include "error.hpp" #include -#include #include #include #include @@ -17,10 +18,10 @@ namespace Exiv2::Internal { namespace { using Bytes = std::vector; +using Box = BmffOutputBox; constexpr uint64_t maxPosition = std::numeric_limits::max(); constexpr uint64_t max32 = std::numeric_limits::max(); constexpr uint32_t max16 = std::numeric_limits::max(); -constexpr size_t copyBufferSize = 64 * 1024; // Reject inconsistent layout state through the common metadata error code. void require(bool condition) { @@ -73,70 +74,6 @@ bool padding(uint32_t type) { return type == bmffType("free") || type == bmffType("skip"); } -// Read an exact source range and propagate seek, short-read, and I/O errors. -void read(BasicIo& input, uint64_t offset, byte* data, size_t size) { - require(offset <= maxPosition && size <= maxPosition - offset); - input.seekOrThrow(static_cast(offset), BasicIo::beg, ErrorCode::kerInputDataReadFailed); - input.readOrThrow(data, size, ErrorCode::kerInputDataReadFailed); - enforce(!input.error(), ErrorCode::kerInputDataReadFailed); -} - -// Write an exact buffer, rejecting short writes before verification proceeds. -void write(BasicIo& output, const byte* data, size_t size) { - if (size != 0) - enforce(output.write(data, size) == size && !output.error(), ErrorCode::kerImageWriteFailed); -} - -// A borrowed source span or replacement buffer, with its absolute output position. -// Replacement buffers outlive the rewrite; chunks never own encoded image data. -struct Chunk { - BmffSpan source; - const Bytes* bytes{}; - uint32_t item{}; - uint64_t position{}; - - //! @brief Return the serialized length of the selected span or replacement buffer. - uint64_t size() const { - return bytes ? bytes->size() : source.size; - } -}; - -// Output layout node owning small prefixes and child nodes, but borrowing payloads. -struct Box { - uint32_t type{}; - bool extended{}; - std::array uuid{}; - Bytes prefix; - std::vector children; - std::vector chunks; - uint64_t position{}; - uint64_t size{}; - uint8_t header{}; -}; - -// Map a retained input interval to its absolute position in the compact output. -struct Relocation { - BmffSpan source; - uint64_t destination{}; -}; - -// Measure descendants first, promoting box headers when a 32-bit size cannot fit. -void measure(Box& box) { - uint64_t payload = box.prefix.size(); - for (auto& child : box.children) { - measure(child); - payload = add(payload, child.size); - } - for (const auto& chunk : box.chunks) - payload = add(payload, chunk.size()); - - // Header promotion is monotonic, including the extra UUID header bytes. - const unsigned uuidSize = box.type == bmffType("uuid") ? 16 : 0; - box.extended |= add(payload, 8 + uuidSize) > max32; - box.header = static_cast((box.extended ? 16 : 8) + uuidSize); - box.size = add(box.header, payload); -} - //! @brief Unite only ranges from the same source payload. Original item boundaries stay in iloc. void mergeRanges(std::vector& spans) { std::sort(spans.begin(), spans.end(), [](auto a, auto b) { return a.offset < b.offset; }); @@ -155,7 +92,7 @@ void mergeRanges(std::vector& spans) { } // Prepare, emit, and verify a compact container without transferring it to the source. -class Rewrite { +class Rewrite : public BmffItemLayoutBuilder { public: //! @brief Borrow both streams and the original model; keep a separate model for the edit. Rewrite(BasicIo& input, BasicIo& output, const HeifDocument& original) : @@ -179,29 +116,11 @@ class Rewrite { for (const auto& entry : document_.meta.associations) associations_[entry.box.offset].push_back(&entry); indexBoxes(original_.file.boxes); - normalizeLocations(); - - // Only offset width can change after locating the output; it promotes 4 -> 8 once. - for (unsigned pass = 0; pass < 2; ++pass) { - auto boxes = build(); - const auto size = locate(boxes); - if (relocate()) - continue; - - // Rebuild offset-bearing boxes with the now-resolved positions. - boxes = build(); - require(locate(boxes) == size); - - // Only a stable layout may be emitted and compared with the requested result. - output_.seekOrThrow(0, BasicIo::beg, ErrorCode::kerImageWriteFailed); - for (const auto& box : boxes) - emit(box); - require(output_.size() == size); - verify(boxes); - return; - } + const auto boxes = layoutBmffItems(document_.meta, *this); - throw Error(ErrorCode::kerCorruptedMetadata); + // Only a stable layout may be emitted and compared with the requested result. + writeBmffLayout(input_, output_, boxes); + verify(boxes); } private: @@ -338,26 +257,6 @@ class Rewrite { } } - // Normalize base offsets and choose widths/versions before measuring output layout. - void normalizeLocations() { - auto& format = document_.meta.locationFormat; - format.offsetSize = 4; - format.lengthSize = 4; - format.baseOffsetSize = 0; - if (document_.meta.items.rbegin()->first > max16 || document_.meta.items.size() > max16) - format.version = 2; - - // Preserve idat addressing, but eliminate per-item base offsets in the new layout. - for (auto& [id, item] : document_.meta.items) { - item.location.baseOffset = 0; - if (item.location.constructionMethod == 1) - format.version = std::max(format.version, 1); - for (const auto& extent : item.location.extents) - if (extent.length > max32) - format.lengthSize = 8; - } - } - // Preserve existing infe entries or serialize a description for a new metadata item. Box itemInfo(uint32_t id) const { const auto& info = document_.meta.items.at(id).info; @@ -379,35 +278,6 @@ class Rewrite { return box; } - // Serialize current item locations with the widths selected for this layout pass. - Bytes locations() const { - const auto& format = document_.meta.locationFormat; - auto bytes = full(format.version); - number(bytes, (format.offsetSize << 4) | format.lengthSize, 1); - number(bytes, format.indexSize, 1); - const unsigned width = format.version == 2 ? 4 : 2; - number(bytes, document_.meta.items.size(), width); - - // Retain location-table order while writing normalized extent coordinates. - for (const auto id : document_.meta.locationOrder) { - const auto& loc = document_.meta.items.at(id).location; - number(bytes, id, width); - if (format.version) - number(bytes, loc.constructionMethod, 2); - number(bytes, 0, 2); - number(bytes, loc.extents.size(), 2); - for (const auto& extent : loc.extents) { - if (format.version && format.indexSize) - number(bytes, extent.index, format.indexSize); - // The first layout pass measures fields whose relocated offsets are not known yet. - number(bytes, format.offsetSize == 4 && extent.offset > max32 ? 0 : extent.offset, format.offsetSize); - number(bytes, extent.length, format.lengthSize); - } - } - - return bytes; - } - // Rebuild directed references, widening IDs while retaining original child ordering. Box references(const BmffBox* original = nullptr) const { Box box; @@ -440,7 +310,7 @@ class Rewrite { box.type = original.type; box.extended = original.headerSize == (original.type == bmffType("uuid") ? 32 : 16); box.uuid = original.userType; - box.chunks.push_back({original.payload()}); + box.segments.push_back({original.payload()}); return box; } @@ -450,20 +320,20 @@ class Rewrite { if (padding(box.type)) { if (!property) return {}; - box.chunks.clear(); // Keep indexed property slots; discard their padding bytes. + box.segments.clear(); // Keep indexed property slots; discard their padding bytes. } else if (box.type == bmffType("mdat") || box.type == bmffType("idat")) { // Build media solely from retained ranges, excluding old metadata and gaps. - box.chunks.clear(); + box.segments.clear(); const auto found = ranges_.find(original.payload().offset); if (found == ranges_.end()) return {}; for (const auto range : found->second) - box.chunks.push_back({range}); + box.segments.push_back({range}); } else if (box.type == bmffType("iloc")) { - box.chunks.clear(); - box.prefix = locations(); + box.segments.clear(); + box.prefix = encodeBmffLocations(document_.meta, HeifLimits{}.boxes.maxBytesRead); } else if (box.type == bmffType("iinf")) { - box.chunks.clear(); + box.segments.clear(); auto version = original.fullBox->version; if (document_.meta.items.size() > max16) version = std::max(version, 1); @@ -475,7 +345,7 @@ class Rewrite { box = references(&original); } else if (box.type == bmffType("ipma")) { // Keep property slots stable while removing associations owned by deleted items. - box.chunks.clear(); + box.segments.clear(); const auto format = *original.fullBox; box.prefix = full(format.version, format.flags); const auto found = associations_.find(original.span.offset); @@ -492,7 +362,7 @@ class Rewrite { format.flags & 1 ? 2 : 1); } } else if (!original.children.empty() || box.type == bmffType("ipco")) { - box.chunks.clear(); + box.segments.clear(); if (original.fullBox) box.prefix = full(original.fullBox->version, original.fullBox->flags); @@ -512,8 +382,8 @@ class Rewrite { return box; } - // Preserve top-level ordering and append one media box for replacement metadata. - std::vector build() const { + //! @brief Preserve top-level order and append one media box for replacement metadata. + std::vector build() const override { std::vector boxes; for (const auto& box : original_.file.boxes) if (auto rebuilt = rebuild(box)) @@ -524,138 +394,38 @@ class Rewrite { Box box; box.type = bmffType("mdat"); for (const auto& [id, bytes] : newItems_) - box.chunks.push_back({{}, bytes, id}); + box.segments.push_back({{}, bytes}); boxes.push_back(std::move(box)); } return boxes; } - // Assign absolute output positions and collect mappings for retained media ranges. - uint64_t locate(Box& box, uint64_t offset) { - box.position = offset; - auto position = add(add(offset, box.header), box.prefix.size()); + // Select only adapter-approved media mappings and the current idat origin. + static void collectPositions(const Box& box, BmffItemPositions& positions, + std::map& replacements) { if (box.type == bmffType("idat")) - idatPosition_ = add(offset, box.header); - for (auto& child : box.children) - position = locate(child, position); - for (auto& chunk : box.chunks) { - // Remember new metadata positions separately from retained source-range mappings. - chunk.position = position; - if (chunk.bytes) - newPositions_.emplace(chunk.item, position); + positions.itemDataPosition = add(box.position, box.header); + for (const auto& child : box.children) + collectPositions(child, positions, replacements); + for (const auto& segment : box.segments) { + if (segment.bytes) + replacements.emplace(segment.bytes, segment.position); else if (box.type == bmffType("mdat") || box.type == bmffType("idat")) - relocations_.push_back({chunk.source, position}); - position = add(position, chunk.size()); - } - - require(position == add(offset, box.size)); - return position; - } - - // Measure the whole output and rebuild its source-to-destination lookup tables. - uint64_t locate(std::vector& boxes) { - relocations_.clear(); - newPositions_.clear(); - idatPosition_ = 0; - uint64_t offset = 0; - - for (auto& box : boxes) { - measure(box); - offset = locate(box, offset); - } - - // A sorted mapping lets each retained extent find its containing interval. - std::sort(relocations_.begin(), relocations_.end(), - [](const auto& a, const auto& b) { return a.source.offset < b.source.offset; }); - return offset; - } - - // Update iloc offsets from the layout; report whether widening requires another pass. - bool relocate() { - bool promoted = false; - for (auto& [id, item] : document_.meta.items) { - auto& location = item.location; - for (auto& extent : location.extents) { - uint64_t position = 0; - if (newItems_.contains(id)) { - position = newPositions_.at(id); - } else { - auto found = std::upper_bound(relocations_.begin(), relocations_.end(), extent.source.offset, - [](auto offset, const auto& map) { return offset < map.source.offset; }); - require(found != relocations_.begin()); - --found; - require(extent.source.offset >= found->source.offset && end(extent.source) <= end(found->source)); - position = add(found->destination, extent.source.offset - found->source.offset); - } - - // Convert absolute output positions back to the coordinate system required by iloc. - const auto base = location.constructionMethod == 1 ? idatPosition_ : 0; - require(position >= base); - extent.offset = position - base; - if (extent.offset > max32 && document_.meta.locationFormat.offsetSize != 8) { - document_.meta.locationFormat.offsetSize = 8; - promoted = true; - } - } + positions.retained.push_back({segment.source, segment.position}); } - - return promoted; } - // Stream a measured box using bounded buffers for all borrowed payload ranges. - void emit(const Box& box) { - require(output_.tell() == box.position); - - Bytes header; - number(header, box.extended ? 1 : box.size, 4); - number(header, box.type, 4); - if (box.extended) - number(header, box.size, 8); - if (box.type == bmffType("uuid")) - header.insert(header.end(), box.uuid.begin(), box.uuid.end()); - write(output_, header.data(), header.size()); - write(output_, box.prefix.data(), box.prefix.size()); - for (const auto& child : box.children) - emit(child); - - // After writing structure, stream payload chunks without loading entire images. - auto& buffer = copyBuffer_; - for (const auto& chunk : box.chunks) { - require(output_.tell() == chunk.position); - for (uint64_t done = 0; done < chunk.size();) { - const auto count = static_cast(std::min(buffer.size(), chunk.size() - done)); - if (chunk.bytes) { - write(output_, chunk.bytes->data() + done, count); - } else { - read(input_, add(chunk.source.offset, done), buffer.data(), count); - write(output_, buffer.data(), count); - } - done += count; - } - } - } + //! @brief Select retained media and replacement positions using HEIF's ownership policy. + BmffItemPositions positions(const std::vector& boxes) const override { + BmffItemPositions result; + std::map replacements; + for (const auto& box : boxes) + collectPositions(box, result, replacements); - // Compare emitted payloads to their source ranges or replacement buffers in bounded chunks. - void verifyBytes(const Box& box) { - for (const auto& child : box.children) - verifyBytes(child); - - auto& a = copyBuffer_; - auto& b = verifyBuffer_; - for (const auto& chunk : box.chunks) { - for (uint64_t done = 0; done < chunk.size();) { - const auto count = static_cast(std::min(a.size(), chunk.size() - done)); - read(output_, add(chunk.position, done), b.data(), count); - if (chunk.bytes) { - require(std::equal(b.begin(), b.begin() + count, chunk.bytes->begin() + done)); - } else { - read(input_, add(chunk.source.offset, done), a.data(), count); - require(std::equal(a.begin(), a.begin() + count, b.begin())); - } - done += count; - } - } + for (const auto& [id, bytes] : newItems_) + result.replacements.emplace(id, replacements.at(bytes)); + return result; } // Reparse the output and check item identity, relocated addressing, relationships, and bytes. @@ -710,8 +480,7 @@ class Rewrite { require(parsed.meta.properties[i].type == document_.meta.properties[i].type); // Structural agreement alone is insufficient; verify every copied or generated byte. - for (const auto& box : boxes) - verifyBytes(box); + verifyBmffLayout(input_, output_, boxes); } BasicIo& input_; @@ -723,12 +492,7 @@ class Rewrite { std::map newItems_; std::map> ranges_; std::map originalBoxes_; - std::vector relocations_; std::map> associations_; - std::array copyBuffer_{}; - std::array verifyBuffer_{}; - std::map newPositions_; - uint64_t idatPosition_{}; }; } // namespace diff --git a/src/meson.build b/src/meson.build index 477e42b936..8f4aa4e21e 100644 --- a/src/meson.build +++ b/src/meson.build @@ -47,6 +47,8 @@ endif int_lib = files( 'bmffbox_int.cpp', 'bmffitem_int.cpp', + 'bmffitemwrite_int.cpp', + 'bmfflayout_int.cpp', 'heifstructure_int.cpp', 'heifwrite_int.cpp', 'canonmn_int.cpp', diff --git a/unitTests/CMakeLists.txt b/unitTests/CMakeLists.txt index ccbdf45865..f53c9654fc 100644 --- a/unitTests/CMakeLists.txt +++ b/unitTests/CMakeLists.txt @@ -13,6 +13,7 @@ add_executable( unit_tests test_basicio.cpp test_bmffbox_int.cpp + test_bmfflayout_int.cpp test_bmffimage_int.cpp test_bmpimage.cpp test_cr2header_int.cpp diff --git a/unitTests/meson.build b/unitTests/meson.build index d8356e0fb2..b768c3f251 100644 --- a/unitTests/meson.build +++ b/unitTests/meson.build @@ -15,6 +15,7 @@ test_sources = files( 'test_XmpKey.cpp', 'test_basicio.cpp', 'test_bmffbox_int.cpp', + 'test_bmfflayout_int.cpp', 'test_bmffimage_int.cpp', 'test_bmpimage.cpp', 'test_cr2header_int.cpp', diff --git a/unitTests/test_bmfflayout_int.cpp b/unitTests/test_bmfflayout_int.cpp new file mode 100644 index 0000000000..0e161b610b --- /dev/null +++ b/unitTests/test_bmfflayout_int.cpp @@ -0,0 +1,383 @@ +// SPDX-License-Identifier: GPL-2.0-or-later + +#include "bmffitemwrite_int.hpp" +#include "bmfflayout_int.hpp" + +#ifdef EXV_ENABLE_BMFF + +#include +#include +#include + +#include +#include + +using namespace Exiv2; +using namespace Exiv2::Internal; + +namespace { +using Bytes = std::vector; +constexpr uint64_t max32 = std::numeric_limits::max(); +constexpr uint64_t maxPosition = std::numeric_limits::max(); + +// Construct a source-backed output node without format recognition or item tables. +BmffOutputBox sourceBox(uint32_t type, BmffSpan source) { + BmffOutputBox box; + box.type = type; + box.segments.push_back({source}); + return box; +} + +// Snapshot the complete contents of a small memory stream for byte comparisons. +Bytes contents(MemIo& io) { + return Bytes(io.mmap(), io.mmap() + io.size()); +} + +// Distinguish layout corruption from a stream's read/write failures. +template +void expectError(ErrorCode code, Operation operation) { + try { + operation(); + FAIL() << "Expected an Exiv2::Error"; + } catch (const Error& error) { + EXPECT_EQ(error.code(), code); + } +} + +// Count requests and inject stream failures while retaining ordinary memory storage. +class TestIo : public MemIo { + public: + using MemIo::read; + using MemIo::write; + + // Start with an empty output stream. + TestIo() = default; + + // Borrow stable fixture storage as the input stream. + explicit TestIo(const Bytes& bytes) : MemIo(bytes.data(), bytes.size()) { + } + + bool shortRead{}; + bool shortWrite{}; + bool failSeek{}; + bool reportError{}; + size_t largestRead{}; + size_t largestWrite{}; + size_t writes{}; + + //! @brief Observe the largest read and optionally return one byte fewer. + size_t read(byte* output, size_t count) override { + largestRead = std::max(largestRead, count); + return MemIo::read(output, shortRead && count ? count - 1 : count); + } + + //! @brief Observe writes and optionally stop before the requested buffer is complete. + size_t write(const byte* data, size_t count) override { + largestWrite = std::max(largestWrite, count); + ++writes; + return MemIo::write(data, shortWrite && count ? count - 1 : count); + } + + //! @brief Inject a seek failure independently of returned read counts. + int seek(int64_t offset, Position origin) override { + return failSeek ? 1 : MemIo::seek(offset, origin); + } + + //! @brief Inject an error flag even after a full-sized transfer. + int error() const override { + return reportError ? 1 : MemIo::error(); + } +}; +} // namespace + +// Preserve opaque bytes and caller-defined prefixes in a non-image container. +TEST(BmffLayout, writesPrefixedContainersAndOpaqueSegmentsWithoutImageMarkers) { + const Bytes source{0, 0, 0, 1, 'b', 'a', 'd', '!', 9, 10}; + const Bytes replacement{11, 12}; + MemIo input(source.data(), source.size()), output; + BmffOutputBox parent; + parent.type = bmffType("nest"); + parent.prefix = {42}; + parent.children.push_back(sourceBox(bmffType("data"), {0, 8})); + parent.segments = {{{8, 2}}, {{}, &replacement}}; + std::vector boxes{parent}; + + EXPECT_EQ(layoutBmff(boxes), 29u); + EXPECT_EQ(boxes[0].children[0].position, 9u); + EXPECT_EQ(boxes[0].segments[0].position, 25u); + writeBmffLayout(input, output, boxes); + EXPECT_NO_THROW(verifyBmffLayout(input, output, boxes)); + + const Bytes expected{0, 0, 0, 29, 'n', 'e', 's', 't', 42, 0, 0, 0, 16, 'd', 'a', + 't', 'a', 0, 0, 0, 1, 'b', 'a', 'd', '!', 9, 10, 11, 12}; + EXPECT_EQ(contents(output), expected); + EXPECT_EQ(contents(input), source); +} + +// Encode both UUID header forms and retain an explicitly extended small box. +TEST(BmffLayout, writesOrdinaryAndExtendedUuidHeaders) { + MemIo input, output; + BmffOutputBox box; + box.type = bmffType("uuid"); + for (size_t i = 0; i < box.uuid.size(); ++i) + box.uuid[i] = static_cast(i); + std::vector boxes{box, box}; + boxes[1].extended = true; + + EXPECT_EQ(layoutBmff(boxes), 56u); + writeBmffLayout(input, output, boxes); + EXPECT_NO_THROW(verifyBmffLayout(input, output, boxes)); + + const Bytes expected{0, 0, 0, 24, 'u', 'u', 'i', 'd', 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, + 11, 12, 13, 14, 15, 0, 0, 0, 1, 'u', 'u', 'i', 'd', 0, 0, 0, 0, 0, 0, + 0, 32, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}; + EXPECT_EQ(contents(output), expected); +} + +// Exercise exact size boundaries and nested promotion without allocating large payloads. +TEST(BmffLayout, promotesHeadersAndPlacesSparseRangesBeyondFourGiB) { + for (const auto type : {bmffType("data"), bmffType("uuid")}) { + const uint64_t shortHeader = type == bmffType("uuid") ? 24 : 8; + std::vector boxes{sourceBox(type, {0, max32 - shortHeader})}; + EXPECT_EQ(layoutBmff(boxes), max32); + EXPECT_FALSE(boxes[0].extended); + + ++boxes[0].segments[0].source.size; + EXPECT_EQ(layoutBmff(boxes), max32 + 9); + EXPECT_TRUE(boxes[0].extended); + EXPECT_EQ(boxes[0].header, shortHeader + 8); + + // Promotion stays in effect if a later pass shrinks the payload. + boxes[0].segments[0].source.size = 1; + EXPECT_EQ(layoutBmff(boxes), shortHeader + 9); + EXPECT_TRUE(boxes[0].extended); + } + + BmffOutputBox parent; + parent.type = bmffType("nest"); + parent.prefix = {1, 2, 3}; + parent.children.push_back(sourceBox(bmffType("data"), {uint64_t{1} << 34, max32})); + std::vector boxes{parent, sourceBox(bmffType("tail"), {0, 1})}; + EXPECT_EQ(layoutBmff(boxes), max32 + 44); + EXPECT_EQ(boxes[0].header, 16u); + EXPECT_EQ(boxes[0].children[0].segments[0].position, 35u); + EXPECT_EQ(boxes[1].position, max32 + 35); +} + +// Reject impossible output sizes and source intervals before attempting any I/O. +TEST(BmffLayout, rejectsSignedPositionOverflow) { + std::vector boxes{sourceBox(bmffType("data"), {maxPosition, 1})}; + EXPECT_THROW((void)layoutBmff(boxes), Error); + boxes[0].segments[0].source = {0, maxPosition}; + EXPECT_THROW((void)layoutBmff(boxes), Error); + boxes[0].segments[0].source = {0, maxPosition - 16}; + EXPECT_EQ(layoutBmff(boxes), maxPosition); + boxes.push_back(sourceBox(bmffType("tail"), {0, 0})); + EXPECT_THROW((void)layoutBmff(boxes), Error); +} + +// Translate approved subranges, rejecting gaps and ambiguous or overflowing maps. +TEST(BmffLayout, relocatesOnlyExplicitlyApprovedSourceRanges) { + const BmffRelocations mappings({{{100, 20}, max32 + 10}, {{20, 10}, 5}}); + EXPECT_EQ(mappings.position({24, 4}), 9u); + EXPECT_EQ(mappings.position({105, 15}), max32 + 15); + EXPECT_EQ(mappings.position({120, 0}), max32 + 30); + EXPECT_THROW((void)mappings.position({19, 1}), Error); + EXPECT_THROW((void)mappings.position({29, 2}), Error); + EXPECT_THROW((void)mappings.position({90, 40}), Error); + EXPECT_THROW((void)mappings.position({maxPosition, 1}), Error); + EXPECT_THROW((void)BmffRelocations({{{20, 10}, 0}, {{25, 10}, 30}}), Error); + EXPECT_THROW((void)BmffRelocations({{{0, 2}, maxPosition}}), Error); + EXPECT_THROW((void)BmffRelocations({{{maxPosition, 1}, 0}}), Error); +} + +// Bound requests for source payloads, replacement buffers and owned structural prefixes. +TEST(BmffLayout, boundsAllCopyingAndVerificationRequests) { + const Bytes source(2 * 64 * 1024 + 13, 0x53); + const Bytes replacement(64 * 1024 + 19, 0xa7); + TestIo input(source), output; + auto box = sourceBox(bmffType("data"), {0, source.size()}); + box.prefix = Bytes(64 * 1024 + 5, 0x29); + box.segments.push_back({{}, &replacement}); + std::vector boxes{box}; + (void)layoutBmff(boxes); + + writeBmffLayout(input, output, boxes); + verifyBmffLayout(input, output, boxes); + + EXPECT_EQ(input.largestRead, 64u * 1024); + EXPECT_EQ(output.largestRead, 64u * 1024); + EXPECT_EQ(output.largestWrite, 64u * 1024); + EXPECT_EQ(input.writes, 0u); + EXPECT_EQ(contents(input), source); +} + +// Propagate failures from both streams without modifying the borrowed input. +TEST(BmffLayout, propagatesShortIoSeekFailuresAndStreamErrors) { + const Bytes source{1, 2, 3, 4}; + std::vector boxes{sourceBox(bmffType("data"), {0, source.size()})}; + (void)layoutBmff(boxes); + + for (unsigned failure = 0; failure != 6; ++failure) { + TestIo input(source), output; + input.shortRead = failure == 0; + input.failSeek = failure == 1; + input.reportError = failure == 2; + output.shortWrite = failure == 3; + output.failSeek = failure == 4; + output.reportError = failure == 5; + expectError(failure < 3 ? ErrorCode::kerInputDataReadFailed : ErrorCode::kerImageWriteFailed, + [&] { writeBmffLayout(input, output, boxes); }); + EXPECT_EQ(input.writes, 0u); + EXPECT_EQ(contents(input), source); + } + + TestIo input(source), output; + writeBmffLayout(input, output, boxes); + output.shortRead = true; + expectError(ErrorCode::kerInputDataReadFailed, [&] { verifyBmffLayout(input, output, boxes); }); +} + +// Verify headers, owned prefixes, source bytes and replacement bytes, not only file length. +TEST(BmffLayout, detectsCorruptionInEveryOutputRegion) { + const Bytes source{1, 2, 3}; + const Bytes replacement{4, 5}; + auto box = sourceBox(bmffType("data"), {0, source.size()}); + box.prefix = {42}; + box.segments.push_back({{}, &replacement}); + std::vector boxes{box}; + (void)layoutBmff(boxes); + + for (const auto offset : {0u, 8u, 9u, 12u}) { + MemIo input(source.data(), source.size()), output; + writeBmffLayout(input, output, boxes); + output.mmap()[offset] ^= 1; + expectError(ErrorCode::kerCorruptedMetadata, [&] { verifyBmffLayout(input, output, boxes); }); + EXPECT_EQ(contents(input), source); + } +} + +// Empty layouts are valid, while aliasing and nonempty output streams are rejected. +TEST(BmffLayout, supportsEmptyLayoutsAndRejectsInvalidSinks) { + MemIo input, output; + std::vector boxes; + EXPECT_EQ(layoutBmff(boxes), 0u); + EXPECT_NO_THROW(writeBmffLayout(input, output, boxes)); + EXPECT_NO_THROW(verifyBmffLayout(input, output, boxes)); + EXPECT_THROW(writeBmffLayout(input, input, boxes), Error); + + const byte canary = 42; + ASSERT_EQ(output.write(&canary, 1), 1u); + EXPECT_THROW(writeBmffLayout(input, output, boxes), Error); + EXPECT_EQ(contents(output), Bytes{canary}); +} + +// Normalize item coordinates and promote iloc offsets independently of any image format. +TEST(BmffItemWrite, preservesIdatOriginsAndPromotesFileOffsets) { + BmffItemModel model; + auto& file = model.items[70000].location; + file.baseOffset = 19; + file.extents.push_back({0, max32 + 1, 3, {100, 3}}); + auto& relative = model.items[2].location; + relative.baseOffset = 20; + relative.constructionMethod = 1; + relative.extents.push_back({0, 0, 5, {200, 5}}); + model.items[3].location.extents.push_back({0, 0, 2, {}}); + model.locationOrder = {70000, 2, 3}; + + normalizeBmffLocations(model); + EXPECT_EQ(model.locationFormat.version, 2u); + EXPECT_EQ(model.locationFormat.offsetSize, 4u); + EXPECT_EQ(file.baseOffset, 0u); + const auto initial = encodeBmffLocations(model, 1024); + const BmffRelocations retained({{{100, 3}, max32 + 100}, {{200, 5}, max32 + 210}}); + EXPECT_TRUE(relocateBmffItems(model, retained, {{3, max32 + 300}}, max32 + 200)); + EXPECT_EQ(file.extents[0].offset, max32 + 100); + EXPECT_EQ(relative.extents[0].offset, 10u); + EXPECT_EQ(model.items.at(3).location.extents[0].offset, max32 + 300); + EXPECT_EQ(model.locationFormat.offsetSize, 8u); + EXPECT_EQ(encodeBmffLocations(model, 1024).size(), initial.size() + 12); + EXPECT_FALSE(relocateBmffItems(model, retained, {{3, max32 + 300}}, max32 + 200)); + EXPECT_THROW(relocateBmffItems(model, retained, {{3, max32 + 300}}, max32 + 211), Error); +} + +// Retain extent indices and widen lengths without tying resource limits to HEIF. +TEST(BmffItemWrite, retainsIndicesAndChecksEncodingBudgets) { + BmffItemModel model; + model.locationFormat.version = 1; + model.locationFormat.indexSize = 2; + model.items[1].location.extents.push_back({9, 0, max32 + 1, {0, max32 + 1}}); + model.locationOrder = {1}; + normalizeBmffLocations(model); + EXPECT_EQ(model.locationFormat.lengthSize, 8u); + EXPECT_EQ(model.locationFormat.indexSize, 2u); + const auto bytes = encodeBmffLocations(model, 100); + EXPECT_EQ(bytes.size(), 30u); + EXPECT_EQ(bytes[4], 0x48); + EXPECT_EQ(bytes[5], 2); + EXPECT_EQ(bytes[17], 9); + EXPECT_EQ(encodeBmffLocations(model, bytes.size()), bytes); + EXPECT_THROW((void)encodeBmffLocations(model, bytes.size() - 1), Error); + EXPECT_THROW((void)encodeBmffLocations(model, 0), Error); +} + +// Keep field-width convergence in the item layer while the adapter chooses payload ownership. +TEST(BmffItemWrite, convergesAndRegeneratesLocationsBeforeAnyIo) { + // Borrow a neutral item model and provide no image or metadata interpretation. + class Builder : public BmffItemLayoutBuilder { + public: + // Keep the model alive while the item layer updates its widths and offsets. + explicit Builder(const BmffItemModel& model) : model_(model) { + } + + mutable unsigned builds{}; + bool unstable{}; + const Bytes replacement{42}; + + //! @brief Encode iloc and place a replacement after the retained source interval. + std::vector build() const override { + ++builds; + BmffOutputBox locations; + locations.type = bmffType("iloc"); + locations.prefix = encodeBmffLocations(model_, 1024); + if (unstable) + locations.prefix.resize(locations.prefix.size() + builds); + auto data = sourceBox(bmffType("data"), model_.items.at(1).location.extents[0].source); + BmffOutputBox tail; + tail.type = bmffType("tail"); + tail.segments.push_back({{}, &replacement}); + return {locations, data, tail}; + } + + //! @brief Approve the source interval and identify the new item's absolute destination. + BmffItemPositions positions(const std::vector& boxes) const override { + const auto& data = boxes.at(1).segments[0]; + return {{{data.source, data.position}}, {{2, boxes.at(2).segments[0].position}}, 0}; + } + + private: + const BmffItemModel& model_; + }; + + for (const auto length : {uint64_t{3}, max32 + 1}) { + BmffItemModel model; + model.items[1].location.extents.push_back({0, 0, length, {0, length}}); + model.items[2].location.extents.push_back({0, 0, 1, {}}); + model.locationOrder = {1, 2}; + Builder builder(model); + + const auto boxes = layoutBmffItems(model, builder); + + EXPECT_EQ(builder.builds, length > max32 ? 3u : 2u); + EXPECT_EQ(model.locationFormat.offsetSize, length > max32 ? 8u : 4u); + EXPECT_EQ(model.items.at(1).location.extents[0].offset, boxes[1].segments[0].position); + EXPECT_EQ(model.items.at(2).location.extents[0].offset, boxes[2].segments[0].position); + EXPECT_EQ(boxes[0].prefix, encodeBmffLocations(model, 1024)); + + // A changing structural size cannot be emitted as a converged result. + builder.unstable = true; + EXPECT_THROW((void)layoutBmffItems(model, builder), Error); + } +} + +#endif From 1ba5bca00dee58eb92e8f1ffe60424798a7419b5 Mon Sep 17 00:00:00 2001 From: Vaclav Haisman Date: Sat, 10 Oct 2026 13:51:47 +0200 Subject: [PATCH 31/40] [bmff] Migrate legacy reader to shared box traversal Use a private adapter for legacy metadata decoding and structure output, retaining format-specific behavior and the existing BmffImage ABI. Share counted traversal and FullBox field decoding with the item parser. Reject malformed UUID and container boundaries and propagate structural I/O failures. Add compatibility and hardening regressions. --- include/exiv2/bmffimage.hpp | 7 + src/bmffbox_int.hpp | 14 +- src/bmffimage.cpp | 664 +++++++++++++++--------------- src/bmffitem_int.cpp | 3 +- unitTests/CMakeLists.txt | 1 + unitTests/meson.build | 1 + unitTests/test_bmffbox_int.cpp | 29 ++ unitTests/test_bmfflegacy_int.cpp | 432 +++++++++++++++++++ 8 files changed, 822 insertions(+), 329 deletions(-) create mode 100644 unitTests/test_bmfflegacy_int.cpp diff --git a/include/exiv2/bmffimage.hpp b/include/exiv2/bmffimage.hpp index 8747253d47..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) { } @@ -123,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/src/bmffbox_int.hpp b/src/bmffbox_int.hpp index cca23a4216..f70ed73a11 100644 --- a/src/bmffbox_int.hpp +++ b/src/bmffbox_int.hpp @@ -40,6 +40,11 @@ struct BmffFullBox { 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. @@ -168,17 +173,20 @@ class BmffReader { @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 on success. Callback exceptions propagate. + 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) { + void visit(BmffCursor& input, unsigned depth, Visitor&& visitor, uint64_t count = UINT64_MAX) { checkTraversal(input, depth); - while (input.remaining() != 0) { + while (input.remaining() != 0 && count != 0) { + --count; auto box = readBox(input); auto fields = cursor(box.payload()); visitor(box, fields); diff --git a/src/bmffimage.cpp b/src/bmffimage.cpp index afeb4fb560..40ea49b9a6 100644 --- a/src/bmffimage.cpp +++ b/src/bmffimage.cpp @@ -4,6 +4,7 @@ #include "bmffimage.hpp" #include "basicio.hpp" +#include "bmffbox_int.hpp" #include "config.h" #include "enforce.hpp" #include "error.hpp" @@ -25,6 +26,7 @@ #include #include #include +#include #include enum TAG { @@ -113,7 +115,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 +225,196 @@ 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) { + auto input = reader_.cursor({0, reader_.fileSize()}); + walk(input, out, option, depth); } - 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) { + 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 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_); + 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 +422,188 @@ 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; + uint32_t width = data.read_uint32(skip, BmffImage::endian_); 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 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'; } - if (bLF && bTrace) - out << '\n'; - // return address of next box - return box_end; + BmffImage& image_; + BmffReader reader_; +}; +} // 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 +743,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 +773,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 index c5d7d52b31..987e10ff14 100644 --- a/src/bmffitem_int.cpp +++ b/src/bmffitem_int.cpp @@ -87,8 +87,7 @@ class Parser { // 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 value = static_cast(input.number(4)); - BmffFullBox full{static_cast(value >> 24), value & 0xffffff}; + const auto full = decodeBmffFullBox(static_cast(input.number(4))); supported(full.version <= maxVersion, "box version"); require((full.flags & ~allowedFlags) == 0); box.fullBox = full; diff --git a/unitTests/CMakeLists.txt b/unitTests/CMakeLists.txt index f53c9654fc..932aba0b24 100644 --- a/unitTests/CMakeLists.txt +++ b/unitTests/CMakeLists.txt @@ -13,6 +13,7 @@ add_executable( unit_tests test_basicio.cpp test_bmffbox_int.cpp + test_bmfflegacy_int.cpp test_bmfflayout_int.cpp test_bmffimage_int.cpp test_bmpimage.cpp diff --git a/unitTests/meson.build b/unitTests/meson.build index b768c3f251..f7cb8ffd81 100644 --- a/unitTests/meson.build +++ b/unitTests/meson.build @@ -15,6 +15,7 @@ test_sources = files( 'test_XmpKey.cpp', 'test_basicio.cpp', 'test_bmffbox_int.cpp', + 'test_bmfflegacy_int.cpp', 'test_bmfflayout_int.cpp', 'test_bmffimage_int.cpp', 'test_bmpimage.cpp', diff --git a/unitTests/test_bmffbox_int.cpp b/unitTests/test_bmffbox_int.cpp index e75c7140f6..d052aed8db 100644 --- a/unitTests/test_bmffbox_int.cpp +++ b/unitTests/test_bmffbox_int.cpp @@ -169,6 +169,35 @@ TEST(BmffBoxReader, traversesNonImageBoxesWithoutInterpretingOpaquePayloads) { EXPECT_NO_THROW(input.finish()); } +// Counted tables may consume a prefix of siblings and resume at the next header. +TEST(BmffBoxReader, visitsCountedSiblingsWithoutConsumingTheRemainder) { + auto bytes = box(bmffType("one ")); + append(bytes, box(bmffType("two "))); + MemIo io(bytes.data(), bytes.size()); + BmffReader reader(io, testLimits); + auto input = reader.cursor({0, reader.fileSize()}); + std::vector types; + auto collect = [&](const BmffBox& current, BmffCursor&) { types.push_back(current.type); }; + + reader.visit(input, 0, collect, 0); + EXPECT_EQ(input.position(), 0u); + reader.visit(input, 0, collect, 1); + EXPECT_EQ(input.position(), 8u); + EXPECT_EQ(types, (std::vector{bmffType("one ")})); + reader.visit(input, 0, collect, 5); + + EXPECT_EQ(types, (std::vector{bmffType("one "), bmffType("two ")})); + EXPECT_NO_THROW(input.finish()); +} + +// Shared prefix decoding retains all bits so each adapter can apply its own policy. +TEST(BmffBoxReader, decodesFullBoxVersionAndFlagsWithoutValidation) { + const auto full = decodeBmffFullBox(0xab123456); + EXPECT_EQ(full.version, 0xabu); + EXPECT_EQ(full.flags, 0x123456u); + EXPECT_EQ(decodeBmffFullBox(0xffffffff).flags, 0xffffffu); +} + // Empty sibling ranges require neither header reads nor a minimum box count. TEST(BmffBoxReader, acceptsAnEmptyRangeWithZeroBudgets) { MemIo io; diff --git a/unitTests/test_bmfflegacy_int.cpp b/unitTests/test_bmfflegacy_int.cpp new file mode 100644 index 0000000000..9385a71c06 --- /dev/null +++ b/unitTests/test_bmfflegacy_int.cpp @@ -0,0 +1,432 @@ +// SPDX-License-Identifier: GPL-2.0-or-later + +#include + +#ifdef EXV_ENABLE_BMFF + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +using namespace Exiv2; + +namespace { +using Bytes = std::vector; +const Bytes canonUuid{0x85, 0xc0, 0xb6, 0x87, 0x82, 0x0f, 0x11, 0xe0, 0x81, 0x11, 0xf4, 0xce, 0x46, 0x2b, 0x6a, 0x48}; +const Bytes previewUuid{0xea, 0xf4, 0x2b, 0x5e, 0x1c, 0x98, 0x4b, 0x88, 0xb9, 0xfb, 0xb7, 0xdc, 0x40, 0x6e, 0x4d, 0x16}; + +// Encode fixture fields independently of the shared parser. +void integer(Bytes& bytes, uint64_t value, unsigned width) { + for (unsigned i = width; i != 0; --i) + bytes.push_back(static_cast(value >> ((i - 1) * 8))); +} + +// Concatenate source bytes without interpreting child boxes or packet contents. +void append(Bytes& bytes, const Bytes& suffix) { + bytes.insert(bytes.end(), suffix.begin(), suffix.end()); +} + +// Construct ordinary, extended or EOF-sized boxes for compatibility fixtures. +Bytes box(std::string_view type, const Bytes& payload = {}, bool extended = false, bool terminal = false) { + Bytes bytes; + integer(bytes, terminal ? 0 : extended ? 1 : payload.size() + 8, 4); + bytes.insert(bytes.end(), type.begin(), type.end()); + if (extended) + integer(bytes, payload.size() + 16, 8); + append(bytes, payload); + return bytes; +} + +// Give the legacy probe a brand without requiring HEIF item-model admission. +Bytes file(std::string_view brand = "avif") { + Bytes payload(brand.begin(), brand.end()); + append(payload, Bytes(4)); + payload.insert(payload.end(), brand.begin(), brand.end()); + return box("ftyp", payload); +} + +// Open a read-only legacy view that borrows fixture storage until destruction. +std::unique_ptr legacy(const Bytes& bytes, size_t depth = 100) { + return std::make_unique(std::make_unique(bytes.data(), bytes.size()), + ImageCtorParams(false, depth)); +} + +// Assert the precise error so hardening does not hide unrelated parsing failures. +template +void expectError(ErrorCode expected, Operation operation) { + try { + operation(); + FAIL() << "Expected an Exiv2::Error"; + } catch (const Error& error) { + EXPECT_EQ(error.code(), expected); + } +} + +// Build a minimal little-endian TIFF with one out-of-line Artist value. +Bytes artistTiff(std::string_view artist) { + Bytes bytes{'I', 'I', 42, 0, 8, 0, 0, 0, 1, 0, 0x3b, 1, 2, 0}; + const auto size = static_cast(artist.size() + 1); + for (unsigned i = 0; i < 4; ++i) + bytes.push_back(static_cast(size >> (i * 8))); + append(bytes, {26, 0, 0, 0, 0, 0, 0, 0}); + bytes.insert(bytes.end(), artist.begin(), artist.end()); + bytes.push_back(0); + return bytes; +} + +// Encode disjoint and overlapping properties to check the legacy XML replacement order. +Bytes packet(std::string_view label, bool extra) { + const auto xml = std::string( + "" + ""; + return Bytes(xml.begin(), xml.end()); +} + +// Inject one short underlying read without changing declared file boundaries. +class ShortReadIo : public MemIo { + public: + using MemIo::read; + + // Borrow source bytes and select the absolute read position to fail. + ShortReadIo(const Bytes& bytes, size_t offset) : MemIo(bytes.data(), bytes.size()), offset_(offset) { + } + + //! @brief Return one byte fewer only at the selected header or payload read. + size_t read(byte* output, size_t count) override { + if (tell() == offset_ && count != 0) { + injected = true; + return MemIo::read(output, count - 1); + } + return MemIo::read(output, count); + } + + bool injected{}; + + private: + size_t offset_; +}; + +// Signal seek or stream errors after otherwise successful positioning or reading. +class ErrorIo : public MemIo { + public: + using MemIo::read; + + // Borrow the fixture and select which underlying failure to expose. + ErrorIo(const Bytes& bytes, bool seekFailure) : MemIo(bytes.data(), bytes.size()), seekFailure_(seekFailure) { + } + + //! @brief Let the seek reach its target while reporting a failure the reader must honor. + int seek(int64_t offset, Position origin) override { + const auto result = MemIo::seek(offset, origin); + if (seekFailure_ && offset == 28 && origin == beg) { + injected = true; + return 1; + } + return result; + } + + //! @brief Signal a stream error after returning a complete opaque payload. + size_t read(byte* output, size_t count) override { + if (!seekFailure_ && tell() == 28) + injected = true; + return MemIo::read(output, count); + } + + //! @brief Preserve the injected stream error until the read is rejected. + int error() const override { + return !seekFailure_ && injected ? 1 : MemIo::error(); + } + + bool injected{}; + + private: + bool seekFailure_; +}; + +// Represent a large mdat without allocating or serving its opaque image bytes. +class SparseLegacyIo : public MemIo { + public: + using MemIo::read; + static constexpr uint64_t tailOffset = (uint64_t{1} << 33) + 20; + + // Store only the file type, extended mdat header, and final free box. + SparseLegacyIo() : prefix_(file()), tail_(box("free")) { + integer(prefix_, 1, 4); + append(prefix_, {'m', 'd', 'a', 't'}); + integer(prefix_, tailOffset - 20, 8); + } + + //! @brief Rewind the virtual input when BmffImage opens it. + int open() override { + position_ = 0; + return 0; + } + + //! @brief Expose the virtual file length without materializing the media payload. + size_t size() const override { + return static_cast(tailOffset + tail_.size()); + } + + //! @brief Report the absolute position used by legacy preview and traversal code. + size_t tell() const override { + return static_cast(position_); + } + + //! @brief Permit only absolute seeks within the synthetic file. + int seek(int64_t offset, Position origin) override { + if (origin != beg || offset < 0 || static_cast(offset) > size()) + return 1; + position_ = static_cast(offset); + return 0; + } + + //! @brief Serve stored headers and detect any accidental media-payload access. + size_t read(byte* output, size_t count) override { + const auto& region = position_ >= tailOffset ? tail_ : prefix_; + const auto relative = position_ >= tailOffset ? position_ - tailOffset : position_; + if (relative > region.size() || count > region.size() - relative) { + forbiddenRead = true; + return 0; + } + std::copy_n(region.begin() + relative, count, output); + position_ += count; + return count; + } + + bool forbiddenRead{}; + + private: + Bytes prefix_; + Bytes tail_; + uint64_t position_{}; +}; +} // namespace + +// Unknown payloads stay opaque and structure output retains original encoded size fields. +TEST(BmffLegacy, retainsExtendedTerminalAndOpaqueStructure) { + auto bytes = file(); + append(bytes, box("skip", {0xff, 0xff, 0xff}, true)); + append(bytes, box("moov", box("free", {}, false, true))); + auto image = legacy(bytes); + ASSERT_NO_THROW(image->readMetadata()); + EXPECT_EQ(image->mimeType(), "image/avif"); + + for (const auto mode : {kpsBasic, kpsRecursive}) { + std::ostringstream output; + image->printStructure(output, mode, 0); + EXPECT_EQ(output.str(), + "Exiv2::BmffImage::boxHandler: ftyp 0->20 brand: avif\n" + "Exiv2::BmffImage::boxHandler: skip 20->1 \n" + "Exiv2::BmffImage::boxHandler: moov 39->16 \n" + " Exiv2::BmffImage::boxHandler: free 47->0 \n"); + } +} + +// Counted iinf traversal keeps the legacy 16-bit count and ignores unclaimed trailing bytes. +TEST(BmffLegacy, retainsCountedInfoCompatibility) { + for (const byte version : {0, 1}) { + Bytes info{version, 0, 0, 0, 0, 1}; + append(info, box("free")); + append(info, {0xff}); + auto bytes = file(); + append(bytes, box("iinf", info)); + auto image = legacy(bytes); + EXPECT_NO_THROW(image->readMetadata()); + } +} + +// A count that claims a missing entry remains corruption, rather than an empty table. +TEST(BmffLegacy, rejectsMissingCountedEntry) { + auto bytes = file(); + append(bytes, box("iinf", {0, 0, 0, 0, 0, 1})); + auto image = legacy(bytes); + expectError(ErrorCode::kerCorruptedMetadata, [&] { image->readMetadata(); }); +} + +// Canon containers retain TIFF interpretation, preview origins, and repeated-read behavior. +TEST(BmffLegacy, readsCanonMetadataAndPrefixedPreviews) { + for (const bool extended : {false, true}) { + auto bytes = file("crx "); + auto metadata = canonUuid; + append(metadata, box("CMT1", artistTiff("Canon artist"))); + append(bytes, box("uuid", metadata, extended)); + + auto previews = previewUuid; + append(previews, Bytes(8)); + const Bytes preview{0, 0, 0, 0, 0, 0, 0, 30, 0, 20, 0, 0, 0, 0, 0, 4, 0xff, 0xd8, 0xff, 0xd9}; + append(previews, box("PRVW", preview)); + const auto previewPosition = bytes.size() + (extended ? 32 : 24) + 8 + 8 + 16; + append(bytes, box("uuid", previews, extended)); + auto image = legacy(bytes); + + for (unsigned read = 0; read < 2; ++read) { + ASSERT_NO_THROW(image->readMetadata()); + EXPECT_EQ(image->mimeType(), "image/x-canon-cr3"); + EXPECT_EQ(image->exifData()["Exif.Image.Artist"].toString(), "Canon artist"); + ASSERT_EQ(image->nativePreviews().size(), read + 1); + const auto& actual = image->nativePreviews().back(); + EXPECT_EQ(actual.position_, previewPosition); + EXPECT_EQ(actual.size_, 4u); + EXPECT_EQ(actual.width_, 30u); + EXPECT_EQ(actual.height_, 20u); + EXPECT_EQ(actual.mimeType_, "image/jpeg"); + } + } +} + +// Last XML and ICC boxes retain legacy precedence without accumulating structured XMP. +TEST(BmffLegacy, retainsDuplicateMetadataAndProfilePrecedence) { + auto bytes = box("JXL ", {13, 10, 135, 10}); + append(bytes, file("jxl ")); + append(bytes, box("xml ", packet("first", true))); + append(bytes, box("xml ", packet("last", false))); + Bytes expected; + for (const byte marker : {1, 2}) { + Bytes profile(128); + profile[3] = 128; + profile.back() = marker; + Bytes colour{'p', 'r', 'o', 'f'}; + append(colour, profile); + append(bytes, box("colr", colour)); + expected = profile; + } + auto image = legacy(bytes); + + for (unsigned read = 0; read < 2; ++read) { + ASSERT_NO_THROW(image->readMetadata()); + EXPECT_EQ(image->mimeType(), "image/jxl"); + ASSERT_EQ(image->iccProfile().size(), expected.size()); + EXPECT_EQ(std::memcmp(image->iccProfile().c_data(), expected.data(), expected.size()), 0); +#ifdef EXV_HAVE_XMP_TOOLKIT + EXPECT_EQ(image->xmpData()["Xmp.xmp.Label"].toString(), "last"); + EXPECT_EQ(image->xmpData().findKey(XmpKey("Xmp.xmp.Nickname")), image->xmpData().end()); +#else + EXPECT_TRUE(image->xmpData().empty()); +#endif + } +} + +// Compressed JPEG XL metadata follows the same feature gates and box order as before migration. +TEST(BmffLegacy, preservesOptionalBrotliMetadataReading) { + // Fixed Brotli streams contain an Artist TIFF and an XMP Label packet; no encoder is needed at runtime. + const Bytes exif{0x45, 0x78, 0x69, 0x66, 0x8b, 0x15, 0x80, 0x00, 0x00, 0x00, 0x00, 0x49, 0x49, + 0x2a, 0x00, 0x08, 0x00, 0x00, 0x00, 0x01, 0x00, 0x3b, 0x01, 0x02, 0x00, 0x0e, + 0x00, 0x00, 0x00, 0x1a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x42, 0x72, + 0x6f, 0x74, 0x6c, 0x69, 0x20, 0x61, 0x72, 0x74, 0x69, 0x73, 0x74, 0x00, 0x03}; + const Bytes xmp{0x78, 0x6d, 0x6c, 0x20, 0x1b, 0xd9, 0x00, 0x00, 0x64, 0x74, 0x5b, 0xaa, 0xe0, 0xe9, 0x1a, 0x35, + 0x31, 0x12, 0x89, 0xd0, 0xae, 0xc9, 0x10, 0xb5, 0xd9, 0xa1, 0x16, 0x00, 0x67, 0x81, 0x04, 0xb7, + 0xd5, 0x16, 0x68, 0x4b, 0xa2, 0xb6, 0x27, 0x7a, 0x83, 0xf4, 0x86, 0xcf, 0xc3, 0x9a, 0x4d, 0x3e, + 0x29, 0x45, 0x7c, 0xec, 0x4b, 0xdb, 0x85, 0xc6, 0xfe, 0x15, 0x15, 0x9f, 0x1c, 0xe7, 0x35, 0x59, + 0x3e, 0x59, 0xea, 0x42, 0xa3, 0x12, 0x87, 0x0b, 0x6c, 0x9d, 0x66, 0xd4, 0x77, 0xb8, 0x20, 0xc7, + 0xe0, 0xb5, 0x48, 0x60, 0x98, 0x22, 0x4a, 0xc1, 0x05, 0xce, 0x3f, 0x5f, 0xfa, 0x03, 0xf9, 0x6c, + 0x49, 0xb6, 0x41, 0xad, 0x62, 0xa2, 0xd0, 0xe5, 0x38, 0xd6, 0xb6, 0xb4, 0x31, 0x23, 0x9f, 0x50, + 0x87, 0x74, 0x76, 0x7c, 0x7a, 0x43, 0x04, 0x62, 0x04, 0xa6, 0x1b, 0x5b, 0xb4, 0xf1, 0x11, 0xb6, + 0xa4, 0x7e, 0x74, 0xef, 0x46, 0xa4, 0x04, 0x12, 0x19, 0x4a, 0x20, 0x4b, 0xaa, 0x00}; + auto bytes = box("JXL ", {13, 10, 135, 10}); + append(bytes, file("jxl ")); + append(bytes, box("brob", exif)); + append(bytes, box("brob", xmp)); + auto image = legacy(bytes); + + ASSERT_NO_THROW(image->readMetadata()); + EXPECT_EQ(image->mimeType(), "image/jxl"); +#ifdef EXV_HAVE_BROTLI + EXPECT_EQ(image->exifData()["Exif.Image.Artist"].toString(), "Brotli artist"); +#ifdef EXV_HAVE_XMP_TOOLKIT + EXPECT_EQ(image->xmpData()["Xmp.xmp.Label"].toString(), "compressed"); +#else + EXPECT_TRUE(image->xmpData().empty()); +#endif +#else + EXPECT_TRUE(image->exifData().empty()); + EXPECT_TRUE(image->xmpData().empty()); +#endif +} + +// Legacy depth limits belong to the adapter; the shared reader must not import HEIF budgets. +TEST(BmffLegacy, preservesDepthLimitsAndSkipsLargeMediaRanges) { + auto bytes = file(); + append(bytes, box("moov", box("free"))); + auto shallow = legacy(bytes, 1); + expectError(ErrorCode::kerCorruptedMetadata, [&] { shallow->readMetadata(); }); + auto deep = legacy(bytes, 2); + EXPECT_NO_THROW(deep->readMetadata()); + + if (sizeof(size_t) < 8) + GTEST_SKIP() << "BasicIo cannot represent the sparse 8 GiB input on this host"; + auto io = std::make_unique(); + const auto* probe = io.get(); + BmffImage large(std::move(io), ImageCtorParams(false, 100)); + EXPECT_NO_THROW(large.readMetadata()); + EXPECT_FALSE(probe->forbiddenRead); + EXPECT_EQ(large.mimeType(), "image/avif"); +} + +// A size-zero nested box cannot terminate at a parent boundary before the actual EOF. +TEST(BmffLegacyHardening, rejectsNestedTerminalBoxBeforeEof) { + auto bytes = file(); + append(bytes, box("moov", box("free", {}, false, true))); + append(bytes, box("free", Bytes(24))); + auto image = legacy(bytes); + expectError(ErrorCode::kerCorruptedMetadata, [&] { image->readMetadata(); }); +} + +// UUID headers must own their complete user type instead of borrowing bytes from a sibling. +TEST(BmffLegacyHardening, rejectsUuidSmallerThanItsUserType) { + for (const bool extended : {false, true}) { + auto bytes = file(); + append(bytes, box("uuid", {}, extended)); + append(bytes, box("free", Bytes(32))); + auto image = legacy(bytes); + expectError(ErrorCode::kerCorruptedMetadata, [&] { image->readMetadata(); }); + } +} + +// Canon's preview prefix must fit inside its UUID box before child traversal can begin. +TEST(BmffLegacyHardening, rejectsTruncatedCanonPreviewPrefix) { + auto bytes = file("crx "); + append(bytes, box("uuid", previewUuid)); + append(bytes, box("free", Bytes(24))); + auto image = legacy(bytes); + expectError(ErrorCode::kerCorruptedMetadata, [&] { image->readMetadata(); }); +} + +// Underlying short reads must not silently discard a subtree or use zero-filled payload bytes. +TEST(BmffLegacyHardening, rejectsShortHeaderAndPayloadReads) { + for (const size_t offset : {20u, 28u}) { + auto bytes = file(); + append(bytes, box("free", Bytes(32))); + auto io = std::make_unique(bytes, offset); + const auto* probe = io.get(); + BmffImage image(std::move(io), ImageCtorParams(false, 100)); + + expectError(ErrorCode::kerInputDataReadFailed, [&] { image.readMetadata(); }); + EXPECT_TRUE(probe->injected); + } +} + +// Failed seeks and stream errors cannot be ignored merely because bytes remain readable. +TEST(BmffLegacyHardening, rejectsFailedSeekAndStreamError) { + for (const bool seekFailure : {false, true}) { + auto bytes = file(); + append(bytes, box("free", Bytes(32))); + auto io = std::make_unique(bytes, seekFailure); + const auto* probe = io.get(); + BmffImage image(std::move(io), ImageCtorParams(false, 100)); + + expectError(ErrorCode::kerInputDataReadFailed, [&] { image.readMetadata(); }); + EXPECT_TRUE(probe->injected); + } +} + +#endif // EXV_ENABLE_BMFF From cc9b899d20b732c50505edd4f55f935e245ae457 Mon Sep 17 00:00:00 2001 From: Vaclav Haisman Date: Sat, 10 Oct 2026 14:07:55 +0200 Subject: [PATCH 32/40] [bmff] Document internal layers and ownership contracts Describe shared box, item and output mechanics and their format adapters. Link the internal guide from the focused testing documentation. --- src/README-BMFF.md | 93 +++++++++++++++++++++++++++++++++++++++++++ tests/README-TESTS.md | 2 + 2 files changed, 95 insertions(+) create mode 100644 src/README-BMFF.md diff --git a/src/README-BMFF.md b/src/README-BMFF.md new file mode 100644 index 0000000000..e2fa10b93b --- /dev/null +++ b/src/README-BMFF.md @@ -0,0 +1,93 @@ +# 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. | +| `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. + +## 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`. +The legacy hardening tests separately cover malformed container/UUID boundaries +and underlying I/O failures. diff --git a/tests/README-TESTS.md b/tests/README-TESTS.md index 02dc9d1496..98ff553ece 100644 --- a/tests/README-TESTS.md +++ b/tests/README-TESTS.md @@ -97,6 +97,8 @@ cmake --build build-heif-debug --parallel 4 The unit filter includes the parameterized corpus tests. The CLI regressions cover metadata extraction/reinsertion, MakerNote removal, rejected writes, and staging/transfer-open failures, using disposable fixture copies. +See the [BMFF internal layers](../src/README-BMFF.md) for the shared reader, +item model, output engine and format-adapter boundaries covered by these tests. Use a separate build to check raw XMP handling without either XMP toolkit: From 9a8b9593d27bad89fa11012169991b2f69ca2443 Mon Sep 17 00:00:00 2001 From: Vaclav Haisman Date: Sat, 31 Oct 2026 10:32:16 +0100 Subject: [PATCH 33/40] [bmff] Avoid GCC bounds warnings in TIFF test fixtures Resolve the source buffer range before taking the destination end iterator. This avoids GCC 15 bounds warnings caused by argument evaluation order in the two failing vector insertions. --- unitTests/test_bmffimage_int.cpp | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/unitTests/test_bmffimage_int.cpp b/unitTests/test_bmffimage_int.cpp index 153911af79..e0af3bb48c 100644 --- a/unitTests/test_bmffimage_int.cpp +++ b/unitTests/test_bmffimage_int.cpp @@ -1711,7 +1711,9 @@ Bytes tiffItem(ExifData exif, const XmpData& xmp = {}, ByteOrder order = littleE TiffParser::encode(output, nullptr, 0, order, exif, IptcData{}, xmp); Bytes bytes(4, 0); - bytes.insert(bytes.end(), output.mmap(), output.mmap() + output.size()); + const auto* first = output.mmap(); + const auto* last = first + output.size(); + bytes.insert(bytes.end(), first, last); return bytes; } @@ -2630,7 +2632,9 @@ TEST(HeifImage, preservesEmbeddedIptcAndThumbnailDataOnExifEdits) { TiffParser::encode(output, nullptr, 0, littleEndian, exif, iptc, XmpData{}); HeifMetadataUpdate update; update.exif = Bytes(4, 0); - update.exif->insert(update.exif->end(), output.mmap(), output.mmap() + output.size()); + const auto* first = output.mmap(); + const auto* last = first + output.size(); + update.exif->insert(update.exif->end(), first, last); auto image = openHeif(rewritten(heifWithMetadata(), update)); image->exifData()["Exif.Image.Artist"] = "new"; From 4af5c57473cf9dafb6027766d23814b0835350c3 Mon Sep 17 00:00:00 2001 From: Vaclav Haisman Date: Sat, 31 Oct 2026 10:44:38 +0100 Subject: [PATCH 34/40] [bmff] Use checked access at CodeQL-reported locations Replace the nine annotated subscript expressions with at(), preserving the existing bounds guards and unflagged accesses. --- src/bmffbox_int.cpp | 2 +- src/heifwrite_int.cpp | 16 ++++++++-------- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/src/bmffbox_int.cpp b/src/bmffbox_int.cpp index 9413d55f7f..b55c49ba63 100644 --- a/src/bmffbox_int.cpp +++ b/src/bmffbox_int.cpp @@ -54,7 +54,7 @@ uint64_t BmffCursor::number(unsigned width) { uint64_t result = 0; for (unsigned i = 0; i < width; ++i) - result = (result << 8) | bytes[i]; + result = (result << 8) | bytes.at(i); return result; } diff --git a/src/heifwrite_int.cpp b/src/heifwrite_int.cpp index 09322ac8ba..2762b17702 100644 --- a/src/heifwrite_int.cpp +++ b/src/heifwrite_int.cpp @@ -194,7 +194,7 @@ class Rewrite : public BmffItemLayoutBuilder { for (const auto span : discarded) { while (next < retained.size() && end(retained[next]) <= span.offset) ++next; - supported(next == retained.size() || retained[next].offset >= end(span), + supported(next == retained.size() || retained.at(next).offset >= end(span), "removed metadata overlaps a retained item"); } } @@ -453,8 +453,8 @@ class Rewrite : public BmffItemLayoutBuilder { actual.location.dataSize == expected.dataSize && actual.location.extents.size() == expected.extents.size()); for (size_t i = 0; i < expected.extents.size(); ++i) { - const auto& a = actual.location.extents[i]; - const auto& e = expected.extents[i]; + const auto& a = actual.location.extents.at(i); + const auto& e = expected.extents.at(i); require(a.index == e.index && a.offset == e.offset && a.length == e.length); } } @@ -464,20 +464,20 @@ class Rewrite : public BmffItemLayoutBuilder { parsed.meta.associations.size() == document_.meta.associations.size() && parsed.meta.properties.size() == document_.meta.properties.size()); for (size_t i = 0; i < document_.meta.references.size(); ++i) { - const auto& a = parsed.meta.references[i]; + const auto& a = parsed.meta.references.at(i); const auto& e = document_.meta.references[i]; require(a.type == e.type && a.from == e.from && a.to == e.to); } for (size_t i = 0; i < document_.meta.associations.size(); ++i) { - const auto& a = parsed.meta.associations[i]; + const auto& a = parsed.meta.associations.at(i); const auto& e = document_.meta.associations[i]; require(a.itemId == e.itemId && a.properties.size() == e.properties.size()); for (size_t j = 0; j < a.properties.size(); ++j) - require(a.properties[j].index == e.properties[j].index && - a.properties[j].essential == e.properties[j].essential); + require(a.properties[j].index == e.properties.at(j).index && + a.properties[j].essential == e.properties.at(j).essential); } for (size_t i = 0; i < document_.meta.properties.size(); ++i) - require(parsed.meta.properties[i].type == document_.meta.properties[i].type); + require(parsed.meta.properties.at(i).type == document_.meta.properties[i].type); // Structural agreement alone is insufficient; verify every copied or generated byte. verifyBmffLayout(input_, output_, boxes); From 9c08599d1333031dcf6831ead4260d74f8bd81d2 Mon Sep 17 00:00:00 2001 From: Vaclav Haisman Date: Sat, 31 Oct 2026 17:01:32 +0100 Subject: [PATCH 35/40] [bmff] Fix MSVC HEIF test failures Separate embedded XMP decoding from error enforcement to avoid incorrect argument passing in MSVC x86 Debug builds. Normalize CRLF output in the HEIF CLI test helper. Validated with MSVC 19.44 x86 Debug: 518 unit tests passed with five expected skips; three HEIF CLI tests passed with one expected POSIX-only skip. --- src/heifimage_int.cpp | 4 ++-- tests/bugfixes/github/test_issue_2349_heif_write.py | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/heifimage_int.cpp b/src/heifimage_int.cpp index 9aae4f3aa0..fded63e9a9 100644 --- a/src/heifimage_int.cpp +++ b/src/heifimage_int.cpp @@ -770,8 +770,8 @@ class HeifImage final : public BmffImage { supported(xml->size() <= heifMetadataLimit, "embedded XMP exceeds the allocation limit"); Bytes bytes(xml->size()); xml->copy(bytes.data(), original.order); - enforce(XmpParser::decode(embedded, std::string(bytes.begin(), bytes.end()), params) == 0, - ErrorCode::kerInvalidXMP); + const auto result = XmpParser::decode(embedded, std::string(bytes.begin(), bytes.end()), params); + enforce(result == 0, ErrorCode::kerInvalidXMP); } } #endif diff --git a/tests/bugfixes/github/test_issue_2349_heif_write.py b/tests/bugfixes/github/test_issue_2349_heif_write.py index 25b7370151..019fc8e92d 100644 --- a/tests/bugfixes/github/test_issue_2349_heif_write.py +++ b/tests/bugfixes/github/test_issue_2349_heif_write.py @@ -36,7 +36,7 @@ def run_exiv2(self, *args, success=True): self.assertEqual(result.returncode, 0, result.stderr.decode(errors="replace")) else: self.assertNotEqual(result.returncode, 0) - return result.stdout + return result.stdout.replace(b"\r\n", b"\n") # Extract metadata, clear its physical storage, and insert it back from the sidecar. @unittest.skipUnless(system_tests.BT.verbose_version().get("have_xmptoolkit") == "1", From 3c934b4e37925a3b46e0f2de51339bfc026e19d9 Mon Sep 17 00:00:00 2001 From: Vaclav Haisman Date: Sat, 31 Oct 2026 14:56:15 +0100 Subject: [PATCH 36/40] Raise the minimum supported GCC version to 10 (cherry picked from commit 168993b98af5c931cad68686b7a409898d6c4c8f) --- .github/workflows/on_PR_meson.yaml | 2 +- README.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/on_PR_meson.yaml b/.github/workflows/on_PR_meson.yaml index c586f251ab..1ad6d72b03 100644 --- a/.github/workflows/on_PR_meson.yaml +++ b/.github/workflows/on_PR_meson.yaml @@ -15,7 +15,7 @@ jobs: name: Linux-GCC${{matrix.cxx}}-deps=${{matrix.deps}} strategy: matrix: - cxx: ['9', '16'] + cxx: ['10', '16'] deps: ['enabled', 'disabled'] steps: - uses: actions/checkout@v7 diff --git a/README.md b/README.md index 947d2064d7..3a54afd89f 100644 --- a/README.md +++ b/README.md @@ -74,7 +74,7 @@ The file ReadMe.txt in a build bundle describes how to install the library on th # Building, Installing, Using and Uninstalling Exiv2 -You need [CMake](https://cmake.org/download/) to configure the Exiv2 project, any C++ compiler implementing the C++ 20 standard and the associated tool chain. +You need [CMake](https://cmake.org/download/) to configure the Exiv2 project, any C++ compiler implementing the C++ 20 standard and the associated tool chain. When building with GCC, version 10 or newer is required.
From e4585d5042c286ea7a5ec2ee04ead0f0d67ad94a Mon Sep 17 00:00:00 2001 From: Vaclav Haisman Date: Sat, 31 Oct 2026 18:09:08 +0100 Subject: [PATCH 37/40] [tests] Respect filesystem permissions in HEIF failure tests Probe whether directory and file write restrictions are enforced before testing those failure paths. Split the checks so an unsupported staging restriction does not skip destination-open coverage. Validated the original false failure and corrected permission checks with the local CLI; the HEIF regression file passes with expected platform skips. --- .../github/test_issue_2349_heif_write.py | 31 +++++++++++++++++-- 1 file changed, 28 insertions(+), 3 deletions(-) diff --git a/tests/bugfixes/github/test_issue_2349_heif_write.py b/tests/bugfixes/github/test_issue_2349_heif_write.py index 019fc8e92d..1a6c299772 100644 --- a/tests/bugfixes/github/test_issue_2349_heif_write.py +++ b/tests/bugfixes/github/test_issue_2349_heif_write.py @@ -101,24 +101,49 @@ def test_read_only_fields_and_formats_do_not_change_source(self): self.assertEqual(hashlib.sha256(target.read_bytes()).digest(), before) self.assertFalse(list(self.root.glob(".exiv2-heif-*"))) - # Verify staging and destination-open failures preserve the source and clean temporary files. + # Verify staging failures preserve the source and clean temporary files. @unittest.skipUnless(os.name == "posix" and getattr(os, "geteuid", lambda: 0)() != 0, "requires an unprivileged POSIX process") - def test_staging_and_destination_open_failures_preserve_source(self): + def test_staging_failure_preserves_source(self): target = self.copy("Stonehenge.heic") before = target.read_bytes() # Prevent staging-file creation by making the containing directory read-only. self.root.chmod(0o500) try: + try: + with (self.root / "permission-probe").open("xb"): + pass + except PermissionError: + pass + else: + self.skipTest("filesystem does not enforce read-only directory permissions") + self.run_exiv2("-M", "set Exif.Image.Artist pending", target, success=False) self.assertEqual(target.read_bytes(), before) finally: self.root.chmod(0o700) - # Allow staging again but prevent the final destination from opening for writing. + self.assertFalse(list(self.root.glob(".exiv2-heif-*"))) + + # Verify destination-open failures preserve the source and clean temporary files. + @unittest.skipUnless(os.name == "posix" and getattr(os, "geteuid", lambda: 0)() != 0, + "requires an unprivileged POSIX process") + def test_destination_open_failure_preserves_source(self): + target = self.copy("Stonehenge.heic") + before = target.read_bytes() + + # Prevent the final destination from opening for writing. target.chmod(0o400) try: + try: + with target.open("r+b"): + pass + except PermissionError: + pass + else: + self.skipTest("filesystem does not enforce read-only file permissions") + self.run_exiv2("-M", "set Exif.Image.Artist pending", target, success=False) self.assertEqual(target.read_bytes(), before) finally: From c649dfaf9d605707c198acd49510a3e2f52322a9 Mon Sep 17 00:00:00 2001 From: Vaclav Haisman Date: Sat, 31 Oct 2026 16:39:13 +0100 Subject: [PATCH 38/40] Allow more time for Meson unit tests on slow CI runners Give the full unit-test executable a bounded 120-second timeout. In PR #9531, macOS sanitizer and FreeBSD VM jobs passed the large Exif boundary cases but exhausted Meson's 30-second default during later XMP concurrency tests. Retain every test and assertion. Validated the registered timeout change and unchanged limits for other test groups. All 400 unit tests passed on MSVC x86 Debug forcefallback, including the 35 focused JPEG/EXV tests. Native platform checks await CI. (cherry picked from commit 1ef5e0562fa0028fa97b8ae7fe15caa728cab1c8) --- unitTests/meson.build | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/unitTests/meson.build b/unitTests/meson.build index f7cb8ffd81..54c4e88bb2 100644 --- a/unitTests/meson.build +++ b/unitTests/meson.build @@ -68,4 +68,6 @@ unit_tests = executable( include_directories: exiv2inc, ) -test('Unit Tests', unit_tests) +# Allow headroom for large Exif fixtures and XMP concurrency tests under +# sanitizers and on slower CI VMs. +test('Unit Tests', unit_tests, timeout: 120) From 4d9b7ed0a912a1e23e8718f5b8dbcc1f544e8b38 Mon Sep 17 00:00:00 2001 From: Vaclav Haisman Date: Sun, 18 Oct 2026 20:08:34 +0200 Subject: [PATCH 39/40] [cr3] Extract full-resolution JPEG previews Resolve single-sample BMFF tables and Canon CRAW/JPEG descriptions through the shared box reader. Expose the embedded JPEG alongside THMB/PRVW using the existing native preview API. Rebuild CR3 preview state on metadata reads and keep structure printing from accumulating duplicate entries. Fixes #2854. --- src/CMakeLists.txt | 4 + src/README-BMFF.md | 24 + src/bmffimage.cpp | 26 ++ src/bmffsample_int.cpp | 90 ++++ src/bmffsample_int.hpp | 36 ++ src/cr3preview_int.cpp | 200 +++++++++ src/cr3preview_int.hpp | 33 ++ src/meson.build | 2 + tests/bugfixes/github/test_issue_1893.py | 5 +- tests/bugfixes/github/test_issue_2854.py | 86 ++++ unitTests/CMakeLists.txt | 1 + unitTests/meson.build | 1 + unitTests/test_bmfflegacy_int.cpp | 4 +- unitTests/test_cr3preview_int.cpp | 544 +++++++++++++++++++++++ 14 files changed, 1053 insertions(+), 3 deletions(-) create mode 100644 src/bmffsample_int.cpp create mode 100644 src/bmffsample_int.hpp create mode 100644 src/cr3preview_int.cpp create mode 100644 src/cr3preview_int.hpp create mode 100644 tests/bugfixes/github/test_issue_2854.py create mode 100644 unitTests/test_cr3preview_int.cpp diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index c70e296ce6..b85361b283 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -6,6 +6,10 @@ 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 diff --git a/src/README-BMFF.md b/src/README-BMFF.md index e2fa10b93b..2100925553 100644 --- a/src/README-BMFF.md +++ b/src/README-BMFF.md @@ -10,6 +10,8 @@ read-only. QuickTime and JPEG 2000 use their existing readers. | 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. | @@ -54,6 +56,25 @@ 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 @@ -89,5 +110,8 @@ 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/bmffimage.cpp b/src/bmffimage.cpp index 40ea49b9a6..df4ed3e213 100644 --- a/src/bmffimage.cpp +++ b/src/bmffimage.cpp @@ -6,6 +6,7 @@ #include "basicio.hpp" #include "bmffbox_int.hpp" #include "config.h" +#include "cr3preview_int.hpp" #include "enforce.hpp" #include "error.hpp" #include "futils.hpp" @@ -23,6 +24,7 @@ #endif // + standard includes +#include #include #include #include @@ -245,12 +247,27 @@ class BmffLegacyReader { //! @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); + } } //! @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}); @@ -279,6 +296,7 @@ class BmffLegacyReader { // 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(); @@ -331,6 +349,9 @@ class BmffLegacyReader { 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_); } @@ -595,10 +616,15 @@ class BmffLegacyReader { } 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); } BmffImage& image_; BmffReader reader_; + bool readingMetadata_{}; }; } // namespace Internal diff --git a/src/bmffsample_int.cpp b/src/bmffsample_int.cpp new file mode 100644 index 0000000000..2aa731f0f1 --- /dev/null +++ b/src/bmffsample_int.cpp @@ -0,0 +1,90 @@ +// SPDX-License-Identifier: GPL-2.0-or-later + +#include "bmffsample_int.hpp" + +#ifdef EXV_ENABLE_BMFF + +#include "enforce.hpp" +#include "error.hpp" + +namespace Exiv2::Internal { +namespace { + +// Require complete version-zero tables before interpreting their fixed-width entries. +BmffCursor fields(BmffReader& reader, const BmffBox& box) { + auto input = reader.cursor(box.payload()); + enforce(input.number(4) == 0, ErrorCode::kerCorruptedMetadata); + return input; +} + +// Reject truncated or trailing table entries without multiplying an untrusted count. +void entries(const BmffCursor& input, uint64_t count, unsigned width) { + enforce(input.remaining() % width == 0 && input.remaining() / width == count, ErrorCode::kerCorruptedMetadata); +} + +} // namespace + +std::optional readBmffSingleSample(BmffReader& reader, const BmffBox& table, unsigned depth) { + std::optional mapping; + std::optional sizes; + std::optional offsets; + bool compactSizes = false; + auto input = reader.cursor(table.payload()); + + // Only standard singleton tables are owned here; other child payloads remain opaque. + reader.visit(input, depth, [&](BmffBox& box, BmffCursor&) { + std::optional* target = nullptr; + if (box.type == bmffType("stsc")) + target = &mapping; + else if (box.type == bmffType("stsz")) + target = &sizes; + else if (box.type == bmffType("stco") || box.type == bmffType("co64")) + target = &offsets; + else if (box.type == bmffType("stz2")) + compactSizes = true; + + if (target) { + enforce(!target->has_value(), ErrorCode::kerCorruptedMetadata); + *target = box; + } + }); + if (!mapping || !sizes || !offsets || compactSizes) + return std::nullopt; + + // A still sample occupies exactly one chunk and uses its explicit description index. + auto map = fields(reader, *mapping); + const auto mapCount = map.number(4); + entries(map, mapCount, 12); + if (mapCount != 1) + return std::nullopt; + const auto firstChunk = map.number(4); + const auto samplesPerChunk = map.number(4); + const auto description = static_cast(map.number(4)); + if (firstChunk != 1 || samplesPerChunk != 1 || description == 0) + return std::nullopt; + + // stsz either repeats one fixed size or stores the singleton size out of line. + auto sizeFields = fields(reader, *sizes); + const auto fixedSize = sizeFields.number(4); + const auto sampleCount = sizeFields.number(4); + entries(sizeFields, fixedSize == 0 ? sampleCount : 0, 4); + if (sampleCount != 1) + return std::nullopt; + const auto size = fixedSize == 0 ? sizeFields.number(4) : fixedSize; + if (size == 0) + return std::nullopt; + + // Chunk offsets are file-relative, independently of the size of the box headers. + auto chunkFields = fields(reader, *offsets); + const auto chunkCount = chunkFields.number(4); + const unsigned width = offsets->type == bmffType("co64") ? 8 : 4; + entries(chunkFields, chunkCount, width); + if (chunkCount != 1) + return std::nullopt; + const BmffSpan range{chunkFields.number(width), size}; + (void)reader.cursor(range); + return BmffSingleSample{range, description}; +} + +} // namespace Exiv2::Internal +#endif // EXV_ENABLE_BMFF diff --git a/src/bmffsample_int.hpp b/src/bmffsample_int.hpp new file mode 100644 index 0000000000..050db879c8 --- /dev/null +++ b/src/bmffsample_int.hpp @@ -0,0 +1,36 @@ +// SPDX-License-Identifier: GPL-2.0-or-later + +#ifndef BMFFSAMPLE_INT_HPP +#define BMFFSAMPLE_INT_HPP + +#include "bmffbox_int.hpp" + +#ifdef EXV_ENABLE_BMFF + +namespace Exiv2::Internal { + +//! @brief One locally stored sample; the unchanged input retains ownership of its bytes. +struct BmffSingleSample { + BmffSpan data; //!< Absolute input range, validated against the input length. + uint32_t descriptionIndex{}; //!< One-based stsd index supplied by the sample-to-chunk entry. +}; + +/*! + @brief Resolve a single-sample, single-chunk standard sample table. + @param reader Reader borrowing the open, unchanged input; its budgets apply. + @param table Validated stbl box whose immediate tables are inspected. + @param depth Nesting depth of the table's immediate children. + @return The sample range and description index, or no value for missing or + unsupported tables, including multiple samples/chunks. + @throws Error For malformed/ambiguous supported tables, exhausted budgets, or I/O failure. + + Supports version-zero stsc/stsz and stco/co64, including a variable stsz entry. + No descriptions, codecs, brands or media ownership are interpreted here. The + caller validates the description and whether the range is in a media payload. + The stream position may change. No payload bytes are copied or retained. + */ +std::optional readBmffSingleSample(BmffReader& reader, const BmffBox& table, unsigned depth); + +} // namespace Exiv2::Internal +#endif // EXV_ENABLE_BMFF +#endif // BMFFSAMPLE_INT_HPP diff --git a/src/cr3preview_int.cpp b/src/cr3preview_int.cpp new file mode 100644 index 0000000000..b960361ccb --- /dev/null +++ b/src/cr3preview_int.cpp @@ -0,0 +1,200 @@ +// SPDX-License-Identifier: GPL-2.0-or-later + +#include "cr3preview_int.hpp" + +#ifdef EXV_ENABLE_BMFF + +#include "bmffsample_int.hpp" +#include "enforce.hpp" +#include "error.hpp" + +#include +#include + +namespace Exiv2::Internal { +namespace { + +// Collect only immediate headers; unknown payloads and compressed media stay opaque. +std::vector children(BmffReader& reader, BmffSpan range, unsigned depth) { + std::vector boxes; + auto input = reader.cursor(range); + reader.visit(input, depth, [&](BmffBox& box, BmffCursor&) { boxes.push_back(box); }); + return boxes; +} + +// Borrow an unambiguous child from a collection that must outlive the pointer. +const BmffBox* unique(const std::vector& boxes, uint32_t type) { + const BmffBox* result = nullptr; + for (const auto& box : boxes) { + if (box.type == type) { + enforce(result == nullptr, ErrorCode::kerCorruptedMetadata); + result = &box; + } + } + return result; +} + +// Select a one-based entry from a version-zero, counted FullBox without buffering entries. +std::optional indexed(BmffReader& reader, const BmffBox& table, uint32_t index, unsigned depth) { + auto input = reader.cursor(table.payload()); + enforce(input.number(4) == 0, ErrorCode::kerCorruptedMetadata); + const auto count = input.number(4); + if (index == 0 || index > count) + return std::nullopt; + + std::optional selected; + uint64_t visited = 0; + reader.visit( + input, depth, + [&](BmffBox& entry, BmffCursor&) { + if (++visited == index) + selected = entry; + }, + count); + enforce(visited == count, ErrorCode::kerCorruptedMetadata); + input.finish(); + return selected; +} + +// Follow the description's data reference only when it explicitly names this file. +bool localReference(BmffReader& reader, const BmffBox& dinf, uint32_t index) { + const auto boxes = children(reader, dinf.payload(), 5); + const auto dref = unique(boxes, bmffType("dref")); + if (!dref) + return false; + const auto entry = indexed(reader, *dref, index, 6); + if (!entry || entry->type != bmffType("url ")) + return false; + + auto input = reader.cursor(entry->payload()); + return input.number(4) == 1 && input.remaining() == 0; +} + +// Interpret Canon's 82-byte visual-entry prefix and require its explicit JPEG child. +std::optional description(BmffReader& reader, const BmffBox& entry, const BmffBox& dinf) { + if (entry.type != bmffType("CRAW")) + return std::nullopt; + + // Canon offsets are relative to the payload, so extended headers need no adjustment. + // Reference: lclevy/canon_cr3 revision 151c1a965775ef409ace17714c24ed491cfcf9c4. + auto input = reader.cursor(entry.payload()); + input.advance(6); + const auto reference = static_cast(input.number(2)); + input.advance(16); + NativePreview preview; + preview.width_ = static_cast(input.number(2)); + preview.height_ = static_cast(input.number(2)); + input.advance(54); + if (preview.width_ == 0 || preview.height_ == 0) + return std::nullopt; + + const auto boxes = children(reader, {input.position(), input.remaining()}, 7); + const auto jpeg = unique(boxes, bmffType("JPEG")); + if (!jpeg || unique(boxes, bmffType("CMP1")) || unique(boxes, bmffType("CDI1")) || unique(boxes, bmffType("hvcC")) || + unique(boxes, bmffType("sinf"))) + return std::nullopt; + auto marker = reader.cursor(jpeg->payload()); + if (marker.number(4) != 0 || marker.remaining() != 0 || !localReference(reader, dinf, reference)) + return std::nullopt; + + preview.mimeType_ = "image/jpeg"; + return preview; +} + +// Require media ownership, rather than accepting offsets into headers or unrelated boxes. +bool inMedia(const std::vector& roots, BmffSpan sample) { + return std::any_of(roots.begin(), roots.end(), [&](const BmffBox& box) { + if (box.type != bmffType("mdat")) + return false; + const auto media = box.payload(); + return sample.offset >= media.offset && sample.offset - media.offset <= media.size && + sample.size <= media.size - (sample.offset - media.offset); + }); +} + +// Resolve one ordinary still-image track; timed and unsupported codecs yield no candidate. +std::optional trackPreview(BmffReader& reader, const BmffBox& track, const std::vector& roots) { + const auto trackBoxes = children(reader, track.payload(), 2); + const auto mdia = unique(trackBoxes, bmffType("mdia")); + if (!mdia) + return std::nullopt; + const auto mediaBoxes = children(reader, mdia->payload(), 3); + const auto hdlr = unique(mediaBoxes, bmffType("hdlr")); + const auto minf = unique(mediaBoxes, bmffType("minf")); + if (!hdlr || !minf) + return std::nullopt; + auto handler = reader.cursor(hdlr->payload()); + if (handler.number(4) != 0) + return std::nullopt; + handler.advance(4); + if (handler.number(4) != bmffType("vide")) + return std::nullopt; + + // Sample mechanics are standard; description interpretation stays in this adapter. + const auto infoBoxes = children(reader, minf->payload(), 4); + const auto table = unique(infoBoxes, bmffType("stbl")); + const auto dinf = unique(infoBoxes, bmffType("dinf")); + if (!table || !dinf) + return std::nullopt; + const auto sample = readBmffSingleSample(reader, *table, 5); + if (!sample || sample->data.size < 2 || !inMedia(roots, sample->data) || + sample->data.offset > std::numeric_limits::max() || + sample->data.size > std::numeric_limits::max() - sample->data.offset) + return std::nullopt; + const auto tables = children(reader, table->payload(), 5); + const auto stsd = unique(tables, bmffType("stsd")); + if (!stsd) + return std::nullopt; + const auto entry = indexed(reader, *stsd, sample->descriptionIndex, 6); + if (!entry) + return std::nullopt; + auto preview = description(reader, *entry, *dinf); + if (!preview) + return std::nullopt; + + // Discovery reads the signature only; PreviewManager performs normal extraction later. + auto signature = reader.cursor({sample->data.offset, 2}); + if (signature.number(2) != 0xffd8) + return std::nullopt; + preview->position_ = static_cast(sample->data.offset); + preview->size_ = static_cast(sample->data.size); + return preview; +} + +} // namespace + +std::optional findCr3JpegPreview(BasicIo& io, size_t maxDepth) { + try { + // These limits apply only to optional CR3 track discovery, never legacy metadata reads. + const auto depth = static_cast(std::min(maxDepth, std::numeric_limits::max())); + BmffReader reader(io, {4096, 1024 * 1024, depth}); + const auto roots = children(reader, {0, reader.fileSize()}, 0); + const auto ftyp = unique(roots, bmffType("ftyp")); + const auto moov = unique(roots, bmffType("moov")); + if (!ftyp || !moov) + return std::nullopt; + auto brand = reader.cursor(ftyp->payload()); + if (brand.number(4) != bmffType("crx ")) + return std::nullopt; + + // At most one new candidate is needed; equal-area tracks retain original file order. + std::optional best; + for (const auto& track : children(reader, moov->payload(), 1)) { + if (track.type != bmffType("trak")) + continue; + const auto candidate = trackPreview(reader, track, roots); + if (candidate && + (!best || uint64_t{candidate->width_} * candidate->height_ > uint64_t{best->width_} * best->height_)) + best = candidate; + } + return best; + } catch (const Error& error) { + // Corrupt optional tracks and exhausted discovery budgets must not hide readable metadata. + if (error.code() != ErrorCode::kerCorruptedMetadata) + throw; + return std::nullopt; + } +} + +} // namespace Exiv2::Internal +#endif // EXV_ENABLE_BMFF diff --git a/src/cr3preview_int.hpp b/src/cr3preview_int.hpp new file mode 100644 index 0000000000..06a87c89f3 --- /dev/null +++ b/src/cr3preview_int.hpp @@ -0,0 +1,33 @@ +// SPDX-License-Identifier: GPL-2.0-or-later + +#ifndef CR3PREVIEW_INT_HPP +#define CR3PREVIEW_INT_HPP + +#include "config.h" + +#ifdef EXV_ENABLE_BMFF + +#include "image.hpp" + +#include + +namespace Exiv2::Internal { + +/*! + @brief Locate the largest supported single-sample JPEG track in a CR3 input. + @param io Open, seekable, unchanged input, borrowed for this call only. + @param maxDepth Caller-selected maximum box nesting depth. + @return A native preview borrowing an absolute source range, or no value if + optional discovery encounters unsupported/malformed structure or limits. + @throws Error For failures reading or seeking the underlying input. + + Only crx-major-brand, locally referenced CRAW/JPEG tracks are accepted. The + extra pass reads at most 4096 headers and 1 MiB of structural fields; image + payloads remain in the input except for a two-byte signature check. The input + must outlive use of the returned preview. The stream position may change. + */ +std::optional findCr3JpegPreview(BasicIo& io, size_t maxDepth); + +} // namespace Exiv2::Internal +#endif // EXV_ENABLE_BMFF +#endif // CR3PREVIEW_INT_HPP diff --git a/src/meson.build b/src/meson.build index 8f4aa4e21e..78ee9b3186 100644 --- a/src/meson.build +++ b/src/meson.build @@ -46,6 +46,8 @@ endif int_lib = files( 'bmffbox_int.cpp', + 'bmffsample_int.cpp', + 'cr3preview_int.cpp', 'bmffitem_int.cpp', 'bmffitemwrite_int.cpp', 'bmfflayout_int.cpp', diff --git a/tests/bugfixes/github/test_issue_1893.py b/tests/bugfixes/github/test_issue_1893.py index 62d19951af..8d5848926f 100644 --- a/tests/bugfixes/github/test_issue_1893.py +++ b/tests/bugfixes/github/test_issue_1893.py @@ -37,7 +37,10 @@ class issue_1893_cr3_preview(metaclass=system_tests.CaseMeta): print("*** test skipped. requires enable_bmff=1***") else: retval = [0, 0] - stderr = ["", ""] + # The legacy XMP reader reports its existing limitation in toolkit-disabled builds. + xmp_warning = ("" if system_tests.BT.verbose_version().get("have_xmptoolkit") == "1" + else "Warning: XMP toolkit support not compiled in.\n") + stderr = [xmp_warning, xmp_warning] stdin = ["", ""] stdout = [ """Preview 1: image/jpeg, 160x120 pixels, 16005 bytes diff --git a/tests/bugfixes/github/test_issue_2854.py b/tests/bugfixes/github/test_issue_2854.py new file mode 100644 index 0000000000..79385a53f9 --- /dev/null +++ b/tests/bugfixes/github/test_issue_2854.py @@ -0,0 +1,86 @@ +# -*- coding: utf-8 -*- + +import hashlib +from pathlib import Path +import struct +import subprocess +import tempfile +import unittest + +import system_tests + + +# Frame generated container fields independently of the library's BMFF reader. +def box(kind, payload): + return struct.pack(">I4s", len(payload) + 8, kind) + payload + + +# Embed an existing small, valid JPEG in a single-sample Canon video track. +def cr3(jpeg, wide_offsets=True, variable_size=False): + ftyp = box(b"ftyp", b"crx \0\0\0\0crx ") + mdat = box(b"mdat", jpeg) + prefix = bytearray(82) + struct.pack_into(">H", prefix, 6, 1) # Local data-reference index. + struct.pack_into(">HH", prefix, 24, 150, 91) + description = box(b"CRAW", prefix + box(b"JPEG", bytes(4))) + + # Resolve the JPEG through sample tables, rather than its position in mdat. + stsd = box(b"stsd", struct.pack(">II", 0, 1) + description) + stsc = box(b"stsc", struct.pack(">IIIII", 0, 1, 1, 1, 1)) + sizes = struct.pack(">III", 0, 0 if variable_size else len(jpeg), 1) + if variable_size: + sizes += struct.pack(">I", len(jpeg)) + stsz = box(b"stsz", sizes) + offset = struct.pack(">Q" if wide_offsets else ">I", len(ftyp) + 8) + chunks = box(b"co64" if wide_offsets else b"stco", struct.pack(">II", 0, 1) + offset) + stbl = box(b"stbl", stsd + stsc + stsz + chunks) + dref = box(b"dref", struct.pack(">II", 0, 1) + box(b"url ", struct.pack(">I", 1))) + minf = box(b"minf", box(b"dinf", dref) + stbl) + hdlr = box(b"hdlr", bytes(8) + b"vide" + bytes(12)) + return ftyp + mdat + box(b"moov", box(b"trak", box(b"mdia", hdlr + minf))) + + +# Exercise public listing/extraction without adding large camera files to the suite. +@unittest.skipUnless(system_tests.BT.verbose_version().get("enable_bmff") == "1", + "requires BMFF support") +class Cr3FullPreview(unittest.TestCase): + # Own disposable containers and preserve the original JPEG fixture. + def setUp(self): + directory = tempfile.TemporaryDirectory(prefix="exiv2-cr3-", dir=system_tests.tmp_path) + self.addCleanup(directory.cleanup) + self.root = Path(directory.name) + self.exiv2 = str(Path(system_tests.BT.Config.bin_dir) / "exiv2") + self.jpeg = (Path(system_tests.data_path) / "exiv2-empty.jpg").read_bytes() + + # Run the intended build with bounded execution and captured diagnostics. + def run_exiv2(self, *args): + return subprocess.run([self.exiv2, *map(str, args)], capture_output=True, timeout=30) + + # Both standard size/offset encodings must expose and extract the exact JPEG. + def test_list_and_extract_full_jpeg(self): + for wide, variable in [(True, False), (False, True)]: + with self.subTest(wide_offsets=wide, variable_size=variable): + path = self.root / f"generated-{wide}-{variable}.CR3" + path.write_bytes(cr3(self.jpeg, wide, variable)) + before = hashlib.sha256(path.read_bytes()).digest() + + listing = self.run_exiv2("-pp", path) + self.assertEqual(listing.returncode, 0, listing.stderr) + self.assertEqual(listing.stdout, ( + f"Preview 1: image/jpeg, 150x91 pixels, {len(self.jpeg)} bytes\n" + ).encode()) + extracted = self.run_exiv2("-ep", path) + self.assertEqual(extracted.returncode, 0, extracted.stderr) + self.assertEqual(path.with_name(path.stem + "-preview1.jpg").read_bytes(), self.jpeg) + self.assertEqual(hashlib.sha256(path.read_bytes()).digest(), before) + + # Additional preview reading must not enable CR3 metadata writing. + def test_cr3_remains_read_only(self): + path = self.root / "read-only.CR3" + data = cr3(self.jpeg) + path.write_bytes(data) + + result = self.run_exiv2("-M", "set Exif.Image.Artist unchanged", path) + + self.assertNotEqual(result.returncode, 0) + self.assertEqual(path.read_bytes(), data) diff --git a/unitTests/CMakeLists.txt b/unitTests/CMakeLists.txt index 932aba0b24..31ac12ea6c 100644 --- a/unitTests/CMakeLists.txt +++ b/unitTests/CMakeLists.txt @@ -16,6 +16,7 @@ add_executable( test_bmfflegacy_int.cpp test_bmfflayout_int.cpp test_bmffimage_int.cpp + test_cr3preview_int.cpp test_bmpimage.cpp test_cr2header_int.cpp test_datasets.cpp diff --git a/unitTests/meson.build b/unitTests/meson.build index 54c4e88bb2..6dcd008282 100644 --- a/unitTests/meson.build +++ b/unitTests/meson.build @@ -18,6 +18,7 @@ test_sources = files( 'test_bmfflegacy_int.cpp', 'test_bmfflayout_int.cpp', 'test_bmffimage_int.cpp', + 'test_cr3preview_int.cpp', 'test_bmpimage.cpp', 'test_cr2header_int.cpp', 'test_datasets.cpp', diff --git a/unitTests/test_bmfflegacy_int.cpp b/unitTests/test_bmfflegacy_int.cpp index 9385a71c06..deb582b984 100644 --- a/unitTests/test_bmfflegacy_int.cpp +++ b/unitTests/test_bmfflegacy_int.cpp @@ -253,7 +253,7 @@ TEST(BmffLegacy, rejectsMissingCountedEntry) { expectError(ErrorCode::kerCorruptedMetadata, [&] { image->readMetadata(); }); } -// Canon containers retain TIFF interpretation, preview origins, and repeated-read behavior. +// Canon containers retain TIFF interpretation and preview origins without accumulating reads. TEST(BmffLegacy, readsCanonMetadataAndPrefixedPreviews) { for (const bool extended : {false, true}) { auto bytes = file("crx "); @@ -273,7 +273,7 @@ TEST(BmffLegacy, readsCanonMetadataAndPrefixedPreviews) { ASSERT_NO_THROW(image->readMetadata()); EXPECT_EQ(image->mimeType(), "image/x-canon-cr3"); EXPECT_EQ(image->exifData()["Exif.Image.Artist"].toString(), "Canon artist"); - ASSERT_EQ(image->nativePreviews().size(), read + 1); + ASSERT_EQ(image->nativePreviews().size(), 1u); const auto& actual = image->nativePreviews().back(); EXPECT_EQ(actual.position_, previewPosition); EXPECT_EQ(actual.size_, 4u); diff --git a/unitTests/test_cr3preview_int.cpp b/unitTests/test_cr3preview_int.cpp new file mode 100644 index 0000000000..fbe911c74a --- /dev/null +++ b/unitTests/test_cr3preview_int.cpp @@ -0,0 +1,544 @@ +// SPDX-License-Identifier: GPL-2.0-or-later + +#include "bmffsample_int.hpp" +#include "cr3preview_int.hpp" + +#ifdef EXV_ENABLE_BMFF + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +using namespace Exiv2; +using namespace Exiv2::Internal; + +namespace { +using Bytes = std::vector; + +// Encode synthetic fields independently of the production cursors and table decoders. +void integer(Bytes& bytes, uint64_t value, unsigned width = 4) { + for (unsigned i = width; i != 0; --i) + bytes.push_back(static_cast(value >> ((i - 1) * 8))); +} + +// Concatenate opaque fixture bytes without interpreting their structure. +void append(Bytes& bytes, const Bytes& suffix) { + bytes.insert(bytes.end(), suffix.begin(), suffix.end()); +} + +// Frame ordinary and extended boxes independently of the production box reader. +Bytes box(std::string_view type, const Bytes& payload = {}, bool extended = false) { + Bytes bytes; + integer(bytes, extended ? 1 : payload.size() + 8); + bytes.insert(bytes.end(), type.begin(), type.end()); + if (extended) + integer(bytes, payload.size() + 16, 8); + append(bytes, payload); + return bytes; +} + +// Assemble fixed-width table words without sharing production serialization code. +Bytes words(std::initializer_list values) { + Bytes bytes; + for (auto value : values) + integer(bytes, value); + return bytes; +} + +// Select physical encodings and Canon policy independently for generated fixtures. +struct Options { + bool wide{true}; + bool variable{}; + bool extended{}; + bool mediaFirst{}; + bool external{}; + bool extraTrack{}; + bool extraMedia{}; + uint32_t descriptionIndex{1}; + uint16_t referenceIndex{1}; + uint16_t width{150}; + uint16_t height{91}; + std::string_view codec{"JPEG"}; + std::vector extraCodecs; +}; + +// Construct the three standard singleton tables without requiring a brand or item model. +Bytes tables(uint64_t offset, uint32_t length, const Options& options = {}) { + auto bytes = box("stsc", words({0, 1, 1, 1, options.descriptionIndex}), options.extended); + auto sizes = words({0, options.variable ? 0 : length, 1}); + if (options.variable) + integer(sizes, length); + append(bytes, box("stsz", sizes, options.extended)); + auto chunks = words({0, 1}); + integer(chunks, offset, options.wide ? 8 : 4); + append(bytes, box(options.wide ? "co64" : "stco", chunks, options.extended)); + return bytes; +} + +// Read an existing small valid JPEG; extraction tests compare every original byte. +Bytes jpeg() { + std::ifstream input(std::string(TESTDATA_PATH) + "/exiv2-empty.jpg", std::ios::binary); + return {std::istreambuf_iterator(input), std::istreambuf_iterator()}; +} + +// Build a Canon visual track, optionally preceding its referenced description with an opaque one. +Bytes track(uint64_t offset, uint32_t length, const Options& options = {}, bool metadata = false) { + Bytes prefix(82); + prefix[6] = static_cast(options.referenceIndex >> 8); + prefix[7] = static_cast(options.referenceIndex); + prefix[24] = static_cast(options.width >> 8); + prefix[25] = static_cast(options.width); + prefix[26] = static_cast(options.height >> 8); + prefix[27] = static_cast(options.height); + append(prefix, box(options.codec, words({0}), options.extended)); + for (const auto codec : options.extraCodecs) + append(prefix, box(codec, words({0}), options.extended)); + auto descriptions = words({0, options.descriptionIndex}); + for (uint32_t i = 1; i < options.descriptionIndex; ++i) + append(descriptions, box("junk")); + append(descriptions, box("CRAW", prefix, options.extended)); + + auto samples = box("stsd", descriptions, options.extended); + append(samples, tables(offset, length, options)); + auto dref = words({0, options.referenceIndex}); + for (uint16_t i = 1; i < options.referenceIndex; ++i) + append(dref, box("url ", words({0}), options.extended)); + append(dref, box("url ", words({options.external ? 0u : 1u}), options.extended)); + auto info = box("dinf", box("dref", dref, options.extended), options.extended); + append(info, box("stbl", samples, options.extended)); + auto handler = words({0, 0}); + const std::string_view kind = metadata ? "meta" : "vide"; + handler.insert(handler.end(), kind.begin(), kind.end()); + auto media = box("hdlr", handler, options.extended); + append(media, box("minf", info, options.extended)); + return box("trak", box("mdia", media, options.extended), options.extended); +} + +// Place a single image inside mdat padding, with independent track and media ordering. +Bytes fixture(const Options& options = {}) { + auto bytes = box("ftyp", {'c', 'r', 'x', ' ', 0, 0, 0, 0, 'c', 'r', 'x', ' '}); + if (options.extraMedia) + append(bytes, box("mdat", Bytes(17, 42), options.extended)); + const auto image = jpeg(); + Bytes media(7, 42); + append(media, image); + append(media, Bytes(11, 43)); + const auto mdat = box("mdat", media, options.extended); + const auto header = options.extended ? 16 : 8; + auto tracks = track(0, static_cast(image.size()), options); + if (options.extraTrack) + append(tracks, track(0, static_cast(image.size()), options, true)); + const auto moovSize = box("moov", tracks, options.extended).size(); + const auto offset = bytes.size() + (options.mediaFirst ? 0 : moovSize) + header + 7; + tracks = options.extraTrack ? track(offset, static_cast(image.size()), options, true) : Bytes{}; + append(tracks, track(offset, static_cast(image.size()), options)); + const auto moov = box("moov", tracks, options.extended); + append(bytes, options.mediaFirst ? mdat : moov); + append(bytes, options.mediaFirst ? moov : mdat); + return bytes; +} + +// Locate a generated field by its unique type, returning the payload's first byte. +size_t payload(const Bytes& bytes, std::string_view type) { + const auto found = std::search(bytes.begin(), bytes.end(), type.begin(), type.end()); + EXPECT_NE(found, bytes.end()); + const auto position = static_cast(found - bytes.begin()); + return position + 4; +} + +// Mutate a fixed-width fixture field to exercise malformed-input handling. +void replace(Bytes& bytes, size_t position, uint64_t value, unsigned width = 4) { + Bytes field; + integer(field, value, width); + ASSERT_LE(position + width, bytes.size()); + std::copy(field.begin(), field.end(), bytes.begin() + position); +} + +// Preserve precise errors instead of allowing optional discovery to swallow actual I/O failures. +template +void expectError(ErrorCode code, Operation operation) { + try { + operation(); + FAIL() << "Expected an Exiv2::Error"; + } catch (const Error& error) { + EXPECT_EQ(error.code(), code); + } +} + +// Discover a preview in borrowed fixture bytes without entering the legacy metadata decoder. +std::optional discover(const Bytes& bytes, size_t depth = 100) { + MemIo io(bytes.data(), bytes.size()); + return findCr3JpegPreview(io, depth); +} + +// Decode a standalone stbl, demonstrating that singleton mechanics need no image-format boxes. +std::optional sample(const Bytes& bytes) { + MemIo io(bytes.data(), bytes.size()); + BmffReader reader(io, {100, 4096, 8}); + auto input = reader.cursor({0, bytes.size()}); + const auto table = reader.readBox(input); + return readBmffSingleSample(reader, table, 1); +} + +// Append a legacy Canon PRVW, leaving existing absolute track/sample coordinates untouched. +void addLegacyPreview(Bytes& bytes) { + Bytes uuid{0xea, 0xf4, 0x2b, 0x5e, 0x1c, 0x98, 0x4b, 0x88, 0xb9, 0xfb, 0xb7, 0xdc, 0x40, 0x6e, 0x4d, 0x16}; + append(uuid, Bytes(8)); + append(uuid, box("PRVW", {0, 0, 0, 0, 0, 0, 0, 30, 0, 20, 0, 0, 0, 0, 0, 4, 0xff, 0xd8, 0xff, 0xd9})); + append(bytes, box("uuid", uuid)); +} + +// Serve a multi-gigabyte virtual file while storing only headers and the JPEG signature. +class SparseIo : public MemIo { + public: + using MemIo::read; + static constexpr uint64_t imageOffset = (uint64_t{1} << 33) + 123; + + // Retain only the small prefix; the mdat payload is represented by source coordinates. + SparseIo() : prefix_(box("ftyp", {'c', 'r', 'x', ' ', 0, 0, 0, 0, 'c', 'r', 'x', ' '})) { + append(prefix_, box("moov", track(imageOffset, 100))); + const auto headerOffset = prefix_.size(); + integer(prefix_, 1); + append(prefix_, {'m', 'd', 'a', 't'}); + integer(prefix_, imageOffset + 100 - headerOffset, 8); + } + + //! @brief Expose the virtual file length without allocating compressed media. + size_t size() const override { + return static_cast(imageOffset + 100); + } + + //! @brief Report the virtual absolute input position. + size_t tell() const override { + return static_cast(position_); + } + + //! @brief Accept only in-range absolute seeks used by the shared reader. + int seek(int64_t offset, Position origin) override { + if (origin != beg || offset < 0 || static_cast(offset) > size()) + return 1; + position_ = static_cast(offset); + return 0; + } + + //! @brief Serve headers and SOI only, recording any attempted image-buffer read. + size_t read(byte* output, size_t count) override { + largestRead = std::max(largestRead, count); + if (position_ == imageOffset && count == 2) { + output[0] = 0xff; + output[1] = 0xd8; + } else if (position_ <= prefix_.size() && count <= prefix_.size() - position_) { + std::copy_n(prefix_.data() + position_, count, output); + } else { + unexpectedRead = true; + return 0; + } + position_ += count; + return count; + } + + size_t largestRead{}; + bool unexpectedRead{}; + + private: + Bytes prefix_; + uint64_t position_{}; +}; + +// Inject a genuine failure specifically in the new optional track discovery path. +class FailingIo : public MemIo { + public: + using MemIo::read; + + // Borrow unchanged fixture storage and choose whether reads or seeks should fail. + FailingIo(const Bytes& bytes, bool seekFailure) : MemIo(bytes.data(), bytes.size()), seekFailure_(seekFailure) { + } + + //! @brief Fail all seeks when selected; malformed metadata must not mask this error. + int seek(int64_t offset, Position origin) override { + return seekFailure_ ? 1 : MemIo::seek(offset, origin); + } + + //! @brief Return a short structural read in the read-failure variant. + size_t read(byte* output, size_t count) override { + return MemIo::read(output, count ? count - 1 : 0); + } + + private: + bool seekFailure_; +}; +} // namespace + +// Standard singleton resolution works without ftyp, meta, Canon tags or JPEG bytes. +TEST(BmffSample, resolvesBothOffsetAndSizeEncodings) { + for (const bool wide : {false, true}) { + for (const bool variable : {false, true}) { + Options options; + options.wide = wide; + options.variable = variable; + options.descriptionIndex = 3; + auto bytes = box("stbl", tables(8, 3, options)); + const auto actual = sample(bytes); + ASSERT_TRUE(actual); + EXPECT_EQ(actual->data, (BmffSpan{8, 3})); + EXPECT_EQ(actual->descriptionIndex, 3u); + } + } +} + +// Supported tables reject ambiguity, truncation, nonzero versions and invalid input ranges. +TEST(BmffSample, rejectsMalformedTables) { + const auto original = box("stbl", tables(8, 3)); + for (const auto type : {"stsc", "stsz", "co64"}) { + auto bytes = original; + replace(bytes, payload(bytes, type), 0x01000000); + expectError(ErrorCode::kerCorruptedMetadata, [&] { sample(bytes); }); + bytes = original; + if (std::string_view(type) == "stsz") + replace(bytes, payload(bytes, type) + 4, 0); + replace(bytes, payload(bytes, type) + (std::string_view(type) == "stsz" ? 8 : 4), 0xffffffff); + expectError(ErrorCode::kerCorruptedMetadata, [&] { sample(bytes); }); + } + auto bytes = original; + replace(bytes, payload(bytes, "co64") + 8, std::numeric_limits::max(), 8); + expectError(ErrorCode::kerCorruptedMetadata, [&] { sample(bytes); }); + bytes = tables(8, 3); + append(bytes, box("stco", words({0, 1, 8}))); + expectError(ErrorCode::kerCorruptedMetadata, [&] { sample(box("stbl", bytes)); }); +} + +// Missing tables, zero-sized samples, multiple samples/chunks and compact sizes are unsupported. +TEST(BmffSample, omitsUnsupportedLayouts) { + EXPECT_FALSE(sample(box("stbl"))); + Options variable; + variable.variable = true; + EXPECT_FALSE(sample(box("stbl", tables(8, 0, variable)))); + auto bytes = box("stbl", tables(8, 3)); + replace(bytes, payload(bytes, "stsz") + 8, 2); + EXPECT_FALSE(sample(bytes)); + bytes = box("stbl", tables(8, 3)); + replace(bytes, payload(bytes, "stsc") + 12, 2); + EXPECT_FALSE(sample(bytes)); + bytes = tables(8, 3); + append(bytes, box("stz2", words({0, 0, 1}))); + EXPECT_FALSE(sample(box("stbl", bytes))); +} + +// Ordinary and extended source headers, table encodings and physical orders yield exact bytes. +TEST(Cr3Preview, discoversAndExtractsThroughBothImageInterfaces) { + for (const bool extended : {false, true}) { + for (const bool wide : {false, true}) { + Options options; + options.extended = extended; + options.wide = wide; + options.variable = !wide; + options.mediaFirst = wide; + options.extraTrack = true; + options.extraMedia = true; + options.descriptionIndex = 2; + options.referenceIndex = 2; + const auto bytes = fixture(options); + + for (const bool factory : {false, true}) { + Image::UniquePtr image; + if (factory) + image = ImageFactory::open(bytes.data(), bytes.size()); + else + image = std::make_unique(std::make_unique(bytes.data(), bytes.size()), + ImageCtorParams(false, 100)); + ASSERT_NE(image, nullptr); + ASSERT_NO_THROW(image->readMetadata()); + ASSERT_EQ(image->nativePreviews().size(), 1u); + EXPECT_EQ(image->mimeType(), "image/x-canon-cr3"); + PreviewManager manager(*image); + const auto properties = manager.getPreviewProperties(); + ASSERT_EQ(properties.size(), 1u); + EXPECT_EQ(properties[0].width_, 150u); + EXPECT_EQ(properties[0].height_, 91u); + const auto extracted = manager.getPreviewImage(properties[0]); + const auto expected = jpeg(); + ASSERT_EQ(extracted.size(), expected.size()); + EXPECT_TRUE(std::equal(expected.begin(), expected.end(), extracted.pData())); + } + } + } +} + +// Repeated reads and printing retain one current view, including replaced backing content. +TEST(Cr3Preview, replacesReadStateAndDoesNotAccumulateDuringPrinting) { + auto bytes = fixture(); + addLegacyPreview(bytes); + auto image = ImageFactory::open(bytes.data(), bytes.size()); + for (unsigned read = 0; read < 3; ++read) { + image->readMetadata(); + ASSERT_EQ(image->nativePreviews().size(), 2u); + EXPECT_EQ(image->nativePreviews()[0].width_, 30u); + EXPECT_EQ(image->nativePreviews()[1].width_, 150u); + std::ostringstream output; + image->printStructure(output, kpsRecursive); + ASSERT_EQ(image->nativePreviews().size(), 2u); + } + + // The previous full-size range must disappear when a new CR3 has no JPEG track. + Options options; + options.codec = "CMP1"; + const auto replacement = fixture(options); + MemIo source(replacement.data(), replacement.size()); + image->io().transfer(source); + image->readMetadata(); + EXPECT_TRUE(image->nativePreviews().empty()); +} + +// Optional corrupt/unsupported tracks never become previews or break ordinary metadata reads. +TEST(Cr3Preview, omitsInvalidAndUnsupportedCandidates) { + for (const auto codec : {"CMP1", "hvcC", "sinf", "free"}) { + Options options; + options.codec = codec; + EXPECT_FALSE(discover(fixture(options))); + } + for (const auto codec : {"CMP1", "CDI1", "hvcC", "sinf", "JPEG"}) { + Options options; + options.extraCodecs = {codec}; + EXPECT_FALSE(discover(fixture(options))); + } + Options external; + external.external = true; + EXPECT_FALSE(discover(fixture(external))); + Options empty; + empty.width = 0; + EXPECT_FALSE(discover(fixture(empty))); + + // Each mutation targets a different validation boundary of an otherwise valid container. + const auto original = fixture(); + for (unsigned mutation = 0; mutation < 12; ++mutation) { + auto bytes = original; + switch (mutation) { + case 0: + replace(bytes, 8, bmffType("avif")); + break; + case 1: + replace(bytes, payload(bytes, "stsz") + 8, 2); + break; + case 2: + replace(bytes, payload(bytes, "stsc") + 16, 2); + break; + case 3: + replace(bytes, payload(bytes, "CRAW") + 6, 2, 2); + break; + case 4: + replace(bytes, payload(bytes, "co64") + 8, 8, 8); + break; + case 5: + replace(bytes, payload(bytes, "co64") + 8, bytes.size() - 1, 8); + break; + case 6: + replace(bytes, payload(bytes, "JPEG") - 8, 7); + break; + case 7: + replace(bytes, payload(bytes, "stsc") + 4, 0xffffffff); + break; + case 8: + replace(bytes, payload(bytes, "CRAW") - 8, 16); + break; + case 9: + replace(bytes, payload(bytes, "stsd") + 4, 0xffffffff); + break; + case 10: + replace(bytes, payload(bytes, "hdlr") + 8, bmffType("meta")); + break; + case 11: + replace(bytes, payload(bytes, "mdat") + 7, 0, 2); + break; + } + EXPECT_FALSE(discover(bytes)) << mutation; + auto image = ImageFactory::open(bytes.data(), bytes.size()); + ASSERT_NO_THROW(image->readMetadata()) << mutation; + EXPECT_TRUE(image->nativePreviews().empty()) << mutation; + } +} + +// Existing native loader slots are never displaced by the optional full-size candidate. +TEST(Cr3Preview, preservesExistingSlotsAndFallbackPreviews) { + auto bytes = fixture(); + for (unsigned i = 0; i < 4; ++i) + addLegacyPreview(bytes); + auto image = ImageFactory::open(bytes.data(), bytes.size()); + image->readMetadata(); + ASSERT_EQ(image->nativePreviews().size(), 4u); + for (const auto& preview : image->nativePreviews()) + EXPECT_EQ(preview.width_, 30u); + + Options options; + options.external = true; + bytes = fixture(options); + addLegacyPreview(bytes); + image = ImageFactory::open(bytes.data(), bytes.size()); + image->readMetadata(); + ASSERT_EQ(image->nativePreviews().size(), 1u); + EXPECT_EQ(image->nativePreviews()[0].width_, 30u); +} + +// Largest-area selection is independent of track numbering, with stable ties in file order. +TEST(Cr3Preview, selectsLargestTrackAndRetainsFileOrderTies) { + for (const bool tie : {false, true}) { + Options options; + options.mediaFirst = true; + auto bytes = fixture(options); + const auto first = discover(bytes); + ASSERT_TRUE(first); + options.width = tie ? 91 : 300; + options.height = tie ? 150 : 200; + const auto next = track(first->position_, static_cast(first->size_), options); + const auto moovPayload = payload(bytes, "moov"); + const auto moovSize = bytes.size() - (moovPayload - 8); + append(bytes, next); + replace(bytes, moovPayload - 8, moovSize + next.size()); + + const auto selected = discover(bytes); + ASSERT_TRUE(selected); + EXPECT_EQ(selected->width_, tie ? 150u : 300u); + EXPECT_EQ(selected->height_, tie ? 91u : 200u); + } +} + +// Optional work respects depth/header budgets rather than buffering arbitrarily large media. +TEST(Cr3Preview, boundsDiscoveryWork) { + EXPECT_FALSE(discover(fixture(), 6)); + auto bytes = fixture(); + for (unsigned i = 0; i < 4096; ++i) + append(bytes, box("free")); + EXPECT_FALSE(discover(bytes)); +} + +// Native source ranges above 4 GiB retain all offset bits and read only the JPEG signature. +TEST(Cr3Preview, resolvesSparseLargeOffsetsWithBoundedReads) { + if (std::numeric_limits::max() <= std::numeric_limits::max()) + GTEST_SKIP() << "requires 64-bit source coordinates"; + SparseIo io; + const auto preview = findCr3JpegPreview(io, 100); + ASSERT_TRUE(preview); + EXPECT_EQ(preview->position_, SparseIo::imageOffset); + EXPECT_EQ(preview->size_, 100u); + EXPECT_LE(io.largestRead, 8u); + EXPECT_FALSE(io.unexpectedRead); +} + +// Genuine seek/short-read failures propagate, unlike malformed optional track structure. +TEST(Cr3Preview, propagatesUnderlyingIoFailures) { + const auto bytes = fixture(); + for (const bool seekFailure : {false, true}) { + FailingIo io(bytes, seekFailure); + expectError(ErrorCode::kerInputDataReadFailed, [&] { findCr3JpegPreview(io, 100); }); + } +} + +#endif // EXV_ENABLE_BMFF From cc366c3f2bc8c5fbf02a0a27d3c96cd52c3d1d17 Mon Sep 17 00:00:00 2001 From: Vaclav Haisman Date: Sat, 31 Oct 2026 18:14:21 +0100 Subject: [PATCH 40/40] [tests] Normalize CR3 preview listing newlines Normalize CRLF in the captured textual listing before comparison. Keep extracted JPEG and source-preservation checks byte exact. Validated with MSVC 19.44 x86 Debug: the CR3 CLI regressions pass, the inherited HEIF CLI tests pass with expected skips, and the full unit-test suite passes. --- tests/bugfixes/github/test_issue_2854.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/bugfixes/github/test_issue_2854.py b/tests/bugfixes/github/test_issue_2854.py index 79385a53f9..fcb1cd79a4 100644 --- a/tests/bugfixes/github/test_issue_2854.py +++ b/tests/bugfixes/github/test_issue_2854.py @@ -66,7 +66,7 @@ def test_list_and_extract_full_jpeg(self): listing = self.run_exiv2("-pp", path) self.assertEqual(listing.returncode, 0, listing.stderr) - self.assertEqual(listing.stdout, ( + self.assertEqual(listing.stdout.replace(b"\r\n", b"\n"), ( f"Preview 1: image/jpeg, 150x91 pixels, {len(self.jpeg)} bytes\n" ).encode()) extracted = self.run_exiv2("-ep", path)