diff --git a/CHANGELOG.md b/CHANGELOG.md index e87ec8eb..b589eaf2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -67,6 +67,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - AVI INFO text honours a `CSET` chunk (code page 65001, 1252, 0 or 28591); without one, valid UTF-8 (ffmpeg's and TagLib#'s encoding) is read as UTF-8 and other text as Windows-1252. On save, an unchanged value keeps its exact bytes and the file keeps its `CSET` (or its absence); changed values are written in the file's code page when they fit it (ASCII only when there is no `CSET`), otherwise the list becomes UTF-8 with a `CSET` of code page 65001 before it. When the list becomes UTF-8, untouched text in a declared code page decoded exactly (1252, 28591, 0) is rewritten as the same text in UTF-8; a save that would have to rewrite untouched text whose code page is a guess (no `CSET`), is not decoded here (for example Shift-JIS or cp1251), or that holds a byte its declared code page leaves undefined (0x81, 0x8D, 0x8F, 0x90, 0x9D in 1252; 0x80-0x9F under code page 0) is refused, and the error names the field and which of those reasons applies. A CSET rewritten to 65001 keeps the file's country, language and dialect codes. The five undefined 1252 code points are never written as 1252 bytes; a value holding one goes to UTF-8. WAV INFO is unchanged (Latin-1). - A path save copies `movi` in 64 KB pieces and patches `idx1` and OpenDML indexes from the source, so it no longer loads the file. `Render` and `SaveToFile(path, span)` still build one buffer. `MediaFile.Read` and `AviFile.ReadFromFile` read only the header and tag chunks. - Matroska `AlbumArtistSort` and `ComposerSort`: `SORT_WITH` nested in the album-level `ARTIST` (`TargetTypeValue` 50) and in `COMPOSER`, with flat `ALBUM_ARTIST_SORT` / `COMPOSER_SORT` as the fallback. Clearing removes both forms at every level the getter reads. When the track inherits the album's `ARTIST`, writing either `ArtistSort` or `AlbumArtistSort` first copies that `ARTIST` to the track level, so the other sort is kept (#116). +- Still images: `MediaFile.Read` and `StillImageFile.Read`/`ReadFromFile`/`ReadFromFileAsync` open JPEG, PNG, GIF, BMP, PCX, Netpbm (PBM, PGM, PPM, PNM), TIFF, DNG, and SVG and report width and height. A TIFF or DNG reports the size exiftool's ImageSize gives (measured case by case): the width and height of the first IFD whose NewSubfileType is 0, the full-resolution image, in the order exiftool reads them (IFD0, its SubIFDs depth first with their next IFDs, then IFD0's next IFD), or else IFD0's; unlike exiftool, a width and a height come from one IFD, and a size of 0, a negative one or one past 2^31 - 1 is none. DNG is TIFF with the DNG version tag in IFD0. A table of any size whose entries fit in the data is read, as exiftool reads one of 65,535 entries, and SubIFD offsets are decoded as exiftool decodes them, with the same rules as the Exif pointers below (in BigTIFF also LONG8, SLONG8 and IFD8, but not UNDEFINED); the walk reads at most 4,096 IFDs, 64 SubIFD levels deep, and stops once it has read more entries than tables that do not overlap could hold. A classic IFD is read when 0, 2 or 4 bytes of its next-IFD field are present and is not read when 1 or 3 are (exiftool 13.55 drops that directory). When that directory is IFD0 the file is not opened, and the error is "IFD0's next-IFD field has 1 of its 4 bytes, so IFD0 is not read and the image has no size" (or 3 of its 4 bytes). A wholly missing next field is still read, with no next IFD. A JPEG whose frame height is 0 takes it from the DNL segment after the first scan (ITU-T T.81 §B.2.5). PNG text keywords (Title, Author, Description, Copyright, Creation Time, Comment) are written before the pixel data, the GIF comment after the header, and the JPEG COM marker before the scan; exiftool's PNG `Artist` keyword is read as the artist when there is no `Author`. `Render` copies every other byte, including the pixels and anything after the PNG IEND, the GIF trailer, or the JPEG EOI; a no-op save is byte-identical. A path save (`SaveToFile(path)` and `SaveToFileAsync`) copies those pixels in 64 KB pieces and writes the same bytes as `Render`. When a field changes, its copies elsewhere in the file change too: the XMP property (`dc:title`, `dc:creator`, `dc:description`, `dc:rights`, `exif:UserComment`) is replaced in place, keeping its start and end tags, or removed for null, in PNG `XML:com.adobe.xmp` and ImageMagick's `Raw profile type xmp`, JPEG APP1 XMP, and the GIF XMP extension; the Exif copies (IFD0 `ImageDescription`, `Artist`, `Copyright`, the Windows XP title, author and comment tags, and `UserComment`) are removed from PNG `eXIf`, ImageMagick's raw EXIF, and JPEG APP1 Exif, from every table exiftool reads with its Exif tags (measured with exiftool 13.55): IFD0 and the IFDs chained after it (IFD1, IFD2, ...), and every Exif IFD (0x8769), SubIFD (0x014A) and interoperability IFD (0xA005) any of them points at, however deep (exiftool shows a copy from any of them; ImageIO and TagLib# read a subset), each table walked once. A pointer is followed as exiftool decodes it: a BYTE, SHORT, LONG, SBYTE, SSHORT, SLONG or IFD value, or UNDEFINED with count 1; an Exif IFD pointer only with count 1, a GPS or interoperability pointer by its first value, SubIFDs by every value; a negative value, or values that do not all lie in the data, name nothing; two pointer arrays at one offset are each read by their own type. IFD0's Exif IFD and GPS pointers are also followed as TagLib# reads them, their 4-byte field taken as a LONG whatever their type and count (measured), so the copy TagLib# shows from such a table is removed too, and its GPS table is protected. A GPS table is read with its GPS tags only: nothing in it is edited and no pointer in it is followed. A table is walked when its entries fit in the data. A pointer whose table's entries do not fit is skipped, as readers skip it. A field edit runs only when that structure is plain, and nothing is written otherwise. It is not plain when a strip, tile or thumbnail offset or length (TIFF 6.0 tags 0x0111/0x0117, 0x0144/0x0145 and 0x0201/0x0202) is typed other than SHORT or LONG; when one of those arrays is named more than once (two tables, both sides of one pair, or the same tag twice in one table); when a complete pair names more values than half the bytes; when a classic next-IFD field has only one, two or three of its four bytes (a wholly absent next field stays editable; exiftool itself still reads a table that has two); when removing an entry would change whether exiftool reads that table's first entry, including a change no tag shows; or when a removed value shares a protected byte, or compacting a table would rewrite any protected range other than that table. Two protected ranges may share a byte. Clear does not use this gate. An edit with nothing to remove still saves. A save is also refused when the tables hold more entries than the data could without overlapping and the block's bytes could hold an entry with one of the field's tags, of any type; edits with nothing to remove save. The `Artist` and ImageMagick `exif:*` text keywords are dropped. A packet no XMP reader reads because it is not well-formed, and does not name a changed field, an ImageMagick raw profile that is not hex, and PNG text that is not zlib data or whose iTXt header is cut short, which no reader decodes, are kept as they are; compressed text past the shared inflation budget is refused, since it cannot be checked. For a JPEG or GIF only the comment is stored, so only the comment's copies change. An XMP packet followed by NULs or padding (as ImageIO writes it) is edited and the tail kept, and GIF XMP written as data sub-blocks (ImageIO) is edited as well as the raw form with its magic trailer. A save that cannot update a copy (XMP that is not well-formed or has a DTD and names a changed field's property, a value XML cannot hold, an Exif block that is not classic TIFF and whose bytes could hold an entry with one of the field's tags, in either byte order, a JPEG XMP packet that would outgrow its segment, extended XMP, or a GIF XMP block in neither the raw form with its magic trailer nor data sub-blocks, that holds a UserComment) is refused with its own reason, as is a container that cannot be spliced, or a multi-picture JPEG whose MPF index cannot be corrected or (for Clear) followed; the file is left unchanged. A length-changing edit moves bytes after the edited segment, as exiftool does; a maker-note pointer to data after the image (for example Sony's preview tag 0x2001) is not rewritten (#163). When a maker note is not fully located, a removed value outside the Exif tables keeps its bytes. Inflated PNG text is capped at 1 MiB for the whole file, on read and on save. `Clear` removes all tag metadata and keeps only what a decoder or colour management needs, or the file's structure: PNG critical chunks and tRNS, gAMA, cHRM, sRGB, iCCP, cICP, mDCV, cLLI, sBIT, bKGD, hIST, pHYs, sPLT, the APNG chunks, oFFs, pCAL, sCAL and sTER; JPEG APP0 JFIF/JFXX, APP2 ICC_PROFILE, MPF and the ISO 21496-1 gain map, APP14 Adobe, the XMP an HDR decoder needs to find and apply a gain map (Ultra HDR `hdrgm` and `Container`/`Item` directory, Apple `apdi` and `HDRGainMap` version and headroom, and the motion-photo `Camera:MotionPhoto`, `MotionPhotoVersion` and `MotionPhotoPresentationTimestampUs` so a motion photo stays one; Clear writes a new packet from those properties alone, each checked against the value the format defines (a version, a Boolean, a Real or three, an integer, a timestamp that may be -1, an item semantic of `Primary`, `GainMap` or `MotionPhoto`, a MIME type of `image/jpeg`, `image/heic`, `image/avif`, `video/mp4` or `video/quicktime`, a length or padding), so no other property, attribute, nested structure or text survives; an item value outside those lists is dropped and the item keeps its place and length, a directory item may be written as `rdf:li` > `rdf:Description`, and a directory with an entry that holds no item is dropped whole; the first occurrence of a property wins, and the gain map's `Item:Length` follows its new length while later items such as a motion-photo video keep theirs. An Apple gain map of version 65536 (iPhone 12-14) has no headroom in its XMP: ImageIO and libultrahdr take it from the primary image's Apple maker note, tags 33 and 48. For such a file Clear writes a new Exif in the primary holding only those two maker-note values, copied as stored, and nothing else of the Exif: no IFD0, GPS or other Exif tag and no other maker-note tag. The values kept are the ones ImageIO applies, measured with every level duplicated and broken (where libultrahdr reads a file differently, Clear follows ImageIO): the first Exif segment, whose TIFF magic must be 42; at each level (IFD0's Exif IFD pointers, each Exif IFD's MakerNote entries, the maker note's 0x0021 and 0x0030 entries) an occurrence ImageIO cannot use is skipped and a later usable one overrides an earlier one, two Exif IFDs merging value by value; a maker-note value is usable when it is SRATIONAL with every value inside the maker note, at any offset; the headroom is kept only when both winning entries have count 1 (otherwise ImageIO renders no HDR image), and a winning MakerNote that is not Apple's keeps nothing. ImageIO then renders exactly what it rendered before, HDR or SDR; without the values it renders the photo SDR and libultrahdr refuses it. The new Exif is a minimal carrier for the two decode parameters, not a conformant Exif: it deliberately omits the tags Exif marks mandatory (ExifVersion, ComponentsConfiguration, ColorSpace, the pixel dimensions, YCbCrPositioning, the resolution tags), consistent with Clear removing all other Exif, so `exiftool -validate` warns about them; ImageIO, libultrahdr, ffmpeg, exiftool and TagLib# all read it), and the APP11 JPEG XT decoding boxes (`ftyp`, `TONE`, `RTRF`, `LTRF`, `LCHK`, `SPEC`, `RESI`); GIF graphic control and plain text extensions, looping and ICC application extensions. Everything else goes, including PNG text, `eXIf`, `tIME` and `caBX`, JPEG Exif (but for the Apple headroom above), the rest of XMP and extended XMP, IPTC, maker segments and every other APP11 box (JUMBF/C2PA, `xml `, `uuid`, `json`, `Exif`, unknown), and GIF XMP and ImageMagick's IPTC. In a multi-picture JPEG (MPF), Clear cleans every image the MPF index lists with the same rules; the index's offsets and sizes are rewritten after Clear and after an edit. An MP index outside its APP2 segment, or listing an image before the first image's end (its EOI), outside the file or overlapping another, is not followed: Clear is refused, and so is an edit that would move the later images. Apple's PNG `iDOT` is dropped when a chunk between it and the first IDAT changes. A field the format does not store reads back as null. EXIF, IPTC, and XMP values are not read yet, and SVG metadata is not read or written yet. #### Raw AAC (ADTS/ADIF) Support - `AacFile` reads and writes raw AAC files (`.aac`): ADTS (ISO/IEC 13818-7 §6.2, MPEG-2 and MPEG-4) and ADIF (§6.1) @@ -77,6 +78,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Changed +- An Exif field edit (Comment, Description, Copyright and the other stored fields) runs only when the Exif structure is plain. Otherwise it is refused, with the reason, and nothing is written. Clear is unchanged. A removed value that shares a protected byte, or a compaction that would rewrite any protected range other than the table itself, is refused. A strip, tile or thumbnail offset or length that is not SHORT or LONG, an array of those that does not lie wholly in the data, an array of those named more than once, a pair tag given twice in one table, a complete pair that names more values than half the bytes, a classic next-IFD field with one, two or three of its four bytes, or a first entry whose format would change whether exiftool reads the table, each refuse on their own. A wholly absent next field stays editable. A first-entry change that shows nothing new is still refused. +- A path save copies still-image pixels in a rented 64 KB buffer and writes the same bytes as `Render`. `SaveToFile(path)` and `SaveToFileAsync` do this for JPEG, PNG, GIF, BMP, PCX, Netpbm, TIFF, DNG, and SVG. `Render` still copies every other byte. - A path save copies the audio in a rented 64 KB buffer and writes the same bytes as `Render` (#20). `SaveToFile(path)` and `SaveToFileAsync` do this for Ogg Vorbis, Opus, and Ogg FLAC, MP3, native FLAC, ASF/WMA, raw AAC, MPEG program streams, Audible, Monkey's Audio, WavPack, Musepack, DSF (when the samples were left on disk), MP4 including a chapter edit, WAV, AIFF, AVI, Matroska, and DFF. `SaveToFile(path, span)`, `Render`, and `ReadFromFile` still build one buffer. The source is closed when the destination is never created. A render failure is returned before an already-cancelled token. - Matroska: `TotalTracks` and `TotalDiscs` follow the tagging spec. `TOTAL_PARTS` counts the parts of the first lower level ([tagging](https://www.matroska.org/technical/tagging.html)), so at 50 it is the album's track count and at 60 the set's disc count ([audio examples](https://www.matroska.org/technical/tagging-audio-example.html), "Collection of CD sets"). `Track` is `PART_NUMBER` at 30 and `DiscNumber` is `PART_NUMBER` at 50. ffmpeg's untargeted `PART_NUMBER` (read as the track), its `4/12` and `DISC=2/3` slash forms and its `TRACKTOTAL`/`DISCTOTAL` names are read as fallbacks; setting a total writes `TOTAL_PARTS` and removes them. A `TOTAL_PARTS` at 30 is read as the track total only when nothing else gives one, and is never written. - Matroska: TagLib writes the track total at 30 and the disc total at 50, against the spec. A TagLib-written file holding both totals now reads its disc total as `TotalTracks`, and TagLib reads a stored level 50 `TOTAL_PARTS` written here as its disc total, reads an untargeted one (what this library writes on ffmpeg files) as its track total, and does not read 60. This is a deliberate spec choice. @@ -97,6 +100,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed +- A path save that is cancelled while it writes the temp file no longer leaves that temp file beside the destination; the save fails with "Operation was cancelled" and the destination is left as it was. - MP4 `Genre` reads the legacy `gnre` atom (a 1-based ID3v1 code: 25 is Soundtrack, 99 Easy Listening, 74 Acid Punk) when `©gen` is empty (#123). Setting `Genre` writes `©gen` and removes `gnre`. - MP4 setters remove every atom their getter reads, so readers that show all of them (ffprobe joins them with `;`) show only the new value. Aliases read as a fallback and removed on set: `gnre` (Genre), `©cpy` (Copyright), `©com` (Composer) and `©swr` (EncoderSettings) from QuickTime user data, `titl`, `albm` and `dscp` (Title, Album, Description) as ExifTool reads them inside `ilst`, and `©st3` (Subtitle). `©aut`, `©inf`, `©des` and `grup` are not aliases and are kept. 3GPP's own `titl`/`albm`/`dscp` FullBoxes directly under `udta` are not read. - MP4 saves keep `ilst` children the library does not map (for example `orch`, `©ope`, `©url`, `stik`, `purd` and the iTunes Store ids), a malformed cover or freeform atom, and freeform names that contain `:` (such as the CDDB `UFID…` atom of iTunes rips). Before, a save dropped them, even with no edit. The meta's other children (`hdlr`, `keys`, `free` padding) are written back as their original bytes. diff --git a/README.md b/README.md index 22492f46..9a80433e 100644 --- a/README.md +++ b/README.md @@ -29,6 +29,7 @@ See the [Migration Guide](docs/MIGRATION-FROM-TAGLIB.md) for detailed comparison - MPEG program streams (`.mpg`, `.mpeg`, `.mpe`, `.vob`) and MPEG video elementary streams (`.mpv`, `.m1v`, `.m2v`): duration, MPEG-1/MPEG-2 video properties, and the first audio stream (MPEG audio, AC-3, LPCM). ID3v2 in front of the stream, an ID3v2.4 tag appended after it (the layout TagLib# writes), and ID3v1 are read and written in place; the stream bytes are not changed. - Audible `.aa`: the text dictionary (title, author, narrator, dates, descriptions, and every other key by name), the cover image, and the duration. Dictionary edits can be saved; the encrypted audio, its DRM keys, and the cover are copied unchanged. Edited files have been checked with ffprobe, ffmpeg, and ExifTool, not with Audible's own apps, which may check a digest the file stores (the purpose of the `68ec733412b9` key is unknown). Keep a copy of the original, or save to a new path. Audible `.aax` is MPEG-4 and opens as MP4/M4A, with its audiobook atoms (narrator, short and parent titles, product IDs, release date) as named properties. Decryption is out of scope. - AVI (`.avi`, including OpenDML): RIFF INFO and `ID32` (ID3v2) tags, duration, video size, frame rate and FourCC, and the first audio stream. Tags are saved without changing the `movi` sample data; every `idx1` and OpenDML index stays valid. INFO text follows the RIFF `CSET` chunk (ISO 8859-1 when there is none): 65001, 1252, 0 and 28591 are decoded, and with no `CSET` valid UTF-8 (what ffmpeg and TagLib# write) is read as UTF-8 and other text as Windows-1252. On save, a value you did not change keeps its exact bytes and the file keeps its `CSET`; changed values are written in the file's code page when they fit it (with no `CSET`, ASCII only), otherwise the list becomes UTF-8 with a `CSET` of code page 65001 before it, which ffprobe, TagLib# and exiftool read (mediainfo ignores `CSET`). When the list becomes UTF-8, untouched text in a declared code page that is decoded exactly (1252, 28591, 0) is rewritten as the same text in UTF-8; the save is refused, with an error naming the field and the reason, when an untouched value's code page is only a guess (no `CSET`), is not decoded here (Shift-JIS, cp1251, ...), or the value holds a byte its declared code page leaves undefined (0x81, 0x8D, 0x8F, 0x90, 0x9D in 1252; 0x80-0x9F under code page 0). The new `CSET` keeps the old one's country, language and dialect codes. The five undefined 1252 code points are written as UTF-8, never as 1252 bytes. A save loads the whole file into memory (about one file's worth when nothing moves, two when the data has to move), so AVI files of 2 GiB or more cannot be saved yet; reading has no such limit. + - Still images: JPEG, PNG, GIF, BMP, PCX, Netpbm (`.pbm`, `.pgm`, `.ppm`, `.pnm`), TIFF, DNG, and SVG open through `MediaFile.Read` or `StillImageFile.ReadFromFile` with width and height. PNG text, the GIF comment, and the JPEG COM marker can be edited; a PNG edit also updates the XMP and Exif copies of the field. Other image metadata is not read or written yet. ## Format Support Matrix diff --git a/docs/IMPLEMENTATION-GUIDE.md b/docs/IMPLEMENTATION-GUIDE.md index a1b1b91d..f9e5148a 100644 --- a/docs/IMPLEMENTATION-GUIDE.md +++ b/docs/IMPLEMENTATION-GUIDE.md @@ -134,6 +134,16 @@ how it was broken before. - **Fields the format requires** are kept: the Vorbis comment vendor string, which the header must carry (Xiph Vorbis comment, "vendor_length / vendor_string"), and Matroska's mandatory `MuxingApp` and `WritingApp` (RFC 9559). + - **Segments a decoder or colour management needs, or that carry the file's structure**, are kept: in + still images, JPEG APP0 JFIF/JFXX, APP2 ICC_PROFILE, APP2 MPF (the multi-picture index; its offsets and + sizes are rewritten, and Clear cleans every image it lists), APP2 ISO 21496-1 (gain map), APP14 Adobe + (colour transform), the gain-map XMP properties an HDR decoder needs (Ultra HDR `hdrgm` and the + `Container`/`Item` directory with only the item values the formats enumerate, Apple `apdi` and `HDRGainMap` version and headroom, motion-photo `Camera` flags, each with the value shape its format defines, written into a new packet; nothing of the original packet is copied.) and, for a version-65536 Apple gain map, a new Exif holding only Apple maker-note tags 33 and 48 (the headroom ImageIO and libultrahdr compute from them; decode parameters, no personal data; when an Exif repeats a pointer, a MakerNote or a tag, the values kept are the ones ImageIO applies (`AppleHeadroom.Keep`); nothing else of the Exif is kept, so it is a minimal carrier that omits Exif's mandatory format tags and `exiftool -validate` warns, while every tested reader reads it), and the APP11 JPEG + XT decoding boxes named in public sources (`ftyp`, `TONE`, `RTRF`, `LTRF`, `LCHK`, `SPEC`, `RESI`); PNG critical chunks and the decode/colour chunks (tRNS, gAMA, cHRM, sRGB, iCCP, cICP, mDCV, cLLI, + sBIT, bKGD, hIST, pHYs, sPLT, the APNG chunks, oFFs, pCAL, sCAL, sTER); GIF graphic control and plain text + extensions, NETSCAPE2.0/ANIMEXTS1.0 looping and ICCRGBG1012. Everything else goes, including C2PA + manifests (PNG caBX, JPEG APP11 JUMBF), which any edit invalidates, every other APP11 box (`xml `, + `uuid`, `json`, `Exif` and unknown ones carry metadata), and unknown APPn, chunks and extensions. - **Chapters** are file structure, not tag metadata. A tag `Clear()` keeps them in Matroska and in MP4 (checked on main: ffprobe lists the same chapters after a Clear and a save). Use the chapter API to remove them. @@ -240,6 +250,8 @@ A fix is new code, so steps (b) to (e) apply to it in full. | `Bounds.AllocatedBytes (action)` | Bytes allocated on this thread while `action` runs. Synchronous code only. | | `Bounds.AssertAllocatesAtMost (limit, action)` | Fails with the count when a parse allocates past a bound. | | `Bounds.AssertLinearAllocation (build, run, n)` | Measures n, 2n and 4n, and fails when the second increment is more than 3× the first (linear work is 2×). This catches quadratic copies even behind a fixed cost. | +| `Bounds.LeastAllocated (action)` | The least bytes `action` allocates after one warm-up, so a single noisy run does not set the bound. | +| `Bytes.Count (data, needle)` | How many times a byte sequence occurs in `data`, including overlaps. | | `CountingStream` | Counts bytes read, reads and seeks, to pin that a stream path reads only what it needs. | | `Hostile.EveryTruncation (valid, read)` | Runs every prefix through `read`, then reports how many threw and the first lengths. | | `Hostile.ByteFlips (valid, read)` | Changes each byte to 0x00 and 0xFF and XORs it with 0x01 and 0x80, reporting the offset and value of each throw. `values:` sets the replacement values. | diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index 79b8da97..41e6e98d 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -2,11 +2,11 @@ > Generated: January 2026 > Last Updated: November 2026 -> Status: Production ready - 18 formats read and write tags, polish phase +> Status: Production ready - audio and video formats read and write tags; still images open with dimensions, polish phase ## Executive Summary -TagLibSharp2 currently supports **18 formats** with read and write. The library has mature read/write capabilities for all major formats. Remaining gaps are niche formats: Speex (obsolete), TrueAudio (niche), and tracker formats (demoscene). A path save copies the audio in 64 KB pieces instead of loading the file. `Render` and a save from a span still build one buffer. +TagLibSharp2 reads and writes tags for the audio and video formats below. JPEG, PNG, GIF, BMP, PCX, Netpbm, TIFF, DNG, and SVG open with width and height. PNG text keywords, the GIF comment, and the JPEG COM marker can be edited. A field edit also removes that field's Exif copies when the Exif structure is plain, and updates the matching XMP property; any other Exif structure is refused and nothing is written. Exif values are not read into the tag. IPTC is not read or written, and SVG metadata is not read or written yet. Remaining audio gaps are niche formats: Speex (obsolete), TrueAudio (niche), and tracker formats (demoscene). Matroska/WebM saves tag values, chapters, and picture attachments. A path save copies the audio in 64 KB pieces instead of loading the file. `Render` and a save from a span still build one buffer. --- @@ -31,6 +31,7 @@ TagLibSharp2 currently supports **18 formats** with read and write. The library | Matroska/WebM | P2 | ✅ | ✅ | ✅ | - | Tag values, chapters, picture attachments, and track enabled flags are saved. Other attachments are preserved, not rewritten | | MPEG PS / video ES | P2 | ✅ | ✅ | ✅ | - | ID3v2 and ID3v1 around the stream; duration from PTS or GOP time codes | | AVI (incl. OpenDML) | P2 | ✅ | ✅ | ✅ | - | RIFF INFO and ID32 tags; movi and every index kept valid. A path save copies movi in 64 KB pieces | +| JPEG, PNG, GIF, BMP, PCX, Netpbm, TIFF, DNG, SVG | P2 | ✅ | Dimensions | PNG text, GIF comment, JPEG COM, plain Exif removal, matching XMP | - | A path save copies pixels in 64 KB pieces. Render still copies every other byte. A field edit removes Exif copies only when the structure is plain, and refuses otherwise. IPTC is not read or written. SVG metadata is not read or written yet | | Ogg FLAC | P1 | ✅ | ✅ | ✅ | - | Recently added | | AAC (ADTS/ADIF) | P1 | ✅ | ✅ | ✅ | - | ID3v2, APEv2, ID3v1 tags | | Speex | P1 | ❌ | ❌ | ❌ | LOW | Uses Vorbis Comment | diff --git a/src/TagLibSharp2/Core/AtomicFileWriter.cs b/src/TagLibSharp2/Core/AtomicFileWriter.cs index 1a0e733a..251061bc 100644 --- a/src/TagLibSharp2/Core/AtomicFileWriter.cs +++ b/src/TagLibSharp2/Core/AtomicFileWriter.cs @@ -186,6 +186,10 @@ internal static FileWriteResult WriteStream (string path, IFileSystem? fileSyste destinationExisted = fileSystem.FileExists (path); fileSystem.Move (tempPath, path); return FileWriteResult.Success (ReportedBytes (bytesWritten)); + } catch (OperationCanceledException) { + if (tempPath is not null) + CleanupTempFile (tempPath, fileSystem); + return FileWriteResult.Failure ("Operation was cancelled"); } catch (EndOfStreamException ex) { return FailWrite ( tempPath, diff --git a/src/TagLibSharp2/Core/BinaryData.cs b/src/TagLibSharp2/Core/BinaryData.cs index 681c28cc..9ac2e037 100644 --- a/src/TagLibSharp2/Core/BinaryData.cs +++ b/src/TagLibSharp2/Core/BinaryData.cs @@ -979,11 +979,16 @@ static ushort[] BuildCrc16CcittTable () /// Computes CRC-32 using the standard polynomial (0xEDB88320). /// This is compatible with zlib/PNG CRC. /// - public uint ComputeCrc32 () + public uint ComputeCrc32 () => ComputeCrc32 (Data); + + /// + /// Computes CRC-32 over without copying it. + /// + internal static uint ComputeCrc32 (ReadOnlySpan data) { var crc = 0xFFFFFFFF; - for (var i = 0; i < Data.Length; i++) - crc = Crc32Table[(crc ^ Data[i]) & 0xFF] ^ (crc >> 8); + for (var i = 0; i < data.Length; i++) + crc = Crc32Table[(crc ^ data[i]) & 0xFF] ^ (crc >> 8); return ~crc; } diff --git a/src/TagLibSharp2/Core/MediaFile.cs b/src/TagLibSharp2/Core/MediaFile.cs index 801afa0d..19288e6a 100644 --- a/src/TagLibSharp2/Core/MediaFile.cs +++ b/src/TagLibSharp2/Core/MediaFile.cs @@ -2,6 +2,7 @@ // Licensed under the MIT License. See LICENSE file in the project root for full license information. using System.Buffers.Binary; +using System.Runtime.InteropServices; using TagLibSharp2.Aac; using TagLibSharp2.Aiff; using TagLibSharp2.Ape; @@ -9,6 +10,7 @@ using TagLibSharp2.Audible; using TagLibSharp2.Dff; using TagLibSharp2.Dsf; +using TagLibSharp2.Image; using TagLibSharp2.Matroska; using TagLibSharp2.Mp4; using TagLibSharp2.Mpeg; @@ -416,6 +418,9 @@ static async Task ReadAsync ( MediaFormat.MpegPs => FromMpegPs (await MpegPsFile.ReadAsync (stream, sourcePath, fileSystem, cancellationToken).ConfigureAwait (false)), MediaFormat.Audible => FromAudible (await AudibleFile.ReadAsync (stream, sourcePath, fileSystem, cancellationToken).ConfigureAwait (false)), MediaFormat.Avi => FromAvi (await AviFile.ReadAsync (stream, sourcePath, fileSystem, cancellationToken).ConfigureAwait (false)), + MediaFormat.Jpeg or MediaFormat.Png or MediaFormat.Gif or MediaFormat.Bmp or MediaFormat.Pcx + or MediaFormat.Netpbm or MediaFormat.Tiff or MediaFormat.Dng or MediaFormat.Svg + => OpenImage (await StreamBytes.ReadToEndAsync (stream, cancellationToken).ConfigureAwait (false), format), _ => OpenDetected (format, stream, sourcePath, fileSystem, pathHint) }; return RememberMatroskaSource (result, sourcePath, fileSystem); @@ -445,11 +450,15 @@ static MediaFileResult OpenDetected (MediaFormat format, Stream stream, string? _ => ReadFromData (StreamBytes.ReadToEnd (stream), pathHint) }; - // ReadFromData's path is only an extension hint. A path read can save Matroska back to that file. + // ReadFromData's path is only an extension hint. A path read can save Matroska and still images back to that file. static MediaFileResult RememberMatroskaSource (MediaFileResult result, string? sourcePath, IFileSystem? fileSystem) { - if (sourcePath is not null && result.IsSuccess && result.File is MatroskaFile matroska) + if (sourcePath is null || !result.IsSuccess) + return result; + if (result.File is MatroskaFile matroska) matroska.SetSourcePath (sourcePath, fileSystem); + else if (result.File is StillImageFile image) + image.SetSource (sourcePath, fileSystem); return result; } @@ -627,6 +636,8 @@ static MediaFileResult ReadCore (ReadOnlyMemory data, string? pathHint) MediaFormat.Aac => FromAac (AacFile.Read (data)), MediaFormat.Audible => FromAudible (AudibleFile.Read (data.Span)), MediaFormat.Avi => FromAvi (AviFile.Read (data.Span)), + MediaFormat.Jpeg or MediaFormat.Png or MediaFormat.Gif or MediaFormat.Bmp or MediaFormat.Pcx + or MediaFormat.Netpbm or MediaFormat.Tiff or MediaFormat.Dng or MediaFormat.Svg => OpenImage (data, format), _ => MediaFileResult.Failure ($"Unknown or unsupported file format{(pathHint is not null ? $": {pathHint}" : "")}") }; @@ -751,6 +762,11 @@ static MediaFormat DetectFormat (ReadOnlySpan data, string? pathHint, Stre if (MpegFrame.IsStartOfAudio (data)) return MediaFormat.Mp3; + // After the audio signatures. A markup check that decoded every unknown buffer + // would copy an MP3, an ID3 tag, or an ASF header on the way to "not an image". + if (data.Length >= 4 && ImageHeader.TryDetect (data, out var image)) + return image == MediaFormat.Tiff && StillImageFile.HasDngName (pathHint) ? MediaFormat.Dng : image; + // Fall back to extension if (!string.IsNullOrEmpty (pathHint)) { var ext = Path.GetExtension (pathHint).ToUpperInvariant (); @@ -774,6 +790,15 @@ static MediaFormat DetectFormat (ReadOnlySpan data, string? pathHint, Stre ".MPG" or ".MPEG" or ".MPE" or ".VOB" or ".MPV" or ".M1V" or ".M2V" => MediaFormat.MpegPs, ".AAC" => MediaFormat.Aac, ".AVI" => MediaFormat.Avi, + ".JPG" or ".JPEG" or ".JPE" => MediaFormat.Jpeg, + ".PNG" => MediaFormat.Png, + ".GIF" => MediaFormat.Gif, + ".BMP" or ".DIB" => MediaFormat.Bmp, + ".PCX" => MediaFormat.Pcx, + ".PBM" or ".PGM" or ".PPM" or ".PNM" => MediaFormat.Netpbm, + ".TIF" or ".TIFF" => MediaFormat.Tiff, + ".DNG" => MediaFormat.Dng, + ".SVG" => MediaFormat.Svg, _ => MediaFormat.Unknown }; } @@ -950,6 +975,28 @@ static MediaFileResult OpenMonkeysAudio (ReadOnlyMemory data) return MediaFileResult.Success (result.File!, result.File!.ApeTag, MediaFormat.MonkeysAudio); } + static MediaFileResult OpenImage (ReadOnlyMemory data, MediaFormat format) + { + var opened = StillImageFile.Open (OwnedBytes (data), format); + return opened.IsSuccess + ? MediaFileResult.Success (opened.File!, opened.File!.Tag, format) + : MediaFileResult.Failure (opened.Error!); + } + + // Reuse the array behind a memory that already owns the whole buffer. A slice is copied. + static byte[] OwnedBytes (ReadOnlyMemory data) + { + if (MemoryMarshal.TryGetArray (data, out ArraySegment segment) + && segment.Array is byte[] array + && segment.Offset == 0 + && segment.Count == array.Length + && data.Length == array.Length) + return array; + + return data.ToArray (); + } + + static MediaFileResult OpenAsf (ReadOnlyMemory data) { var result = AsfFile.Read (data.Span); @@ -1141,5 +1188,32 @@ public enum MediaFormat /// /// AVI (RIFF AVI form, including OpenDML). /// - Avi + Avi, + + /// JPEG still image. + Jpeg, + + /// PNG still image. + Png, + + /// GIF still image. + Gif, + + /// BMP still image. + Bmp, + + /// PCX still image. + Pcx, + + /// Netpbm raster (PBM, PGM, PPM, or PNM). + Netpbm, + + /// TIFF still image. + Tiff, + + /// DNG, a TIFF file with the DNG version tag or a .dng name. + Dng, + + /// SVG image. + Svg } diff --git a/src/TagLibSharp2/Core/Tag.cs b/src/TagLibSharp2/Core/Tag.cs index d168fdb0..202aae56 100644 --- a/src/TagLibSharp2/Core/Tag.cs +++ b/src/TagLibSharp2/Core/Tag.cs @@ -72,6 +72,11 @@ public enum TagTypes /// Audible = 1 << 10, + /// + /// Text stored in a still image: PNG keywords, a GIF comment, or a JPEG COM marker. + /// + Image = 1 << 11, + /// /// All tag types. /// diff --git a/src/TagLibSharp2/Image/Endian.cs b/src/TagLibSharp2/Image/Endian.cs new file mode 100644 index 00000000..a64ecbad --- /dev/null +++ b/src/TagLibSharp2/Image/Endian.cs @@ -0,0 +1,51 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Buffers.Binary; + +namespace TagLibSharp2.Image; + +/// +/// Reads and writes unsigned integers in either byte order over spans: the one byte-order helper of the image +/// code (TIFF and Exif "II"/"MM", the MPF index, PNG chunk fields, BMP headers). +/// +static class Endian +{ + public static int U16 (ReadOnlySpan data, int at, bool le) => + le ? BinaryPrimitives.ReadUInt16LittleEndian (data.Slice (at)) : BinaryPrimitives.ReadUInt16BigEndian (data.Slice (at)); + + public static long U32 (ReadOnlySpan data, int at, bool le) => + le ? BinaryPrimitives.ReadUInt32LittleEndian (data.Slice (at)) : BinaryPrimitives.ReadUInt32BigEndian (data.Slice (at)); + + public static int I32 (ReadOnlySpan data, int at, bool le) => + le ? BinaryPrimitives.ReadInt32LittleEndian (data.Slice (at)) : BinaryPrimitives.ReadInt32BigEndian (data.Slice (at)); + + /// False outside the data, or for a value above . + public static bool TryU64 (ReadOnlySpan data, int at, bool le, out long value) + { + value = 0; + if (at < 0 || at > data.Length - 8) + return false; + var raw = le ? BinaryPrimitives.ReadUInt64LittleEndian (data.Slice (at)) : BinaryPrimitives.ReadUInt64BigEndian (data.Slice (at)); + if (raw > long.MaxValue) + return false; + value = (long)raw; + return true; + } + + public static void WriteU16 (Span data, int at, int value, bool le) + { + if (le) + BinaryPrimitives.WriteUInt16LittleEndian (data.Slice (at), (ushort)value); + else + BinaryPrimitives.WriteUInt16BigEndian (data.Slice (at), (ushort)value); + } + + public static void WriteU32 (Span data, int at, long value, bool le) + { + if (le) + BinaryPrimitives.WriteUInt32LittleEndian (data.Slice (at), (uint)value); + else + BinaryPrimitives.WriteUInt32BigEndian (data.Slice (at), (uint)value); + } +} diff --git a/src/TagLibSharp2/Image/Exif/AppleHeadroom.cs b/src/TagLibSharp2/Image/Exif/AppleHeadroom.cs new file mode 100644 index 00000000..719462d0 --- /dev/null +++ b/src/TagLibSharp2/Image/Exif/AppleHeadroom.cs @@ -0,0 +1,231 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using TagLibSharp2.Image.Tiff; + +namespace TagLibSharp2.Image.Exif; + +/// +/// The HDR headroom a version-65536 Apple gain map takes from the primary image's Apple maker note, and the minimal +/// Exif that keeps it after Clear. +/// +static class AppleHeadroom +{ + const int MakerNoteTag = 0x927C; + const int HeadroomTag = 0x0021; + const int GainTag = 0x0030; + const int SRationalType = 10; + + static ReadOnlySpan MakerNoteHeader => "Apple iOS\0\0\u0001MM"u8; + + /// + /// The Exif a version-65536 Apple gain map needs after Clear: a big-endian TIFF with IFD0 -> Exif IFD -> + /// MakerNote, and in the Apple maker note only tags 0x0021 and 0x0030, copied as stored. Null when the + /// values ImageIO would apply are not both there as one SRATIONAL each. + /// + /// + /// Apple, "Applying Apple HDR effect to your photos" + /// (https://developer.apple.com/documentation/appkit/applying-apple-hdr-effect-to-your-photos): a gain map + /// whose metadata has HDRGainMapVersion takes its headroom from the MakerNote keys 33 and 48. + /// They are decode parameters, not personal data. The maker note (Exif 2.32 §4.6.5, tag 0x927C, UNDEFINED) + /// starts "Apple iOS", NUL, version 1, "MM", then a big-endian IFD whose value offsets count from the start of + /// the maker note. + /// TIFF 6.0 does not say which of two entries with one tag wins, or what a reader does with one it cannot + /// use, so the values kept are the ones ImageIO applies, measured on ImageIO-written files with every level + /// duplicated and broken. Where libultrahdr differs, this follows ImageIO, Apple's decoder for Apple's format. + /// At every level an occurrence that cannot be used is skipped and a later usable one overrides an earlier one: + /// + /// IFD0 0x8769 (Exif IFD pointer): usable when LONG or IFD, count 1, and its table lies inside the data. + /// Two Exif IFDs merge tag by tag: a later one's maker-note value replaces an earlier one's, and a later Exif + /// IFD without one leaves the earlier one's (libultrahdr reads only the first pointer and refuses the file + /// when that one is out of range); + /// Exif IFD 0x927C (MakerNote): usable when UNDEFINED, more than 4 bytes, inside the data, and either not + /// an Apple maker note (it then wins with no values, so nothing is kept) or one whose header is exactly as above + /// and whose entry table fits; an Apple maker note with another header or a table that does not fit is skipped. + /// The last usable one of an Exif IFD is that IFD's maker note, whole (libultrahdr reads the first); + /// maker-note 0x0021 and 0x0030: usable when SRATIONAL, count at least 1 and the 8 bytes of each value + /// inside the maker note, at any offset (its header and entry table included). The last usable one of each tag + /// wins. When a winner's count is not 1 ImageIO renders no HDR image at all, so nothing is kept (libultrahdr + /// reads the first value regardless of the count, and refuses a value outside the maker note). + /// + /// The Exif segment is the first one (both decoders use the first), and its TIFF header must carry the magic 42 + /// (ImageIO ignores an Exif without it). + /// The result is a minimal carrier for the two decode parameters, not a conformant Exif: it deliberately + /// omits the tags Exif marks mandatory (ExifVersion, ComponentsConfiguration, ColorSpace, the pixel dimensions, + /// YCbCrPositioning and the resolution tags, CIPA DC-008 §4.6.8), consistent with Clear removing all other + /// Exif, so exiftool -validate warns about them. ImageIO, libultrahdr, ffmpeg, exiftool and TagLib# read + /// it. + /// Each distinct Exif IFD and maker note is walked once, from the last, and every entry visit is counted + /// in ; the entries walked are bounded by the data (tables that overlap past it keep + /// nothing); nothing recurses and nothing throws. + /// + internal static byte[]? Keep (ReadOnlySpan data) + { + // A header that is not classic TIFF (byte order and magic 42) keeps nothing: ImageIO ignores that Exif. + if (!TiffReader.TryClassic (data, out var tiff, out var ifd0) || !tiff.TryTable (ifd0, out var ifd0Count)) + return null; + var pointers = ExifIfdPointers (tiff, ifd0, ifd0Count); + var (headroom, gain) = FindWinners (tiff, pointers); + if (headroom.Count != 1 || gain.Count != 1) + return null; + return HeadroomTiff (data.Slice ((int)headroom.At, 8), data.Slice ((int)gain.At, 8)); + } + + // The last usable entry of a tag: its value's offset in the TIFF and its count (0 when there is none). + readonly record struct Winner (long At, long Count) + { + public bool Found => Count > 0; + } + + // Later Exif IFDs override earlier ones tag by tag: walking from the last, the first value found for a tag is + // the one that wins, and an Exif IFD seen again adds nothing. The walk stops when both are found, or when the + // entries walked pass the bound of one per 12 bytes (tables that overlap past it keep nothing: every value needs a + // maker note entry, so none can be found past the bound). + static (Winner Headroom, Winner Gain) FindWinners (TiffReader tiff, CountedList pointers) + { + var (headroom, gain) = (default (Winner), default (Winner)); + var budget = tiff.EntryBound; + var seen = new HashSet (); + for (var p = pointers.Count - 1; p >= 0 && (!headroom.Found || !gain.Found); p--) { + var ifd = pointers[p]; + if (!seen.Add (ifd)) + continue; + _ = tiff.TryTable (ifd, out var count); + budget -= count; + var found = ReadMakerNote (tiff, ifd, count, ref budget); + if (budget < 0) + return (default (Winner), default (Winner)); + if (!headroom.Found) + headroom = found.Headroom; + if (!gain.Found) + gain = found.Gain; + } + + return (headroom, gain); + } + + // The headroom entries of an Exif IFD's Apple maker note, with offsets in the TIFF (none when its maker note is + // not Apple's); its entries are taken from the budget. + static (Winner Headroom, Winner Gain) ReadMakerNote (TiffReader tiff, long ifd, int count, ref long budget) + { + // A usable maker note that starts with Apple's header has an entry table that fits (IsUsable). + if (LastMakerNote (tiff, ifd, count) is not var (noteAt, noteSize)) + return default; + var note = tiff.Data.Slice ((int)noteAt, (int)noteSize); + if (!note.StartsWith (MakerNoteHeader)) + return default; + // The entry count IsUsable already required to fit. It is the same count the maker-note walk reads. + var noteReader = new TiffReader (note, littleEndian: false); + if (!noteReader.TryTable (MakerNoteHeader.Length, out var entries)) + return default; + budget -= entries; + var (headroom, gain) = HeadroomEntries (noteReader); + return (headroom with { At = noteAt + headroom.At }, gain with { At = noteAt + gain.At }); + } + + // The Exif IFD pointers ImageIO follows: LONG or IFD, count 1, a table inside the data; in IFD0 order. + static CountedList ExifIfdPointers (TiffReader tiff, long ifd0, int ifd0Count) + { + var pointers = new CountedList (); + for (var n = 0; n < ifd0Count; n++) { + IfdSteps.Count++; + var entry = tiff.Entry (ifd0, n); + if (tiff.Tag (entry) != TiffReader.ExifIfdPointer || tiff.Type (entry) is not (4 or 13) || tiff.Count (entry) != 1) + continue; + var at = tiff.Value (entry); + if (tiff.TryTable (at, out _)) + pointers.Add (at); + } + + return pointers; + } + + // The maker note of an Exif IFD as ImageIO takes it: the last usable 0x927C entry (UNDEFINED, more than 4 + // bytes, inside the data; an Apple maker note only with its exact header and a table that fits), or null. + static (long At, long Size)? LastMakerNote (TiffReader tiff, long ifd, int count) + { + (long At, long Size)? note = null; + for (var n = 0; n < count; n++) { + IfdSteps.Count++; + var entry = tiff.Entry (ifd, n); + if (tiff.Tag (entry) != MakerNoteTag || tiff.Type (entry) != 7) + continue; + var size = tiff.Count (entry); + var at = tiff.Value (entry); + if (size <= 4 || size > tiff.Length - at) + continue; + if (IsUsable (tiff.Data.Slice ((int)at, (int)size))) + note = (at, size); + } + + return note; + } + + // Another maker note is usable as it is; an Apple one only with its exact header and an entry table that fits. + // The maker note is a big-endian IFD at offset 14 of its own bytes (14 is past the classic header). + static bool IsUsable (ReadOnlySpan bytes) + { + if (!bytes.StartsWith (MakerNoteHeader.Slice (0, 10))) + return true; + if (!bytes.StartsWith (MakerNoteHeader)) + return false; + return new TiffReader (bytes, littleEndian: false).TryTable (MakerNoteHeader.Length, out _); + } + + // The last usable 0x0021 and 0x0030 entries of an Apple maker note: SRATIONAL, count at least 1, every value + // inside the maker note (any offset). Offsets count from the maker note. The IFD is the one TiffReader reads. + static (Winner Headroom, Winner Gain) HeadroomEntries (TiffReader tiff) + { + if (!tiff.TryTable (MakerNoteHeader.Length, out var count)) + return default; + var (headroom, gain) = (default (Winner), default (Winner)); + for (var n = 0; n < count; n++) { + IfdSteps.Count++; + var entry = tiff.Entry (MakerNoteHeader.Length, n); + var tag = tiff.Tag (entry); + if ((tag != HeadroomTag && tag != GainTag) || tiff.Type (entry) != SRationalType) + continue; + var values = tiff.Count (entry); + var offset = tiff.Value (entry); + if (values == 0 || values > (tiff.Length - offset) / 8) + continue; + if (tag == HeadroomTag) + headroom = new Winner (offset, values); + else + gain = new Winner (offset, values); + } + + return (headroom, gain); + } + + // TIFF header, IFD0 at 8 (the Exif IFD pointer), the Exif IFD at 26 (the maker note), the maker note at 44: + // its header, two entries, a zero next-IFD offset, and the two values at 44 and 52 of the maker note. + static byte[] HeadroomTiff (ReadOnlySpan headroom, ReadOnlySpan gain) + { + const int ExifAt = 26; + const int NoteAt = 44; + const int NoteLength = 14 + 2 + 24 + 4 + 16; + var output = new byte[NoteAt + NoteLength]; + "MM\0*"u8.CopyTo (output); + Endian.WriteU32 (output, 4, 8, le: false); + Endian.WriteU16 (output, 8, 1, le: false); + WriteEntry (output, 10, TiffReader.ExifIfdPointer, 4, 1, ExifAt); + Endian.WriteU16 (output, ExifAt, 1, le: false); + WriteEntry (output, ExifAt + 2, MakerNoteTag, 7, NoteLength, NoteAt); + MakerNoteHeader.CopyTo (output.AsSpan (NoteAt)); + Endian.WriteU16 (output, NoteAt + 14, 2, le: false); + WriteEntry (output, NoteAt + 16, HeadroomTag, SRationalType, 1, 44); + WriteEntry (output, NoteAt + 28, GainTag, SRationalType, 1, 52); + headroom.CopyTo (output.AsSpan (NoteAt + 44)); + gain.CopyTo (output.AsSpan (NoteAt + 52)); + return output; + + static void WriteEntry (byte[] data, int at, int tag, int type, int count, int value) + { + Endian.WriteU16 (data, at, tag, le: false); + Endian.WriteU16 (data, at + 2, type, le: false); + Endian.WriteU32 (data, at + 4, count, le: false); + Endian.WriteU32 (data, at + 8, value, le: false); + } + } +} diff --git a/src/TagLibSharp2/Image/Exif/ByteRanges.cs b/src/TagLibSharp2/Image/Exif/ByteRanges.cs new file mode 100644 index 00000000..4b07ba6d --- /dev/null +++ b/src/TagLibSharp2/Image/Exif/ByteRanges.cs @@ -0,0 +1,50 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using TagLibSharp2.Image.Tiff; + +namespace TagLibSharp2.Image.Exif; + +/// Sorted, merged byte ranges and the overlap test the Exif removal uses on them. +static class ByteRanges +{ + public static CountedList<(long Start, long End)> Merge (CountedList<(long Start, long End)> ranges) + { + ranges.Sort ((a, b) => a.Start.CompareTo (b.Start)); + var merged = new CountedList<(long Start, long End)> (); + for (var n = 0; n < ranges.Count; n++) { + var range = ranges[n]; + if (range.End <= range.Start) + continue; + if (merged.Count > 0 && range.Start <= merged[merged.Count - 1].End) + merged[merged.Count - 1] = (merged[merged.Count - 1].Start, Math.Max (merged[merged.Count - 1].End, range.End)); + else + merged.Add (range); + } + + return merged; + } + + /// The first range whose end is past , or sorted.Count when none is. + public static int FirstEndingAfter (CountedList<(long Start, long End)> sorted, long start) + { + int low = 0, high = sorted.Count; + while (low < high) { + IfdSteps.Count++; + var mid = low + ((high - low) / 2); + if (sorted[mid].End <= start) + low = mid + 1; + else + high = mid; + } + + return low; + } + + // The merged ranges are disjoint and sorted, so their ends are sorted too. + public static bool Overlaps (CountedList<(long Start, long End)> merged, (long Start, long End) range) + { + var low = FirstEndingAfter (merged, range.Start); + return low < merged.Count && merged[low].Start < range.End; + } +} diff --git a/src/TagLibSharp2/Image/Exif/ExifCarrier.cs b/src/TagLibSharp2/Image/Exif/ExifCarrier.cs new file mode 100644 index 00000000..32dab3d6 --- /dev/null +++ b/src/TagLibSharp2/Image/Exif/ExifCarrier.cs @@ -0,0 +1,33 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +namespace TagLibSharp2.Image.Exif; + +/// +/// A block that holds an Exif TIFF: a JPEG APP1 segment, a PNG eXIf chunk, or an ImageMagick raw EXIF profile. +/// Each may start with the "Exif\0\0" signature (CIPA DC-008 §4.7.2); the edited TIFF is wrapped back the way the +/// block stores it, so never depends on the format. +/// +/// Names the block in a refusal, such as "eXIf". +/// Builds the block's new bytes around the edited TIFF (with its signature, when it had one). +sealed class ExifCarrier (string name, Func wrap) +{ + public string Name { get; } = name; + + /// Removes the changed fields' copies from the TIFF in . + /// The Exif bytes, with or without the signature. + /// The tag whose changed fields are removed. + /// The block's new bytes, or null when nothing changed. + /// Why the copy cannot be updated. + public bool TryEdit (ReadOnlySpan block, ImageTag tag, out byte[]? rewritten, out string? error) + { + rewritten = null; + var exif = block.ToArray (); + var start = block.StartsWith ("Exif\0\0"u8) ? 6 : 0; + if (!ExifEditor.TryRemove (exif, start, tag, Name, out var changed, out error)) + return false; + if (changed) + rewritten = wrap (exif); + return true; + } +} diff --git a/src/TagLibSharp2/Image/Exif/ExifEditor.cs b/src/TagLibSharp2/Image/Exif/ExifEditor.cs new file mode 100644 index 00000000..67a6b1a6 --- /dev/null +++ b/src/TagLibSharp2/Image/Exif/ExifEditor.cs @@ -0,0 +1,216 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using TagLibSharp2.Image.Tiff; + +namespace TagLibSharp2.Image.Exif; + +/// +/// Removes each changed field's Exif entries (all its tags) from every table exiftool reads with its Exif tags: +/// IFD0 and the chain of IFDs after it, and every Exif IFD (0x8769), SubIFD (0x014A) and interoperability IFD +/// (0xA005) any of those points at, however deep, each pointer decoded as exiftool decodes it +/// (, ; ImageIO reads a subset), and the Exif IFD that +/// IFD0's 0x8769 field names read as a LONG whatever its type and count, as TagLib# reads it. GPS tables are +/// read with GPS tags and left as they are. Each table is walked once. The entry table shrinks in place, so no offset +/// moves. A field edit runs only when calls the structure plain and +/// agrees. Anything else is refused and nothing is written. +/// +/// +/// A field edit is refused when a removed value shares a protected byte, or when compacting a table would rewrite +/// any protected range other than that table. Two protected ranges may share a byte; zeroing does not touch them. +/// A pair given twice is not plain, and only the plainness check decides that. Skipping that check still applies +/// the edit from the first of each pair. The plan's value-budget stop stays, so a skipped check cannot read every +/// offset past half the bytes. +/// +static class ExifEditor +{ + /// Compacting the edited tables would rewrite a protected range. + internal const string StructureWouldChange = "has IFD structure that removing the copy would change"; + + /// Two IFD tables share a byte, so neither can be compacted. + internal const string TablesOverlap = "has IFD tables that overlap each other"; + + /// A SubIFD offset array lies in a table the edit rewrites. + internal const string SubIfdInsideTable = "has SubIFD offsets inside an IFD table"; + + /// A kept value lies in a table the edit rewrites. + internal const string ValueInsideTable = "has a value inside an IFD table that the edit rewrites"; + + /// An IFD pointer names the middle of another table. + internal const string PointerIntoTable = "has an IFD pointer into the middle of another IFD table"; + + /// Set by tests to see the edit an unchecked removal would make (the matrix judges refusals by it). + [ThreadStatic] + internal static bool SkipCheck; + + /// Removes the changed fields' entries from the TIFF at , in place. + /// + /// False, with an error and nothing written, when the block is not classic TIFF or its tables overlap past the + /// bound that keeps the walk linear, and its bytes could hold an entry with one of the fields' tags; and when + /// something is to be removed from structure that is not plain or not clean. + /// + internal static bool TryRemove (byte[] block, int start, ImageTag tag, string carrier, out bool changed, out string? error) + { + changed = false; + error = null; + if (!TryRequest (tag, out var tags, out var what)) + return true; + var data = block.AsSpan (start); + + // Refused, not skipped: a block that is not classic TIFF (another byte order mark, or the magic 43 of + // BigTIFF) may still be read by a reader that knows that form, so a copy in it cannot be known to be gone, + // unless none of the field's tags is in its bytes in either byte order: then no form can hold one. + if (!TiffReader.TryClassic (data, out var tiff, out var ifd0)) + return (!HoldsAnyTag (data, tags, littleEndian: true, anyType: false) && !HoldsAnyTag (data, tags, littleEndian: false, anyType: false)) + || Refuse ($"The {carrier} block is not a TIFF structure, so its copy of {what} cannot be updated.", out error); + + // An IFD0 whose entries do not fit is read by no one (exiftool reports a bad IFD0 directory), and every other + // IFD is reached through it: there is no copy to update. + if (!tiff.TryTable (ifd0, out _)) + return true; + var graph = IfdGraph.Walk (tiff, ifd0); + + // Past the bound the walk stops, so a copy beyond it cannot be ruled out, unless none of the field's tags is + // in the block's bytes at all: then no table can hold one, and there is nothing to remove. + if (graph.OverBudget) + return !HoldsAnyTag (data, tags, tiff.LittleEndian, anyType: true) + || Refuse ($"The {carrier} block has IFD tables that overlap each other beyond what its data holds, so its copy of {what} cannot be updated.", out error); + + // Plain structure is decided before any range is recorded or any value array is read. Nothing to remove + // leaves the block as it is, including when the structure is not plain. + var verdict = PlainExif.Judge (tiff, graph, tags); + if (!verdict.Removes) + return true; + if (!verdict.Plain && !SkipCheck) + return Refuse ($"The {carrier} block {verdict.Why}, so its copy of {what} cannot be updated.", out error); + + var plan = RemovalPlan.Mark (tiff, graph, tags); + if (plan.Removing.Count == 0) + return true; + // The plan stopped before it had read every offset and length, so applying it could zero a strip, tile or + // thumbnail it never recorded. Nothing to remove never reaches here. + if (plan.ValueBudgetExceeded) + return Refuse ($"The {carrier} block {PlainExif.OverBudget}, so its copy of {what} cannot be updated.", out error); + // A removed value that shares a byte, or a table whose compaction would rewrite something a reader sees. + // Nothing is written. Two protected ranges may share a byte; zeroing does not touch them. + if (!SkipCheck && (!plan.IsClean () || CompactionConflict (graph, plan, carrier, what) is not null)) + return Refuse (Reason (graph, plan, carrier, what), out error); + plan.Apply (block.AsSpan (start), tiff, graph); + changed = true; + return true; + } + + static bool Refuse (string reason, out string? error) + { + error = reason; + return false; + } + + // The tags of every changed field, and their names for a refusal; false when no changed field has Exif tags. + static bool TryRequest (ImageTag tag, out HashSet tags, out string what) + { + tags = []; + var names = new List (); + foreach (var field in MirrorFields.All) { + if (!tag.Changed (field.Store)) + continue; + tags.UnionWith (field.Ifd0); + tags.UnionWith (field.ExifIfd); + names.Add (field.Name); + } + + what = string.Join (", ", names); + return tags.Count > 0; + } + + // Whether the bytes, at any offset, in the given byte order, could be an entry with one of the tags: the tag + // followed by any type (TagLib# reads a UserComment of any type) or, for a block that is not classic TIFF, by a + // field type a TIFF or BigTIFF reader knows (1-18). One pass. + static bool HoldsAnyTag (ReadOnlySpan data, HashSet tags, bool littleEndian, bool anyType) + { + for (var at = 0; at + 4 <= data.Length; at++) { + IfdSteps.Count++; + if (tags.Contains (Endian.U16 (data, at, littleEndian)) && (anyType || Endian.U16 (data, at + 2, littleEndian) is >= 1 and <= 18)) + return true; + } + + return false; + } + + // Why a checked edit was refused: the structure the edit would rewrite, named from its shape. + static string Reason (IfdGraph graph, RemovalPlan plan, string carrier, string what) => + CompactionConflict (graph, plan, carrier, what) + ?? StructureChange (carrier, what); + + // The shape that explains a refusal, or null: a table being compacted shares a byte with another table, or an + // unread table's count, a pointer array or another kept value or data range lies in a table being compacted. + static string? CompactionConflict (IfdGraph graph, RemovalPlan plan, string carrier, string what) + { + if (CompactedRanges (graph, plan.Removing) is not CountedList<(long Start, long End)> compacted) + return Refusal (carrier, what, TablesOverlap); + for (var n = 0; n < graph.Unread.Count; n++) { + var at = graph.Unread[n]; + if (ByteRanges.Overlaps (compacted, (at, at + 2))) + return Refusal (carrier, what, PointerIntoTable); + } + + // A kept value inside a table being compacted would be rewritten: a SubIFD offset array (readers would follow it + // elsewhere), another entry's value, or the data an offset/length pair names. + for (var n = 0; n < plan.Kept.Count; n++) { + var (start, end, kind) = plan.Kept[n]; + if (ByteRanges.Overlaps (compacted, (start, end))) + return Refusal (carrier, what, kind == TiffReader.SubIfdsPointer ? SubIfdInsideTable : ValueInsideTable); + } + + // A protected range inside a table being compacted (a pointer's value, another table's bytes) would be + // rewritten. The table's own range is one of those protected ranges and is the edit, so it does not count. + for (var n = 0; n < plan.Protected.Count; n++) { + var range = plan.Protected[n]; + if (!ByteRanges.Overlaps (compacted, range) || IsCompactedTable (compacted, range)) + continue; + return StructureChange (carrier, what); + } + + return null; + } + + static string StructureChange (string carrier, string what) => + Refusal (carrier, what, StructureWouldChange); + + static string Refusal (string carrier, string what, string reason) => + $"The {carrier} block {reason}, so its copy of {what} cannot be updated."; + + // Compacted tables are sorted and disjoint, so the table a protected range names is one binary search. + static bool IsCompactedTable (CountedList<(long Start, long End)> compacted, (long Start, long End) range) + { + var low = ByteRanges.FirstEndingAfter (compacted, range.Start); + return low < compacted.Count && compacted[low].Start == range.Start && compacted[low].End == range.End; + } + + // The sorted ranges of the tables being compacted, or null when one of them shares a byte with another table. + static CountedList<(long Start, long End)>? CompactedRanges (IfdGraph graph, Dictionary> removing) + { + var ranges = new CountedList<(long Start, long End, bool Compacted)> (); + for (var t = 0; t < graph.Tables.Count; t++) { + var (at, count, _) = graph.Tables[t]; + var (rangeStart, rangeEnd) = TiffReader.TableRange (at, count); + ranges.Add ((rangeStart, rangeEnd, removing.ContainsKey (at))); + } + + ranges.Sort ((a, b) => a.Start.CompareTo (b.Start)); + var compacted = new CountedList<(long Start, long End)> (); + long furthest = long.MinValue, furthestCompacted = long.MinValue; + for (var n = 0; n < ranges.Count; n++) { + var range = ranges[n]; + if (range.Start < furthestCompacted || (range.Compacted && range.Start < furthest)) + return null; + furthest = Math.Max (furthest, range.End); + if (range.Compacted) { + furthestCompacted = Math.Max (furthestCompacted, range.End); + compacted.Add ((range.Start, range.End)); + } + } + + return compacted; + } +} diff --git a/src/TagLibSharp2/Image/Exif/OffsetLengthPairs.cs b/src/TagLibSharp2/Image/Exif/OffsetLengthPairs.cs new file mode 100644 index 00000000..5a3bc24a --- /dev/null +++ b/src/TagLibSharp2/Image/Exif/OffsetLengthPairs.cs @@ -0,0 +1,24 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +namespace TagLibSharp2.Image.Exif; + +/// +/// The offset/length pairs a plain edit may read: StripOffsets/StripByteCounts (0x0111/0x0117), +/// TileOffsets/TileByteCounts (0x0144/0x0145) and JPEGInterchangeFormat/JPEGInterchangeFormatLength (0x0201/0x0202, +/// TIFF 6.0 §3 and Exif 2.32 §4.6.5). Slot order is strip, tile, then thumbnail, the offset side then the length side. +/// +static class OffsetLengthPairs +{ + public static readonly (int Offsets, int Lengths)[] All = [(0x0111, 0x0117), (0x0144, 0x0145), (0x0201, 0x0202)]; + + public static int Slot (int tag) => tag switch { + 0x0111 => 0, + 0x0117 => 1, + 0x0144 => 2, + 0x0145 => 3, + 0x0201 => 4, + 0x0202 => 5, + _ => -1 + }; +} diff --git a/src/TagLibSharp2/Image/Exif/PlainExif.cs b/src/TagLibSharp2/Image/Exif/PlainExif.cs new file mode 100644 index 00000000..98279df5 --- /dev/null +++ b/src/TagLibSharp2/Image/Exif/PlainExif.cs @@ -0,0 +1,187 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using TagLibSharp2.Image.Tiff; + +namespace TagLibSharp2.Image.Exif; + +/// +/// Whether a field edit may run. One pass over the tables already walked, before a records +/// a range or reads a value array. The structure is not plain when a classic next-IFD field has only one, two or +/// three of its four bytes (TIFF 6.0 §2), when one table names the same strip, tile or thumbnail offset or length +/// twice, when one of those is not SHORT or LONG, when one of those arrays does not lie wholly in the data, when +/// one array is named twice, when removing an entry would change whether exiftool reads that table's first entry, +/// or when a complete pair names more values than half the bytes. The first of these reasons stands; a later check +/// does not replace it. An absent next field is plain. An empty table is read. A first-entry change that shows +/// nothing new is still refused. +/// +static class PlainExif +{ + /// A plain block, whether the edit removes an entry, and why it is not plain. + public readonly record struct Verdict (bool Plain, bool Removes, string? Why); + + /// A classic next-IFD field has some, but not all, of its four bytes. + internal const string NextCutShort = "has an IFD whose next offset is cut short"; + + /// One table names the same strip, tile or thumbnail offset or length tag twice. + internal const string PairTagRepeated = "names a strip, tile or thumbnail offset or length more than once"; + + /// A strip, tile or thumbnail offset or length is not SHORT or LONG. + internal const string PairTypeWrong = "has a strip, tile or thumbnail offset or length that is not SHORT or LONG"; + + /// Two entries name one strip, tile or thumbnail array. + internal const string PairArrayRepeated = "names one strip, tile or thumbnail array more than once"; + + /// A strip, tile or thumbnail array does not lie wholly in the data. + internal const string PairDoesNotFit = "has a strip, tile or thumbnail array that does not fit in its data"; + + /// Removing an entry would change whether exiftool reads the table's first entry. + internal const string FirstEntryChanges = "would change whether exiftool reads a table's first entry"; + + /// Complete offset/length pairs name more values than half the bytes. + internal const string OverBudget = "names more strip, tile or thumbnail values than its data holds"; + + /// + /// Strip, tile and thumbnail offset/length tags (TIFF 6.0 §3, tags 0x0111/0x0117, 0x0144/0x0145, and + /// JPEGInterchangeFormat 0x0201/0x0202) are plain only as SHORT (3) or LONG (4), and only when each array lies + /// wholly in the data and is named once. A complete pair whose values, counted from the entry headers, exceed + /// half the bytes is not plain. A next-IFD field that is partly in the data is not plain. The first entry exiftool will see is + /// plain only when does not change; GPS tables are not edited. + /// + public static Verdict Judge (TiffReader tiff, IfdGraph graph, HashSet tags) + { + string? why = null; + var removes = false; + long budget = 0; + HashSet? named = null; + HashSet? counted = null; + var slots = new ValueArray[6]; + for (var t = 0; t < graph.Tables.Count; t++) { + var (at, count, roles) = graph.Tables[t]; + why ??= NextFieldCutShort (tiff, at, count); + var notes = NoteEntries (tiff, at, count, (roles & IfdGraph.ReadRoles) != 0, tags, slots, ref named, ref why); + removes |= notes.Removes; + if (why is null) + budget += CompletePairCounts (slots, notes.Got, ref counted); + why ??= FirstEntryReadability (count, notes); + if (why is not null && removes) + break; + } + + // Counts come from the entry headers. The first reason stands: a cut-short next field, a pair tag given + // twice, a type other than SHORT or LONG, an array that does not fit, one array named twice, then a first + // entry whose readability would change. The budget is reported only when none of those was found. + if (why is null && removes && ValueBudget.PastHalf (0, budget, tiff.Length)) + why = OverBudget; + return new Verdict (why is null, removes, why); + } + + // Entry(at, count) is the first byte after the entries: the classic 4-byte next-IFD field. + static string? NextFieldCutShort (TiffReader tiff, long at, int count) + { + var nextAt = tiff.Entry (at, count); + return nextAt < tiff.Length && nextAt + 4 > tiff.Length ? NextCutShort : null; + } + + static TableNotes NoteEntries ( + TiffReader tiff, + long at, + int count, + bool edited, + HashSet tags, + ValueArray[] slots, + ref HashSet? named, + ref string? why) + { + var notes = new TableNotes (); + var seenSide = 0; + for (var n = 0; n < count; n++) { + IfdSteps.Count++; + var entry = tiff.Entry (at, n); + var tag = tiff.Tag (entry); + if (n == 0) + notes.FirstType = tiff.Type (entry); + if (edited && tags.Contains (tag)) { + notes.Removes = true; + notes.Loses = true; + } else if (!notes.KeptOne) { + notes.KeptOne = true; + notes.KeptType = tiff.Type (entry); + } + + // Once a reason stands it is kept, and later entries are not read for another one. + if (why is null) + why = PairEntry (tiff, entry, tag, ref seenSide, ref notes, slots, ref named); + } + + return notes; + } + + // A second entry with the same pair tag names a different array. Which bytes it means is unknown. + static string? PairEntry ( + TiffReader tiff, + long entry, + int tag, + ref int seenSide, + ref TableNotes notes, + ValueArray[] slots, + ref HashSet? named) + { + var slot = OffsetLengthPairs.Slot (tag); + if (slot < 0) + return null; + var repeated = (seenSide & (1 << slot)) != 0; + seenSide |= 1 << slot; + if (tiff.Count (entry) == 0 || repeated) + return repeated ? PairTagRepeated : null; + if (tiff.Type (entry) is not (3 or 4)) + return PairTypeWrong; + if (!tiff.TryValueArray (entry, out var key)) + return PairDoesNotFit; + named ??= []; + if (!named.Add (key)) + return PairArrayRepeated; + slots[slot] = key; + notes.Got |= 1 << slot; + return null; + } + + // Both sides of a pair, from this table's headers. A lone offset or length is not a value the plan reads. + static long CompletePairCounts (ValueArray[] slots, int got, ref HashSet? counted) + { + if (got == 0) + return 0; + long added = 0; + for (var pair = 0; pair < 6; pair += 2) { + if ((got & (3 << pair)) != (3 << pair)) + continue; + counted ??= []; + if (counted.Add (slots[pair])) + added += slots[pair].Count; + if (counted.Add (slots[pair + 1])) + added += slots[pair + 1].Count; + } + + return added; + } + + // An empty table is read. A table with entries is read when its first format is one exiftool reads. + static string? FirstEntryReadability (int count, TableNotes notes) + { + if (!notes.Loses) + return null; + var before = count == 0 || TiffReader.FormatExiftoolReads (notes.FirstType); + var after = !notes.KeptOne || TiffReader.FormatExiftoolReads (notes.KeptType); + return before != after ? FirstEntryChanges : null; + } + + struct TableNotes + { + public bool Removes; + public bool Loses; + public int FirstType; + public int KeptType; + public bool KeptOne; + public int Got; + } +} diff --git a/src/TagLibSharp2/Image/Exif/RemovalPlan.cs b/src/TagLibSharp2/Image/Exif/RemovalPlan.cs new file mode 100644 index 00000000..785ac139 --- /dev/null +++ b/src/TagLibSharp2/Image/Exif/RemovalPlan.cs @@ -0,0 +1,409 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using TagLibSharp2.Image.Tiff; + +namespace TagLibSharp2.Image.Exif; + +/// +/// What an Exif removal changes: the entries to remove from each table, the values they free, and the bytes that +/// must never be zeroed. +/// +/// +/// Never zeroed: the header (a value is cleared only from byte 8), every table (count, entries, next offset), every +/// kept entry's value (a SubIFD offset array is the value of the 0x014A entry that names it, which is never +/// removed), the data that offset/length pairs name (the IFD1 thumbnail, strips, tiles), the structure of every +/// table no reader reads (its count, entries and next offset as far as the data goes), and the bytes a maker note +/// (Exif 2.32 §4.6.5 tag 0x927C) or one of its entries names. A removed value inside the note's own block still +/// overlaps that kept value, so the edit is refused. A value the note's entries name past the block is kept and +/// the edit runs: zeroing it would change the note, and refusing would reject a plain file. A maker note whose +/// IFD this pass does not finish (a version byte, a rejected entry, an unknown layout, or the entry budget) +/// leaves every removed value outside the tables as it was. +/// +sealed class RemovalPlan +{ + // Exif 2.32 §4.6.5. The block is undefined; a classic IFD in it is the note's own directory. + const int MakerNoteTag = 0x927C; + const int MakerNotePrefix = 32; + + public CountedList<(long Start, long End)> Protected { get; } = new (); + public CountedList<(long Start, long End)> Removed { get; } = new (); + + /// + /// The kept entries' values and the data their offset/length pairs name, in tables some reader reads and wholly + /// inside the data (a value past the data is read by no one: exiftool reports a bad offset), with the tag that + /// names each. + /// + public CountedList<(long Start, long End, int Tag)> Kept { get; } = new (); + + /// For each table that loses an entry, which of its entries go. + public Dictionary> Removing { get; } = new (); + + /// + /// The offset and length arrays name more values, across every table, than half the bytes of the block. The + /// plan then does not hold every range, so an edit that has something to remove is refused rather than applied. + /// The plainness check refuses the same bound from the entry headers first. This stop remains so a caller that + /// skips that check neither allocates past the bound nor applies a partial plan. The comparison is + /// . + /// + public bool ValueBudgetExceeded { get; private set; } + + // Each distinct SHORT or LONG array once. Keyed as a pointer array is: where it starts, how many values, and + // how wide each value is. A plain edit names each array once; the cache still keeps a skipped check from + // reading one array twice. + readonly Dictionary _values = new (); + long _valuesRead; + + // The maker-note block and the values its entries name. Apply skips these bytes. They are not protected: + // a share with them is not a reason to refuse. + readonly CountedList<(long Start, long End)> _makerOwned = new (); + + // False when any UNDEFINED maker note was not walked to the end: a version byte, a rejected entry, an + // unknown layout, or the entry budget. Zeroing then leaves removed values outside the tables as they are. + bool _allNotesLocated = true; + + // Entry reads across every maker note. One note fits: its entries occupy twelve bytes each. A second walk of + // the same bytes, or of a blob that overlaps one already walked, stops at the size of the block. + long _noteBudget; + long _noteEntriesRead; + + bool NoteBudgetSpent => _noteEntriesRead >= _noteBudget; + + // The outside targets of a blob already walked, or null when that walk did not locate the IFD. + readonly Dictionary<(long Start, long End), CountedList<(long Start, long End)>?> _noteScans = new (); + + public static RemovalPlan Mark (TiffReader tiff, IfdGraph graph, HashSet tags) + { + var plan = new RemovalPlan { _noteBudget = tiff.Length }; + for (var t = 0; t < graph.Tables.Count; t++) { + var (at, count, roles) = graph.Tables[t]; + var seen = (roles & IfdGraph.SeenRoles) != 0; + var table = TiffReader.TableRange (at, count); + plan.Protected.Add (table); + plan.AddDataRanges (tiff, at, count, seen); + plan.MarkEntries (tiff, at, count, edited: (roles & IfdGraph.ReadRoles) != 0, seen, tags); + } + + for (var n = 0; n < graph.Unread.Count; n++) { + var at = graph.Unread[n]; + var entries = at + 2 <= tiff.Length ? tiff.U16 (at) : 0; + var unread = (at, Math.Min (at + 2 + (entries * 12L) + 4, tiff.Length)); + plan.Protected.Add (unread); + } + + return plan; + } + + // Every kept value is protected. The out-of-line value of an Exif, GPS or interoperability IFD pointer (count 2, + // or a wide type) is shown by no reader (exiftool: "Bad value"); what it leads to is a table. + void MarkEntries (TiffReader tiff, long at, int count, bool edited, bool seen, HashSet tags) + { + for (var n = 0; n < count; n++) { + IfdSteps.Count++; + var entry = tiff.Entry (at, n); + var range = tiff.ValueRange (entry); + if (edited && tags.Contains (tiff.Tag (entry))) { + if (!Removing.TryGetValue (at, out var marks)) + Removing[at] = marks = CountedList.Filled (count); + marks[n] = true; + if (range.End > range.Start) + Removed.Add (range); + } else if (range.End > range.Start) { + Protected.Add (range); + if (seen && tiff.Tag (entry) is not (TiffReader.ExifIfdPointer or TiffReader.GpsIfdPointer or TiffReader.InteropIfdPointer) + && range.Start < tiff.Length && range.End <= tiff.Length) + Kept.Add ((range.Start, range.End, tiff.Tag (entry))); + if (tiff.Tag (entry) == MakerNoteTag && tiff.Type (entry) == 7) + RecordMakerNote (tiff, range); + } + } + } + + /// + /// Whether zeroing the removed values would leave every protected byte alone. Two protected ranges may share a + /// byte: that share is not zeroed. A table being compacted is a separate question, answered where the edit is + /// applied. A pair tag given twice is not this question: the plainness check owns it. + /// + public bool IsClean () + { + if (ValueBudgetExceeded) + return false; + if (Removed.Count == 0 || Protected.Count == 0) + return true; + var guarded = new CountedList<(long Start, long End)> (); + for (var n = 0; n < Protected.Count; n++) + guarded.Add (Protected[n]); + var merged = ByteRanges.Merge (guarded); + for (var n = 0; n < Removed.Count; n++) { + if (ByteRanges.Overlaps (merged, Removed[n])) + return false; + } + + return true; + } + + /// Compacts every table that loses an entry, then zeroes the freed values no other structure uses. + public void Apply (Span data, TiffReader tiff, IfdGraph graph) + { + for (var t = 0; t < graph.Tables.Count; t++) { + var (at, count, _) = graph.Tables[t]; + if (Removing.TryGetValue (at, out var marks)) + CompactTable (data, tiff, at, count, marks); + } + + // One sort, then a binary search per removed value: linear-logarithmic in the entries, whatever their number. + var merged = ByteRanges.Merge (Protected); + var maker = ByteRanges.Merge (_makerOwned); + for (var n = 0; n < Removed.Count; n++) { + var range = Removed[n]; + if (range.Start < TiffReader.HeaderSize || range.End > data.Length || ByteRanges.Overlaps (merged, range)) + continue; + // A note this pass did not finish may name any byte outside the tables. A value inside a table + // overlaps Protected and was skipped above, so every range here is outside them. + if (!_allNotesLocated) + continue; + ClearExcept (data, range, maker); + } + } + + // Zeroes [range) except where a maker-note range covers it. Both lists are sorted and disjoint, so the covered + // part is one forward pass from the first note range that ends after the value starts. + static void ClearExcept (Span data, (long Start, long End) range, CountedList<(long Start, long End)> maker) + { + var cursor = range.Start; + var low = ByteRanges.FirstEndingAfter (maker, range.Start); + + for (var n = low; n < maker.Count; n++) { + var keep = maker[n]; + if (keep.Start >= range.End) + break; + var keepStart = Math.Max (keep.Start, range.Start); + var keepEnd = Math.Min (keep.End, range.End); + if (cursor < keepStart) + data.Slice ((int)cursor, (int)(keepStart - cursor)).Clear (); + if (keepEnd > cursor) + cursor = keepEnd; + } + + if (cursor < range.End) + data.Slice ((int)cursor, (int)(range.End - cursor)).Clear (); + } + + // The note's own bytes, then any value a classic IFD in the note names outside that block. The IFD may sit at + // the start or after at most 32 bytes of ASCII or NUL (Panasonic's "Panasonic" header is 12). One pass over + // the entries. Offsets that all land inside the block are counted from the block, so nothing outside it is + // claimed. Offsets that all land inside the TIFF are counted from the TIFF, and only those outside the block + // are kept as well. A mix that fits neither is left to the block alone. + void RecordMakerNote (TiffReader tiff, (long Start, long End) blob) + { + var end = Math.Min (blob.End, tiff.Length); + if (blob.Start < 0 || end <= blob.Start) + return; + _makerOwned.Add ((blob.Start, end)); + var key = (blob.Start, end); + // The first walk already stored this blob's outside ranges. Copying them again is the square of the notes. + if (_noteScans.TryGetValue (key, out var cached)) { + if (cached is null) + _allNotesLocated = false; + return; + } + + if (NoteBudgetSpent || !TryMakerTargets (tiff, blob.Start, end, out var outside)) { + _allNotesLocated = false; + _noteScans[key] = null; + return; + } + + _noteScans[key] = outside; + CopyRanges (outside); + } + + void CopyRanges (CountedList<(long Start, long End)> ranges) + { + for (var n = 0; n < ranges.Count; n++) + _makerOwned.Add (ranges[n]); + } + + bool TryMakerTargets (TiffReader tiff, long blobStart, long blobEnd, out CountedList<(long Start, long End)> outside) + { + outside = new CountedList<(long Start, long End)> (); + var last = blobStart + MakerNotePrefix; + for (var at = blobStart; at + 2 <= blobEnd && at <= last; at++) { + if (TryNoteIfd (tiff, at, blobStart, blobEnd, out outside)) + return true; + if (NoteBudgetSpent) + return false; + if (at < 0 || at >= tiff.Length || !IsAsciiOrNul (tiff.Data[(int)at])) + break; + } + + return false; + } + + // A classic IFD wholly inside the block: a count, sorted tags, types 1-12 (TIFF 6.0 §2). False leaves + // unused. + bool TryNoteIfd ( + TiffReader tiff, + long at, + long blobStart, + long blobEnd, + out CountedList<(long Start, long End)> outside) + { + outside = new CountedList<(long Start, long End)> (); + if (at < 0 || at > tiff.Length - 2) + return false; + var count = tiff.U16 (at); + if (count <= 0) + return false; + var tableEnd = at + 2 + (count * 12L) + 4; + if (tableEnd < at || tableEnd > blobEnd) + return false; + var fromNote = true; + var fromTiff = true; + var extra = new CountedList<(long Start, long End)> (); + long previous = -1; + for (var n = 0; n < count; n++) { + if (NoteBudgetSpent) + return false; + + _noteEntriesRead++; + IfdSteps.Count++; + var entry = tiff.Entry (at, n); + var tag = tiff.Tag (entry); + var type = tiff.Type (entry); + if (tag <= previous || type is < 1 or > 12) + return false; + previous = tag; + var range = tiff.ValueRange (entry); + var size = range.End - range.Start; + if (size <= 0) + continue; + var offset = range.Start; + var inNote = Fits (blobStart, offset, size, blobEnd); + var inTiff = Fits (0, offset, size, tiff.Length); + if (!inNote) + fromNote = false; + // A value past the TIFF is not part of this block. One inside the TIFF but outside the note is. + if ((inTiff || offset < tiff.Length) && !WhollyInside (offset, size, blobStart, blobEnd)) + extra.Add ((offset, offset + size)); + if (!inTiff) + fromTiff = false; + // A count taken from a version byte can look like an IFD. Past the first byte, a value that fits + // neither the note nor the TIFF is not that IFD. + if (at > blobStart && !inNote && !inTiff) + return false; + } + + if (!fromNote && fromTiff) + outside = extra; + return true; + } + + static bool Fits (long origin, long offset, long size, long limit) + { + if (offset < 0 || size <= 0 || origin > long.MaxValue - offset) + return false; + var start = origin + offset; + return start <= limit && size <= limit - start; + } + + static bool WhollyInside (long start, long size, long low, long high) => + start >= low && start <= high && size <= high - start; + + static bool IsAsciiOrNul (byte value) => value == 0 || value is >= 0x20 and <= 0x7E; + + // Moves the kept entries up and the next-IFD offset after them (0 when it was missing or cut short), then clears + // the freed bytes up to the end of the old offset, or of the data when the table ended there. + static void CompactTable (Span data, TiffReader tiff, long ifd, int count, CountedList removing) + { + var at = (int)ifd; + var table = at + 2; + var kept = 0; + for (var n = 0; n < count; n++) { + if (removing[n]) + continue; + if (kept != n) + data.Slice (table + (n * 12), 12).CopyTo (data.Slice (table + (kept * 12))); + kept++; + } + + var nextAt = table + (count * 12); + var next = nextAt + 4 <= data.Length ? Endian.U32 (data, nextAt, tiff.LittleEndian) : 0; + Endian.WriteU16 (data, at, kept, tiff.LittleEndian); + var newNext = table + (kept * 12); + Endian.WriteU32 (data, newNext, next, tiff.LittleEndian); + data.Slice (newNext + 4, Math.Min (nextAt + 4, data.Length) - (newNext + 4)).Clear (); + } + + // Each array is read once. Values read across every table are bounded by half the bytes present: two arrays that + // both fit can pass that only by overlapping, and past it the plan stops reading rather than allocating. A plain + // edit never reaches that bound; it is refused from the entry headers first. A second entry with the same pair + // tag is the plainness check's reason, so the first entry is the one read here. + void AddDataRanges (TiffReader tiff, long ifd, int count, bool seen) + { + foreach (var (offsetsTag, lengthsTag) in OffsetLengthPairs.All) { + var hasOffsets = TryKey (tiff, ifd, count, offsetsTag, out var offsetsKey); + var hasLengths = TryKey (tiff, ifd, count, lengthsTag, out var lengthsKey); + if (!hasOffsets || !hasLengths || ValueBudgetExceeded) + continue; + if (!TryValues (tiff, offsetsKey, out var offsets) || !TryValues (tiff, lengthsKey, out var lengths)) + continue; + var shared = Math.Min (offsets.Length, lengths.Length); + for (var n = 0; n < shared; n++) { + var end = offsets[n] + lengths[n]; + if (end < offsets[n]) + continue; + Protected.Add ((offsets[n], end)); + if (seen && offsets[n] < tiff.Length && end <= tiff.Length) + Kept.Add ((offsets[n], end, offsetsTag)); + } + } + } + + // The first SHORT or LONG entry with the tag, when every value lies in the data. + static bool TryKey (TiffReader tiff, long ifd, int count, int tag, out ValueArray key) + { + key = default; + var found = FindEntry (tiff, ifd, count, tag); + return found >= 0 && tiff.TryValueArray (tiff.Entry (ifd, found), out key); + } + + // The values of one array, from the cache when a table already named it. Past the bound, or a count no array + // can hold, nothing is allocated and the plan is incomplete. + bool TryValues (TiffReader tiff, ValueArray key, out long[] values) + { + if (_values.TryGetValue (key, out var cached)) { + values = cached; + return true; + } + if (key.Count > int.MaxValue || ValueBudget.PastHalf (_valuesRead, key.Count, tiff.Length)) { + ValueBudgetExceeded = true; + values = []; + return false; + } + + var count = (int)key.Count; + values = new long[count]; + for (var k = 0; k < count; k++) { + IfdSteps.Count++; + var p = (int)key.At + (k * key.Size); + values[k] = key.Size == 2 ? tiff.U16 (p) : tiff.U32 (p); + } + + _valuesRead += count; + _values[key] = values; + return true; + } + + // The first entry with the tag, or -1. A second entry with that tag is refused by the plainness check. + static int FindEntry (TiffReader tiff, long ifd, int count, int tag) + { + for (var n = 0; n < count; n++) { + IfdSteps.Count++; + if (tiff.Tag (tiff.Entry (ifd, n)) == tag) + return n; + } + + return -1; + } +} diff --git a/src/TagLibSharp2/Image/Exif/ValueBudget.cs b/src/TagLibSharp2/Image/Exif/ValueBudget.cs new file mode 100644 index 00000000..04e51989 --- /dev/null +++ b/src/TagLibSharp2/Image/Exif/ValueBudget.cs @@ -0,0 +1,15 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +namespace TagLibSharp2.Image.Exif; + +/// +/// Whether offset and length arrays name more values than half the bytes. Equality still fits: two arrays that +/// both lie in the data can meet it. The plainness check counts from the entry headers and the removal plan counts +/// the values it is about to read. Both ask here. The plan keeps its own stop, because a test may skip the +/// plainness check: that stop is what the edit matrix counts, and it is what keeps the plan from allocating past it. +/// +static class ValueBudget +{ + public static bool PastHalf (long already, long more, long length) => more > (length / 2) - already; +} diff --git a/src/TagLibSharp2/Image/Gif/GifRewriter.cs b/src/TagLibSharp2/Image/Gif/GifRewriter.cs new file mode 100644 index 00000000..0f34c6be --- /dev/null +++ b/src/TagLibSharp2/Image/Gif/GifRewriter.cs @@ -0,0 +1,329 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Text; +using TagLibSharp2.Core; +using TagLibSharp2.Image.Xmp; + +namespace TagLibSharp2.Image.Gif; + +/// +/// Reads a GIF's comment extensions and splices a new one after the header (GIF89a §24). Every other block, and +/// anything after the trailer, is copied as it is; the XMP copy of a changed comment is updated. +/// +static class GifRewriter +{ + internal const string HeaderError = "The GIF header is truncated, so the comment cannot be spliced in."; + internal const string SpliceError = + "The GIF block list is truncated or holds an unknown block, so the comment cannot be spliced in."; + + public static void Read (ReadOnlySpan data, ImageTag tag) + { + if (TryComments (data, out var text)) + tag.ReadField (ImageStores.Comment, text); + } + + /// The edited file as new pieces and ranges of . + public static ImagePlan? Plan (ReadOnlySpan data, ImageTag tag, out string? error) + { + error = null; + var replaceComment = tag.Changed (ImageStores.Comment); + if (!replaceComment && !tag.DropUnmapped) + return null; + if (!TryHeader (data, out var header)) { + error = HeaderError; + return null; + } + + var plan = new ImagePlan (); + var comment = replaceComment ? tag.Field (ImageStores.Comment) : null; + if (comment is not null && data.StartsWith ("GIF87a"u8)) { + plan.Add ("GIF89a"u8); + plan.Copy (6, header - 6); + } else { + plan.Copy (0, header); + } + + if (comment is not null) + plan.Add (CommentBytes (comment)); + if (TryCopyBlocks (data, header, tag, replaceComment, plan, out error)) + return plan; + error ??= SpliceError; + return null; + } + + static byte[] CommentBytes (string comment) + { + using var builder = new BinaryDataBuilder (); + AddComment (builder, comment); + return builder.ToArray (); + } + + // Copies the blocks after the header through the trailer and what follows it. False at a truncated or unknown + // block (error null), or when the XMP copy cannot be updated (error set). + static bool TryCopyBlocks ( + ReadOnlySpan data, + int header, + ImageTag tag, + bool replaceComment, + ImagePlan plan, + out string? error) + { + error = null; + var mirrors = replaceComment && !tag.DropUnmapped; + var i = header; + while (i < data.Length) { + var start = i; + var introducer = data[i]; + if (introducer == 0x3B) { + plan.Copy (start, data.Length - start); + return true; + } + + if (introducer == 0x2C) { + if (!SkipImage (data, ref i)) + return false; + plan.Copy (start, i - start); + continue; + } + + if (introducer != 0x21 || i + 2 > data.Length || !SkipSubBlocks (data, ref i, startAtLabel: true)) + return false; + if (!TryCopyExtension (data, start, i - start, tag, replaceComment, mirrors, plan, out error)) + return false; + } + + return false; + } + + static bool TryCopyExtension ( + ReadOnlySpan data, + int start, + int length, + ImageTag tag, + bool replaceComment, + bool mirrors, + ImagePlan plan, + out string? error) + { + error = null; + var block = data.Slice (start, length); + if ((replaceComment && block[1] == 0xFE) || (tag.DropUnmapped && !IsKeptOnClear (block))) + return true; + if (!mirrors || !IsXmp (block)) { + plan.Copy (start, length); + return true; + } + + if (!TryMirrorXmp (block, tag, out var edited, out error)) + return false; + if (edited is not null) + plan.Add (edited); + else + plan.Copy (start, length); + return true; + } + + // GIF89a defines four extensions: graphic control (0xF9), plain text (0x01), comment (0xFE) and + // application (0xFF). Clear keeps graphic control and plain text (they are drawn), and the application + // extensions a decoder or colour management needs: NETSCAPE2.0 and ANIMEXTS1.0 (the loop count) and + // ICCRGBG1012 (the ICC profile). Every other application extension (XMP, ImageMagick's IPTC and 8BIM, and + // unknown ones) and any extension with an undefined label is dropped; the comment goes through the tag. + static bool IsKeptOnClear (ReadOnlySpan block) + { + var label = block[1]; + if (label is 0xF9 or 0x01 or 0xFE) + return true; + if (label != 0xFF || block.Length < 14 || block[2] != 11) + return false; + var id = block.Slice (3, 11); + return id.SequenceEqual ("NETSCAPE2.0"u8) || id.SequenceEqual ("ANIMEXTS1.0"u8) || id.SequenceEqual ("ICCRGBG1012"u8); + } + + static bool IsXmp (ReadOnlySpan block) => + block.Length >= 14 && block[1] == 0xFF && block[2] == 11 && block.Slice (3, 11).SequenceEqual ("XMP DataXMP"u8); + + // XMP Specification Part 3 §1.1.2: the GIF XMP extension holds the packet bytes as they are, then a + // 258-byte "magic trailer" (0x01, 0xFF down to 0x00, then 0x00) that makes the bytes parse as sub-blocks. + static byte[] XmpTrailer () + { + var trailer = new byte[258]; + trailer[0] = 0x01; + for (var n = 0; n < 256; n++) + trailer[1 + n] = (byte)(0xFF - n); + return trailer; + } + + static bool TryMirrorXmp (ReadOnlySpan block, ImageTag tag, out byte[]? edited, out string? error) + { + edited = null; + error = null; + var trailer = XmpTrailer (); + if (block.Length < 14 + trailer.Length || !block.Slice (block.Length - trailer.Length).SequenceEqual (trailer)) + return TryMirrorXmpSubBlocks (block, tag, out edited, out error); + + var packet = Encoding.UTF8.GetString (block.Slice (14, block.Length - 14 - trailer.Length)); + if (!XmpMirror.TryUpdate (packet, tag, "GIF XMP packet", out var updated, out error)) + return false; + if (ReferenceEquals (updated, packet)) + return true; + var bytes = Encoding.UTF8.GetBytes (updated); + edited = new byte[14 + bytes.Length + trailer.Length]; + block.Slice (0, 14).CopyTo (edited); + bytes.CopyTo (edited, 14); + trailer.CopyTo (edited, 14 + bytes.Length); + return true; + } + + // ImageIO writes the GIF XMP packet as ordinary data sub-blocks (GIF89a §15) instead of the raw bytes and the + // magic trailer. The packet is then the sub-blocks joined, and is written back the same way. + static bool TryMirrorXmpSubBlocks (ReadOnlySpan block, ImageTag tag, out byte[]? edited, out string? error) + { + edited = null; + error = null; + var joined = JoinSubBlocks (block, out var end); + if (end != block.Length - 1 || !joined.Contains ((byte)'<')) { + if (block.IndexOf ("UserComment"u8) < 0) + return true; + error = "The GIF XMP extension is neither the XMP raw form with its magic trailer nor data sub-blocks, and holds a UserComment, so that copy of Comment cannot be located and updated."; + return false; + } + + var packet = Encoding.UTF8.GetString ([.. joined]); + if (!XmpMirror.TryUpdate (packet, tag, "GIF XMP packet", out var updated, out error)) + return false; + if (ReferenceEquals (updated, packet)) + return true; + using var builder = new BinaryDataBuilder (block.Length + 64); + builder.Add (block.Slice (0, 14)); + var bytes = Encoding.UTF8.GetBytes (updated); + for (var at = 0; at < bytes.Length; at += 255) { + var take = Math.Min (255, bytes.Length - at); + builder.Add ((byte)take); + builder.Add (bytes.AsSpan (at, take)); + } + + builder.Add (0); + edited = builder.ToArray (); + return true; + } + + // The data of the sub-blocks after the 14-byte application header, and where the walk stopped. + static List JoinSubBlocks (ReadOnlySpan block, out int end) + { + var joined = new List (block.Length); + var i = 14; + while (i < block.Length && block[i] != 0) { + var size = block[i]; + if (i + 1 + size > block.Length) + break; + for (var n = 0; n < size; n++) + joined.Add (block[i + 1 + n]); + i += 1 + size; + } + + end = i; + return joined; + } + + static bool TryComments (ReadOnlySpan data, out string? text) + { + text = null; + if (!TryHeader (data, out var header)) + return false; + var collected = new List (); + var i = header; + while (i < data.Length) { + var introducer = data[i]; + if (introducer == 0x3B) { + text = collected.Count == 0 ? null : Encoding.UTF8.GetString (collected.ToArray ()); + return true; + } + + var skipped = introducer switch { + 0x21 => i + 2 <= data.Length && SkipSubBlocks (data, ref i, startAtLabel: true, data[i + 1] == 0xFE ? collected : null), + 0x2C => SkipImage (data, ref i), + _ => false + }; + if (!skipped) + return false; + } + + return false; + } + + static bool TryHeader (ReadOnlySpan data, out int header) + { + header = 0; + if (data.Length < 13 || (!data.StartsWith ("GIF87a"u8) && !data.StartsWith ("GIF89a"u8))) + return false; + var colors = (data[10] & 0x80) == 0 ? 0 : 3 * (1 << ((data[10] & 0x07) + 1)); + header = 13 + colors; + return header <= data.Length; + } + + static bool SkipImage (ReadOnlySpan data, ref int i) + { + if (i + 10 > data.Length) + return false; + var packed = data[i + 9]; + i += 10; + if ((packed & 0x80) != 0) { + var table = 3 * (1 << ((packed & 0x07) + 1)); + if (i + table > data.Length) + return false; + i += table; + } + + if (i >= data.Length) + return false; + i++; + return SkipSubBlocks (data, ref i, startAtLabel: false); + } + + static bool SkipSubBlocks (ReadOnlySpan data, ref int i, bool startAtLabel, List? payload = null) + { + if (startAtLabel) { + if (i + 2 > data.Length) + return false; + i += 2; + } + + while (i < data.Length) { + var size = data[i++]; + if (size == 0) + return true; + if (i + size > data.Length) + return false; + if (payload is not null) { + for (var n = 0; n < size; n++) + payload.Add (data[i + n]); + } + + i += size; + } + + return false; + } + + /// A comment extension (GIF89a §24): sub-blocks of at most 255 bytes, split between UTF-8 sequences. + public static void AddComment (BinaryDataBuilder builder, string comment) + { + var bytes = Encoding.UTF8.GetBytes (comment); + builder.Add (0x21); + builder.Add (0xFE); + var offset = 0; + while (offset < bytes.Length) { + var take = Math.Min (255, bytes.Length - offset); + while (take > 0 && offset + take < bytes.Length && (bytes[offset + take] & 0xC0) == 0x80) + take--; + if (take == 0) + take = Math.Min (255, bytes.Length - offset); + builder.Add ((byte)take); + builder.Add (bytes.AsSpan (offset, take)); + offset += take; + } + + builder.Add (0); + } +} diff --git a/src/TagLibSharp2/Image/ImageGainMap.cs b/src/TagLibSharp2/Image/ImageGainMap.cs new file mode 100644 index 00000000..d5970ee2 --- /dev/null +++ b/src/TagLibSharp2/Image/ImageGainMap.cs @@ -0,0 +1,506 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Globalization; +using System.Text; +using System.Xml; + +namespace TagLibSharp2.Image; + +/// +/// The XMP an HDR decoder needs to find and apply a JPEG gain map, which Clear keeps (rule 7: what a decoder +/// needs). Clear writes a new packet from an explicit list of properties with typed values; nothing of the +/// original packet is copied, so no other property, attribute, nested structure, comment or text survives. +/// +/// +/// Ultra HDR v1.0 (https://developer.android.com/media/platform/hdr-image-format, "XMP attributes"): +/// hdrgm:Version ("1.0"), hdrgm:BaseRenditionIsHDR (Boolean), hdrgm:GainMapMin, +/// GainMapMax, Gamma, OffsetSDR, OffsetHDR (Real, or an ordered array of three Reals, +/// one per channel), hdrgm:HDRCapacityMin and HDRCapacityMax (Real); and in the primary image, +/// Container:Directory, an ordered array of Container:Item structures with Item:Semantic, +/// Item:Mime, Item:Length and Item:Padding (lengths and paddings are integers; an item's +/// offset is the primary's length plus the preceding items' lengths and paddings). +/// Apple (the properties ImageIO writes for an HDRGainMap auxiliary image, as in +/// CGImageDestinationAddAuxiliaryDataInfo output): apdi:AuxiliaryImageType +/// (urn:com:apple:photo:2020:aux:hdrgainmap), apdi:NativeFormat and apdi:StoredFormat +/// (integer pixel formats), HDRGainMap:HDRGainMapVersion (integer) and, from version 131072 (iPhone 15), +/// HDRGainMap:HDRGainMapHeadroom (Real), the headroom ImageIO and libultrahdr scale the gain map by. A +/// version-65536 gain map (iPhone 12-14) has no headroom in its XMP: decoders compute it from the primary image's +/// Apple maker note, tags 33 and 48 (Apple, "Applying Apple HDR effect to your photos", +/// https://developer.apple.com/documentation/appkit/applying-apple-hdr-effect-to-your-photos). For such a packet +/// Clear keeps those two values, as ImageIO applies them, and nothing else of the Exif, in a new minimal Exif in +/// the primary (, which also says why it is not a conformant Exif); +/// after Clear ImageIO decodes the HDR rendition exactly as before. Without them ImageIO renders the photo SDR and +/// libultrahdr refuses it as a gain-map image. +/// Motion Photo 1.0 (https://developer.android.com/media/platform/motion-photo-format): Camera:MotionPhoto +/// and Camera:MotionPhotoVersion (Integer) and Camera:MotionPhotoPresentationTimestampUs (Long, -1 for +/// unset), and the directory's Item:Semantic and Item:Mime values, which are enumerated. +/// The packet is read with one forward pass of that keeps only the path of the +/// current element, so the cost is linear in the packet and nesting does not recurse. Only properties of a +/// top-level rdf:Description count; the first occurrence of a property wins. +/// +static class ImageGainMap +{ + const string Rdf = "http://www.w3.org/1999/02/22-rdf-syntax-ns#"; + const string Hdrgm = "http://ns.adobe.com/hdr-gain-map/1.0/"; + const string AppleGainMap = "http://ns.apple.com/HDRGainMap/1.0/"; + const string Apdi = "http://ns.apple.com/pixeldatainfo/1.0/"; + const string Container = "http://ns.google.com/photos/1.0/container/"; + const string Item = "http://ns.google.com/photos/1.0/container/item/"; + const string Camera = "http://ns.google.com/photos/1.0/camera/"; + const string AppleGainMapType = "urn:com:apple:photo:2020:aux:hdrgainmap"; + + enum Shape { Version, Boolean, Real, RealOrThree, Integer, Long, AppleType } + + // The order is the order they are written in. + static readonly (string Ns, string Name, string Prefix, Shape Shape)[] Properties = [ + (Hdrgm, "Version", "hdrgm", Shape.Version), + (Hdrgm, "BaseRenditionIsHDR", "hdrgm", Shape.Boolean), + (Hdrgm, "GainMapMin", "hdrgm", Shape.RealOrThree), + (Hdrgm, "GainMapMax", "hdrgm", Shape.RealOrThree), + (Hdrgm, "Gamma", "hdrgm", Shape.RealOrThree), + (Hdrgm, "OffsetSDR", "hdrgm", Shape.RealOrThree), + (Hdrgm, "OffsetHDR", "hdrgm", Shape.RealOrThree), + (Hdrgm, "HDRCapacityMin", "hdrgm", Shape.Real), + (Hdrgm, "HDRCapacityMax", "hdrgm", Shape.Real), + (Apdi, "AuxiliaryImageType", "apdi", Shape.AppleType), + (Apdi, "NativeFormat", "apdi", Shape.Integer), + (Apdi, "StoredFormat", "apdi", Shape.Integer), + (AppleGainMap, "HDRGainMapVersion", "HDRGainMap", Shape.Integer), + (AppleGainMap, "HDRGainMapHeadroom", "HDRGainMap", Shape.Real), + (Camera, "MotionPhoto", "Camera", Shape.Integer), + (Camera, "MotionPhotoVersion", "Camera", Shape.Integer), + (Camera, "MotionPhotoPresentationTimestampUs", "Camera", Shape.Long), + ]; + + // Ultra HDR v1.0 and Motion Photo 1.0 (https://developer.android.com/media/platform/motion-photo-format) + // enumerate these; any other value is dropped (the item keeps its slot, its length and its padding). + static readonly string[] Semantics = ["Primary", "GainMap", "MotionPhoto"]; + static readonly string[] MimeTypes = ["image/jpeg", "image/heic", "image/avif", "video/mp4", "video/quicktime"]; + + static readonly string[] ItemFields = ["Semantic", "Mime", "Length", "Padding"]; + + // Marks an rdf:li whose Container:Item was read; not one of ItemFields, so it is never written. + const string ItemSeen = "\0item"; + + /// Steps of the last read on this thread, for tests that bound it by an operation count. + [ThreadStatic] + internal static long Steps; + + /// + /// The packet Clear keeps: null when it holds no valid gain-map property, otherwise a new packet that holds + /// only those properties. + /// + /// The packet bytes (UTF-8), possibly followed by NULs or padding. + /// The new lengths of the images after the first, in file order, or null. + /// True when the kept packet has HDRGainMapVersion and no + /// HDRGainMapHeadroom: decoders then take the headroom from the primary image's Apple maker note. + internal static byte[]? KeepForClear (ReadOnlySpan packet, IReadOnlyList? itemLengths, out bool headroomInMakerNote) + { + headroomInMakerNote = false; + var text = Encoding.UTF8.GetString (packet.ToArray ()); + var end = text.LastIndexOf ('>'); + if (end < 0) + return null; + var start = text.Length > 0 && text[0] == '' ? 1 : 0; + var found = new Found (); + try { + Read (text.Substring (start, end + 1 - start), found); + } catch (XmlException) { + return null; + } + + if (found.Values.Count == 0 && found.Items is null) + return null; + if (found.Items is not null && itemLengths is not null) + SetItemLengths (found.Items, itemLengths); + headroomInMakerNote = found.Values.ContainsKey (Key ("HDRGainMap", "HDRGainMapVersion")) && !found.Values.ContainsKey (Key ("HDRGainMap", "HDRGainMapHeadroom")); + return Encoding.UTF8.GetBytes (Write (found)); + } + + sealed class Found + { + public Dictionary> Values { get; } = []; + public List>? Items { get; set; } + } + + enum Role { Other, Rdf, Description, Property, PropertySeq, PropertyLi, Directory, DirectorySeq, DirectoryLi, DirectoryLiDescription, ItemNode, ItemDescription, ItemField } + + sealed class Frame (Role role, string key) + { + public Role Role { get; } = role; + public string Key { get; } = key; + public StringBuilder? Text { get; set; } + public List? Values { get; set; } + public bool Invalid { get; set; } + } + + static void Read (string packet, Found found) + { + var settings = new XmlReaderSettings { DtdProcessing = DtdProcessing.Prohibit, XmlResolver = null, IgnoreComments = true, IgnoreProcessingInstructions = true }; + using var reader = XmlReader.Create (new StringReader (packet), settings); + var state = new ReadState (); + while (reader.Read ()) { + Steps++; + switch (reader.NodeType) { + case XmlNodeType.Element: + Open (reader, state, found); + break; + case XmlNodeType.Text: + case XmlNodeType.CDATA: + case XmlNodeType.SignificantWhitespace: + case XmlNodeType.Whitespace: + AppendText (reader, state.Stack); + break; + case XmlNodeType.EndElement: { + var frame = state.Stack[^1]; + state.Stack.RemoveAt (state.Stack.Count - 1); + Close (frame, state.Stack, found, state.Item, ref state.Items, ref state.DirectoryDone); + break; + } + } + } + } + + // The open elements, the directory's items so far and the one being read, and whether the directory is done. + sealed class ReadState + { + public readonly List Stack = []; + public List>? Items; + public Dictionary? Item; + public bool DirectoryDone; + } + + static void Open (XmlReader reader, ReadState state, Found found) + { + var stack = state.Stack; + var parent = stack.Count > 0 ? stack[^1] : null; + var frame = Classify (reader, parent, found, state.DirectoryDone); + if (frame.Role == Role.Description) + ReadAttributes (reader, found.Values); + if (frame.Role == Role.Directory) + state.Items = []; + if (frame.Role == Role.DirectoryLi && state.Items is not null) { + state.Item = []; + state.Items.Add (state.Item); + } + + if (frame.Role is Role.ItemNode or Role.ItemDescription && state.Item is not null) { + state.Item[ItemSeen] = ""; + ReadItemAttributes (reader, state.Item); + } + + // Anything but the expected shape inside a kept value makes that value invalid: it is dropped. + if (frame.Role == Role.Other && parent is not null) { + if (parent.Role == Role.ItemField) + parent.Invalid = true; + else + InvalidateProperty (stack); + } + + if (reader.IsEmptyElement) + Close (frame, stack, found, state.Item, ref state.Items, ref state.DirectoryDone); + else + stack.Add (frame); + } + + static void AppendText (XmlReader reader, List stack) + { + if (stack.Count == 0 || stack[^1].Role is not (Role.Property or Role.PropertyLi or Role.ItemField)) + return; + var top = stack[^1]; + top.Text ??= new StringBuilder (); + if (top.Text.Length <= 64) + top.Text.Append (reader.Value); + } + + static Frame Classify (XmlReader reader, Frame? parent, Found found, bool directoryDone) + { + var ns = reader.NamespaceURI; + var name = reader.LocalName; + var role = parent?.Role; + if (ns == Rdf && name == "RDF") + return new Frame (Role.Rdf, ""); + if (role == Role.Rdf) + return new Frame (ns == Rdf && name == "Description" ? Role.Description : Role.Other, ""); + if (role == Role.Description) { + if (ns == Container && name == "Directory" && !directoryDone) + return new Frame (Role.Directory, ""); + foreach (var property in Properties) { + if (property.Ns == ns && property.Name == name && !found.Values.ContainsKey (Key (property.Prefix, name))) + return new Frame (Role.Property, Key (property.Prefix, name)) { Values = [] }; + } + + return new Frame (Role.Other, ""); + } + + if (role == Role.Property && ns == Rdf && name is "Seq" or "Bag" or "Alt") + return new Frame (Role.PropertySeq, parent!.Key); + if (role == Role.PropertySeq && ns == Rdf && name == "li") + return new Frame (Role.PropertyLi, parent!.Key); + if (role == Role.Directory && ns == Rdf && name == "Seq") + return new Frame (Role.DirectorySeq, ""); + if (role == Role.DirectorySeq && ns == Rdf && name == "li") + return new Frame (Role.DirectoryLi, ""); + // An item is rdf:li > Container:Item, or the RDF struct form rdf:li > rdf:Description > Container:Item. + if (role == Role.DirectoryLi && ns == Rdf && name == "Description") + return new Frame (Role.DirectoryLiDescription, ""); + if (role is Role.DirectoryLi or Role.DirectoryLiDescription && ns == Container && name == "Item") + return new Frame (Role.ItemNode, ""); + if (role == Role.ItemNode && ns == Rdf && name == "Description") + return new Frame (Role.ItemDescription, ""); + if (role is Role.ItemNode or Role.ItemDescription && ns == Item && Array.IndexOf (ItemFields, name) >= 0) + return new Frame (Role.ItemField, name); + return new Frame (Role.Other, ""); + } + + // The property a frame on top of the stack belongs to (Property, or Property > Seq > li), or null. + static Frame? EnclosingProperty (List stack) + { + for (var n = stack.Count - 1; n >= 0 && n >= stack.Count - 3; n--) { + if (stack[n].Role == Role.Property) + return stack[n]; + if (stack[n].Role is not (Role.PropertySeq or Role.PropertyLi)) + return null; + } + + return null; + } + + static void InvalidateProperty (List stack) + { + if (EnclosingProperty (stack) is Frame property) + property.Invalid = true; + } + + static void Close (Frame frame, List stack, Found found, Dictionary? item, ref List>? items, ref bool directoryDone) + { + switch (frame.Role) { + case Role.Property: { + if (frame.Invalid || found.Values.ContainsKey (frame.Key)) + return; + var values = frame.Values!.Count > 0 ? frame.Values : frame.Text is null ? [] : [frame.Text.ToString ().Trim ()]; + if (IsValid (frame.Key, values)) + found.Values[frame.Key] = values; + return; + } + + case Role.PropertyLi: { + var property = EnclosingProperty (stack); + if (property is null) + return; + if (frame.Invalid || frame.Text is null) + property.Invalid = true; + else + property.Values!.Add (frame.Text.ToString ().Trim ()); + return; + } + + case Role.ItemField: + if (!frame.Invalid && item is not null && frame.Text is not null && !item.ContainsKey (frame.Key) && IsItemValue (frame.Key, frame.Text.ToString ().Trim ())) + item[frame.Key] = frame.Text.ToString ().Trim (); + return; + + case Role.Directory: + // Readers locate items by their order and lengths, so a slot is never removed: when one rdf:li + // holds no Container:Item that can be read, the whole directory is dropped. + if (items is { Count: > 0 } && found.Items is null && items.TrueForAll (i => i.ContainsKey (ItemSeen))) + found.Items = items; + directoryDone = true; + items = null; + return; + } + } + + static void ReadAttributes (XmlReader reader, Dictionary> values) + { + if (!reader.MoveToFirstAttribute ()) + return; + do { + foreach (var property in Properties) { + if (property.Ns != reader.NamespaceURI || property.Name != reader.LocalName) + continue; + var key = Key (property.Prefix, property.Name); + if (!values.ContainsKey (key) && IsValid (key, [reader.Value.Trim ()])) + values[key] = [reader.Value.Trim ()]; + } + } while (reader.MoveToNextAttribute ()); + reader.MoveToElement (); + } + + static void ReadItemAttributes (XmlReader reader, Dictionary item) + { + if (!reader.MoveToFirstAttribute ()) + return; + do { + if (reader.NamespaceURI == Item && Array.IndexOf (ItemFields, reader.LocalName) >= 0 && !item.ContainsKey (reader.LocalName) && IsItemValue (reader.LocalName, reader.Value.Trim ())) + item[reader.LocalName] = reader.Value.Trim (); + } while (reader.MoveToNextAttribute ()); + reader.MoveToElement (); + } + + static string Key (string prefix, string name) => prefix + ":" + name; + + static Shape ShapeOf (string key) + { + foreach (var property in Properties) { + if (Key (property.Prefix, property.Name) == key) + return property.Shape; + } + + return Shape.Real; + } + + static bool IsValid (string key, List values) + { + var shape = ShapeOf (key); + if (shape == Shape.RealOrThree) + return values.Count == 1 ? IsReal (values[0]) : values.Count == 3 && values.TrueForAll (IsReal); + if (values.Count != 1) + return false; + var value = values[0]; + return shape switch { + Shape.Version => IsVersion (value), + Shape.Boolean => value is "True" or "False", + Shape.Real => IsReal (value), + Shape.Integer => IsInteger (value), + Shape.Long => IsInteger (value) || (value.Length > 1 && value[0] == '-' && IsInteger (value.Substring (1))), + Shape.AppleType => value == AppleGainMapType, + _ => false + }; + } + + static bool IsItemValue (string field, string value) => field switch { + "Semantic" => Array.IndexOf (Semantics, value) >= 0, + "Mime" => Array.IndexOf (MimeTypes, value) >= 0, + _ => IsInteger (value) + }; + + // "1.0": digits, one dot, digits. + static bool IsVersion (string value) + { + if (value.Length is 0 or > 16) + return false; + var dots = 0; + for (var i = 0; i < value.Length; i++) { + if (value[i] == '.') { + if (i == 0 || i == value.Length - 1 || ++dots > 1) + return false; + } else if (value[i] is < '0' or > '9') { + return false; + } + } + + return dots == 1; + } + + static bool IsReal (string value) => + value.Length is > 0 and <= 32 + && double.TryParse (value, NumberStyles.Float, CultureInfo.InvariantCulture, out var number) + && !double.IsNaN (number) && !double.IsInfinity (number); + + static bool IsInteger (string value) => + value.Length is > 0 and <= 19 && value.All (c => c is >= '0' and <= '9'); + + // The first item is the primary; the next lengths.Count items are the later MPF images in file order. Items + // after those (a motion-photo video, which Clear copies as it is) keep their lengths. + static void SetItemLengths (List> items, IReadOnlyList lengths) + { + for (var n = 1; n < items.Count && n - 1 < lengths.Count; n++) + items[n]["Length"] = lengths[n - 1].ToString (CultureInfo.InvariantCulture); + } + + static string Write (Found found) + { + var builder = new StringBuilder (512); + builder.Append (""); + builder.Append (""); + builder.Append ("'); + WriteElements (builder, found); + if (found.Items is not null) + WriteDirectory (builder, found.Items); + builder.Append (""); + return builder.ToString (); + } + + static void WriteNamespaces (StringBuilder builder, Found found) + { + var used = new HashSet (); + foreach (var property in Properties) { + if (found.Values.ContainsKey (Key (property.Prefix, property.Name)) && used.Add (property.Prefix)) + builder.Append (" xmlns:").Append (property.Prefix).Append ("=\"").Append (property.Ns).Append ('"'); + } + + if (found.Items is not null) + builder.Append (" xmlns:Container=\"").Append (Container).Append ("\" xmlns:Item=\"").Append (Item).Append ('"'); + } + + // Ultra HDR writes single values as attributes (the format's examples); arrays and Apple's properties + // (as ImageIO writes them) are elements. + static bool IsAttribute (string ns, List values) => ns is Hdrgm or Camera && values.Count == 1; + + static void WriteAttributes (StringBuilder builder, Found found) + { + foreach (var property in Properties) { + var key = Key (property.Prefix, property.Name); + if (found.Values.TryGetValue (key, out var values) && IsAttribute (property.Ns, values)) + builder.Append (' ').Append (key).Append ("=\"").Append (Escape (values[0])).Append ('"'); + } + } + + static void WriteElements (StringBuilder builder, Found found) + { + foreach (var property in Properties) { + var key = Key (property.Prefix, property.Name); + if (!found.Values.TryGetValue (key, out var values) || IsAttribute (property.Ns, values)) + continue; + builder.Append ('<').Append (key).Append ('>'); + if (values.Count == 1) { + builder.Append (Escape (values[0])); + } else { + builder.Append (""); + foreach (var value in values) + builder.Append ("").Append (Escape (value)).Append (""); + builder.Append (""); + } + + builder.Append ("'); + } + } + + static void WriteDirectory (StringBuilder builder, List> items) + { + builder.Append (""); + foreach (var item in items) { + builder.Append (""); + } + + builder.Append (""); + } + + static string Escape (string value) + { + var builder = new StringBuilder (value.Length); + foreach (var c in value) { + if (c == '&') + builder.Append ("&"); + else if (c == '<') + builder.Append ("<"); + else if (c == '"') + builder.Append ("""); + else + builder.Append (c); + } + + return builder.ToString (); + } +} diff --git a/src/TagLibSharp2/Image/ImageHeader.cs b/src/TagLibSharp2/Image/ImageHeader.cs new file mode 100644 index 00000000..d6261626 --- /dev/null +++ b/src/TagLibSharp2/Image/ImageHeader.cs @@ -0,0 +1,219 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using TagLibSharp2.Core; +using TagLibSharp2.Image.Jpeg; +using TagLibSharp2.Image.Svg; +using TagLibSharp2.Image.Tiff; + +namespace TagLibSharp2.Image; + +/// +/// Detects the still-image formats and reads their dimensions from the container, not from Exif. PNG IHDR is the +/// PNG specification, GIF the logical screen of GIF89a, BMP the DIB header, PCX the ZSoft window and Netpbm the +/// P1-P6 raster header; JPEG, TIFF and DNG, and SVG have their own readers (, +/// , ). +/// +internal static class ImageHeader +{ + public static bool TryDetect (ReadOnlySpan data, out MediaFormat format) + { + format = JpegSize.IsJpeg (data) ? MediaFormat.Jpeg + : IsPng (data) ? MediaFormat.Png + : IsGif (data) ? MediaFormat.Gif + : IsBmp (data) ? MediaFormat.Bmp + : IsPcx (data) ? MediaFormat.Pcx + : IsNetpbm (data) ? MediaFormat.Netpbm + : TiffReader.IsTiff (data) ? TiffSize.HasDngVersion (data) ? MediaFormat.Dng : MediaFormat.Tiff + : SvgSize.IsSvg (data) ? MediaFormat.Svg + : MediaFormat.Unknown; + return format != MediaFormat.Unknown; + } + + public static bool TryRead (ReadOnlySpan data, MediaFormat format, out ImageProperties? properties) + { + properties = null; + return format switch { + MediaFormat.Jpeg => JpegSize.TryRead (data, out properties), + MediaFormat.Png => TryPng (data, out properties), + MediaFormat.Gif => TryGif (data, out properties), + MediaFormat.Bmp => TryBmp (data, out properties), + MediaFormat.Pcx => TryPcx (data, out properties), + MediaFormat.Netpbm => TryNetpbm (data, out properties), + MediaFormat.Tiff => TiffSize.TryRead (data, dng: false, out properties), + MediaFormat.Dng => TiffSize.TryRead (data, dng: true, out properties), + MediaFormat.Svg => SvgSize.TryRead (data, out properties), + _ => false + }; + } + + // 0x89 must be written as a byte. In a UTF-8 literal, \x89 is U+0089 and encodes as C2 89. + static bool IsPng (ReadOnlySpan data) => + data.Length >= 8 + && data[0] == 0x89 && data[1] == (byte)'P' && data[2] == (byte)'N' && data[3] == (byte)'G' + && data[4] == 0x0D && data[5] == 0x0A && data[6] == 0x1A && data[7] == 0x0A; + + static bool TryPng (ReadOnlySpan data, out ImageProperties? properties) + { + properties = null; + if (!IsPng (data) || data.Length < 29 || !data.Slice (12, 4).SequenceEqual ("IHDR"u8)) + return false; + + var width = Endian.I32 (data, 16, le: false); + var height = Endian.I32 (data, 20, le: false); + if (width <= 0 || height <= 0) + return false; + + var bitDepth = data[24]; + var samples = data[25] switch { + 0 => 1, + 2 => 3, + 3 => 1, + 4 => 2, + 6 => 4, + _ => 0 + }; + if (samples == 0) + return false; + + properties = new ImageProperties (width, height, bitDepth * samples, "PNG"); + return true; + } + + static bool IsGif (ReadOnlySpan data) => + data.Length >= 6 && (data.StartsWith ("GIF87a"u8) || data.StartsWith ("GIF89a"u8)); + + static bool TryGif (ReadOnlySpan data, out ImageProperties? properties) + { + properties = null; + if (!IsGif (data) || data.Length < 13) + return false; + + var width = Endian.U16 (data, 6, le: true); + var height = Endian.U16 (data, 8, le: true); + if (width <= 0 || height <= 0) + return false; + + var depth = (data[10] & 0x07) + 1; + properties = new ImageProperties (width, height, depth, "GIF"); + return true; + } + + static bool IsBmp (ReadOnlySpan data) => + data.Length >= 26 && data[0] == (byte)'B' && data[1] == (byte)'M'; + + static bool TryBmp (ReadOnlySpan data, out ImageProperties? properties) + { + properties = null; + if (!IsBmp (data)) + return false; + + var header = Endian.I32 (data, 14, le: true); + int width; + int height; + var depth = 0; + if (header == 12) { + if (data.Length < 26) + return false; + width = Endian.U16 (data, 18, le: true); + height = Endian.U16 (data, 20, le: true); + depth = Endian.U16 (data, 24, le: true); + } else if (header >= 16 && data.Length >= 26) { + width = Endian.I32 (data, 18, le: true); + var rawHeight = Endian.I32 (data, 22, le: true); + if (rawHeight == int.MinValue) + return false; + height = rawHeight < 0 ? -rawHeight : rawHeight; + if (data.Length >= 30) + depth = Endian.U16 (data, 28, le: true); + } else { + return false; + } + + if (width <= 0 || height <= 0) + return false; + + properties = new ImageProperties (width, height, depth, "BMP"); + return true; + } + + static bool IsPcx (ReadOnlySpan data) => + data.Length >= 12 && data[0] == 0x0A && data[1] <= 5 && data[2] <= 1; + + static bool TryPcx (ReadOnlySpan data, out ImageProperties? properties) + { + properties = null; + if (!IsPcx (data)) + return false; + + var xmin = Endian.U16 (data, 4, le: true); + var ymin = Endian.U16 (data, 6, le: true); + var xmax = Endian.U16 (data, 8, le: true); + var ymax = Endian.U16 (data, 10, le: true); + if (xmax < xmin || ymax < ymin) + return false; + + var depth = (int)data[3]; + if (data.Length >= 66 && data[65] > 0) + depth *= data[65]; + + properties = new ImageProperties (xmax - xmin + 1, ymax - ymin + 1, depth, "PCX"); + return true; + } + + static bool IsNetpbm (ReadOnlySpan data) => + data.Length >= 3 && data[0] == (byte)'P' && data[1] is >= (byte)'1' and <= (byte)'6' && IsSpace (data[2]); + + static bool TryNetpbm (ReadOnlySpan data, out ImageProperties? properties) + { + properties = null; + if (!IsNetpbm (data)) + return false; + + var i = 2; + if (!TryNetpbmInt (data, ref i, out var width) || !TryNetpbmInt (data, ref i, out var height)) + return false; + if (width <= 0 || height <= 0) + return false; + + var kind = data[1] switch { + (byte)'1' or (byte)'4' => "PBM", + (byte)'2' or (byte)'5' => "PGM", + _ => "PPM" + }; + properties = new ImageProperties (width, height, 0, kind); + return true; + } + + static bool TryNetpbmInt (ReadOnlySpan data, ref int i, out int value) + { + value = 0; + while (i < data.Length) { + if (data[i] == (byte)'#') { + while (i < data.Length && data[i] != (byte)'\n') + i++; + } else if (IsSpace (data[i])) { + i++; + } else { + break; + } + } + + if (i >= data.Length || data[i] is < (byte)'0' or > (byte)'9') + return false; + + var acc = 0; + while (i < data.Length && data[i] is >= (byte)'0' and <= (byte)'9') { + var digit = data[i] - (byte)'0'; + if (acc > (1_000_000_000 - digit) / 10) + return false; + acc = (acc * 10) + digit; + i++; + } + + value = acc; + return true; + } + + static bool IsSpace (byte value) => value is (byte)' ' or (byte)'\t' or (byte)'\r' or (byte)'\n'; +} diff --git a/src/TagLibSharp2/Image/ImagePlan.cs b/src/TagLibSharp2/Image/ImagePlan.cs new file mode 100644 index 00000000..34ea6dfc --- /dev/null +++ b/src/TagLibSharp2/Image/ImagePlan.cs @@ -0,0 +1,340 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using TagLibSharp2.Core; + +namespace TagLibSharp2.Image; + +/// +/// Ordered new bytes and ranges of the original file. Rendering and writing are separate. +/// +sealed class ImagePlan +{ + readonly List _pieces = []; + + /// Gets the number of bytes the plan produces. + public long Length { get; private set; } + + /// Gets the exclusive end of the furthest original-file range. + public long SourceEnd { + get { + long end = 0; + foreach (var piece in _pieces) { + if (!piece.IsRange) + continue; + var pieceEnd = piece.Offset + piece.Length; + if (pieceEnd > end) + end = pieceEnd; + } + + return end; + } + } + + /// One range covering the whole original file. + /// Length of the original file. + public static ImagePlan Whole (int length) + { + var plan = new ImagePlan (); + plan.Copy (0, length); + return plan; + } + + /// Appends bytes that are not in the original file. + /// The new bytes. Empty appends nothing. + public void Add (ReadOnlySpan bytes) + { + if (bytes.IsEmpty) + return; + + Add (bytes.ToArray ()); + } + + /// Appends bytes that are not in the original file. + /// The new bytes. Empty appends nothing. The array is kept. + public void Add (byte[] bytes) + { + if (bytes.Length == 0) + return; + + AddLiteral (_pieces, bytes); + Length += bytes.Length; + } + + /// Appends a range of the original file. Adjacent ranges become one. + /// Offset in the original file. + /// Number of bytes. Zero appends nothing. + public void Copy (long offset, long count) + { + if (count == 0) + return; + +#if NETSTANDARD2_0 || NETSTANDARD2_1 + if (count < 0) + throw new ArgumentOutOfRangeException (nameof (count)); +#else + ArgumentOutOfRangeException.ThrowIfNegative (count); +#endif + AddRange (_pieces, offset, count); + Length += count; + } + + /// Appends another plan. Its ranges keep their original-file offsets. + /// Plan to append. + public void Append (ImagePlan other) + { + foreach (var piece in other._pieces) { + if (piece.IsRange) + Copy (piece.Offset, piece.Length); + else + Add (piece.Bytes!); + } + } + + /// Copies the plan into one buffer. + /// The original file. + /// The bytes the plan produces. + public byte[] Materialize (ReadOnlySpan source) + { + var output = new byte[checked((int)Length)]; + var dest = 0; + foreach (var piece in _pieces) { + var count = checked((int)piece.Length); + CopyPiece (piece, 0, count, source, output.AsSpan (dest, count)); + dest += count; + } + + return output; + } + + /// + /// Returns when the plan is that whole file; otherwise . + /// + /// The original file. + public ReadOnlyMemory MaterializeShared (byte[] source) + { + if (_pieces.Count == 1 && _pieces[0].IsRange && _pieces[0].Offset == 0 && _pieces[0].Length == source.Length) + return source; + + return Materialize (source); + } + + /// Copies one span of the output. + /// Offset in the output. + /// Number of bytes. + /// The original file, for ranges. + public byte[] MaterializeRange (long start, long count, ReadOnlySpan source) + { + if (start < 0 || count < 0 || start > Length || count > Length - start) + throw new ArgumentOutOfRangeException (nameof (start)); + + var output = new byte[checked((int)count)]; + if (count == 0) + return output; + + var filled = 0; + var skip = start; + foreach (var piece in _pieces) { + if (skip >= piece.Length) { + skip -= piece.Length; + continue; + } + + var take = (int)Math.Min (piece.Length - skip, count - filled); + CopyPiece (piece, skip, take, source, output.AsSpan (filled, take)); + filled += take; + skip = 0; + if (filled == count) + return output; + } + + throw new ArgumentOutOfRangeException (nameof (count)); + } + + /// Removes an output span. Ranges on either side keep their original-file offsets. + /// Offset in the output. + /// Number of bytes removed. Zero removes nothing. + public void Cut (long start, long count) + { + if (count == 0) + return; + + if (start < 0 || count < 0 || start > Length || count > Length - start) + throw new ArgumentOutOfRangeException (nameof (start)); + + ReplaceSpan (start, start + count, null); + Length -= count; + } + + /// Replaces an output span with of the same length. + /// Offset in the output. + /// Number of bytes replaced. + /// The new bytes. Its length is . + public void Splice (long start, long count, byte[] replacement) + { + if (count == 0) + return; + + if (start < 0 || count < 0 || start > Length || count > Length - start || replacement.Length != count) + throw new ArgumentOutOfRangeException (nameof (start)); + + ReplaceSpan (start, start + count, replacement); + } + + // insert null removes the span. Otherwise the span is replaced by those bytes. + void ReplaceSpan (long start, long end, byte[]? insert) + { + var next = new List (_pieces.Count + 1); + long at = 0; + var inserted = insert is null; + foreach (var piece in _pieces) { + var pieceEnd = at + piece.Length; + if (pieceEnd <= start || at >= end) { + AddExisting (next, piece); + } else { + var before = start > at ? start - at : 0; + if (before > 0) + AddSlice (next, piece, 0, before); + if (!inserted) { + AddLiteral (next, insert!); + inserted = true; + } + + var after = pieceEnd > end ? pieceEnd - end : 0; + if (after > 0) + AddSlice (next, piece, piece.Length - after, after); + } + + at = pieceEnd; + } + + if (!inserted) + throw new ArgumentOutOfRangeException (nameof (start)); + + _pieces.Clear (); + _pieces.AddRange (next); + } + + /// + /// Writes the plan. Ranges come from when it is set, and from + /// when it is not. New bytes are written as they are. + /// + /// Original file, or null to read ranges from . + /// Original bytes used when is null. + /// Stream that receives the output. + /// Buffer from . + /// Checked before each chunk. Cancelled copies throw. + public void Write ( + Stream? source, + ReadOnlySpan held, + Stream destination, + byte[] chunk, + CancellationToken cancellationToken = default) + { + foreach (var piece in _pieces) { + if (!piece.IsRange) { + WriteChunked (destination, piece.Bytes, chunk, cancellationToken); + continue; + } + + if (source is not null) { + if (source.Position != piece.Offset) + source.Position = piece.Offset; + CopyChunked (source, destination, piece.Length, chunk, cancellationToken); + continue; + } + + var offset = checked((int)piece.Offset); + var count = checked((int)piece.Length); + WriteChunked (destination, held.Slice (offset, count), chunk, cancellationToken); + } + } + + // One StreamCopy call is at most one chunk, so a cancel during a write stops the next chunk. + static void CopyChunked ( + Stream source, + Stream destination, + long count, + byte[] chunk, + CancellationToken cancellationToken) + { + var left = count; + while (left > 0) { + cancellationToken.ThrowIfCancellationRequested (); + var take = left < StreamCopy.ChunkSize ? left : StreamCopy.ChunkSize; + StreamCopy.Copy (source, destination, take, chunk); + left -= take; + } + } + + static void WriteChunked ( + Stream destination, + ReadOnlySpan data, + byte[] chunk, + CancellationToken cancellationToken) + { + var offset = 0; + while (offset < data.Length) { + cancellationToken.ThrowIfCancellationRequested (); + var count = Math.Min (StreamCopy.ChunkSize, data.Length - offset); + StreamCopy.Write (destination, data.Slice (offset, count), chunk); + offset += count; + } + } + + static void CopyPiece (Piece piece, long skip, int take, ReadOnlySpan source, Span destination) + { + if (piece.IsRange) + source.Slice (checked((int)(piece.Offset + skip)), take).CopyTo (destination); + else + piece.Bytes!.AsSpan (checked((int)skip), take).CopyTo (destination); + } + + static void AddExisting (List pieces, Piece piece) + { + if (piece.IsRange) + AddRange (pieces, piece.Offset, piece.Length); + else + AddLiteral (pieces, piece.Bytes!); + } + + static void AddSlice (List pieces, Piece piece, long skip, long count) + { + if (count == 0) + return; + + if (piece.IsRange) { + AddRange (pieces, piece.Offset + skip, count); + return; + } + + var slice = new byte[checked((int)count)]; + piece.Bytes!.AsSpan (checked((int)skip), slice.Length).CopyTo (slice); + AddLiteral (pieces, slice); + } + + // Each new piece stays its own entry. Copying it onto the previous piece would copy every byte gathered so + // far, once per piece. + static void AddLiteral (List pieces, byte[] bytes) + { + if (bytes.Length == 0) + return; + + pieces.Add (new Piece (false, 0, bytes.Length, bytes)); + } + + static void AddRange (List pieces, long offset, long count) + { + if (pieces.Count > 0) { + var last = pieces[^1]; + if (last.IsRange && last.Offset + last.Length == offset) { + pieces[^1] = new Piece (true, last.Offset, last.Length + count, null); + return; + } + } + + pieces.Add (new Piece (true, offset, count, null)); + } + + readonly record struct Piece (bool IsRange, long Offset, long Length, byte[]? Bytes); +} diff --git a/src/TagLibSharp2/Image/ImageRewrite.cs b/src/TagLibSharp2/Image/ImageRewrite.cs new file mode 100644 index 00000000..8eac3d1b --- /dev/null +++ b/src/TagLibSharp2/Image/ImageRewrite.cs @@ -0,0 +1,108 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Diagnostics.CodeAnalysis; +using TagLibSharp2.Core; +using TagLibSharp2.Image.Gif; +using TagLibSharp2.Image.Jpeg; +using TagLibSharp2.Image.Png; + +namespace TagLibSharp2.Image; + +/// +/// Reads and splices the text blocks an image format already defines: PNG tEXt, zTXt and iTXt, the GIF comment +/// extension, and the JPEG COM marker before the scan. Pixel bytes are copied through. +/// +static class ImageRewrite +{ + internal static ImageTag? CreateTag (ReadOnlySpan data, MediaFormat format) + { + var stores = format switch { + MediaFormat.Png => ImageStores.Png, + MediaFormat.Gif or MediaFormat.Jpeg => ImageStores.CommentOnly, + _ => ImageStores.None + }; + if (stores == ImageStores.None) + return null; + + var tag = new ImageTag (format, stores); + if (format == MediaFormat.Png) + PngRewriter.Read (data, tag); + else if (format == MediaFormat.Gif) + GifRewriter.Read (data, tag); + else + JpegRewriter.Read (data, tag); + return tag; + } + + internal static byte[] RenderTag (ImageTag tag) + { + using var builder = new BinaryDataBuilder (); + if (tag.Format == MediaFormat.Png) + PngRewriter.AddFields (builder, tag, onlyChanged: false); + else if (tag.Field (ImageStores.Comment) is string comment) { + if (tag.Format == MediaFormat.Gif) + GifRewriter.AddComment (builder, comment); + else + builder.Add (JpegRewriter.EncodeComment (comment)); + } + + return builder.ToArray (); + } + + /// A plan for a format whose path save copies original ranges. False when the container cannot be updated. + internal static bool TryPlan ( + ReadOnlySpan data, + MediaFormat format, + ImageTag? tag, + [NotNullWhen (true)] out ImagePlan? plan, + [NotNullWhen (false)] out string? error) + { + error = null; + if (format == MediaFormat.Png) + return TryEditedPlan (data, tag, PngRewriter.Plan, PngRewriter.SpliceError, out plan, out error); + if (format == MediaFormat.Gif) + return TryEditedPlan (data, tag, GifRewriter.Plan, GifRewriter.SpliceError, out plan, out error); + if (format == MediaFormat.Jpeg) + return TryEditedPlan (data, tag, JpegRewriter.Plan, JpegRewriter.SpliceError, out plan, out error); + if (CopiesWholeFile (format)) { + plan = ImagePlan.Whole (data.Length); + return true; + } + + plan = null; + error = "The image container could not be updated."; + return false; + } + + /// + /// An unchanged file is one range of the original. An edit is that format's plan, or its splice error. + /// + static bool TryEditedPlan ( + ReadOnlySpan data, + ImageTag? tag, + RewriterPlan build, + string spliceError, + [NotNullWhen (true)] out ImagePlan? plan, + [NotNullWhen (false)] out string? error) + { + error = null; + if (tag is null || !tag.AffectsFile) { + plan = ImagePlan.Whole (data.Length); + return true; + } + + plan = build (data, tag, out error); + if (plan is null && error is null) + error = spliceError; + return plan is not null; + } + + delegate ImagePlan? RewriterPlan (ReadOnlySpan data, ImageTag tag, out string? error); + + /// These formats have no metadata rewriter, so the plan is the original file. + static bool CopiesWholeFile (MediaFormat format) => + format is MediaFormat.Tiff or MediaFormat.Dng + or MediaFormat.Bmp or MediaFormat.Pcx + or MediaFormat.Netpbm or MediaFormat.Svg; +} diff --git a/src/TagLibSharp2/Image/ImageTag.cs b/src/TagLibSharp2/Image/ImageTag.cs new file mode 100644 index 00000000..584fd36c --- /dev/null +++ b/src/TagLibSharp2/Image/ImageTag.cs @@ -0,0 +1,191 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using TagLibSharp2.Core; + +namespace TagLibSharp2.Image; + +[Flags] +enum ImageStores +{ + None = 0, + Title = 1 << 0, + Artist = 1 << 1, + Description = 1 << 2, + Copyright = 1 << 3, + Year = 1 << 4, + Comment = 1 << 5, + Png = Title | Artist | Description | Copyright | Year | Comment, + CommentOnly = Comment +} + +/// +/// Text stored in an image file. PNG keeps the standard text keywords. +/// GIF and JPEG keep the comment. A field the format does not store reads +/// back as null, and assigning it changes nothing. +/// +sealed class ImageTag : Tag +{ + readonly ImageStores _stores; + ImageStores _dirty; + string? _title; + string? _artist; + string? _description; + string? _copyright; + string? _year; + string? _comment; + + internal ImageTag (MediaFormat format, ImageStores stores) + { + Format = format; + _stores = stores; + } + + internal MediaFormat Format { get; } + + /// Clear asked the rewriter to drop text it does not map onto a field. + internal bool DropUnmapped { get; private set; } + + internal bool AffectsFile => _dirty != 0 || DropUnmapped; + + internal bool Changed (ImageStores field) => (_dirty & field) != 0; + + internal string? Field (ImageStores field) => field switch { + ImageStores.Title => _title, + ImageStores.Artist => _artist, + ImageStores.Description => _description, + ImageStores.Copyright => _copyright, + ImageStores.Year => _year, + ImageStores.Comment => _comment, + _ => null + }; + + internal void ReadField (ImageStores field, string? value) + { + if (field == ImageStores.None || (_stores & field) == 0) + return; + Assign (field, string.IsNullOrEmpty (value) ? null : value, markDirty: false); + } + + /// + public override TagTypes TagType => TagTypes.Image; + + /// + public override string? Title { + get => _title; + set => Assign (ImageStores.Title, value, markDirty: true); + } + + /// + public override string? Artist { + get => _artist; + set => Assign (ImageStores.Artist, value, markDirty: true); + } + + /// + public override string? Album { + get => null; + set { } + } + + /// + public override string? Year { + get => _year; + set => Assign (ImageStores.Year, value, markDirty: true); + } + + /// + public override string? Comment { + get => _comment; + set => Assign (ImageStores.Comment, value, markDirty: true); + } + + /// + public override string? Genre { + get => null; + set { } + } + + /// + public override uint? Track { + get => null; + set { } + } + + /// + public override string? Description { + get => _description; + set => Assign (ImageStores.Description, value, markDirty: true); + } + + /// + public override string? Copyright { + get => _copyright; + set => Assign (ImageStores.Copyright, value, markDirty: true); + } + + /// + public override bool IsEmpty => + base.IsEmpty + && string.IsNullOrEmpty (_description) + && string.IsNullOrEmpty (_copyright); + + /// + public override BinaryData Render () => new (ImageRewrite.RenderTag (this)); + + /// + public override void Clear () + { + DropUnmapped = true; + ClearStored (ImageStores.Title); + ClearStored (ImageStores.Artist); + ClearStored (ImageStores.Description); + ClearStored (ImageStores.Copyright); + ClearStored (ImageStores.Year); + ClearStored (ImageStores.Comment); + } + + void ClearStored (ImageStores field) + { + if (Field (field) is null) + return; + Assign (field, null, markDirty: true); + } + + void Assign (ImageStores field, string? value, bool markDirty) + { + if ((_stores & field) == 0) + return; + value = EmptyAsNull (value); + if (string.Equals (Field (field), value, StringComparison.Ordinal)) + return; + + switch (field) { + case ImageStores.Title: + _title = value; + break; + case ImageStores.Artist: + _artist = value; + break; + case ImageStores.Description: + _description = value; + break; + case ImageStores.Copyright: + _copyright = value; + break; + case ImageStores.Year: + _year = value; + break; + case ImageStores.Comment: + _comment = value; + break; + default: + return; + } + + if (markDirty && (_stores & field) != 0) + _dirty |= field; + } + + static string? EmptyAsNull (string? value) => string.IsNullOrEmpty (value) ? null : value; +} diff --git a/src/TagLibSharp2/Image/Jpeg/JpegRewriter.cs b/src/TagLibSharp2/Image/Jpeg/JpegRewriter.cs new file mode 100644 index 00000000..9d4cf774 --- /dev/null +++ b/src/TagLibSharp2/Image/Jpeg/JpegRewriter.cs @@ -0,0 +1,496 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Text; +using TagLibSharp2.Core; +using TagLibSharp2.Image; +using TagLibSharp2.Image.Exif; +using TagLibSharp2.Image.Xmp; + +namespace TagLibSharp2.Image.Jpeg; + +/// +/// Reads a JPEG's COM segments and splices a new comment before the scan (ITU-T T.81 §B.2.4.5). Clear also drops +/// the metadata APPn segments of every image a multi-picture index lists, and rewrites the index. Every byte from +/// the scan on is copied as it is. +/// +static class JpegRewriter +{ + const int MaxSegment = 65535; + internal const string SpliceError = "The JPEG marker list before the scan is truncated or malformed, so the comment cannot be spliced in."; + + public static void Read (ReadOnlySpan data, ImageTag tag) + { + if (TryComment (data, out var text)) + tag.ReadField (ImageStores.Comment, text); + } + + /// The edited file as new pieces and ranges of . + public static ImagePlan? Plan (ReadOnlySpan data, ImageTag tag, out string? error) + { + error = null; + if (!tag.Changed (ImageStores.Comment) && !tag.DropUnmapped) + return null; + byte[]? replacement = tag.Changed (ImageStores.Comment) + ? tag.Field (ImageStores.Comment) is string comment ? EncodeComment (comment) : [] + : null; + return TryRewrite (data, tag, replacement, out error); + } + + static bool IsSoi (ReadOnlySpan data) => data.Length >= 2 && data[0] == 0xFF && data[1] == 0xD8; + + static bool TryComment (ReadOnlySpan data, out string? text) + { + text = null; + if (!IsSoi (data)) + return false; + var collected = new List (); + var i = 2; + while (i < data.Length) { + if (data[i] != 0xFF) + return collected.Count > 0; + while (i < data.Length && data[i] == 0xFF) + i++; + if (i >= data.Length) + return false; + var marker = data[i++]; + if (marker is 0x01 or (>= 0xD0 and <= 0xD9)) { + if (marker == 0xD9) + break; + continue; + } + + if (i + 1 >= data.Length) + return false; + var length = Endian.U16 (data, i, le: false); + if (length < 2 || i + length > data.Length) + return false; + if (marker == 0xDA) + break; + if (marker == 0xFE) + collected.AddRange (data.Slice (i + 2, length - 2).ToArray ()); + i += length; + } + + text = collected.Count == 0 ? null : Encoding.UTF8.GetString (collected.ToArray ()); + return true; + } + + static ImagePlan? TryRewrite (ReadOnlySpan data, ImageTag tag, byte[]? comment, out string? error) + { + error = null; + var dropMetadata = tag.DropUnmapped; + if (!IsSoi (data)) { + error = SpliceError; + return null; + } + + // CIPA DC-007 §5.2: the first image's APP2 "MPF" index lists every image of a multi-picture file. Each + // later image is a whole JPEG with its own APPn after the first image's EOI; Clear cleans those too. + var index = MpfIndex.Read (data); + if (dropMetadata && index.Unreadable) { + error = "The JPEG MPF index cannot be read, so the metadata of the file's other images cannot be cleared."; + return null; + } + + var images = dropMetadata ? index.Images : []; + if (!TryCleanLaterImages (data, images, tag, out var cleaned, out error)) + return null; + + // A version-65536 Apple gain map takes its headroom from the primary's maker note, so the later images are + // read first to know whether the primary keeps those two values (AppleHeadroom). + var options = new ImageOptions (comment, dropMetadata, Mirrors: comment is not null && !dropMetadata, + ItemLengths: dropMetadata ? cleaned.ConvertAll (c => c.Plan.Length) : null, AppleHeadroom: cleaned.Exists (c => c.HeadroomInMakerNote)); + var primaryEnd = images.Count > 0 ? images[0].Start : data.Length; + var primary = RewriteImage (data.Slice (0, primaryEnd), tag, options, 0, out error); + if (primary is null) + return null; + if (primary.InMpf < 0) + return primary.Plan; + if (images.Count == 0) + return ShiftMpEntries (primary, data, out error); + return PlaceImages (data, primary, primaryEnd, images, cleaned, out error); + } + + // The later images are cleaned first: an Ultra HDR primary lists their lengths (Item:Length). + static bool TryCleanLaterImages (ReadOnlySpan data, List images, ImageTag tag, out List cleaned, out string? error) + { + error = null; + cleaned = []; + var options = new ImageOptions ([], DropMetadata: true, Mirrors: false, ItemLengths: null, AppleHeadroom: false); + foreach (var image in images) { + if (RewriteImage (data.Slice (image.Start, image.Size), tag, options, image.Start, out _) is not JpegImage clean) { + error = $"Image {image.Entry + 1} of the JPEG MPF index cannot be parsed, so its metadata cannot be cleared."; + return false; + } + + cleaned.Add (clean); + } + + return true; + } + + // Everything after the scan is copied, so the later images move with the bytes between the MP header and the + // scan, and image 1's size changes with everything before the scan. + static ImagePlan? ShiftMpEntries (JpegImage primary, ReadOnlySpan source, out string? error) + { + error = null; + var offsetDelta = (primary.OutRest - primary.OutMpf) - (long)(primary.InRest - primary.InMpf); + var sizeDelta = primary.OutRest - (long)primary.InRest; + if (offsetDelta == 0 && sizeDelta == 0) + return primary.Plan; + var count = primary.OutMpfEnd - primary.OutMpf; + var window = primary.Plan.MaterializeRange (primary.OutMpf, count, source); + if (!MpfIndex.TryRewriteEntries (window, 0, window.Length, (n, offset, size) => offset == 0 ? (0, size + sizeDelta) : (offset + offsetDelta, size))) { + error = "The JPEG MPF index cannot be read, so the offsets of its other images cannot be kept right after the edit."; + return null; + } + + primary.Plan.Splice (primary.OutMpf, count, window); + return primary.Plan; + } + + // The cleaned primary, then each cleaned later image in place of the old one with the bytes between copied, and + // every MP entry pointed at its image's new place. + static ImagePlan? PlaceImages (ReadOnlySpan data, JpegImage primary, int primaryEnd, List images, List cleaned, out string? error) + { + error = null; + var output = new ImagePlan (); + output.Append (primary.Plan); + var placed = new Dictionary (); + var at = primaryEnd; + for (var n = 0; n < images.Count; n++) { + var gap = images[n].Start - at; + if (gap > 0) + output.Copy (at, gap); + placed[images[n].Entry] = (output.Length, cleaned[n].Plan.Length); + output.Append (cleaned[n].Plan); + at = images[n].Start + images[n].Size; + } + + if (at < data.Length) + output.Copy (at, data.Length - at); + var count = primary.OutMpfEnd - primary.OutMpf; + var window = output.MaterializeRange (primary.OutMpf, count, data); + var primaryDelta = primary.Plan.Length - primaryEnd; + var header = primary.OutMpf; + if (!MpfIndex.TryRewriteEntries (window, 0, window.Length, (n, offset, size) => + placed.TryGetValue (n, out var image) ? (image.Start - header, image.Size) : offset == 0 ? (0, size + primaryDelta) : (offset, size))) { + error = "The JPEG MPF index cannot be read, so the offsets of its other images cannot be kept right after Clear."; + return null; + } + + output.Splice (header, count, window); + return output; + } + + // How one image is rewritten: the comment to add (null keeps the COM segments), whether its metadata is + // dropped (Clear), whether the APP1 copies of a changed comment are updated, the gain-map item lengths to + // write, and whether its first Exif keeps the Apple maker-note headroom. + sealed record ImageOptions (byte[]? Comment, bool DropMetadata, bool Mirrors, IReadOnlyList? ItemLengths, bool AppleHeadroom); + + sealed class JpegImage + { + public ImagePlan Plan { get; init; } = new (); + public int InMpf { get; init; } = -1; + public int OutMpf { get; init; } = -1; + public int OutMpfEnd { get; init; } = -1; + public int InRest { get; init; } + public int OutRest { get; init; } + public bool HeadroomInMakerNote { get; init; } + } + + // Rewrites the marker segments of one image up to its scan (or EOI), adds the new comment there, and copies + // the rest of the span as it is. + static JpegImage? RewriteImage (ReadOnlySpan data, ImageTag tag, ImageOptions options, int origin, out string? error) + { + error = null; + if (!IsSoi (data)) + return Fail (out error); + var image = new ImageBuilder (tag, options, origin); + image.Keep (0, 2); + var i = 2; + while (i < data.Length) { + var start = i; + if (!TryMarker (data, ref i, out var marker)) + return Fail (out error); + + if (marker is 0x01 or (>= 0xD0 and <= 0xD8)) { + image.Keep (start, i - start); + continue; + } + + if (marker == 0xD9) + return image.Finish (data, start, out error); + if (!TryLength (data, i, out var length)) + return Fail (out error); + + if (marker == 0xDA) + return image.Finish (data, start, out error); + + // Fill bytes (0xFF) before the marker (T.81 §B.1.1.2) are part of what is kept or rewritten. + var segment = new Segment (marker, start, data.Slice (start, i - 2 - start), data.Slice (start, i + length - start), data.Slice (i + 2, length - 2)); + i += length; + if (!image.TryAdd (segment, out error)) + return null; + } + + return image.Finish (data, data.Length, out error); + } + + static JpegImage? Fail (out string? error) + { + error = SpliceError; + return null; + } + + // At a 0xFF, skips the fill bytes and reads the marker; false when the byte is not 0xFF or the data ends. + static bool TryMarker (ReadOnlySpan data, ref int i, out byte marker) + { + marker = 0; + if (data[i] != 0xFF) + return false; + while (i < data.Length && data[i] == 0xFF) + i++; + if (i >= data.Length) + return false; + marker = data[i++]; + return true; + } + + // The segment length at i (it counts itself), when the segment lies inside the data. + static bool TryLength (ReadOnlySpan data, int i, out int length) + { + length = 0; + if (i + 1 >= data.Length) + return false; + length = Endian.U16 (data, i, le: false); + return length >= 2 && i + length <= data.Length; + } + + // A marker segment: where it starts, the fill bytes before its marker, the whole segment and its payload. + readonly ref struct Segment (byte marker, int start, ReadOnlySpan fill, ReadOnlySpan whole, ReadOnlySpan payload) + { + public byte Marker { get; } = marker; + public int Start { get; } = start; + public ReadOnlySpan Fill { get; } = fill; + public ReadOnlySpan Whole { get; } = whole; + public ReadOnlySpan Payload { get; } = payload; + } + + // The output of one image as its segments are kept, dropped or rewritten. + sealed class ImageBuilder (ImageTag tag, ImageOptions options, int origin) + { + readonly ImagePlan _plan = new (); + int _inMpf = -1; + int _outMpf = -1; + int _mpfLength; + bool _headroomInMakerNote; + bool _firstExif = true; + + int Written => checked((int)_plan.Length); + + public void Keep (int start, int count) => _plan.Copy (origin + (long)start, count); + + public bool TryAdd (Segment segment, out string? error) + { + error = null; + var marker = segment.Marker; + var payload = segment.Payload; + if (options.DropMetadata && marker == 0xE1 && TryClearApp1 (segment)) + return true; + if ((options.Comment is not null && marker == 0xFE) || (options.DropMetadata && marker is >= 0xE0 and <= 0xEF && !IsKeptOnClear (marker, payload))) + return true; + if (marker == 0xE2 && _inMpf < 0 && payload.StartsWith ("MPF\0"u8)) { + _inMpf = segment.Start + (segment.Whole.Length - payload.Length) + 4; + _outMpf = Written + (segment.Whole.Length - payload.Length) + 4; + _mpfLength = payload.Length - 4; + } + + if (options.Mirrors && marker == 0xE1) { + if (!TryMirrorApp1 (payload, tag, out var edited, out error)) + return false; + if (edited is not null) { + AddEdited (segment, edited); + return true; + } + } + + Keep (segment.Start, segment.Whole.Length); + return true; + } + + // Clear keeps only the gain-map XMP an HDR decoder needs (ImageGainMap), and of the first Exif (the one + // readers use) only the Apple maker-note headroom. True when the segment was handled (kept or dropped). + bool TryClearApp1 (Segment segment) + { + var payload = segment.Payload; + if (TryXmpSignature (payload, out var signature)) { + var kept = ImageGainMap.KeepForClear (payload.Slice (signature), options.ItemLengths, out var makerNote); + if (kept is null || 2 + signature + kept.Length > MaxSegment) + return true; + _headroomInMakerNote |= makerNote; + AddEdited (segment, SegmentBytes (0xE1, [.. payload.Slice (0, signature), .. kept])); + return true; + } + + if (!payload.StartsWith ("Exif\0\0"u8) || !_firstExif) + return false; + _firstExif = false; + if (options.AppleHeadroom && AppleHeadroom.Keep (payload.Slice (6)) is byte[] headroom) + AddEdited (segment, SegmentBytes (0xE1, [.. "Exif\0\0"u8, .. headroom])); + return true; + } + + void AddEdited (Segment segment, byte[] replacement) + { + if (!segment.Fill.IsEmpty) + _plan.Copy (origin + (long)segment.Start, segment.Fill.Length); + _plan.Add (replacement); + } + + public JpegImage? Finish (ReadOnlySpan data, int rest, out string? error) + { + if (options.Comment is { Length: > 0 }) + _plan.Add (options.Comment); + var outRest = Written; + _plan.Copy (origin + (long)rest, data.Length - rest); + error = null; + return Built (outRest, rest); + } + + JpegImage Built (int outRest, int rest) => new () { + Plan = _plan, + InMpf = _inMpf, + OutMpf = _outMpf, + OutMpfEnd = _outMpf < 0 ? -1 : _outMpf + _mpfLength, + InRest = rest, + OutRest = outRest, + HeadroomInMakerNote = _headroomInMakerNote + }; + } + + // "http://ns.adobe.com/xap/1.0/" then NUL (XMP Part 3 §1.1.3), or with a space before the NUL as some writers + // do; exiftool and ImageIO read that packet too. + static bool TryXmpSignature (ReadOnlySpan payload, out int length) + { + length = payload.StartsWith ("http://ns.adobe.com/xap/1.0/\0"u8) ? 29 : payload.StartsWith ("http://ns.adobe.com/xap/1.0/ \0"u8) ? 30 : 0; + return length > 0; + } + + // A Comment edit also changes the copies of the comment in APP1: Exif UserComment and XPComment, and XMP + // exif:UserComment. Extended XMP is spread over several segments and keyed by a digest of its content; when + // it may hold the comment, the save is refused rather than leave a stale copy. + static bool TryMirrorApp1 (ReadOnlySpan payload, ImageTag tag, out byte[]? edited, out string? error) + { + edited = null; + error = null; + if (payload.StartsWith ("Exif\0\0"u8)) { + var carrier = new ExifCarrier ("JPEG Exif", exif => SegmentBytes (0xE1, exif)); + return carrier.TryEdit (payload, tag, out edited, out error); + } + if (TryXmpSignature (payload, out var signature)) + return TryMirrorXmp (payload, signature, tag, out edited, out error); + if (payload.StartsWith ("http://ns.adobe.com/xmp/extension/\0"u8) && payload.IndexOf ("UserComment"u8) >= 0) { + error = "The JPEG extended XMP holds a UserComment, a copy of Comment that cannot be updated here."; + return false; + } + + return true; + } + + static bool TryMirrorXmp (ReadOnlySpan payload, int signature, ImageTag tag, out byte[]? edited, out string? error) + { + edited = null; + var packet = Encoding.UTF8.GetString (payload.Slice (signature)); + if (!XmpMirror.TryUpdate (packet, tag, "JPEG XMP packet", out var updated, out error)) + return false; + if (ReferenceEquals (updated, packet)) + return true; + var bytes = Encoding.UTF8.GetBytes (updated); + if (2 + signature + bytes.Length > MaxSegment) { + error = "The JPEG XMP packet would no longer fit in one APP1 segment after the comment edit."; + return false; + } + + var body = new byte[signature + bytes.Length]; + payload.Slice (0, signature).CopyTo (body); + bytes.CopyTo (body, signature); + edited = SegmentBytes (0xE1, body); + return true; + } + + static byte[] SegmentBytes (byte marker, byte[] payload) + { + var segment = new byte[4 + payload.Length]; + segment[0] = 0xFF; + segment[1] = marker; + segment[2] = (byte)((payload.Length + 2) >> 8); + segment[3] = (byte)(payload.Length + 2); + payload.CopyTo (segment, 4); + return segment; + } + + // Clear drops every APPn segment except the ones a decoder or colour management needs, or that carry the + // file's structure: + // - APP0 "JFIF" and "JFXX" (JFIF 1.02: pixel density and the format of the file, and its thumbnail); + // - APP2 "ICC_PROFILE" (ICC.1 Annex B.4: the colour profile); + // - APP2 "MPF" (CIPA DC-007 §5.2: the index of the images of a multi-picture file, and their attributes); + // - APP2 "urn:iso:std:iso:ts:21496:-1" (ISO 21496-1: the gain map version and parameters an HDR decoder + // applies to the gain-map image); + // - APP14 "Adobe" (the colour transform flag that says whether the components are YCbCr or YCCK); + // - APP11 JPEG XT boxes a JPEG XT decoder uses to rebuild the image. Each APP11 segment holds "JP", the box + // instance En, the sequence number Z, then the box's LBox and TBox, repeated in every segment of a box + // (ISO/IEC 18477-3 Annex A). The decoding boxes are those named in A. Artusi et al., "JPEG XT: A Compression + // Standard for HDR and WCG Images", IEEE Signal Processing Magazine 33(2), 2016, §III and Fig. 3: ftyp (file + // type), TONE (inverse tone mapping), RTRF and LTRF (residual and base colour transforms), LCHK (legacy data + // checksum), SPEC (the superbox that says how to reassemble the image) and RESI (the residual codestream). + // A legacy decoder skips every APP11 box (same paper, §III), so the base image never needs them. Every other + // box goes: JUMBF superboxes "jumb" (ISO/IEC 19566-5: C2PA, JSON, XML), "xml ", "uuid", "json", "Exif", and + // unknown types. (Annex B of 18477-3, the full box list, is not public; refinement and alpha boxes are not + // named there and are dropped.) + // Exif (but for the Apple maker-note headroom a version-65536 gain map needs, AppleHeadroom), XMP and extended + // XMP, Photoshop/IPTC, Ducky, FlashPix, maker segments such as SCALADO, and unknown APPn are dropped. Segments + // other than APPn (tables, frame, restart interval) are kept. + static bool IsKeptOnClear (byte marker, ReadOnlySpan payload) => marker switch { + 0xE0 => payload.StartsWith ("JFIF\0"u8) || payload.StartsWith ("JFXX\0"u8), + 0xE2 => payload.StartsWith ("ICC_PROFILE\0"u8) || payload.StartsWith ("MPF\0"u8) || payload.StartsWith ("urn:iso:std:iso:ts:21496:-1\0"u8), + 0xEB => payload.Length >= 16 && payload[0] == (byte)'J' && payload[1] == (byte)'P' && IsXtDecodingBox (payload.Slice (12, 4)), + 0xEE => payload.StartsWith ("Adobe"u8), + _ => false + }; + + static readonly string[] XtDecodingBoxes = ["ftyp", "TONE", "RTRF", "LTRF", "LCHK", "SPEC", "RESI"]; + + static bool IsXtDecodingBox (ReadOnlySpan type) + { + foreach (var box in XtDecodingBoxes) { + if (type[0] == box[0] && type[1] == box[1] && type[2] == box[2] && type[3] == box[3]) + return true; + } + + return false; + } + + /// COM segments of at most 65,533 bytes each, split between UTF-8 sequences. + public static byte[] EncodeComment (string comment) + { + var bytes = Encoding.UTF8.GetBytes (comment); + using var builder = new BinaryDataBuilder (bytes.Length + 8); + var offset = 0; + while (offset < bytes.Length) { + var take = Math.Min (65533, bytes.Length - offset); + while (take > 0 && offset + take < bytes.Length && (bytes[offset + take] & 0xC0) == 0x80) + take--; + if (take == 0) + take = Math.Min (65533, bytes.Length - offset); + builder.Add (0xFF); + builder.Add (0xFE); + builder.AddUInt16BE ((ushort)(take + 2)); + builder.Add (bytes.AsSpan (offset, take)); + offset += take; + } + + return builder.ToArray (); + } +} diff --git a/src/TagLibSharp2/Image/Jpeg/JpegSize.cs b/src/TagLibSharp2/Image/Jpeg/JpegSize.cs new file mode 100644 index 00000000..e0a28c73 --- /dev/null +++ b/src/TagLibSharp2/Image/Jpeg/JpegSize.cs @@ -0,0 +1,140 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using TagLibSharp2.Core; +using TagLibSharp2.Image; + +namespace TagLibSharp2.Image.Jpeg; + +/// +/// The width, height and bit depth of a JPEG: the first start-of-frame segment (ITU-T T.81 §B.2.2), or with a zero +/// height, the DNL segment after the first scan (§B.2.5). +/// +static class JpegSize +{ + public static bool IsJpeg (ReadOnlySpan data) => + data.Length >= 3 && data[0] == 0xFF && data[1] == 0xD8 && data[2] == 0xFF; + + public static bool TryRead (ReadOnlySpan data, out ImageProperties? properties) + { + properties = null; + if (!IsJpeg (data)) + return false; + var i = 2; + Frame? pending = null; + while (TryNextSegment (data, ref i, out var marker, out var length)) { + if (IsStartOfFrame (marker)) { + if (!TryFrame (data.Slice (i, length), out var frame)) + return false; + if (frame.Height > 0) { + properties = frame.Properties (frame.Height); + return true; + } + + // ITU-T T.81 §B.2.2: a zero height is defined by the DNL segment at the end of the first scan. + pending = frame; + } else if (marker == 0xDA) { + if (pending is not Frame waiting || !TryDnlHeight (data, i + length, out var lines)) + return false; + properties = waiting.Properties (lines); + return true; + } + + i += length; + } + + return false; + } + + // The next marker segment at i, past fill bytes and RSTn: its marker, and i at its length field. False at a + // byte that is not a marker, at SOI or EOI, or when the segment runs past the data. + static bool TryNextSegment (ReadOnlySpan data, ref int i, out byte marker, out int length) + { + marker = 0; + length = 0; + while (i + 1 < data.Length) { + if (data[i] != 0xFF) + return false; + while (i < data.Length && data[i] == 0xFF) + i++; + if (i >= data.Length) + return false; + marker = data[i++]; + if (marker is 0xD8 or 0xD9) + return false; + if (marker is >= 0xD0 and <= 0xD7) + continue; + if (i + 1 >= data.Length) + return false; + length = Endian.U16 (data, i, le: false); + return length >= 2 && i + length <= data.Length; + } + + return false; + } + + readonly record struct Frame (int Width, int Height, int Precision, int Components) + { + public ImageProperties Properties (int height) + { + var depth = Precision; + if (Components is >= 1 and <= 4 && Precision <= int.MaxValue / Components) + depth = Precision * Components; + return new ImageProperties (Width, height, depth, "JPEG"); + } + } + + // A start-of-frame segment from its length field: precision, height, width, then the component count. + static bool TryFrame (ReadOnlySpan segment, out Frame frame) + { + frame = default; + if (segment.Length < 7) + return false; + var height = Endian.U16 (segment, 3, le: false); + var width = Endian.U16 (segment, 5, le: false); + if (width <= 0 || height < 0) + return false; + var components = segment.Length >= 8 && segment[7] is >= 1 and <= 4 ? segment[7] : 1; + frame = new Frame (width, height, segment[2], components); + return true; + } + + // ITU-T T.81 §B.2.5: a DNL segment "shall immediately follow the first scan". The scan's entropy-coded data + // (§B.1.1.5) holds no marker: a 0xFF data byte is followed by a stuffed 0x00, and RSTn (0xD0-0xD7) may sit + // between intervals. Fill bytes 0xFF may precede a marker (§B.1.1.2). Any other marker before DNL means + // there is none. One pass over the bytes present. + static bool TryDnlHeight (ReadOnlySpan data, int scan, out int lines) + { + lines = 0; + var i = scan; + while (i < data.Length) { + if (data[i] != 0xFF) { + i++; + continue; + } + + while (i < data.Length && data[i] == 0xFF) + i++; + if (i >= data.Length) + return false; + var marker = data[i++]; + if (marker == 0x00 || marker is >= 0xD0 and <= 0xD7) + continue; + if (marker != 0xDC || i + 3 >= data.Length) + return false; + var length = Endian.U16 (data, i, le: false); + if (length != 4) + return false; + lines = Endian.U16 (data, i + 2, le: false); + return lines > 0; + } + + return false; + } + + static bool IsStartOfFrame (byte marker) => + marker is 0xC0 or 0xC1 or 0xC2 or 0xC3 + or 0xC5 or 0xC6 or 0xC7 + or 0xC9 or 0xCA or 0xCB + or 0xCD or 0xCE or 0xCF; +} diff --git a/src/TagLibSharp2/Image/Jpeg/MpfIndex.cs b/src/TagLibSharp2/Image/Jpeg/MpfIndex.cs new file mode 100644 index 00000000..30ec1871 --- /dev/null +++ b/src/TagLibSharp2/Image/Jpeg/MpfIndex.cs @@ -0,0 +1,149 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using TagLibSharp2.Image; +using TagLibSharp2.Image.Tiff; + +namespace TagLibSharp2.Image.Jpeg; + +/// One later image of a multi-picture file: its MP entry number, where it starts and its size. +readonly record struct MpImage (int Entry, int Start, int Size); + +/// +/// The first image's MP index (CIPA DC-007 §5.2.3.3): an MP Entry per image, each 16 bytes of attribute, size, +/// and offset from the MP header (0 for the first image). The MP index IFD and its entry list are a TIFF structure +/// inside the APP2 "MPF" segment, read with over that segment's bytes. +/// +sealed class MpfIndex +{ + const int MpEntryTag = 0xB002; + + public bool Unreadable { get; init; } + public List Images { get; init; } = []; + + /// + /// The later images, sorted. For Clear, every later image must be a whole JPEG inside the file, after the first + /// image's end (its EOI), without overlapping another; otherwise the index is unreadable. + /// + public static MpfIndex Read (ReadOnlySpan data) + { + if (FindHeader (data) is not var (header, limit, firstEnd)) + return new MpfIndex (); + var entries = new List<(long Offset, long Size)> (); + if (!TryReadEntries (data, header, limit, entries)) + return new MpfIndex { Unreadable = true }; + var images = new List (); + for (var n = 0; n < entries.Count; n++) { + var (offset, size) = entries[n]; + if (offset == 0) + continue; + var start = header + offset; + if (start < firstEnd || size < 4 || start + size > data.Length || data[(int)start] != 0xFF || data[(int)start + 1] != 0xD8) + return new MpfIndex { Unreadable = true }; + images.Add (new MpImage (n, (int)start, (int)size)); + } + + images.Sort ((a, b) => a.Start.CompareTo (b.Start)); + for (var n = 1; n < images.Count; n++) { + if (images[n].Start < images[n - 1].Start + images[n - 1].Size) + return new MpfIndex { Unreadable = true }; + } + + return new MpfIndex { Images = images }; + } + + // The MP header of the first APP2 "MPF" segment, the end of that segment's payload, and where the first image + // ends (a later image cannot start before it); null without an MPF segment before the scan. + static (int Header, int Limit, int Scan)? FindHeader (ReadOnlySpan data) + { + (int Header, int Limit)? found = null; + var i = 2; + while (i + 4 <= data.Length && data[i] == 0xFF) { + var marker = data[i + 1]; + if (marker is 0xDA or 0xD9) + return found is var (header, limit) ? (header, limit, FirstImageEnd (data, i)) : null; + if (marker is 0x01 or (>= 0xD0 and <= 0xD8) or 0xFF) { + i += marker == 0xFF ? 1 : 2; + continue; + } + + var length = Endian.U16 (data, i + 2, le: false); + if (length < 2 || i + 2 + length > data.Length) + break; + if (marker == 0xE2 && data.Slice (i + 4, length - 2).StartsWith ("MPF\0"u8)) + found ??= (i + 8, i + 2 + length); + i += 2 + length; + } + + return found is var (h, l) ? (h, l, data.Length) : null; + } + + // The end of the first image: after its EOI, the first FF D9 from its first scan on (entropy-coded data holds no + // FF D9: an FF there is followed by 00 or a restart marker); the data's end without one. + static int FirstImageEnd (ReadOnlySpan data, int scan) => + data.Slice (scan).IndexOf (Eoi) is var eoi and >= 0 ? scan + eoi + 2 : data.Length; + + static ReadOnlySpan Eoi => [0xFF, 0xD9]; + + static bool TryReadEntries (ReadOnlySpan data, int header, int limit, List<(long Offset, long Size)> entries) + { + if (!TryEntryList (data, header, limit, out var le, out var list, out var count)) + return false; + for (var n = 0; n < count; n++) { + var at = (int)list + (16 * n); + entries.Add ((Endian.U32 (data, at + 8, le), Endian.U32 (data, at + 4, le))); + } + + return true; + } + + /// Rewrites every MP entry's offset and size with update (entry number, offset, size). + public static bool TryRewriteEntries (byte[] output, int header, int limit, Func update) + { + if (!TryEntryList (output, header, limit, out var le, out var list, out var count)) + return false; + var span = output.AsSpan (); + for (var n = 0; n < count; n++) { + var at = (int)list + (16 * n); + var (offset, size) = update (n, Endian.U32 (span, at + 8, le), Endian.U32 (span, at + 4, le)); + if (offset < 0 || offset > uint.MaxValue || size < 0 || size > uint.MaxValue) + return false; + Endian.WriteU32 (span, at + 8, offset, le); + Endian.WriteU32 (span, at + 4, size, le); + } + + return true; + } + + // CIPA DC-007 §5.2: the MP index IFD and the MP entry list it points to are inside the APP2 segment. An index + // that points outside it is unreadable: following it would read or overwrite other bytes. The list is where the + // entries start in the file; count 0 when the index has no MP Entry tag. The header and the segment's end are + // where the segment was found in these bytes. + static bool TryEntryList (ReadOnlySpan data, int header, int limit, out bool le, out long list, out int count) + { + (le, list, count) = (default, 0, 0); + if (header + 8 > limit) + return false; + var segment = data.Slice (header, limit - header); + if (!TiffReader.TryByteOrder (segment, out le)) + return false; + var tiff = new TiffReader (segment, le); + var ifd = tiff.U32 (4); + if (!tiff.TryTable (ifd, out var tags)) + return false; + for (var n = 0; n < tags; n++) { + var entry = tiff.Entry (ifd, n); + if (tiff.Tag (entry) != MpEntryTag) + continue; + var bytes = tiff.Count (entry); + var at = tiff.Value (entry); + list = header + at; + if (bytes % 16 != 0 || at < TiffReader.HeaderSize || at + bytes > segment.Length) + return false; + count = (int)(bytes / 16); + return true; + } + + return true; + } +} diff --git a/src/TagLibSharp2/Image/MirrorFields.cs b/src/TagLibSharp2/Image/MirrorFields.cs new file mode 100644 index 00000000..33f799dd --- /dev/null +++ b/src/TagLibSharp2/Image/MirrorFields.cs @@ -0,0 +1,54 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +namespace TagLibSharp2.Image; + +/// +/// The fields an image tag stores whose copies other blocks of the same file hold, and where each copy is. macOS +/// ImageIO shows the XMP (dc:title, dc:creator, dc:description, dc:rights) and the Exif +/// IFD0 values (ImageDescription, Artist, Copyright) in preference to PNG text, so an edit that +/// left them would not show there. +/// +/// +/// XMP: Adobe XMP Specification Part 1 §7.9 (language alternatives, rdf:Alt with x-default) and §8.2.2.4 +/// (Dublin Core: title, description and rights are Lang Alt, creator is an ordered array). Exif: CIPA DC-008 (Exif +/// 2.32) §4.6.4 Table 4 (IFD0 tags 0x010E, 0x013B, 0x8298) and §4.6.5 (UserComment 0x9286 in the Exif IFD, reached +/// through tag 0x8769). The Windows XP tags 0x9C9B-0x9C9D are read by Windows and exiftool as title, comment and +/// author. Text: the keywords exiftool and ImageMagick write for the same fields. +/// +static class MirrorFields +{ + internal const string DcNamespace = "http://purl.org/dc/elements/1.1/"; + internal const string ExifNamespace = "http://ns.adobe.com/exif/1.0/"; + + internal static readonly MirrorField[] All = [ + new (ImageStores.Title, "Title", DcNamespace, "title", ordered: false, ifd0: [0x9C9B], exifIfd: [], text: []), + new (ImageStores.Artist, "Artist", DcNamespace, "creator", ordered: true, ifd0: [0x013B, 0x9C9D], exifIfd: [], text: ["exif:Artist", "Artist"]), + new (ImageStores.Description, "Description", DcNamespace, "description", ordered: false, ifd0: [0x010E], exifIfd: [], text: ["exif:ImageDescription"]), + new (ImageStores.Copyright, "Copyright", DcNamespace, "rights", ordered: false, ifd0: [0x8298], exifIfd: [], text: ["exif:Copyright"]), + new (ImageStores.Comment, "Comment", ExifNamespace, "UserComment", ordered: false, ifd0: [0x9C9C], exifIfd: [0x9286], text: ["exif:UserComment"]), + ]; + + internal static bool AnyChanged (ImageTag tag) + { + foreach (var field in All) { + if (tag.Changed (field.Store)) + return true; + } + + return false; + } + + + internal sealed class MirrorField (ImageStores store, string name, string xmpNamespace, string xmpName, bool ordered, int[] ifd0, int[] exifIfd, string[] text) + { + public ImageStores Store { get; } = store; + public string Name { get; } = name; + public string XmpNamespace { get; } = xmpNamespace; + public string XmpName { get; } = xmpName; + public bool Ordered { get; } = ordered; + public int[] Ifd0 { get; } = ifd0; + public int[] ExifIfd { get; } = exifIfd; + public string[] Text { get; } = text; + } +} diff --git a/src/TagLibSharp2/Image/Png/PngChunks.cs b/src/TagLibSharp2/Image/Png/PngChunks.cs new file mode 100644 index 00000000..879c6652 --- /dev/null +++ b/src/TagLibSharp2/Image/Png/PngChunks.cs @@ -0,0 +1,76 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using TagLibSharp2.Core; + +namespace TagLibSharp2.Image.Png; + +/// A chunk of a PNG file: where it starts and its whole length (length, type, data and CRC). +readonly struct PngChunk (int start, int length) +{ + public int Start { get; } = start; + public int Length { get; } = length; +} + +/// The chunk list of a PNG file (PNG 3rd ed. §5.3): walking it, checking a CRC, and writing a chunk. +static class PngChunks +{ + /// The chunks from the signature up to IEND or the first chunk that runs past the data. + public static bool TryWalk (ReadOnlySpan data, out List chunks) + { + chunks = []; + if (data.Length < 8 || data[0] != 0x89 || data[1] != (byte)'P' || data[2] != (byte)'N' || data[3] != (byte)'G' + || data[4] != 0x0D || data[5] != 0x0A || data[6] != 0x1A || data[7] != 0x0A) + return false; + var i = 8; + while (i + 12 <= data.Length) { + var length = ReadLength (data, i); + if (length < 0 || i + 12L + length > data.Length) + break; + var size = 12 + length; + chunks.Add (new PngChunk (i, size)); + if (data.Slice (i + 4, 4).SequenceEqual ("IEND"u8)) + break; + i += size; + } + + return true; + } + + public static bool IsTextChunk (ReadOnlySpan type) => + type.SequenceEqual ("tEXt"u8) || type.SequenceEqual ("zTXt"u8) || type.SequenceEqual ("iTXt"u8); + + public static bool TypeEquals (ReadOnlySpan data, PngChunk chunk, ReadOnlySpan type) => + data.Slice (chunk.Start + 4, 4).SequenceEqual (type); + + public static bool CrcMatches (ReadOnlySpan chunk) + { + var length = chunk.Length - 12; + return BinaryData.ComputeCrc32 (chunk.Slice (4, 4 + length)) == (uint)Endian.U32 (chunk, 8 + length, le: false); + } + + /// A chunk length field, or -1 above 2^31 - 1 (PNG 3rd ed. §5.3). + public static int ReadLength (ReadOnlySpan data, int offset) + { + var value = Endian.U32 (data, offset, le: false); + return value > int.MaxValue ? -1 : (int)value; + } + + public static void Add (BinaryDataBuilder builder, ReadOnlySpan type, byte[] payload) + { + builder.AddUInt32BE ((uint)payload.Length); + builder.Add (type); + builder.Add (payload); + var crcInput = new byte[4 + payload.Length]; + type.CopyTo (crcInput); + payload.CopyTo (crcInput, 4); + builder.AddUInt32BE (new BinaryData (crcInput).ComputeCrc32 ()); + } + + public static byte[] Chunk (ReadOnlySpan type, byte[] payload) + { + using var builder = new BinaryDataBuilder (payload.Length + 12); + Add (builder, type, payload); + return builder.ToArray (); + } +} diff --git a/src/TagLibSharp2/Image/Png/PngKeywords.cs b/src/TagLibSharp2/Image/Png/PngKeywords.cs new file mode 100644 index 00000000..1257960c --- /dev/null +++ b/src/TagLibSharp2/Image/Png/PngKeywords.cs @@ -0,0 +1,48 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +namespace TagLibSharp2.Image.Png; + +/// +/// The PNG text keywords of the tag's fields (PNG 3rd ed. §11.3.3.2 predefined keywords), and the keywords other +/// writers copy a field into: exiftool's "Artist", and ImageMagick's exif:* text. +/// +static class PngKeywords +{ + /// exiftool writes its Artist tag to a PNG as this keyword; "Author" wins when both are present. + internal const string ExiftoolArtist = "Artist"; + + public static ImageStores FieldFor (string keyword) => keyword switch { + "Title" => ImageStores.Title, + "Author" => ImageStores.Artist, + "Description" => ImageStores.Description, + "Copyright" => ImageStores.Copyright, + "Creation Time" => ImageStores.Year, + "Comment" => ImageStores.Comment, + _ => ImageStores.None + }; + + public static string Keyword (ImageStores field) => field switch { + ImageStores.Artist => "Author", + ImageStores.Description => "Description", + ImageStores.Copyright => "Copyright", + ImageStores.Year => "Creation Time", + ImageStores.Comment => "Comment", + _ => "Title" + }; + + /// A text keyword that copies a changed field (ImageMagick writes these as plain tEXt). + public static bool IsMirror (string keyword, ImageTag tag) + { + foreach (var field in MirrorFields.All) { + if (!tag.Changed (field.Store)) + continue; + foreach (var text in field.Text) { + if (string.Equals (text, keyword, StringComparison.Ordinal)) + return true; + } + } + + return false; + } +} diff --git a/src/TagLibSharp2/Image/Png/PngRewriter.cs b/src/TagLibSharp2/Image/Png/PngRewriter.cs new file mode 100644 index 00000000..fd63f263 --- /dev/null +++ b/src/TagLibSharp2/Image/Png/PngRewriter.cs @@ -0,0 +1,308 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Text; +using TagLibSharp2.Core; +using TagLibSharp2.Image.Exif; +using TagLibSharp2.Image.Xmp; + +namespace TagLibSharp2.Image.Png; + +/// +/// Reads a PNG's text fields and splices edited text into its chunk list: new text before the pixel data, changed +/// keywords dropped, and the XMP and Exif copies of a changed field updated. Every other chunk, and anything after +/// IEND, is copied as it is. +/// +static class PngRewriter +{ + internal const string SpliceError = "The PNG chunk list does not reach IEND, so the text cannot be spliced in."; + + const string XmpKeyword = "XML:com.adobe.xmp"; + const string RawXmpKeyword = "Raw profile type xmp"; + const string RawExifKeyword = "Raw profile type exif"; + const string RawApp1Keyword = "Raw profile type APP1"; + + // Clear keeps what a decoder or colour management needs to show the pixels and drops every other + // ancillary chunk (rule 7: mapped and unmapped, known and unknown). Kept: + // - every critical chunk (PNG 3rd ed. §5.4: an uppercase first letter; a decoder must understand it); + // - tRNS, gAMA, cHRM, sRGB, iCCP, cICP, mDCV, cLLI, sBIT (§11.3.1-§11.3.2: transparency, colour space, + // HDR mastering and content light level, significant bits); + // - bKGD, hIST, pHYs, sPLT (§11.3.5: background, palette histogram, pixel aspect, suggested palette); + // - acTL, fcTL, fdAT (§11.3.6: APNG animation; fdAT holds frame pixels); + // - oFFs, pCAL, sCAL, sTER (PNG Extensions 1.6.0: position, pixel calibration, scale, stereo layout). + // Dropped include tEXt, zTXt, iTXt (XMP and ImageMagick's raw EXIF/IPTC/XMP profiles), eXIf, zxIf, tIME, + // caBX (a C2PA manifest, which any edit invalidates: C2PA 2.1 §14.3.3), dSIG, and Apple's iDOT. + static readonly string[] KeptOnClear = [ + "tRNS", "gAMA", "cHRM", "sRGB", "iCCP", "cICP", "mDCV", "cLLI", "sBIT", + "bKGD", "hIST", "pHYs", "sPLT", "acTL", "fcTL", "fdAT", "oFFs", "pCAL", "sCAL", "sTER", + ]; + + static readonly ImageStores[] TextFields = [ + ImageStores.Title, ImageStores.Artist, ImageStores.Description, ImageStores.Copyright, ImageStores.Year, ImageStores.Comment, + ]; + + public static void Read (ReadOnlySpan data, ImageTag tag) + { + if (!PngChunks.TryWalk (data, out var chunks)) + return; + var budget = PngText.MaxInflatedText; + string? artist = null; + foreach (var chunk in chunks) + ReadChunk (data.Slice (chunk.Start, chunk.Length), tag, ref budget, ref artist); + + // exiftool writes its Artist tag to a PNG as the keyword "Artist". PNG 3rd ed. §11.3.3.2 predefines + // "Author" for the same field, which wins when both are present. + if (tag.Artist is null && artist is not null) + tag.ReadField (ImageStores.Artist, artist); + } + + static void ReadChunk (ReadOnlySpan chunk, ImageTag tag, ref int budget, ref string? artist) + { + if (chunk.Length < 12) + return; + var length = PngChunks.ReadLength (chunk, 0); + if (length < 0 || 12 + length != chunk.Length) + return; + var type = chunk.Slice (4, 4); + if (!PngChunks.IsTextChunk (type) || !PngChunks.CrcMatches (chunk)) + return; + var payload = chunk.Slice (8, length); + if (!PngText.TryKeyword (payload, out var keyword, out var rest)) + return; + var field = PngKeywords.FieldFor (keyword); + if (field == ImageStores.None && keyword != PngKeywords.ExiftoolArtist) + return; + if (!PngText.TryText (type, payload.Slice (rest), ref budget, out var text)) + return; + if (field == ImageStores.None) + artist = string.IsNullOrEmpty (text) ? artist : text; + else + tag.ReadField (field, text); + } + + /// Every text field (or only the changed ones) as new text chunks, in a fixed order. + public static void AddFields (BinaryDataBuilder builder, ImageTag tag, bool onlyChanged) + { + foreach (var field in TextFields) { + if ((onlyChanged && !tag.Changed (field)) || tag.Field (field) is not string value) + continue; + PngText.Add (builder, PngKeywords.Keyword (field), value); + } + } + + /// The edited file as new pieces and ranges of . + public static ImagePlan? Plan (ReadOnlySpan data, ImageTag tag, out string? error) + { + error = null; + var walked = PngChunks.TryWalk (data, out var chunks); + var ends = walked && chunks.Count > 0 && PngChunks.TypeEquals (data, chunks[^1], "IEND"u8); + if (!ends) { + error = SpliceError; + return null; + } + + return CopyChunks (data, chunks, tag, Layout.Of (data, chunks), out error); + } + + // Where new text goes: before the pixel data, and before Apple's iDOT, which records where the IDAT chunks are. + readonly record struct Layout (int Insert, int Idot, int Idat) + { + public static Layout Of (ReadOnlySpan data, List chunks) + { + var insert = chunks[^1].Start; + var idot = -1; + var idat = -1; + foreach (var chunk in chunks) { + if (PngChunks.TypeEquals (data, chunk, "IDAT"u8)) { + idat = chunk.Start; + insert = idot >= 0 ? idot : chunk.Start; + break; + } + + if (PngChunks.TypeEquals (data, chunk, "iDOT"u8)) + idot = chunk.Start; + } + + return new Layout (insert, idot, idat); + } + } + + static ImagePlan? CopyChunks ( + ReadOnlySpan data, + List chunks, + ImageTag tag, + Layout layout, + out string? error) + { + error = null; + var plan = new ImagePlan (); + var mirrors = !tag.DropUnmapped && MirrorFields.AnyChanged (tag); + // One inflation budget for every compressed copy in the file, as when it is read. + var budget = PngText.MaxInflatedText; + long outIdot = -1; + long outIdat = -1; + var copiedIdot = false; + plan.Copy (0, 8); + foreach (var chunk in chunks) { + if (chunk.Start == layout.Insert) + plan.Add (ChangedFields (tag)); + if (chunk.Start == layout.Idot) + outIdot = plan.Length; + if (chunk.Start == layout.Idat) + outIdat = plan.Length; + if (IsDropped (data, chunk, tag)) + continue; + byte[]? edited = null; + var whole = data.Slice (chunk.Start, chunk.Length); + if (mirrors && !TryMirrorChunk (whole, tag, ref budget, out edited, out error)) + return null; + if (edited is not null) { + plan.Add (edited); + continue; + } + + if (chunk.Start == layout.Idot) + copiedIdot = true; + plan.Copy (chunk.Start, chunk.Length); + } + + // PNG 3rd ed. §5.6: IEND is the last chunk. Whatever follows it (an appended archive, padding) is not + // the PNG's to change, so it is copied as it is. + var tail = chunks[^1].Start + chunks[^1].Length; + plan.Copy (tail, data.Length - tail); + DropStaleIdot (plan, data, layout, outIdot, outIdat, copiedIdot); + return plan; + } + + static byte[] ChangedFields (ImageTag tag) + { + using var builder = new BinaryDataBuilder (); + AddFields (builder, tag, onlyChanged: true); + return builder.ToArray (); + } + + // iDOT holds the offset of the IDAT data from itself. When a chunk between them changed, the offset is wrong, + // so iDOT is dropped (a decoder then reads the IDAT chunks in order, as it does for any PNG). + static void DropStaleIdot ( + ImagePlan plan, + ReadOnlySpan data, + Layout layout, + long outIdot, + long outIdat, + bool copiedIdot) + { + var kept = copiedIdot && outIdot >= 0 && outIdot + 8 <= plan.Length && IsIdot (data, layout.Idot); + if (!kept || layout.Idat < 0 || outIdat - outIdot == layout.Idat - layout.Idot) + return; + var length = PngChunks.ReadLength (data, layout.Idot); + if (length < 0) + return; + plan.Cut (outIdot, 12L + length); + } + + static bool IsIdot (ReadOnlySpan data, int start) => + data.Slice (start + 4, 4).SequenceEqual ("iDOT"u8); + + static bool IsKeptOnClear (ReadOnlySpan type) + { + if ((type[0] & 0x20) == 0) + return true; + foreach (var kept in KeptOnClear) { + if (type[0] == kept[0] && type[1] == kept[1] && type[2] == kept[2] && type[3] == kept[3]) + return true; + } + + return false; + } + + static bool IsDropped (ReadOnlySpan data, PngChunk chunk, ImageTag tag) + { + var type = data.Slice (chunk.Start + 4, 4); + if (tag.DropUnmapped) + return !IsKeptOnClear (type); + if (!PngChunks.IsTextChunk (type)) + return false; + var payload = data.Slice (chunk.Start + 8, chunk.Length - 12); + if (!PngText.TryKeyword (payload, out var keyword, out _)) + return false; + var field = PngKeywords.FieldFor (keyword); + if (field != ImageStores.None) + return tag.Changed (field); + return PngKeywords.IsMirror (keyword, tag); + } + + // A changed field is also changed in the XMP packet and the Exif profile that copy it, so that no reader shows + // the old value from there. A chunk with a bad CRC is not read by PNG decoders and is copied as it is. + static bool TryMirrorChunk (ReadOnlySpan whole, ImageTag tag, ref int budget, out byte[]? edited, out string? error) + { + edited = null; + error = null; + var type = whole.Slice (4, 4); + if (!PngChunks.CrcMatches (whole)) + return true; + var payload = whole.Slice (8, whole.Length - 12); + if (type.SequenceEqual ("eXIf"u8)) { + var carrier = new ExifCarrier ("eXIf", exif => PngChunks.Chunk ("eXIf"u8, exif)); + return carrier.TryEdit (payload, tag, out edited, out error); + } + if (!PngChunks.IsTextChunk (type) || !PngText.TryKeyword (payload, out var keyword, out var rest)) + return true; + if (keyword is not (XmpKeyword or RawXmpKeyword or RawExifKeyword or RawApp1Keyword)) + return true; + // Text no reader can decode (not zlib, or a broken international header) holds no copy: it is kept. Text that + // would pass the inflation budget may hold one, and cannot be checked. + if (!PngText.TryTextBody (type, payload.Slice (rest), ref budget, out var body, out var header, out var overBudget)) { + if (!overBudget) + return true; + error = $"The PNG {keyword} chunk does not fit in the {PngText.MaxInflatedText / (1024 * 1024)} MiB that all compressed text in the file shares, so its copy of a changed field cannot be updated."; + return false; + } + + var text = new TextChunk (type.ToArray (), keyword, header); + if (keyword != XmpKeyword) + return TryMirrorRawProfile (text, body, tag, out edited, out error); + if (!TryMirrorXmp (Encoding.UTF8.GetString (body), tag, out var packet, out error)) + return false; + edited = packet is null ? null : text.Build (Encoding.UTF8.GetBytes (packet)); + return true; + } + + // A text chunk's type, keyword and the header between the keyword and the text, to rebuild it around new text. + sealed class TextChunk (byte[] type, string keyword, byte[] header) + { + public string Keyword { get; } = keyword; + + public byte[] Build (byte[] text) => PngText.Rebuild (type, Keyword, header, text); + } + + // The updated packet, or null when it did not change. + static bool TryMirrorXmp (string packet, ImageTag tag, out string? updated, out string? error) + { + updated = null; + if (!XmpMirror.TryUpdate (packet, tag, "PNG XMP packet", out var result, out error)) + return false; + if (!ReferenceEquals (result, packet)) + updated = result; + return true; + } + + static bool TryMirrorRawProfile (TextChunk text, byte[] body, ImageTag tag, out byte[]? edited, out string? error) + { + edited = null; + error = null; + // A profile that is not hexadecimal is decoded by no reader (exiftool: "Unknown raw profile"): there is no copy + // in it to update, and it is kept as it is. + if (!RawProfile.TryDecode (Polyfills.Latin1.GetString (body), out var name, out var profile)) + return true; + + byte[] Encode (byte[] bytes) => text.Build (Polyfills.Latin1.GetBytes (RawProfile.Encode (name, bytes))); + if (text.Keyword != RawXmpKeyword) { + var carrier = new ExifCarrier (text.Keyword, Encode); + return carrier.TryEdit (profile, tag, out edited, out error); + } + if (!TryMirrorXmp (Encoding.UTF8.GetString (profile), tag, out var packet, out error)) + return false; + edited = packet is null ? null : Encode (Encoding.UTF8.GetBytes (packet)); + return true; + } +} diff --git a/src/TagLibSharp2/Image/Png/PngText.cs b/src/TagLibSharp2/Image/Png/PngText.cs new file mode 100644 index 00000000..e3c418f3 --- /dev/null +++ b/src/TagLibSharp2/Image/Png/PngText.cs @@ -0,0 +1,236 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.IO.Compression; +using System.Text; +using TagLibSharp2.Core; + +namespace TagLibSharp2.Image.Png; + +/// +/// The PNG text chunks (PNG 3rd ed. §11.3.3): tEXt (Latin-1), zTXt (zlib-compressed Latin-1) and iTXt (UTF-8, +/// optionally compressed, with a language tag and a translated keyword). Inflation shares one budget per file. +/// +static class PngText +{ + /// All the text a file's compressed chunks may inflate to, together. + internal const int MaxInflatedText = 1024 * 1024; + + /// The keyword (1-79 Latin-1 characters, then a null) and where the rest of the payload starts. + public static bool TryKeyword (ReadOnlySpan payload, out string keyword, out int rest) + { + keyword = ""; + rest = 0; + var end = 0; + while (end < payload.Length && payload[end] != 0) + end++; + if (end == 0 || end >= payload.Length || end > 79) + return false; + keyword = Polyfills.Latin1.GetString (payload.Slice (0, end)); + rest = end + 1; + return true; + } + + /// The text of a chunk after its keyword's null, decoded. + public static bool TryText (ReadOnlySpan type, ReadOnlySpan rest, ref int budget, out string? text) + { + text = null; + if (type.SequenceEqual ("tEXt"u8)) { + text = Polyfills.Latin1.GetString (rest); + return true; + } + + if (type.SequenceEqual ("zTXt"u8)) { + if (rest.Length < 1 || rest[0] != 0 || !TryInflate (rest.Slice (1), ref budget, out var raw)) + return false; + text = Polyfills.Latin1.GetString (raw); + return true; + } + + if (!TryInternationalHeader (rest, out var compressed, out var i)) + return false; + var body = rest.Slice (i); + if (compressed) { + if (!TryInflate (body, ref budget, out var raw)) + return false; + body = raw; + } + + text = Encoding.UTF8.GetString (body.ToArray ()); + return true; + } + + // The text after the keyword's null, inflated when compressed. header is what sits between the keyword's null + // and the text: the zTXt method byte, or the iTXt flag, method, language tag and translated keyword. overBudget + // is set when the text was not read because it would pass the inflation budget. + public static bool TryTextBody (ReadOnlySpan type, ReadOnlySpan rest, ref int budget, out byte[] body, out byte[] header, out bool overBudget) + { + body = []; + header = []; + overBudget = false; + if (type.SequenceEqual ("tEXt"u8)) { + body = rest.ToArray (); + return true; + } + + if (type.SequenceEqual ("zTXt"u8)) { + if (rest.Length < 1 || rest[0] != 0 || !TryInflate (rest.Slice (1), ref budget, out body, out overBudget)) + return false; + header = [0]; + return true; + } + + if (!TryInternationalHeader (rest, out var compressed, out var i)) + return false; + header = rest.Slice (0, i).ToArray (); + if (compressed) + return TryInflate (rest.Slice (i), ref budget, out body, out overBudget); + body = rest.Slice (i).ToArray (); + return true; + } + + // iTXt after the keyword: compression flag, method, language tag and null, translated keyword and null. + static bool TryInternationalHeader (ReadOnlySpan rest, out bool compressed, out int textAt) + { + compressed = false; + textAt = 2; + if (rest.Length < 2) + return false; + compressed = rest[0] == 1; + return SkipToNull (rest, ref textAt) && SkipToNull (rest, ref textAt); + } + + static bool SkipToNull (ReadOnlySpan data, ref int i) + { + while (i < data.Length && data[i] != 0) + i++; + if (i >= data.Length) + return false; + i++; + return true; + } + + /// Inflates a zlib stream (RFC 1950), taking its size from the shared budget. + public static bool TryInflate (ReadOnlySpan zlib, ref int budget, out byte[] raw) => TryInflate (zlib, ref budget, out raw, out _); + + // overBudget: set when the data was not inflated because it would pass the budget. + public static bool TryInflate (ReadOnlySpan zlib, ref int budget, out byte[] raw, out bool overBudget) + { + raw = []; + overBudget = budget <= 0; + if (overBudget || zlib.Length < 6 || (zlib[0] & 0x0F) != 8) + return false; + var header = (zlib[1] & 0x20) == 0 ? 2 : 6; + if (zlib.Length < header + 4) + return false; + try { + using var input = new MemoryStream (zlib.Slice (header, zlib.Length - header - 4).ToArray ()); + using var stream = new DeflateStream (input, CompressionMode.Decompress); + if (!TryReadAll (stream, budget, out raw)) { + overBudget = true; + return false; + } + + budget -= raw.Length; + return true; + } catch (InvalidDataException) { + return false; + } catch (IOException) { + return false; + } + } + + static bool TryReadAll (Stream stream, int budget, out byte[] raw) + { + raw = []; + using var output = new MemoryStream (); + var buffer = new byte[8192]; + var total = 0; + while (true) { + var read = stream.Read (buffer, 0, buffer.Length); + if (read == 0) + break; + if ((long)total + read > budget) + return false; + total += read; + output.Write (buffer, 0, read); + } + + raw = output.ToArray (); + return true; + } + + /// Compresses as a zlib stream (RFC 1950) for zTXt or a compressed iTXt. + internal static byte[] Zlib (byte[] raw) + { + using var output = new MemoryStream (); + output.WriteByte (0x78); + output.WriteByte (0x9C); + using (var deflate = new DeflateStream (output, CompressionLevel.Optimal, leaveOpen: true)) + deflate.Write (raw, 0, raw.Length); + uint a = 1, b = 0; + foreach (var value in raw) { + a = (a + value) % 65521; + b = (b + a) % 65521; + } + + var adler = (b << 16) | a; + output.WriteByte ((byte)(adler >> 24)); + output.WriteByte ((byte)(adler >> 16)); + output.WriteByte ((byte)(adler >> 8)); + output.WriteByte ((byte)adler); + return output.ToArray (); + } + + /// Rebuilds a text chunk of the same type around new text. Compression and the iTXt language tags are kept. + public static byte[] Rebuild (ReadOnlySpan type, string keyword, byte[] header, byte[] text) + { + var key = Polyfills.Latin1.GetBytes (keyword); + var compressed = type.SequenceEqual ("zTXt"u8) || (type.SequenceEqual ("iTXt"u8) && header.Length > 0 && header[0] == 1); + var body = compressed ? Zlib (text) : text; + var payload = new byte[key.Length + 1 + header.Length + body.Length]; + key.CopyTo (payload, 0); + header.CopyTo (payload, key.Length + 1); + body.CopyTo (payload, key.Length + 1 + header.Length); + return PngChunks.Chunk (type, payload); + } + + /// A new text chunk: tEXt when the value is Latin-1, otherwise an uncompressed iTXt. + public static void Add (BinaryDataBuilder builder, string keyword, string value) + { + if (IsLatin1 (value)) + PngChunks.Add (builder, "tEXt"u8, Latin1Text (keyword, value)); + else + PngChunks.Add (builder, "iTXt"u8, InternationalText (keyword, value)); + } + + static byte[] Latin1Text (string keyword, string value) + { + var key = Polyfills.Latin1.GetBytes (keyword); + var text = Polyfills.Latin1.GetBytes (value); + var payload = new byte[key.Length + 1 + text.Length]; + key.CopyTo (payload, 0); + text.CopyTo (payload, key.Length + 1); + return payload; + } + + static byte[] InternationalText (string keyword, string value) + { + var key = Encoding.ASCII.GetBytes (keyword); + var text = Encoding.UTF8.GetBytes (value); + var payload = new byte[key.Length + 5 + text.Length]; + key.CopyTo (payload, 0); + text.CopyTo (payload, key.Length + 5); + return payload; + } + + static bool IsLatin1 (string value) + { + foreach (var c in value) { + if (c > 0xFF) + return false; + } + + return true; + } +} diff --git a/src/TagLibSharp2/Image/Png/RawProfile.cs b/src/TagLibSharp2/Image/Png/RawProfile.cs new file mode 100644 index 00000000..020d01a6 --- /dev/null +++ b/src/TagLibSharp2/Image/Png/RawProfile.cs @@ -0,0 +1,86 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Globalization; +using System.Text; + +namespace TagLibSharp2.Image.Png; + +/// +/// An ImageMagick raw profile in a PNG text chunk ("Raw profile type exif" and the like): a line feed, the profile +/// name, a line feed, the byte count, a line feed, then the bytes as hexadecimal pairs split across lines. +/// +static class RawProfile +{ + internal static bool TryDecode (string text, out string name, out byte[] bytes) + { + name = ""; + bytes = []; + var i = 0; + while (i < text.Length && text[i] == '\n') + i++; + var nameEnd = text.IndexOf ('\n', i); + if (nameEnd < 0) + return false; + name = text.Substring (i, nameEnd - i); + i = nameEnd + 1; + while (i < text.Length && text[i] == ' ') + i++; + var countEnd = text.IndexOf ('\n', i); + if (countEnd < 0 || !TryCount (text, i, countEnd, out var count)) + return false; + bytes = new byte[count]; + return TryHexBytes (text, countEnd + 1, bytes); + } + + static bool TryCount (string text, int from, int end, out int count) + { +#if NETSTANDARD2_0 + if (!int.TryParse (text.Substring (from, end - from), NumberStyles.None, CultureInfo.InvariantCulture, out count)) +#else + if (!int.TryParse (text.AsSpan (from, end - from), NumberStyles.None, CultureInfo.InvariantCulture, out count)) +#endif + return false; + return count >= 0 && count <= (text.Length - end) / 2; + } + + static bool TryHexBytes (string text, int i, byte[] bytes) + { + for (var n = 0; n < bytes.Length; n++) { + while (i < text.Length && text[i] is '\n' or '\r' or ' ') + i++; + if (i + 1 >= text.Length || !TryHex (text[i], out var high) || !TryHex (text[i + 1], out var low)) + return false; + bytes[n] = (byte)((high << 4) | low); + i += 2; + } + + return true; + } + + internal static string Encode (string name, byte[] bytes) + { + const string Digits = "0123456789abcdef"; + var builder = new StringBuilder ((bytes.Length * 2) + (bytes.Length / 36) + name.Length + 16); + builder.Append ('\n').Append (name).Append ('\n'); + builder.Append (bytes.Length.ToString (CultureInfo.InvariantCulture).PadLeft (8)).Append ('\n'); + for (var n = 0; n < bytes.Length; n++) { + builder.Append (Digits[bytes[n] >> 4]).Append (Digits[bytes[n] & 0x0F]); + if (n % 36 == 35 || n == bytes.Length - 1) + builder.Append ('\n'); + } + + return builder.ToString (); + } + + static bool TryHex (char c, out int value) + { + value = c switch { + >= '0' and <= '9' => c - '0', + >= 'a' and <= 'f' => c - 'a' + 10, + >= 'A' and <= 'F' => c - 'A' + 10, + _ => -1 + }; + return value >= 0; + } +} diff --git a/src/TagLibSharp2/Image/StillImageFile.cs b/src/TagLibSharp2/Image/StillImageFile.cs new file mode 100644 index 00000000..e76abc41 --- /dev/null +++ b/src/TagLibSharp2/Image/StillImageFile.cs @@ -0,0 +1,402 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Diagnostics.CodeAnalysis; +using TagLibSharp2.Core; +using TagLibSharp2.Image.Tiff; + +namespace TagLibSharp2.Image; + +/// +/// A still image: JPEG, PNG, GIF, BMP, PCX, Netpbm, TIFF, DNG, or SVG. Open one with , +/// , , +/// or . +/// +/// +/// PNG text keywords, the GIF comment, and the JPEG COM marker can be edited +/// through . copies every other byte, +/// including the pixels. A path save copies those pixels in 64 KB pieces. +/// BMP, PCX, Netpbm, TIFF, DNG, and SVG have no text +/// block here yet, so is null and is +/// the file that was read. +/// +public sealed class StillImageFile : IMediaFile +{ + readonly byte[] _data; + readonly ImageTag? _tag; + IFileSystem? _fileSystem; + + internal StillImageFile (byte[] data, MediaFormat format, ImageProperties? properties, ImageTag? tag) + { + _data = data; + _tag = tag; + Format = format; + ImageProperties = properties is { IsValid: true } ? properties : null; + } + + /// Returns true when the data starts with the signature of a still-image format read here. + /// The start of the file. + /// Reads at most the first 64 KiB of markup for SVG and the IFD chain for TIFF; nothing is copied. + public static bool IsValidFormat (ReadOnlySpan data) => ImageHeader.TryDetect (data, out _); + + /// Reads a still image from its bytes. The bytes are copied once. + /// The whole file. + /// The parsed file, or a failure naming why it could not be read. + /// A TIFF without the DNG version tag reads as TIFF; also treats a .dng name as DNG. + public static StillImageFileReadResult Read (ReadOnlySpan data) => Open (data.ToArray (), null); + + /// Reads a still image from its bytes without an error string. + /// The whole file. + /// The parsed file when the read succeeds. + /// True when the data is a still image read here. + public static bool TryRead (ReadOnlySpan data, out StillImageFile? file) + { + var result = Read (data); + file = result.File; + return result.IsSuccess; + } + + /// Reads a still image from disk. The file is read into memory once. + /// The file path. + /// Optional file system abstraction. + /// The parsed file, or a failure. + public static StillImageFileReadResult ReadFromFile (string path, IFileSystem? fileSystem = null) + { + var fs = fileSystem ?? DefaultFileSystem.Instance; + if (OpenFailure (path, fs) is { } missing) + return missing; + + try { + byte[] bytes; + using (var stream = fs.OpenRead (path)) + bytes = StreamBytes.ReadToEnd (stream); + return Remember (Open (bytes, path), path, fileSystem); + } catch (IOException ex) { + return StillImageFileReadResult.Failure ($"Failed to read file: {ex.Message}"); + } catch (UnauthorizedAccessException ex) { + return StillImageFileReadResult.Failure ($"Access denied: {ex.Message}"); + } + } + + /// Reads a still image from disk asynchronously. The file is read into memory once. + /// The file path. + /// Optional file system abstraction. + /// Cancellation token. + /// The parsed file, or a failure. + public static async Task ReadFromFileAsync ( + string path, + IFileSystem? fileSystem = null, + CancellationToken cancellationToken = default) + { + var fs = fileSystem ?? DefaultFileSystem.Instance; + if (OpenFailure (path, fs) is { } missing) + return missing; + + try { + byte[] bytes; + using (var stream = fs.OpenRead (path)) + bytes = await StreamBytes.ReadToEndAsync (stream, cancellationToken).ConfigureAwait (false); + return Remember (Open (bytes, path), path, fileSystem); + } catch (IOException ex) { + return StillImageFileReadResult.Failure ($"Failed to read file: {ex.Message}"); + } catch (UnauthorizedAccessException ex) { + return StillImageFileReadResult.Failure ($"Access denied: {ex.Message}"); + } catch (OperationCanceledException) { + return StillImageFileReadResult.Failure ("Operation was cancelled"); + } + } + + static StillImageFileReadResult? OpenFailure (string path, IFileSystem fileSystem) + { +#if NETSTANDARD2_0 || NETSTANDARD2_1 + if (path is null) + throw new ArgumentNullException (nameof (path)); +#else + ArgumentNullException.ThrowIfNull (path); +#endif + return fileSystem.FileExists (path) ? null : StillImageFileReadResult.Failure ($"File not found: {path}"); + } + + static StillImageFileReadResult Remember (StillImageFileReadResult result, string path, IFileSystem? fileSystem) + { + result.File?.SetSource (path, fileSystem); + return result; + } + + static StillImageFileReadResult Open (byte[] data, string? path) + { + if (!ImageHeader.TryDetect (data, out var format)) + return StillImageFileReadResult.Failure ("Not a still image: no JPEG, PNG, GIF, BMP, PCX, Netpbm, TIFF, or SVG signature"); + if (format == MediaFormat.Tiff && HasDngName (path)) + format = MediaFormat.Dng; + return Open (data, format); + } + + internal static bool HasDngName (string? path) => + !string.IsNullOrEmpty (path) && Path.GetExtension (path).Equals (".dng", StringComparison.OrdinalIgnoreCase); + + /// Opens as . The array is kept, not copied. + internal static StillImageFileReadResult Open (byte[] data, MediaFormat format) + { + if (!ImageHeader.TryRead (data, format, out var properties)) { + var cut = format is MediaFormat.Tiff or MediaFormat.Dng ? TiffSize.Ifd0NextCutShort (data) : null; + return StillImageFileReadResult.Failure (cut ?? $"Not a {format} image"); + } + var tag = ImageRewrite.CreateTag (data, format); + return StillImageFileReadResult.Success (new StillImageFile (data, format, properties, tag)); + } + + /// + public Tag? Tag => _tag; + + /// + public IMediaProperties? AudioProperties => null; + + /// + public VideoProperties? VideoProperties => null; + + /// + public ImageProperties? ImageProperties { get; } + + /// + public MediaTypes MediaTypes => MediaTypes.Image; + + /// + public string? SourcePath { get; private set; } + + /// + public MediaFormat Format { get; } + + /// + /// The file bytes after any text edit. Pixel data is not rewritten. + /// A container that cannot be updated safely is returned unchanged. + /// fails instead of writing that unchanged file, with the reason. + /// + public ReadOnlyMemory Render () + { + if (!TryOutput (out var plan, out _)) + return _data; + return plan.MaterializeShared (_data); + } + + /// Writes the edited file to . + /// Fails, and does not write, when a text edit cannot be spliced into the container. + public FileWriteResult SaveToFile (string path, IFileSystem? fileSystem = null) + { +#if NETSTANDARD2_0 || NETSTANDARD2_1 + if (path is null) + throw new ArgumentNullException (nameof (path)); +#else + ArgumentNullException.ThrowIfNull (path); +#endif + var fs = fileSystem ?? _fileSystem ?? DefaultFileSystem.Instance; + if (SpliceFormat && !string.IsNullOrEmpty (SourcePath)) + return WriteSpliceSource (path, fs, default); + if (!TryOutput (out var plan, out var error)) + return FileWriteResult.Failure (error); + return WritePlan (path, fs, plan); + } + + /// Writes back to . + public FileWriteResult SaveToFile (IFileSystem? fileSystem = null) + { + if (string.IsNullOrEmpty (SourcePath)) + return FileWriteResult.Failure ("No source path available. Use SaveToFile(path) instead."); + return SaveToFile (SourcePath!, fileSystem); + } + + /// Writes to . + public Task SaveToFileAsync ( + string path, + IFileSystem? fileSystem = null, + CancellationToken cancellationToken = default) + { +#if NETSTANDARD2_0 || NETSTANDARD2_1 + if (path is null) + throw new ArgumentNullException (nameof (path)); +#else + ArgumentNullException.ThrowIfNull (path); +#endif + var fs = fileSystem ?? _fileSystem ?? DefaultFileSystem.Instance; + if (SpliceFormat && !string.IsNullOrEmpty (SourcePath)) + return Task.FromResult (WriteSpliceSource (path, fs, cancellationToken)); + if (!TryOutput (out var plan, out var error)) + return Task.FromResult (FileWriteResult.Failure (error)); + return Task.FromResult (WritePlan (path, fs, plan, cancellationToken)); + } + + bool SpliceFormat => Format is MediaFormat.Jpeg or MediaFormat.Png or MediaFormat.Gif; + + // The source is opened before the plan. A splice failure disposes it and beats a cancelled token. + FileWriteResult WriteSpliceSource (string path, IFileSystem fileSystem, CancellationToken cancellationToken) + { + OpenedFile? source = null; + try { + if (!PathSave.TryOpen (SourcePath!, fileSystem, out source, out var openError)) + return openError; + if (!TryOutput (out var plan, out var error)) + return FileWriteResult.Failure (error); + + var opened = source!; + source = null; + return CopyOpened (path, opened, plan, cancellationToken); + } finally { + source?.Dispose (); + } + } + + // Every format this file opens has a plan: a text rewriter, or the original bytes as one range. + bool TryOutput ([NotNullWhen (true)] out ImagePlan? plan, [NotNullWhen (false)] out string? error) => + ImageRewrite.TryPlan (_data, Format, _tag, out plan, out error); + + FileWriteResult WritePlan ( + string path, + IFileSystem fileSystem, + ImagePlan plan, + CancellationToken cancellationToken = default) + { + if (string.IsNullOrEmpty (SourcePath)) + return WriteHeld (path, fileSystem, plan, cancellationToken); + return WriteSource (path, fileSystem, plan, cancellationToken); + } + + // Ranges stay in _data. The source file is not opened. + FileWriteResult WriteHeld ( + string path, + IFileSystem fileSystem, + ImagePlan plan, + CancellationToken cancellationToken = default) + { + if (cancellationToken.IsCancellationRequested) + return FileWriteResult.Failure ("Operation was cancelled"); + + var chunk = StreamCopy.Rent (); + try { + return AtomicFileWriter.WriteStream ( + path, + fileSystem, + output => plan.Write (null, _data, output, chunk, cancellationToken)); + } finally { + StreamCopy.Return (chunk); + } + } + + // Ranges are read back from the file that was opened, in the same order as Render. + FileWriteResult WriteSource ( + string path, + IFileSystem? fileSystem, + ImagePlan plan, + CancellationToken cancellationToken = default) + { + OpenedFile? source = null; + try { + if (!PathSave.TryOpen (SourcePath!, fileSystem, out source, out var error)) + return error; + + var opened = source!; + source = null; + return CopyOpened (path, opened, plan, cancellationToken); + } finally { + source?.Dispose (); + } + } + + // Caller has transferred ownership of source. This disposes it on every path. + static FileWriteResult CopyOpened ( + string path, + OpenedFile source, + ImagePlan plan, + CancellationToken cancellationToken) + { + byte[]? chunk = null; + try { + if (source.Length < plan.SourceEnd) + return FileWriteResult.Failure ("The source ended before the requested bytes were copied"); + if (cancellationToken.IsCancellationRequested) + return FileWriteResult.Failure ("Failed to re-read source file: Operation was cancelled"); + + chunk = StreamCopy.Rent (); + var copyBuffer = chunk; + return PathSave.Replace (path, source, output => { + plan.Write (source.Stream, default, output, copyBuffer, cancellationToken); + }); + } finally { + source.Dispose (); + if (chunk is not null) + StreamCopy.Return (chunk); + } + } + + /// Writes back to . + public Task SaveToFileAsync ( + IFileSystem? fileSystem = null, + CancellationToken cancellationToken = default) + { + if (string.IsNullOrEmpty (SourcePath)) + return Task.FromResult (FileWriteResult.Failure ("No source path available. Use SaveToFile(path) instead.")); + return SaveToFileAsync (SourcePath!, fileSystem, cancellationToken); + } + + /// + public void Dispose () + { + } + + internal void SetSource (string path, IFileSystem? fileSystem) + { + SourcePath = path; + _fileSystem = fileSystem; + } +} + +/// +/// The result of reading a still image. +/// +public readonly struct StillImageFileReadResult : IEquatable +{ + StillImageFileReadResult (StillImageFile? file, string? error) + { + File = file; + Error = error; + } + + /// Gets the parsed file, or null when the read failed. + public StillImageFile? File { get; } + + /// Gets the error message when the read failed. + public string? Error { get; } + + /// Gets whether the read succeeded. + public bool IsSuccess => File is not null && Error is null; + + /// Creates a successful result. + /// The parsed file. + /// The result. + public static StillImageFileReadResult Success (StillImageFile file) => new (file, null); + + /// Creates a failed result. + /// The error message. + /// The result. + public static StillImageFileReadResult Failure (string error) => new (null, error); + + /// + public bool Equals (StillImageFileReadResult other) => ReferenceEquals (File, other.File) && Error == other.Error; + + /// + public override bool Equals (object? obj) => obj is StillImageFileReadResult other && Equals (other); + + /// + public override int GetHashCode () => HashCode.Combine (File, Error); + + /// Determines whether two results are equal. + /// The first result. + /// The second result. + /// True when both results hold the same file and error. + public static bool operator == (StillImageFileReadResult left, StillImageFileReadResult right) => left.Equals (right); + + /// Determines whether two results differ. + /// The first result. + /// The second result. + /// True when the results differ. + public static bool operator != (StillImageFileReadResult left, StillImageFileReadResult right) => !left.Equals (right); +} diff --git a/src/TagLibSharp2/Image/Svg/SvgSize.cs b/src/TagLibSharp2/Image/Svg/SvgSize.cs new file mode 100644 index 00000000..6ba55283 --- /dev/null +++ b/src/TagLibSharp2/Image/Svg/SvgSize.cs @@ -0,0 +1,353 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Globalization; +using System.Text; +using TagLibSharp2.Core; + +namespace TagLibSharp2.Image.Svg; + +/// +/// The width and height of an SVG: the root element's width and height attributes in absolute units, or its +/// viewBox (SVG 1.1 §7.2, §7.7). Only the root start tag is decoded, never the document. +/// +static class SvgSize +{ + // Reads only until the first code unit that cannot start a prolog, so an audio buffer stops at byte 0. + public static bool IsSvg (ReadOnlySpan data) => TrySvgRoot (new Markup (data), out _); + + public static bool TryRead (ReadOnlySpan data, out ImageProperties? properties) + { + properties = null; + var markup = new Markup (data); + if (!TrySvgRoot (markup, out var start)) + return false; + + // Only the root start tag is decoded, never the document. + var end = TagEnd (markup, start); + var tag = markup.Decode (start, end); + if (TrySvgLength (tag, "width", out var width) && TrySvgLength (tag, "height", out var height)) + properties = new ImageProperties (width, height, 0, "SVG"); + else if (TryViewBox (tag, out width, out height)) + properties = new ImageProperties (width, height, 0, "SVG"); + + return true; + } + + // XML 1.0 §2.8 prolog: an XML declaration, then comments, processing instructions, white space and one + // doctype, then the root element. The scan reads code units in place (UTF-8, or UTF-16 after a BOM) and + // compares ASCII only, so nothing is decoded or copied. + static bool TrySvgRoot (Markup text, out int start) + { + start = 0; + var i = 0; + if (text.StartsAt (i, "")) + return false; + while (i < text.Length) { + while (i < text.Length && IsXmlSpace (text[i])) + i++; + if (i >= text.Length) + return false; + if (text.StartsAt (i, "")) + return false; + continue; + } + + if (text.StartsAt (i, "")) + return false; + continue; + } + + if (IsSvgRootAt (text, i)) { + start = i; + return true; + } + + return false; + } + + return false; + } + + static bool IsSvgRootAt (Markup text, int i) + { + if (!text.StartsAt (i, "= text.Length || IsXmlSpace (text[n]) || text[n] is '>' or '/'; + } + + // The code unit after the '>' that closes the start tag at start, skipping quoted attribute values, or the + // end of the scanned window. + static int TagEnd (Markup text, int start) + { + var quote = 0; + for (var i = start; i < text.Length; i++) { + var c = text[i]; + if (quote != 0) { + if (c == quote) + quote = 0; + } else if (c is '"' or '\'') { + quote = c; + } else if (c == '>') { + return i; + } + } + + return text.Length; + } + + static bool SkipDoctype (Markup text, ref int index) + { + var quote = 0; + var depth = 0; + while (index < text.Length) { + var value = text[index++]; + if (quote != 0) { + if (value == quote) + quote = 0; + continue; + } + + if (value is '\'' or '"') { + quote = value; + continue; + } + + if (value == '[') + depth++; + else if (value == ']' && depth > 0) + depth--; + else if (value == '>' && depth == 0) + return true; + } + + return false; + } + + // XML 1.0 §2.3 S: space, tab, carriage return, line feed. + static bool IsXmlSpace (int value) => value is ' ' or '\t' or '\r' or '\n'; + + const int SvgScanBytes = 64 * 1024; + + /// + /// The first of a markup file as code units: bytes for UTF-8 (after an optional + /// BOM), or 16-bit units after a UTF-16 BOM. A unit above 0x7F never equals an ASCII token. + /// + readonly ref struct Markup + { + readonly ReadOnlySpan _data; + readonly int _unit; + readonly bool _bigEndian; + + public Markup (ReadOnlySpan data) + { + var window = data.Slice (0, Math.Min (data.Length, SvgScanBytes)); + if (window.Length >= 2 && window[0] == 0xFF && window[1] == 0xFE) { + _unit = 2; + _bigEndian = false; + window = window.Slice (2); + } else if (window.Length >= 2 && window[0] == 0xFE && window[1] == 0xFF) { + _unit = 2; + _bigEndian = true; + window = window.Slice (2); + } else { + _unit = 1; + _bigEndian = false; + if (window.Length >= 3 && window[0] == 0xEF && window[1] == 0xBB && window[2] == 0xBF) + window = window.Slice (3); + } + + _data = window; + Length = window.Length / _unit; + } + + public int Length { get; } + + public int this[int index] => + _unit == 1 ? _data[index] : Endian.U16 (_data, 2 * index, le: !_bigEndian); + + /// ASCII case-insensitive match of at . + public bool StartsAt (int index, string token) + { + if (index < 0 || index > Length - token.Length) + return false; + for (var n = 0; n < token.Length; n++) { + var c = this[index + n]; + if (c is >= 'A' and <= 'Z') + c += 'a' - 'A'; + var t = token[n]; + if (t is >= 'A' and <= 'Z') + t = (char)(t + ('a' - 'A')); + if (c != t) + return false; + } + + return true; + } + + public bool SkipTo (ref int index, string marker) + { + for (var i = index; i <= Length - marker.Length; i++) { + var match = true; + for (var n = 0; n < marker.Length && match; n++) + match = this[i + n] == marker[n]; + if (match) { + index = i + marker.Length; + return true; + } + } + + return false; + } + + public string Decode (int start, int end) + { + var bytes = _data.Slice (start * _unit, (end - start) * _unit); + if (_unit == 1) + return Encoding.UTF8.GetString (bytes); + return (_bigEndian ? Encoding.BigEndianUnicode : Encoding.Unicode).GetString (bytes); + } + } + + static bool TrySvgLength (string tag, string name, out int value) + { + value = 0; + var key = FindAttribute (tag, name); + if (key < 0) + return false; + var i = key + name.Length; + while (i < tag.Length && (tag[i] == ' ' || tag[i] == '\t' || tag[i] == '=')) + i++; + if (i >= tag.Length) + return false; + char quote = tag[i] is '\'' or '"' ? tag[i++] : '\0'; + var start = i; + if (!TrySkipNumber (tag, ref i)) + return false; + var unitStart = i; + while (i < tag.Length && char.IsLetter (tag[i])) + i++; + if (i < tag.Length && tag[i] == '%') + return false; + if (!TryParseNumber (tag, start, unitStart - start, out var number) || !TrySvgPixels (number, tag.Substring (unitStart, i - unitStart), out value)) + return false; + return quote == '\0' || (i < tag.Length && tag[i] == quote); + } + + // Digits with at most one dot, then an optional exponent with digits: false when no digit was read. + static bool TrySkipNumber (string tag, ref int i) + { + var start = i; + var sawDigit = false; + var sawDot = false; + while (i < tag.Length && (char.IsDigit (tag[i]) || (tag[i] == '.' && !sawDot))) { + sawDigit |= tag[i] != '.'; + sawDot |= tag[i] == '.'; + i++; + } + + if (i < tag.Length && tag[i] is 'e' or 'E') { + var exponent = i + 1; + if (exponent < tag.Length && tag[exponent] is '+' or '-') + exponent++; + var digits = exponent; + while (digits < tag.Length && char.IsDigit (tag[digits])) + digits++; + if (digits > exponent) { + sawDigit = true; + i = digits; + } + } + + return sawDigit && i != start; + } + + static bool TryParseNumber (string tag, int start, int length, out double number) => +#if NETSTANDARD2_0 + double.TryParse (tag.Substring (start, length), NumberStyles.Float, CultureInfo.InvariantCulture, out number); +#else + double.TryParse (tag.AsSpan (start, length), NumberStyles.Float, CultureInfo.InvariantCulture, out number); +#endif + + static bool TrySvgPixels (double number, string unit, out int value) + { + value = 0; + var pixels = unit.ToUpperInvariant () switch { + "" or "PX" => number, + "IN" => number * 96d, + "CM" => number * 96d / 2.54d, + "MM" => number * 96d / 25.4d, + "PT" => number * 96d / 72d, + "PC" => number * 16d, + _ => double.NaN + }; + if (double.IsNaN (pixels) || pixels <= 0 || pixels > int.MaxValue) + return false; + value = (int)Math.Round (pixels); + return value > 0; + } + + static int FindAttribute (string tag, string name) + { + var from = 0; + while (from < tag.Length) { + var key = tag.IndexOf (name, from, StringComparison.OrdinalIgnoreCase); + if (key < 0) + return -1; + var before = key == 0 ? ' ' : tag[key - 1]; + if (before is ' ' or '\t' or '\r' or '\n') + return key; + from = key + name.Length; + } + + return -1; + } + + static bool TryViewBox (string tag, out int width, out int height) + { + width = 0; + height = 0; + var key = FindAttribute (tag, "viewBox"); + if (key < 0) + return false; + var i = key + "viewBox".Length; + while (i < tag.Length && tag[i] != '"' && tag[i] != '\'') + i++; + if (i >= tag.Length) + return false; + var quote = tag[i++]; + var end = tag.IndexOf (quote, i); + if (end < 0) + return false; + var parts = tag.Substring (i, end - i).Replace (',', ' ').Split ((char[]?)null, StringSplitOptions.RemoveEmptyEntries); + return parts.Length >= 4 && TryWhole (parts[2], out width) && TryWhole (parts[3], out height); + } + + static bool TryWhole (string text, out int value) + { + var length = 0; + while (length < text.Length && text[length] != '.') + length++; +#if NETSTANDARD2_0 + var whole = length == text.Length ? text : text.Substring (0, length); + return int.TryParse (whole, NumberStyles.Integer, CultureInfo.InvariantCulture, out value) && value > 0; +#else + return int.TryParse (text.AsSpan (0, length), NumberStyles.Integer, CultureInfo.InvariantCulture, out value) && value > 0; +#endif + } +} diff --git a/src/TagLibSharp2/Image/Tiff/CountedList.cs b/src/TagLibSharp2/Image/Tiff/CountedList.cs new file mode 100644 index 00000000..8e8089a5 --- /dev/null +++ b/src/TagLibSharp2/Image/Tiff/CountedList.cs @@ -0,0 +1,47 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +namespace TagLibSharp2.Image.Tiff; + +/// +/// The only collection the IFD walks and the Exif removal keep per entry. Every add, read, write and sort adds +/// to , and it has no enumerator and no search, so any per-entry scan of it shows in the +/// operation count. +/// +sealed class CountedList +{ + T[] _items = new T[8]; + + public static CountedList Filled (int count) => new () { _items = new T[Math.Max (count, 1)], Count = count }; + + public int Count { get; private set; } + + public T this[int index] { + get { + IfdSteps.Count++; + if ((uint)index >= (uint)Count) + throw new ArgumentOutOfRangeException (nameof (index)); + return _items[index]; + } + set { + IfdSteps.Count++; + if ((uint)index >= (uint)Count) + throw new ArgumentOutOfRangeException (nameof (index)); + _items[index] = value; + } + } + + public void Add (T item) + { + IfdSteps.Count++; + if (Count == _items.Length) + Array.Resize (ref _items, _items.Length * 2); + _items[Count++] = item; + } + + public void Sort (Comparison comparison) + { + IfdSteps.Count += Count; + Array.Sort (_items, 0, Count, Comparer.Create (comparison)); + } +} diff --git a/src/TagLibSharp2/Image/Tiff/IfdGraph.cs b/src/TagLibSharp2/Image/Tiff/IfdGraph.cs new file mode 100644 index 00000000..8883d39e --- /dev/null +++ b/src/TagLibSharp2/Image/Tiff/IfdGraph.cs @@ -0,0 +1,139 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +namespace TagLibSharp2.Image.Tiff; + +/// +/// The IFD tables exiftool reads, as measured: IFD0 and the chain after it through next-IFD offsets (IFD1, IFD2, +/// ...); from each of those, and from every Exif, SubIFD and interoperability table they lead to, the Exif IFDs +/// (0x8769), SubIFDs (0x014A) and interoperability IFDs (0xA005) they point at, all read with the Exif::Main tags, +/// so all of them may hold a copy (, ). Pointers are decoded as exiftool +/// decodes them (), and IFD0's Exif and GPS pointers also as TagLib# reads them +/// (). GPS tables (0x8825) are read with the GPS tags and follow no pointer +/// (): kept and protected. The next IFD of an Exif, SubIFD, interoperability or GPS table, +/// which no reader follows, is protected from zeroing only (). +/// +/// +/// Each table is walked once by offset; a pointer whose table's entries do not fit in the data is listed as +/// unread. The entries walked are bounded by the data (tables that do not overlap hold at most one per 12 bytes), +/// and so are the pointer offsets read (one per 4 bytes, each array once): past either bound the tables overlap, +/// and the walk stops with set. Every table, entry and offset visit is counted in +/// . +/// +sealed class IfdGraph +{ + public const int MainRole = 1; + public const int ExifRole = 2; + public const int GpsRole = 4; + public const int ProtectRole = 8; + + /// The roles whose tables are read with the Exif tags, and whose pointers are followed. + public const int ReadRoles = MainRole | ExifRole; + + /// The roles of tables some reader reads: with the Exif tags, or GPS tables with the GPS tags. + public const int SeenRoles = ReadRoles | GpsRole; + + public CountedList<(long At, int Count, int Roles)> Tables { get; } = new (); + + /// Offsets a pointer names, inside the data and past the header, where no table can be read. + public CountedList Unread { get; } = new (); + + public bool OverBudget { get; set; } + + public static IfdGraph Walk (TiffReader tiff, long ifd0) + { + var walk = new WalkState (tiff.EntryBound, ifd0); + walk.Queue.Enqueue ((ifd0, MainRole)); + while (walk.Queue.Count > 0 && !walk.Graph.OverBudget) { + IfdSteps.Count++; + var (at, role) = walk.Queue.Dequeue (); + Visit (tiff, walk, at, role); + } + + return walk.Graph; + } + + sealed class WalkState (long entryBound, long ifd0) + { + public IfdGraph Graph { get; } = new (); + public Queue<(long At, int Role)> Queue { get; } = new (); + public Dictionary Index { get; } = new (); + public HashSet UnreadSeen { get; } = new (); + public HashSet ArraysSeen { get; } = new (); + public long EntryBound { get; } = entryBound; + public long Ifd0 { get; } = ifd0; + public long Offsets { get; set; } + long _entries; + + // The table's index in the graph, added the first time; past the entry bound the walk is over budget, and + // its loop stops after this table. + public int IndexOf (long at, int count) + { + if (Index.TryGetValue (at, out var index)) + return index; + index = Graph.Tables.Count; + Index[at] = index; + Graph.Tables.Add ((at, count, 0)); + _entries += count; + Graph.OverBudget |= _entries > EntryBound; + return index; + } + } + + static void Visit (TiffReader tiff, WalkState walk, long at, int role) + { + if (!tiff.TryTable (at, out var count)) { + if (at >= TiffReader.HeaderSize && at < tiff.Length && walk.UnreadSeen.Add (at)) + walk.Graph.Unread.Add (at); + return; + } + + var index = walk.IndexOf (at, count); + var had = walk.Graph.Tables[index].Roles; + if ((had & role) != 0) + return; + walk.Graph.Tables[index] = (at, count, had | role); + if ((role & ReadRoles) != 0 && (had & ReadRoles) == 0) + FollowPointers (tiff, walk, at, count); + + // exiftool follows IFD0's chain of next IFDs. No reader reads the next IFD of an Exif, SubIFD, + // interoperability or GPS table (measured): it is protected from zeroing only. + if ((role & MainRole) != 0) + walk.Queue.Enqueue ((tiff.Next (at, count), MainRole)); + else if ((role & (ExifRole | GpsRole)) != 0 && (had & SeenRoles) == 0) + walk.Queue.Enqueue ((tiff.Next (at, count), ProtectRole)); + } + + // Past the bound on pointer offsets each further pointer only adds to the count; the walk then stops. + static void FollowPointers (TiffReader tiff, WalkState walk, long at, int count) + { + for (var n = 0; n < count; n++) { + IfdSteps.Count++; + var entry = tiff.Entry (at, n); + var role = tiff.Tag (entry) switch { + TiffReader.ExifIfdPointer or TiffReader.InteropIfdPointer or TiffReader.SubIfdsPointer => ExifRole, + TiffReader.GpsIfdPointer => GpsRole, + _ => 0 + }; + if (role != 0 && tiff.TryPointers (entry, out var values)) + Follow (tiff, walk, values, role); + // TagLib# reads IFD0's Exif and GPS pointers as the 4-byte field, whatever their type and count (measured). + if (at == walk.Ifd0 && tiff.Tag (entry) is TiffReader.ExifIfdPointer or TiffReader.GpsIfdPointer) + Follow (tiff, walk, TiffReader.RawPointer (entry), role); + } + } + + // Each pointer value once per array as one type reads it; the values read are bounded by one per 4 bytes of data, + // and none is read past it. + static void Follow (TiffReader tiff, WalkState walk, PointerValues values, int role) + { + if (!walk.ArraysSeen.Add (values)) + return; + walk.Offsets += values.Count; + walk.Graph.OverBudget |= walk.Offsets > tiff.Length / 4; + for (var k = 0L; k < values.Count && !walk.Graph.OverBudget; k++) { + IfdSteps.Count++; + walk.Queue.Enqueue ((tiff.PointerAt (values, k), role)); + } + } +} diff --git a/src/TagLibSharp2/Image/Tiff/IfdSteps.cs b/src/TagLibSharp2/Image/Tiff/IfdSteps.cs new file mode 100644 index 00000000..2c5d7d95 --- /dev/null +++ b/src/TagLibSharp2/Image/Tiff/IfdSteps.cs @@ -0,0 +1,14 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +namespace TagLibSharp2.Image.Tiff; + +/// +/// Steps of the IFD walks of an edit and of Clear on this thread (the graph walk, the Exif removal, the Apple +/// maker-note walk), for tests that bound them by an operation count. +/// +static class IfdSteps +{ + [ThreadStatic] + internal static long Count; +} diff --git a/src/TagLibSharp2/Image/Tiff/TiffReader.cs b/src/TagLibSharp2/Image/Tiff/TiffReader.cs new file mode 100644 index 00000000..9370afe0 --- /dev/null +++ b/src/TagLibSharp2/Image/Tiff/TiffReader.cs @@ -0,0 +1,259 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +namespace TagLibSharp2.Image.Tiff; + +/// +/// A TIFF structure over its bytes, every offset counted from the byte-order mark (TIFF 6.0 §2). Classic TIFF has +/// 2-byte entry counts, 12-byte entries and 4-byte offsets; BigTIFF (version 43) has 8-byte counts and offsets and +/// 20-byte entries. This is the one definition of the header, of when a table is read, of entry fields, of the +/// next-IFD offset and of an entry's value bytes; the walks that use it differ only in which pointers they follow. +/// +readonly ref struct TiffReader +{ + public const int ExifIfdPointer = 0x8769; + public const int GpsIfdPointer = 0x8825; + public const int InteropIfdPointer = 0xA005; + public const int SubIfdsPointer = 0x014A; + + /// No IFD can start inside the 8-byte classic header. + public const int HeaderSize = 8; + + public TiffReader (ReadOnlySpan data, bool littleEndian, bool big = false) + { + Data = data; + LittleEndian = littleEndian; + Big = big; + } + + public ReadOnlySpan Data { get; } + public bool LittleEndian { get; } + public bool Big { get; } + public int Length => Data.Length; + public int CountSize => Big ? 8 : 2; + public int EntrySize => Big ? 20 : 12; + + public int U16 (long at) => Endian.U16 (Data, (int)at, LittleEndian); + public long U32 (long at) => Endian.U32 (Data, (int)at, LittleEndian); + + /// "II" (little-endian) or "MM" (big-endian), with nothing else checked. + public static bool TryByteOrder (ReadOnlySpan data, out bool littleEndian) + { + littleEndian = data[0] == (byte)'I' && data[1] == (byte)'I'; + return littleEndian || (data[0] == (byte)'M' && data[1] == (byte)'M'); + } + + /// A classic TIFF header: "II" then 42, or "MM" then 42, then IFD0's offset. + public static bool TryClassic (ReadOnlySpan data, out TiffReader reader, out long ifd0) + { + reader = default; + ifd0 = 0; + if (!IsClassic (data)) + return false; + reader = new TiffReader (data, data[0] == (byte)'I'); + ifd0 = reader.U32 (4); + return true; + } + + /// A classic or BigTIFF header and the first IFD's offset (BigTIFF: offset size 8, reserved 0). + public static bool TryOpen (ReadOnlySpan data, out TiffReader reader, out long first) + { + if (IsClassic (data)) + return TryClassic (data, out reader, out first); + reader = new TiffReader (data, data.Length > 0 && data[0] == (byte)'I', big: true); + first = 0; + return IsBig (data) && reader.U16 (4) == 8 && reader.U16 (6) == 0 && Endian.TryU64 (data, 8, reader.LittleEndian, out first); + } + + public static bool IsTiff (ReadOnlySpan data) => IsClassic (data) || IsBig (data); + + static bool IsClassic (ReadOnlySpan data) => + data.Length >= HeaderSize && ( + (data[0] == (byte)'I' && data[1] == (byte)'I' && data[2] == 42 && data[3] == 0) || + (data[0] == (byte)'M' && data[1] == (byte)'M' && data[2] == 0 && data[3] == 42)); + + static bool IsBig (ReadOnlySpan data) => + data.Length >= 16 && ( + (data[0] == (byte)'I' && data[1] == (byte)'I' && data[2] == 0x2B && data[3] == 0) || + (data[0] == (byte)'M' && data[1] == (byte)'M' && data[2] == 0 && data[3] == 0x2B)); + + /// + /// A table is read when its count and all its entries lie inside the data, as exiftool, ImageIO and TagLib# + /// read it: the next-IFD offset after the entries may be missing or cut short, and is then 0 (). + /// A table whose entries run past the data is read by none of them. No table starts inside the 8-byte classic + /// header. Any count that fits is read: exiftool reads a classic table of 65,535 entries and a BigTIFF one of + /// 70,000 (measured); a walk bounds the entries it reads in all by instead. + /// + public bool TryTable (long at, out int count) + { + count = 0; + if (at < HeaderSize || at > Length - CountSize) + return false; + long entries; + if (!Big) + entries = U16 (at); + else if (!Endian.TryU64 (Data, (int)at, LittleEndian, out entries)) + return false; + if (entries > (Length - at - CountSize) / EntrySize) + return false; + count = (int)entries; + return true; + } + + /// + /// The most entries tables that do not overlap can hold in all, one per entry's bytes: a walk that has read more + /// has met tables that share their entries, and stops there, so its work stays proportional to the data. + /// + public long EntryBound => Length / EntrySize; + + public long Entry (long table, long n) => table + CountSize + (n * EntrySize); + public int Tag (long entry) => U16 (entry); + public int Type (long entry) => U16 (entry + 2); + + /// The entry's value count; a BigTIFF count above 2^63 - 1, which no data can hold, as 0. + public long Count (long entry) => !Big ? U32 (entry + 4) : U64OrZero (entry + 4); + + /// Where an entry's value, or the offset of its value, starts. + public long ValueField (long entry) => entry + (Big ? 12 : 8); + + /// The bytes of value an entry holds itself: 4 in classic TIFF, 8 in BigTIFF. + public int ValueFieldSize => Big ? 8 : 4; + + /// + /// The value in the entry, or the offset of its value: a 4-byte field, or in BigTIFF an 8-byte one, of which a + /// value above 2^63 - 1 is past any data (). + /// + public long Value (long entry) => !Big ? U32 (entry + 8) : Endian.TryU64 (Data, (int)entry + 12, LittleEndian, out var value) ? value : long.MaxValue; + + /// + /// Where the offsets a pointer entry (0x8769, 0x8825, 0xA005, 0x014A) names are, as exiftool follows them + /// (measured): BYTE, SHORT, LONG, SBYTE, SSHORT, SLONG and IFD values; in classic TIFF also UNDEFINED with count + /// 1, and in BigTIFF also LONG8, SLONG8 and IFD8 (an UNDEFINED byte there is read as text, which names the + /// header). An Exif IFD pointer only with count 1, a GPS or interoperability pointer by its first value, SubIFDs + /// by every value. Values that do not fit in the entry are at its offset and must all lie in the data. Any other + /// type, or count 0, names nothing. + /// + public bool TryPointers (long entry, out PointerValues values) + { + values = default; + var tag = Tag (entry); + var count = Count (entry); + var type = Type (entry); + var size = type switch { + 1 or 6 => 1, + 7 when count == 1 && !Big => 1, + 3 or 8 => 2, + 4 or 9 or 13 => 4, + 16 or 17 or 18 when Big => 8, + _ => 0 + }; + // SBYTE and SSHORT values are signed. A negative SLONG read unsigned is at least 2^31, past any data, and a + // negative SLONG8 is above 2^63 - 1, which PointerAt reads as no table, so neither needs its sign. + var signed = type is 6 or 8; + if (size == 0 || count == 0 || (tag == ExifIfdPointer && count != 1)) + return false; + var from = count <= ValueFieldSize / size ? ValueField (entry) : Value (entry); + // From past the data, the room left is negative: no value fits. + if (count > (Length - from) / size) + return false; + values = new PointerValues (from, tag is GpsIfdPointer or InteropIfdPointer ? 1 : count, size, signed); + return true; + } + + /// + /// A classic pointer entry's 4-byte field as one LONG, whatever the entry's type and count: how TagLib# reads IFD0's + /// Exif IFD and GPS IFD pointers (measured: it follows a SHORT, ASCII, RATIONAL or count-0 or count-2 0x8769 or + /// 0x8825 in IFD0 to the table that LONG names). + /// + public static PointerValues RawPointer (long entry) => new (entry + 8, 1, 4, false); + + /// The offset a pointer value names, or 0 (no table) when it is negative or above 2^63 - 1. + public long PointerAt (PointerValues values, long n) + { + var at = values.From + (n * values.Size); + if (values.Size == 8) + return U64OrZero (at); + long value = values.Size switch { + 1 => Data[(int)at], + 2 => U16 (at), + _ => U32 (at) + }; + return values.Signed && value >= 1L << ((8 * values.Size) - 1) ? 0 : value; + } + + /// + /// The next-IFD offset after a table's entries (4 bytes, or 8 in BigTIFF), or 0 when its bytes are not all in + /// the data or, in BigTIFF, it is above 2^63 - 1. + /// + public long Next (long table, long count) + { + var at = Entry (table, count); + if (Big) + return U64OrZero (at); + return at + 4 <= Length ? U32 (at) : 0; + } + + long U64OrZero (long at) => Endian.TryU64 (Data, (int)at, LittleEndian, out var value) ? value : 0; + + /// + /// The bytes a classic table occupies: its count, its entries and its next-IFD offset (bytes past the data are + /// never written or zeroed, so a range that runs past it needs no clipping). + /// + public static (long Start, long End) TableRange (long table, long count) => (table, table + 2 + (count * 12L) + 4); + + /// + /// The out-of-line value of a classic entry; empty when the value fits in the entry. Only the Exif edit reads + /// values out of line, and it reads classic TIFF only. + /// + public (long Start, long End) ValueRange (long entry) + { + var bytes = TypeSize (Type (entry)) * Count (entry); + if (bytes <= 4) + return (0, 0); + var offset = Value (entry); + return (offset, offset + bytes); + } + + /// + /// A SHORT (3) or LONG (4) array that lies wholly in the data (TIFF 6.0 §2). An inline value is the entry's own + /// value field. Any other type, a count of zero, or an array that runs past the data is not located. + /// + internal bool TryValueArray (long entry, out ValueArray key) + { + key = default; + var size = Type (entry) switch { 3 => 2, 4 => 4, _ => 0 }; + var items = Count (entry); + if (size == 0 || items == 0) + return false; + var at = items * size <= 4 ? entry + 8 : Value (entry); + if (at < 0 || at > Length || items > (Length - at) / size) + return false; + key = new ValueArray (at, items, size); + return true; + } + + /// + /// Whether exiftool reads an entry of this format (measured, exiftool 13.55): TIFF 6.0 §2 types 1-12 and IFD + /// (13, TIFF Technical Note 1). A first entry of any other format drops the whole table, and none of its + /// pointers or its next IFD is followed; a later entry of such a format is skipped and the table is read. + /// + public static bool FormatExiftoolReads (int type) => type is >= 1 and <= 13; + + /// + /// The size of one value of a classic field type: TIFF 6.0 §2 types 1-12 and IFD (13, TIFF Technical Note 1); 0 + /// for any other type. + /// + static int TypeSize (int type) => type switch { + 1 or 2 or 6 or 7 => 1, + 3 or 8 => 2, + 4 or 9 or 11 or 13 => 4, + 5 or 10 or 12 => 8, + _ => 0 + }; +} + +/// The offsets a pointer entry names: where they start, how many are followed, their size and signedness. +readonly record struct PointerValues (long From, long Count, int Size, bool Signed); + +/// One SHORT or LONG value array: where it starts, how many values, and the size of each. +readonly record struct ValueArray (long At, long Count, int Size); diff --git a/src/TagLibSharp2/Image/Tiff/TiffSize.cs b/src/TagLibSharp2/Image/Tiff/TiffSize.cs new file mode 100644 index 00000000..08d748d5 --- /dev/null +++ b/src/TagLibSharp2/Image/Tiff/TiffSize.cs @@ -0,0 +1,239 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using TagLibSharp2.Core; + +namespace TagLibSharp2.Image.Tiff; + +/// +/// The width and height of a TIFF or DNG, as exiftool's ImageSize gives them (measured): tags 256 and 257 (SHORT, +/// SSHORT, LONG or SLONG, LONG8 in BigTIFF, one value each, 1 to 2^31 - 1) of the first IFD whose NewSubfileType (254) is 0, the +/// full-resolution image, in the order exiftool reads them: IFD0, its SubIFDs (tag 330) depth first in entry order +/// with each one's next IFDs, then IFD0's next IFD. Without one, IFD0's. DNG is TIFF with tag 50706 in IFD0. +/// Classic TIFF and BigTIFF. +/// +/// +/// Tables, entries, next offsets and SubIFD offsets are read by , as every IFD walk reads +/// them. A classic IFD with 1 or 3 bytes of its 4-byte next-IFD field in the data is not read (exiftool 13.55: +/// "Illegal directory size"); 0, 2 or 4 bytes are, and BigTIFF is read either way. The walk is iterative (a +/// file-controlled chain must not recurse), at most 64 SubIFD levels deep and 4,096 IFDs in all, each IFD read +/// once, and it stops when the entries it has read pass (past it the tables +/// share their entries). Detection reads IFD0 only. Unlike exiftool, a width and a height are taken from one IFD, +/// never one from each. +/// +static class TiffSize +{ + const int DngVersionTag = 0xC612; + const int NewSubFileTypeTag = 254; + const int MaxTiffIfds = 4096; + const int MaxTiffDepth = 64; + const int SmallIfdCount = 16; + const int MaxSubIfds = 32; + + /// IFD tables read on this thread, for tests that bound the walk by an operation count. + [ThreadStatic] + internal static int IfdReads; + + /// IFD entries read on this thread, for tests that bound the walk by an operation count. + [ThreadStatic] + internal static long EntryReads; + + public static bool HasDngVersion (ReadOnlySpan data) => + TiffReader.TryOpen (data, out var tiff, out var first) && tiff.TryTable (first, out var count) && + ReadIfd (tiff, first, count, [], out _).SawDng; + + /// The TIFF. + /// Report the format as DNG even without the DNG version tag (a file named .dng). + /// The size, and the format: DNG or TIFF. + public static bool TryRead (ReadOnlySpan data, bool dng, out ImageProperties? properties) + { + properties = null; + if (!TiffReader.TryOpen (data, out var tiff, out var first)) + return false; + var (root, full) = Walk (tiff, first); + var image = full ?? root; + if (!image.HasSize) + return false; + properties = new ImageProperties (image.Width, image.Height, 0, dng || root.SawDng ? "DNG" : "TIFF"); + return true; + } + + /// + /// Why a classic TIFF header has no size: IFD0's next-IFD field has 1 or 3 of its 4 bytes, so IFD0 is not read. + /// Null for every other file, including one whose size is 0, negative, or past . + /// + internal static string? Ifd0NextCutShort (ReadOnlySpan data) + { + if (!TiffReader.TryOpen (data, out var tiff, out var first) || tiff.Big) + return null; + if (!tiff.TryTable (first, out var count) || !ClassicNextIsUnread (tiff, first, count)) + return null; + var present = (int)Math.Min (4, tiff.Length - tiff.Entry (first, count)); + return $"IFD0's next-IFD field has {present} of its 4 bytes, so IFD0 is not read and the image has no size."; + } + + // IFD0, and the first full-resolution IFD in exiftool's order (IFD0 itself when it is one) or null. + static (IfdInfo Root, IfdInfo? Full) Walk (TiffReader tiff, long first) + { + Span<(long, int)> pending = stackalloc (long, int)[SmallIfdCount]; + Span visitedSmall = stackalloc long[SmallIfdCount]; + Span subs = stackalloc long[MaxSubIfds]; + var stack = new IfdStack (pending); + Dictionary? visited = null; + IfdInfo root = default; + var entries = tiff.EntryBound; + stack.Push (first, 0); + var seen = 0; + while (stack.Count > 0 && seen < MaxTiffIfds) { + var (offset, depth) = stack.Pop (); + if (!tiff.TryTable (offset, out var count) || !Visit (visitedSmall, ref visited, seen, offset, tiff.Length)) + continue; + // 1 or 3 bytes of a classic next-IFD field: exiftool drops the directory. Do not read its entries or follow it. + if (ClassicNextIsUnread (tiff, offset, count)) + continue; + entries -= count; + if (entries < 0) + break; + var info = ReadIfd (tiff, offset, count, subs, out var subCount); + if (seen++ == 0) + root = info; + if (info.FullResolution) + return (root, info); + if (depth >= MaxTiffDepth) + continue; + stack.Push (info.Next, depth); + for (var s = subCount - 1; s >= 0; s--) + stack.Push (subs[s], depth + 1); + } + + return (root, null); + } + + // exiftool 13.55 reads a classic IFD when 0, 2 or 4 bytes of its next-IFD field are present and drops it when 1 + // or 3 are ("Illegal directory size"). BigTIFF still reports the image. + static bool ClassicNextIsUnread (TiffReader tiff, long table, long count) + { + if (tiff.Big) + return false; + var at = tiff.Entry (table, count); + if (at >= tiff.Length) + return false; + var present = (int)Math.Min (4, tiff.Length - at); + return present is 1 or 3; + } + + // The work stack of offsets and their SubIFD depths: on the stack for a handful of IFDs, then on the heap, + // doubling. Every read IFD pushes at most 33 offsets, so it grows with the IFDs read. + ref struct IfdStack (Span<(long Offset, int Depth)> items) + { + Span<(long Offset, int Depth)> _items = items; + + public int Count { get; private set; } + + public void Push (long offset, int depth) + { + if (Count == _items.Length) { + var grown = new (long, int)[2 * Count]; + _items.CopyTo (grown); + _items = grown; + } + + _items[Count++] = (offset, depth); + } + + public (long Offset, int Depth) Pop () => _items[--Count]; + } + + // True the first time a table's offset is seen. The first SmallIfdCount offsets are kept in a stack span and + // scanned; past that in a set sized by the IFDs the data can hold (the smallest is a 2-byte count and a 4-byte + // next offset), at most the IFD cap. + static bool Visit (Span small, ref Dictionary? set, int seen, long offset, int length) + { + if (set is null) { + for (var n = 0; n < seen; n++) { + if (small[n] == offset) + return false; + } + + if (seen < small.Length) { + small[seen] = offset; + return true; + } + + set = new Dictionary (Math.Min (MaxTiffIfds, length / 6)); + foreach (var known in small) + set[known] = 0; + } + + if (set.ContainsKey (offset)) + return false; + set[offset] = 0; + return true; + } + + readonly record struct IfdInfo (int Width, int Height, bool FullResolutionType, bool SawDng, long Next) + { + public bool HasSize => Width > 0 && Height > 0; + public bool FullResolution => FullResolutionType && HasSize; + } + + // What one readable IFD of count entries says. Its SubIFD offsets go to subs, as many as fit. + static IfdInfo ReadIfd (TiffReader tiff, long offset, int count, Span subs, out int subCount) + { + subCount = 0; + IfdReads++; + int width = 0, height = 0; + bool full = false, sawDng = false; + for (var n = 0; n < count; n++) { + EntryReads++; + var entry = tiff.Entry (offset, n); + switch (tiff.Tag (entry)) { + case DngVersionTag: + sawDng = true; + break; + case 256 when TryScalar (tiff, entry, out var value) && value <= int.MaxValue: + width = (int)value; + break; + case 257 when TryScalar (tiff, entry, out var value) && value <= int.MaxValue: + height = (int)value; + break; + case NewSubFileTypeTag when TryScalar (tiff, entry, out var value): + full = value == 0; + break; + case TiffReader.SubIfdsPointer when tiff.TryPointers (entry, out var values): + for (var k = 0L; k < values.Count && subCount < subs.Length; k++) + subs[subCount++] = tiff.PointerAt (values, k); + break; + } + } + + return new IfdInfo (width, height, full, sawDng, tiff.Next (offset, count)); + } + + // One SHORT, SSHORT, LONG or SLONG value (or LONG8 in BigTIFF) in the entry, as exiftool reads them. + static bool TryScalar (TiffReader tiff, long entry, out long value) + { + var at = (int)tiff.ValueField (entry); + value = 0; + if (tiff.Count (entry) != 1) + return false; + switch (tiff.Type (entry)) { + case 3: + value = tiff.U16 (at); + return true; + case 4: + value = tiff.U32 (at); + return true; + case 8: + value = (short)tiff.U16 (at); + return true; + case 9: + value = (int)tiff.U32 (at); + return true; + case 16 when tiff.Big: + return Endian.TryU64 (tiff.Data, at, tiff.LittleEndian, out value); + default: + return false; + } + } +} diff --git a/src/TagLibSharp2/Image/Xmp/XmlText.cs b/src/TagLibSharp2/Image/Xmp/XmlText.cs new file mode 100644 index 00000000..4ace2d12 --- /dev/null +++ b/src/TagLibSharp2/Image/Xmp/XmlText.cs @@ -0,0 +1,154 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Text; +using System.Xml; + +namespace TagLibSharp2.Image.Xmp; + +/// +/// The XML 1.0 rules the XMP splice needs on packet text: characters and white space (§2.2, §2.3), escaping, where +/// a tag or an attribute value ends, and offsets from the reader's line and column (§2.11). +/// +static class XmlText +{ + // IXmlLineInfo counts a line break as CR LF, CR or LF (XML 1.0 §2.11) and columns from 1. + public static int[] LineStarts (string text) + { + var starts = new List { 0 }; + for (var i = 0; i < text.Length; i++) { + if (text[i] == '\r') { + if (i + 1 < text.Length && text[i + 1] == '\n') + i++; + starts.Add (i + 1); + } else if (text[i] == '\n') { + starts.Add (i + 1); + } + } + + return [.. starts]; + } + + public static int Offset (int[] lines, int line, int position) + { + if (line < 1 || line > lines.Length || position < 1) + return -1; + return lines[line - 1] + position - 1; + } + + public static bool At (string text, int index, string token) => + index >= 0 && index <= text.Length - token.Length && string.CompareOrdinal (text, index, token, 0, token.Length) == 0; + + // The index just past the '>' that closes a tag, skipping quoted attribute values. + public static bool TryTagEnd (string text, int from, out int end) + { + end = -1; + var quote = '\0'; + for (var i = from; i < text.Length; i++) { + var c = text[i]; + if (quote != '\0') { + if (c == quote) + quote = '\0'; + } else if (c is '"' or '\'') { + quote = c; + } else if (c == '>') { + end = i + 1; + return true; + } + } + + return false; + } + + public static bool TryAttributeEnd (string text, int from, out int end) + { + end = -1; + var i = from; + while (i < text.Length && IsXmlSpace (text[i])) + i++; + if (i >= text.Length || text[i] != '=') + return false; + i++; + while (i < text.Length && IsXmlSpace (text[i])) + i++; + if (i >= text.Length || text[i] is not ('"' or '\'')) + return false; + var close = text.IndexOf (text[i], i + 1); + if (close < 0) + return false; + end = close + 1; + return true; + } + + public static bool IsXmlSpace (char c) => c is ' ' or '\t' or '\r' or '\n'; + + public static bool IsWellFormed (string packet) + { + var settings = new XmlReaderSettings { DtdProcessing = DtdProcessing.Prohibit, XmlResolver = null }; + try { + using var reader = XmlReader.Create (new StringReader (packet), settings); + while (reader.Read ()) { + } + + return true; + } catch (XmlException) { + return false; + } + } + + // XML 1.0 §2.2 Char: tab, LF, CR, U+0020-U+D7FF, U+E000-U+FFFD and paired surrogates. + public static bool IsXmlText (string value) + { + for (var i = 0; i < value.Length; i++) { + var c = value[i]; + if (char.IsHighSurrogate (c)) { + if (i + 1 >= value.Length || !char.IsLowSurrogate (value[i + 1])) + return false; + i++; + continue; + } + + if (c is '\t' or '\n' or '\r') + continue; + if (c < 0x20 || char.IsLowSurrogate (c) || c is '￾' or '￿') + return false; + } + + return true; + } + + public static string EscapeXml (string value, bool attribute) + { + var builder = new StringBuilder (value.Length + 16); + foreach (var c in value) { + switch (c) { + case '&': + builder.Append ("&"); + break; + case '<': + builder.Append ("<"); + break; + case '>': + builder.Append (">"); + break; + case '"' when attribute: + builder.Append ("""); + break; + case '\r': + builder.Append (" "); + break; + case '\n' when attribute: + builder.Append (" "); + break; + case '\t' when attribute: + builder.Append (" "); + break; + default: + builder.Append (c); + break; + } + } + + return builder.ToString (); + } +} diff --git a/src/TagLibSharp2/Image/Xmp/XmpMirror.cs b/src/TagLibSharp2/Image/Xmp/XmpMirror.cs new file mode 100644 index 00000000..f28a9820 --- /dev/null +++ b/src/TagLibSharp2/Image/Xmp/XmpMirror.cs @@ -0,0 +1,166 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Text; + +namespace TagLibSharp2.Image.Xmp; + +/// +/// Replaces each changed field's property in an XMP packet, or removes it when the field is null. A property the +/// packet does not hold is not added. The property's own start and end tags (and so any namespace they declare) are +/// kept; only its content changes. Every other character of the packet is kept, in one forward pass. +/// +static class XmpMirror +{ + /// Characters the splice has written on this thread, for tests that pin it to one pass. + [ThreadStatic] + internal static long SpliceWrites; + + /// The packet text. + /// The tag whose changed fields are written. + /// Names the block in an error, such as "PNG XMP packet". + /// The new packet, or itself when nothing changed. + /// Why the packet cannot be updated. + /// False, with an error, when the packet is not well-formed XML or a value cannot be written as XML. + internal static bool TryUpdate (string packet, ImageTag tag, string carrier, out string updated, out string? error) + { + // A UTF-8 byte order mark before the packet is not part of the XML. + if (packet.Length > 0 && packet[0] == '') + return TryUpdateAfterBom (packet, tag, carrier, out updated, out error); + + // XMP Part 1 §7.3: the packet ends with the trailer processing instruction. Some writers follow it with + // NULs (ImageIO ends JPEG XMP with one) or padding; those bytes are not XML and are copied back as they are. + var last = packet.LastIndexOf ('>'); + if (last >= 0 && last < packet.Length - 1 && IsPacketTail (packet, last + 1)) + return TryUpdateBeforeTail (packet, last + 1, tag, carrier, out updated, out error); + return TrySplice (packet, tag, carrier, out updated, out error); + } + + static bool TryUpdateAfterBom (string packet, ImageTag tag, string carrier, out string updated, out string? error) + { + updated = packet; + if (!TryUpdate (packet.Substring (1), tag, carrier, out var body, out error)) + return false; + updated = body.Length == packet.Length - 1 && string.CompareOrdinal (body, 0, packet, 1, body.Length) == 0 ? packet : "" + body; + return true; + } + + static bool TryUpdateBeforeTail (string packet, int tail, ImageTag tag, string carrier, out string updated, out string? error) + { + updated = packet; + if (!TryUpdate (packet.Substring (0, tail), tag, carrier, out var head, out error)) + return false; + updated = head.Length == tail && string.CompareOrdinal (head, 0, packet, 0, head.Length) == 0 ? packet : Join (head, packet, tail); + return true; + } + + static bool TrySplice (string packet, ImageTag tag, string carrier, out string updated, out string? error) + { + updated = packet; + var edits = new List (); + if (!XmpProperties.TryFind (packet, tag, carrier, edits, out error)) + return false; + if (edits.Count == 0) + return true; + + // One forward pass: copy the text between edits, then each edit's replacement. Edits never overlap. + edits.Sort ((a, b) => a.Start.CompareTo (b.Start)); + var builder = new StringBuilder (packet.Length + 64); + var written = new HashSet (); + var at = 0; + foreach (var edit in edits) { + var value = tag.Field (edit.Field.Store); + var keep = value is not null && written.Add (edit.Field.Store); + if (keep && !XmlText.IsXmlText (value!)) { + error = $"The {carrier} holds {edit.Field.Name}, and the new value has a character XML cannot store, so the copy there cannot be updated."; + return false; + } + + at = keep ? Replace (builder, packet, at, edit, value!) : Remove (builder, packet, at, edit); + } + + Append (builder, packet, at, packet.Length); + updated = builder.ToString (); + if (!XmlText.IsWellFormed (updated)) { + error = $"The {carrier} could not be updated: the edited packet is not well-formed XML."; + return false; + } + + return true; + } + + // Removed: an attribute takes the white space before it with it. + static int Remove (StringBuilder builder, string packet, int at, XmpEdit edit) + { + Append (builder, packet, at, edit.Attribute ? edit.LeadStart : edit.Start); + return edit.End; + } + + static int Replace (StringBuilder builder, string packet, int at, XmpEdit edit, string value) + { + Append (builder, packet, at, edit.Start); + if (edit.Attribute) { + Write (builder, $"{edit.Name}=\"{XmlText.EscapeXml (value, attribute: true)}\""); + return edit.End; + } + + // The start tag, without rdf attributes that would contradict the new content. + var tagAt = edit.Start; + foreach (var (cutStart, cutEnd) in edit.Cuts) { + Append (builder, packet, tagAt, cutStart); + tagAt = cutEnd; + } + + Append (builder, packet, tagAt, edit.StartTagEnd); + Write (builder, edit.Empty ? ">" : ""); + Write (builder, PropertyContent (edit, value)); + if (edit.Empty) + Write (builder, $""); + else + Append (builder, packet, edit.ContentEnd, edit.End); + return edit.End; + } + + static string Join (string head, string packet, int tail) => +#if NETSTANDARD2_0 || NETSTANDARD2_1 + head + packet.Substring (tail); +#else + string.Concat (head.AsSpan (), packet.AsSpan (tail)); +#endif + + static bool IsPacketTail (string packet, int from) + { + for (var i = from; i < packet.Length; i++) { + if (packet[i] != '\0' && !XmlText.IsXmlSpace (packet[i])) + return false; + } + + return true; + } + + static void Append (StringBuilder builder, string text, int from, int to) + { + if (to <= from) + return; + builder.Append (text, from, to - from); + SpliceWrites += to - from; + } + + static void Write (StringBuilder builder, string text) + { + builder.Append (text); + SpliceWrites += text.Length; + } + + static string PropertyContent (XmpEdit edit, string value) + { + var item = XmlText.EscapeXml (value, attribute: false); + // The RDF namespace may have no prefix in scope at the property (a declaration on it can hide one); + // then the container declares it as its default namespace. + var rdf = edit.RdfPrefix is null ? "" : edit.RdfPrefix.Length == 0 ? "" : edit.RdfPrefix + ":"; + var declare = edit.RdfPrefix is null ? $" xmlns=\"{XmpProperties.RdfNamespace}\"" : ""; + return edit.Field.Ordered + ? $"<{rdf}Seq{declare}><{rdf}li>{item}" + : $"<{rdf}Alt{declare}><{rdf}li xml:lang=\"x-default\">{item}"; + } +} diff --git a/src/TagLibSharp2/Image/Xmp/XmpProperties.cs b/src/TagLibSharp2/Image/Xmp/XmpProperties.cs new file mode 100644 index 00000000..5d690521 --- /dev/null +++ b/src/TagLibSharp2/Image/Xmp/XmpProperties.cs @@ -0,0 +1,219 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Xml; +using static TagLibSharp2.Image.MirrorFields; + +namespace TagLibSharp2.Image.Xmp; + +/// +/// Finds, in the text of an XMP packet, each changed field's property of a top-level rdf:Description: as an +/// attribute or as a child element (XMP Part 1 §7.4, §7.5), with the exact character ranges to splice. +/// +static class XmpProperties +{ + internal const string RdfNamespace = "http://www.w3.org/1999/02/22-rdf-syntax-ns#"; + + // rdf attributes on a property element that say its content is something else; they go with a new value. + static readonly string[] ContradictingRdfAttributes = ["resource", "parseType", "datatype", "nodeID"]; + + public static bool TryFind (string packet, ImageTag tag, string carrier, List edits, out string? error) + { + error = null; + var lines = XmlText.LineStarts (packet); + var settings = new XmlReaderSettings { + DtdProcessing = DtdProcessing.Prohibit, + XmlResolver = null, + IgnoreComments = true, + IgnoreProcessingInstructions = false, + CloseInput = true + }; + try { + using var reader = XmlReader.Create (new StringReader (packet), settings); + return TryScan (packet, lines, reader, tag, carrier, edits, out error); + } catch (XmlException ex) { + // A packet that is not well-formed is read by no XMP reader (exiftool: "Empty XMP"); it can hold a copy only + // where its text names a changed field's property, and is refused only then. + edits.Clear (); + if (!NamesAnyField (packet, tag)) + return true; + error = $"The {carrier} is not well-formed XML ({ex.Message}), so its copy of a changed field cannot be updated."; + return false; + } + } + + static bool NamesAnyField (string packet, ImageTag tag) + { + foreach (var field in All) { + if (tag.Changed (field.Store) && packet.Contains (field.XmpName, StringComparison.Ordinal)) + return true; + } + + return false; + } + + static bool TryScan (string packet, int[] lines, XmlReader reader, ImageTag tag, string carrier, List edits, out string? error) + { + error = null; + var info = (IXmlLineInfo)reader; + var descriptionDepth = -1; + while (reader.Read ()) { + if (reader.NodeType == XmlNodeType.EndElement && reader.Depth == descriptionDepth) { + descriptionDepth = -1; + continue; + } + + if (reader.NodeType != XmlNodeType.Element) + continue; + if (descriptionDepth < 0) { + if (reader.LocalName == "Description" && reader.NamespaceURI == RdfNamespace) { + if (!TryFindAttributes (packet, lines, reader, info, tag, carrier, edits, out error)) + return false; + if (!reader.IsEmptyElement) + descriptionDepth = reader.Depth; + } + + continue; + } + + if (reader.Depth != descriptionDepth + 1 || FieldFor (reader.NamespaceURI, reader.LocalName, tag) is not MirrorField field) + continue; + if (!TryElementEdit (packet, lines, reader, info, field, out var edit)) { + error = NotLocated (carrier, field); + return false; + } + + edits.Add (edit!); + } + + return true; + } + + static string NotLocated (string carrier, MirrorField field) => + $"The {carrier} holds {field.Name}, and the property could not be located in the packet text, so the copy there cannot be updated."; + + static bool TryFindAttributes (string packet, int[] lines, XmlReader reader, IXmlLineInfo info, ImageTag tag, string carrier, List edits, out string? error) + { + error = null; + if (!reader.MoveToFirstAttribute ()) + return true; + do { + var field = FieldFor (reader.NamespaceURI, reader.LocalName, tag); + if (field is null) + continue; + if (!TryAttributeRange (packet, lines, reader, info, out var lead, out var start, out var end)) { + error = NotLocated (carrier, field); + return false; + } + + edits.Add (new XmpEdit (field, reader.Name, Attribute: true) { LeadStart = lead, Start = start, End = end }); + } while (reader.MoveToNextAttribute ()); + reader.MoveToElement (); + return true; + } + + // The range of the attribute the reader is on, and where the white space before it starts. + static bool TryAttributeRange (string packet, int[] lines, XmlReader reader, IXmlLineInfo info, out int lead, out int start, out int end) + { + end = -1; + start = XmlText.Offset (lines, info.LineNumber, info.LinePosition); + lead = start; + var name = reader.Name; + if (start < 0 || !XmlText.At (packet, start, name) || !XmlText.TryAttributeEnd (packet, start + name.Length, out end)) + return false; + while (lead > 0 && XmlText.IsXmlSpace (packet[lead - 1])) + lead--; + return true; + } + + static bool TryElementEdit (string packet, int[] lines, XmlReader reader, IXmlLineInfo info, MirrorField field, out XmpEdit? edit) + { + edit = null; + var name = reader.Name; + var nameAt = XmlText.Offset (lines, info.LineNumber, info.LinePosition); + var start = nameAt - 1; + if (start < 0 || packet[start] != '<' || !XmlText.At (packet, nameAt, name) || !XmlText.TryTagEnd (packet, nameAt + name.Length, out var startTagEnd)) + return false; + var rdfPrefix = (reader as IXmlNamespaceResolver)?.LookupPrefix (RdfNamespace); + var empty = reader.IsEmptyElement; + if (!TryRdfCuts (packet, lines, reader, info, out var cuts)) + return false; + var element = new XmpEdit (field, name, Attribute: false) { Start = start, StartTagEnd = startTagEnd, RdfPrefix = rdfPrefix, Cuts = cuts }; + if (!empty) + return TryCloseElement (packet, lines, reader, info, element, out edit); + + // "": the start tag is kept up to the "/". + var slash = startTagEnd - 2; + if (packet[slash] != '/') + return false; + edit = element with { StartTagEnd = slash, ContentEnd = startTagEnd, End = startTagEnd, Empty = true }; + return true; + } + + // The ranges of the rdf attributes of the element the reader is on that contradict a new content. + static bool TryRdfCuts (string packet, int[] lines, XmlReader reader, IXmlLineInfo info, out List<(int Start, int End)> cuts) + { + cuts = []; + if (!reader.MoveToFirstAttribute ()) + return true; + do { + if (reader.NamespaceURI != RdfNamespace || Array.IndexOf (ContradictingRdfAttributes, reader.LocalName) < 0) + continue; + if (!TryAttributeRange (packet, lines, reader, info, out var lead, out _, out var attributeEnd)) + return false; + cuts.Add ((lead, attributeEnd)); + } while (reader.MoveToNextAttribute ()); + reader.MoveToElement (); + return true; + } + + // Reads to the element's end tag and records where its content and end tag are. + static bool TryCloseElement (string packet, int[] lines, XmlReader reader, IXmlLineInfo info, XmpEdit element, out XmpEdit? edit) + { + edit = null; + var name = element.Name; + var depth = reader.Depth; + while (reader.Read ()) { + if (reader.NodeType != XmlNodeType.EndElement || reader.Depth != depth) + continue; + var closeAt = XmlText.Offset (lines, info.LineNumber, info.LinePosition); + if (closeAt < 2 || packet[closeAt - 2] != '<' || packet[closeAt - 1] != '/' || !XmlText.At (packet, closeAt, name) || !XmlText.TryTagEnd (packet, closeAt + name.Length, out var end)) + return false; + edit = element with { ContentEnd = closeAt - 2, End = end }; + return true; + } + + return false; + } + + static MirrorField? FieldFor (string ns, string localName, ImageTag tag) + { + foreach (var field in All) { + if (tag.Changed (field.Store) && field.XmpNamespace == ns && field.XmpName == localName) + return field; + } + + return null; + } +} + +/// One property to splice: its character ranges in the packet text. +sealed record XmpEdit (MirrorField Field, string Name, bool Attribute) +{ + /// An attribute's preceding white space, removed with it. + public int LeadStart { get; init; } + + /// The '<' of the element, or the attribute name. + public int Start { get; init; } + + /// Past the start tag's '>', or the '/' of an empty element. + public int StartTagEnd { get; init; } + + /// The '<' of the end tag. + public int ContentEnd { get; init; } + + public int End { get; init; } + public bool Empty { get; init; } + public string? RdfPrefix { get; init; } + public List<(int Start, int End)> Cuts { get; init; } = []; +} diff --git a/src/TagLibSharp2/README.md b/src/TagLibSharp2/README.md index 0bbafc3f..221f2ab7 100644 --- a/src/TagLibSharp2/README.md +++ b/src/TagLibSharp2/README.md @@ -35,6 +35,7 @@ A modern .NET library for reading and writing metadata in media files. | Audible .aa | ✅ | ✅¹ | ✅ | | Audible .aax (as MP4) | ✅ | ✅ | ✅ | | APE Tags (standalone) | ✅ | ✅ | — | +| JPEG, PNG, GIF, BMP, PCX, Netpbm, TIFF, DNG, SVG | Dimensions; PNG text, GIF comment, JPEG COM | Those text fields | — | ¹ The text dictionary is written; the encrypted audio is copied unchanged. Edited `.aa` files have been checked with ffprobe, ffmpeg, and ExifTool, not with Audible's own apps, which may check a digest stored in the file. Keep a copy of the original, or save to a new path. diff --git a/src/TagLibSharp2/TagLibSharp2.csproj b/src/TagLibSharp2/TagLibSharp2.csproj index e3e48122..5cfd0fd9 100644 --- a/src/TagLibSharp2/TagLibSharp2.csproj +++ b/src/TagLibSharp2/TagLibSharp2.csproj @@ -9,8 +9,8 @@ $(ReleaseVersion) - A modern .NET library for reading and writing metadata in media files. Supports 18 formats: MP3 (ID3v1/ID3v2), FLAC, Ogg Vorbis, Ogg Opus, Ogg FLAC, WAV, AIFF, MP4/M4A (AAC/ALAC, including Audible .aax), ASF/WMA, DSF (DSD), DFF (DSDIFF), WavPack, Monkey's Audio (.ape), Musepack, Matroska/WebM, MPEG program streams (.mpg/.vob/.m2v), Audible .aa, and APE tags. Clean, span-based API designed for performance. MIT licensed alternative to TagLib#. - audio;metadata;id3;flac;vorbis;ogg;opus;mp3;mp4;m4a;aac;alac;wav;aiff;dsf;dsd;dff;dsdiff;ape;asf;wma;wavpack;musepack;mpc;monkeys-audio;mpeg;mpg;vob;audible;aa;aax;audiobook;tags;taglib;music;album-art;replaygain;musicbrainz + A modern .NET library for reading and writing metadata in media files. Supports MP3 (ID3v1/ID3v2), FLAC, Ogg Vorbis, Ogg Opus, Ogg FLAC, WAV, AIFF, MP4/M4A (AAC/ALAC, including Audible .aax), ASF/WMA, DSF (DSD), DFF (DSDIFF), WavPack, Monkey's Audio (.ape), Musepack, Matroska/WebM, MPEG program streams (.mpg/.vob/.m2v), raw AAC, Audible .aa, and APE tags. Still images (JPEG, PNG, GIF, BMP, PCX, Netpbm, TIFF, DNG, SVG) open with width and height. PNG text, GIF comments, and JPEG COM markers can be edited. Clean, span-based API designed for performance. MIT licensed alternative to TagLib#. + audio;metadata;id3;flac;vorbis;ogg;opus;mp3;mp4;m4a;aac;alac;wav;aiff;dsf;dsd;dff;dsdiff;ape;asf;wma;wavpack;musepack;mpc;monkeys-audio;mpeg;mpg;vob;audible;aa;aax;audiobook;tags;taglib;music;album-art;replaygain;musicbrainz;image;jpeg;png;gif;tiff;svg MIT https://github.com/decriptor/TagLibSharp2 README.md diff --git a/tests/TagLibSharp2.Tests/Core/FaultFileSystem.cs b/tests/TagLibSharp2.Tests/Core/FaultFileSystem.cs new file mode 100644 index 00000000..839cd01e --- /dev/null +++ b/tests/TagLibSharp2.Tests/Core/FaultFileSystem.cs @@ -0,0 +1,72 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using TagLibSharp2.Core; + +namespace TagLibSharp2.Tests.Core; + +/// +/// A file system that fails. answers a directory lookup and throws on every other +/// call, counting both. reports the file present and throws the given error on every read or +/// write. Neither reports timestamps, so an atomic save does not list the directory. +/// +sealed class FaultFileSystem : IFileSystem +{ + readonly Exception? _io; + + readonly bool _rootLookup; + + FaultFileSystem (Exception? io, bool rootLookup) + { + _io = io; + _rootLookup = rootLookup; + } + + public int Calls { get; private set; } + + /// A directory lookup returns "/". Any other call throws and is counted. + public static FaultFileSystem RootDirectory () => new (null, true); + + /// The file exists. Opening, reading, writing, or deleting it throws . + public static FaultFileSystem Io (Exception error) => new (error, false); + + public bool FileExists (string path) => _rootLookup ? Fail (path) : true; + + public Stream OpenRead (string path) => Fail (path); + + public Stream OpenReadWrite (string path) => Fail (path); + + public Stream Create (string path) => Fail (path); + + public byte[] ReadAllBytes (string path) => Fail (path); + + public Task ReadAllBytesAsync (string path, CancellationToken cancellationToken = default) => + Fail> (path); + + public void WriteAllBytes (string path, ReadOnlySpan data) => Fail (path); + + public Task WriteAllBytesAsync (string path, ReadOnlyMemory data, CancellationToken cancellationToken = default) => + Fail (path); + + public void Delete (string path) => Fail (path); + + public void Move (string sourcePath, string destinationPath) => Fail (sourcePath); + + public string? GetDirectoryName (string path) + { + if (!_rootLookup) + return null; + Calls++; + return "/"; + } + + public string GetFileName (string path) => _rootLookup ? Fail (path) : path; + + public string CombinePath (string path1, string path2) => _rootLookup ? Fail (path1) : path1 + path2; + + T Fail (string path) + { + Calls++; + throw _io ?? new InvalidOperationException (path); + } +} diff --git a/tests/TagLibSharp2.Tests/Core/PathSaveCancellationTests.cs b/tests/TagLibSharp2.Tests/Core/PathSaveCancellationTests.cs index 7561e1d1..344d3e50 100644 --- a/tests/TagLibSharp2.Tests/Core/PathSaveCancellationTests.cs +++ b/tests/TagLibSharp2.Tests/Core/PathSaveCancellationTests.cs @@ -10,6 +10,7 @@ using TagLibSharp2.Audible; using TagLibSharp2.Core; using TagLibSharp2.Dsf; +using TagLibSharp2.Image; using TagLibSharp2.Mp4; using TagLibSharp2.Mpeg; using TagLibSharp2.Musepack; @@ -21,6 +22,7 @@ using TagLibSharp2.Tests.Mpeg; using TagLibSharp2.WavPack; using TagLibSharp2.Xiph; +using static TagLibSharp2.Tests.Image.ImageTestBuilder; namespace TagLibSharp2.Tests.Core; @@ -146,6 +148,34 @@ public async Task AiffDeclaredSizePastMemory_BeatsAnAlreadyCancelledToken () Assert.IsFalse (fs.FileExists (Destination)); } + [TestMethod] + public void WriteStream_CancelledCopy_LeavesNoTempFile () + { + var dir = Path.Combine (Path.GetTempPath (), "tls-" + Guid.NewGuid ().ToString ("N")); + Directory.CreateDirectory (dir); + var destination = Path.Combine (dir, "out.bin"); + try { + File.WriteAllBytes (destination, [1, 2, 3]); + + FileWriteResult save; + try { + save = AtomicFileWriter.WriteStream (destination, fileSystem: null, _ => throw new OperationCanceledException ()); + } catch (OperationCanceledException) { + var temps = Directory.GetFiles (dir).Where (path => Path.GetFileName (path).StartsWith (".taglib_", StringComparison.Ordinal)).ToList (); + Assert.Fail ("The cancel escaped the path save and left " + (temps.Count == 0 ? "no temp name" : string.Join (", ", temps))); + return; + } + + Assert.IsFalse (save.IsSuccess); + Assert.AreEqual ("Operation was cancelled", save.Error); + CollectionAssert.AreEqual (new byte[] { 1, 2, 3 }, File.ReadAllBytes (destination)); + var left = Directory.GetFiles (dir).Where (path => Path.GetFileName (path).StartsWith (".taglib_", StringComparison.Ordinal)).ToList (); + Assert.IsEmpty (left, string.Join (", ", left)); + } finally { + Directory.Delete (dir, true); + } + } + [TestMethod] public void WriteStream_ShortCopy_ReturnsTheSourceEndedMessageAndLeavesTheDestination () { @@ -205,10 +235,13 @@ public static IEnumerable ShortSources () yield return ["oggflac", "Failed to render Ogg FLAC file"]; yield return ["m4a", "Failed to render MP4 file"]; yield return ["mpg", "The original data is not the MPEG stream that was read"]; + foreach (var image in new[] { "jpeg", "png", "gif", "tiff", "dng", "bmp", "pcx", "netpbm", "svg" }) + yield return new object[] { image, "The source ended before the requested bytes were copied" }; } static readonly string[] Kinds = [ - "vorbis", "opus", "oggflac", "mp3", "flac", "asf", "dsf", "ape", "wv", "mpc", "aac", "mpg", "aa", "m4a", "wav", "aiff" + "vorbis", "opus", "oggflac", "mp3", "flac", "asf", "dsf", "ape", "wv", "mpc", "aac", "mpg", "aa", "m4a", "wav", "aiff", + "jpeg", "png", "gif", "tiff", "dng", "bmp", "pcx", "netpbm", "svg" ]; static CancellationToken Cancelled () @@ -280,6 +313,7 @@ static Task Save (object file, string path, IFileSystem fs, Can Mp4File mp4 => mp4.SaveToFileAsync (path, fs, token), WavFile wav => wav.SaveToFileAsync (path, fs, token), AiffFile aiff => aiff.SaveToFileAsync (path, fs, token), + StillImageFile image => image.SaveToFileAsync (path, fs, token), _ => throw new InvalidOperationException (file.GetType ().FullName) }; @@ -306,6 +340,15 @@ static Task Save (object file, string path, IFileSystem fs, Can "wav" => Wav (8), "aiff" => Aiff (8, ssndSize: 8), "aiff-huge" => Aiff (8, ssndSize: 0x80000000), + "jpeg" => Jpeg (), + "png" => Png (), + "gif" => Gif (), + "tiff" => TiffImage (2, 3), + "dng" => TiffImage (2, 3, dng: true), + "bmp" => Bmp (4, 2), + "pcx" => Pcx (0, 0, 1, 1, planes: 1), + "netpbm" => "P4\n1 1\n"u8.ToArray (), + "svg" => ""u8.ToArray (), _ => throw new InvalidOperationException (kind) }; @@ -437,91 +480,4 @@ public async Task Probe_ForwardsTheStore_AndAnUnseekableSourceHidesItsLength () source.Flush (); Assert.AreEqual (1, source.Read (new byte[1], 0, 1)); } - - sealed class ProbeFileSystem : IFileSystem - { - public MockFileSystem Store { get; } = new (); - - public bool Seekable { get; set; } = true; - - public string? OpenReadFault { get; set; } - - public void Add (string path, byte[] data) => Store.AddFile (path, data); - - public bool FileExists (string path) => Store.FileExists (path); - - public Stream OpenRead (string path) - { - if (OpenReadFault == "denied") - throw new UnauthorizedAccessException ("Access denied"); - if (OpenReadFault == "io") - throw new IOException ("disk fault"); - - var stream = Store.OpenRead (path); - if (Seekable) - return stream; - return new UnseekableStream (stream); - } - - public Stream OpenReadWrite (string path) => Store.OpenReadWrite (path); - - public Stream Create (string path) => Store.Create (path); - - public byte[] ReadAllBytes (string path) => Store.ReadAllBytes (path); - - public Task ReadAllBytesAsync (string path, CancellationToken cancellationToken = default) => - Store.ReadAllBytesAsync (path, cancellationToken); - - public void WriteAllBytes (string path, ReadOnlySpan data) => Store.WriteAllBytes (path, data); - - public Task WriteAllBytesAsync (string path, ReadOnlyMemory data, CancellationToken cancellationToken = default) => - Store.WriteAllBytesAsync (path, data, cancellationToken); - - public void Delete (string path) => Store.Delete (path); - - public void Move (string sourcePath, string destinationPath) => Store.Move (sourcePath, destinationPath); - - public string? GetDirectoryName (string path) => Store.GetDirectoryName (path); - - public string GetFileName (string path) => Store.GetFileName (path); - - public string CombinePath (string path1, string path2) => Store.CombinePath (path1, path2); - } - - sealed class UnseekableStream : Stream - { - readonly Stream _inner; - - public UnseekableStream (Stream inner) => _inner = inner; - - public override bool CanRead => _inner.CanRead; - - public override bool CanSeek => false; - - public override bool CanWrite => false; - - public override long Length => throw new NotSupportedException (); - - public override long Position { - get => throw new NotSupportedException (); - set => throw new NotSupportedException (); - } - - public override void Flush () => _inner.Flush (); - - public override int Read (byte[] buffer, int offset, int count) => _inner.Read (buffer, offset, count); - - public override long Seek (long offset, SeekOrigin origin) => throw new NotSupportedException (); - - public override void SetLength (long value) => throw new NotSupportedException (); - - public override void Write (byte[] buffer, int offset, int count) => throw new NotSupportedException (); - - protected override void Dispose (bool disposing) - { - if (disposing) - _inner.Dispose (); - base.Dispose (disposing); - } - } } diff --git a/tests/TagLibSharp2.Tests/Core/ProbeFileSystem.cs b/tests/TagLibSharp2.Tests/Core/ProbeFileSystem.cs new file mode 100644 index 00000000..16e7329f --- /dev/null +++ b/tests/TagLibSharp2.Tests/Core/ProbeFileSystem.cs @@ -0,0 +1,206 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using TagLibSharp2.Core; + +namespace TagLibSharp2.Tests.Core; + +/// +/// In-memory file system for a path save. An unseekable open, a length fault, or open tracking wraps the +/// source. A create counts the call and records the largest write. +/// +sealed class ProbeFileSystem : IFileSystem +{ + public MockFileSystem Store { get; } = new (); + + public bool Seekable { get; set; } = true; + + public string? OpenReadFault { get; set; } + + public string? LengthFault { get; set; } + + public bool ArmOpenTracking { get; set; } + + public TrackedStream? SaveOpen { get; private set; } + + public CancellationTokenSource? CancelOnWrite { get; set; } + + public int CreateCalls { get; private set; } + + public int MaxWrite { get; private set; } + + public byte[] Original { get; private set; } = []; + + public void Add (string path, byte[] data) + { + Original = data.ToArray (); + Store.AddFile (path, data); + } + + public bool FileExists (string path) => Store.FileExists (path); + + public Stream OpenRead (string path) + { + if (OpenReadFault == "denied") + throw new UnauthorizedAccessException ("Access denied"); + if (OpenReadFault == "io") + throw new IOException ("disk fault"); + + var stream = Store.OpenRead (path); + if (Seekable && LengthFault is null && !ArmOpenTracking) + return stream; + + var tracked = new TrackedStream (stream, Seekable, LengthFault); + if (ArmOpenTracking) + SaveOpen = tracked; + return tracked; + } + + public Stream OpenReadWrite (string path) => Store.OpenReadWrite (path); + + public Stream Create (string path) + { + CreateCalls++; + return new RecordingStream (Store.Create (path), this); + } + + public byte[] ReadAllBytes (string path) => Store.ReadAllBytes (path); + + public Task ReadAllBytesAsync (string path, CancellationToken cancellationToken = default) => + Store.ReadAllBytesAsync (path, cancellationToken); + + public void WriteAllBytes (string path, ReadOnlySpan data) => Store.WriteAllBytes (path, data); + + public Task WriteAllBytesAsync ( + string path, + ReadOnlyMemory data, + CancellationToken cancellationToken = default) => + Store.WriteAllBytesAsync (path, data, cancellationToken); + + public void Delete (string path) => Store.Delete (path); + + public void Move (string sourcePath, string destinationPath) => Store.Move (sourcePath, destinationPath); + + public string? GetDirectoryName (string path) => Store.GetDirectoryName (path); + + public string GetFileName (string path) => Store.GetFileName (path); + + public string CombinePath (string path1, string path2) => Store.CombinePath (path1, path2); + + internal void NoteWrite (int count) + { + if (count > MaxWrite) + MaxWrite = count; + CancelOnWrite?.Cancel (); + } + + public sealed class TrackedStream : Stream + { + readonly Stream _inner; + readonly bool _seekable; + readonly string? _lengthFault; + + public TrackedStream (Stream inner, bool seekable, string? lengthFault) + { + _inner = inner; + _seekable = seekable; + _lengthFault = lengthFault; + } + + public bool WasDisposed { get; private set; } + + public override bool CanRead => _inner.CanRead; + + public override bool CanSeek => _seekable; + + public override bool CanWrite => false; + + public override long Length { + get { + if (_lengthFault == "io") + throw new IOException ("disk fault"); + if (_lengthFault == "denied") + throw new UnauthorizedAccessException ("Access denied"); + if (!_seekable) + throw new NotSupportedException (); + return _inner.Length; + } + } + + public override long Position { + get => _seekable ? _inner.Position : throw new NotSupportedException (); + set { + if (!_seekable) + throw new NotSupportedException (); + _inner.Position = value; + } + } + + public override void Flush () => _inner.Flush (); + + public override int Read (byte[] buffer, int offset, int count) => _inner.Read (buffer, offset, count); + + public override long Seek (long offset, SeekOrigin origin) => + _seekable ? _inner.Seek (offset, origin) : throw new NotSupportedException (); + + public override void SetLength (long value) => throw new NotSupportedException (); + + public override void Write (byte[] buffer, int offset, int count) => throw new NotSupportedException (); + + protected override void Dispose (bool disposing) + { + if (disposing) { + WasDisposed = true; + _inner.Dispose (); + } + + base.Dispose (disposing); + } + } + + sealed class RecordingStream : Stream + { + readonly Stream _inner; + readonly ProbeFileSystem _owner; + + public RecordingStream (Stream inner, ProbeFileSystem owner) + { + _inner = inner; + _owner = owner; + } + + public override bool CanRead => _inner.CanRead; + + public override bool CanSeek => _inner.CanSeek; + + public override bool CanWrite => _inner.CanWrite; + + public override long Length => _inner.Length; + + public override long Position { + get => _inner.Position; + set => _inner.Position = value; + } + + public override void Flush () => _inner.Flush (); + + public override int Read (byte[] buffer, int offset, int count) => _inner.Read (buffer, offset, count); + + public override long Seek (long offset, SeekOrigin origin) => _inner.Seek (offset, origin); + + public override void SetLength (long value) => _inner.SetLength (value); + + public override void Write (byte[] buffer, int offset, int count) + { + _owner.NoteWrite (count); + _inner.Write (buffer, offset, count); + } + + protected override void Dispose (bool disposing) + { + if (disposing) + _inner.Dispose (); + base.Dispose (disposing); + } + } +} diff --git a/tests/TagLibSharp2.Tests/Core/TagTypeClassification.cs b/tests/TagLibSharp2.Tests/Core/TagTypeClassification.cs index 244872a0..da7e230f 100644 --- a/tests/TagLibSharp2.Tests/Core/TagTypeClassification.cs +++ b/tests/TagLibSharp2.Tests/Core/TagTypeClassification.cs @@ -19,8 +19,8 @@ static class TagTypeClassification /// internal static readonly string[] LeafTagTypeNames = [ "TagLibSharp2.Ape.ApeTag", "TagLibSharp2.Asf.AsfTag", "TagLibSharp2.Audible.AudibleTag", "TagLibSharp2.Id3.Id3v1Tag", - "TagLibSharp2.Id3.Id3v2.Id3v2Tag", "TagLibSharp2.Matroska.MatroskaTag", "TagLibSharp2.Mp4.Mp4Tag", "TagLibSharp2.Riff.RiffInfoTag", - "TagLibSharp2.Xiph.VorbisComment", + "TagLibSharp2.Id3.Id3v2.Id3v2Tag", "TagLibSharp2.Image.ImageTag", "TagLibSharp2.Matroska.MatroskaTag", "TagLibSharp2.Mp4.Mp4Tag", + "TagLibSharp2.Riff.RiffInfoTag", "TagLibSharp2.Xiph.VorbisComment", ]; /// diff --git a/tests/TagLibSharp2.Tests/Image/AppleHeadroomTests.cs b/tests/TagLibSharp2.Tests/Image/AppleHeadroomTests.cs new file mode 100644 index 00000000..ac3f568e --- /dev/null +++ b/tests/TagLibSharp2.Tests/Image/AppleHeadroomTests.cs @@ -0,0 +1,719 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Text; +using System.Xml.Linq; +using TagLibSharp2.Core; +using TagLibSharp2.Image; +using TagLibSharp2.Image.Exif; +using TagLibSharp2.Image.Tiff; +using TagLibSharp2.Tests.Core; +using static TagLibSharp2.Tests.Image.GainMapTestData; +using static TagLibSharp2.Tests.Image.ImageTestBuilder; + +namespace TagLibSharp2.Tests.Image; + +/// Clear of a version-65536 Apple gain map keeps the maker-note headroom ImageIO applies, chosen as ImageIO chooses it, in linear work. +[TestClass] +[TestCategory ("Unit")] +public class AppleHeadroomTests +{ + // Which occurrence wins, at every level the headroom passes through: IFD0's Exif IFD pointer (0x8769), the + // Exif IFD's MakerNote (0x927C) and the maker note's 0x0021 and 0x0030. TIFF 6.0 does not say, so the rule is + // ImageIO's, measured on m1-real variants (one level changed at a time; ImageIO HDR max: the real values + // render 4.0031, the other valid ones 2.9742, SDR is 0.9996, "none" is no HDR image at all): + // level kind ImageIO libultrahdr + // 0x8769 LONG / IFD type, count 1 usable, later overrides reads the first + // other type, count 0 or 2 skipped skipped + // table outside the data skipped refuses the file + // later Exif IFD w/o maker note keeps the earlier values - + // 0x927C UNDEFINED, > 4 bytes, inside usable, later overrides reads the first + // other type, count 0, <= 4, skipped - + // outside the data + // Apple header not exact, or skipped - + // its table does not fit + // not an Apple maker note usable: wins with nothing refuses + // 0x21/0x30 SRATIONAL, count >= 1, every usable, the last wins the last (out-of-note: refuses) + // value inside the note (any + // offset: header, table, end) + // other type, count 0, outside skipped - + // winner with count 2 none reads the first value + // So: every occurrence that cannot be used is skipped, the last usable one wins, and the headroom is kept only + // when both winning tags have count 1. Each row below is one level x one pattern x one kind of bad occurrence. + public enum Use { Skipped, Usable, Nothing } + + // iPhone 15 and later write HDRGainMapVersion 131072 with the headroom in the gain map's own XMP; ImageIO and + // libultrahdr scale the gain map by it, so Clear keeps it. + [TestMethod] + public void Clear_KeepsTheAppleHeadroom_OfAVersion131072GainMap () + { + var packet = AppleGainMapXmp.Replace ("65536", + "1310723.500000", StringComparison.Ordinal); + var input = MpfJpeg (Concat (GpsExif (), JpegXmpBytes (XmpPacket (Seq ("dc:creator", "Jane Private")))), [], Jpeg (GpsExif (), JpegXmpBytes (packet)), out _); + var file = Open (input, "a.jpg"); + file.Tag!.Clear (); + + var apple = XDocument.Parse (Packets (file.Render ().ToArray ()).Single ().TrimStart ('\uFEFF')).Descendants (Rdf + "Description").Single (); + + Assert.AreEqual ("131072", apple.Element (AppleGainMap + "HDRGainMapVersion")?.Value); + Assert.AreEqual ("3.500000", apple.Element (AppleGainMap + "HDRGainMapHeadroom")?.Value); + } + + // Tags 0x0021 and 0x0030 of an Apple maker note (exiftool's HDRHeadroom and HDRGain), each one SRATIONAL. + static readonly (int Tag, int Type, int Count, byte[] Value) Headroom = (0x0021, 10, 1, SRational (6, 5)); + static readonly (int Tag, int Type, int Count, byte[] Value) Gain = (0x0030, 10, 1, SRational (1, 2)); + + // Tags an iPhone writes next to them; the ASCII one stands in for anything personal in the maker note. + static readonly (int Tag, int Type, int Count, byte[] Value) MakerNoteInteger = (0x0001, 9, 1, [0, 0, 0, 14]); + static readonly (int Tag, int Type, int Count, byte[] Value) MakerNoteText = (0x000B, 2, 17, Concat ("Jane Private 4711"u8.ToArray (), [0])); + + static byte[] AppleV1 (byte[] primaryExif, string? gainMapXmp = null) => + MpfJpeg ( + Concat (primaryExif, GpsExif (), JpegXmpBytes (XmpPacket (Seq ("dc:creator", "Jane Private")))), + [], + Jpeg (JpegExif (AppleExifTiff (AppleMakerNote ([Headroom, Gain]))), JpegXmpBytes (gainMapXmp ?? AppleGainMapXmp)), + out _); + + // The Exif Clear writes for a version-65536 Apple gain map: IFD0 -> Exif IFD -> MakerNote, and in the maker + // note only tags 0x0021 and 0x0030 with their stored values, offsets counted from the maker note. + static byte[] ExpectedHeadroomExif (byte[] headroom, byte[] gain) + { + var note = AppleMakerNote ([(0x0021, 10, 1, headroom), (0x0030, 10, 1, gain)]); + var tiff = new byte[44]; + "MM\0*"u8.CopyTo (tiff); + System.Buffers.Binary.BinaryPrimitives.WriteInt32BigEndian (tiff.AsSpan (4), 8); + System.Buffers.Binary.BinaryPrimitives.WriteUInt16BigEndian (tiff.AsSpan (8), 1); + System.Buffers.Binary.BinaryPrimitives.WriteUInt16BigEndian (tiff.AsSpan (10), 0x8769); + System.Buffers.Binary.BinaryPrimitives.WriteUInt16BigEndian (tiff.AsSpan (12), 4); + System.Buffers.Binary.BinaryPrimitives.WriteInt32BigEndian (tiff.AsSpan (14), 1); + System.Buffers.Binary.BinaryPrimitives.WriteInt32BigEndian (tiff.AsSpan (18), 26); + System.Buffers.Binary.BinaryPrimitives.WriteUInt16BigEndian (tiff.AsSpan (26), 1); + System.Buffers.Binary.BinaryPrimitives.WriteUInt16BigEndian (tiff.AsSpan (28), 0x927C); + System.Buffers.Binary.BinaryPrimitives.WriteUInt16BigEndian (tiff.AsSpan (30), 7); + System.Buffers.Binary.BinaryPrimitives.WriteInt32BigEndian (tiff.AsSpan (32), note.Length); + System.Buffers.Binary.BinaryPrimitives.WriteInt32BigEndian (tiff.AsSpan (36), 44); + return JpegExif (Concat (tiff, note)); + } + + static List ExifSegments (byte[] jpeg) + { + var found = new List (); + var at = 0; + while (jpeg.AsSpan (at).IndexOf ("Exif\0\0"u8) is var next and >= 0) { + at += next; + found.Add (at - 4); + at++; + } + + return found; + } + + // iPhone 12-14 write HDRGainMapVersion 65536 with no headroom in the gain map's XMP. ImageIO and libultrahdr + // take it from the primary's Apple maker note, tags 0x0021 and 0x0030 (Apple, "Applying Apple HDR effect to + // your photos"), so Clear keeps those two values in a new Exif and nothing else of it: not IFD0, GPS or the + // other Exif tags, not the other maker-note tags, not a second Exif segment, not the gain map's own Exif. + [TestMethod] + [DataRow ("tags in order")] + [DataRow ("tags out of order")] + [DataRow ("little-endian TIFF")] + public void Clear_OfAVersion65536AppleGainMap_KeepsOnlyTheMakerNoteHeadroom (string order) + { + var entries = order == "tags out of order" ? new[] { Gain, MakerNoteText, Headroom, MakerNoteInteger } : [MakerNoteInteger, MakerNoteText, Headroom, Gain]; + // Readers use the first Exif; a second one with other values is dropped with the rest. + var second = JpegExif (AppleExifTiff (AppleMakerNote ([(0x0021, 10, 1, SRational (9, 1)), (0x0030, 10, 1, SRational (9, 1))]))); + var file = Open (AppleV1 (Concat (JpegExif (AppleExifTiff (AppleMakerNote (entries), littleEndian: order == "little-endian TIFF")), second)), "a.jpg"); + file.Tag!.Clear (); + + var output = file.Render ().ToArray (); + + var segments = ExifSegments (output); + Assert.AreEqual (1, segments.Count, "one Exif, in the primary"); + var expected = ExpectedHeadroomExif (Headroom.Value, Gain.Value); + Assert.AreEqual (114, expected.Length); + Assert.IsTrue (segments[0] < MpfSecondImage (output)); + CollectionAssert.AreEqual (expected, output[segments[0]..(segments[0] + expected.Length)]); + foreach (var personal in new[] { "Jane", "iPhone", "2024:05", "Canon" }) + Assert.IsTrue (output.AsSpan ().IndexOf (Encoding.ASCII.GetBytes (personal)) < 0, $"'{personal}' survived Clear"); + StringAssert.Contains (Packets (output).Single (), "65536"); + Assert.AreEqual (output.Length - MpfSecondImage (output), MpfEntries (output)[1].Size); + Assert.IsNotNull (Open (output, "a.jpg").ImageProperties); + } + + // Without a valid headroom in the maker note there is nothing to keep, and none of the Exif survives. + public static IEnumerable UnkeptHeadroom () + { + static byte[] Note (params (int Tag, int Type, int Count, byte[] Value)[] entries) => AppleMakerNote (entries); + static byte[] Patch (byte[] note, int entry, int field, int value) + { + var copy = (byte[])note.Clone (); + var at = AppleMakerNoteHeader.Length + 2 + (12 * entry) + field; + if (field == 2) + System.Buffers.Binary.BinaryPrimitives.WriteUInt16BigEndian (copy.AsSpan (at), (ushort)value); + else + System.Buffers.Binary.BinaryPrimitives.WriteInt32BigEndian (copy.AsSpan (at), value); + return copy; + } + + static byte[] Count (byte[] note, int count) + { + var copy = (byte[])note.Clone (); + System.Buffers.Binary.BinaryPrimitives.WriteUInt16BigEndian (copy.AsSpan (AppleMakerNoteHeader.Length), (ushort)count); + return copy; + } + + static byte[] Magic (byte[] tiff, byte first, byte second) + { + tiff[2] = first; + tiff[3] = second; + return tiff; + } + + static byte[] Ifd0Count (byte[] tiff, int count) + { + System.Buffers.Binary.BinaryPrimitives.WriteUInt16BigEndian (tiff.AsSpan (8), (ushort)count); + return tiff; + } + + var valid = Note (Headroom, Gain); + yield return ["no 0x0021", JpegExif (AppleExifTiff (Note (MakerNoteText, Gain)))]; + yield return ["no 0x0030", JpegExif (AppleExifTiff (Note (MakerNoteText, Headroom)))]; + yield return ["little-endian header", JpegExif (AppleExifTiff (AppleMakerNote ([Headroom, Gain], "Apple iOS\0\0\u0001II"u8.ToArray ())))]; + yield return ["another maker's header", JpegExif (AppleExifTiff (AppleMakerNote ([Headroom, Gain], "Nikon\0\u0002\u0010\0\0MM\0\0"u8.ToArray ())))]; + yield return ["maker note shorter than its table", JpegExif (AppleExifTiff (valid, makerNoteCount: AppleMakerNoteHeader.Length + 2 + 12 + 6))]; + yield return ["maker note shorter than its header", JpegExif (AppleExifTiff (valid, makerNoteCount: 15))]; + yield return ["maker note past the Exif", JpegExif (AppleExifTiff (valid, makerNoteCount: 70_000))]; + yield return ["maker note not UNDEFINED", JpegExif (AppleExifTiff (valid, makerNoteType: 2))]; + yield return ["0x0021 value past the maker note", JpegExif (AppleExifTiff (Patch (valid, 0, 8, valid.Length - 4)))]; + yield return ["0x0021 RATIONAL", JpegExif (AppleExifTiff (Patch (valid, 0, 2, 5)))]; + yield return ["0x0030 FLOAT", JpegExif (AppleExifTiff (Patch (valid, 1, 2, 11)))]; + yield return ["0x0021 count 2", JpegExif (AppleExifTiff (Patch (valid, 0, 4, 2)))]; + yield return ["0x0030 count 0", JpegExif (AppleExifTiff (Patch (valid, 1, 4, 0)))]; + yield return ["entry count past the maker note", JpegExif (AppleExifTiff (Count (Note (MakerNoteInteger), 50)))]; + yield return ["Exif IFD past the data", JpegExif (AppleExifTiff (valid, exifIfd: 0x7FFF_0000))]; + // The last two bytes of the TIFF (the gain's denominator, 2) read as the Exif IFD's entry count. + yield return ["Exif IFD table past the data", JpegExif (AppleExifTiff (valid, exifIfd: AppleExifTiff (valid).Length - 2))]; + yield return ["IFD0 table past the data", JpegExif (Ifd0Count (AppleExifTiff (valid), 0x0FFF))]; + yield return ["no TIFF header", JpegSegment (0xE1, Concat ("Exif\0\0XX\0*"u8.ToArray (), valid))]; + // ImageIO ignores an Exif whose TIFF magic is not 42, so it never applied this headroom. + yield return ["big-endian magic 43", JpegExif (Magic (AppleExifTiff (valid), 0x00, 0x2B))]; + yield return ["little-endian magic 43", JpegExif (Magic (AppleExifTiff (valid, littleEndian: true), 0x2B, 0x00))]; + // The last usable 0x0021 has count 2: ImageIO then renders no HDR image at all. + yield return ["0x0021 twice, the last of count 2", JpegExif (AppleExifTiff (Patch (Note (Headroom, (0x0021, 10, 1, SRational (7, 3)), Gain), 1, 4, 2)))]; + } + + [TestMethod] + [DynamicData (nameof (UnkeptHeadroom))] + public void Clear_OfAVersion65536AppleGainMap_WithoutAValidMakerNoteHeadroom_KeepsNoExif (string shape, byte[] primaryExif) + { + var file = Open (AppleV1 (primaryExif), "a.jpg"); + file.Tag!.Clear (); + + var save = file.SaveToFile ("/a.jpg", new MockFileSystem ()); + Assert.IsTrue (save.IsSuccess, $"{shape}: {save.Error}"); + var output = file.Render ().ToArray (); + + Assert.AreEqual (0, ExifSegments (output).Count, shape); + StringAssert.Contains (Packets (output).Single (), "65536", shape); + } + + // Only a version-65536 Apple gain map reads its headroom from the maker note. An iPhone 15 gain map carries it + // in its own XMP, Ultra HDR in hdrgm, and a single image has no gain map: none of them keeps any Exif. + [TestMethod] + [DataRow ("version 131072 with HDRGainMapHeadroom")] + [DataRow ("Ultra HDR")] + [DataRow ("Apple properties without HDRGainMapVersion")] + [DataRow ("no gain map")] + [DataRow ("a version-65536 packet that outgrows its segment")] + public void Clear_KeepsNoExif_UnlessAVersion65536AppleGainMapNeedsTheMakerNote (string kind) + { + var exif = JpegExif (AppleExifTiff (AppleMakerNote ([MakerNoteText, Headroom, Gain]))); + var input = kind switch { + "version 131072 with HDRGainMapHeadroom" => AppleV1 (exif, AppleGainMapXmp.Replace ("65536", + "1310723.5", StringComparison.Ordinal)), + "Ultra HDR" => AppleV1 (exif, UltraHdrGainMap), + "a version-65536 packet that outgrows its segment" => AppleV1 (exif, OutgrowingPacket ("xmlns:G='http://ns.apple.com/HDRGainMap/1.0/' G:HDRGainMapVersion='65536'")), + "Apple properties without HDRGainMapVersion" => AppleV1 (exif, AppleGainMapXmp.Replace ("65536", "", StringComparison.Ordinal)), + _ => Jpeg (exif, JpegXmpBytes (AppleGainMapXmp)) + }; + var file = Open (input, "a.jpg"); + file.Tag!.Clear (); + + var output = file.Render ().ToArray (); + + Assert.AreEqual (0, ExifSegments (output).Count, kind); + Assert.IsTrue (output.AsSpan ().IndexOf ("Apple iOS"u8) < 0, kind); + } + + sealed record Kind (string Name, Use Use, (int Tag, int Type, long Count, long Value) Entry); + + // Real (6/5, 1/2) and alternative (7/3, 5/4) values; the real maker note holds both pairs, at V and V + 8, + // V + 16 and V + 24. + static readonly byte[] Real21 = SRational (6, 5), Alt21 = SRational (7, 3), Real30 = SRational (1, 2), Alt30 = SRational (5, 4); + + // Symbolic offsets, resolved when the TIFF is laid out. + const long RealIfd = -1, AltIfd = -2, BareIfd = -3, ForeignIfd = -4, RealNote = -5, AltNote = -6, BadHeaderNote = -7, Foreign = -8, RealNoteLength = -9, TablePast = -10; + + static byte[] MatrixExif (List<(int Tag, int Type, long Count, long Value)> ifd0, List<(int Tag, int Type, long Count, long Value)> exif, List<(int Tag, int Type, long Count, long Value)> note) + { + var v = 16 + (12 * note.Count) + 4; + var noteBytes = new byte[v + 32]; + AppleMakerNoteHeader.CopyTo (noteBytes, 0); + System.Buffers.Binary.BinaryPrimitives.WriteUInt16BigEndian (noteBytes.AsSpan (14), (ushort)note.Count); + for (var n = 0; n < note.Count; n++) + Entry (noteBytes, 16 + (12 * n), note[n].Tag, note[n].Type, note[n].Count, note[n].Value < 0 ? v + ((-note[n].Value - 100) * 8) : note[n].Value); + Concat (Real21, Alt21, Real30, Alt30).CopyTo (noteBytes, v); + + var alt = AppleMakerNote ([(0x0021, 10, 1, Alt21), (0x0030, 10, 1, Alt30)]); + var badHeader = (byte[])alt.Clone (); + badHeader[12] = 2; + // Another maker's note; read as Apple's it would claim 65,535 entries. + var foreign = Concat ("Nikon\0\u0002\u0010\0\0MM\0*"u8.ToArray (), [0xFF, 0xFF], new byte[42], [0x0F, 0xFF]); + var ifd0At = 8; + var realIfd = ifd0At + 2 + (12 * ifd0.Count) + 4; + var altIfd = realIfd + 2 + (12 * exif.Count) + 4; + var bareIfd = altIfd + 18; + var foreignIfd = bareIfd + 18; + var realNote = foreignIfd + 18; + var altNote = realNote + noteBytes.Length; + var badHeaderNote = altNote + alt.Length; + var foreignAt = badHeaderNote + badHeader.Length; + var length = foreignAt + foreign.Length; + long Resolve (long value) => value switch { + RealIfd => realIfd, + AltIfd => altIfd, + BareIfd => bareIfd, + ForeignIfd => foreignIfd, + RealNote => realNote, + AltNote => altNote, + BadHeaderNote => badHeaderNote, + Foreign => foreignAt, + RealNoteLength => noteBytes.Length, + TablePast => length - 2, + _ => value + }; + var tiff = new byte[length]; + "MM\0*"u8.CopyTo (tiff); + System.Buffers.Binary.BinaryPrimitives.WriteInt32BigEndian (tiff.AsSpan (4), ifd0At); + Table (tiff, ifd0At, ifd0); + Table (tiff, realIfd, exif); + Table (tiff, altIfd, [(0x927C, 7, alt.Length, AltNote)]); + Table (tiff, bareIfd, [(0x9003, 7, 4, 0x31323334)]); + Table (tiff, foreignIfd, [(0x927C, 7, foreign.Length, Foreign)]); + noteBytes.CopyTo (tiff, realNote); + alt.CopyTo (tiff, altNote); + badHeader.CopyTo (tiff, badHeaderNote); + foreign.CopyTo (tiff, foreignAt); + return tiff; + + void Table (byte[] data, int at, List<(int Tag, int Type, long Count, long Value)> entries) + { + System.Buffers.Binary.BinaryPrimitives.WriteUInt16BigEndian (data.AsSpan (at), (ushort)entries.Count); + for (var n = 0; n < entries.Count; n++) + Entry (data, at + 2 + (12 * n), entries[n].Tag, entries[n].Type, Resolve (entries[n].Count), Resolve (entries[n].Value)); + } + + static void Entry (byte[] data, int at, int tag, int type, long count, long value) + { + System.Buffers.Binary.BinaryPrimitives.WriteUInt16BigEndian (data.AsSpan (at), (ushort)tag); + System.Buffers.Binary.BinaryPrimitives.WriteUInt16BigEndian (data.AsSpan (at + 2), (ushort)type); + System.Buffers.Binary.BinaryPrimitives.WriteUInt32BigEndian (data.AsSpan (at + 4), (uint)count); + System.Buffers.Binary.BinaryPrimitives.WriteUInt32BigEndian (data.AsSpan (at + 8), (uint)value); + } + } + + // A maker-note value at the real note's value area: -100 is V (real 0x21), -101 V + 8, -102 V + 16, -103 V + 24. + const long V21 = -100, VAlt21 = -101, V30 = -102, VAlt30 = -103; + + static readonly (int Tag, int Type, long Count, long Value) NoEntry = (0, 0, 0, 0); + + public static IEnumerable OccurrenceMatrix () + { + var levels = new (string Level, (int Tag, int Type, long Count, long Value) Valid, (int Tag, int Type, long Count, long Value) Other, Kind[] Kinds)[] { + ("0x8769", (0x8769, 4, 1, RealIfd), (0x8769, 13, 1, AltIfd), [ + new ("UNDEFINED", Use.Skipped, (0x8769, 7, 4, AltIfd)), + new ("SHORT", Use.Skipped, (0x8769, 3, 1, AltIfd)), + new ("count 0", Use.Skipped, (0x8769, 4, 0, AltIfd)), + new ("count 2", Use.Skipped, (0x8769, 4, 2, AltIfd)), + new ("past the data", Use.Skipped, (0x8769, 4, 1, 0xFFFFF0)), + new ("inside the header", Use.Skipped, (0x8769, 4, 1, 4)), + new ("table past the data", Use.Skipped, (0x8769, 4, 1, TablePast)), + new ("an Exif IFD without a maker note", Use.Skipped, (0x8769, 4, 1, BareIfd)), + new ("an Exif IFD with a foreign maker note", Use.Skipped, (0x8769, 4, 1, ForeignIfd))]), + ("0x927C", (0x927C, 7, RealNoteLength, RealNote), (0x927C, 7, 60, AltNote), [ + new ("ASCII", Use.Skipped, (0x927C, 2, 60, AltNote)), + new ("count 0", Use.Skipped, (0x927C, 7, 0, AltNote)), + new ("4 bytes, held in the entry", Use.Skipped, (0x927C, 7, 4, AltNote)), + new ("past the data", Use.Skipped, (0x927C, 7, 60, 0xFFFFF0)), + new ("Apple header of version 2", Use.Skipped, (0x927C, 7, 60, BadHeaderNote)), + new ("Apple table past its bytes", Use.Skipped, (0x927C, 7, 16, AltNote)), + new ("not an Apple maker note", Use.Nothing, (0x927C, 7, 60, Foreign)), + new ("8 bytes of an Apple maker note", Use.Nothing, (0x927C, 7, 8, AltNote))]), + ("0x0021", (0x0021, 10, 1, V21), (0x0021, 10, 1, VAlt21), TagKinds (0x0021)), + ("0x0030", (0x0030, 10, 1, V30), (0x0030, 10, 1, VAlt30), TagKinds (0x0030)), + }; + foreach (var (level, valid, other, kinds) in levels) { + yield return [level, "valid only", "-", Use.Skipped, valid, other, NoEntry]; + yield return [level, "valid, then another valid", "-", Use.Skipped, valid, other, NoEntry]; + foreach (var kind in kinds) { + foreach (var pattern in new[] { "bad, then valid", "valid, then bad", "bad only" }) + yield return [level, pattern, kind.Name, kind.Use, valid, other, kind.Entry]; + } + } + + static Kind[] TagKinds (int tag) => [ + new ("RATIONAL", Use.Skipped, (tag, 5, 1, VAlt21)), + new ("count 0", Use.Skipped, (tag, 10, 0, VAlt21)), + new ("count 2", Use.Nothing, (tag, 10, 2, V21)), + new ("past the maker note", Use.Skipped, (tag, 10, 1, 0x7FFFFFF0)), + new ("one byte past the maker note", Use.Skipped, (tag, 10, 1, RealNoteEnd - 7)), + new ("the maker note's last 8 bytes", Use.Usable, (tag, 10, 1, RealNoteEnd - 8)), + new ("in the maker-note header", Use.Usable, (tag, 10, 1, 0)), + new ("in the maker-note entry table", Use.Usable, (tag, 10, 1, 16))]; + } + + // The real note's length, resolved per note (see NoteEnd). + const long RealNoteEnd = 1_000_000; + + [TestMethod] + [DynamicData (nameof (OccurrenceMatrix))] + public void Clear_KeepsTheHeadroomImageIOApplies_WhicheverOccurrenceWins (string level, string pattern, string kind, Use use, (int Tag, int Type, long Count, long Value) valid, (int Tag, int Type, long Count, long Value) other, (int Tag, int Type, long Count, long Value) bad) + { + var occurrences = pattern switch { + "valid only" => [valid], + "valid, then another valid" => [valid, other], + "bad, then valid" => [bad, valid], + "valid, then bad" => new[] { valid, bad }, + _ => [bad] + }; + var ifd0 = new List<(int Tag, int Type, long Count, long Value)> { (0x010F, 2, 4, 0x41424300) }; + var exif = new List<(int Tag, int Type, long Count, long Value)> { (0x9003, 7, 4, 0x31323334) }; + var note = new List<(int Tag, int Type, long Count, long Value)> { (0x0001, 9, 1, 14) }; + var target = level switch { "0x8769" => ifd0, "0x927C" => exif, _ => note }; + if (level != "0x8769") + ifd0.Add ((0x8769, 4, 1, RealIfd)); + if (level != "0x927C") + exif.Add ((0x927C, 7, RealNoteLength, RealNote)); + if (level != "0x0021") + note.Add ((0x0021, 10, 1, V21)); + if (level != "0x0030") + note.Add ((0x0030, 10, 1, V30)); + var noteLength = 16 + (12 * (note.Count + (level is "0x0021" or "0x0030" ? occurrences.Length : 0))) + 4 + 32; + foreach (var o in occurrences) + target.Add (o.Value == RealNoteEnd - 7 || o.Value == RealNoteEnd - 8 ? (o.Tag, o.Type, o.Count, noteLength - (RealNoteEnd - o.Value)) : o); + var tiff = MatrixExif (ifd0, exif, note); + + var file = Open (AppleV1 (JpegExif (tiff)), "a.jpg"); + file.Tag!.Clear (); + var output = file.Render ().ToArray (); + var segments = ExifSegments (output); + var row = $"{level} / {pattern} / {kind}"; + + // The winner is the last occurrence that is not skipped; none, or one that brings nothing, keeps nothing. + var usable = occurrences.Where (o => !(o.Equals (bad) && use == Use.Skipped)).ToList (); + var winner = usable.Count > 0 ? usable[^1] : bad; + if (usable.Count == 0 || (winner.Equals (bad) && use == Use.Nothing)) { + Assert.AreEqual (0, segments.Count, row); + return; + } + + var (headroom, gain) = (Real21, Real30); + if (winner.Equals (other)) + (headroom, gain) = level switch { "0x0021" => (Alt21, Real30), "0x0030" => (Real21, Alt30), _ => (Alt21, Alt30) }; + if (winner.Equals (bad)) { + // A usable entry at an odd offset: the kept bytes are the 8 there, as stored. + var noteAt = tiff.AsSpan ().IndexOf ("Apple iOS\0"u8); + var offset = (int)target.Last ().Value; + var bytes = tiff[(noteAt + offset)..(noteAt + offset + 8)]; + (headroom, gain) = level == "0x0021" ? (bytes, Real30) : (Real21, bytes); + } + + Assert.AreEqual (1, segments.Count, row); + var expected = ExpectedHeadroomExif (headroom, gain); + CollectionAssert.AreEqual (expected, output[segments[0]..(segments[0] + expected.Length)], row); + } + + // Each distinct Exif IFD is walked once however many IFD0 entries point at it, so the work stays linear in the + // entries (and IFD tables that overlap past the data keep nothing rather than being walked again and again). + [TestMethod] + public void Clear_ExifIfdPointerWalk_IsLinearInTheEntries () + { + static long Steps (int n) + { + var ifd0 = Enumerable.Range (0, n).Select (_ => (Tag: 0x8769, Type: 4, Count: 1L, Value: RealIfd)).ToList (); + var exif = Enumerable.Range (0, n).Select (k => (Tag: 0x9000 + k, Type: 7, Count: 4L, Value: 0L)).ToList (); + exif.Add ((0x927C, 7, RealNoteLength, RealNote)); + var file = Open (AppleV1 (JpegExif (MatrixExif (ifd0, exif, [(0x0021, 10, 1, V21), (0x0030, 10, 1, V30)]))), "a.jpg"); + file.Tag!.Clear (); + IfdSteps.Count = 0; + var output = file.Render ().ToArray (); + Assert.AreEqual (1, ExifSegments (output).Count, $"N={n}: the headroom is kept"); + return IfdSteps.Count; + } + + var small = Steps (300); + var large = Steps (2400); + Assert.IsTrue (large >= 3L * 2400, $"{large} steps: every IFD0 entry, pointer kept and Exif IFD entry is counted"); + Assert.IsTrue (large <= 4L * 2400, $"{large} steps for 2,400 pointers to one Exif IFD of 2,400 entries"); + Assert.IsTrue (large < 10 * small, $"8x the entries took {large / (double)small:F1}x the steps"); + } + + // Many pointers to one Exif IFD whose maker note lacks the tags, after an Exif IFD that has them: the shared + // Exif IFD is walked once, so the earlier values are still found (walking it again for each pointer would + // exceed the entries the data holds and keep nothing). + [TestMethod] + public void Clear_ManyPointersToOneExifIfd_WalkItOnce () + { + var ifd0 = new List<(int Tag, int Type, long Count, long Value)> { (0x8769, 4, 1, AltIfd) }; + ifd0.AddRange (Enumerable.Range (0, 200).Select (_ => (0x8769, 4, 1L, RealIfd))); + var exif = Enumerable.Range (0, 200).Select (k => (Tag: 0x9000 + k, Type: 7, Count: 4L, Value: 0L)).ToList (); + exif.Add ((0x927C, 7, RealNoteLength, RealNote)); + var file = Open (AppleV1 (JpegExif (MatrixExif (ifd0, exif, [(0x0001, 9, 1, 14)]))), "a.jpg"); + file.Tag!.Clear (); + + var output = file.Render ().ToArray (); + + var segments = ExifSegments (output); + Assert.AreEqual (1, segments.Count); + var expected = ExpectedHeadroomExif (Alt21, Alt30); + CollectionAssert.AreEqual (expected, output[segments[0]..(segments[0] + expected.Length)]); + } + + // Exif IFDs or maker notes that overlap, so that walking each would read the same bytes again and again, keep + // nothing once the entries walked exceed what the data holds. + [TestMethod] + [DataRow ("400 Exif IFDs two bytes apart")] + [DataRow ("300 Exif IFDs sharing one maker note without the tags")] + public void Clear_OverlappingExifIfdsOrMakerNotes_AreBoundedByTheData (string shape) + { + var ifd0 = new List<(int Tag, int Type, long Count, long Value)> (); + var exif = new List<(int Tag, int Type, long Count, long Value)> (); + var note = new List<(int Tag, int Type, long Count, long Value)> (); + byte[] tiff; + if (shape.StartsWith ("400", StringComparison.Ordinal)) { + // Every pointer lands in a run of 0x00 0xC8 bytes: each reads as a table of 200 entries. + ifd0.AddRange (Enumerable.Range (0, 400).Select (n => (0x8769, 4, 1L, 4820L + (2 * n)))); + tiff = MatrixExif (ifd0, exif, [(0x0021, 10, 1, V21), (0x0030, 10, 1, V30)]); + tiff = Concat (tiff[..4820], Enumerable.Repeat (new byte[] { 0x00, 0xC8 }, 2200).SelectMany (b => b).ToArray ()); + } else { + note.AddRange (Enumerable.Range (0, 2000).Select (k => (0x1000 + k, 9, 1L, 0L))); + exif.Add ((0x927C, 7, RealNoteLength, RealNote)); + ifd0.AddRange (Enumerable.Range (0, 301).Select (n => (0x8769, 4, 1L, n == 0 ? RealIfd : 0L))); + var head = MatrixExif (ifd0, exif, note); + + // 300 more Exif IFDs, each a copy of the real one's table, so each names the same maker note. + var realIfd = 8 + 2 + (12 * 301) + 4; + var table = head[realIfd..(realIfd + 18)]; + tiff = Concat (head, Enumerable.Repeat (table, 300).SelectMany (t => t).ToArray ()); + for (var n = 1; n <= 300; n++) + System.Buffers.Binary.BinaryPrimitives.WriteInt32BigEndian (tiff.AsSpan (8 + 2 + (12 * n) + 8), head.Length + (18 * (n - 1))); + } + + IfdSteps.Count = 0; + var kept = AppleHeadroom.Keep (tiff); + + Assert.IsNull (kept, shape); + Assert.IsTrue (IfdSteps.Count <= tiff.Length, $"{shape}: {IfdSteps.Count} steps for {tiff.Length} bytes"); + } + + // ImageIO reads an IFD0 or Exif IFD whose 4-byte next-IFD offset is missing or cut short (m1-real with + // either table last renders HDR, max 4.0031, as m1-real does), so Clear keeps the headroom from it. + [TestMethod] + [DataRow ("Exif IFD", 4)] + [DataRow ("Exif IFD", 2)] + [DataRow ("IFD0", 4)] + [DataRow ("IFD0", 2)] + public void Clear_KeepsTheHeadroom_WhenATableHasNoNextOffset (string last, int cut) + { + var note = AppleMakerNote ([MakerNoteText, Headroom, Gain]); + static byte[] Table (int tag, int type, int count, int value, bool next) + { + var table = new byte[2 + 12 + (next ? 4 : 0)]; + System.Buffers.Binary.BinaryPrimitives.WriteUInt16BigEndian (table, 1); + System.Buffers.Binary.BinaryPrimitives.WriteUInt16BigEndian (table.AsSpan (2), (ushort)tag); + System.Buffers.Binary.BinaryPrimitives.WriteUInt16BigEndian (table.AsSpan (4), (ushort)type); + System.Buffers.Binary.BinaryPrimitives.WriteInt32BigEndian (table.AsSpan (6), count); + System.Buffers.Binary.BinaryPrimitives.WriteInt32BigEndian (table.AsSpan (10), value); + return table; + } + + static byte[] Header (int ifd0) + { + var header = "MM\0*\0\0\0\0"u8.ToArray (); + System.Buffers.Binary.BinaryPrimitives.WriteInt32BigEndian (header.AsSpan (4), ifd0); + return header; + } + + var partial = new byte[4 - cut]; + byte[] tiff; + if (last == "Exif IFD") { + // Header, IFD0 at 8, the maker note at 26, the Exif IFD last. + var noteAt = 8 + 18; + var exifAt = noteAt + note.Length; + tiff = Concat (Header (8), Table (0x8769, 4, 1, exifAt, next: true), note, Table (0x927C, 7, note.Length, noteAt, next: false), partial); + } else { + // Header, the maker note at 8, the Exif IFD, IFD0 last. + var exifAt = 8 + note.Length; + var ifd0At = exifAt + 18; + tiff = Concat (Header (ifd0At), note, Table (0x927C, 7, note.Length, 8, next: true), Table (0x8769, 4, 1, exifAt, next: false), partial); + } + + var file = Open (AppleV1 (JpegExif (tiff)), "a.jpg"); + file.Tag!.Clear (); + + var output = file.Render ().ToArray (); + + var segments = ExifSegments (output); + Assert.AreEqual (1, segments.Count, $"{last}, {cut} bytes cut"); + var expected = ExpectedHeadroomExif (SRational (6, 5), SRational (1, 2)); + CollectionAssert.AreEqual (expected, output[segments[0]..(segments[0] + expected.Length)]); + } + + // The gain map need not be the last image the MPF index lists: any later image's packet decides. + [TestMethod] + [DataRow ("gain map before another image")] + [DataRow ("gain map after another image")] + public void Clear_KeepsTheMakerNoteHeadroom_WhereverTheGainMapIsInTheIndex (string order) + { + var gainMap = Jpeg (JpegXmpBytes (AppleGainMapXmp)); + var other = Jpeg (JpegSegment (0xFE, "depth"u8.ToArray ())); + var primary = Concat (JpegExif (AppleExifTiff (AppleMakerNote ([MakerNoteText, Headroom, Gain]))), JpegXmpBytes (XmpPacket (Seq ("dc:creator", "Jane Private")))); + var input = order == "gain map before another image" ? MpfJpegMany (primary, [], gainMap, other) : MpfJpegMany (primary, [], other, gainMap); + var file = Open (input, "a.jpg"); + file.Tag!.Clear (); + + var output = file.Render ().ToArray (); + + var segments = ExifSegments (output); + Assert.AreEqual (1, segments.Count, order); + var expected = ExpectedHeadroomExif (Headroom.Value, Gain.Value); + CollectionAssert.AreEqual (expected, output[segments[0]..(segments[0] + expected.Length)], order); + } + + // The maker-note walk visits each entry once (counted in IfdSteps.Count), so the work Clear does is + // linear in the entries a hostile maker note declares. + [TestMethod] + public void Clear_MakerNoteHeadroomWalk_IsLinearInTheEntries () + { + static long Steps (int n) + { + var entries = Enumerable.Range (0, n).Select (k => (0x1000 + k, 9, 1, new byte[] { 0, 0, 0, 1 })).Concat ([Headroom, Gain]).ToList (); + var file = Open (AppleV1 (JpegExif (AppleExifTiff (AppleMakerNote (entries)))), "a.jpg"); + file.Tag!.Clear (); + IfdSteps.Count = 0; + var output = file.Render ().ToArray (); + Assert.AreEqual (1, ExifSegments (output).Count, $"N={n}: the headroom is kept"); + return IfdSteps.Count; + } + + var small = Steps (500); + var large = Steps (4000); + Assert.IsTrue (large >= 4002, $"{large} steps: every maker-note entry is counted"); + Assert.IsTrue (large <= 2L * 4002, $"{large} steps for 4,002 entries"); + Assert.IsTrue (large < 10 * small, $"8x the entries took {large / (double)small:F1}x the steps"); + } + // IFD0 with one Exif IFD pointer per Exif IFD, in order; each Exif IFD with one MakerNote entry per note, in order; + // the notes after the tables. Big-endian. + static byte[] ExifWithNotes (params byte[][][] notesOfEachExifIfd) + { + var m = notesOfEachExifIfd.Length; + var at = 8 + 2 + (12 * m) + 4; + var ifds = new List (); + foreach (var notes in notesOfEachExifIfd) { + ifds.Add (at); + at += 2 + (12 * notes.Length) + 4; + } + + var length = at + notesOfEachExifIfd.Sum (notes => notes.Sum (n => n.Length)); + var tiff = new TiffBuilder (length, bigEndian: true).Header (8).Table (8, [.. ifds.Select (ifd => (0x8769, 4, 1L, (long)ifd))]); + var noteAt = at; + for (var k = 0; k < m; k++) { + var entries = new List<(int, int, long, long)> (); + foreach (var note in notesOfEachExifIfd[k]) { + entries.Add ((0x927C, 7, note.Length, noteAt)); + tiff.Bytes (noteAt, note); + noteAt += note.Length; + } + + tiff.Table (ifds[k], [.. entries]); + } + + return tiff.ToArray (); + } + + static byte[] Kept (byte[] headroom, byte[] gain) => ExpectedHeadroomExif (headroom, gain)[10..]; + + // Exif IFDs merge value by value: walking from the last, a value one lacks is taken from an earlier one. + [TestMethod] + public void Keep_TakesAValueTheLastExifIfdLacks_FromAnEarlierOne () + { + var both = AppleMakerNote ([(0x0021, 10, 1, Real21), (0x0030, 10, 1, Real30)]); + + CollectionAssert.AreEqual (Kept (Alt21, Real30), AppleHeadroom.Keep (ExifWithNotes ([both], [AppleMakerNote ([(0x0021, 10, 1, Alt21)])]))); + CollectionAssert.AreEqual (Kept (Real21, Alt30), AppleHeadroom.Keep (ExifWithNotes ([both], [AppleMakerNote ([(0x0030, 10, 1, Alt30)])]))); + } + + // The last usable MakerNote of an Exif IFD wins: an Apple one of exactly its header and an empty table, or one + // whose table ends exactly at its end (values may lie in the table), is usable; one whose count claims more + // entries than it holds is not, and the one before it is used. + [TestMethod] + public void Keep_TheLastUsableMakerNote_AtTheEdgesOfUsable () + { + var first = AppleMakerNote ([(0x0021, 10, 1, Real21), (0x0030, 10, 1, Real30)]); + var empty = Concat (AppleMakerNoteHeader, [0, 0]); + Assert.IsNull (AppleHeadroom.Keep (ExifWithNotes ([first, empty])), "an empty Apple maker note is the winner, and holds nothing"); + + // Two entries whose values are the bytes of the table itself, at 16 and 24: exactly 40 bytes. + var exact = Concat (AppleMakerNoteHeader, [0, 2], [0x00, 0x21, 0x00, 0x0A, 0, 0, 0, 1, 0, 0, 0, 16], [0x00, 0x30, 0x00, 0x0A, 0, 0, 0, 1, 0, 0, 0, 24]); + CollectionAssert.AreEqual (Kept (exact[16..24], exact[24..32]), AppleHeadroom.Keep (ExifWithNotes ([first, exact])), "a table that ends at the note's end"); + + var claims = exact.ToArray (); + claims[15] = 3; + CollectionAssert.AreEqual (Kept (Real21, Real30), AppleHeadroom.Keep (ExifWithNotes ([first, claims])), "a table past the note's end"); + CollectionAssert.AreEqual (Kept (Real21, Real30), AppleHeadroom.Keep (ExifWithNotes ([first, exact[..36]])), "a table 4 bytes past the note's end"); + } + + // A maker note holds only its counted entries: bytes after its table that read as a 0x0021 entry are not one. + [TestMethod] + public void Keep_ReadsOnlyTheMakerNotesCountedEntries () + { + static byte[] Entry (int tag, int offset) => [(byte)(tag >> 8), (byte)tag, 0x00, 0x0A, 0, 0, 0, 1, 0, 0, 0, (byte)offset]; + // Two counted entries, then 12 bytes where the next-IFD offset would start that read as a third, then the values. + var shadow = Concat (AppleMakerNoteHeader, [0, 2], Entry (0x0021, 52), Entry (0x0030, 60), Entry (0x0021, 68), Real21, Real30, Alt21); + + CollectionAssert.AreEqual (Kept (Real21, Real30), AppleHeadroom.Keep (ExifWithNotes ([shadow]))); + } + // The walk reads at most one entry per 12 bytes of the TIFF, counting the Exif IFDs' and the maker notes' + // entries. Here a second Exif IFD pointer names a table inside the maker note's entries whose count is a filler + // entry's tag: with 6 the entries walked are exactly the bound and the headroom is kept; with 7 they pass it, and + // nothing is. + [TestMethod] + [DataRow (6, true)] + [DataRow (7, false)] + public void Keep_AtTheEntryBound_KeepsTheHeadroom_AndPastItNothing (int fillerTag, bool kept) + { + const int Ifd0 = 8, Exif = Ifd0 + 2 + 24 + 4, Note = Exif + 2 + 12 + 4, Entries = 10; + var valuesAt = 16 + (12 * Entries) + 4; + var note = new List (); + note.AddRange (AppleMakerNoteHeader); + note.AddRange (new byte[] { 0, Entries }); + note.AddRange (new byte[] { 0x00, 0x21, 0x00, 0x0A, 0, 0, 0, 1, 0, 0, 0, (byte)valuesAt }); + note.AddRange (new byte[] { 0x00, 0x30, 0x00, 0x0A, 0, 0, 0, 1, 0, 0, 0, (byte)(valuesAt + 8) }); + for (var n = 2; n < Entries; n++) + note.AddRange (new byte[] { 0x00, (byte)fillerTag, 0x00, 0x03, 0, 0, 0, 1, 0, 0, 0, 0 }); + note.AddRange (new byte[4]); + note.AddRange (Real21); + note.AddRange (Real30); + var length = Note + note.Count; + Assert.AreEqual (7 + Entries, length / 12, "fixture: the bound"); + var tiff = new TiffBuilder (length, bigEndian: true).Header (Ifd0) + .Table (Ifd0, [(0x8769, 4, 1, Exif), (0x8769, 4, 1, Note + 16 + 24)]) + .Table (Exif, [(0x927C, 7, note.Count, Note)]).Bytes (Note, note.ToArray ()).ToArray (); + + var result = AppleHeadroom.Keep (tiff); + + if (kept) + CollectionAssert.AreEqual (Kept (Real21, Real30), result); + else + Assert.IsNull (result); + } +} diff --git a/tests/TagLibSharp2.Tests/Image/ExifEditMatrixTests.cs b/tests/TagLibSharp2.Tests/Image/ExifEditMatrixTests.cs new file mode 100644 index 00000000..9af8801f --- /dev/null +++ b/tests/TagLibSharp2.Tests/Image/ExifEditMatrixTests.cs @@ -0,0 +1,530 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Text; +using TagLibSharp2.Core; +using TagLibSharp2.Image; +using TagLibSharp2.Image.Exif; +using TagLibSharp2.Tests.Core; +using static TagLibSharp2.Tests.Image.ExifTestData; +using static TagLibSharp2.Tests.Image.ImageTestBuilder; + +namespace TagLibSharp2.Tests.Image; + +/// +/// The Exif edit over the structure space: every ordered pair of IFD structures, the second placed against the first +/// in every relation (same start, inside, covers, touching or sharing a byte on either side, starting or ending in the +/// first's count, entries, next offset or value), in both byte orders and three carriers, through every field edit, +/// a no-op save and Clear. +/// +/// +/// The oracle is the tests' own reader (, checked against exiftool for every input +/// here by ). Two-sided and judged by consequence: a save must leave exactly what +/// any reader sees, less the removed copies (no value masked), and exiftool must still read the same tables with +/// the same other entries; a refusal is right when the same edit made without its check +/// () would have changed something either view sees, when the unchecked edit +/// is refused too (the linear bound), or when the structure is not plain and the reason says the copy cannot be +/// updated; a field with no copy always saves with the Exif bytes unchanged. +/// The test also asserts its own coverage: inputs, saves and refusals per relation, both byte orders, and every +/// structure where the canonical input puts it. +/// +[TestClass] +[TestCategory ("Unit")] +public class ExifEditMatrixTests +{ + // Tables: IFD0 and the chain after it (IFD1, IFD2); Exif IFDs at depth 1 and 2, one IFD1 points at, one an + // IFD0 pointer typed SHORT names, and one only TagLib# reads (IFD0's 0x8769 typed ASCII, its field a LONG); a SubIFD given inline and one given by an offset array; an interoperability + // IFD and an Exif IFD under it; a GPS table holding an Exif IFD pointer and a SubIFD pointer to a table no reader + // reads (GpsChild); a pointer target whose entries do not fit. Values: the removed UserComment of every table that + // holds one, the removed XPComment, a kept Artist value, and IFD1's thumbnail data. + internal enum S + { + Ifd0, Exif, Nested, Ifd1, Ifd2, Ifd1Exif, ShortExif, RawExif, SubIfd, SubArray, SubIfd2, Interop, InteropExif, Gps, GpsChild, Unread, + UcExif, UcNested, UcIfd1Exif, UcIfd2, UcShort, UcRaw, UcSub, UcSub2, UcInterop, UcInteropExif, UcGpsChild, Xp, Kept, Thumb, + } + + static readonly S[] All = Enum.GetValues (); + + static byte[] Uc (string text) => Concat ("ASCII\0\0\0"u8.ToArray (), Encoding.ASCII.GetBytes (text)); + + static readonly Dictionary Values = new () { + [S.UcExif] = Uc ("uc-exif!"), + [S.UcNested] = Uc ("uc-nest!"), + [S.UcIfd1Exif] = Uc ("uc-ifd1!"), + [S.UcIfd2] = Uc ("uc-ifd2!"), + [S.UcShort] = Uc ("uc-shrt!"), + [S.UcRaw] = Uc ("uc-raw!!"), + [S.UcSub] = Uc ("uc-subi!"), + [S.UcSub2] = Uc ("uc-sub2!"), + [S.UcInterop] = Uc ("uc-iop!!"), + [S.UcInteropExif] = Uc ("uc-iopx!"), + [S.UcGpsChild] = Uc ("uc-gpsc!"), + [S.SubArray] = new byte[8], + [S.Xp] = Encoding.Unicode.GetBytes ("xp-old\0"), + [S.Kept] = "kept-value\0\0"u8.ToArray (), + [S.Thumb] = "thumbnail-bytes!"u8.ToArray (), + }; + + // Each table's entries: (tag, type, count, the structure its value names, or a literal value). + static (int Tag, int Type, int Count, S? Names, long Literal)[] EntriesOf (S s) => s switch { + S.Ifd0 => [(0x8769, 4, 1, S.Exif, 0), (0x8769, 4, 1, S.Unread, 0), (0x8825, 4, 1, S.Gps, 0), (0x014A, 4, 1, S.SubIfd, 0), + (0x014A, 4, 2, S.SubArray, 0), (0x9C9C, 1, Values[S.Xp].Length, S.Xp, 0), (0x013B, 2, Values[S.Kept].Length, S.Kept, 0), (0x8769, 3, 1, S.ShortExif, 0), + (0x8769, 2, 4, S.RawExif, 0)], + S.Exif => [(0x9286, 7, Values[S.UcExif].Length, S.UcExif, 0), (0x8769, 4, 1, S.Nested, 0), (0xA005, 4, 1, S.Interop, 0)], + S.Ifd1 => [(0x8769, 4, 1, S.Ifd1Exif, 0), (0x9003, 7, 4, null, 0x31303032), (0x0201, 4, 1, S.Thumb, 0), (0x0202, 4, 1, null, Values[S.Thumb].Length)], + S.Interop => [(0x0001, 2, 4, null, 0x00383952), (0x9286, 7, Values[S.UcInterop].Length, S.UcInterop, 0), (0x8769, 4, 1, S.InteropExif, 0)], + S.Gps => [(0x0001, 2, 2, null, 0x4E), (0x8769, 4, 1, S.GpsChild, 0), (0x014A, 4, 1, S.GpsChild, 0)], + _ => [(0x9286, 7, Values[ValueOf (s)].Length, ValueOf (s), 0)], + }; + + static S ValueOf (S table) => table switch { + S.Nested => S.UcNested, + S.Ifd1Exif => S.UcIfd1Exif, + S.Ifd2 => S.UcIfd2, + S.ShortExif => S.UcShort, + S.RawExif => S.UcRaw, + S.SubIfd => S.UcSub, + S.SubIfd2 => S.UcSub2, + S.InteropExif => S.UcInteropExif, + S.GpsChild => S.UcGpsChild, + _ => S.UcExif + }; + + static bool IsTable (S s) => s is not S.Unread && !Values.ContainsKey (s); + + static int LengthOf (S s) => s switch { + S.Unread => 2, + _ when Values.TryGetValue (s, out var value) => value.Length, + _ => 2 + (12 * EntriesOf (s).Length) + 4, + }; + + // The canonical layout: every structure on its own, 4 bytes apart. + internal static Dictionary Canonical () + { + var at = new Dictionary (); + var next = 8; + foreach (var s in All) { + at[s] = next; + next += LengthOf (s) + 4; + } + + return at; + } + + // Where X goes against Y. Disjoint is the canonical layout itself (every pair 4 or more bytes apart). + internal static readonly string[] Relations = [ + "same start", "inside", "covers", "touches before", "touches after", "shares first byte", "shares last byte", + "starts in count", "starts in entries", "starts in next", "starts in value", + "ends in count", "ends in entries", "ends in next", "ends in value", + ]; + + static int? Place (string relation, S x, int yAt, S y) + { + int lx = LengthOf (x), ly = LengthOf (y), yEnd = yAt + ly; + var table = IsTable (y); + int? anchor = relation[(relation.LastIndexOf (' ') + 1)..] switch { + "count" when table || y == S.Unread => yAt + 1, + "entries" when table => yAt + 2 + 6, + "next" when table => yEnd - 2, + "value" when !table && y != S.Unread => yAt + 1, + _ => null, + }; + int? at = relation switch { + "same start" => yAt, + "inside" => lx <= ly - 2 ? yAt + ((ly - lx) / 2) : null, + "covers" => lx >= ly + 2 ? yAt - ((lx - ly) / 2) : null, + "touches before" => yAt - lx, + "touches after" => yEnd, + "shares first byte" => yAt - lx + 1, + "shares last byte" => yEnd - 1, + _ when anchor is null => null, + _ when relation.StartsWith ("starts", StringComparison.Ordinal) => anchor, + _ => anchor + 1 - lx, + }; + return at >= 8 ? at : null; + } + + // Writes every structure at its place, X last so that X is whole and what it lands on is overwritten. + internal static byte[] Build (Dictionary at, S? last, bool bigEndian) + { + var tiff = new TiffBuilder (All.Max (s => at[s] + LengthOf (s)) + 16, bigEndian).Header (at[S.Ifd0]); + foreach (var s in All) { + if (s != last) + Write (tiff, at, s); + } + + if (last is S x) + Write (tiff, at, x); + return tiff.ToArray (); + } + + static void Write (TiffBuilder tiff, Dictionary at, S s) + { + if (s == S.Unread) { + // 257 entries: they do not fit, so no reader reads this table. + tiff.U16 (at[s], 0x0101); + return; + } + + if (s == S.SubArray) { + // Two offsets: the second SubIFD, and 0 (no table). + tiff.U32 (at[s], at[S.SubIfd2]).U32 (at[s] + 4, 0); + return; + } + + if (!IsTable (s)) { + tiff.Bytes (at[s], Values[s]); + return; + } + + var entries = EntriesOf (s); + long? next = s == S.Ifd0 ? at[S.Ifd1] : s == S.Ifd1 ? at[S.Ifd2] : 0; + tiff.Table (at[s], [.. entries.Select (e => (e.Tag, e.Type, (long)e.Count, e.Names is S named ? (long)at[named] : e.Literal))], next); + // A SHORT pointer holds its offset in the first two bytes of the field, in the file's byte order. + for (var n = 0; n < entries.Length; n++) { + if (entries[n].Type == 3 && entries[n].Names is S named) + tiff.U32 (at[s] + 2 + (12 * n) + 8, 0).U16 (at[s] + 2 + (12 * n) + 8, at[named]); + } + } + + /// Every input: the canonical layout, then each relation of each ordered pair, in each byte order. + internal static IEnumerable<(string Name, byte[] Tiff)> Inputs () + { + var canonical = Canonical (); + foreach (var bigEndian in new[] { false, true }) { + yield return ($"{(bigEndian ? "BE" : "LE")} [disjoint] every pair", Build (canonical, null, bigEndian)); + foreach (var x in All) { + foreach (var y in All) { + if (x == y) + continue; + // Two relations that put X at the same offset are one input, named by the first. + var seen = new HashSet (); + foreach (var relation in Relations) { + if (Place (relation, x, canonical[y], y) is not int at || !seen.Add (at)) + continue; + var placed = new Dictionary (canonical) { [x] = at }; + yield return ($"{(bigEndian ? "BE" : "LE")} {x} [{relation}] {y}", Build (placed, x, bigEndian)); + } + } + } + } + } + + static readonly string[] Carriers = ["jpeg APP1", "png eXIf", "png raw EXIF profile"]; + + // Relations whose comment does not share a protected byte, measured for Comment and Comment null. + static readonly string[] CommentSaves = [ + "covers", "ends in count", "ends in value", "inside", "same start", "shares first byte", "shares last byte", + "starts in entries", "starts in next", "starts in value", "touches after", "touches before", + ]; + + sealed class Tally + { + public int Inputs; + public int Saved; + public int Bound; + public readonly Dictionary InputsBy = []; + public readonly Dictionary SavedBy = []; + public readonly Dictionary RefusedBy = []; + public readonly Dictionary FailedBy = []; + public readonly Dictionary SafeRefusal = []; + public readonly List Failures = []; + + public static void Add (Dictionary counts, string key) => counts[key] = counts.GetValueOrDefault (key) + 1; + + public void Fail (string kind, string message) + { + Add (FailedBy, kind); + if (Failures.Count < 40) + Failures.Add (message); + } + } + + // What each operation asks to remove. A JPEG stores only the comment, so its other setters change nothing. + static HashSet RemovedBy (string operation, string carrier) => operation switch { + "Comment" or "Comment null" => [0x9286, 0x9C9C], + "Artist" when carrier != "jpeg APP1" => [0x013B, 0x9C9D], + "Title" when carrier != "jpeg APP1" => [0x9C9B], + "Description" when carrier != "jpeg APP1" => [0x010E], + "Copyright" when carrier != "jpeg APP1" => [0x8298], + _ => [], + }; + + static void Apply (string operation, ImageTag tag) + { + switch (operation) { + case "Comment": + tag.Comment = "new"; + break; + case "Comment null": + tag.Comment = null; + break; + case "Artist": + tag.Artist = "new"; + break; + case "Title": + tag.Title = "new"; + break; + case "Description": + tag.Description = "new"; + break; + case "Copyright": + tag.Copyright = "new"; + break; + case "Clear": + tag.Clear (); + break; + } + } + + // The save, and its output (the input when refused). + static (bool Saved, string? Error, byte[] Output) Save (byte[] input, string carrier, string operation, bool unchecked_) + { + var file = (StillImageFile)MediaFile.ReadFromData (input, carrier.StartsWith ("jpeg", StringComparison.Ordinal) ? "a.jpg" : "a.png").File!; + Apply (operation, (ImageTag)file.Tag!); + ExifEditor.SkipCheck = unchecked_; + try { + var save = file.SaveToFile ("/out", new MockFileSystem ()); + return (save.IsSuccess, save.Error, file.Render ().ToArray ()); + } finally { + ExifEditor.SkipCheck = false; + } + } + + static Tally RunMatrix (string operation) + { + var tally = new Tally (); + foreach (var (name, tiff) in Inputs ()) { + var before = ExifReaderModel.AnyReader (tiff); + foreach (var carrier in Carriers) { + tally.Inputs++; + Tally.Add (tally.InputsBy, RelationOf (name)); + Check (tally, operation, carrier, name, tiff, before); + } + } + + return tally; + } + + static void Check (Tally tally, string operation, string carrier, string name, byte[] tiff, ExifReaderModel before) + { + var cell = $"{operation} | {carrier} | {name}"; + var input = InCarrier (carrier, tiff); + var (saved, error, output) = Save (input, carrier, operation, unchecked_: false); + if (operation == "Clear") { + if (!saved || ExifIn (carrier, output) is not null) + tally.Fail ("Clear left Exif or was refused", $"{cell}: {error}"); + else + tally.Saved++; + return; + } + + var removed = RemovedBy (operation, carrier); + var expected = before.Visible (removed); + if (!before.Tables.Any (t => t.ReadsExifTags && Enumerable.Range (0, t.Count).Any (n => removed.Contains (before.U16 (t.At + 2 + (12 * n)))))) { + // Nothing to remove: never refused, and the Exif block keeps every byte. The one exception is the linear + // bound: past it the walk stops, and the edit is refused when the block's bytes hold one of the field's + // tags anywhere, as some table may (TagLib# reads the tag at any type). + if (!saved && error!.Contains ("beyond what its data holds", StringComparison.Ordinal) && HoldsTag (tiff, removed)) + tally.Bound++; + else if (!saved) + tally.Fail ("refused with nothing to remove", $"{cell}: {error}"); + else if (!ExifIn (carrier, output)!.AsSpan ().SequenceEqual (tiff)) + tally.Fail ("changed with nothing to remove", $"{cell}: the Exif block changed"); + else + tally.Saved++; + return; + } + + if (saved) { + tally.Saved++; + Tally.Add (tally.SavedBy, RelationOf (name)); + var got = ExifReaderModel.AnyReader (ExifIn (carrier, output)!).Visible ([]); + if (got != expected) + tally.Fail ("saved, and readers see more than the copies change", $"{cell}: readers would show\n {got}\n instead of\n {expected}"); + var exifAfter = ExiftoolView (ExifIn (carrier, output)!, removed); + if (exifAfter != ExiftoolView (tiff, removed)) + tally.Fail ("saved, and exiftool reads a different table", $"{cell}: exiftool would show\n {exifAfter}\n instead of\n {ExiftoolView (tiff, removed)}"); + return; + } + + // Refused: right when the unchecked edit would change what a reader sees, including which tables exiftool + // reads, when that edit is refused too (the bound), or when the structure is not plain. A not-plain + // refusal names its reason. The unchecked edit may still be safe; that over-refusal is accepted. + var (rawSaved, _, rawOutput) = Save (input, carrier, operation, unchecked_: true); + Tally.Add (tally.RefusedBy, RelationOf (name)); + if (!rawSaved) + tally.Bound++; + else if (ExifReaderModel.AnyReader (ExifIn (carrier, rawOutput)!).Visible ([]) == expected + && ExiftoolView (ExifIn (carrier, rawOutput)!, removed) == ExiftoolView (tiff, removed)) { + Tally.Add (tally.SafeRefusal, ReasonKey (error)); + if (!IsAcceptedRefusal (error)) + tally.Fail ("refused when safe", $"{cell}: refused, but the edit changes nothing else readers see: {error}"); + } + } + + // A not-plain refusal names one PlainExif reason. A clean refusal names one ExifEditor reason. Both phrases + // are the production constants. A refusal that only says the copy cannot be updated matches neither. + static readonly string[] PlainReasons = [ + PlainExif.NextCutShort, + PlainExif.PairTagRepeated, + PlainExif.PairTypeWrong, + PlainExif.PairArrayRepeated, + PlainExif.PairDoesNotFit, + PlainExif.FirstEntryChanges, + PlainExif.OverBudget, + ]; + + static readonly string[] CleanReasons = [ + ExifEditor.StructureWouldChange, + ExifEditor.TablesOverlap, + ExifEditor.SubIfdInsideTable, + ExifEditor.ValueInsideTable, + ExifEditor.PointerIntoTable, + ]; + + static bool IsNotPlainRefusal (string? error) => + error is not null && PlainReasons.Any (reason => error.Contains (reason, StringComparison.Ordinal)); + + // The walk-bound sentence contains TablesOverlap plus "beyond what its data holds", and a block that is not + // TIFF is its own refusal. Neither is a clean-structure reason; the unchecked edit judges those two. + static bool IsCleanRefusal (string? error) => + error is not null + && !error.Contains ("beyond what its data holds", StringComparison.Ordinal) + && !error.Contains ("not a TIFF", StringComparison.Ordinal) + && CleanReasons.Any (reason => error.Contains (reason, StringComparison.Ordinal)); + + static bool IsAcceptedRefusal (string? error) => IsNotPlainRefusal (error) || IsCleanRefusal (error); + + static string ReasonKey (string? error) + { + if (error is null) + return "(null)"; + foreach (var reason in PlainReasons) { + if (error.Contains (reason, StringComparison.Ordinal)) + return reason; + } + + var block = error.IndexOf ("block ", StringComparison.Ordinal); + var so = error.IndexOf (", so", StringComparison.Ordinal); + return block >= 0 && so > block ? error[(block + "block ".Length)..so] : error; + } + + // What exiftool shows once the removed tags are gone, in every table. A save or a refusal is wrong when the + // edit changes which tables it reads or which other entries those tables hold: compaction can move a format + // it does not read into the first entry, or out of it. + static string ExiftoolView (byte[] tiff, HashSet removed) => ExifReaderModel.Exiftool (tiff).Visible (removed, anyTable: true); + + // Whether any two bytes of the block, read in its byte order, are one of the tags. + static bool HoldsTag (byte[] tiff, HashSet tags) + { + var le = tiff[0] == (byte)'I'; + for (var at = 0; at + 2 <= tiff.Length; at++) { + if (tags.Contains (le ? tiff[at] | (tiff[at + 1] << 8) : (tiff[at] << 8) | tiff[at + 1])) + return true; + } + + return false; + } + + static string RelationOf (string name) => name[(name.IndexOf ('[') + 1)..name.IndexOf (']')]; + + static string Format (Dictionary counts) => + string.Join ("; ", counts.OrderBy (p => p.Key, StringComparer.Ordinal).Select (p => $"{p.Key}: {p.Value}")); + + [TestMethod] + [DataRow ("Comment")] + [DataRow ("Comment null")] + [DataRow ("Artist")] + [DataRow ("Title")] + [DataRow ("Description")] + [DataRow ("Copyright")] + [DataRow ("no-op save")] + [DataRow ("Clear")] + public void EveryStructurePairAndRelation_SavesExactlyWhatReadersShouldSee_OrRefusesOnlyWhenUnsafe (string operation) + { + var tally = RunMatrix (operation); + + Console.WriteLine ($"{operation}: {tally.Inputs} inputs ({Format (tally.InputsBy)}); {tally.Saved} saved ({Format (tally.SavedBy)}); refused by relation: {Format (tally.RefusedBy)}; at the bound: {tally.Bound}; safe refusal: {Format (tally.SafeRefusal)}"); + Assert.AreEqual (0, tally.FailedBy.Values.Sum (), $"{operation}: failing cells of {tally.Inputs} by kind: {Format (tally.FailedBy)}\n" + string.Join ("\n", tally.Failures)); + Assert.AreEqual (16, tally.InputsBy.Count, $"{operation}: every relation has inputs"); + Assert.IsTrue (tally.InputsBy.Values.All (n => n >= 3 * 2), $"{operation}: every relation in both byte orders and every carrier"); + if (operation is "Comment" or "Comment null") { + // Measured at this head. The canonical layout's unread table counts 257 entries, so its protected span + // runs to the end of the data and covers the comment values: that base layout refuses. Twelve relations + // still have a placement whose comment does not share a protected byte. + Assert.AreEqual (47712, tally.Inputs, operation); + Assert.AreEqual (534, tally.Saved, $"{operation}: {Format (tally.SavedBy)}"); + Assert.AreEqual (48, tally.Bound, operation); + CollectionAssert.AreEquivalent (CommentSaves, tally.SavedBy.Keys.ToList (), $"{operation}: {Format (tally.SavedBy)}"); + Assert.AreEqual (16, tally.RefusedBy.Count, $"{operation}: refusals per relation: {Format (tally.RefusedBy)}"); + Assert.AreEqual (6, tally.RefusedBy["disjoint"], "the base layout refuses"); + Assert.AreEqual (Format (CommentSafe), Format (tally.SafeRefusal), operation); + } else if (operation == "Artist") { + Assert.AreEqual (Format (ArtistSafe), Format (tally.SafeRefusal), operation); + } else { + Assert.AreEqual ("", Format (tally.SafeRefusal), operation); + } + } + + // Measured on the Comment matrix. The phrases are the production constants; the counts are the cells. + static Dictionary CommentSafe { get; } = new () { + [ExifEditor.StructureWouldChange] = 31995, + [ExifEditor.TablesOverlap] = 1344, + [ExifEditor.SubIfdInsideTable] = 123, + [PlainExif.PairDoesNotFit] = 243, + [PlainExif.PairTypeWrong] = 18, + [ExifEditor.ValueInsideTable] = 282, + [ExifEditor.PointerIntoTable] = 1140, + [PlainExif.FirstEntryChanges] = 231, + }; + + static Dictionary ArtistSafe { get; } = new () { + [ExifEditor.StructureWouldChange] = 27776, + [ExifEditor.TablesOverlap] = 654, + [ExifEditor.SubIfdInsideTable] = 10, + [PlainExif.PairDoesNotFit] = 202, + [PlainExif.PairTypeWrong] = 68, + [ExifEditor.ValueInsideTable] = 122, + [ExifEditor.PointerIntoTable] = 574, + }; + + // The coverage the matrix rests on: in the base layout every table is where readers find it, in its kinds, every + // copy is shown, the table under the GPS pointers and the unread target are read by no one, and both byte orders + // are generated alike. + [TestMethod] + [DataRow (false)] + [DataRow (true)] + public void TheBaseLayout_PutsEveryStructureWhereReadersFindIt (bool bigEndian) + { + var at = Canonical (); + + var model = ExifReaderModel.AnyReader (Build (at, null, bigEndian)); + + var tables = model.Tables.ToDictionary (t => t.At, t => string.Join ("+", t.Kinds.OrderBy (k => k))); + var expected = new Dictionary { + [S.Ifd0] = "Main", + [S.Ifd1] = "Main", + [S.Ifd2] = "Main", + [S.Exif] = "Exif", + [S.Nested] = "Exif", + [S.Ifd1Exif] = "Exif", + [S.ShortExif] = "Exif", + [S.RawExif] = "Exif", + [S.InteropExif] = "Exif", + [S.SubIfd] = "SubIfd", + [S.SubIfd2] = "SubIfd", + [S.Interop] = "Interop", + [S.Gps] = "Gps", + }; + foreach (var (s, kinds) in expected) + Assert.AreEqual (kinds, tables.GetValueOrDefault (at[s]), $"{s} at {at[s]}"); + Assert.AreEqual (expected.Count, tables.Count, "no other table is read: not GpsChild, not the unread target"); + CollectionAssert.AreEqual (new long[] { at[S.Unread] }, model.Unread); + var copies = model.CopiesOf (0x9286); + foreach (var table in new[] { S.Exif, S.Nested, S.Ifd1Exif, S.Ifd2, S.ShortExif, S.RawExif, S.SubIfd, S.SubIfd2, S.Interop, S.InteropExif }) + Assert.AreEqual (1, copies.Count (c => c == at[table]), $"{table} shows its UserComment"); + Assert.AreEqual (10, copies.Count); + Assert.AreEqual (Inputs ().Count (i => i.Name.StartsWith ("LE", StringComparison.Ordinal)), Inputs ().Count (i => i.Name.StartsWith ("BE", StringComparison.Ordinal)), "both byte orders alike"); + } +} diff --git a/tests/TagLibSharp2.Tests/Image/ExifEditPinTests.cs b/tests/TagLibSharp2.Tests/Image/ExifEditPinTests.cs new file mode 100644 index 00000000..ec5a5b39 --- /dev/null +++ b/tests/TagLibSharp2.Tests/Image/ExifEditPinTests.cs @@ -0,0 +1,124 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Runtime.InteropServices; +using System.Text; +using TagLibSharp2.Core; +using TagLibSharp2.Image; +using TagLibSharp2.Image.Exif; +using TagLibSharp2.Image.Gif; +using TagLibSharp2.Image.Png; +using TagLibSharp2.Image.Svg; +using TagLibSharp2.Image.Tiff; +using TagLibSharp2.Tests.Core; +using TagLibSharp2.Tests.Kit; +using static TagLibSharp2.Tests.Image.ImageTestBuilder; + +namespace TagLibSharp2.Tests.Image; + +public partial class ExifEditTests +{ + [TestMethod] + public void UnchangedExifRequest_TakesNoSteps () + { + var tiff = new TiffBuilder (30).Header (8).Table (8, [(0x010E, 2, 4, 0x41424344)]).ToArray (); + var tag = new ImageTag (MediaFormat.Jpeg, ImageStores.Comment); + IfdSteps.Count = 0; + + Assert.IsTrue (ExifEditor.TryRemove (tiff, 0, tag, "eXIf", out var changed, out var error), error); + + Assert.IsFalse (changed); + Assert.AreEqual (0, IfdSteps.Count); + } + + [TestMethod] + public void CommentEdit_TakesTheMeasuredSteps () + { + var simple = Steps (new TiffBuilder (30).Header (8).Table (8, [(0x9286, 7, 4, 0x41424344)]).ToArray ()); + var strips = Steps (new TiffBuilder (80).Header (8).Table (8, [(0x9286, 7, 4, 0x41424344), (0x0111, 3, 2, 50), (0x0117, 3, 2, 54)]) + .U16 (50, 1).U16 (52, 1).U16 (54, 4).U16 (56, 4).ToArray ()); + var note = Steps (new TiffBuilder (160).Header (8) + .Table (8, [(0x8769, 4, 1, 26)]) + .Table (26, [(0x9286, 7, 4, 0x41424344), (0x927C, 7, 30, 80)]) + .Table (80, [(0x0001, 7, 4, 100)]) + .Bytes (100, "KEEP"u8.ToArray ()).ToArray ()); + var foreign = ForeignSteps (); + + Assert.IsTrue (simple <= 60 && strips <= 160 && note <= 320 && foreign <= 64, $"{simple},{strips},{note},{foreign}"); + } + + [TestMethod] + public void KeptTableThatCoversACompactedOne_Refuses () + { + // IFD0 is not edited and its bytes run through offset 62. The Exif IFD at 40 is inside those bytes and + // holds the comment, so compacting it would rewrite IFD0. The furthest-end of the kept table is what + // sees that. + var bytes = new TiffBuilder (80).Header (8) + .Table (8, [(0x8769, 4, 1, 40), (0x010F, 2, 4, 0x41424344), (0x0110, 2, 4, 0x41424344), (0x0112, 3, 1, 1)]) + .Table (40, [(0x9286, 7, 4, 0x41424344)]) + .ToArray (); + + Assert.IsFalse (ExifEditor.TryRemove (bytes, 0, CommentTag (), "eXIf", out var changed, out var error)); + + Assert.IsFalse (changed); + StringAssert.Contains (error, ExifEditor.TablesOverlap); + } + + static long Steps (byte[] tiff) + { + var tag = CommentTag (); + IfdSteps.Count = 0; + Assert.IsTrue (ExifEditor.TryRemove (tiff, 0, tag, "eXIf", out var changed, out var error), error); + Assert.IsTrue (changed); + return IfdSteps.Count; + } + + static long ForeignSteps () + { + var block = new byte[32]; + "XX\0*"u8.CopyTo (block); + var tag = CommentTag (); + IfdSteps.Count = 0; + Assert.IsTrue (ExifEditor.TryRemove (block, 0, tag, "eXIf", out var changed, out var error), error); + Assert.IsFalse (changed); + return IfdSteps.Count; + } + + [TestMethod] + public void UnreadTable_ProtectsTheTailAShortCountWouldLeave () + { + // (length - 80 - 2) % 12 == 11, so a count of 1 does not fit and the table is unread. + // The comment's bytes are the last of the file, inside that protected tail. + var bytes = new TiffBuilder (93).Header (8) + .Table (8, [(0x8769, 4, 1, 26)]) + .Table (26, [(0x9286, 7, 5, 91)], next: 80) + .U16 (80, 1) + .ToArray (); + + Assert.IsFalse (ExifEditor.TryRemove (bytes, 0, CommentTag (), "eXIf", out var changed, out var error)); + Assert.IsFalse (changed); + Assert.IsNotNull (error); + } + + [TestMethod] + public void ProtectOnlyValueInsideTheEditedTable_RefusesBecauseTheStructureWouldChange () + { + var bytes = new TiffBuilder (120).Header (8) + .Table (8, [(0x8769, 4, 1, 40), (0x9286, 7, 4, 0x41424344)]) + .Table (40, [(0x010F, 2, 4, 0x41424344)], next: 70) + .Table (70, [(0x004E, 7, 6, 10)]) + .ToArray (); + + Assert.IsFalse (ExifEditor.TryRemove (bytes, 0, CommentTag (), "eXIf", out var changed, out var error)); + + Assert.IsFalse (changed); + StringAssert.Contains (error, ExifEditor.StructureWouldChange); + } + + static ImageTag CommentTag () + { + var tag = new ImageTag (MediaFormat.Png, ImageStores.Comment); + tag.Comment = "New"; + return tag; + } +} diff --git a/tests/TagLibSharp2.Tests/Image/ExifEditRefusalTests.cs b/tests/TagLibSharp2.Tests/Image/ExifEditRefusalTests.cs new file mode 100644 index 00000000..5901a766 --- /dev/null +++ b/tests/TagLibSharp2.Tests/Image/ExifEditRefusalTests.cs @@ -0,0 +1,533 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Text; +using System.Xml.Linq; +using TagLibSharp2.Core; +using TagLibSharp2.Image; +using TagLibSharp2.Image.Exif; +using TagLibSharp2.Image.Tiff; +using TagLibSharp2.Image.Xmp; +using TagLibSharp2.Tests.Core; +using TagLibSharp2.Tests.Kit; +using static TagLibSharp2.Tests.Image.ExifTestData; +using static TagLibSharp2.Tests.Image.ImageTestBuilder; + +namespace TagLibSharp2.Tests.Image; + +/// When an Exif edit is refused and when it must save: overlapping tables, pointers into a table, the bounds, and blocks that cannot hold the field. +[TestClass] +[TestCategory ("Unit")] +public class ExifEditRefusalTests +{ + // IFD tables that overlap hold more entries than the data could: refused with its own reason before any of + // them is walked. Exif IFDs (whose interoperability pointers would be read) and GPS IFDs (protected tables). + // The copy is an XPComment (BYTE) or a UserComment (UNDEFINED, whose tag bytes differ when read the other way), or + // a UserComment of a type exiftool does not show (0, 19, 255) but TagLib# reads as the comment. + [TestMethod] + [DataRow (0x8769, 0x9C9C, 1)] + [DataRow (0x8825, 0x9C9C, 1)] + [DataRow (0x8769, 0x9286, 7)] + [DataRow (0x8769, 0x9286, 0)] + [DataRow (0x8769, 0x9286, 19)] + [DataRow (0x8769, 0x9286, 255)] + public void Edit_IfdsThatOverlap_AreRefusedBeforeTheyAreWalked (int tag, int copy, int type) + { + // 400 IFDs two bytes apart, each read as a table of 200 entries: 80,000 entries in 9 KB. + var entries = Enumerable.Range (0, 400).Select (n => (tag, 4, 1, 4820 + (2 * n))).ToList (); + entries.Add ((copy, type, 4, 0x41424344)); + var tiff = new TiffBuilder (9100).Header (8).Entries (8, [.. entries]); + for (var at = 4820; at < 9100 - 2; at += 2) + tiff.Bytes (at, [0xC8, 0x00]); + var file = Open (Png (PngChunk ("eXIf", tiff.ToArray ()), Text ("Comment", "c")), "a.png"); + file.Tag!.Comment = "New"; + + IfdSteps.Count = 0; + var save = file.SaveToFile ("/a.png", new MockFileSystem ()); + + Assert.IsFalse (save.IsSuccess); + StringAssert.Contains (save.Error, "beyond what its data holds", "refused by the entry bound, before any table is compared"); + Assert.IsTrue (IfdSteps.Count <= 9100, $"{IfdSteps.Count} steps before the refusal"); + } + + // The same overlapping tables with no copy of the field: Title's tag 0x9C9B is in no byte of the block, or only + // as a value (9B 9C 00 00: type 0, which no reader shows as an entry). No table can hold a copy, so the edit + // saves and the block keeps every byte, in linear steps (the walk to the bound, then one pass over the bytes). + [TestMethod] + [DataRow (0x8769, false)] + [DataRow (0x8825, false)] + [DataRow (0x8769, true)] + public void Edit_IfdsThatOverlap_WithNoCopyOfTheField_SaveUnchanged (int tag, bool tagAsAValue) + { + var entries = Enumerable.Range (0, 400).Select (n => (tag, 4, 1, 4820 + (2 * n))).ToList (); + entries.Add ((0x9C9C, 1, 4, 0x41424344)); + if (tagAsAValue) + entries.Add ((0x9003, 4, 1, 0x9C9B)); + var tiff = new TiffBuilder (9100).Header (8).Entries (8, [.. entries]); + for (var at = 4820; at < 9100 - 2; at += 2) + tiff.Bytes (at, [0xC8, 0x00]); + var exif = tiff.ToArray (); + var file = Open (Png (PngChunk ("eXIf", exif), Text ("Comment", "c")), "a.png"); + file.Tag!.Title = "New"; + + IfdSteps.Count = 0; + var save = file.SaveToFile ("/a.png", new MockFileSystem ()); + + Assert.IsTrue (save.IsSuccess, save.Error); + CollectionAssert.AreEqual (exif, ExifOf (file.Render ().ToArray ())); + Assert.IsTrue (IfdSteps.Count <= 3 * 9100, $"{IfdSteps.Count} steps"); + } + + // A block that is not classic TIFF (BigTIFF in either byte order, or an unknown byte order mark) is refused only + // when a reader of another form could find the field in it: when one of the field's tags is in its bytes, in + // either byte order. Otherwise no form can hold a copy, and the block is kept byte for byte. + [TestMethod] + [DataRow ("png", "BigTIFF MM", "Title", false)] + [DataRow ("png", "BigTIFF II", "Title", false)] + [DataRow ("png", "unknown order", "Title", false)] + [DataRow ("png", "BigTIFF MM", "Comment", false)] + [DataRow ("jpeg", "BigTIFF II", "Comment", false)] + [DataRow ("jpeg", "unknown order", "Comment", false)] + [DataRow ("png", "BigTIFF MM", "Title", true)] + [DataRow ("png", "BigTIFF II", "Artist", true)] + [DataRow ("png", "unknown order", "Comment", true)] + [DataRow ("jpeg", "BigTIFF MM", "Comment", true)] + [DataRow ("jpeg", "unknown order", "Comment", true)] + [DataRow ("png", "BigTIFF II", "Comment", true, 1)] + [DataRow ("png", "BigTIFF MM", "Comment", true, 18)] + [DataRow ("png", "BigTIFF MM", "Comment", false, 19)] + [DataRow ("png", "BigTIFF MM", "Comment", false, 0)] + [DataRow ("png", "BigTIFF II", "Comment", false, 19)] + [DataRow ("png", "BigTIFF II", "Comment", false, 0)] + public void Edit_OfABlockThatIsNotClassicTiff_IsRefusedOnlyWhenItMayHoldTheField (string carrier, string form, string field, bool holdsTag, int type = 2) + { + // With a type no TIFF or BigTIFF reader knows (0, 19), the field's tag bytes are no entry: nothing to remove. + var block = new byte[72]; + var bigEndian = form != "BigTIFF II"; + block[0] = block[1] = form switch { "BigTIFF MM" => (byte)'M', "BigTIFF II" => (byte)'I', _ => (byte)'X' }; + block[bigEndian ? 3 : 2] = form == "unknown order" ? (byte)42 : (byte)0x2B; + block[bigEndian ? 5 : 4] = 8; + block[bigEndian ? 15 : 8] = 16; + block[bigEndian ? 23 : 16] = 1; // an 8-byte entry count at 16, then 20-byte entries + block[bigEndian ? 24 : 25] = 1; // tag 0x0100 ImageWidth + block[bigEndian ? 27 : 26] = 3; + if (holdsTag || type != 2) { + // A second entry with one of the field's tags (Title 0x9C9B, Artist 0x013B, Comment 0x9286). + var fieldTag = field switch { "Title" => 0x9C9B, "Artist" => 0x013B, _ => 0x9286 }; + block[bigEndian ? 44 : 45] = (byte)(fieldTag >> 8); + block[bigEndian ? 45 : 44] = (byte)fieldTag; + block[bigEndian ? 47 : 46] = (byte)type; + block[bigEndian ? 23 : 16] = 2; + } + + var input = InCarrier (carrier, block); + var file = Open (input, carrier == "png" ? "a.png" : "a.jpg"); + typeof (Tag).GetProperty (field)!.SetValue (file.Tag, "New"); + + var save = file.SaveToFile ("/a", new MockFileSystem ()); + + if (holdsTag) { + Assert.IsFalse (save.IsSuccess, $"{form}: a reader of that form may hold the field"); + StringAssert.Contains (save.Error, "is not a TIFF structure", form); + CollectionAssert.AreEqual (input, file.Render ().ToArray (), "a refused save changes nothing"); + } else { + Assert.IsTrue (save.IsSuccess, $"{form}: {save.Error}"); + CollectionAssert.AreEqual (block, ExifOf (file.Render ().ToArray ()), $"{form}: the block keeps every byte"); + } + } + + // The scan reaches both ends of a block that is not classic TIFF: a UserComment tag and type as its first or last + // 4 bytes may be an entry (refused); the tag as the last 2 bytes, with no type after it, is not (saved). + [TestMethod] + [DataRow ("first 4 bytes", false)] + [DataRow ("last 4 bytes", false)] + [DataRow ("last 2 bytes", true)] + public void Edit_OfABlockThatIsNotClassicTiff_ReadsTheTagAtEitherEnd (string where, bool saves) + { + var block = new byte[24]; + "XX\0*"u8.CopyTo (block); + byte[] entry = [0x92, 0x86, 0x00, 0x07]; + switch (where) { + case "first 4 bytes": + entry.CopyTo (block, 0); + break; + case "last 4 bytes": + entry.CopyTo (block, block.Length - 4); + break; + default: + entry[..2].CopyTo (block, block.Length - 2); + break; + } + + var input = InCarrier ("png", block); + var file = Open (input, "a.png"); + file.Tag!.Comment = "New"; + + var save = file.SaveToFile ("/a.png", new MockFileSystem ()); + + Assert.AreEqual (saves, save.IsSuccess, $"{where}: {save.Error}"); + CollectionAssert.AreEqual (saves ? block : input, saves ? ExifOf (file.Render ().ToArray ()) : file.Render ().ToArray (), where); + } + + // Two Exif IFDs that share bytes (the second starts inside the first, its count read from the first's + // ExifVersion), as exiftool reads them: compacting one would rewrite the other, so the edit is refused with its + // own reason and nothing is written, however few entries they hold. + [TestMethod] + [DataRow ("png", "the outer table first")] + [DataRow ("png", "the inner table first")] + [DataRow ("jpeg", "the outer table first")] + public void Edit_ExifIfdsThatShareBytes_AreRefused (string carrier, string order) + { + const int Ifd0 = 8, A = 40, B = A + 12, Values = 100; + // A: ExifVersion "02" with 0x0002 in its last two bytes (B's count), UserComment, DateTimeOriginal. + var tiff = new TiffBuilder (Values + 48).Header (8) + .Entries (A, (0x9000, 7, 4, 0x00023230), (0x9286, 7, OldOne.Length, Values), (0x9003, 2, 20, Values + 24)) + .Bytes (Values, OldOne).Bytes (Values + 24, "2001:01:01 01:01:01\0"u8); + tiff.Entries (Ifd0, order == "the outer table first" ? [(0x8769, 4, 1, A), (0x8769, 4, 1, B)] : [(0x8769, 4, 1, B), (0x8769, 4, 1, A)]); + var data = tiff.ToArray (); + var input = carrier == "png" ? Png (PngChunk ("eXIf", data), Text ("Comment", "c")) : Jpeg (JpegExif (data), JpegSegment (0xFE, "c"u8.ToArray ())); + var file = Open (input, carrier == "png" ? "a.png" : "a.jpg"); + file.Tag!.Comment = "New"; + + var fs = new MockFileSystem (); + var save = file.SaveToFile ("/a", fs); + + Assert.IsFalse (save.IsSuccess, $"{carrier} {order}"); + StringAssert.Contains (save.Error, "overlap"); + StringAssert.Contains (save.Error, "its copy of Comment cannot be updated", "the refusal names the field"); + Assert.IsFalse (fs.FileExists ("/a")); + CollectionAssert.AreEqual (input, file.Render ().ToArray (), "the file is unchanged"); + } + + // A pointer whose table does not fit lands inside a table the edit compacts. That unread range overlaps the + // compacted table whether or not the bytes moved under it would read as a table, so both shapes are refused + // and nothing is written. + [TestMethod] + [DataRow (0x8769, false)] + [DataRow (0x8825, false)] + [DataRow (0x8769, true)] + [DataRow (0x8825, true)] + public void Edit_APointerIntoTheMiddleOfAnEditedTable_IsRefused (int tag, bool appears) + { + const int Ifd0 = 8, A = 40, Values = 100; + // The pointer lands on the tag of A's second entry (0x9003): read as a count, 36,867 entries do not fit. The + // third entry moves there: its tag 0x9004 does not fit either; a tag 0x0001 reads as a table of one entry. + var tiff = new TiffBuilder (Values + 48).Header (8) + .Entries (A, (0x9286, 7, OldOne.Length, Values), (0x9003, 2, 20, Values + 24), (appears ? 0x0001 : 0x9004, 2, 4, 0x00383952)) + .Entries (Ifd0, (0x8769, 4, 1, A), (tag, 4, 1, A + 14)) + .Bytes (Values, OldOne).Bytes (Values + 24, "2001:01:01 01:01:01\0"u8).ToArray (); + var input = Png (PngChunk ("eXIf", tiff), Text ("Comment", "c")); + var file = Open (input, "a.png"); + file.Tag!.Comment = "New"; + + var fs = new MockFileSystem (); + var save = file.SaveToFile ("/a.png", fs); + + Assert.IsFalse (save.IsSuccess, $"{tag:X4} appears {appears}: {save.Error}"); + StringAssert.Contains (save.Error, "into the middle of another IFD table"); + Assert.IsFalse (fs.FileExists ("/a.png")); + CollectionAssert.AreEqual (input, file.Render ().ToArray ()); + } + + // A refusal is scoped to its reason: only a table the edit rewrites may not share bytes with another table, and + // an unread pointer's count may not lie in one. Tables that overlap but are not rewritten, or an edit with no + // copy to remove, save; the GPS, IFD1 and interoperability tables keep their bytes. + [TestMethod] + [DataRow ("png", "two Exif IFDs that overlap, with no copy", "Comment")] + [DataRow ("jpeg", "two Exif IFDs that overlap, with no copy", "Comment")] + [DataRow ("png", "IFD1 starts inside the GPS table", "Comment")] + [DataRow ("png", "IFD1 starts inside the GPS table", "Title")] + [DataRow ("jpeg", "IFD1 starts inside the GPS table", "Comment")] + [DataRow ("png", "an interoperability pointer into the GPS table's values", "Comment")] + [DataRow ("jpeg", "an interoperability pointer into the GPS table's values", "Comment")] + public void Edit_SavesWhenNoTableItRewritesOverlapsAnother (string carrier, string shape, string field) + { + const int Ifd0 = 8, E = 60, Gps = 100, Value = 200, Other = 240; + var comment = (0x9286, 7, SecretUc.Length, Value); + var date = (0x9003, 2, 20, Other); + var tiff = new TiffBuilder (Other + 24, bigEndian: false).Header (Ifd0).Bytes (Value, SecretUc).Bytes (Other, "2001:01:01 01:01:01\0"u8); + (int Start, int End) untouched; + switch (shape) { + case "two Exif IFDs that overlap, with no copy": + // B starts 12 bytes into A: B's count is the last two bytes of A's first entry. + tiff.Table (Ifd0, [(0x8769, 4, 1, E), (0x8769, 4, 1, E + 12)]).Table (E, [(0x9000, 7, 4, 0x00023230), date, date]); + untouched = (0, Other + 24); + break; + case "IFD1 starts inside the GPS table": + tiff.Table (Ifd0, [(0x8769, 4, 1, E), (0x8825, 4, 1, Gps)], next: Gps + 12).Table (E, [comment]) + .Table (Gps, [(0x0001, 2, 2, 0x4E), (0x0002, 2, 2, 0x45), (0x0003, 2, 2, 0x4E)]); + untouched = (Gps, Gps + 2 + 36 + 4); + break; + default: + tiff.Table (Ifd0, [(0x8769, 4, 1, E), (0x8825, 4, 1, Gps)]).Table (E, [comment, (0xA005, 4, 1, Gps + 2 + 24 + 8)]) + .Table (Gps, [(0x0001, 2, 2, 0x4E), (0x0002, 2, 2, 0x45), (0x0003, 7, 4, 0x0000FFFF)]); + untouched = (Gps, Gps + 2 + 36 + 4); + break; + } + + var data = tiff.ToArray (); + var input = InCarrier (carrier, data); + var file = Open (input, carrier == "png" ? "a.png" : "a.jpg"); + if (field == "Title") + file.Tag!.Title = "New"; + else + file.Tag!.Comment = "New"; + + var save = file.SaveToFile ("/a", new MockFileSystem ()); + + // The interoperability pointer's value sits inside the GPS table. Compaction of the Exif IFD does not rewrite + // the GPS table, but the pointer range is protected structure the edit would leave inconsistent, so it refuses. + if (shape == "an interoperability pointer into the GPS table's values") { + Assert.IsFalse (save.IsSuccess, $"{carrier} {shape}: {save.Error}"); + StringAssert.Contains (save.Error, "cannot be updated"); + CollectionAssert.AreEqual (input, file.Render ().ToArray (), shape); + return; + } + + Assert.IsTrue (save.IsSuccess, $"{carrier} {shape} {field}: {save.Error}"); + var exif = ExifOf (file.Render ().ToArray ()); + Assert.AreEqual (field == "Title" ? UserCommentsInEveryExifIfd (data).Count : 0, UserCommentsInEveryExifIfd (exif).Count, shape); + if (field == "Title") + AssertOnlyTheCopiesAreGone (data, exif, shape, 0x9C9B); + else + AssertOnlyTheCopiesAreGone (data, exif, shape, 0x9286, 0x9C9C); + CollectionAssert.AreEqual (data[untouched.Start..untouched.End], exif[untouched.Start..untouched.End], $"{shape}: the tables not rewritten keep their bytes"); + } + + // Tables at the edge of a table the edit compacts (A holds the UserComment): A's compaction moves its 4-byte + // next-IFD offset and clears where it was, so a table B whose count lies there would change (saving would lose B's + // DateTimeDigitized): refused, nothing written. An unread pointer whose count's second byte is A's first byte is + // a pointer into the middle of the compacted table, so that edit is refused too. + [TestMethod] + [DataRow ("B's count is the last two bytes of A's next-IFD offset", true)] + [DataRow ("B starts on the last byte of A's next-IFD offset", true)] + [DataRow ("a pointer whose count's second byte is A's first byte", true)] + public void Edit_TablesThatTouchAnEditedTableAtItsEdge_AreRefusedWhenTheEditChangesThem (string shape, bool refused) + { + const int Ifd0 = 8, A = 40, Value = 140; + var aEnd = A + 2 + 24 + 4; + var comment = (0x9286, 7, SecretUc.Length, Value); + var digitized = (0x9004, 2, 20, Value + 24); + var tiff = new TiffBuilder (Value + 48, bigEndian: false).Header (Ifd0).Bytes (Value, SecretUc).Bytes (Value + 24, "2001:01:01 01:01:01\0"u8); + switch (shape) { + case "B's count is the last two bytes of A's next-IFD offset": + tiff.Table (A, [comment, (0x9003, 2, 20, Value + 24)], next: 0x00020000).Table (aEnd - 2, [digitized, digitized]); + tiff.Table (Ifd0, [(0x8769, 4, 1, A), (0x8769, 4, 1, aEnd - 2)]); + break; + case "B starts on the last byte of A's next-IFD offset": + tiff.Table (A, [comment, (0x9003, 2, 20, Value + 24)], next: 0x02000000).Table (aEnd - 1, [digitized, digitized]); + tiff.U16 (aEnd - 1, 2); + tiff.Table (Ifd0, [(0x8769, 4, 1, A), (0x8769, 4, 1, aEnd - 1)]); + break; + default: + // Byte 39 is 0xFF: with A's count 2 as the second byte, the pointer reads 767 entries, which do not fit. + tiff.Table (A, [comment, (0x9003, 2, 20, Value + 24)]).Bytes (A - 1, [0xFF]); + tiff.Table (Ifd0, [(0x8769, 4, 1, A), (0x8769, 4, 1, A - 1)]); + break; + } + + var data = tiff.ToArray (); + var input = InCarrier ("png", data); + var file = Open (input, "a.png"); + file.Tag!.Comment = "New"; + + var fs = new MockFileSystem (); + var save = file.SaveToFile ("/a.png", fs); + + Assert.AreEqual (!refused, save.IsSuccess, $"{shape}: {save.Error}"); + if (!refused) { + // A's count 1 leaves the pointer at 511 entries, which still do not fit: only the copy changes. + AssertOnlyTheCopiesAreGone (data, ExifOf (file.Render ().ToArray ()), shape, 0x9286); + return; + } + + Assert.IsFalse (fs.FileExists ("/a.png")); + CollectionAssert.AreEqual (input, file.Render ().ToArray (), $"{shape}: the file is unchanged"); + } + + // Tables that overlap (nothing compacted) and hold exactly as many entries as the bound allows (one per 12 + // bytes of data) are within it: an edit with nothing to remove saves. + [TestMethod] + public void Edit_TablesExactlyAtTheEntryBound_Save () + { + // IFD0 (2 entries) at 8; A (2 entries) at 38, on IFD0's next offset; B at 50, inside A, its count 1 taken + // from A's first entry. 5 entries in 68 bytes: 68 / 12 = 5. + var tiff = new TiffBuilder (68, bigEndian: false).Header (8) + .Table (8, [(0x8769, 4, 1, 38), (0x8769, 4, 1, 50)]) + .Table (38, [(0x9003, 7, 4, 0x00010000), (0x9004, 7, 4, 0x31303032)]) + .ToArray (); + Assert.AreEqual (68 / 12, ExifReaderModel.AnyReader (tiff).Entries, "the tables hold exactly the bound"); + var file = Open (InCarrier ("png", tiff), "a.png"); + file.Tag!.Comment = "New"; + + var save = file.SaveToFile ("/a.png", new MockFileSystem ()); + + Assert.IsTrue (save.IsSuccess, save.Error); + CollectionAssert.AreEqual (tiff, ExifOf (file.Render ().ToArray ())); + } + + // The same bound with a copy to remove: IFD0 (3 entries, one an inline UserComment) at 8; A (2 entries) at 50, on + // IFD0's next offset; B at 62, inside A, its count 1 taken from A's first entry. 6 entries in 80 bytes: 80 / 12 = 6. + // Within the bound the walk runs and the copy is removed (past it, the block's UserComment tag would refuse it). + [TestMethod] + public void Edit_RemovesTheCopy_InTablesExactlyAtTheEntryBound () + { + var tiff = new TiffBuilder (80, bigEndian: false).Header (8) + .Table (8, [(0x8769, 4, 1, 50), (0x8769, 4, 1, 62), (0x9286, 7, 4, 0x64636261)], next: 50) + .Table (50, [(0x9003, 7, 4, 0x00010000), (0x9004, 7, 4, 0x31303032)]) + .ToArray (); + Assert.AreEqual (80 / 12, ExifReaderModel.AnyReader (tiff).Entries, "the tables hold exactly the bound"); + var file = Open (InCarrier ("png", tiff), "a.png"); + file.Tag!.Comment = "New"; + + var save = file.SaveToFile ("/a.png", new MockFileSystem ()); + + Assert.IsTrue (save.IsSuccess, save.Error); + AssertOnlyTheCopiesAreGone (tiff, ExifOf (file.Render ().ToArray ()), "at the bound", 0x9286); + } + + // Pointer offsets exactly at the bound (one per 4 bytes of data) are within it: the edit saves and removes the + // copy. The Exif IFD pointer, two SubIFD arrays over the zeroed tail (32 and 30 offsets) and one inline SubIFD + // offset: 64 in 256 bytes. + [TestMethod] + public void Edit_PointerOffsetsExactlyAtTheBound_Save () + { + const int Ifd0 = 8, Exif = 70, Values = 96, Tail = 128; + var tiff = new TiffBuilder (256, bigEndian: false).Header (Ifd0) + .Table (Ifd0, [(0x8769, 4, 1, Exif), (0x014A, 4, 32, Tail), (0x014A, 4, 30, Tail + 4), (0x014A, 4, 1, 0)]) + .Table (Exif, [(0x9286, 7, SecretUc.Length, Values)]).Bytes (Values, SecretUc).ToArray (); + Assert.AreEqual (256 / 4, ExifReaderModel.AnyReader (tiff).PointerValues, "the pointer offsets are exactly the bound"); + var file = Open (InCarrier ("png", tiff), "a.png"); + file.Tag!.Comment = "New"; + + var save = file.SaveToFile ("/a.png", new MockFileSystem ()); + + Assert.IsTrue (save.IsSuccess, save.Error); + AssertOnlyTheCopiesAreGone (tiff, ExifOf (file.Render ().ToArray ()), "at the SubIFD bound", 0x9286); + } + + // A refusal names every changed field whose copy it could not update. + [TestMethod] + public void Edit_RefusalNamesEveryFieldItCouldNotUpdate () + { + const int Ifd0 = 8, A = 40, B = A + 12, Values = 100; + var tiff = new TiffBuilder (Values + 48, bigEndian: false).Header (Ifd0) + .Table (A, [(0x9000, 7, 4, 0x00023230), (0x9286, 7, SecretUc.Length, Values), (0x013B, 2, 6, Values + 24)]) + .Table (Ifd0, [(0x8769, 4, 1, A), (0x8769, 4, 1, B)]).Bytes (Values, SecretUc).Bytes (Values + 24, "Jane\0\0"u8).ToArray (); + var file = Open (InCarrier ("png", tiff), "a.png"); + file.Tag!.Artist = "New"; + file.Tag!.Comment = "New"; + + var save = file.SaveToFile ("/a.png", new MockFileSystem ()); + + Assert.IsFalse (save.IsSuccess); + StringAssert.Contains (save.Error, "its copy of Artist, Comment cannot be updated"); + } + // A table some reader reads (B, at 44) lies inside the Exif IFD the edit compacts (A, at 40), its one entry's + // value offset on A's removed UserComment entry: 0x00079286, past the data, so no reader shows that value. Once A + // is compacted, A's next offset (200) lands there, and B's value would be the 20 bytes at 200, which every reader + // would show. The edit is refused, and nothing is written. + [TestMethod] + public void Edit_ThatMovesAValueOffsetFromPastTheDataIntoIt_IsRefused () + { + const int A = 40, B = 44; + var tiff = new TiffBuilder (260).Header (8).Table (8, [(0x8769, 4, 1, A), (0x8769, 4, 1, B)]) + .Table (A, [(0x0100, 1, 0x00029003, 20), (0x9286, 7, 0, 0)], next: 200).ToArray (); + var model = ExifReaderModel.Of (tiff); + Assert.AreEqual (1, model.Tables.Single (t => t.At == B).Count, "B holds one entry"); + Assert.AreEqual (0x00079286, model.U32 (B + 2 + 8), "B's value offset is A's UserComment tag and type"); + var input = InCarrier ("png", tiff); + var file = Open (input, "a.png"); + file.Tag!.Comment = "New"; + + var save = file.SaveToFile ("/a.png", new MockFileSystem ()); + + Assert.IsFalse (save.IsSuccess, "saved"); + CollectionAssert.AreEqual (tiff, ExifOf (file.Render ().ToArray ()), "nothing written"); + } + // The same shape at the data's end, B's entry typed SSHORT (A's first entry then counts 0x00089003 bytes, past the + // data). B's 40-byte value moves from past the data (at 0x00079286) to 200, ending at the data's last byte, where + // every reader shows it; or from ending at the data's last byte (the data is 0x00079286 + 40 bytes) to past it (A's + // next offset 0x7FFF0000), so a value readers show is gone. Both are refused. + [TestMethod] + [DataRow (240, 200)] + [DataRow (0x00079286 + 40, 0x7FFF0000)] + public void Edit_ThatMovesAValueOffsetAcrossTheDataEnd_IsRefused (int length, long next) + { + const int A = 40, B = 44; + var tiff = new TiffBuilder (length).Header (8).Table (8, [(0x8769, 4, 1, A), (0x8769, 4, 1, B)]) + .Table (A, [(0x0100, 1, 0x00089003, 20), (0x9286, 7, 0, 0)], next: next).ToArray (); + var input = InCarrier ("png", tiff); + var file = Open (input, "a.png"); + file.Tag!.Comment = "New"; + + var save = file.SaveToFile ("/a.png", new MockFileSystem ()); + + Assert.IsFalse (save.IsSuccess, "saved"); + CollectionAssert.AreEqual (tiff, ExifOf (file.Render ().ToArray ()), "nothing written"); + } + + // The reason names the structure the edit would rewrite, whatever else overlaps. IFD0 names the Exif IFD (at 200, + // count 2) and also the byte before it, where the count reads 512 and the table does not fit; compacting the + // Exif IFD to one entry makes that count 256, which fits. A GPS table and IFD1 overlap each other elsewhere, but + // neither is rewritten, so the reason is the pointer into the middle of the Exif IFD, not overlapping tables. + [TestMethod] + public void Edit_RefusalReason_IsThePointerIntoTheTableItCompacts_NotOtherOverlaps () + { + const int Gps = 100, Exif = 200, Value = 300; + var tiff = new TiffBuilder (4000).Header (8) + .Table (8, [(0x8769, 4, 1, Exif), (0x8769, 4, 1, Exif - 1), (0x8825, 4, 1, Gps)], next: Gps + 2) + .Table (Gps, [(0x0001, 2, 2, 0x4E)], next: null).U32 (Gps + 14, 0).U16 (Gps + 18, 0) + .Table (Exif, [(0x9286, 7, SecretUc.Length, Value), (0x9003, 2, 4, 0x30303032)]).Bytes (Value, SecretUc).ToArray (); + var model = ExifReaderModel.Of (tiff); + Assert.IsTrue (model.Tables.Any (t => t.At == Gps + 2), "fixture: IFD1 overlaps the GPS table"); + CollectionAssert.Contains (model.Unread, (long)Exif - 1, "fixture: no table fits at 199"); + var file = Open (InCarrier ("png", tiff), "a.png"); + file.Tag!.Comment = "New"; + + var save = file.SaveToFile ("/a.png", new MockFileSystem ()); + + Assert.IsFalse (save.IsSuccess, "the edit would make a table readable at 199"); + StringAssert.Contains (save.Error, "an IFD pointer into the middle of another IFD table"); + } + // A refusal with no shape that names it gets the general reason: the Exif IFD's GPS pointer holds four SHORT + // values out of line, inside the Exif IFD on its third entry, whose tag (100) is the GPS table's offset. Removing + // the UserComment, the first entry, moves the third entry down, and the first value becomes the next-IFD offset + // (0): the GPS table would no longer be read. (In an Exif IFD, no reader takes the pointer's field as an offset.) + [TestMethod] + public void Edit_ThatWouldLoseATableNoNamedShapeExplains_IsRefusedWithTheGeneralReason () + { + const int Exif = 40, Gps = 100, Value = 140; + var tiff = new TiffBuilder (Value + 40).Header (8).Table (8, [(0x8769, 4, 1, Exif)]) + .Table (Exif, [(0x9286, 7, SecretUc.Length, Value), (0x8825, 3, 4, Exif + 2 + 24), (Gps, 3, 1, 1)]) + .Table (Gps, [(0x0001, 2, 2, 0x4E)]).Bytes (Value, SecretUc).ToArray (); + Assert.IsTrue (ExifReaderModel.Of (tiff).Tables.Any (t => t.At == Gps), "fixture: the GPS table is read"); + var file = Open (InCarrier ("png", tiff), "a.png"); + file.Tag!.Comment = "New"; + + var save = file.SaveToFile ("/a.png", new MockFileSystem ()); + + Assert.IsFalse (save.IsSuccess); + StringAssert.Contains (save.Error, ExifEditor.StructureWouldChange); + Assert.AreEqual (save.Error.IndexOf ("Comment", StringComparison.Ordinal), save.Error.LastIndexOf ("Comment", StringComparison.Ordinal)); + } + + [TestMethod] + public void Comment_OfAJpegThatIsNotTiff_NamesTheExifBlock () + { + var block = new byte[8]; + "XX\0*"u8.CopyTo (block); + block[4] = 0x86; + block[5] = 0x92; + block[6] = 0x07; + var input = InCarrier ("jpeg", block); + var file = Open (input, "a.jpg"); + file.Tag!.Comment = "New"; + + var save = file.SaveToFile ("/a.jpg", new MockFileSystem ()); + + Assert.IsFalse (save.IsSuccess); + Assert.AreEqual ("The JPEG Exif block is not a TIFF structure, so its copy of Comment cannot be updated.", save.Error); + CollectionAssert.AreEqual (input, file.Render ().ToArray ()); + } +} diff --git a/tests/TagLibSharp2.Tests/Image/ExifEditScalingTests.cs b/tests/TagLibSharp2.Tests/Image/ExifEditScalingTests.cs new file mode 100644 index 00000000..47c4c9a5 --- /dev/null +++ b/tests/TagLibSharp2.Tests/Image/ExifEditScalingTests.cs @@ -0,0 +1,542 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Text; +using System.Xml.Linq; +using TagLibSharp2.Core; +using TagLibSharp2.Image; +using TagLibSharp2.Image.Exif; +using TagLibSharp2.Image.Tiff; +using TagLibSharp2.Image.Xmp; +using TagLibSharp2.Tests.Core; +using TagLibSharp2.Tests.Kit; +using static TagLibSharp2.Tests.Image.ExifTestData; +using static TagLibSharp2.Tests.Image.ImageTestBuilder; + +namespace TagLibSharp2.Tests.Image; + +/// The Exif edit walks are linear in the entries: step counts at growing sizes for the worst shapes. +[TestClass] +[TestCategory ("Unit")] +public class ExifEditScalingTests +{ + // N copies of XPComment in IFD0 and N kept entries in IFD1: one sort and a binary search per removed value. + static long ExifRemovalSteps (int n) + { + const int Header = 8; + var ifd0 = Header; + var ifd1 = ifd0 + 2 + (12 * n) + 4; + var values = ifd1 + 2 + (12 * n) + 4; + var data = new byte[values + (16 * n)]; + data[0] = (byte)'I'; + data[1] = (byte)'I'; + data[2] = 42; + BitConverter.GetBytes (ifd0).CopyTo (data, 4); + BitConverter.GetBytes ((ushort)n).CopyTo (data, ifd0); + BitConverter.GetBytes ((ushort)n).CopyTo (data, ifd1); + BitConverter.GetBytes (ifd1).CopyTo (data, ifd0 + 2 + (12 * n)); + for (var k = 0; k < n; k++) { + foreach (var (table, id, value) in new[] { (ifd0, 0x9C9C, values + (16 * k)), (ifd1, 0x0131, values + (16 * k) + 8) }) { + var at = table + 2 + (12 * k); + BitConverter.GetBytes ((ushort)id).CopyTo (data, at); + BitConverter.GetBytes ((ushort)2).CopyTo (data, at + 2); + BitConverter.GetBytes (8).CopyTo (data, at + 4); + BitConverter.GetBytes (value).CopyTo (data, at + 8); + } + } + + var tag = new ImageTag (MediaFormat.Png, (ImageStores)0x3F); + tag.ReadField ((ImageStores)32, "Old"); + tag.Comment = "New"; + IfdSteps.Count = 0; + Assert.IsTrue (ExifEditor.TryRemove (data, 0, tag, "eXIf", out var changed, out var error), error); + Assert.IsTrue (changed); + return IfdSteps.Count; + } + + static readonly int[] ExifSizes = [1000, 2000, 4000, 8000]; + + [TestMethod] + public void Edit_ExifRemoval_IsLinearithmicInTheEntries () + { + var steps = ExifSizes.Select (n => (N: n, Steps: ExifRemovalSteps (n))).ToList (); + // ExifSteps counts every entry visit and every read or write of the removal marks and the protected + // ranges, so a scan of either per entry (quadratic: about 64x for 8x the entries) shows here. + // 9 is the measured constant after the removed-versus-protected check (N=1000 took 82,973 steps; + // 8 * N * ceil(log2 N) is 80,000). A scan per entry is still about 64x at 8x the entries. + foreach (var (n, count) in steps) + Assert.IsTrue (count <= 9L * n * (long)Math.Ceiling (Math.Log2 (n)), $"N={n}: {count} steps"); + Assert.IsTrue (steps[^1].Steps < 16 * steps[0].Steps, $"8x the entries took {steps[^1].Steps / (double)steps[0].Steps:F1}x the steps"); + } + + // The scan for the field's tags is one pass: steps grow with the block, not faster (N and 4N bytes, no tag). + [TestMethod] + public void Edit_OfABlockThatIsNotClassicTiff_ScansInLinearSteps () + { + long Steps (int size) + { + var block = new byte[size]; + "XX\0*"u8.CopyTo (block); + var file = Open (InCarrier ("png", block), "a.png"); + file.Tag!.Comment = "New"; + IfdSteps.Count = 0; + Assert.IsTrue (file.SaveToFile ("/a.png", new MockFileSystem ()).IsSuccess); + return IfdSteps.Count; + } + + var small = Steps (4096); + var large = Steps (16384); + Assert.IsTrue (small <= 2 * 4096, $"{small} steps for 4 KB"); + Assert.IsTrue (large <= 4.5 * small, $"{small} steps at 4 KB, {large} at 16 KB"); + } + + // The worst shapes for every walk over IFD pointers, N entries each, one UserComment to remove; little-endian. + // "self": N 0x8769 entries at IFD0 itself. "one": N at one Exif IFD of N entries. "mix": half at IFD0, half + // 0xA005 at one interoperability IFD. "many": N at N distinct one-entry Exif IFDs. "gps-mix": a third each of + // 0x8769 at IFD0, 0xA005 at one interoperability IFD and 0x8825 at one GPS IFD. + static byte[] ManyPointers (string shape, int n) + { + if (shape is "nested-chain" or "subifds" or "main-chain" or "cycles" or "subifd-arrays" or "subifd-arrays-varied") + return NestedPointers (shape, n); + const int Ifd0 = 8; + var ifd0Entries = shape == "one" ? n : n + 1; + var exif = Ifd0 + 2 + (12 * ifd0Entries) + 4; + var exifBytes = shape switch { "one" => 2 + (12 * n) + 4, "many" => 18 * n, _ => 0 }; + var interop = exif + exifBytes; + var gps = interop + 18; + var value = gps + 18; + var tiff = new TiffBuilder (value + OldOne.Length).Header (8); + var comment = (0x9286, 7, OldOne.Length, value); + switch (shape) { + case "self": + tiff.Entries (Ifd0, [.. Enumerable.Range (0, n).Select (_ => (0x8769, 4, 1, Ifd0)), comment]); + break; + case "one": + tiff.Entries (Ifd0, [.. Enumerable.Range (0, n).Select (_ => (0x8769, 4, 1, exif))]); + tiff.Entries (exif, [.. Enumerable.Range (0, n - 1).Select (k => (0x9003, 7, 4, k)), comment]); + break; + case "many": + tiff.Entries (Ifd0, [.. Enumerable.Range (0, n).Select (k => (0x8769, 4, 1, exif + (18 * k))), comment]); + for (var k = 0; k < n; k++) + tiff.Entries (exif + (18 * k), (0x9003, 7, 4, k)); + break; + case "gps-mix": + tiff.Entries (Ifd0, [.. Enumerable.Range (0, n).Select (k => (k % 3) switch { 0 => (0x8769, 4, 1, Ifd0), 1 => (0xA005, 4, 1, interop), _ => (0x8825, 4, 1, gps) }), comment]); + break; + default: + tiff.Entries (Ifd0, [.. Enumerable.Range (0, n).Select (k => k % 2 == 0 ? (0x8769, 4, 1, Ifd0) : (0xA005, 4, 1, interop)), comment]); + break; + } + + tiff.Entries (interop, (0x0001, 2, 4, 0x00383952)); + tiff.Entries (gps, (0x0001, 2, 2, 0x4E)); + return tiff.Bytes (value, OldOne).ToArray (); + } + + // The shapes of the nested walk, N tables each, the comment in the last one reached: a chain of N Exif IFDs, + // each pointing at the next ("nested-chain"); one 0x014A with N SubIFD offsets ("subifds"); IFD0 and N IFDs + // after it through next-IFD offsets ("main-chain"); N Exif IFDs that each point at the next, at IFD0 and back at + // IFD0 through their next offset ("cycles"); and N 0x014A entries that all name one array of N offsets to IFD0 + // ("subifd-arrays", N squared offsets to read, refused past the data's bound). + static byte[] NestedPointers (string shape, int n) + { + const int Ifd0 = 8; + var arrays = shape.StartsWith ("subifd-arrays", StringComparison.Ordinal); + var first = Ifd0 + (arrays ? 2 + (12 * (n + 1)) + 4 : 2 + (12 * 3) + 4); + var array = first; + var tables = array + (shape == "subifds" || arrays ? 4 * n : 0); + const int Size = 2 + (12 * 2) + 4; + var value = tables + (arrays ? 0 : Size * n); + var tiff = new TiffBuilder (value + OldOne.Length).Header (8).Bytes (value, OldOne); + var comment = (0x9286, 7, OldOne.Length, value); + var filler = (0x9003, 7, 4, 0x31303032); + int At (int k) => tables + (Size * k); + void Next (int at, int entries, int next) => tiff.Bytes (at + 2 + (12 * entries), BitConverter.GetBytes (next)); + switch (shape) { + case "nested-chain": + tiff.Entries (Ifd0, (0x8769, 4, 1, At (0)), filler); + for (var k = 0; k < n; k++) + tiff.Entries (At (k), k == n - 1 ? comment : (0x8769, 4, 1, At (k + 1)), filler); + break; + case "subifds": + tiff.Entries (Ifd0, (0x014A, 4, n, array), filler); + for (var k = 0; k < n; k++) { + tiff.Bytes (array + (4 * k), BitConverter.GetBytes (At (k))); + tiff.Entries (At (k), k == n - 1 ? comment : filler, filler); + } + + break; + case "main-chain": + tiff.Entries (Ifd0, filler, filler); + Next (Ifd0, 2, At (0)); + for (var k = 0; k < n; k++) { + tiff.Entries (At (k), k == n - 1 ? comment : filler, filler); + if (k < n - 1) + Next (At (k), 2, At (k + 1)); + } + + break; + case "cycles": + tiff.Entries (Ifd0, (0x8769, 4, 1, At (0)), (0x014A, 4, 1, At (0)), comment); + Next (Ifd0, 3, At (0)); + for (var k = 0; k < n; k++) { + tiff.Entries (At (k), (0x8769, 4, 1, At ((k + 1) % n)), (0x014A, 4, 1, Ifd0)); + Next (At (k), 2, Ifd0); + } + + break; + case "subifd-arrays-varied": + // Each entry names the same array with another length: about N squared / 2 offsets, past the bound. + tiff.Entries (Ifd0, [.. Enumerable.Range (0, n).Select (k => (0x014A, 4, k + 2, array)), comment]); + for (var k = 0; k < n; k++) + tiff.Bytes (array + (4 * k), BitConverter.GetBytes (Ifd0)); + break; + default: + tiff.Entries (Ifd0, [.. Enumerable.Range (0, n).Select (_ => (0x014A, 4, n, array)), comment]); + for (var k = 0; k < n; k++) + tiff.Bytes (array + (4 * k), BitConverter.GetBytes (Ifd0)); + break; + } + + return tiff.ToArray (); + } + + static byte[] ManyPointersFile (string carrier, string shape, int n) => carrier == "png" + ? Png (PngChunk ("eXIf", ManyPointers (shape, n)), Text ("Comment", "c")) + : Jpeg (JpegExif (ManyPointers (shape, n)), JpegSegment (0xFE, "c"u8.ToArray ())); + + static long EditSteps (string carrier, string shape, int n) + { + var file = Open (ManyPointersFile (carrier, shape, n), carrier == "png" ? "a.png" : "a.jpg"); + file.Tag!.Comment = "New"; + IfdSteps.Count = 0; + var output = file.Render ().ToArray (); + Assert.IsTrue (output.AsSpan ().IndexOf ("old comment one"u8) < 0, $"{carrier} {shape} N={n}: the comment is removed"); + return IfdSteps.Count; + } + + // However many IFD0 entries point at a table, a Comment edit walks it once: the steps and the allocation + // grow linearly (with a sort's log factor) in the entries, for PNG eXIf and JPEG APP1 (capped at 64 KB). + [TestMethod] + [DoNotParallelize] + [DataRow ("png", "self", 1000)] + [DataRow ("png", "one", 1000)] + [DataRow ("png", "mix", 1000)] + [DataRow ("jpeg", "self", 1000)] + [DataRow ("jpeg", "one", 500)] + [DataRow ("jpeg", "mix", 1000)] + public void Edit_ManyPointersToOneTable_IsLinearInTheEntries (string carrier, string shape, int n) + { + var small = EditSteps (carrier, shape, n); + var large = EditSteps (carrier, shape, 4 * n); + Assert.IsTrue (large <= 40L * 4 * n, $"{carrier} {shape}: {large} steps for {4 * n} pointers"); + Assert.IsTrue (large < 6 * small, $"{carrier} {shape}: 4x the pointers took {large / (double)small:F1}x the steps"); + Bounds.AssertLinearAllocation (size => ManyPointersFile (carrier, shape, size), data => { + var file = Open (data, carrier == "png" ? "a.png" : "a.jpg"); + file.Tag!.Comment = "New"; + _ = file.Render (); + }, n, runs: 3); + } + + // A version-65536 Apple gain map behind the primary, so Clear walks the Exif for the maker-note headroom. + static byte[] AppleGainMapImage () => Jpeg (JpegXmp ("")); + + static byte[] WalkInput (string carrier, string shape, int n) => carrier == "png" + ? Png (PngChunk ("eXIf", ManyPointers (shape, n)), Text ("Comment", "c")) + : MpfJpeg (Concat (JpegExif (ManyPointers (shape, n)), JpegSegment (0xFE, "c"u8.ToArray ())), [], AppleGainMapImage (), out _); + + static void RunWalk (string op, byte[] data, string name) + { + var file = Open (data, name); + if (op == "read") { + _ = file.ImageProperties; + return; + } + + if (op == "clear") + file.Tag!.Clear (); + else + file.Tag!.Comment = "New"; + _ = file.Render (); + } + + // Every walk over IFD pointers and tables (Clear with its maker-note headroom walk, the Comment edit) stays + // linear in the entries for every worst shape, in PNG eXIf and in a JPEG APP1 behind an Apple gain map: the + // step count at 4N is under 6x the count at N, and the allocation grows linearly over N, 2N and 4N. The read + // rows pin that opening such a PNG or JPEG stays linear; it walks no IFD (Exif values are not read). The TIFF + // and DNG IFD walk is pinned by Tiff_IfdChainEndingWithoutANextOffset_IsReadLinearly and by the "tiff IFD chain" + // row of ReadAndRewrite_AllocateLinearly. + public static IEnumerable Walks () + { + foreach (var op in new[] { "read", "clear", "edit" }) { + foreach (var shape in new[] { "self", "one", "mix", "many", "gps-mix", "nested-chain", "subifds", "main-chain", "cycles", "subifd-arrays", "subifd-arrays-varied" }) { + yield return [op, "png", shape, 600]; + yield return [op, "jpeg", shape, 300]; + } + } + } + + [TestMethod] + [DoNotParallelize] + [DynamicData (nameof (Walks))] + public void EveryIfdWalk_IsLinearInTheEntries (string op, string carrier, string shape, int n) + { + var name = carrier == "png" ? "a.png" : "a.jpg"; + long Steps (int size) + { + var data = WalkInput (carrier, shape, size); + RunWalk (op, data, name); + IfdSteps.Count = 0; + RunWalk (op, data, name); + return IfdSteps.Count; + } + + var small = Steps (n); + var large = Steps (4 * n); + var row = $"{op} {carrier} {shape}"; + if (op == "edit" || (op == "clear" && carrier == "jpeg")) + Assert.IsTrue (small > 0, $"{row}: the walk ran"); + // 55 is the measured cost of a successful edit: the plainness pass, marking ranges, and the + // removed-versus-protected check. jpeg cycles at 1,200 entries took 64,881 steps. + Assert.IsTrue (large <= 55L * 4 * n, $"{row}: {large} steps for {4 * n} entries"); + Assert.IsTrue (large <= Math.Max (6 * small, 64), $"{row}: 4x the entries took {large / (double)Math.Max (small, 1):F1}x the steps"); + Bounds.AssertLinearAllocation (size => WalkInput (carrier, shape, size), data => RunWalk (op, data, name), n, runs: 3); + + // The edit reaches every copy the reader model sees, however deep the table that holds it. + if (op == "edit") { + var input = WalkInput (carrier, shape, n); + var file = Open (input, name); + file.Tag!.Comment = "New"; + var output = file.Render ().ToArray (); + Assert.AreEqual (1, UserCommentsInEveryExifIfd (ExifOf (input)).Count, $"{row}: the input holds one copy"); + if (shape == "subifd-arrays-varied") + CollectionAssert.AreEqual (input, output, $"{row}: past the bound on SubIFD offsets, refused"); + else + Assert.AreEqual (0, UserCommentsInEveryExifIfd (ExifOf (output)).Count, $"{row}: no copy is left"); + } + } + + // N tables share one strip, tile or thumbnail array of N values. A comment edit refuses that structure before + // the values are read, in linear steps. Title removes nothing and does not read them either. + [TestMethod] + [DoNotParallelize] + [DataRow ("png", "comment", "strips")] + [DataRow ("png", "title", "strips")] + [DataRow ("jpeg", "comment", "strips")] + [DataRow ("jpeg", "title", "strips")] + [DataRow ("png", "comment", "tiles")] + [DataRow ("png", "comment", "thumb")] + [DataRow ("png", "comment", "chain")] + public void Edit_SharedStripArray_IsLinearInTheTables (string carrier, string field, string shape) + { + const int n = 250; + var small = SharedStripSteps (carrier, field, shape, n); + var large = SharedStripSteps (carrier, field, shape, 4 * n); + var row = $"{field} {carrier} {shape}"; + Assert.IsTrue (small > 0, $"{row}: the walk ran"); + // The refusal walks each table and does not read the shared array. 320 steps a table is above that. + Assert.IsTrue (large <= 320L * 4 * n, $"{row}: {large} steps for {4 * n} tables"); + Assert.IsTrue (large <= Math.Max (6 * small, 64), $"{row}: 4x the tables took {large / (double)small:F1}x the steps ({small} -> {large})"); + Bounds.AssertLinearAllocation (size => SharedStripFile (carrier, shape, size), data => RunSharedStrip (field, data, carrier == "png" ? "a.png" : "a.jpg"), n, runs: 3); + } + + // The reported sizes: about 85 KB at 2,000 tables and 169 KB at 4,000, each table sharing one strip array. + // Recording a range per table exhausts a 1 GB heap at the larger one. The edit refuses and leaves the comment. + [TestMethod] + [DataRow (2000)] + [DataRow (4000)] + public void Edit_SharedStripArray_AtTheReportedSizes_RefusesTheComment (int n) + { + var data = SharedStripFile ("png", "strips", n); + Assert.IsTrue (data.Length > (n == 2000 ? 80_000 : 160_000), $"N={n}: {data.Length} bytes"); + var output = RunSharedStrip ("comment", data, "a.png"); + Assert.AreEqual (1, UserCommentsInEveryExifIfd (ExifOf (output)).Count, $"N={n}: the comment stays"); + } + + static byte[] SharedStripFile (string carrier, string shape, int n) => carrier == "png" + ? Png (PngChunk ("eXIf", SharedStripTiff (shape, n)), Text ("Comment", "c")) + : Jpeg (JpegExif (SharedStripTiff (shape, n)), JpegSegment (0xFE, "c"u8.ToArray ())); + + static long SharedStripSteps (string carrier, string field, string shape, int n) + { + var data = SharedStripFile (carrier, shape, n); + IfdSteps.Count = 0; + var output = RunSharedStrip (field, data, carrier == "png" ? "a.png" : "a.jpg"); + var comments = UserCommentsInEveryExifIfd (ExifOf (output)).Count; + Assert.AreEqual (1, comments, $"{field} {carrier} {shape} N={n}: the shared array is not plain, and a title removes nothing"); + return IfdSteps.Count; + } + + static byte[] RunSharedStrip (string field, byte[] data, string name) + { + // JPEG stores only the comment, so assigning Title never reaches the editor. Measure that walk on the TIFF. + if (field == "title" && name.EndsWith (".jpg", StringComparison.Ordinal)) { + var tiff = ExifOf (data); + var tag = new ImageTag (MediaFormat.Jpeg, (ImageStores)0x3F); + tag.ReadField (ImageStores.Title, "Old"); + tag.Title = "New"; + Assert.IsTrue (ExifEditor.TryRemove (tiff, 0, tag, "jpeg APP1", out var changed, out var error), error); + Assert.IsFalse (changed, "jpeg title: the TIFF holds no title"); + return data; + } + + var file = Open (data, name); + if (field == "comment") + file.Tag!.Comment = "New"; + else + file.Tag!.Title = "New"; + var save = file.SaveToFile ("/out", new MockFileSystem ()); + if (field == "comment") { + Assert.IsFalse (save.IsSuccess, save.Error); + StringAssert.Contains (save.Error, "more than once"); + return data; + } + + Assert.IsTrue (save.IsSuccess, save.Error); + return file.Render ().ToArray (); + } + + // IFD0 points at an Exif IFD that holds the UserComment, and at N tables that share one N-value offset array + // and one N-value length array: a SubIFD array, or a next-IFD chain. + static byte[] SharedStripTiff (string shape, int n) + { + var (offTag, lenTag) = shape switch { + "tiles" => (0x0144, 0x0145), + "thumb" => (0x0201, 0x0202), + _ => (0x0111, 0x0117), + }; + var chain = shape == "chain"; + const int Ifd0 = 8; + var ifd0Entries = chain ? 1 : 2; + var exifAt = Ifd0 + 2 + (12 * ifd0Entries) + 4; + var arrayAt = exifAt + 18; + var tablesAt = chain ? arrayAt : arrayAt + (4 * n); + const int TableSize = 30; + var offsetsAt = tablesAt + (TableSize * n); + var lengthsAt = offsetsAt + (4 * n); + var commentAt = lengthsAt + (4 * n); + var tiff = new TiffBuilder (commentAt + OldOne.Length).Header (Ifd0); + if (chain) + tiff.Table (Ifd0, [(0x8769, 4, 1, exifAt)], next: tablesAt); + else + tiff.Table (Ifd0, [(0x8769, 4, 1, exifAt), (0x014A, 4, n, arrayAt)]); + tiff.Table (exifAt, [(0x9286, 7, OldOne.Length, commentAt)]); + for (var i = 0; i < n; i++) { + var at = tablesAt + (TableSize * i); + var next = chain && i + 1 < n ? at + TableSize : 0L; + tiff.Table (at, [(offTag, 4, n, offsetsAt), (lenTag, 4, n, lengthsAt)], next); + if (!chain) + tiff.U32 (arrayAt + (4 * i), at); + } + + for (var k = 0; k < n; k++) + tiff.U32 (offsetsAt + (4 * k), 8).U32 (lengthsAt + (4 * k), 4); + return tiff.Bytes (commentAt, OldOne).ToArray (); + } + + // A plain PNG eXIf chain of N one-entry IFDs (IFD0, then next, then next), each holding one inline value of + // the field. A Description, Artist, Copyright or Comment edit compacts every table. The compacted-table check + // is one sorted lookup per protected range: 4x the tables stays under 6x the steps. A scan of the compacted + // list per range is about 16x. + [TestMethod] + [DoNotParallelize] + [DataRow ("description", false)] + [DataRow ("artist", false)] + [DataRow ("copyright", false)] + [DataRow ("comment", false)] + [DataRow ("description", true)] + public void Edit_CompactedIfdChain_IsLinearInTheTables (string field, bool bigEndian) + { + const int n = 2000; + long Steps (int size) + { + var data = CompactedChainPng (field, size, bigEndian); + var file = Open (data, "a.png"); + SetChainField (file.Tag!, field); + IfdSteps.Count = 0; + var save = file.SaveToFile ("/a.png", new MockFileSystem ()); + var steps = IfdSteps.Count; + Assert.IsTrue (save.IsSuccess, $"{field} {(bigEndian ? "BE" : "LE")} N={size}: {save.Error}"); + var output = file.Render ().ToArray (); + var row = $"{field} {(bigEndian ? "BE" : "LE")} N={size}"; + // Compaction rewrites each table in place, so the chunk length stays and the entry is gone. + Assert.AreEqual (size, CountChainEntries (PngPayload (data, "eXIf"), field, bigEndian), $"{row}: the input holds one entry a table"); + Assert.AreEqual (0, CountChainEntries (PngPayload (output, "eXIf"), field, bigEndian), $"{row}: every table is compacted"); + return steps; + } + + var small = Steps (n); + var large = Steps (4 * n); + var row = $"{field} {(bigEndian ? "BE" : "LE")}"; + // 90 steps a table is the measured ceiling of one successful edit (8,000 tables took 695,238 steps). + // A scan of the compacted list per protected range took 32,475,618 steps at the same size. + Assert.IsTrue (large <= 90L * 4 * n, $"{row}: {large} steps for {4 * n} tables ({small} at {n})"); + Assert.IsTrue (large <= Math.Max (6 * small, 64), $"{row}: 4x the tables took {large / (double)small:F1}x the steps ({small} -> {large})"); + Bounds.AssertLinearAllocation (size => CompactedChainPng (field, size, bigEndian), data => { + var file = Open (data, "a.png"); + SetChainField (file.Tag!, field); + _ = file.Render (); + }, n, runs: 3); + } + + static void SetChainField (Tag tag, string field) + { + switch (field) { + case "artist": + tag.Artist = "x"; + break; + case "copyright": + tag.Copyright = "x"; + break; + case "comment": + tag.Comment = "x"; + break; + default: + tag.Description = "x"; + break; + } + } + + // IFD0 and N-1 tables after it. Each table is 18 bytes: a count, one inline entry, and a next offset. + static byte[] CompactedChainPng (string field, int n, bool bigEndian) + { + var (tag, type, count, value) = field switch { + "artist" => (0x013B, 2, 4L, InlineAscii ("abc\0")), + "copyright" => (0x8298, 2, 4L, InlineAscii ("abc\0")), + "comment" => (0x9C9C, 1, 4L, InlineAscii ("abc\0")), + _ => (0x010E, 2, 4L, InlineAscii ("abc\0")), + }; + var length = 8 + (18 * n); + var tiff = new TiffBuilder (length, bigEndian).Header (8); + for (var k = 0; k < n; k++) { + var at = 8 + (18 * k); + var next = k + 1 < n ? (long)(at + 18) : 0L; + tiff.Table (at, [(tag, type, count, value)], next); + } + + return Png (PngChunk ("eXIf", tiff.ToArray ())); + } + + // Four ASCII bytes stored in the entry's value field, in the TIFF's byte order. + static long InlineAscii (string text) + { + var bytes = Encoding.ASCII.GetBytes (text); + return bytes[0] | (bytes[1] << 8) | (bytes[2] << 16) | (bytes[3] << 24); + } + + // How many entry headers of this field the TIFF still holds. Compaction overwrites a removed entry, so a + // compacted chain counts zero. + static int CountChainEntries (byte[] tiff, string field, bool bigEndian) + { + var (tag, type) = field switch { + "artist" => (0x013B, 2), + "copyright" => (0x8298, 2), + "comment" => (0x9C9C, 1), + _ => (0x010E, 2), + }; + var needle = bigEndian + ? new byte[] { (byte)(tag >> 8), (byte)tag, (byte)(type >> 8), (byte)type } + : new byte[] { (byte)tag, (byte)(tag >> 8), (byte)type, (byte)(type >> 8) }; + return Bytes.Count (tiff, needle); + } +} diff --git a/tests/TagLibSharp2.Tests/Image/ExifEditTests.cs b/tests/TagLibSharp2.Tests/Image/ExifEditTests.cs new file mode 100644 index 00000000..e62668e8 --- /dev/null +++ b/tests/TagLibSharp2.Tests/Image/ExifEditTests.cs @@ -0,0 +1,1717 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Text; +using System.Xml.Linq; +using TagLibSharp2.Core; +using TagLibSharp2.Image; +using TagLibSharp2.Image.Exif; +using TagLibSharp2.Image.Tiff; +using TagLibSharp2.Image.Xmp; +using TagLibSharp2.Tests.Core; +using TagLibSharp2.Tests.Kit; +using static TagLibSharp2.Tests.Image.ExifTestData; +using static TagLibSharp2.Tests.Image.ImageTestBuilder; + +namespace TagLibSharp2.Tests.Image; + +/// Removing a changed field from Exif: every table a reader reads loses its copy, and no byte other structure uses is changed. +[TestClass] +[TestCategory ("Unit")] +public partial class ExifEditTests +{ + public static IEnumerable OverlappingExif () + { + // Make and Artist share value bytes; Artist points into IFD0's table; Artist points at the header. + yield return ["shared value", (Action)((tiff, artist, make) => Array.Copy (tiff, make + 4, tiff, artist + 4, 8))]; + yield return ["into the IFD table", (Action)((tiff, artist, _) => { BitConverter.GetBytes (20).CopyTo (tiff, artist + 4); BitConverter.GetBytes (8).CopyTo (tiff, artist + 8); })]; + yield return ["into the header", (Action)((tiff, artist, _) => { BitConverter.GetBytes (8).CopyTo (tiff, artist + 4); BitConverter.GetBytes (0).CopyTo (tiff, artist + 8); })]; + } + + // A removed value that shares bytes with another value, or that lies inside an IFD table, is not plain: the edit + // is refused and nothing is written. A value that points into the header names no protected byte, so that edit saves. + [TestMethod] + [DynamicData (nameof (OverlappingExif))] + public void Edit_RemovedExifValue_NeverZeroesBytesItShares (string shape, Action corrupt) + { + var tiff = ExifTiff ([(0x010F, "CanonMake"), (0x0110, "ModelName"), (0x013B, "OldArtist")], []); + corrupt (tiff, 8 + 2 + (2 * 12), 8 + 2); + var input = Png (PngChunk ("eXIf", tiff), Text ("Author", "a")); + var file = Open (input, "a.png"); + file.Tag!.Artist = "New"; + + var save = file.SaveToFile ("/a.png", new MockFileSystem ()); + if (shape != "into the header") { + AssertUnchangedRefusal (save, input, file.Render ().ToArray (), shape); + return; + } + + Assert.IsTrue (save.IsSuccess, save.Error); + var exif = PngChunks (file.Render ().ToArray ()).Single (c => c.Type == "eXIf").Payload; + CollectionAssert.AreEqual (tiff[..8], exif[..8], $"{shape}: header"); + var values = ExifReaderModel.Of (exif).Strings (); + Assert.AreEqual ("CanonMake", values[0x010F], shape); + Assert.AreEqual ("ModelName", values[0x0110], shape); + Assert.IsFalse (values.ContainsKey (0x013B), shape); + } + + // IFD0 (Make, Artist, GPS pointer) -> IFD1, and a GPS IFD; Artist's value is also named by IFD1 or GPS. + static byte[] SharedArtistTiff (string shape) + { + var data = new byte[256]; + data[0] = (byte)'I'; + data[1] = (byte)'I'; + data[2] = 42; + const int Ifd0 = 8, Ifd1 = 8 + 2 + (3 * 12) + 4, Gps = Ifd1 + 2 + (2 * 12) + 4, Make = Gps + 2 + 12 + 4, Artist = Make + 10; + BitConverter.GetBytes (Ifd0).CopyTo (data, 4); + void Entry (int at, int tag, int type, int count, int value) + { + BitConverter.GetBytes ((ushort)tag).CopyTo (data, at); + BitConverter.GetBytes ((ushort)type).CopyTo (data, at + 2); + BitConverter.GetBytes (count).CopyTo (data, at + 4); + BitConverter.GetBytes (value).CopyTo (data, at + 8); + } + + BitConverter.GetBytes ((ushort)3).CopyTo (data, Ifd0); + Entry (Ifd0 + 2, 0x010F, 2, 10, Make); + Entry (Ifd0 + 14, 0x013B, 2, 10, Artist); + Entry (Ifd0 + 26, 0x8825, 4, 1, Gps); + BitConverter.GetBytes (Ifd1).CopyTo (data, Ifd0 + 38); + BitConverter.GetBytes ((ushort)2).CopyTo (data, Ifd1); + if (shape == "thumbnail") { + Entry (Ifd1 + 2, 0x0201, 4, 1, Artist); + Entry (Ifd1 + 14, 0x0202, 4, 1, 10); + } else { + Entry (Ifd1 + 2, 0x0131, 2, 10, shape == "IFD1 value" ? Artist : Make); + Entry (Ifd1 + 14, 0x0132, 2, 10, Make); + } + + BitConverter.GetBytes ((ushort)1).CopyTo (data, Gps); + Entry (Gps + 2, 0x0012, 2, 10, shape == "GPS value" ? Artist : Make); + "CanonMake\0"u8.CopyTo (data.AsSpan (Make)); + "OldArtist\0"u8.CopyTo (data.AsSpan (Artist)); + return data[..(Artist + 10)]; + } + + // Artist's value is also a thumbnail, an IFD1 string or a GPS string. Zeroing it would change that other use, so + // the edit is refused and the shared bytes stay. + [TestMethod] + [DataRow ("IFD1 value")] + [DataRow ("thumbnail")] + [DataRow ("GPS value")] + public void Edit_RemovedExifValue_KeepsBytesTheThumbnailIfd1OrGpsUse (string shape) + { + var tiff = SharedArtistTiff (shape); + var input = Png (PngChunk ("eXIf", tiff), Text ("Author", "a")); + var file = Open (input, "a.png"); + file.Tag!.Artist = "New"; + var save = file.SaveToFile ("/a.png", new MockFileSystem ()); + AssertUnchangedRefusal (save, input, file.Render ().ToArray (), shape); + Assert.IsTrue (tiff.AsSpan ().IndexOf ("OldArtist\0"u8) > 0, shape); + } + + static readonly byte[] FilledApp1 = [0xFF, 0xFF, 0xFF, 0xFF, 0xE1]; + + [TestMethod] + public void Jpeg_RewrittenExifSegment_KeepsTheFillBytesBeforeIt () + { + var exif = JpegExif (ExifTiff ([(0x010F, "Canon"), (0x9C9C, "Old XP comment")], [])); + var input = Jpeg (Concat ([0xFF, 0xFF, 0xFF], exif), JpegSegment (0xFE, "Old"u8.ToArray ())); + var file = Open (input, "a.jpg"); + file.Tag!.Comment = "New"; + var output = file.Render ().ToArray (); + var at = output.AsSpan ().IndexOf ("Exif\0\0"u8) - 4; + Assert.IsTrue (output.AsSpan (at - 3, 5).SequenceEqual (FilledApp1), "the three fill bytes stay before the rewritten segment"); + Assert.IsTrue (output.AsSpan ().IndexOf ("Old XP comment"u8) < 0); + } + + // ImageIO merges every Exif IFD IFD0 points at and exiftool lists each, so a Comment edit removes UserComment + // from all of them. The GPS, interoperability and thumbnail data of every IFD is protected from zeroing. + // A strip offset given twice is not plain: which bytes it names cannot be told, so that edit is refused. + [TestMethod] + [DataRow ("two Exif IFDs")] + [DataRow ("two Exif IFDs, the other way round")] + [DataRow ("the same Exif IFD twice")] + [DataRow ("the Exif IFD is IFD0")] + [DataRow ("a second GPS IFD shares the old comment's bytes")] + [DataRow ("a second Exif IFD's interoperability IFD shares them")] + [DataRow ("StripOffsets given twice")] + [DataRow ("an empty Exif IFD pointer before the real one")] + [DataRow ("StripOffsets given twice in IFD0 and in IFD1")] + [DataRow ("a kept RATIONAL value shares the old comment's bytes")] + public void Edit_RemovesTheCommentFromEveryExifIfd (string shape) + { + const int Ifd0 = 8, ExifA = 80, ExifB = 120, Gps = 160, Interop = 200, One = 240, Two = 264; + var tiff = new TiffBuilder (300).Header (8).Bytes (One, OldOne).Bytes (Two, OldTwo); + (int, int, int, int) Comment (int at, byte[] value) => (0x9286, 7, value.Length, at); + var shared = false; + switch (shape) { + case "two Exif IFDs": + tiff.Entries (Ifd0, (0x8769, 4, 1, ExifA), (0x8769, 4, 1, ExifB)).Entries (ExifA, Comment (One, OldOne)).Entries (ExifB, Comment (Two, OldTwo)); + break; + case "two Exif IFDs, the other way round": + tiff.Entries (Ifd0, (0x8769, 4, 1, ExifB), (0x8769, 4, 1, ExifA)).Entries (ExifA, Comment (One, OldOne)).Entries (ExifB, Comment (Two, OldTwo)); + break; + case "the same Exif IFD twice": + tiff.Entries (Ifd0, (0x8769, 4, 1, ExifA), (0x8769, 4, 1, ExifA)).Entries (ExifA, Comment (One, OldOne), (0x9003, 7, 4, 0x31303032), Comment (Two, OldTwo), (0x9004, 7, 4, 0x31303032)); + break; + case "the Exif IFD is IFD0": + tiff.Entries (Ifd0, (0x8769, 4, 1, Ifd0), Comment (One, OldOne), Comment (Two, OldTwo)); + break; + case "a second GPS IFD shares the old comment's bytes": + tiff.Entries (Ifd0, (0x8769, 4, 1, ExifA), (0x8825, 4, 1, Gps), (0x8825, 4, 1, Gps + 20)).Entries (ExifA, Comment (One, OldOne), Comment (Two, OldTwo)) + .Entries (Gps, (0x0001, 2, 2, 0x4E)).Entries (Gps + 20, (0x001B, 7, OldTwo.Length, Two)); + shared = true; + break; + case "a second Exif IFD's interoperability IFD shares them": + tiff.Entries (Ifd0, (0x8769, 4, 1, ExifA), (0x8769, 4, 1, ExifB)).Entries (ExifA, Comment (One, OldOne)) + .Entries (ExifB, Comment (Two, OldTwo), (0xA005, 4, 1, Interop)).Entries (Interop, (0x0002, 7, OldTwo.Length, Two)); + shared = true; + break; + case "StripOffsets given twice in IFD0 and in IFD1": + // Each table alone would stop the zeroing; two of them must too. + tiff.Entries (Ifd0, (0x8769, 4, 1, ExifA), (0x0111, 4, 1, Gps), (0x0111, 4, 1, Two)).Entries (ExifA, Comment (One, OldOne), Comment (Two, OldTwo)); + tiff.Bytes (Ifd0 + 2 + 36, BitConverter.GetBytes (ExifB)).Entries (ExifB, (0x0111, 4, 1, Gps), (0x0111, 4, 1, Two)); + shared = true; + break; + case "a kept RATIONAL value shares the old comment's bytes": + tiff.Entries (Ifd0, (0x8769, 4, 1, ExifA), (0x8825, 4, 1, Gps)).Entries (ExifA, Comment (One, OldOne), Comment (Two, OldTwo)) + .Entries (Gps, (0x0002, 5, 1, Two + 8)); + shared = true; + break; + case "an empty Exif IFD pointer before the real one": + tiff.Entries (Ifd0, (0x8769, 4, 1, 0), (0x8769, 4, 1, ExifA)).Entries (ExifA, Comment (One, OldOne), Comment (Two, OldTwo)); + break; + default: + tiff.Entries (Ifd0, (0x8769, 4, 1, ExifA), (0x0111, 4, 1, Gps), (0x0117, 4, 1, 4), (0x0111, 4, 1, Two), (0x0117, 4, 1, 4)).Entries (ExifA, Comment (One, OldOne), Comment (Two, OldTwo)); + shared = true; + break; + } + + var file = Open (Png (PngChunk ("eXIf", tiff.ToArray ()), Text ("Comment", "c")), "a.png"); + file.Tag!.Comment = "New"; + var save = file.SaveToFile ("/a.png", new MockFileSystem ()); + if (shape.StartsWith ("StripOffsets given twice", StringComparison.Ordinal)) { + Assert.IsFalse (save.IsSuccess, shape); + StringAssert.Contains (save.Error, "offset or length more than once", shape); + CollectionAssert.AreEqual (tiff.ToArray (), PngChunks (file.Render ().ToArray ()).Single (c => c.Type == "eXIf").Payload, shape); + return; + } + + // A second table's value, or a kept rational, occupies the comment's bytes. Removing the comment would change + // that structure, so the edit is refused. + if (shared) { + var input = Png (PngChunk ("eXIf", tiff.ToArray ()), Text ("Comment", "c")); + AssertUnchangedRefusal (save, input, file.Render ().ToArray (), shape); + return; + } + + Assert.IsTrue (save.IsSuccess, $"{shape}: {save.Error}"); + + var exif = PngChunks (file.Render ().ToArray ()).Single (c => c.Type == "eXIf").Payload; + Assert.AreEqual (0, UserCommentsInEveryExifIfd (exif).Count, $"{shape}: a UserComment is left"); + AssertOnlyTheCopiesAreGone (tiff.ToArray (), exif, shape, 0x9286, 0x9C9C); + if (shape == "two Exif IFDs") { + // The compacted table's freed bytes are cleared: its one entry is gone, its next offset moves up, and the + // 12 bytes after it hold nothing of the old entry. + Assert.AreEqual (0, BitConverter.ToUInt16 (exif, ExifA)); + CollectionAssert.AreEqual (new byte[16], exif[(ExifA + 2)..(ExifA + 18)], "the freed bytes are zero"); + } + + if (shape == "the same Exif IFD twice") { + // The table is compacted once: the entries kept are the two dates, in order. + Assert.AreEqual (2, BitConverter.ToUInt16 (exif, ExifA)); + Assert.AreEqual (0x9003, BitConverter.ToUInt16 (exif, ExifA + 2)); + Assert.AreEqual (0x9004, BitConverter.ToUInt16 (exif, ExifA + 14)); + } + + Assert.IsTrue (exif.AsSpan ().IndexOf ("old comment one"u8) < 0, $"{shape}: the first comment's bytes are zeroed"); + Assert.AreEqual (shared, exif.AsSpan ().IndexOf ("old comment two"u8) >= 0, $"{shape}: the second comment's bytes are kept only when another IFD uses them"); + } + + // A pointer no reader follows (its table is not inside the data) can hold no copy: the edit skips it, as Clear, + // ImageIO and exiftool do, and updates the readable tables. One row per pointer kind the edit follows. + [TestMethod] + [DataRow ("an Exif IFD pointer past the data", 0x8769)] + [DataRow ("an Exif IFD pointer whose table runs past the data", 0x8769)] + [DataRow ("a GPS IFD pointer past the data", 0x8825)] + [DataRow ("an interoperability IFD pointer past the data", 0xA005)] + [DataRow ("an IFD1 offset past the data", 0)] + [DataRow ("an IFD0 offset past the data", -1)] + public void Edit_SkipsAPointerNoReaderFollows (string shape, int tag) + { + const int Ifd0 = 8, Exif = 64, One = 120; + var bad = shape.Contains ("runs past", StringComparison.Ordinal) ? 150 : 0x7FFF_0000; + var tiff = new TiffBuilder (160).Header (8).Bytes (One, OldOne).Bytes (150, [0xFF, 0x00]); + var ifd0 = new List<(int, int, int, int)> { (0x8769, 4, 1, Exif) }; + if (tag is 0x8769 or 0x8825) + ifd0.Add ((tag, 4, 1, bad)); + tiff.Entries (Ifd0, [.. ifd0]); + var exif = new List<(int, int, int, int)> { (0x9286, 7, OldOne.Length, One) }; + if (tag == 0xA005) + exif.Add ((0xA005, 4, 1, bad)); + tiff.Entries (Exif, [.. exif]); + var data = tiff.ToArray (); + if (tag == 0) + BitConverter.GetBytes (bad).CopyTo (data, Ifd0 + 2 + (12 * ifd0.Count)); + if (tag == -1) { + // No reader reads anything of this block (exiftool: "Bad IFD0 directory"), so the edit saves it as it is. + BitConverter.GetBytes (bad).CopyTo (data, 4); + var unread = Open (Png (PngChunk ("eXIf", data), Text ("Comment", "c")), "a.png"); + unread.Tag!.Comment = "New"; + Assert.IsTrue (unread.SaveToFile ("/a.png", new MockFileSystem ()).IsSuccess, shape); + CollectionAssert.AreEqual (data, PngChunks (unread.Render ().ToArray ()).Single (c => c.Type == "eXIf").Payload, shape); + return; + } + + var file = Open (Png (PngChunk ("eXIf", data), Text ("Comment", "c")), "a.png"); + file.Tag!.Comment = "New"; + + var save = file.SaveToFile ("/a.png", new MockFileSystem ()); + + Assert.IsTrue (save.IsSuccess, $"{shape}: {save.Error}"); + var exifOut = PngChunks (file.Render ().ToArray ()).Single (c => c.Type == "eXIf").Payload; + Assert.AreEqual (0, UserCommentsInEveryExifIfd (exifOut).Count, shape); + AssertOnlyTheCopiesAreGone (data, exifOut, shape, 0x9286, 0x9C9C); + Assert.IsTrue (exifOut.AsSpan ().IndexOf ("old comment one"u8) < 0, shape); + } + + static readonly byte[] OldXp = Encoding.Unicode.GetBytes ("old xp comment\0"); + + // TIFF 6.0 §2 puts a 4-byte next-IFD offset after every table. A field edit still runs when that field is wholly + // absent (cut = 4). One, two or three bytes present are not plain, so the edit is refused and nothing is written. + // The table under test is the last thing in the data. + [TestMethod] + [DataRow ("IFD0", 4)] + [DataRow ("IFD0", 2)] + [DataRow ("Exif IFD", 4)] + [DataRow ("Exif IFD", 2)] + [DataRow ("GPS IFD", 4)] + [DataRow ("GPS IFD", 2)] + [DataRow ("interoperability IFD", 4)] + [DataRow ("interoperability IFD", 2)] + [DataRow ("IFD1", 4)] + [DataRow ("IFD1", 2)] + public void Edit_ReadsATableWhoseNextOffsetIsMissing (string table, int cut) + { + // Values first, then the tables; the table under test goes last. + const int One = 8, Xp = One + 24, Tables = 64; + var exifComment = (0x9286, 7, OldOne.Length, One); + var xpComment = (0x9C9C, 1, OldXp.Length, Xp); + var shared = (0x0002, 7, OldOne.Length, One); + var data = new List<(int At, (int, int, int, int)[] Entries, int Next)> (); + int At (int index) => Tables + (index * 60); + switch (table) { + case "IFD0": + data.Add ((At (0), [exifComment], 0)); + data.Add ((At (1), [xpComment, (0x8769, 4, 1, At (0))], 0)); + break; + case "Exif IFD": + data.Add ((At (0), [xpComment, (0x8769, 4, 1, At (1))], 0)); + data.Add ((At (1), [exifComment], 0)); + break; + case "GPS IFD": + data.Add ((At (0), [xpComment, (0x8769, 4, 1, At (1)), (0x8825, 4, 1, At (2))], 0)); + data.Add ((At (1), [exifComment], 0)); + data.Add ((At (2), [shared], 0)); + break; + case "interoperability IFD": + data.Add ((At (0), [xpComment, (0x8769, 4, 1, At (1))], 0)); + data.Add ((At (1), [exifComment, (0xA005, 4, 1, At (2))], 0)); + data.Add ((At (2), [shared], 0)); + break; + default: + data.Add ((At (0), [xpComment, (0x8769, 4, 1, At (1))], At (2))); + data.Add ((At (1), [exifComment], 0)); + data.Add ((At (2), [shared], 0)); + break; + } + + var last = data[^1]; + var length = last.At + 2 + (12 * last.Entries.Length) + 4 - cut; + var tiff = new TiffBuilder (length + cut).Header (8).Bytes (One, OldOne).Bytes (Xp, OldXp); + foreach (var (at, entries, next) in data) { + tiff.Entries (at, [.. entries]); + tiff.Bytes (at + 2 + (12 * entries.Length), BitConverter.GetBytes (next)); + } + + var bytes = tiff.ToArray ()[..length]; + var ifd0 = table == "IFD0" ? At (1) : At (0); + BitConverter.GetBytes (ifd0).CopyTo (bytes, 4); + var file = Open (Png (PngChunk ("eXIf", bytes), Text ("Comment", "c")), "a.png"); + file.Tag!.Comment = "New"; + + var save = file.SaveToFile ("/a.png", new MockFileSystem ()); + + if (cut != 4) { + Assert.IsFalse (save.IsSuccess, $"{table} cut {cut}: saved"); + StringAssert.Contains (save.Error, "cut short", table); + CollectionAssert.AreEqual (bytes, PngChunks (file.Render ().ToArray ()).Single (c => c.Type == "eXIf").Payload, table); + return; + } + + // GPS, interoperability and IFD1 name the comment bytes as their own value. A wholly absent next field is + // still plain, but that share is not, so those edits are refused. IFD0 and the Exif IFD do not share it. + if (table is "GPS IFD" or "interoperability IFD" or "IFD1") { + var sharedInput = Png (PngChunk ("eXIf", bytes), Text ("Comment", "c")); + AssertUnchangedRefusal (save, sharedInput, file.Render ().ToArray (), table); + return; + } + + Assert.IsTrue (save.IsSuccess, $"{table}: {save.Error}"); + var exif = PngChunks (file.Render ().ToArray ()).Single (c => c.Type == "eXIf").Payload; + Assert.AreEqual (length, exif.Length, $"{table}: nothing is written past the data"); + Assert.AreEqual (0, UserCommentsInEveryExifIfd (exif).Count, $"{table}: a comment copy is left"); + AssertOnlyTheCopiesAreGone (bytes, exif, table, 0x9286, 0x9C9C); + var protectedTable = table is "GPS IFD" or "interoperability IFD" or "IFD1"; + Assert.AreEqual (protectedTable, exif.AsSpan ().IndexOf ("old comment one"u8) >= 0, $"{table}: the old comment's bytes are kept only when that table uses them"); + } + + // The removed UserComment's last byte is the first count byte of a table P that no reader reads (big-endian + // 0x0102: 258 entries, which do not fit). Zeroing it would make the count 2. That share is not plain, so the edit + // is refused, whichever way the walk reaches P. + [TestMethod] + [DataRow ("png", "IFD0's Exif IFD pointer")] + [DataRow ("jpeg", "IFD0's Exif IFD pointer")] + [DataRow ("png", "a nested Exif IFD pointer")] + [DataRow ("jpeg", "a nested Exif IFD pointer")] + [DataRow ("png", "a SubIFD pointer")] + [DataRow ("jpeg", "a SubIFD pointer")] + public void Edit_NeverZeroesTheCountOfATableNoReaderReads (string carrier, string shape) + { + const int Ifd0 = 8, A = 48, Value = 100; + var p = Value + SecretUc.Length - 1; + var hidden = p + 2 + (12 * 2) + 4; + var tiff = new TiffBuilder (hidden + HiddenUc.Length, bigEndian: true).Header (Ifd0) + .Bytes (Value, SecretUc) + .U16 (p, 0x0102) + .Bytes (p + 2, new byte[24]) + .Bytes (hidden, HiddenUc); + // P's entries, as they would be read if its count were 2. + tiff.U16 (p + 2, 0x9286).U16 (p + 4, 7).U32 (p + 6, HiddenUc.Length).U32 (p + 10, hidden); + var comment = (0x9286, 7, SecretUc.Length, Value); + _ = shape switch { + "IFD0's Exif IFD pointer" => tiff.Table (Ifd0, [(0x8769, 4, 1, A), (0x8769, 4, 1, p)]).Table (A, [comment]), + "a nested Exif IFD pointer" => tiff.Table (Ifd0, [(0x8769, 4, 1, A)]).Table (A, [comment, (0x8769, 4, 1, p)]), + _ => tiff.Table (Ifd0, [(0x8769, 4, 1, A), (0x014A, 4, 1, p)]).Table (A, [comment]), + }; + var data = tiff.ToArray (); + Assert.AreEqual (1, UserCommentsInEveryExifIfd (data).Count, "the input shows its UserComment and not P's"); + var input = InCarrier (carrier, data); + var file = Open (input, carrier == "png" ? "a.png" : "a.jpg"); + file.Tag!.Comment = "New"; + + var save = file.SaveToFile ("/a", new MockFileSystem ()); + AssertUnchangedRefusal (save, input, file.Render ().ToArray (), $"{carrier} {shape}"); + Assert.AreEqual (0x01, data[p], shape); + Assert.AreEqual (0x02, data[p + 1], shape); + } + + // exiftool reads every table of IFD0's chain (IFD1, IFD2, ...), and from each, from every Exif IFD and every + // SubIFD it follows 0x8769 and 0x014A, all with the Exif::Main tags (measured: it shows [IFD0] UserComment, + // [IFD1] Artist, [ExifIFD] XPComment and Artist, [SubIFD] UserComment, XPComment, ImageDescription, Copyright, + // [IFD2] UserComment, and the nested Exif IFD's UserComment). An edit removes the field's copies from each. + [TestMethod] + [DataRow ("png", "nested Exif IFD and the first", 0x9286)] + [DataRow ("jpeg", "nested Exif IFD and the first", 0x9286)] + [DataRow ("png", "nested Exif IFD only", 0x9286)] + [DataRow ("jpeg", "nested Exif IFD only", 0x9286)] + [DataRow ("png", "IFD1's Exif IFD", 0x9286)] + [DataRow ("jpeg", "IFD1's Exif IFD", 0x9286)] + [DataRow ("png", "SubIFD", 0x9286)] + [DataRow ("jpeg", "SubIFD", 0x9286)] + [DataRow ("png", "IFD2", 0x9286)] + [DataRow ("png", "IFD0", 0x9286)] + [DataRow ("png", "SubIFD", 0x9C9C)] + [DataRow ("png", "nested Exif IFD only", 0x013B)] + [DataRow ("png", "IFD1's Exif IFD", 0x8298)] + public void Edit_RemovesTheCopiesExiftoolReadsInNestedTables (string carrier, string where, int copy) + { + const int Ifd0 = 8, E = 60, N = 100, Ifd1 = 140, Ifd2 = 180, Value = 240; + var copyBytes = copy == 0x9C9C ? Encoding.Unicode.GetBytes ("old copy\0") : copy == 0x9286 ? "ASCII\0\0\0old copy"u8.ToArray () : "old copy\0"u8.ToArray (); + var entry = (copy, copy switch { 0x9C9C => 1, 0x9286 => 7, _ => 2 }, copyBytes.Length, Value); + var filler = (0x9003, 7, 4, 0x31303032); + var tiff = new TiffBuilder (Value + 32, bigEndian: carrier == "jpeg").Header (Ifd0).Bytes (Value, copyBytes); + _ = where switch { + "nested Exif IFD and the first" => tiff.Table (Ifd0, [(0x8769, 4, 1, E)]).Table (E, [entry, (0x8769, 4, 1, N)]).Table (N, [(copy, entry.Item2, copyBytes.Length, Value)]), + "nested Exif IFD only" => tiff.Table (Ifd0, [(0x8769, 4, 1, E)]).Table (E, [filler, (0x8769, 4, 1, N)]).Table (N, [entry]), + "IFD1's Exif IFD" => tiff.Table (Ifd0, [filler], next: Ifd1).Table (Ifd1, [(0x8769, 4, 1, N)]).Table (N, [entry]), + "SubIFD" => tiff.Table (Ifd0, [(0x014A, 4, 1, N)]).Table (N, [entry]), + "IFD2" => tiff.Table (Ifd0, [filler], next: Ifd1).Table (Ifd1, [filler], next: Ifd2).Table (Ifd2, [entry]), + _ => tiff.Table (Ifd0, [entry, filler]), + }; + var data = tiff.ToArray (); + Assert.IsTrue (ExifReaderModel.Of (data).CopiesOf (copy).Count > 0, "the input shows the copy"); + var file = Open (InCarrier (carrier, data), carrier == "png" ? "a.png" : "a.jpg"); + switch (copy) { + case 0x013B: + file.Tag!.Artist = "New"; + break; + case 0x8298: + file.Tag!.Copyright = "New"; + break; + default: + file.Tag!.Comment = "New"; + break; + } + + var save = file.SaveToFile ("/a", new MockFileSystem ()); + + Assert.IsTrue (save.IsSuccess, $"{carrier} {where}: {save.Error}"); + var exif = ExifOf (file.Render ().ToArray ()); + Assert.AreEqual (0, ExifReaderModel.Of (exif).CopiesOf (copy).Count, $"{carrier} {where}: the copy is left"); + int[] removed = copy switch { 0x013B => [0x013B, 0x9C9D], 0x8298 => [0x8298], _ => [0x9286, 0x9C9C] }; + AssertOnlyTheCopiesAreGone (data, exif, $"{carrier} {where}", removed); + } + + // An array of SubIFD offsets is IFD structure. Inside a table the edit compacts, or inside the removed value, + // removing the comment would rewrite it, so the edit is refused and nothing is written. + [TestMethod] + [DataRow ("inside the table the edit compacts")] + [DataRow ("inside the removed UserComment")] + [DataRow ("ending inside the table the edit compacts")] + public void Edit_KeepsSubIfdOffsetArraysAsTheyAre (string shape) + { + const int Ifd0 = 8, S1 = 80, S2 = 100, Value = 140; + var ucAt = Value; + var tiff = new TiffBuilder (Value + 48, bigEndian: false).Header (Ifd0) + .Table (S1, [(0x9003, 7, 4, 0x31303032)]).Table (S2, [(0x9004, 7, 4, 0x31303032)]); + int arrayAt; + if (shape == "inside the table the edit compacts") { + // The array is the count and value fields of IFD0's second entry, which moves up when the first goes. + arrayAt = Ifd0 + 2 + 12 + 4; + tiff.Table (Ifd0, [(0x9286, 7, SecretUc.Length, ucAt), (0x9003, 7, S1, S2), (0x014A, 4, 2, arrayAt)]); + } else if (shape == "ending inside the table the edit compacts") { + // The array starts at 4 (IFD0's own offset, 8) and its second offset is IFD0's count and first tag. + arrayAt = 4; + tiff.Table (Ifd0, [(0x9286, 7, SecretUc.Length, ucAt), (0x014A, 4, 2, arrayAt)]); + } else { + arrayAt = Value + 8; + tiff.Table (Ifd0, [(0x9286, 7, 24, ucAt), (0x014A, 4, 2, arrayAt)]).Bytes (ucAt, "ASCII\0\0\0"u8).U32 (arrayAt, S1).U32 (arrayAt + 4, S2); + } + + var data = tiff.ToArray (); + var input = InCarrier ("png", data); + var file = Open (input, "a.png"); + file.Tag!.Comment = "New"; + + var fs = new MockFileSystem (); + var save = file.SaveToFile ("/a.png", fs); + + Assert.IsFalse (save.IsSuccess, shape); + StringAssert.Contains (save.Error, shape == "inside the removed UserComment" ? "IFD structure that removing" : "SubIFD offsets", shape); + CollectionAssert.AreEqual (input, file.Render ().ToArray (), shape); + } + + // What exiftool does not read keeps its bytes: the next IFD of an Exif IFD (exiftool follows only IFD0's chain) + // and a GPS table (its 0x9286 is not a UserComment), as measured. + [TestMethod] + [DataRow ("the next IFD of an Exif IFD")] + [DataRow ("a GPS table")] + public void Edit_LeavesTablesExiftoolDoesNotReadAsTheyAre (string where) + { + const int Ifd0 = 8, E = 60, X = 100, Value = 160, Other = 200; + var otherUc = "ASCII\0\0\0other-uc"u8.ToArray (); + var tiff = new TiffBuilder (Other + otherUc.Length, bigEndian: false).Header (Ifd0).Bytes (Value, SecretUc).Bytes (Other, otherUc) + .Table (X, [(0x9286, 7, otherUc.Length, Other)]); + if (where == "a GPS table") + tiff.Table (Ifd0, [(0x8769, 4, 1, E), (0x8825, 4, 1, X)]).Table (E, [(0x9286, 7, SecretUc.Length, Value)]); + else + tiff.Table (Ifd0, [(0x8769, 4, 1, E)]).Table (E, [(0x9286, 7, SecretUc.Length, Value)], next: X); + var data = tiff.ToArray (); + var file = Open (InCarrier ("png", data), "a.png"); + file.Tag!.Comment = "New"; + + Assert.IsTrue (file.SaveToFile ("/a.png", new MockFileSystem ()).IsSuccess); + var exif = ExifOf (file.Render ().ToArray ()); + + Assert.AreEqual (0, UserCommentsInEveryExifIfd (exif).Count, where); + AssertOnlyTheCopiesAreGone (data, exif, where, 0x9286, 0x9C9C); + CollectionAssert.AreEqual (data[X..(X + 18)], exif[X..(X + 18)], $"{where}: the table is kept"); + CollectionAssert.AreEqual (data[Other..], exif[Other..], $"{where}: and so is its value"); + } + + // With no mirrored field changed there is nothing to remove: the block is left as it is. + [TestMethod] + public void RemoveExif_WithNoChangedField_ChangesNothing () + { + var tiff = new TiffBuilder (64, bigEndian: false).Header (8).Table (8, [(0x9286, 7, 8, 40)]).Bytes (40, "ASCII\0\0\0"u8).ToArray (); + var copy = (byte[])tiff.Clone (); + var tag = new ImageTag (MediaFormat.Png, (ImageStores)0x3F); + + Assert.IsTrue (ExifEditor.TryRemove (tiff, 0, tag, "eXIf", out var changed, out var error), error); + + Assert.IsFalse (changed); + CollectionAssert.AreEqual (copy, tiff); + } + + // A removed value that covers an unread table, or that is the next offset of an Exif or GPS table, shares + // protected structure, so the edit is refused. A value that lies wholly before that structure, a pointer into + // the header or at the last byte, and the next IFD of an Exif IFD's next IFD (named by nothing) still save. + [TestMethod] + [DataRow ("the removed value covers an unread table's entries")] + [DataRow ("the removed value covers the last bytes of an unread table")] + [DataRow ("the removed value lies before an unread table")] + [DataRow ("an unread table at offset 8")] + [DataRow ("a pointer into the header")] + [DataRow ("a pointer to the data's last byte")] + [DataRow ("the removed value is the next IFD of an Exif IFD")] + [DataRow ("the removed value is the next IFD of a GPS table")] + [DataRow ("the removed value is the next IFD of an Exif IFD's next IFD")] + public void Edit_KeepsTheStructureOfTablesNoReaderReads (string shape) + { + const int Value = 100; + var removed = "ASCII\0\0\0secret-uc-long-text"u8.ToArray (); + var length = Value + removed.Length + 40; + var tiff = new TiffBuilder (length, bigEndian: false).Bytes (Value, removed); + var comment = (0x9286, 7, removed.Length, Value); + int watchedStart, watchedEnd; + var cleared = false; + switch (shape) { + case "the removed value covers an unread table's entries": + // P's count (257) sits just before the value; its first entries are the value's bytes. + tiff.Header (8).Table (8, [comment, (0x8769, 4, 1, Value - 2)]).U16 (Value - 2, 0x0101); + (watchedStart, watchedEnd) = (Value - 2, length); + break; + case "the removed value covers the last bytes of an unread table": + // P counts 5 entries, which end 2 bytes past the data; the removed value is the data's last bytes. + length = Value + removed.Length; + tiff = new TiffBuilder (length, bigEndian: false).Bytes (Value, removed).Header (8).Table (8, [comment, (0x8769, 4, 1, length - (12 * 5))]).U16 (length - (12 * 5), 5); + (watchedStart, watchedEnd) = (Value, length); + break; + case "the removed value lies before an unread table": + // The unread table's structure starts after the value, so the value is still cleared. + tiff.Header (8).Table (8, [comment, (0x8769, 4, 1, Value + removed.Length + 4)]).U16 (Value + removed.Length + 4, 0x0101); + (watchedStart, watchedEnd) = (Value, Value + removed.Length); + cleared = true; + break; + case "an unread table at offset 8": + // IFD0 lies at 60; the table at 8 counts 257 entries, and its count is the removed value's first bytes. + tiff.Header (60).Table (60, [(0x9286, 7, 6, 8), (0x8769, 4, 1, 8)]).U16 (8, 0x0101); + (watchedStart, watchedEnd) = (8, 10); + break; + case "the removed value is the next IFD of an Exif IFD": + // No reader reads the next IFD of an Exif IFD (measured); here it is the removed value, whose first + // bytes ("AS") count more entries than the data holds. + tiff.Header (8).Table (8, [(0x8769, 4, 1, 40)]).Table (40, [comment], next: Value); + (watchedStart, watchedEnd) = (Value, Value + removed.Length); + break; + case "the removed value is the next IFD of a GPS table": + // Nor the next IFD of a GPS table (measured): the same, with the GPS table's next offset. + tiff.Header (8).Table (8, [(0x8769, 4, 1, 40), (0x8825, 4, 1, 60)]).Table (40, [comment]).Table (60, [(1, 2, 2, 0x4E)], next: Value); + (watchedStart, watchedEnd) = (Value, Value + removed.Length); + break; + case "the removed value is the next IFD of an Exif IFD's next IFD": + // The Exif IFD's next IFD (at 60) is kept, but nothing names the table after it: the value is cleared. + tiff.Header (8).Table (8, [(0x8769, 4, 1, 40)]).Table (40, [comment], next: 60).Table (60, [(0x0131, 2, 4, 0x00636261)], next: Value); + (watchedStart, watchedEnd) = (Value, Value + removed.Length); + cleared = true; + break; + case "a pointer into the header": + tiff.Header (8).Table (8, [comment, (0x8769, 4, 1, 7)]); + (watchedStart, watchedEnd) = (0, 8); + break; + default: + tiff.Header (8).Table (8, [comment, (0x8769, 4, 1, length - 1)]).Bytes (length - 1, [0xFF]); + (watchedStart, watchedEnd) = (length - 1, length); + break; + } + + var data = tiff.ToArray (); + var input = InCarrier ("png", data); + var file = Open (input, "a.png"); + file.Tag!.Comment = "New"; + + var save = file.SaveToFile ("/a.png", new MockFileSystem ()); + var overlaps = !cleared && shape != "a pointer into the header" && shape != "a pointer to the data's last byte"; + if (overlaps) { + AssertUnchangedRefusal (save, input, file.Render ().ToArray (), shape); + return; + } + + Assert.IsTrue (save.IsSuccess, $"{shape}: {save.Error}"); + var exif = ExifOf (file.Render ().ToArray ()); + AssertOnlyTheCopiesAreGone (data, exif, shape, 0x9286, 0x9C9C); + if (cleared) + Assert.IsTrue (exif[watchedStart..watchedEnd].All (b => b == 0), $"{shape}: the removed value is cleared"); + else + CollectionAssert.AreEqual (data[watchedStart..watchedEnd], exif[watchedStart..watchedEnd], $"{shape}: the structure is kept"); + } + + // The edges of the data, in both carriers (a JPEG's TIFF starts 6 bytes into its segment): a table whose last + // entry runs past the data, a SubIFD array cut short or ending exactly at the end, and a next-IFD offset that is + // the data's last 4 bytes. Nothing is read past the data, and what fits is read. + [TestMethod] + [DataRow ("png", "an Exif IFD whose last entry runs 2 bytes past the data")] + [DataRow ("jpeg", "an Exif IFD whose last entry runs 2 bytes past the data")] + [DataRow ("png", "a SubIFD array cut short at the end of the data")] + [DataRow ("jpeg", "a SubIFD array cut short at the end of the data")] + [DataRow ("png", "a SubIFD array that ends at the end of the data")] + [DataRow ("jpeg", "a SubIFD array that ends at the end of the data")] + [DataRow ("png", "IFD0's next offset is the data's last 4 bytes")] + [DataRow ("jpeg", "IFD0's next offset is the data's last 4 bytes")] + [DataRow ("png", "a pointer to the end of the data, after an edited table with no next offset")] + public void Edit_AtTheEdgesOfTheData_ReadsWhatFitsAndNothingPast (string carrier, string shape) + { + const int Value = 120; + var copy = "ASCII\0\0\0old-copy"u8.ToArray (); + var comment = (0x9286, 7, copy.Length, Value); + byte[] data; + switch (shape) { + case "an Exif IFD whose last entry runs 2 bytes past the data": + // The second Exif IFD counts 2 entries; only 22 of their 24 bytes are there, so no reader reads it. + var buffer = new TiffBuilder (Value + copy.Length + 32, bigEndian: false).Header (8).Table (8, [comment, (0x8769, 4, 1, Value + copy.Length - 2)]).Bytes (Value, copy) + .Table (Value + copy.Length - 2, [(0x9286, 7, copy.Length, Value), (0x9003, 7, 4, 0x31303032)]).ToArray (); + data = buffer[..(Value + copy.Length + 22)]; + break; + case "a SubIFD array cut short at the end of the data": + data = new TiffBuilder (Value + copy.Length + 4, bigEndian: false).Header (8).Table (8, [comment, (0x014A, 4, 2, Value + copy.Length)]).Bytes (Value, copy) + .U32 (Value + copy.Length, 60).ToArray (); + break; + case "a SubIFD array that ends at the end of the data": + data = new TiffBuilder (Value + copy.Length + 8, bigEndian: false).Header (8).Table (8, [(0x014A, 4, 2, Value + copy.Length)]).Bytes (Value, copy) + .Table (60, [comment]).Table (80, [(0x9003, 7, 4, 0x31303032)]).U32 (Value + copy.Length, 60).U32 (Value + copy.Length + 4, 80).ToArray (); + break; + case "a pointer to the end of the data, after an edited table with no next offset": + // IFD0 is last and has no next offset, so its range runs 4 bytes past the data; a second pointer names + // the offset just past the data, where no table can be. Nothing there is IFD structure: the edit saves. + var end = Value + copy.Length + 2 + 24; + data = new TiffBuilder (end + 4, bigEndian: false).Header (Value + copy.Length).Bytes (Value, copy) + .Table (Value + copy.Length, [comment, (0x8769, 4, 1, end)]).ToArray ()[..end]; + break; + default: + // IFD1 at 40 holds the copy; IFD0 is the last thing in the data, its next offset the last 4 bytes. + data = new TiffBuilder (Value + copy.Length + 18, bigEndian: false).Header (Value + copy.Length).Bytes (Value, copy) + .Table (40, [comment]).Table (Value + copy.Length, [(0x9003, 7, 4, 0x31303032)], next: 40).ToArray (); + break; + } + + var input = InCarrier (carrier, data); + var file = Open (input, carrier == "png" ? "a.png" : "a.jpg"); + file.Tag!.Comment = "New"; + + var save = file.SaveToFile ("/a", new MockFileSystem ()); + // The second Exif IFD's count sits inside the removed value, so that edit is not plain. + if (shape == "an Exif IFD whose last entry runs 2 bytes past the data") { + AssertUnchangedRefusal (save, input, file.Render ().ToArray (), $"{carrier} {shape}"); + return; + } + + Assert.IsTrue (save.IsSuccess, $"{carrier} {shape}: {save.Error}"); + var exif = ExifOf (file.Render ().ToArray ()); + Assert.AreEqual (data.Length, exif.Length, "nothing is written past the data"); + AssertOnlyTheCopiesAreGone (data, exif, $"{carrier} {shape}", 0x9286, 0x9C9C); + Assert.AreEqual (0, UserCommentsInEveryExifIfd (exif).Count, $"{carrier} {shape}: a copy is left"); + } + + [TestMethod] + public void Edit_RefusesWhenStripOffsetsStartPastTheData () + { + // StripOffsets (0x0111) as two LONGs at an offset past the block, and its byte counts likewise. The array + // does not fit, so the artist edit is refused and nothing is written. + var tiff = ExifTiff ([(0x010F, "Canon"), (0x013B, "Old artist")], []); + var far = Concat (tiff[..10], new byte[12 * 2], tiff[10..]); + far[8] = 4; + for (var (at, tag) = (10, 0x0111); at < 34; at += 12, tag = 0x0117) { + BitConverter.GetBytes ((ushort)tag).CopyTo (far, at); + BitConverter.GetBytes ((ushort)4).CopyTo (far, at + 2); + BitConverter.GetBytes (2).CopyTo (far, at + 4); + BitConverter.GetBytes (0x7FFF0000).CopyTo (far, at + 8); + } + + // Shift the original entries' out-of-line offsets by the 24 bytes inserted. + for (var n = 2; n < 4; n++) { + var entry = 10 + (12 * n); + var value = BitConverter.ToInt32 (far, entry + 8); + if (BitConverter.ToInt32 (far, entry + 4) > 4) + BitConverter.GetBytes (value + 24).CopyTo (far, entry + 8); + } + + var input = Png (PngChunk ("eXIf", far), Text ("Author", "a")); + var file = Open (input, "a.png"); + file.Tag!.Artist = "New"; + var save = file.SaveToFile ("/a.png", new MockFileSystem ()); + AssertUnchangedRefusal (save, input, file.Render ().ToArray (), "strip offsets past the data"); + StringAssert.Contains (save.Error, "does not fit in its data"); + } + + // exiftool reads an interoperability IFD with the Exif tags and follows its pointers, and follows a pointer typed + // BYTE, SHORT, SSHORT, SBYTE, SLONG or UNDEFINED (count 1) as it follows a LONG one (measured, the probes in + // Golden/exif-reader-probes.txt): every copy it reads that way is removed, and nothing else readers see changes. + [TestMethod] + [DataRow ("a UserComment in the interoperability IFD", false)] + [DataRow ("a UserComment in the interoperability IFD", true)] + [DataRow ("an Exif IFD under the interoperability IFD", false)] + [DataRow ("an Exif IFD pointer typed SHORT", false)] + [DataRow ("an Exif IFD pointer typed SHORT", true)] + [DataRow ("an Exif IFD pointer typed SSHORT", false)] + [DataRow ("an Exif IFD pointer typed BYTE", true)] + [DataRow ("an Exif IFD pointer typed SBYTE", false)] + [DataRow ("an Exif IFD pointer typed SLONG", true)] + [DataRow ("an Exif IFD pointer typed UNDEFINED", false)] + [DataRow ("a SubIFD pointer typed SHORT", false)] + [DataRow ("a SubIFD array of two SHORT offsets", true)] + [DataRow ("an Exif IFD pointer typed SHORT in the Exif IFD", false)] + [DataRow ("an Exif IFD pointer typed SSHORT in the Exif IFD", false)] + [DataRow ("an Exif IFD pointer typed BYTE in the Exif IFD", false)] + [DataRow ("an Exif IFD pointer typed SBYTE in the Exif IFD", false)] + [DataRow ("an Exif IFD pointer typed SLONG in the Exif IFD", false)] + [DataRow ("an Exif IFD pointer typed UNDEFINED in the Exif IFD", false)] + public void Edit_RemovesTheCopiesOfEveryTableExiftoolReads_ByItsPointerRules (string shape, bool bigEndian) + { + const int Exif = 40, Inner = 100, Values = 160; + var t = new TiffBuilder (Values + 40, bigEndian).Header (8); + // In IFD0 a pointer's field read as a LONG may name the same table (TagLib#'s reading); in the Exif IFD only + // the typed reading can. + var inExif = shape.EndsWith (" in the Exif IFD", StringComparison.Ordinal); + var typed = inExif ? shape[..^" in the Exif IFD".Length] : shape; + (int Tag, int Type, int Size) pointer = typed switch { + _ when typed.EndsWith ("typed SHORT", StringComparison.Ordinal) && typed.StartsWith ("an Exif", StringComparison.Ordinal) => (0x8769, 3, 2), + _ when typed.EndsWith ("SSHORT", StringComparison.Ordinal) => (0x8769, 8, 2), + _ when typed.EndsWith ("typed BYTE", StringComparison.Ordinal) => (0x8769, 1, 1), + _ when typed.EndsWith ("SBYTE", StringComparison.Ordinal) => (0x8769, 6, 1), + _ when typed.EndsWith ("SLONG", StringComparison.Ordinal) => (0x8769, 9, 4), + _ when typed.EndsWith ("UNDEFINED", StringComparison.Ordinal) => (0x8769, 7, 1), + _ when shape.StartsWith ("a SubIFD pointer", StringComparison.Ordinal) => (0x014A, 3, 2), + _ => (0, 0, 0), + }; + if (shape.Contains ("interoperability", StringComparison.Ordinal)) { + var inner = shape.StartsWith ("an Exif IFD under", StringComparison.Ordinal); + t.Table (8, [(0x8769, 4, 1, Exif)]).Table (Exif, [(0xA005, 4, 1, Inner)]) + .Table (Inner, inner ? [(0x0001, 2, 4, 0x00383952), (0x8769, 4, 1, Inner + 40)] : [(0x0001, 2, 4, 0x00383952), (0x9286, 7, SecretUc.Length, Values)]); + if (inner) + t.Table (Inner + 40, [(0x9286, 7, SecretUc.Length, Values)]); + } else if (shape.StartsWith ("a SubIFD array", StringComparison.Ordinal)) { + t.Table (8, [(0x014A, 3, 2, 0)]).U16 (8 + 2 + 8, Exif).U16 (8 + 2 + 10, Inner) + .Table (Exif, [(0x9286, 7, SecretUc.Length, Values)]).Table (Inner, [(0x9C9C, 1, 4, 0x00410041)]); + } else { + // The holder of the typed pointer: IFD0, or an Exif IFD at Inner that IFD0 names. + var holder = inExif ? Inner : 8; + if (inExif) + t.Table (8, [(0x8769, 4, 1, Inner)]); + t.Table (holder, [(pointer.Tag, pointer.Type, 1, 0)]).Table (Exif, [(0x9286, 7, SecretUc.Length, Values)]); + var field = holder + 2 + 8; + if (pointer.Size == 1) + t.Bytes (field, [Exif]); + else if (pointer.Size == 2) + t.U32 (field, 0).U16 (field, Exif); + else + t.U32 (field, Exif); + } + + var tiff = t.Bytes (Values, SecretUc).ToArray (); + Assert.IsTrue (UserCommentsInEveryExifIfd (tiff).Count > 0, $"{shape}: readers show a copy"); + var file = Open (InCarrier ("jpeg", tiff), "a.jpg"); + file.Tag!.Comment = "New"; + + var save = file.SaveToFile ("/a.jpg", new MockFileSystem ()); + + Assert.IsTrue (save.IsSuccess, $"{shape}: {save.Error}"); + var exif = ExifOf (file.Render ().ToArray ()); + Assert.AreEqual (0, UserCommentsInEveryExifIfd (exif).Count, $"{shape}: a copy is left"); + AssertOnlyTheCopiesAreGone (tiff, exif, shape, 0x9286, 0x9C9C); + } + + // Two pointer arrays at one offset with one count but different types name different tables: a SubIFD array of 8 + // LONGs, [0x2864, 0, ...], and one of 8 BYTEs over its first 8 bytes, [0x64, 0x28, 0, ...] (little-endian). + // exiftool reads each by its own type (measured), so all three tables are read and each copy is removed. + [TestMethod] + public void Edit_TwoPointerArraysAtOneOffset_AreEachReadByTheirOwnType () + { + const int Array = 200, Values = 140, Long = 0x2864; + int[] tables = [Long, 0x64, 0x28]; + var t = new TiffBuilder (Long + 60).Header (8).Table (8, [(0x014A, 4, 8, Array), (0x014A, 1, 8, Array)]) + .U32 (Array, Long).Bytes (Values, SecretUc); + foreach (var table in tables) + t.Table (table, [(0x9286, 7, SecretUc.Length, Values), (0x9003, 2, 4, 0x30303032)]); + var tiff = t.ToArray (); + var file = Open (InCarrier ("png", tiff), "a.png"); + file.Tag!.Comment = "New"; + + var save = file.SaveToFile ("/a.png", new MockFileSystem ()); + + Assert.IsTrue (save.IsSuccess, save.Error); + var exif = ExifOf (file.Render ().ToArray ()); + foreach (var table in tables) + Assert.AreEqual (1, U16 (exif, table, false), $"the table at {table} keeps only its other entry"); + AssertOnlyTheCopiesAreGone (tiff, exif, "two arrays at one offset", 0x9286, 0x9C9C); + } + + // IFD0's removed XPComment value starts at IFD1's next offset. That share is not plain, so the edit is refused + // and the next offset stays. + [TestMethod] + public void Edit_RemovedValue_NeverZeroesATablesNextOffset () + { + const int Ifd1 = 40, Next = Ifd1 + 2 + 12, Ifd2 = 100; + var tiff = new TiffBuilder (Ifd2 + 40).Header (8).Table (8, [(0x9C9C, 1, 20, Next)], next: Ifd1) + .Table (Ifd1, [(0x0131, 2, 4, 0x41414141)], next: Ifd2).Table (Ifd2, [(0x0132, 2, 4, 0x32303031)]).ToArray (); + Assert.AreEqual (3, ExifReaderModel.Of (tiff).Tables.Count, "IFD0, IFD1 and IFD2 are read"); + var input = InCarrier ("png", tiff); + var file = Open (input, "a.png"); + file.Tag!.Comment = "New"; + + var save = file.SaveToFile ("/a.png", new MockFileSystem ()); + AssertUnchangedRefusal (save, input, file.Render ().ToArray (), "IFD1's next offset inside a removed value"); + } + + // The next IFD of an Exif IFD is read by no one, and its value sits inside the Exif IFD the edit would compact. + // Compaction would rewrite that protected range, so the edit is refused. + [TestMethod] + public void Edit_AValueOfATableNoReaderReads_InsideTheCompactedTable_IsRefused () + { + const int Exif = 40, Unread = 120, Values = 160; + var tiff = new TiffBuilder (Values + 40).Header (8).Table (8, [(0x8769, 4, 1, Exif)]) + .Table (Exif, [(0x9286, 7, SecretUc.Length, Values), (0x9003, 2, 20, Values + 20)], next: Unread) + .Table (Unread, [(0x9004, 2, 20, Exif + 2)]).Bytes (Values, SecretUc).Bytes (Values + 20, "2001:02:03 04:05:06\0"u8).ToArray (); + var input = InCarrier ("png", tiff); + var file = Open (input, "a.png"); + file.Tag!.Comment = "New"; + + var save = file.SaveToFile ("/a.png", new MockFileSystem ()); + AssertUnchangedRefusal (save, input, file.Render ().ToArray (), "an unread table's value inside the compacted table"); + } + + // exiftool reads an UNDEFINED pointer value as unsigned: 200 names the table at 200 (measured, probe + // "pointer 8769 in IFD0 type 7 count 1"). In an Exif IFD only that typed reading names it. + [TestMethod] + public void Edit_RemovesTheCopyAnUndefinedPointerOf200Names () + { + const int Exif = 40, Target = 200, Values = 140; + var tiff = new TiffBuilder (Target + 40).Header (8).Table (8, [(0x8769, 4, 1, Exif)]) + .Table (Exif, [(0x9003, 2, 4, 0x30303032), (0x8769, 7, 1, Target)]) + .Table (Target, [(0x9286, 7, SecretUc.Length, Values), (0x9004, 2, 4, 0x30303032)]).Bytes (Values, SecretUc).ToArray (); + var file = Open (InCarrier ("png", tiff), "a.png"); + file.Tag!.Comment = "New"; + + var save = file.SaveToFile ("/a.png", new MockFileSystem ()); + + Assert.IsTrue (save.IsSuccess, save.Error); + var exif = ExifOf (file.Render ().ToArray ()); + Assert.AreEqual (1, U16 (exif, Target, false), "the table at 200 keeps only its other entry"); + AssertOnlyTheCopiesAreGone (tiff, exif, "an UNDEFINED pointer of 200", 0x9286, 0x9C9C); + } + + // IFD0's Artist (100 bytes) holds Copyright, Make and Model, and the removed XPComment sits inside those bytes. + // Removing the comment would change the kept value, so the edit is refused and Artist stays whole. + [TestMethod] + public void Edit_RemovedValueInsideAKeptValueThatHoldsOthers_IsNotZeroed () + { + const int Artist = 100; + var artist = Encoding.ASCII.GetBytes (new string ('a', 99) + "\0"); + var tiff = new TiffBuilder (Artist + 120).Header (8) + .Table (8, [(0x013B, 2, 100, Artist), (0x8298, 2, 5, Artist + 10), (0x010F, 2, 5, Artist + 20), (0x0110, 2, 5, Artist + 30), (0x9C9C, 1, 10, Artist + 50)]) + .Bytes (Artist, artist).ToArray (); + var input = InCarrier ("png", tiff); + var file = Open (input, "a.png"); + file.Tag!.Comment = "New"; + + var save = file.SaveToFile ("/a.png", new MockFileSystem ()); + AssertUnchangedRefusal (save, input, file.Render ().ToArray (), "a removed value inside a kept one"); + } + + // IFD0 at the end of the data, its next offset (IFD1, before it) the data's last 4 bytes: compacting IFD0 keeps the + // chain, so IFD1 is still read. + [TestMethod] + [DataRow (false)] + [DataRow (true)] + public void Edit_CompactingATableWhoseNextOffsetEndsTheData_KeepsTheChain (bool bigEndian) + { + const int Ifd1 = 8, Ifd0 = 26; + var tiff = new TiffBuilder (Ifd0 + 2 + (2 * 12) + 4, bigEndian).Header (Ifd0) + .Table (Ifd1, [(0x0131, 2, 4, bigEndian ? 0x78797A00 : 0x007A7978)]) + .Table (Ifd0, [(0x9286, 7, 4, 0x61626364), (0x0110, 2, 4, bigEndian ? 0x61626300 : 0x00636261)], next: Ifd1) + .ToArray (); + var file = Open (InCarrier ("png", tiff), "a.png"); + file.Tag!.Comment = "New"; + + var save = file.SaveToFile ("/a.png", new MockFileSystem ()); + + Assert.IsTrue (save.IsSuccess, save.Error); + AssertOnlyTheCopiesAreGone (tiff, ExifOf (file.Render ().ToArray ()), "the next offset ends the data", 0x9286); + } + + // Strip offsets and byte counts given as SHORT or LONG arrays out of line: a removed UserComment that shares bytes + // with a strip they name is not plain, so the edit is refused. An array that runs past the data does not fit, so + // that edit is refused before the value budget and nothing is written. + [TestMethod] + [DataRow (3, false, false)] + [DataRow (4, false, false)] + [DataRow (3, true, false)] + [DataRow (4, true, false)] + [DataRow (3, true, true)] + public void Edit_KeepsTheBytesOfEveryStripAnArrayNames (int type, bool atTheEnd, bool cut) + { + const int V = 200; + var size = type == 3 ? 2 : 4; + var length = atTheEnd ? 240 : 300; + var lengths = atTheEnd ? length - (3 * size) + (cut ? 2 : 0) : 260; + var offsets = lengths - (3 * size); + var removed = "ASCII\0\0\0old-comment!"u8.ToArray (); + var tiff = new TiffBuilder (length).Header (8) + .Table (8, [(0x0111, type, 3, offsets), (0x0117, type, 3, lengths), (0x9286, 7, removed.Length, V)]) + .Bytes (V, removed); + for (var n = 0; n < 3; n++) { + var (strip, bytes) = (new[] { 120, 140, 205 }[n], 10); + if (size == 2) { + tiff.U16 (offsets + (2 * n), strip); + if (lengths + (2 * n) + 2 <= length) + tiff.U16 (lengths + (2 * n), bytes); + } else { + tiff.U32 (offsets + (4 * n), strip).U32 (lengths + (4 * n), bytes); + } + } + + var data = tiff.ToArray (); + var input = InCarrier ("png", data); + var file = Open (input, "a.png"); + file.Tag!.Comment = "New"; + + var save = file.SaveToFile ("/a.png", new MockFileSystem ()); + AssertUnchangedRefusal (save, input, file.Render ().ToArray (), $"type {type} atTheEnd {atTheEnd} cut {cut}"); + if (cut) + StringAssert.Contains (save.Error, "does not fit in its data"); + } + + // A data range of length 0 (an empty thumbnail) protects no byte: the removed XPComment around its offset is + // zeroed. + [TestMethod] + public void Edit_AnEmptyThumbnailInsideARemovedValue_DoesNotKeepItsBytes () + { + const int Ifd1 = 60, Xp = 100; + var tiff = new TiffBuilder (Xp + 40).Header (8).Table (8, [(0x9C9C, 1, 16, Xp)], next: Ifd1) + .Table (Ifd1, [(0x0201, 4, 1, Xp + 8), (0x0202, 4, 1, 0)]).Bytes (Xp, "x\0p\0-\0o\0l\0d\0!\0!\0"u8).ToArray (); + var file = Open (InCarrier ("png", tiff), "a.png"); + file.Tag!.Comment = "New"; + + var save = file.SaveToFile ("/a.png", new MockFileSystem ()); + + Assert.IsTrue (save.IsSuccess, save.Error); + CollectionAssert.AreEqual (new byte[16], ExifOf (file.Render ().ToArray ())[Xp..(Xp + 16)], "the old XPComment is zeroed"); + } + + // Pointers no reader follows name no table: exiftool follows no Exif IFD pointer with count 0 or 2, typed ASCII or + // RATIONAL, nothing inside a GPS table (it reads GPS tables with the GPS tags), only the first value of an + // interoperability IFD pointer, no negative value of a signed type and no UNDEFINED pointer of count 2; TagLib# + // reads only IFD0's pointer field as a LONG, and ImageIO follows a subset of what exiftool follows (measured). The table they name is + // read by no one; the edit is not refused and leaves it byte for byte. + [TestMethod] + [DataRow ("IFD0's Exif IFD pointer with count 2, its field naming nothing as a LONG")] + [DataRow ("an Exif IFD pointer with count 0 in the Exif IFD")] + [DataRow ("an Exif IFD pointer typed ASCII in the Exif IFD")] + [DataRow ("an Exif IFD pointer typed RATIONAL in the Exif IFD")] + [DataRow ("an Exif IFD pointer inside a GPS table")] + [DataRow ("a SubIFD pointer inside a GPS table")] + [DataRow ("the second value of an interoperability IFD pointer in the Exif IFD")] + [DataRow ("an Exif IFD pointer typed SBYTE with a negative value in the Exif IFD")] + [DataRow ("an Exif IFD pointer typed SBYTE of -128 in the Exif IFD")] + [DataRow ("an Exif IFD pointer typed SSHORT of -32768 in the Exif IFD")] + [DataRow ("a SubIFD pointer typed UNDEFINED with count 2")] + public void Edit_LeavesATableNoReaderFollowsAPointerTo_AsItIs (string shape) + { + const int Holder = 40, Values = 160; + // SBYTE 0xC8 is -56 and 0x80 is -128, SSHORT 0x8000 is -32768: the table there is named only by a reader that + // took the value as unsigned. + var target = shape.Contains ("negative", StringComparison.Ordinal) ? 0xC8 : shape.Contains ("-128", StringComparison.Ordinal) ? 0x80 : shape.Contains ("-32768", StringComparison.Ordinal) ? 0x8000 : 100; + var t = new TiffBuilder (Math.Max (Values + 40, target + 60)).Header (8); + (int, int, long, long) pointer = shape switch { + _ when shape.StartsWith ("IFD0's", StringComparison.Ordinal) => (0x8769, 3, 2, target | (target << 16)), + _ when shape.StartsWith ("the second value", StringComparison.Ordinal) => (0xA005, 3, 2, (long)target << 16), + _ when shape.Contains ("SBYTE", StringComparison.Ordinal) => (0x8769, 6, 1, target), + _ when shape.Contains ("SSHORT", StringComparison.Ordinal) => (0x8769, 8, 1, target), + _ when shape.Contains ("UNDEFINED", StringComparison.Ordinal) => (0x014A, 7, 2, target), + _ when shape.Contains ("count 0", StringComparison.Ordinal) => (0x8769, 4, 0, target), + _ when shape.Contains ("ASCII", StringComparison.Ordinal) => (0x8769, 2, 1, target), + _ when shape.Contains ("RATIONAL", StringComparison.Ordinal) => (0x8769, 5, 1, target), + _ when shape.StartsWith ("an Exif", StringComparison.Ordinal) => (0x8769, 4, 1, target), + _ => (0x014A, 4, 1, target), + }; + if (shape.EndsWith ("inside a GPS table", StringComparison.Ordinal)) + t.Table (8, [(0x8825, 4, 1, Holder), (0x9C9C, 1, SecretUc.Length, Values)]).Table (Holder, [(0x0001, 2, 2, 0x4E), pointer]); + else if (shape.EndsWith ("in the Exif IFD", StringComparison.Ordinal)) + t.Table (8, [(0x8769, 4, 1, Holder), (0x9C9C, 1, SecretUc.Length, Values)]).Table (Holder, [(0x9003, 2, 4, 0x30303032), pointer]); + else + t.Table (8, [pointer, (0x9C9C, 1, SecretUc.Length, Values)]); + var tiff = t.Table (target, [(0x9286, 7, 8, 0), (0x9003, 2, 4, 0x30303032)]).Bytes (Values, SecretUc).ToArray (); + var file = Open (InCarrier ("png", tiff), "a.png"); + file.Tag!.Comment = "New"; + + var save = file.SaveToFile ("/a.png", new MockFileSystem ()); + + Assert.IsTrue (save.IsSuccess, $"{shape}: {save.Error}"); + var exif = ExifOf (file.Render ().ToArray ()); + CollectionAssert.AreEqual (tiff[target..(target + 30)], exif[target..(target + 30)], $"{shape}: the table no reader reads keeps its bytes"); + AssertOnlyTheCopiesAreGone (tiff, exif, shape, 0x9286, 0x9C9C); + } + + // TagLib# reads IFD0's Exif IFD pointer as its 4-byte field taken as a LONG, whatever its type and count (measured + // with every type and counts 0-2, and on corpus files whose pointer is typed SHORT or has count 2): the copy it + // shows from that table is removed, as is the one exiftool reads where the two decodings name different tables. + // With count 2 or RATIONAL the field is the offset of the pointer's own value, so that value is the table's first + // bytes. Compacting the table would rewrite that protected range, so those two edits are refused. The other + // shapes name a table whose bytes stay outside the compacted table, and the copy is removed. + [TestMethod] + [DataRow ("count 0", false)] + [DataRow ("typed ASCII", true)] + [DataRow ("typed SHORT with count 2", false)] + [DataRow ("typed SHORT, its first value 0", true)] + [DataRow ("typed BYTE, the field naming another table as a LONG", false)] + [DataRow ("count 2", false)] + [DataRow ("typed RATIONAL", true)] + public void Edit_RemovesTheCopyTagLibSharpReads_ThroughIfd0sExifPointerFieldAsALong (string shape, bool bigEndian) + { + // The BYTE row: exiftool reads the byte 100, TagLib# the LONG 0x2864. + const int Raw = 40, Values = 160, Byte = 100, Long = 0x2864; + var t = new TiffBuilder (Long + 60, bigEndian).Header (8); + var (type, count) = shape switch { + "count 0" => (4, 0), + "count 2" => (4, 2), + "typed ASCII" => (2, 4), + "typed RATIONAL" => (5, 1), + "typed SHORT with count 2" => (3, 2), + "typed SHORT, its first value 0" => (3, 1), + _ => (1, 1), + }; + var two = type == 1; + int[] tables = two ? [Byte, Long] : [Raw]; + t.Table (8, [(0x8769, type, count, two ? 0x2800 | Byte : Raw)]).Bytes (Values, SecretUc); + foreach (var table in tables) + t.Table (table, [(0x9286, 7, SecretUc.Length, Values), (0x9003, 2, 4, 0x30303032)]); + var tiff = t.ToArray (); + var input = InCarrier ("jpeg", tiff); + var file = Open (input, "a.jpg"); + file.Tag!.Comment = "New"; + + var save = file.SaveToFile ("/a.jpg", new MockFileSystem ()); + if (shape is "count 2" or "typed RATIONAL") { + AssertUnchangedRefusal (save, input, file.Render ().ToArray (), shape); + return; + } + + Assert.IsTrue (save.IsSuccess, $"{shape}: {save.Error}"); + var exif = ExifOf (file.Render ().ToArray ()); + foreach (var table in tables) + Assert.AreEqual (1, U16 (exif, table, bigEndian), $"{shape}: the table at {table} keeps only its other entry"); + AssertOnlyTheCopiesAreGone (tiff, exif, shape, 0x9286, 0x9C9C); + } + + static int U16 (byte[] data, int at, bool bigEndian) => bigEndian ? (data[at] << 8) | data[at + 1] : data[at] | (data[at + 1] << 8); + + // Zeroing a removed value must not empty a table a typed pointer names: big-endian, IFD0's Exif IFD (or GPS) + // pointer typed SHORT names a table whose count is the last two bytes of IFD0's removed UserComment. Read as a + // LONG the pointer named nothing and the count was zeroed, emptying the table for exiftool. Typed ASCII, the + // pointer names the same table only for TagLib#, which reads IFD0's pointer field as a LONG. + [TestMethod] + [DataRow (0x8769, 3)] + [DataRow (0x8825, 3)] + [DataRow (0x8769, 2)] + [DataRow (0x8825, 2)] + public void Edit_NeverZeroesATableATypedPointerNames (int tag, int type) + { + const int Values = 100; + var uc = "ASCII\0\0\0secret-uc"u8.ToArray (); + var target = Values + uc.Length - 2; + var t = new TiffBuilder (target + 70, bigEndian: true).Header (8) + .Table (8, [(0x9286, 7, uc.Length, Values), (tag, type, 1, type == 3 ? target << 16 : target)]) + .Bytes (Values, uc); + var tiff = (tag == 0x8825 ? t.Table (target, [(0x0001, 2, 2, 0x4E000000), (0x0002, 5, 3, target + 40)]) : t.Table (target, [(0x9003, 2, 4, 0x32303030), (0xA420, 2, 4, 0x69642D31)])).ToArray (); + var file = Open (InCarrier ("png", tiff), "a.png"); + file.Tag!.Comment = "New"; + + var save = file.SaveToFile ("/a.png", new MockFileSystem ()); + + if (save.IsSuccess) + AssertOnlyTheCopiesAreGone (tiff, ExifOf (file.Render ().ToArray ()), "the typed pointer's table keeps its count", 0x9286, 0x9C9C); + else + StringAssert.Contains (save.Error, "cannot be updated"); + Assert.AreEqual (2, ExifReaderModel.AnyReader (ExifOf (file.Render ().ToArray ())).Tables.Single (x => x.At == target).Count); + } + + // A kept value, or the thumbnail an offset/length pair names, whose bytes lie inside a table the edit compacts + // would be rewritten by the compaction: the edit is refused with its own reason, and nothing is written. + [TestMethod] + [DataRow ("IFD0's Artist is the Exif IFD's second entry")] + [DataRow ("IFD1's thumbnail is the Exif IFD's entries after the UserComment")] + [DataRow ("IFD1's thumbnail, its pair given twice, the first naming the Exif IFD's entries after the UserComment")] + public void Edit_RefusesToRewriteAValueInsideATableItCompacts (string shape) + { + const int Exif = 60, Ifd1 = 120, Values = 180; + var thumb = shape.StartsWith ("IFD1", StringComparison.Ordinal); + var t = new TiffBuilder (Values + 40).Header (8) + .Table (Exif, [(0x9286, 7, SecretUc.Length, Values), (0x9003, 2, 4, 0x41414141), (0x9004, 2, 4, 0x42424242)]) + .Bytes (Values, SecretUc); + // Given twice, readers take the first pair (exiftool and the tests' reader); the second names bytes past the value. + if (thumb && shape.Contains ("twice", StringComparison.Ordinal)) + t.Table (8, [(0x8769, 4, 1, Exif)], next: Ifd1).Table (Ifd1, [(0x0201, 4, 1, Exif + 14), (0x0202, 4, 1, 24), (0x0201, 4, 1, Values + 20), (0x0202, 4, 1, 4)]); + else if (thumb) + t.Table (8, [(0x8769, 4, 1, Exif)], next: Ifd1).Table (Ifd1, [(0x0201, 4, 1, Exif + 14), (0x0202, 4, 1, 24)]); + else + t.Table (8, [(0x8769, 4, 1, Exif), (0x013B, 2, 12, Exif + 14)]); + var input = InCarrier ("png", t.ToArray ()); + var file = Open (input, "a.png"); + file.Tag!.Comment = "New"; + + var save = file.SaveToFile ("/a.png", new MockFileSystem ()); + + Assert.IsFalse (save.IsSuccess, shape); + // A pair tag given twice is refused before compaction, so the thumbnail-inside-the-table reason is not reached. + StringAssert.Contains (save.Error, shape.Contains ("twice", StringComparison.Ordinal) ? "offset or length more than once" : "a value inside an IFD table"); + CollectionAssert.AreEqual (input, file.Render ().ToArray (), $"{shape}: nothing is written"); + } + + // The same at the data's end: IFD0 ends the data, and a kept value (Make, 8 bytes) or the thumbnail an + // offset/length pair names is its last 8 bytes, which compacting IFD0 rewrites (exiftool would show them change). + [TestMethod] + [DataRow ("a kept value")] + [DataRow ("the thumbnail")] + public void Edit_RefusesToRewriteAValueThatEndsTheDataInsideATableItCompacts (string shape) + { + var comment = (0x9286, 7, 4L, 0x64636261L); + var tiff = shape == "a kept value" + ? new TiffBuilder (38).Header (8).Table (8, [comment, (0x010F, 2, 8, 30)]).ToArray () + : new TiffBuilder (50).Header (8).Table (8, [comment, (0x0201, 4, 1, 42), (0x0202, 4, 1, 8)]).ToArray (); + var input = InCarrier ("png", tiff); + var file = Open (input, "a.png"); + file.Tag!.Comment = "New"; + + var save = file.SaveToFile ("/a.png", new MockFileSystem ()); + + Assert.IsFalse (save.IsSuccess, shape); + StringAssert.Contains (save.Error, "a value inside an IFD table"); + CollectionAssert.AreEqual (input, file.Render ().ToArray (), $"{shape}: nothing is written"); + } + + // A thumbnail that starts in IFD0's entries and runs past the data is still a protected range inside the table + // the edit would compact, so the edit is refused. + [TestMethod] + public void Edit_OfATableHoldingAThumbnailThatRunsPastTheData_IsRefused () + { + var tiff = new TiffBuilder (50).Header (8).Table (8, [(0x9286, 7, 4, 0x64636261), (0x0201, 4, 1, 42), (0x0202, 4, 1, 20)]).ToArray (); + var input = InCarrier ("png", tiff); + var file = Open (input, "a.png"); + file.Tag!.Comment = "New"; + + var save = file.SaveToFile ("/a.png", new MockFileSystem ()); + AssertUnchangedRefusal (save, input, file.Render ().ToArray (), "a thumbnail past the data"); + } + + // A GPS or interoperability pointer whose first value sits out of line, inside the Exif IFD the edit compacts. + // Compaction writes the Exif IFD's next offset over that value, so the walk reaches the table at 130 instead of + // the one at 100. The out-of-line value is not a kept value (a reader follows it, and shows the bytes as a bad + // value), so only the table offsets catch it. An Exif pointer of count 2 is not followed; a SubIFD array is a + // kept value and is already refused as one. + [TestMethod] + [DataRow (0x8825, false)] + [DataRow (0xA005, false)] + [DataRow (0x8825, true)] + [DataRow (0xA005, true)] + public void Edit_RefusesWhenAPointerArrayInsideTheCompactedTableNamesAnotherTable (int tag, bool bigEndian) + { + const int Exif = 40, Array = 66, Named = 100, Other = 130; + var craftedTag = bigEndian ? Named >> 16 : Named & 0xFFFF; + var craftedType = bigEndian ? Named & 0xFFFF : Named >> 16; + var hill = bigEndian ? 0x48696C6C : 0x6C6C6948; + var tiff = new TiffBuilder (Other + 18, bigEndian).Header (8) + .Table (8, [(0x8769, 4, 1, Exif)]) + .Table (Exif, [(0x9286, 7, 4, 0x64636261), (tag, 4, 2, Array), (craftedTag, craftedType, 1, 0)], next: Other) + .Table (Named, [(0x0001, 2, 4, hill)]) + .Table (Other, [(0x0001, 2, 4, hill)]) + .ToArray (); + var input = InCarrier ("png", tiff); + var file = Open (input, "a.png"); + file.Tag!.Comment = "New"; + + var save = file.SaveToFile ("/a.png", new MockFileSystem ()); + + Assert.IsFalse (save.IsSuccess, $"{tag:X4} {(bigEndian ? "big-endian" : "little-endian")}"); + StringAssert.Contains (save.Error, ExifEditor.StructureWouldChange); + CollectionAssert.AreEqual (input, file.Render ().ToArray (), "nothing is written"); + } + + // Two SHORT strip-offset arrays that both fit, in two tables, name more values than half the data holds. + // Each is the first strip entry of its table, so both are read. The edit is refused and nothing is written. + [TestMethod] + [DataRow ("strips")] + [DataRow ("tiles")] + [DataRow ("thumb")] + public void Edit_RefusesWhenSharedValueArraysExceedTheData (string pair) + { + var tiff = StripBudgetTiff (pair, 60, 59); + var input = InCarrier ("png", tiff); + var file = Open (input, "a.png"); + file.Tag!.Comment = "New"; + + var save = file.SaveToFile ("/a.png", new MockFileSystem ()); + + Assert.IsFalse (save.IsSuccess, pair); + StringAssert.Contains (save.Error, "more strip, tile or thumbnail values than its data holds"); + CollectionAssert.AreEqual (input, file.Render ().ToArray (), $"{pair}: nothing is written"); + } + + // 49 + 49 offset values and one inline length value from each table is 100, exactly half of 200 bytes. A bound + // that refuses at equality would refuse this, and the comment would stay. + [TestMethod] + public void Edit_SavesWhenSharedValueArraysFillTheDataExactly () + { + var tiff = StripBudgetTiff ("strips", 49, 49); + var file = Open (InCarrier ("png", tiff), "a.png"); + file.Tag!.Comment = "New"; + + var save = file.SaveToFile ("/a.png", new MockFileSystem ()); + + Assert.IsTrue (save.IsSuccess, save.Error); + Assert.AreEqual (0, UserCommentsInEveryExifIfd (ExifOf (file.Render ().ToArray ())).Count); + } + + // Two tables share one array of a strip pair. That structure is not plain, so the comment stays and so does + // the strip. Both byte orders, and either array shared. + [TestMethod] + [DataRow ("offsets", false)] + [DataRow ("offsets", true)] + [DataRow ("lengths", false)] + [DataRow ("lengths", true)] + public void Edit_RefusesAStripNamedOnlyByTheSecondTableThatSharesAnArray (string shared, bool bigEndian) + { + var tiff = SharedPairTiff (shared, bigEndian); + var file = Open (InCarrier ("png", tiff), "a.png"); + file.Tag!.Comment = "New"; + + var save = file.SaveToFile ("/a.png", new MockFileSystem ()); + + var where = $"{shared} {(bigEndian ? "big-endian" : "little-endian")}"; + Assert.IsFalse (save.IsSuccess, where); + StringAssert.Contains (save.Error, "more than once", where); + CollectionAssert.AreEqual (tiff, ExifOf (file.Render ().ToArray ()), where); + } + + // exiftool 13.55 reads a type 13 (IFD) entry, so a table whose first remaining entry is type 13 stays + // readable and the ImageDescription after it stays. A bound that stops at 12 refuses this edit. + [TestMethod] + [DataRow (false)] + [DataRow (true)] + public void Edit_SavesWhenTheFirstKeptEntryHasIfdType (bool bigEndian) + { + var hill = bigEndian ? 0x48696C6C : 0x6C6C6948; + var tiff = new TiffBuilder (80, bigEndian).Header (8) + .Table (8, [(0x9286, 7, 4, 0x64636261), (0x0001, 13, 1, 0), (0x010E, 2, 4, hill)]) + .ToArray (); + Assert.AreEqual ("Hill", ExifReaderModel.Exiftool (tiff).Strings ()[0x010E], bigEndian ? "big-endian" : "little-endian"); + var file = Open (InCarrier ("png", tiff), "a.png"); + file.Tag!.Comment = "New"; + + var save = file.SaveToFile ("/a.png", new MockFileSystem ()); + + Assert.IsTrue (save.IsSuccess, save.Error); + Assert.AreEqual ("Hill", ExifReaderModel.Exiftool (ExifOf (file.Render ().ToArray ())).Strings ()[0x010E]); + } + + // Nothing of the field is in the block. The value-array bound is not a reason to refuse, and the Exif bytes stay. + [TestMethod] + public void Edit_OfATitle_SavesWhenValueArraysExceedTheDataAndNothingIsRemoved () + { + var tiff = StripBudgetTiff ("strips", 60, 59); + var input = InCarrier ("png", tiff); + var file = Open (input, "a.png"); + file.Tag!.Title = "New"; + + var save = file.SaveToFile ("/a.png", new MockFileSystem ()); + + Assert.IsTrue (save.IsSuccess, save.Error); + CollectionAssert.AreEqual (tiff, ExifOf (file.Render ().ToArray ())); + } + + // Length 200. IFD0 holds the UserComment and one SHORT offset array; IFD1 holds another. Each length entry is + // one inline SHORT. 60 + 59 + 2 is past half the data; 49 + 49 + 2 is exactly half. + static byte[] StripBudgetTiff (string pair, int first, int second) + { + var (off, len) = pair switch { + "tiles" => (0x0144, 0x0145), + "thumb" => (0x0201, 0x0202), + _ => (0x0111, 0x0117), + }; + return new TiffBuilder (200).Header (8) + .Table (8, [(0x9286, 7, 4, 0x64636261), (off, 3, first, 80), (len, 3, 1, 0)], next: 50) + .Table (50, [(off, 3, second, 82), (len, 3, 1, 0)]) + .ToArray (); + } + + // Length 200. The UserComment value is the eight bytes at 170. IFD0's strip ends at 168, so it does not cover + // them. IFD1 shares one array with IFD0 and its strip is those eight bytes. The arrays are out of line, so a + // second table hits the value cache. + static byte[] SharedPairTiff (string shared, bool bigEndian) + { + var tiff = new TiffBuilder (200, bigEndian).Header (8); + if (shared == "offsets") { + tiff.U32 (100, 160).U32 (104, 160) + .U16 (108, 4).U16 (110, 4).U16 (112, 4) + .U16 (114, 20).U16 (116, 20).U16 (118, 20) + .Table (8, [(0x9286, 7, 8, 170), (0x0111, 4, 2, 100), (0x0117, 3, 3, 108)], next: 50) + .Table (50, [(0x0111, 4, 2, 100), (0x0117, 3, 3, 114)]); + } else { + tiff.U16 (100, 8).U16 (102, 8).U16 (104, 8) + .U32 (108, 160).U32 (112, 160) + .U32 (116, 170).U32 (120, 170) + .Table (8, [(0x9286, 7, 8, 170), (0x0111, 4, 2, 108), (0x0117, 3, 3, 100)], next: 50) + .Table (50, [(0x0111, 4, 2, 116), (0x0117, 3, 3, 100)]); + } + + return tiff.Bytes (170, "strips!!"u8).ToArray (); + } + + // Removing the first entry leaves a format exiftool does not read (0 or 14) in front. Measured with + // exiftool 13.55 -a -G1 -s -v3: the kept tag (Make, DateTimeOriginal or InteropIndex) is shown before and + // absent once that format is first, in IFD0, IFD1, the Exif IFD, a SubIFD and an interoperability IFD, + // both byte orders. The edit is refused and nothing is written. The unchecked edit does drop the tag. + public static IEnumerable FirstEntryLost () + { + foreach (var kind in new[] { "IFD0", "IFD1", "Exif", "SubIFD", "Interop" }) + foreach (var type in new[] { 0, 14 }) + foreach (var big in new[] { false, true }) + yield return new object[] { kind, type, big }; + } + + [TestMethod] + [DynamicData (nameof (FirstEntryLost))] + public void Edit_RefusesWhenRemovingTheFirstEntryMakesTheNextOnesFormatUnreadable (string kind, int badType, bool bigEndian) + { + var (tiff, tag, text) = TableWhoseFirstEntryChanges (kind, badType, badIsTheComment: false, bigEndian); + Assert.AreEqual (text, ExifReaderModel.Exiftool (tiff).Strings ()[tag], $"{kind} type {badType}"); + var input = InCarrier ("png", tiff); + var file = Open (input, "a.png"); + file.Tag!.Comment = "New"; + + var save = file.SaveToFile ("/a.png", new MockFileSystem ()); + + var order = bigEndian ? "big-endian" : "little-endian"; + Assert.IsFalse (save.IsSuccess, $"{kind} type {badType} {order}"); + StringAssert.Contains (save.Error, "cannot be updated"); + CollectionAssert.AreEqual (input, file.Render ().ToArray (), $"{kind}: nothing is written"); + var after = ExifReaderModel.Exiftool (ExifOf (UncheckedComment (input))).Strings (); + Assert.IsFalse (after.ContainsKey (tag), $"{kind} type {badType}: the unchecked edit drops {text}"); + } + + // The first entry is a UserComment of a format exiftool does not read, so the table is dropped and the tag + // after it is hidden. Removing that UserComment makes the table readable (type 0 and 19, measured). Refused. + public static IEnumerable FirstEntryGained () + { + foreach (var kind in new[] { "IFD0", "IFD1", "Exif", "SubIFD", "Interop" }) + foreach (var type in new[] { 0, 19 }) + foreach (var big in new[] { false, true }) + yield return new object[] { kind, type, big }; + } + + [TestMethod] + [DynamicData (nameof (FirstEntryGained))] + public void Edit_RefusesWhenRemovingABadFirstEntryMakesTheTableReadable (string kind, int badType, bool bigEndian) + { + var (tiff, tag, text) = TableWhoseFirstEntryChanges (kind, badType, badIsTheComment: true, bigEndian); + Assert.IsFalse (ExifReaderModel.Exiftool (tiff).Strings ().ContainsKey (tag), $"{kind} type {badType}: the table is dropped"); + var input = InCarrier ("png", tiff); + var file = Open (input, "a.png"); + file.Tag!.Comment = "New"; + + var save = file.SaveToFile ("/a.png", new MockFileSystem ()); + + var order = bigEndian ? "big-endian" : "little-endian"; + Assert.IsFalse (save.IsSuccess, $"{kind} type {badType} {order}"); + StringAssert.Contains (save.Error, "cannot be updated"); + CollectionAssert.AreEqual (input, file.Render ().ToArray (), $"{kind}: nothing is written"); + Assert.AreEqual (text, ExifReaderModel.Exiftool (ExifOf (UncheckedComment (input))).Strings ()[tag], $"{kind}: the unchecked edit reveals {text}"); + } + + // A format exiftool skips only when it is not the first entry stays where it is. The comment is removed and + // DateTimeOriginal stays. Measured: type 14 in the third entry does not drop the Exif IFD. + [TestMethod] + [DataRow (0, false)] + [DataRow (14, false)] + [DataRow (0, true)] + [DataRow (14, true)] + public void Edit_SavesWhenABadFormatEntryStaysOffTheFirstPosition (int badType, bool bigEndian) + { + const int TextAt = 300; + var date = "2009:09:09 09:09:09\0"u8.ToArray (); + var tiff = new TiffBuilder (340, bigEndian).Header (8) + .Table (8, [(0x8769, 4, 1, 40)]) + .Table (40, [(0x9003, 2, date.Length, TextAt), (0x9286, 7, SecretUc.Length, 240), (0x0010, badType, 1, 0), (0x9004, 2, date.Length, TextAt)]) + .Bytes (240, SecretUc).Bytes (TextAt, date).ToArray (); + var file = Open (InCarrier ("png", tiff), "a.png"); + file.Tag!.Comment = "New"; + + var save = file.SaveToFile ("/a.png", new MockFileSystem ()); + + Assert.IsTrue (save.IsSuccess, save.Error); + Assert.AreEqual ("2009:09:09 09:09:09", ExifReaderModel.Exiftool (ExifOf (file.Render ().ToArray ())).Strings ()[0x9003]); + } + + // A comment edit does not remove GPS entries. A GPS table exiftool drops for its first entry stays dropped, and + // one it reads stays read. Measured: GPSLatitudeRef after a type-0 or type-14 entry is absent; in front of a + // type-14 entry it is "N". + [TestMethod] + [DataRow (0)] + [DataRow (14)] + public void Edit_KeepsAGpsTableUnreadWhenItsFirstEntryHasAFormatExiftoolDrops (int badType) + { + var tiff = new TiffBuilder (80).Header (8) + .Table (8, [(0x9286, 7, 4, 0x64636261), (0x8825, 4, 1, 40)]) + .Table (40, [(0x0010, badType, 1, 0), (0x0001, 2, 2, 0x4E)]) + .ToArray (); + Assert.IsFalse (ExifReaderModel.Exiftool (tiff).Summary ().Contains ("G0001", StringComparison.Ordinal), $"type {badType}"); + var file = Open (InCarrier ("png", tiff), "a.png"); + file.Tag!.Comment = "New"; + + var save = file.SaveToFile ("/a.png", new MockFileSystem ()); + + Assert.IsTrue (save.IsSuccess, save.Error); + Assert.IsFalse (ExifReaderModel.Exiftool (ExifOf (file.Render ().ToArray ())).Summary ().Contains ("G0001", StringComparison.Ordinal), $"type {badType}"); + } + + [TestMethod] + public void Edit_KeepsAGpsLatitudeRefThatStaysTheFirstEntry () + { + var tiff = new TiffBuilder (80).Header (8) + .Table (8, [(0x9286, 7, 4, 0x64636261), (0x8825, 4, 1, 40)]) + .Table (40, [(0x0001, 2, 2, 0x4E), (0x0010, 14, 1, 0)]) + .ToArray (); + Assert.IsTrue (ExifReaderModel.Exiftool (tiff).Summary ().Contains ("G0001=1", StringComparison.Ordinal)); + var file = Open (InCarrier ("png", tiff), "a.png"); + file.Tag!.Comment = "New"; + + var save = file.SaveToFile ("/a.png", new MockFileSystem ()); + + Assert.IsTrue (save.IsSuccess, save.Error); + Assert.IsTrue (ExifReaderModel.Exiftool (ExifOf (file.Render ().ToArray ())).Summary ().Contains ("G0001=1", StringComparison.Ordinal)); + } + + // IFD0's only entry is a UserComment of type 0, and its next IFD holds Make. exiftool follows a next IFD of an + // empty table and does not follow one of a table dropped for its first entry (measured, both byte orders). + // Removing the UserComment would make Make appear. Refused. + [TestMethod] + [DataRow (false)] + [DataRow (true)] + public void Edit_RefusesWhenRemovingTheOnlyBadFirstEntryFollowsTheNextIfd (bool bigEndian) + { + const int TextAt = 90; + var tiff = new TiffBuilder (100, bigEndian).Header (8) + .Table (8, [(0x9286, 0, SecretUc.Length, 40)], next: 60) + .Table (60, [(0x010F, 2, 6, TextAt)]) + .Bytes (40, SecretUc).Bytes (TextAt, "Canon\0"u8).ToArray (); + Assert.IsFalse (ExifReaderModel.Exiftool (tiff).Strings ().ContainsKey (0x010F), bigEndian ? "big-endian" : "little-endian"); + var input = InCarrier ("png", tiff); + var file = Open (input, "a.png"); + file.Tag!.Comment = "New"; + + var save = file.SaveToFile ("/a.png", new MockFileSystem ()); + + Assert.IsFalse (save.IsSuccess, save.Error); + StringAssert.Contains (save.Error, "cannot be updated"); + CollectionAssert.AreEqual (input, file.Render ().ToArray (), "nothing is written"); + Assert.AreEqual ("Canon", ExifReaderModel.Exiftool (ExifOf (UncheckedComment (input))).Strings ()[0x010F]); + } + + // UserComment, then a format exiftool does not read, then one tag that kind shows; or the UserComment itself + // carrying that format, in front of the tag. The strings are what exiftool 13.55 prints for these bytes. + static (byte[] Tiff, int Tag, string Text) TableWhoseFirstEntryChanges (string kind, int badType, bool badIsTheComment, bool bigEndian) + { + const int CommentAt = 240; + const int TextAt = 300; + var tag = kind == "Interop" ? 0x0001 : kind == "Exif" ? 0x9003 : 0x010F; + var text = kind == "Interop" ? "R98" : kind == "Exif" ? "2009:09:09 09:09:09" : "Canon"; + (int Tag, int Type, long Count, long Value) visible = kind switch { + "Interop" => (0x0001, 2, 4, bigEndian ? 0x52393800L : 0x00383952L), + "Exif" => (0x9003, 2, 20, TextAt), + _ => (0x010F, 2, 6, TextAt), + }; + (int, int, long, long) comment = (0x9286, badIsTheComment ? badType : 7, SecretUc.Length, CommentAt); + (int, int, long, long)[] entries = badIsTheComment ? [comment, visible] : [comment, (0x0010, badType, 1, 0), visible]; + var tiff = new TiffBuilder (360, bigEndian).Header (8); + switch (kind) { + case "IFD0": + tiff.Table (8, entries); + break; + case "IFD1": + tiff.Table (8, [(0x0100, 4, 1, 1)], next: 40).Table (40, entries); + break; + case "SubIFD": + tiff.Table (8, [(0x014A, 4, 1, 40)]).Table (40, entries); + break; + case "Exif": + tiff.Table (8, [(0x8769, 4, 1, 40)]).Table (40, entries); + break; + default: + tiff.Table (8, [(0x8769, 4, 1, 40)]).Table (40, [(0xA005, 4, 1, 80)]).Table (80, entries); + break; + } + + tiff.Bytes (CommentAt, SecretUc); + if (kind == "Exif") + tiff.Bytes (TextAt, "2009:09:09 09:09:09\0"u8); + else if (kind != "Interop") + tiff.Bytes (TextAt, "Canon\0"u8); + return (tiff.ToArray (), tag, text); + } + + static byte[] UncheckedComment (byte[] input) + { + var file = Open (input, "a.png"); + file.Tag!.Comment = "New"; + ExifEditor.SkipCheck = true; + try { + var save = file.SaveToFile ("/a.png", new MockFileSystem ()); + Assert.IsTrue (save.IsSuccess, save.Error); + return file.Render ().ToArray (); + } finally { + ExifEditor.SkipCheck = false; + } + } + + // The next IFD of an Exif, GPS, interoperability or SubIFD table is read by no one, but its thumbnail, strips or + // tiles are a protected range inside the Exif IFD the edit would compact. That is not plain, so the edit is refused. + [TestMethod] + [DataRow ("Exif", "thumbnail", false)] + [DataRow ("Exif", "strips", false)] + [DataRow ("Exif", "tiles", false)] + [DataRow ("GPS", "thumbnail", false)] + [DataRow ("GPS", "strips", false)] + [DataRow ("GPS", "tiles", false)] + [DataRow ("Interop", "thumbnail", false)] + [DataRow ("Interop", "strips", false)] + [DataRow ("Interop", "tiles", false)] + [DataRow ("SubIFD", "thumbnail", false)] + [DataRow ("SubIFD", "strips", false)] + [DataRow ("SubIFD", "tiles", false)] + [DataRow ("Exif", "thumbnail", true)] + [DataRow ("Exif", "strips", true)] + [DataRow ("Exif", "tiles", true)] + [DataRow ("GPS", "thumbnail", true)] + [DataRow ("GPS", "strips", true)] + [DataRow ("GPS", "tiles", true)] + [DataRow ("Interop", "thumbnail", true)] + [DataRow ("Interop", "strips", true)] + [DataRow ("Interop", "tiles", true)] + [DataRow ("SubIFD", "thumbnail", true)] + [DataRow ("SubIFD", "strips", true)] + [DataRow ("SubIFD", "tiles", true)] + public void Edit_RefusesWhenAProtectOnlyTablesDataLiesInTheCompactedTable (string parent, string pair, bool bigEndian) + { + var tiff = ProtectOnlyData (parent, pair, bigEndian).Tiff; + var input = InCarrier ("png", tiff); + var file = Open (input, "a.png"); + file.Tag!.Comment = "New"; + + var save = file.SaveToFile ("/a.png", new MockFileSystem ()); + AssertUnchangedRefusal (save, input, file.Render ().ToArray (), $"{parent} {pair} {(bigEndian ? "big-endian" : "little-endian")}"); + } + + // Compaction of the Exif IFD clears the count of another table. The count is the last two bytes of the Exif + // IFD's next-offset field, and the entry that follows is one the table's kind shows: ImageDescription "Hill", + // or GPSLatitudeRef "N" in a GPS table. That entry's tag and type are also the table's next offset, so a check + // that reads one entry past the edited count sees equal bytes and would save, dropping the tag. The edit is + // refused, and nothing is written. The unchecked edit does drop the tag. + [TestMethod] + [DataRow ("IFD1", false)] + [DataRow ("GPS", false)] + [DataRow ("Interop", false)] + [DataRow ("SubIFD", false)] + [DataRow ("IFD1", true)] + [DataRow ("GPS", true)] + [DataRow ("Interop", true)] + [DataRow ("SubIFD", true)] + public void Edit_RefusesWhenCompactionClearsTheCountOfATableThatEndsTheData (string kind, bool bigEndian) + { + var tiff = EndingTableWithAVisibleEntry (kind, bigEndian); + var before = ExifReaderModel.Exiftool (tiff); + var order = bigEndian ? "big-endian" : "little-endian"; + if (kind == "GPS") + Assert.IsTrue (before.Summary ().Contains ("G0001=1", StringComparison.Ordinal), $"{kind} {order}"); + else + Assert.AreEqual ("Hill", before.Strings ()[0x010E], $"{kind} {order}"); + var input = InCarrier ("png", tiff); + var file = Open (input, "a.png"); + file.Tag!.Comment = "New"; + + var save = file.SaveToFile ("/a.png", new MockFileSystem ()); + + Assert.IsFalse (save.IsSuccess, $"{kind} {order}"); + StringAssert.Contains (save.Error, "IFD tables that overlap"); + CollectionAssert.AreEqual (input, file.Render ().ToArray (), $"{kind}: nothing is written"); + var after = ExifReaderModel.Exiftool (ExifOf (UncheckedComment (input))); + if (kind == "GPS") + Assert.IsFalse (after.Summary ().Contains ("G0001", StringComparison.Ordinal), $"{kind}: the unchecked edit drops GPSLatitudeRef"); + else + Assert.IsFalse (after.Strings ().ContainsKey (0x010E), $"{kind}: the unchecked edit drops ImageDescription"); + } + + // Exif at 60 (two entries). Its next-offset field is bytes 86-89, and the last two of those are a count of 1 + // at 88. The entry starts at 90, past the bytes compaction clears, and the table's next offset equals that + // entry's tag and type. Both byte orders. Table() is not used for the ending table: it would overwrite the count. + static byte[] EndingTableWithAVisibleEntry (string kind, bool bigEndian) + { + const int Exif = 60; + const int Table = 88; + var exifNext = bigEndian ? 0x00000001L : 0x00010000L; + byte[] entry; + long tableNext; + if (kind == "GPS") { + entry = bigEndian + ? [0x00, 0x01, 0x00, 0x02, 0x00, 0x00, 0x00, 0x02, 0x4E, 0x00, 0x00, 0x00] + : [0x01, 0x00, 0x02, 0x00, 0x02, 0x00, 0x00, 0x00, 0x4E, 0x00, 0x00, 0x00]; + tableNext = bigEndian ? 0x00010002L : 0x00020001L; + } else { + entry = bigEndian + ? [0x01, 0x0E, 0x00, 0x02, 0x00, 0x00, 0x00, 0x04, 0x48, 0x69, 0x6C, 0x6C] + : [0x0E, 0x01, 0x02, 0x00, 0x04, 0x00, 0x00, 0x00, 0x48, 0x69, 0x6C, 0x6C]; + tableNext = bigEndian ? 0x010E0002L : 0x0002010EL; + } + + var t = new TiffBuilder (106, bigEndian).Header (8); + if (kind == "IFD1") + t.Table (8, [(0x8769, 4, 1, Exif)], next: Table); + else { + var pointer = kind switch { "GPS" => 0x8825, "Interop" => 0xA005, _ => 0x014A }; + t.Table (8, [(0x8769, 4, 1, Exif), (pointer, 4, 1, Table)]); + } + + return t.Table (Exif, [(0x9286, 7, 4, 0x64636261), (0x9003, 2, 4, bigEndian ? 0x32303234 : 0x34323032)], next: exifNext) + .Bytes (90, entry).U32 (102, tableNext).ToArray (); + } + + // ImageDescription "Hill", an Exif IFD whose UserComment is removed, and a protect-only table whose + // offset/length pair names the twelve bytes compaction clears. The Exif IFD's own next is that table; a GPS, + // interoperability or SubIFD table's next is that table, and the Exif IFD's next is 0. + static (byte[] Tiff, int ExifAt, int DataAt, int Protect, byte[] ExifNext) ProtectOnlyData (string parent, string pair, bool bigEndian) + { + var (offsetsTag, lengthsTag) = pair switch { + "strips" => (0x0111, 0x0117), + "tiles" => (0x0144, 0x0145), + _ => (0x0201, 0x0202), + }; + var hill = bigEndian ? 0x48696C6C : 0x6C6C6948; + var date = bigEndian ? 0x32303234 : 0x34323032; + var exifNext = parent == "Exif"; + var exifAt = exifNext ? 40 : 60; + var dataAt = exifNext ? 58 : 78; + var protect = exifNext ? 80 : 140; + var t = new TiffBuilder (protect + 30, bigEndian).Header (8); + if (exifNext) + t.Table (8, [(0x010E, 2, 4, hill), (0x8769, 4, 1, exifAt)]); + else { + var pointer = parent switch { "GPS" => 0x8825, "Interop" => 0xA005, _ => 0x014A }; + t.Table (8, [(0x010E, 2, 4, hill), (0x8769, 4, 1, exifAt), (pointer, 4, 1, 100)]); + t.Table (100, [(0x0000, 1, 4, 0x00000002)], next: protect); + } + + t.Table (exifAt, [(0x9286, 7, 4, 0x64636261), (0x9003, 2, 4, date)], next: exifNext ? protect : 0) + .Table (protect, [(offsetsTag, 4, 1, dataAt), (lengthsTag, 4, 1, 12)]); + // The Exif IFD's next is 80 when that next is the protect-only table, and 0 when another table's next is. + byte[] nextBytes = exifNext + ? (bigEndian ? [0x00, 0x00, 0x00, 0x50] : [0x50, 0x00, 0x00, 0x00]) + : [0x00, 0x00, 0x00, 0x00]; + return (t.ToArray (), exifAt, dataAt, protect, nextBytes); + } + + static void AssertUnchangedRefusal (FileWriteResult save, byte[] before, byte[] after, string because) + { + Assert.IsFalse (save.IsSuccess, $"{because}: {save.Error}"); + StringAssert.Contains (save.Error, "cannot be updated", because); + CollectionAssert.AreEqual (before, after, because); + } +} diff --git a/tests/TagLibSharp2.Tests/Image/ExifOutsideTests.cs b/tests/TagLibSharp2.Tests/Image/ExifOutsideTests.cs new file mode 100644 index 00000000..ad00ae70 --- /dev/null +++ b/tests/TagLibSharp2.Tests/Image/ExifOutsideTests.cs @@ -0,0 +1,811 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using TagLibSharp2.Image.Exif; +using TagLibSharp2.Tests.Core; +using static TagLibSharp2.Tests.Image.ImageTestBuilder; + +namespace TagLibSharp2.Tests.Image; + +/// +/// A length-changing edit saves and moves the bytes after the edited segment. A maker note's own bytes and a +/// trailer keep their contents. A pointer from the note at data after the image is not rewritten. +/// +[TestClass] +[TestCategory ("Unit")] +public class ExifOutsideTests +{ + static readonly byte[] Trailer = "TRAILER!"u8.ToArray (); + + static byte[] AssertCommentSaved (byte[] fileBytes, string name, string comment) + { + var file = Open (fileBytes, name); + file.Tag!.Comment = comment; + var save = file.SaveToFile ("/" + name, new MockFileSystem ()); + Assert.IsTrue (save.IsSuccess, save.Error); + var output = file.Render ().ToArray (); + Assert.AreEqual (comment, Open (output, name).Tag!.Comment); + if (fileBytes.AsSpan ().EndsWith (Trailer)) + CollectionAssert.AreEqual (Trailer, output[^Trailer.Length..]); + return output; + } + + // The 18-byte directory whose first entry starts with stays where it was. + static void AssertSameDirectory (byte[] before, byte[] after, byte[] tag) + { + var at = before.AsSpan ().IndexOf (tag); + Assert.IsTrue (at >= 2, "directory"); + CollectionAssert.AreEqual (before[(at - 2)..(at - 2 + 18)], after[(at - 2)..(at - 2 + 18)]); + } + + static byte[] PngChunkPayload (byte[] file, string type) + { + var at = file.AsSpan ().IndexOf (System.Text.Encoding.ASCII.GetBytes (type)); + Assert.IsTrue (at >= 4); + var length = System.Buffers.Binary.BinaryPrimitives.ReadInt32BigEndian (file.AsSpan (at - 4)); + return file[(at + 4)..(at + 4 + length)]; + } + + static void AssertCom (byte[] output, int at) => + CollectionAssert.AreEqual (new byte[] { 0xFF, 0xFE, 0x00, 0x05, (byte)'N', (byte)'e', (byte)'w' }, output[at..(at + 7)]); + + [TestMethod] + public void Comment_OfAJpegWhoseMakerNoteNamesTheTrailer_IsSaved () + { + var fileBytes = JpegWithExternalNote (located: true, trailer: true, comment: null); + var output = AssertCommentSaved (fileBytes, "a.jpg", "New"); + Assert.AreEqual (fileBytes.Length + 7, output.Length); + AssertSameDirectory (fileBytes, output, new byte[] { 0x01, 0x00, 0x07, 0x00 }); + } + + [TestMethod] + public void Comment_OfTheSameLength_LeavesTheTrailerWhereTheNoteNamesIt () + { + var fileBytes = JpegWithExternalNote (located: true, trailer: true, comment: "old"); + var file = Open (fileBytes, "a.jpg"); + file.Tag!.Comment = "new"; + var save = file.SaveToFile ("/a.jpg", new MockFileSystem ()); + + Assert.IsTrue (save.IsSuccess, save.Error); + var output = file.Render ().ToArray (); + CollectionAssert.AreEqual (Trailer, output[^Trailer.Length..]); + Assert.AreEqual (fileBytes.Length, output.Length); + } + + [TestMethod] + public void Comment_OfAJpegWithAnUnlocatedNoteAndATrailer_IsSaved () + { + var fileBytes = JpegWithExternalNote (located: false, trailer: true, comment: null); + var file = Open (fileBytes, "a.jpg"); + file.Tag!.Comment = "New"; + var save = file.SaveToFile ("/a.jpg", new MockFileSystem ()); + + Assert.IsTrue (save.IsSuccess, save.Error); + var output = file.Render ().ToArray (); + CollectionAssert.AreEqual (Trailer, output[^Trailer.Length..]); + AssertCom (output, 115); + CollectionAssert.AreEqual ("COMMENT!"u8.ToArray (), output[94..102]); + } + + [TestMethod] + public void Comment_OfAJpegWhoseNoteNamesTheByteAfterTheFile_IsSaved () + { + var fileBytes = JpegWithExternalNote (located: true, trailer: false, comment: null); + var file = Open (fileBytes, "a.jpg"); + file.Tag!.Comment = "New"; + var save = file.SaveToFile ("/a.jpg", new MockFileSystem ()); + + Assert.IsTrue (save.IsSuccess, save.Error); + var output = file.Render ().ToArray (); + AssertCom (output, 107); + Assert.AreEqual (-1, output.AsSpan ().IndexOf ("COMMENT!"u8)); + } + + [TestMethod] + public void Comment_OfAJpegWithAnUnlocatedNoteAndNoTrailer_IsSaved () + { + var fileBytes = JpegWithExternalNote (located: false, trailer: false, comment: null); + var file = Open (fileBytes, "a.jpg"); + file.Tag!.Comment = "New"; + var save = file.SaveToFile ("/a.jpg", new MockFileSystem ()); + + Assert.IsTrue (save.IsSuccess, save.Error); + var output = file.Render ().ToArray (); + AssertCom (output, 115); + CollectionAssert.AreEqual ("COMMENT!"u8.ToArray (), output[94..102]); + } + + [TestMethod] + public void Comment_ThatGrowsTheXmpPacket_IsSavedWhenTheNoteNamesTheTrailer () + { + var packet = "Old"; + var fileBytes = JpegWithExternalNote (located: true, trailer: true, comment: "abcde", xmp: packet); + var output = AssertCommentSaved (fileBytes, "a.jpg", "newer"); + Assert.IsTrue (output.Length > fileBytes.Length); + AssertSameDirectory (fileBytes, output, new byte[] { 0x01, 0x00, 0x07, 0x00 }); + } + + [TestMethod] + public void Comment_OfAPngWhoseMakerNoteNamesBytesAfterIend_IsSaved () + { + var fileBytes = PngWithExternalNote (); + var output = AssertCommentSaved (fileBytes, "a.png", "New"); + Assert.IsTrue (output.Length > fileBytes.Length); + AssertSameDirectory (fileBytes, output, new byte[] { 0x01, 0x00, 0x07, 0x00 }); + } + + [TestMethod] + public void ArtistAndComment_OfAPngWhoseNoteNamesBytesAfterIend_SavesBothFields () + { + var fileBytes = PngWithExternalNote (); + var file = Open (fileBytes, "a.png"); + file.Tag!.Artist = "Ada"; + file.Tag.Comment = "New"; + var save = file.SaveToFile ("/a.png", new MockFileSystem ()); + + Assert.IsTrue (save.IsSuccess, save.Error); + var output = file.Render ().ToArray (); + var again = Open (output, "a.png"); + Assert.AreEqual ("Ada", again.Tag!.Artist); + Assert.AreEqual ("New", again.Tag.Comment); + CollectionAssert.AreEqual (Trailer, output[^Trailer.Length..]); + Assert.IsTrue (output.Length > fileBytes.Length); + AssertSameDirectory (fileBytes, output, new byte[] { 0x01, 0x00, 0x07, 0x00 }); + } + + [TestMethod] + public void Comment_OfAPngWithAnUnlocatedNoteAndBytesAfterIend_IsSaved () + { + var fileBytes = PngWithUnlocatedNote (); + var file = Open (fileBytes, "a.png"); + file.Tag!.Comment = "New"; + var save = file.SaveToFile ("/a.png", new MockFileSystem ()); + + Assert.IsTrue (save.IsSuccess, save.Error); + var output = file.Render ().ToArray (); + CollectionAssert.AreEqual (Trailer, output[^Trailer.Length..]); + CollectionAssert.AreEqual ("Comment\0New"u8.ToArray (), output[135..146]); + } + + [TestMethod] + public void Comment_OfTheSameLength_IsSavedWhenAnUnlocatedNoteNamesNothing () + { + var fileBytes = JpegWithExternalNote (located: false, trailer: true, comment: "old"); + var file = Open (fileBytes, "a.jpg"); + file.Tag!.Comment = "new"; + var save = file.SaveToFile ("/a.jpg", new MockFileSystem ()); + + Assert.IsTrue (save.IsSuccess, save.Error); + var output = file.Render ().ToArray (); + CollectionAssert.AreEqual (Trailer, output[^Trailer.Length..]); + Assert.AreEqual (fileBytes.Length, output.Length); + } + + [TestMethod] + public void Comment_OfAJpegWithAnUnlocatedNoteAndNoEndOfImage_IsSaved () + { + var fileBytes = JpegWithExternalNote (located: false, trailer: false, comment: null); + // Drop the EOI and leave a marker prefix with no second byte, so the scan has no end of image. + fileBytes = [.. fileBytes[..^2], 0xFF]; + var file = Open (fileBytes, "a.jpg"); + file.Tag!.Comment = "New"; + var save = file.SaveToFile ("/a.jpg", new MockFileSystem ()); + + Assert.IsTrue (save.IsSuccess, save.Error); + var output = file.Render ().ToArray (); + AssertCom (output, 115); + CollectionAssert.AreEqual ("COMMENT!"u8.ToArray (), output[94..102]); + } + + [TestMethod] + public void Comment_OfAGifWithBytesAfterTheTrailer_IsSaved () + { + var gif = Concat (Gif (GifComment ("old")), "AFTER"u8.ToArray ()); + var file = Open (gif, "a.gif"); + file.Tag!.Comment = "new"; + var save = file.SaveToFile ("/a.gif", new MockFileSystem ()); + + Assert.IsTrue (save.IsSuccess, save.Error); + var output = file.Render ().ToArray (); + CollectionAssert.AreEqual ("AFTER"u8.ToArray (), output[^5..]); + } + + // Maker note at the start of its blob. When located, its one entry names the trailer. The comment segment, + // when present, is the same length as a later "newer" or "old"/"new" replacement. + static byte[] JpegWithExternalNote (bool located, bool trailer, string? comment, string? xmp = null) + { + byte[] Tiff (int offset) + { + var header = located ? Array.Empty () : "OLYMP\0\u0001\0"u8.ToArray (); + const int ifd0 = 8; + var exif = ifd0 + 2 + 12 + 4; + var note = exif + 2 + (2 * 12) + 4; + var noteLen = header.Length + 2 + 12 + 4; + var commentAt = note + noteLen; + var length = commentAt + 8; + var tiff = new TiffBuilder (length).Header (ifd0); + tiff.Table (ifd0, [(0x8769, 4, 1, exif)]); + tiff.Table (exif, [(0x927C, 7, noteLen, note), (0x9286, 7, 8, commentAt)]); + tiff.Bytes (note, header); + tiff.Entries (note + header.Length, (0x0001, 7, Trailer.Length, offset)); + tiff.Bytes (commentAt, "COMMENT!"u8); + return tiff.ToArray (); + } + + var segments = new List (); + if (comment is not null) + segments.Add (JpegSegment (0xFE, System.Text.Encoding.ASCII.GetBytes (comment))); + if (xmp is not null) + segments.Add (JpegXmp (xmp)); + byte[] Wrap (byte[] tiff) + { + var parts = new List { JpegExif (tiff) }; + parts.AddRange (segments); + return Jpeg (parts.ToArray ()); + } + + var wrapped = Wrap (Tiff (0)); + var offset = wrapped.Length - 12; + var jpeg = Wrap (Tiff (offset)); + return trailer ? Concat (jpeg, Trailer) : jpeg; + } + + static byte[] PngWithExternalNote () + { + byte[] Tiff (int offset) + { + const int ifd0 = 8; + var exif = ifd0 + 2 + 12 + 4; + var note = exif + 2 + (2 * 12) + 4; + var noteLen = 2 + 12 + 4; + var length = note + noteLen; + var tiff = new TiffBuilder (length).Header (ifd0); + tiff.Table (ifd0, [(0x8769, 4, 1, exif)]); + tiff.Table (exif, [(0x927C, 7, noteLen, note), (0x9286, 7, 4, 0x41424344)]); + tiff.Entries (note, (0x0001, 7, Trailer.Length, offset)); + return tiff.ToArray (); + } + + byte[] Wrap (byte[] tiff) => Concat (Png (PngChunk ("eXIf", tiff)), Trailer); + var probe = Wrap (Tiff (0)); + var marker = "II*"u8.ToArray (); + var tiffBase = 0; + for (var i = 0; i + 3 <= probe.Length; i++) { + if (probe[i] == marker[0] && probe[i + 1] == marker[1] && probe[i + 2] == marker[2]) { + tiffBase = i; + break; + } + } + + var offset = probe.Length - Trailer.Length - tiffBase; + return Wrap (Tiff (offset)); + } + + [TestMethod] + public void Comment_OfAJpegWhoseMarkerByteIsStuffed_IsSavedWhenTheNoteIsUnlocated () + { + var fileBytes = JpegWithExternalNote (located: false, trailer: true, comment: null); + var eoi = fileBytes.Length - Trailer.Length - 2; + fileBytes[eoi - 1] = 0x00; + var file = Open (fileBytes, "a.jpg"); + file.Tag!.Comment = "New"; + + var save = file.SaveToFile ("/a.jpg", new MockFileSystem ()); + + Assert.IsTrue (save.IsSuccess, save.Error); + var output = file.Render ().ToArray (); + CollectionAssert.AreEqual (Trailer, output[^Trailer.Length..]); + AssertCom (output, 115); + CollectionAssert.AreEqual ("COMMENT!"u8.ToArray (), output[94..102]); + } + + [TestMethod] + public void Comment_OfTheSameLength_IsSavedWhenThePngTrailerStays () + { + var fileBytes = PngNaming (fileAt: -1, comment: "abcd", between: false); + var file = Open (fileBytes, "a.png"); + file.Tag!.Comment = "wxyz"; + + var save = file.SaveToFile ("/a.png", new MockFileSystem ()); + + Assert.IsTrue (save.IsSuccess, save.Error); + var output = file.Render ().ToArray (); + CollectionAssert.AreEqual (Trailer, output[^Trailer.Length..]); + Assert.AreEqual (fileBytes.Length, output.Length); + } + + [TestMethod] + public void Comment_IsSavedWhenTheNamedByteIsStrictlyAfterThePngChunk () + { + var fileBytes = PngNaming (fileAt: -1, comment: "abcd", between: true); + var output = AssertCommentSaved (fileBytes, "a.png", "longer"); + Assert.IsTrue (output.Length > fileBytes.Length); + } + + [TestMethod] + public void Comment_OfTheSameLength_IsSavedWhenTheNoteNamesTheCrc () + { + var fileBytes = PngNaming (fileAt: int.MinValue, comment: "abcd", between: true); + var file = Open (fileBytes, "a.png"); + file.Tag!.Comment = "wxyz"; + + var save = file.SaveToFile ("/a.png", new MockFileSystem ()); + + Assert.IsTrue (save.IsSuccess, save.Error); + var output = file.Render ().ToArray (); + CollectionAssert.AreEqual (Trailer, output[^Trailer.Length..]); + Assert.AreEqual (fileBytes.Length, output.Length); + } + + [TestMethod] + public void Comment_IsSavedWhenTheSignedNoteNamesTheByteAfterIdat () + { + var fileBytes = PngNaming (fileAt: -4, comment: null, between: true, signature: true); + var output = AssertCommentSaved (fileBytes, "a.png", "New"); + Assert.IsTrue (output.Length > fileBytes.Length); + CollectionAssert.AreEqual (PngChunkPayload (fileBytes, "IDAT"), PngChunkPayload (output, "IDAT")); + } + + [TestMethod] + public void Comment_IsSavedWhenTheNoteNamesTheLastTrailerByte () + { + var fileBytes = PngNaming (fileAt: -2, comment: "abcd", between: true); + var output = AssertCommentSaved (fileBytes, "a.png", "longer"); + Assert.IsTrue (output.Length > fileBytes.Length); + } + + [TestMethod] + public void Comment_IsSavedWhenTheNoteNamesTheByteAfterIdat () + { + var fileBytes = PngNaming (fileAt: -3, comment: "abcd", between: true); + var output = AssertCommentSaved (fileBytes, "a.png", "longer"); + Assert.IsTrue (output.Length > fileBytes.Length); + CollectionAssert.AreEqual (PngChunkPayload (fileBytes, "IDAT"), PngChunkPayload (output, "IDAT")); + } + + [TestMethod] + public void Comment_OfAPngWhoseHexProfileIsNotLocated_IsSaved () + { + var fileBytes = PngWithUnlocatedHexProfile (); + var file = Open (fileBytes, "a.png"); + file.Tag!.Comment = "longer"; + + var save = file.SaveToFile ("/a.png", new MockFileSystem ()); + + Assert.IsTrue (save.IsSuccess, save.Error); + var output = file.Render ().ToArray (); + // The raw profile is zlib, so its bytes are not at one index on every runtime. The comment chunk is exact. + CollectionAssert.AreEqual (Trailer, output[^Trailer.Length..]); + CollectionAssert.AreEqual (Text ("Comment", "longer"), PngTextChunk (output, "tEXt", "Comment")); + Assert.AreEqual ("abcd", Open (fileBytes, "a.png").Tag!.Comment); + Assert.AreEqual ("longer", Open (output, "a.png").Tag!.Comment); + } + + // An Apple note carries its own "MM" header, so its offsets stay inside the note. The MPF image after the EOI + // is the gain map ShiftMpEntries already rewrites. UserComment and XPComment are the two comment copies. + [TestMethod] + [DataRow (false)] + [DataRow (true)] + public void Comment_OfAnAppleNoteWithAnMpfImage_IsSaved (bool xpComment) + { + var second = Jpeg (JpegSegment (0xFE, "gain map"u8.ToArray ())); + var fileBytes = MpfJpeg (JpegExif (AppleExif (xpComment)), [], second, out _); + var file = Open (fileBytes, "a.jpg"); + file.Tag!.Comment = "new"; + + var save = file.SaveToFile ("/a.jpg", new MockFileSystem ()); + + Assert.IsTrue (save.IsSuccess, save.Error); + var output = file.Render ().ToArray (); + CollectionAssert.AreEqual ("Apple iOS\0"u8.ToArray (), output[90..100]); + CollectionAssert.AreEqual (new byte[] { 0xFF, 0xFE, 0x00, 0x05, (byte)'n', (byte)'e', (byte)'w' }, output[201..208]); + CollectionAssert.AreEqual (second, output[MpfSecondImage (output)..], xpComment ? "XPComment" : "UserComment"); + } + + // A kept entry can name an offset past the file (TIFF type 12, eight bytes, so the value is a pointer). + // Bytes after the EOI are not that offset, so a comment edit still saves. + [TestMethod] + public void Comment_IsSavedWhenAKeptOffsetIsPastTheFileAndBytesFollowTheEoi () + { + const int ifd0 = 8; + var exif = ifd0 + 2 + 12 + 4; + var commentAt = exif + 2 + (2 * 12) + 4; + var tiff = new TiffBuilder (commentAt + 8).Header (ifd0); + tiff.Table (ifd0, [(0x8769, 4, 1, exif)]); + tiff.Table (exif, [(0x9003, 12, 1, 0x31323334), (0x9286, 7, 8, commentAt)]); + tiff.Bytes (commentAt, "COMMENT!"u8); + var fileBytes = Concat (Jpeg (JpegExif (tiff.ToArray ())), Trailer); + var file = Open (fileBytes, "a.jpg"); + file.Tag!.Comment = "New"; + + var save = file.SaveToFile ("/a.jpg", new MockFileSystem ()); + + Assert.IsTrue (save.IsSuccess, save.Error); + var output = file.Render ().ToArray (); + CollectionAssert.AreEqual (Trailer, output[^Trailer.Length..]); + AssertCom (output, 89); + Assert.AreEqual (-1, output.AsSpan ().IndexOf ("COMMENT!"u8)); + } + + // "NOTE", then a two-entry IFD. Entry 0 is four inline ASCII bytes. Entry 1 names five bytes at a TIFF offset: + // inside the file past the Exif block, past the end of the file, or exactly at that end. + [TestMethod] + [DataRow ("jpeg", "in-file", false, DisplayName = "jpeg entry past the Exif block")] + [DataRow ("jpeg", "past-file", true, DisplayName = "jpeg offset past the file, bytes after EOI")] + [DataRow ("jpeg", "past-file", false, DisplayName = "jpeg offset past the file, no trailing bytes")] + [DataRow ("jpeg", "file-end", true, DisplayName = "jpeg offset at the end of the file")] + [DataRow ("png", "in-file", false, DisplayName = "png entry past the eXIf chunk")] + [DataRow ("png", "past-file", true, DisplayName = "png offset past the file, bytes after IEND")] + [DataRow ("png", "past-file", false, DisplayName = "png offset past the file, no trailing bytes")] + [DataRow ("png", "file-end", true, DisplayName = "png offset at the end of the file")] + public void Comment_WhenAnAsciiPrefixedNoteNamesPastTheTiff (string carrier, string where, bool trailer) + { + var fileBytes = AsciiPrefixedNote (carrier, where, trailer); + var file = Open (fileBytes, carrier == "jpeg" ? "a.jpg" : "a.png"); + file.Tag!.Comment = "New"; + var save = file.SaveToFile (carrier == "jpeg" ? "/a.jpg" : "/a.png", new MockFileSystem ()); + Assert.IsTrue (save.IsSuccess, save.Error); + var output = file.Render ().ToArray (); + var again = Open (output, carrier == "jpeg" ? "a.jpg" : "a.png"); + Assert.AreEqual ("New", again.Tag!.Comment); + // The note is not located, so the old UserComment value stays where it was. The new comment is the marker + // spliced in front of the scan or the IDAT. + if (carrier == "jpeg") { + Assert.AreEqual (trailer ? 148 : 140, fileBytes.Length); + Assert.AreEqual (trailer ? 155 : 147, output.Length); + CollectionAssert.AreEqual (new byte[] { 0xFF, 0xFE, 0x00, 0x05, (byte)'N', (byte)'e', (byte)'w' }, output[123..130]); + CollectionAssert.AreEqual ("COMMENT!"u8.ToArray (), output[102..110]); + CollectionAssert.AreEqual ("abcd"u8.ToArray (), output[82..86]); + } else { + Assert.AreEqual (trailer ? 179 : 171, fileBytes.Length); + Assert.AreEqual (trailer ? 202 : 194, output.Length); + CollectionAssert.AreEqual ("Comment\0New"u8.ToArray (), output[151..162]); + CollectionAssert.AreEqual ("COMMENT!"u8.ToArray (), output[131..139]); + CollectionAssert.AreEqual ("abcd"u8.ToArray (), output[111..115]); + } + + if (trailer) + CollectionAssert.AreEqual (Trailer, output[^Trailer.Length..]); + } + + // A kept DOUBLE names an offset past the file, and bytes follow the EOI or IEND. An Apple note is not located, + // but it does not name that offset. Tag 0x9004 is the same bytes with no maker note. + [TestMethod] + [DataRow ("jpeg", true, DisplayName = "jpeg Apple note, kept offset past the file, trailer")] + [DataRow ("jpeg", false, DisplayName = "jpeg tag 0x9004, kept offset past the file, trailer")] + [DataRow ("png", true, DisplayName = "png Apple note, kept offset past the file, trailer")] + [DataRow ("png", false, DisplayName = "png tag 0x9004, kept offset past the file, trailer")] + public void Comment_IsSavedWhenAKeptOffsetPastTheFileMeetsAnAppleNoteAndATrailer (string carrier, bool makerNote) + { + var fileBytes = KeptOffsetPastFileWithAppleNote (carrier, makerNote); + var file = Open (fileBytes, carrier == "jpeg" ? "a.jpg" : "a.png"); + file.Tag!.Comment = "New"; + var save = file.SaveToFile (carrier == "jpeg" ? "/a.jpg" : "/a.png", new MockFileSystem ()); + + Assert.IsTrue (save.IsSuccess, save.Error); + var output = file.Render ().ToArray (); + var again = Open (output, carrier == "jpeg" ? "a.jpg" : "a.png"); + Assert.AreEqual ("New", again.Tag!.Comment); + var oldComment = makerNote ? "COMMENT!"u8.ToArray () : new byte[8]; + if (carrier == "jpeg") { + Assert.AreEqual (158, fileBytes.Length); + Assert.AreEqual (165, output.Length); + CollectionAssert.AreEqual (new byte[] { 0xFF, 0xFE, 0x00, 0x05, (byte)'N', (byte)'e', (byte)'w' }, output[133..140]); + CollectionAssert.AreEqual (oldComment, output[80..88]); + CollectionAssert.AreEqual ("Apple iOS\0"u8.ToArray (), output[88..98]); + } else { + Assert.AreEqual (189, fileBytes.Length); + Assert.AreEqual (212, output.Length); + CollectionAssert.AreEqual ("Comment\0New"u8.ToArray (), output[161..172]); + CollectionAssert.AreEqual (oldComment, output[109..117]); + CollectionAssert.AreEqual ("Apple iOS\0"u8.ToArray (), output[117..127]); + } + + CollectionAssert.AreEqual (Trailer, output[^Trailer.Length..]); + } + + // Nikon type 3 ("Nikon", NUL, version, then its own TIFF header) plus a JPEG appended after the EOI. + [TestMethod] + public void Comment_OfANikonType3NoteWithAPreviewAfterTheEoi_IsSaved () + { + var preview = Jpeg (JpegSegment (0xFE, "preview"u8.ToArray ())); + var fileBytes = Concat (Jpeg (JpegExif (NikonExif ())), preview); + var file = Open (fileBytes, "a.jpg"); + file.Tag!.Comment = "new"; + + var save = file.SaveToFile ("/a.jpg", new MockFileSystem ()); + + Assert.IsTrue (save.IsSuccess, save.Error); + var output = file.Render ().ToArray (); + CollectionAssert.AreEqual ("Nikon\0"u8.ToArray (), output[81..87]); + CollectionAssert.AreEqual (new byte[] { 0xFF, 0xFE, 0x00, 0x05, (byte)'n', (byte)'e', (byte)'w' }, output[112..119]); + CollectionAssert.AreEqual (preview, output[^preview.Length..]); + } + + // 0x9003 names the eight bytes of an APP12 segment or a prVt chunk just after the Exif block. Those bytes sit + // before the comment splice, so they stay put. 0x9004 names the trailer after EOI or IEND, which the splice moves. + [TestMethod] + [DataRow ("jpeg", true, DisplayName = "jpeg nearer DOUBLE and the trailer")] + [DataRow ("png", true, DisplayName = "png nearer DOUBLE and the trailer")] + [DataRow ("jpeg", false, DisplayName = "jpeg only the nearer DOUBLE")] + [DataRow ("png", false, DisplayName = "png only the nearer DOUBLE")] + public void Comment_WhenANearerKeptDoubleSitsBeforeTheSplice (string carrier, bool namesTrailer) + { + var fileBytes = NearerDouble (carrier, namesTrailer); + var nearAt = fileBytes.AsSpan ().IndexOf ("LOWBYTES"u8); + var file = Open (fileBytes, carrier == "jpeg" ? "a.jpg" : "a.png"); + file.Tag!.Comment = "New"; + var save = file.SaveToFile (carrier == "jpeg" ? "/a.jpg" : "/a.png", new MockFileSystem ()); + Assert.IsTrue (save.IsSuccess, save.Error); + var output = file.Render ().ToArray (); + Assert.AreEqual ("New", Open (output, carrier == "jpeg" ? "a.jpg" : "a.png").Tag!.Comment); + Assert.AreEqual (nearAt, output.AsSpan ().IndexOf ("LOWBYTES"u8)); + CollectionAssert.AreEqual (Trailer, output[^Trailer.Length..]); + Assert.IsTrue (output.Length > fileBytes.Length); + } + + // The trailer entry is recorded first and the nearer entry second. Both stay: the nearer bytes do not move, + // and the trailer keeps its contents at the new end. + [TestMethod] + [DataRow ("jpeg")] + [DataRow ("png")] + public void Comment_WhenTheTrailerDoubleIsRecordedBeforeTheNearerOne (string carrier) + { + var fileBytes = NearerDouble (carrier, namesTrailer: true, trailerFirst: true); + var nearAt = fileBytes.AsSpan ().IndexOf ("LOWBYTES"u8); + var output = AssertCommentSaved (fileBytes, carrier == "jpeg" ? "a.jpg" : "a.png", "New"); + Assert.AreEqual (nearAt, output.AsSpan ().IndexOf ("LOWBYTES"u8)); + Assert.IsTrue (output.Length > fileBytes.Length); + } + + // A kept DOUBLE names an offset past the file, and bytes follow the EOI. The note's second entry starts inside + // the TIFF and runs past its end, so it is not an offset past the file. The comment edit still saves. + [TestMethod] + public void Comment_IsSavedWhenAStraddlingNoteEntryMeetsAKeptOffsetPastTheFile () + { + var fileBytes = StraddlingNoteWithKeptOffsetPastFile (); + var file = Open (fileBytes, "a.jpg"); + file.Tag!.Comment = "New"; + var save = file.SaveToFile ("/a.jpg", new MockFileSystem ()); + + Assert.IsTrue (save.IsSuccess, save.Error); + var output = file.Render ().ToArray (); + Assert.AreEqual ("New", Open (output, "a.jpg").Tag!.Comment); + CollectionAssert.AreEqual (Trailer, output[^Trailer.Length..]); + Assert.IsTrue (output.Length > fileBytes.Length); + } + + // fileAt: -1 the trailer, -2 the last file byte, -3 the first IDAT payload byte, -4 the first byte of the IDAT + // chunk, int.MinValue the first CRC byte of eXIf. between puts a Title chunk after eXIf. signature prefixes Exif\0\0. + static byte[] PngNaming (int fileAt, string? comment, bool between, bool signature = false) + { + byte[] Tiff (int offset) + { + const int ifd0 = 8; + var exif = ifd0 + 2 + 12 + 4; + var note = exif + 2 + (2 * 12) + 4; + var noteLen = 2 + 12 + 4; + var length = note + noteLen; + var tiff = new TiffBuilder (length).Header (ifd0); + tiff.Table (ifd0, [(0x8769, 4, 1, exif)]); + tiff.Table (exif, [(0x927C, 7, noteLen, note), (0x9286, 7, 4, 0x41424344)]); + tiff.Entries (note, (0x0001, 7, Trailer.Length, offset)); + return tiff.ToArray (); + } + + byte[] Wrap (byte[] tiff) + { + var payload = signature ? Concat ("Exif\0\0"u8.ToArray (), tiff) : tiff; + var chunks = new List { PngChunk ("eXIf", payload) }; + if (between) + chunks.Add (Text ("Title", "t")); + if (comment is not null) + chunks.Add (Text ("Comment", comment)); + return Concat (Png (chunks.ToArray ()), Trailer); + } + + var probe = Wrap (Tiff (0)); + var marker = "II*"u8.ToArray (); + var tiffBase = 0; + for (var i = 0; i + 3 <= probe.Length; i++) { + if (probe[i] == marker[0] && probe[i + 1] == marker[1] && probe[i + 2] == marker[2]) { + tiffBase = i; + break; + } + } + + var tiffLength = Tiff (0).Length; + var at = fileAt switch { + -1 => probe.Length - Trailer.Length, + -2 => probe.Length - 1, + -3 => IndexOf (probe, "IDAT"u8) + 4, + -4 => IndexOf (probe, "IDAT"u8) - 3, + _ => tiffBase + tiffLength + }; + return Wrap (Tiff (at - tiffBase)); + } + + static int IndexOf (byte[] file, ReadOnlySpan needle) + { + var at = file.AsSpan ().IndexOf (needle); + return at < 0 ? 0 : at; + } + + // An unlocated maker note and a description that starts at the TIFF end, in a hex profile, with bytes after IEND. + // The profile's offsets address the decoded TIFF, so the bytes after IEND do not refuse the edit. + static byte[] PngWithUnlocatedHexProfile () + { + var header = "OLYMP\0\u0001\0"u8.ToArray (); + const int ifd0 = 8; + var exif = ifd0 + 2 + (2 * 12) + 4; + var note = exif + 2 + (2 * 12) + 4; + var noteLen = header.Length + 2 + 12 + 4; + var length = note + noteLen; + var tiff = new TiffBuilder (length).Header (ifd0); + tiff.Table (ifd0, [(0x010E, 2, 5, length), (0x8769, 4, 1, exif)]); + tiff.Table (exif, [(0x927C, 7, noteLen, note), (0x9286, 7, 4, 0x41424344)]); + tiff.Bytes (note, header); + tiff.Entries (note + header.Length, (0x0001, 7, 4, 0)); + return Concat (Png (RawProfile ("exif", tiff.ToArray ()), Text ("Comment", "abcd")), Trailer); + } + + // The note header is not a classic IFD, so the note is not located. Bytes after IEND are copied. + static byte[] PngWithUnlocatedNote () + { + var header = "OLYMP\0\u0001\0"u8.ToArray (); + const int ifd0 = 8; + var exif = ifd0 + 2 + 12 + 4; + var note = exif + 2 + (2 * 12) + 4; + var noteLen = header.Length + 2 + 12 + 4; + var length = note + noteLen; + var tiff = new TiffBuilder (length).Header (ifd0); + tiff.Table (ifd0, [(0x8769, 4, 1, exif)]); + tiff.Table (exif, [(0x927C, 7, noteLen, note), (0x9286, 7, 4, 0x41424344)]); + tiff.Bytes (note, header); + tiff.Entries (note + header.Length, (0x0001, 7, 4, 0)); + return Concat (Png (PngChunk ("eXIf", tiff.ToArray ())), Trailer); + } + + // Big-endian Exif, as an iPhone writes it. The Apple note starts "Apple iOS", NUL, version 1, "MM". + static byte[] AppleExif (bool xpComment) + { + var note = AppleMakerNote ([(0x0001, 4, 1, [0, 0, 0, 1])]); + var comment = xpComment ? System.Text.Encoding.Unicode.GetBytes ("xp comment\0") : Concat ("ASCII\0\0\0"u8.ToArray (), "from the phone"u8.ToArray ()); + return ExifWithNote (note, comment, xpComment); + } + + // "Nikon", NUL, type 3 version, then a TIFF header of the note's own. The version byte stops the prefix scan. + static byte[] NikonExif () + { + var note = new byte[18]; + "Nikon\0"u8.CopyTo (note); + note[6] = 0x02; + note[7] = 0x10; + "MM\0*"u8.CopyTo (note.AsSpan (10)); + note[17] = 8; + return ExifWithNote (note, Concat ("ASCII\0\0\0"u8.ToArray (), "blank"u8.ToArray ()), xpComment: false); + } + + static byte[] ExifWithNote (byte[] note, byte[] comment, bool xpComment) + { + const int ifd0 = 8; + var ifd0Count = xpComment ? 2 : 1; + var exif = ifd0 + 2 + (12 * ifd0Count) + 4; + var exifCount = xpComment ? 1 : 2; + var commentAt = exif + 2 + (12 * exifCount) + 4; + var noteAt = commentAt + comment.Length; + var tiff = new TiffBuilder (noteAt + note.Length, bigEndian: true).Header (ifd0); + if (xpComment) + tiff.Table (ifd0, [(0x8769, 4, 1, exif), (0x9C9C, 1, comment.Length, commentAt)]); + else + tiff.Table (ifd0, [(0x8769, 4, 1, exif)]); + if (xpComment) + tiff.Table (exif, [(0x927C, 7, note.Length, noteAt)]); + else + tiff.Table (exif, [(0x927C, 7, note.Length, noteAt), (0x9286, 7, comment.Length, commentAt)]); + tiff.Bytes (commentAt, comment); + tiff.Bytes (noteAt, note); + return tiff.ToArray (); + } + + // TIFF is 98 bytes: IFD0, the Exif IFD, "NOTE", a two-entry directory, then "COMMENT!". + // Entry 0's value field is the inline ASCII "abcd". Entry 1's offset is filled once the wrapped file's length is known. + static byte[] AsciiPrefixedNote (string carrier, string where, bool trailer) + { + const int ifd0 = 8; + const int exif = 26; + const int note = 56; + const int noteLen = 34; + const int commentAt = 90; + const int tiffLength = 98; + + byte[] Tiff (int offset) + { + var tiff = new TiffBuilder (tiffLength).Header (ifd0); + tiff.Table (ifd0, [(0x8769, 4, 1, exif)]); + tiff.Table (exif, [(0x927C, 7, noteLen, note), (0x9286, 7, 8, commentAt)]); + tiff.Bytes (note, "NOTE"u8); + tiff.Entries (note + 4, (0x0001, 2, 4, 0x64636261), (0x0002, 7, 5, offset)); + tiff.Bytes (commentAt, "COMMENT!"u8); + return tiff.ToArray (); + } + + byte[] Wrap (byte[] tiff) => carrier == "jpeg" ? Jpeg (JpegExif (tiff)) : Png (PngChunk ("eXIf", tiff)); + var probe = Wrap (Tiff (0)); + var tiffBase = probe.AsSpan ().IndexOf ("II*"u8); + var fileLength = probe.Length + (trailer ? Trailer.Length : 0); + var offset = where switch { + "in-file" => carrier == "jpeg" ? probe.Length - 7 - tiffBase : IndexOf (probe, "IDAT"u8) + 4 - tiffBase, + "past-file" => 0x100000, + _ => fileLength - tiffBase + }; + var body = Wrap (Tiff (offset)); + return trailer ? Concat (body, Trailer) : body; + } + + // Exif IFD: a kept DOUBLE past the file, an Apple-style note (or the same bytes under tag 0x9004), and UserComment. + static byte[] KeptOffsetPastFileWithAppleNote (string carrier, bool makerNote) + { + var note = AppleMakerNote ([(0x0001, 4, 1, new byte[] { 0, 0, 0, 1 })]); + const int ifd0 = 8; + const int exif = 26; + const int commentAt = 68; + const int noteAt = 76; + var tiff = new TiffBuilder (noteAt + note.Length).Header (ifd0); + tiff.Table (ifd0, [(0x8769, 4, 1, exif)]); + tiff.Table (exif, [(0x9003, 12, 1, 0x31323334), (makerNote ? 0x927C : 0x9004, 7, note.Length, noteAt), (0x9286, 7, 8, commentAt)]); + tiff.Bytes (commentAt, "COMMENT!"u8); + tiff.Bytes (noteAt, note); + var body = carrier == "jpeg" ? Jpeg (JpegExif (tiff.ToArray ())) : Png (PngChunk ("eXIf", tiff.ToArray ())); + return Concat (body, Trailer); + } + + // TIFF is 76 bytes: IFD0, an Exif IFD of three entries, then "COMMENT!". 0x9003's offset is the eight bytes + // just after the Exif block. 0x9004's offset is the trailer when it names one; otherwise the value is inline. + static byte[] NearerDouble (string carrier, bool namesTrailer, bool trailerFirst = false) + { + const int tiffLength = 76; + + byte[] Tiff (int near, int far) + { + var tiff = new TiffBuilder (tiffLength).Header (8); + tiff.Table (8, [(0x8769, 4, 1, 26)]); + (int, int, long, long) nearer = (trailerFirst ? 0x9004 : 0x9003, 12, 1, near); + (int, int, long, long) farther = namesTrailer ? (trailerFirst ? 0x9003 : 0x9004, 12, 1, far) : (0x9004, 3, 1, 1); + var first = trailerFirst ? farther : nearer; + var second = trailerFirst ? nearer : farther; + tiff.Table (26, [first, second, (0x9286, 7, 8, 68)]); + tiff.Bytes (68, "COMMENT!"u8); + return tiff.ToArray (); + } + + byte[] Wrap (byte[] tiff) => carrier == "jpeg" + ? Concat (Jpeg (JpegExif (tiff), JpegSegment (0xEC, "LOWBYTES"u8.ToArray ())), Trailer) + : Concat (Png (PngChunk ("eXIf", tiff), PngChunk ("prVt", "LOWBYTES"u8.ToArray ())), Trailer); + + var probe = Wrap (Tiff (0, 0)); + var tiffBase = probe.AsSpan ().IndexOf ("II*"u8); + var near = probe.AsSpan ().IndexOf ("LOWBYTES"u8) - tiffBase; + var far = probe.AsSpan ().IndexOf (Trailer) - tiffBase; + return Wrap (Tiff (near, far)); + } + + // "NOTE" then a two-entry IFD. Entry 0 is four inline ASCII bytes. Entry 1 names eight bytes that start four + // bytes before the TIFF ends. A kept DOUBLE names an offset past the file, and "TRAILER!" follows the EOI. + static byte[] StraddlingNoteWithKeptOffsetPastFile () + { + const int ifd0 = 8; + const int exif = 26; + const int note = 68; + const int noteLen = 34; + const int commentAt = 102; + const int tiffLength = 110; + var tiff = new TiffBuilder (tiffLength).Header (ifd0); + tiff.Table (ifd0, [(0x8769, 4, 1, exif)]); + tiff.Table (exif, [(0x9003, 12, 1, 0x31323334), (0x927C, 7, noteLen, note), (0x9286, 7, 8, commentAt)]); + tiff.Bytes (note, "NOTE"u8); + tiff.Entries (note + 4, (0x0001, 2, 4, 0x64636261), (0x0002, 7, 8, tiffLength - 4)); + tiff.Bytes (commentAt, "COMMENT!"u8); + return Concat (Jpeg (JpegExif (tiff.ToArray ())), Trailer); + } +} diff --git a/tests/TagLibSharp2.Tests/Image/ExifPlainPinTests.cs b/tests/TagLibSharp2.Tests/Image/ExifPlainPinTests.cs new file mode 100644 index 00000000..a8f9e07f --- /dev/null +++ b/tests/TagLibSharp2.Tests/Image/ExifPlainPinTests.cs @@ -0,0 +1,101 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Runtime.InteropServices; +using System.Text; +using TagLibSharp2.Core; +using TagLibSharp2.Image; +using TagLibSharp2.Image.Exif; +using TagLibSharp2.Image.Gif; +using TagLibSharp2.Image.Png; +using TagLibSharp2.Image.Svg; +using TagLibSharp2.Image.Tiff; +using TagLibSharp2.Tests.Core; +using TagLibSharp2.Tests.Kit; +using static TagLibSharp2.Tests.Image.ImageTestBuilder; + +namespace TagLibSharp2.Tests.Image; + +public partial class ExifPlainTests +{ + [TestMethod] + public void OneStripOffset_IsNotARepeatedPairTag () + { + var bytes = new TiffBuilder (40).Header (8).Table (8, [(0x9286, 7, 4, 0x41424344), (0x0111, 3, 1, 1)]).ToArray (); + var verdict = Judge (bytes, 0x9286); + + Assert.IsTrue (verdict.Plain, verdict.Why); + Assert.IsTrue (verdict.Removes); + } + + [TestMethod] + public void PairCounts_ThatExceedHalfTheBlock_AreNotPlain () + { + var over = new TiffBuilder (100).Header (8).Table (8, [(0x9286, 7, 4, 0x41424344), (0x0111, 3, 30, 40), (0x0117, 3, 26, 40)]).ToArray (); + var verdict = Judge (over, 0x9286); + Assert.IsFalse (verdict.Plain, verdict.Why); + Assert.AreEqual (PlainExif.OverBudget, verdict.Why); + } + + static PlainExif.Verdict Judge (byte[] bytes, int tag) + { + Assert.IsTrue (TiffReader.TryOpen (bytes, out var tiff, out var first)); + return PlainExif.Judge (tiff, IfdGraph.Walk (tiff, first), [tag]); + } + + [TestMethod] + public void ZeroCountStripOffset_IsPlain () + { + var bytes = new TiffBuilder (40).Header (8).Table (8, [(0x9286, 7, 4, 0x41424344), (0x0111, 3, 0, 0)]).ToArray (); + var verdict = Judge (bytes); + + Assert.IsTrue (verdict.Plain, verdict.Why); + Assert.IsNull (verdict.Why); + Assert.IsTrue (verdict.Removes); + } + + [TestMethod] + public void SkipCheck_StillRefusesWhenThePlanReadsPastHalfTheBlock () + { + var bytes = new TiffBuilder (100).Header (8) + .Table (8, [(0x9286, 7, 4, 0x41424344), (0x0111, 3, 30, 40), (0x0117, 3, 26, 40)]) + .ToArray (); + ExifEditor.SkipCheck = true; + try { + Assert.IsFalse (ExifEditor.TryRemove (bytes, 0, CommentTag (), "eXIf", out var changed, out var error)); + Assert.IsFalse (changed); + Assert.AreEqual ( + "The eXIf block names more strip, tile or thumbnail values than its data holds, so its copy of Comment cannot be updated.", + error); + } finally { + ExifEditor.SkipCheck = false; + } + } + + [TestMethod] + public void OverBudgetPlan_IsNotClean () + { + var bytes = new TiffBuilder (100).Header (8) + .Table (8, [(0x9286, 7, 4, 0x41424344), (0x0111, 3, 30, 40), (0x0117, 3, 26, 40)]) + .ToArray (); + Assert.IsTrue (TiffReader.TryOpen (bytes, out var tiff, out var first)); + + var plan = RemovalPlan.Mark (tiff, IfdGraph.Walk (tiff, first), [0x9286]); + + Assert.IsTrue (plan.ValueBudgetExceeded); + Assert.IsFalse (plan.IsClean ()); + } + + static PlainExif.Verdict Judge (byte[] bytes) + { + Assert.IsTrue (TiffReader.TryOpen (bytes, out var tiff, out var first)); + return PlainExif.Judge (tiff, IfdGraph.Walk (tiff, first), [0x9286]); + } + + static ImageTag CommentTag () + { + var tag = new ImageTag (MediaFormat.Png, ImageStores.Comment); + tag.Comment = "New"; + return tag; + } +} diff --git a/tests/TagLibSharp2.Tests/Image/ExifPlainTests.cs b/tests/TagLibSharp2.Tests/Image/ExifPlainTests.cs new file mode 100644 index 00000000..4638fc29 --- /dev/null +++ b/tests/TagLibSharp2.Tests/Image/ExifPlainTests.cs @@ -0,0 +1,915 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using TagLibSharp2.Core; +using TagLibSharp2.Image; +using TagLibSharp2.Image.Exif; +using TagLibSharp2.Image.Tiff; +using TagLibSharp2.Tests.Kit; +using static TagLibSharp2.Tests.Image.ExifTestData; + +namespace TagLibSharp2.Tests.Image; + +/// +/// A field edit runs only on plain Exif. A strip, tile or thumbnail offset or length that is not SHORT or LONG, +/// an array of those values that does not lie wholly in the data, an array of those values named more than once, +/// a complete pair that names more values than half the bytes, +/// a next-IFD field with only one, two or three of its four bytes, or a first entry whose readability would +/// change, is refused before a plan is built. The block is left as it was. A wholly absent next field is still +/// edited. A first-entry change that shows nothing new is still refused. +/// +[TestClass] +[TestCategory ("Unit")] +public partial class ExifPlainTests +{ + public static IEnumerable PairTypes () + { + (int Offsets, int Lengths)[] pairs = [(0x0111, 0x0117), (0x0144, 0x0145), (0x0201, 0x0202)]; + foreach (var littleEndian in new[] { true, false }) + foreach (var home in new[] { "IFD0", "IFD1", "Exif", "SubIFD", "Interop", "GPS" }) + foreach (var (offsets, lengths) in pairs) + foreach (var badType in new[] { 7, 8 }) + foreach (var offsetsBad in new[] { true, false }) + yield return [littleEndian, home, offsets, lengths, badType, offsetsBad]; + } + + [TestMethod] + [DynamicData (nameof (PairTypes))] + public void Edit_RefusesAPairTypedOtherThanShortOrLong (bool littleEndian, string home, int offsets, int lengths, int badType, bool offsetsBad) + { + var tiff = WithPair (littleEndian, home, offsets, lengths, offsetsBad ? badType : 4, offsetsBad ? 4 : badType); + var copy = (byte[])tiff.Clone (); + var tag = new ImageTag (MediaFormat.Png, ImageStores.CommentOnly) { Comment = "n" }; + + var saved = ExifEditor.TryRemove (tiff, 0, tag, "eXIf", out var changed, out var error); + + Assert.IsFalse (saved, $"{home} {(littleEndian ? "LE" : "BE")} {offsets:X4}/{lengths:X4} type {badType}: saved"); + Assert.IsFalse (changed); + StringAssert.Contains (error, "cannot be updated"); + StringAssert.Contains (error, "SHORT or LONG"); + CollectionAssert.AreEqual (copy, tiff); + } + + // The pair lives in `home`. A UserComment in the Exif IFD gives the edit something to remove. Every next-IFD + // field is present, and the other side of the pair is LONG, so the type is the only thing that is not plain. + static byte[] WithPair (bool littleEndian, string home, int offsets, int lengths, int offsetsType, int lengthsType) + { + const int Ifd0 = 8, Exif = 90, Ifd1 = 180, Sub = 270, Iop = 360, Gps = 450, Comment = 540; + var comment = SecretUc; + var ifd0 = new List<(int Tag, int Type, long Count, long Value)> { (0x8769, 4, 1, Exif) }; + var exif = new List<(int Tag, int Type, long Count, long Value)> { (0x9286, 7, comment.Length, Comment) }; + (int At, (int Tag, int Type, long Count, long Value)[] Entries)? extra = null; + long ifd0Next = 0; + (int, int, long, long)[] pair = [(offsets, offsetsType, 1, 600), (lengths, lengthsType, 1, 8)]; + switch (home) { + case "IFD0": + ifd0.AddRange (pair); + break; + case "Exif": + exif.AddRange (pair); + break; + case "IFD1": + extra = (Ifd1, pair); + ifd0Next = Ifd1; + break; + case "SubIFD": + extra = (Sub, pair); + ifd0.Add ((0x014A, 4, 1, Sub)); + break; + case "Interop": + extra = (Iop, pair); + exif.Add ((0xA005, 4, 1, Iop)); + break; + default: + extra = (Gps, pair); + ifd0.Add ((0x8825, 4, 1, Gps)); + break; + } + + var tiff = new TiffBuilder (Comment + comment.Length, bigEndian: !littleEndian).Header (Ifd0).Bytes (Comment, comment) + .Table (Ifd0, [.. ifd0], ifd0Next) + .Table (Exif, [.. exif]); + if (extra is var (at, entries)) + tiff.Table (at, entries); + return tiff.ToArray (); + } + + public static IEnumerable CutNextFields () + { + foreach (var littleEndian in new[] { true, false }) + foreach (var home in new[] { "IFD0", "IFD1", "Exif", "SubIFD", "Interop", "GPS" }) + foreach (var present in new[] { 0, 1, 2, 3, 4 }) + yield return [littleEndian, home, present, false]; + // An odd-aligned IFD0 still has 1, 2 or 3 next bytes. exiftool's directory-size rule is about those counts. + foreach (var littleEndian in new[] { true, false }) + foreach (var present in new[] { 1, 2, 3 }) + yield return [littleEndian, "IFD0", present, true]; + } + + // Zero or four next bytes are a whole field (absent or present). One, two or three bytes are cut short. + [TestMethod] + [DynamicData (nameof (CutNextFields))] + public void Edit_RefusesWhenANextFieldIsCutShort (bool littleEndian, string home, int present, bool odd) + { + var tiff = CutNext (littleEndian, home, present, odd); + var copy = (byte[])tiff.Clone (); + var tag = new ImageTag (MediaFormat.Png, ImageStores.CommentOnly) { Comment = "n" }; + var where = $"{home} {(littleEndian ? "LE" : "BE")} {present} byte{(present == 1 ? "" : "s")}{(odd ? " odd" : "")}"; + + var saved = ExifEditor.TryRemove (tiff, 0, tag, "eXIf", out var changed, out var error); + + if (present is 0 or 4) { + Assert.IsTrue (saved, $"{where}: {error}"); + Assert.IsTrue (changed, where); + return; + } + + Assert.IsFalse (saved, $"{where}: saved"); + Assert.IsFalse (changed, where); + StringAssert.Contains (error, "cannot be updated", where); + StringAssert.Contains (error, "cut short", where); + CollectionAssert.AreEqual (copy, tiff, where); + } + + // A cut-short next field is not plain, but a field the block does not hold is not removed, so the block is kept. + [TestMethod] + [DataRow (true)] + [DataRow (false)] + public void Edit_OfATitle_SavesWhenTheNextFieldIsCutShort (bool littleEndian) + { + var tiff = CutNext (littleEndian, "GPS", 1, odd: false); + var copy = (byte[])tiff.Clone (); + var tag = new ImageTag (MediaFormat.Png, (ImageStores)0x3F); + tag.ReadField (ImageStores.Title, "Old"); + tag.Title = "New"; + + var saved = ExifEditor.TryRemove (tiff, 0, tag, "eXIf", out var changed, out var error); + + Assert.IsTrue (saved, error); + Assert.IsFalse (changed); + CollectionAssert.AreEqual (copy, tiff); + } + + public static IEnumerable ReadableThenUnreadHomes () + { + foreach (var littleEndian in new[] { true, false }) + foreach (var home in new[] { "IFD0", "IFD1", "Exif", "SubIFD", "Interop" }) + yield return [littleEndian, home]; + } + + // The only entry exiftool reads is the UserComment. After it comes a type-0 entry and a next field of 0, so + // removing the comment drops the table and shows nothing new. That flip is still not plain. + [TestMethod] + [DynamicData (nameof (ReadableThenUnreadHomes))] + public void Edit_RefusesWhenTheOnlyReadableEntryGoesAndLeavesAnUnreadFirstEntry (bool littleEndian, string home) + { + var tiff = ReadableThenUnread (littleEndian, home); + var copy = (byte[])tiff.Clone (); + var where = $"{home} {(littleEndian ? "LE" : "BE")}"; + Assert.IsFalse (ExifReaderModel.Exiftool (tiff).Strings ().ContainsKey (0x010F), where); + var tag = new ImageTag (MediaFormat.Png, ImageStores.CommentOnly) { Comment = "n" }; + + var saved = ExifEditor.TryRemove (tiff, 0, tag, "eXIf", out var changed, out var error); + + Assert.IsFalse (saved, $"{where}: saved"); + Assert.IsFalse (changed, where); + StringAssert.Contains (error, "cannot be updated", where); + StringAssert.Contains (error, "first entry", where); + CollectionAssert.AreEqual (copy, tiff, where); + } + + // UserComment, then a type-0 entry the table would hide once it is first. The next field is present and zero. + static byte[] ReadableThenUnread (bool littleEndian, string home) + { + (int, int, long, long) comment = (0x9286, 7, 4, 0x61626364); + (int, int, long, long) hidden = (0x010F, 0, 1, 0); + static int Span (int entries) => 2 + (12 * entries) + 4; + var ifd0 = new List<(int, int, long, long)> (); + (int At, (int, int, long, long)[] Entries)? middle = null; + (int At, (int, int, long, long)[] Entries) edited; + long ifd0Next = 0; + switch (home) { + case "IFD0": + edited = (8, [comment, hidden]); + break; + case "IFD1": { + var ifd1 = 8 + Span (1); + ifd0.Add ((0x0100, 4, 1, 1)); + ifd0Next = ifd1; + edited = (ifd1, [comment, hidden]); + break; + } + case "Exif": { + var exif = 8 + Span (1); + ifd0.Add ((0x8769, 4, 1, exif)); + edited = (exif, [comment, hidden]); + break; + } + case "SubIFD": { + var sub = 8 + Span (1); + ifd0.Add ((0x014A, 4, 1, sub)); + edited = (sub, [comment, hidden]); + break; + } + default: { + var exif = 8 + Span (1); + var iop = exif + Span (1); + ifd0.Add ((0x8769, 4, 1, exif)); + middle = (exif, [(0xA005, 4, 1, iop)]); + edited = (iop, [comment, hidden]); + break; + } + } + + var end = edited.At + Span (edited.Entries.Length); + var tiff = new TiffBuilder (end, bigEndian: !littleEndian).Header (8); + if (home == "IFD0") + tiff.Table (8, edited.Entries); + else + tiff.Table (8, [.. ifd0], ifd0Next); + if (middle is var (midAt, midEntries)) + tiff.Table (midAt, midEntries); + if (home != "IFD0") + tiff.Table (edited.At, edited.Entries); + return tiff.ToArray (); + } + + // The home table is the last bytes of the file. Its entries fit; `present` bytes of its 4-byte next field do. + static byte[] CutNext (bool littleEndian, string home, int present, bool odd) + { + var ifd0 = odd ? 9 : 8; + (int, int, long, long) desc = (0x010E, 2, 2, 0x4142); + (int, int, long, long) comment = (0x9286, 7, 4, 0x61626364); + (int, int, long, long) date = (0x9003, 2, 4, 0x31323334); + (int, int, long, long) make = (0x010F, 2, 2, 0x4D); + (int, int, long, long) index = (0x0001, 2, 2, 0x5239); + static int Span (int entries) => 2 + (12 * entries) + 4; + + var ifd0Entries = new List<(int, int, long, long)> (); + (int At, (int, int, long, long)[] Entries)? middle = null; + (int At, (int, int, long, long)[] Entries) cut; + long ifd0Next = 0; + switch (home) { + case "IFD0": + cut = (ifd0, [desc, comment]); + break; + case "Exif": { + var exif = ifd0 + Span (1); + ifd0Entries.Add ((0x8769, 4, 1, exif)); + cut = (exif, [date, comment]); + break; + } + case "IFD1": { + var ifd1 = ifd0 + Span (2); + ifd0Entries.Add (desc); + ifd0Entries.Add (comment); + ifd0Next = ifd1; + cut = (ifd1, [make]); + break; + } + case "SubIFD": { + var sub = ifd0 + Span (3); + ifd0Entries.Add (desc); + ifd0Entries.Add (comment); + ifd0Entries.Add ((0x014A, 4, 1, sub)); + cut = (sub, [make]); + break; + } + case "Interop": { + var exif = ifd0 + Span (1); + var iop = exif + Span (3); + ifd0Entries.Add ((0x8769, 4, 1, exif)); + middle = (exif, [date, comment, (0xA005, 4, 1, iop)]); + cut = (iop, [index]); + break; + } + default: { + var gps = ifd0 + Span (3); + ifd0Entries.Add (desc); + ifd0Entries.Add (comment); + ifd0Entries.Add ((0x8825, 4, 1, gps)); + cut = (gps, [index]); + break; + } + } + + var full = cut.At + Span (cut.Entries.Length); + var kept = cut.At + 2 + (12 * cut.Entries.Length) + present; + var tiff = new TiffBuilder (full, bigEndian: !littleEndian).Header (ifd0); + if (home == "IFD0") + tiff.Table (ifd0, cut.Entries); + else + tiff.Table (ifd0, [.. ifd0Entries], ifd0Next); + if (middle is var (midAt, midEntries)) + tiff.Table (midAt, midEntries); + if (home != "IFD0") + tiff.Table (cut.At, cut.Entries); + return tiff.ToArray ()[..kept]; + } + + public static IEnumerable SharedArrays () + { + foreach (var littleEndian in new[] { true, false }) + foreach (var home in new[] { "IFD1", "Exif", "SubIFD", "Interop", "GPS" }) + foreach (var (offsets, lengths) in new[] { (0x0111, 0x0117), (0x0144, 0x0145), (0x0201, 0x0202) }) + yield return [littleEndian, home, offsets, lengths]; + } + + [TestMethod] + [DynamicData (nameof (SharedArrays))] + public void Edit_RefusesWhenTwoTablesNameOneArray (bool littleEndian, string home, int offsets, int lengths) + { + var tiff = Shared (littleEndian, home, offsets, lengths); + var copy = (byte[])tiff.Clone (); + var tag = new ImageTag (MediaFormat.Png, ImageStores.CommentOnly) { Comment = "n" }; + + var saved = ExifEditor.TryRemove (tiff, 0, tag, "eXIf", out var changed, out var error); + + Assert.IsFalse (saved, $"{home} {(littleEndian ? "LE" : "BE")} {offsets:X4}: saved"); + Assert.IsFalse (changed); + StringAssert.Contains (error, "cannot be updated"); + StringAssert.Contains (error, "more than once"); + CollectionAssert.AreEqual (copy, tiff); + } + + [TestMethod] + [DataRow (true)] + [DataRow (false)] + public void Edit_RefusesWhenOneArrayIsBothSidesOfAPair (bool littleEndian) + { + const int Arr = 80; + var tiff = new TiffBuilder (220, bigEndian: !littleEndian).Header (8) + .U16 (Arr, 100).U16 (Arr + 2, 100).U16 (Arr + 4, 100) + .Table (8, [(0x9286, 7, 4, 0x61626364), (0x0111, 3, 3, Arr), (0x0117, 3, 3, Arr)]) + .ToArray (); + var copy = (byte[])tiff.Clone (); + var tag = new ImageTag (MediaFormat.Png, ImageStores.CommentOnly) { Comment = "n" }; + + var saved = ExifEditor.TryRemove (tiff, 0, tag, "eXIf", out _, out var error); + + Assert.IsFalse (saved, error); + StringAssert.Contains (error, "more than once"); + CollectionAssert.AreEqual (copy, tiff); + } + + // s = 10, 20, 40, 80 is the reported series (about 11 KB, 41 KB, 164 KB, 653 KB). Recording one range per + // cross-pair is superlinear and exhausts a 1 GB heap at s = 80. The refusal counts names and stops. + [TestMethod] + [DoNotParallelize] + public void Edit_CrossPairedSeries_IsRefusedInBoundedMemory () + { + var crossRefused = true; + Bounds.AssertLinearAllocation ( + tables => Cross ((int)Math.Ceiling (Math.Sqrt (tables)), 3, littleEndian: true), + tiff => crossRefused &= !Edit (tiff).Saved, + 100, + runs: 3); + Assert.IsTrue (crossRefused); + + foreach (var (s, least) in new[] { (10, 8_000), (20, 30_000), (40, 100_000), (80, 600_000) }) { + var tiff = Cross (s, 17 * s, littleEndian: true); + Assert.IsTrue (tiff.Length > least, $"s={s}: {tiff.Length} bytes"); + _ = Edit (tiff); + (bool Saved, string? Error) edit = default; + var allocated = Bounds.AssertAllocatesAtMost (Math.Max (8_000_000L, tiff.Length * 40L), () => edit = Edit (tiff), $"s={s}"); + Assert.IsFalse (edit.Saved, edit.Error); + StringAssert.Contains (edit.Error, "more than once"); + Assert.IsTrue (allocated < tiff.Length * 40L, $"s={s} allocated {allocated}"); + } + + var child = KitChild.Run (TimeSpan.FromSeconds (60), "kit-exif-cross", "80"); + Assert.AreEqual (0, child.ExitCode, child.Describe ()); + StringAssert.Contains (child.Output, "more than once"); + } + + /// The s = 80 cross-pair file, edited under the child's 1 GB heap. Exit 0 when the edit is refused. + internal static int CrossInChild (int s) + { + var tiff = Cross (s, 17 * s, littleEndian: true); + var edit = Edit (tiff); + Console.WriteLine ($"bytes={tiff.Length}"); + Console.WriteLine (edit.Saved ? "saved" : edit.Error); + return edit.Saved ? 1 : 0; + } + + static (bool Saved, string? Error) Edit (byte[] tiff) + { + var tag = new ImageTag (MediaFormat.Png, ImageStores.CommentOnly) { Comment = "n" }; + var saved = ExifEditor.TryRemove (tiff, 0, tag, "eXIf", out _, out var error); + return (saved, error); + } + + [TestMethod] + [DataRow (true)] + [DataRow (false)] + public void Edit_RefusesCrossPairedArrays (bool littleEndian) + { + var tiff = Cross (2, 3, littleEndian); + var copy = (byte[])tiff.Clone (); + var tag = new ImageTag (MediaFormat.Png, ImageStores.CommentOnly) { Comment = "n" }; + + var saved = ExifEditor.TryRemove (tiff, 0, tag, "eXIf", out _, out var error); + + Assert.IsFalse (saved, littleEndian ? "LE saved" : "BE saved"); + StringAssert.Contains (error, "more than once"); + CollectionAssert.AreEqual (copy, tiff); + } + + // Two tables name one offsets array and different length arrays. The comment gives the edit a copy to remove. + static byte[] Shared (bool littleEndian, string home, int offsets, int lengths) + { + const int Ifd0 = 8, Exif = 120, Other = 200, Arr = 320; + var tiff = new TiffBuilder (400, bigEndian: !littleEndian).Header (Ifd0) + .U16 (Arr, 360).U16 (Arr + 2, 360).U16 (Arr + 4, 360) + .U16 (Arr + 8, 4).U16 (Arr + 10, 4).U16 (Arr + 12, 4) + .U16 (Arr + 16, 4).U16 (Arr + 18, 4).U16 (Arr + 20, 4); + var ifd0 = new List<(int, int, long, long)> { (0x9286, 7, 4, 0x61626364), (offsets, 3, 3, Arr), (lengths, 3, 3, Arr + 8) }; + (int, int, long, long)[] second = [(offsets, 3, 3, Arr), (lengths, 3, 3, Arr + 16)]; + switch (home) { + case "IFD1": + tiff.Table (Ifd0, [.. ifd0], Other).Table (Other, second); + break; + case "Exif": + ifd0.Add ((0x8769, 4, 1, Exif)); + tiff.Table (Ifd0, [.. ifd0]).Table (Exif, second); + break; + case "SubIFD": + ifd0.Add ((0x014A, 4, 1, Other)); + tiff.Table (Ifd0, [.. ifd0]).Table (Other, second); + break; + case "Interop": + ifd0.Add ((0x8769, 4, 1, Exif)); + tiff.Table (Ifd0, [.. ifd0]).Table (Exif, [(0xA005, 4, 1, Other)]).Table (Other, second); + break; + default: + ifd0.Add ((0x8825, 4, 1, Other)); + tiff.Table (Ifd0, [.. ifd0]).Table (Other, second); + break; + } + + return tiff.ToArray (); + } + + // s offset arrays and s length arrays, and s² SubIFDs. Table (i, j) names offset array i and length array j. + static byte[] Cross (int s, int k, bool littleEndian) + { + var tables = s * s; + const int Ifd0 = 8; + var exif = Ifd0 + 2 + 24 + 4; + var offsets = exif + 2 + 12 + 4; + var tabs = offsets + (4 * tables); + var arrayA = tabs + (30 * tables); + var arrayB = arrayA + (2 * k * s); + var commentAt = arrayB + (2 * k * s); + var comment = SecretUc; + var tiff = new TiffBuilder (commentAt + comment.Length, bigEndian: !littleEndian).Header (Ifd0).Bytes (commentAt, comment); + for (var n = 0; n < tables; n++) + tiff.U32 (offsets + (4 * n), tabs + (30 * n)); + for (var n = 0; n < k * s; n++) { + tiff.U16 (arrayA + (2 * n), 8); + tiff.U16 (arrayB + (2 * n), 4); + } + + tiff.Table (Ifd0, [(0x8769, 4, 1, exif), (0x014A, 4, tables, offsets)]) + .Table (exif, [(0x9286, 7, comment.Length, commentAt)]); + for (var i = 0; i < s; i++) + for (var j = 0; j < s; j++) + tiff.Table (tabs + (30 * ((i * s) + j)), [(0x0111, 3, k, arrayA + (2 * k * i)), (0x0117, 3, k, arrayB + (2 * k * j))]); + return tiff.ToArray (); + } + + public static IEnumerable OverBudgetPairs () + { + foreach (var littleEndian in new[] { true, false }) + foreach (var home in new[] { "IFD0", "IFD1", "Exif", "SubIFD", "Interop", "GPS" }) + foreach (var (offsets, lengths) in new[] { (0x0111, 0x0117), (0x0144, 0x0145), (0x0201, 0x0202) }) + yield return [littleEndian, home, offsets, lengths]; + } + + // Two complete pairs name more values than half the bytes. The refusal reads no value array: the same + // entries a title edit walks, and nothing more. + [TestMethod] + [DynamicData (nameof (OverBudgetPairs))] + public void Edit_RefusesAnOverBudgetPairBeforeReadingItsValues (bool littleEndian, string home, int offsets, int lengths) + { + var tiff = OverBudget (littleEndian, home, offsets, lengths); + var copy = (byte[])tiff.Clone (); + var where = $"{home} {(littleEndian ? "LE" : "BE")} {offsets:X4}"; + var title = new ImageTag (MediaFormat.Png, ImageStores.Png); + title.ReadField (ImageStores.Title, "Old"); + title.Title = "New"; + + IfdSteps.Count = 0; + Assert.IsTrue (ExifEditor.TryRemove ((byte[])tiff.Clone (), 0, title, "eXIf", out _, out var titleError), $"{where}: {titleError}"); + var idle = IfdSteps.Count; + + IfdSteps.Count = 0; + var tag = new ImageTag (MediaFormat.Png, ImageStores.CommentOnly) { Comment = "n" }; + var saved = ExifEditor.TryRemove (tiff, 0, tag, "eXIf", out var changed, out var error); + + Assert.IsFalse (saved, $"{where}: saved"); + Assert.IsFalse (changed, where); + StringAssert.Contains (error, "cannot be updated", where); + StringAssert.Contains (error, "more strip, tile or thumbnail values than its data holds", where); + CollectionAssert.AreEqual (copy, tiff, where); + Assert.AreEqual (idle, IfdSteps.Count, $"{where}: a refusal read value arrays ({IfdSteps.Count} steps, a title edit took {idle})"); + } + + // 60 + 59 offset values and one inline length from each table. The arrays overlap in the file and still fit, + // and their counts sum to more than half the bytes. Both tables are walked. + static byte[] OverBudget (bool littleEndian, string home, int offsets, int lengths) + { + const int Ifd0 = 8; + var big = new (int, int, long, long)[] { (offsets, 3, 60, 0), (lengths, 3, 1, 1) }; + var small = new (int, int, long, long)[] { (offsets, 3, 59, 0), (lengths, 3, 1, 1) }; + var comment = (0x9286, 7, 4L, 0x61626364L); + int length, arrayAt; + TiffBuilder tiff; + switch (home) { + case "IFD0": + length = 200; + arrayAt = 80; + tiff = new TiffBuilder (length, bigEndian: !littleEndian).Header (Ifd0); + big[0].Item4 = arrayAt; + small[0].Item4 = arrayAt + 2; + tiff.Table (Ifd0, [comment, big[0], big[1]], 50).Table (50, small); + break; + case "IFD1": + length = 200; + arrayAt = 80; + tiff = new TiffBuilder (length, bigEndian: !littleEndian).Header (Ifd0); + big[0].Item4 = arrayAt; + small[0].Item4 = arrayAt + 2; + tiff.Table (Ifd0, [comment, small[0], small[1]], 50).Table (50, big); + break; + case "Interop": + length = 230; + arrayAt = 110; + tiff = new TiffBuilder (length, bigEndian: !littleEndian).Header (Ifd0); + big[0].Item4 = arrayAt; + small[0].Item4 = arrayAt + 2; + tiff.Table (Ifd0, [comment, small[0], small[1], (0x8769, 4, 1, 62)]) + .Table (62, [(0xA005, 4, 1, 80)]) + .Table (80, big); + break; + default: + length = 212; + arrayAt = 92; + var pointer = home switch { "Exif" => 0x8769, "SubIFD" => 0x014A, _ => 0x8825 }; + tiff = new TiffBuilder (length, bigEndian: !littleEndian).Header (Ifd0); + big[0].Item4 = arrayAt; + small[0].Item4 = arrayAt + 2; + tiff.Table (Ifd0, [comment, small[0], small[1], (pointer, 4, 1, 62)]).Table (62, big); + break; + } + + return tiff.ToArray (); + } + + public static IEnumerable LonePairSides () + { + foreach (var littleEndian in new[] { true, false }) + foreach (var (offsets, lengths) in new[] { (0x0111, 0x0117), (0x0144, 0x0145), (0x0201, 0x0202) }) + yield return [littleEndian, offsets, lengths]; + } + + // Each table names one side of a pair, and each array fits. A lone offset or length is not summed, so the + // counts stay under half the bytes and the comment is removed. + [TestMethod] + [DynamicData (nameof (LonePairSides))] + public void Edit_SavesWhenEachTableNamesOnlyOneSideOfAPair (bool littleEndian, int offsets, int lengths) + { + var tiff = LoneSides (littleEndian, offsets, lengths); + var copy = (byte[])tiff.Clone (); + var where = $"{(littleEndian ? "LE" : "BE")} {offsets:X4}"; + var tag = new ImageTag (MediaFormat.Png, ImageStores.CommentOnly) { Comment = "n" }; + + var saved = ExifEditor.TryRemove (tiff, 0, tag, "eXIf", out var changed, out var error); + + Assert.IsTrue (saved, $"{where}: {error}"); + Assert.IsTrue (changed, where); + CollectionAssert.AreNotEqual (copy, tiff, where); + } + + // IFD0 names the offset side (60 values at 80) and IFD1 names the length side (41 values at 80). 60 + 41 is + // over half of 200, and neither table has both sides. + static byte[] LoneSides (bool littleEndian, int offsets, int lengths) => + new TiffBuilder (200, bigEndian: !littleEndian).Header (8) + .Table (8, [(0x9286, 7, 4, 0x61626364), (offsets, 3, 60, 80)], 40) + .Table (40, [(lengths, 3, 41, 80)]) + .ToArray (); + + public static IEnumerable InlineFourBytePairs () + { + foreach (var littleEndian in new[] { true, false }) { + foreach (var (offsets, lengths) in new[] { (0x0111, 0x0117), (0x0144, 0x0145) }) + yield return [littleEndian, 3, 2, offsets, lengths]; + foreach (var (offsets, lengths) in new[] { (0x0111, 0x0117), (0x0144, 0x0145), (0x0201, 0x0202) }) + yield return [littleEndian, 4, 1, offsets, lengths]; + } + } + + // Four bytes is still the entry's own value field: a SHORT count of 2, or a LONG count of 1. Two such entries + // may hold the same word and stay two arrays. The comment is removed. + [TestMethod] + [DynamicData (nameof (InlineFourBytePairs))] + public void Edit_SavesWhenAnInlinePairValueIsExactlyFourBytes (bool littleEndian, int type, int count, int offsets, int lengths) + { + var tiff = InlineFourBytes (littleEndian, type, count, offsets, lengths); + var copy = (byte[])tiff.Clone (); + var where = $"{(littleEndian ? "LE" : "BE")} type {type} count {count} {offsets:X4}"; + var tag = new ImageTag (MediaFormat.Png, ImageStores.CommentOnly) { Comment = "n" }; + + var saved = ExifEditor.TryRemove (tiff, 0, tag, "eXIf", out var changed, out var error); + + Assert.IsTrue (saved, $"{where}: {error}"); + Assert.IsTrue (changed, where); + CollectionAssert.AreNotEqual (copy, tiff, where); + } + + // Both sides store the word 100. That word is inside each entry. The bytes it names, 100..200, sit past the table. + static byte[] InlineFourBytes (bool littleEndian, int type, int count, int offsets, int lengths) => + new TiffBuilder (220, bigEndian: !littleEndian).Header (8) + .Table (8, [(0x9286, 7, 4, 0x61626364), (offsets, type, count, 100), (lengths, type, count, 100)]) + .ToArray (); + + public static IEnumerable ArraysAtZero () + { + foreach (var littleEndian in new[] { true, false }) + foreach (var (offsets, lengths) in new[] { (0x0111, 0x0117), (0x0144, 0x0145), (0x0201, 0x0202) }) + yield return [littleEndian, offsets, lengths]; + } + + // Both sides name the same three SHORT values at offset 0. That array fits, and it is one array, so the edit is + // refused before a plan is built. A budget refusal is a different reason. + [TestMethod] + [DynamicData (nameof (ArraysAtZero))] + public void Edit_RefusesWhenBothSidesNameTheArrayAtOffsetZero (bool littleEndian, int offsets, int lengths) + { + var tiff = ArrayAtZero (littleEndian, offsets, lengths); + var copy = (byte[])tiff.Clone (); + var where = $"{(littleEndian ? "LE" : "BE")} {offsets:X4}"; + var tag = new ImageTag (MediaFormat.Png, ImageStores.CommentOnly) { Comment = "n" }; + + var saved = ExifEditor.TryRemove (tiff, 0, tag, "eXIf", out var changed, out var error); + + Assert.IsFalse (saved, $"{where}: saved"); + Assert.IsFalse (changed, where); + StringAssert.Contains (error, "cannot be updated", where); + StringAssert.Contains (error, "one strip, tile or thumbnail array more than once", where); + Assert.IsFalse (error.Contains ("more strip, tile or thumbnail values than its data holds"), where + ": " + error); + CollectionAssert.AreEqual (copy, tiff, where); + } + + // Three SHORT values at offset 0. Six bytes do not fit in an entry, the array lies in the block, and both sides name it. + static byte[] ArrayAtZero (bool littleEndian, int offsets, int lengths) => + new TiffBuilder (80, bigEndian: !littleEndian).Header (8) + .Table (8, [(0x9286, 7, 4, 0x61626364), (offsets, 3, 3, 0), (lengths, 3, 3, 0)]) + .ToArray (); + + public static IEnumerable TruncatedPairArrays () + { + foreach (var littleEndian in new[] { true, false }) + foreach (var home in new[] { "IFD0", "IFD1", "Exif", "SubIFD", "Interop", "GPS" }) + foreach (var (offsets, lengths) in new[] { (0x0111, 0x0117), (0x0144, 0x0145), (0x0201, 0x0202) }) + foreach (var offsetsBad in new[] { true, false }) + yield return [littleEndian, home, offsets, lengths, offsetsBad]; + } + + // A SHORT array that starts in the block and runs past its end does not fit. The gate refuses that on its own, + // before the value budget, whichever side and whichever table names it. + [TestMethod] + [DynamicData (nameof (TruncatedPairArrays))] + public void Edit_RefusesWhenAPairArrayDoesNotFit (bool littleEndian, string home, int offsets, int lengths, bool offsetsBad) + { + var tiff = TruncatedPair (littleEndian, home, offsets, lengths, offsetsBad); + var copy = (byte[])tiff.Clone (); + var where = $"{home} {(littleEndian ? "LE" : "BE")} {(offsetsBad ? offsets : lengths):X4}"; + var tag = new ImageTag (MediaFormat.Png, ImageStores.CommentOnly) { Comment = "n" }; + + var saved = ExifEditor.TryRemove (tiff, 0, tag, "eXIf", out var changed, out var error); + + Assert.IsFalse (saved, $"{where}: saved"); + Assert.IsFalse (changed, where); + StringAssert.Contains (error, "cannot be updated", where); + StringAssert.Contains (error, "does not fit in its data", where); + Assert.IsFalse (error.Contains ("more strip, tile or thumbnail values than its data holds"), where + ": " + error); + CollectionAssert.AreEqual (copy, tiff, where); + } + + // Six SHORT values at offset 96 need 12 bytes, and the block ends four bytes later. The other side is one inline value. + static byte[] TruncatedPair (bool littleEndian, string home, int offsets, int lengths, bool offsetsBad) + { + const int Ifd0 = 8; + var comment = (0x9286, 7, 4L, 0x61626364L); + (int, int, long, long) side = offsetsBad ? (offsets, 3, 6, 96) : (lengths, 3, 6, 96); + (int, int, long, long) other = offsetsBad ? (lengths, 3, 1, 1) : (offsets, 3, 1, 1); + var tiff = new TiffBuilder (100, bigEndian: !littleEndian).Header (Ifd0); + switch (home) { + case "IFD0": + tiff.Table (Ifd0, [comment, side, other]); + break; + case "IFD1": + tiff.Table (Ifd0, [comment], 40).Table (40, [side, other]); + break; + case "Exif": + tiff.Table (Ifd0, [comment, (0x8769, 4, 1, 40)]).Table (40, [side, other]); + break; + case "SubIFD": + tiff.Table (Ifd0, [comment, (0x014A, 4, 1, 40)]).Table (40, [side, other]); + break; + case "Interop": + tiff.Table (Ifd0, [comment, (0x8769, 4, 1, 40)]).Table (40, [(0xA005, 4, 1, 60)]).Table (60, [side, other]); + break; + default: + tiff.Table (Ifd0, [comment, (0x8825, 4, 1, 40)]).Table (40, [side, other]); + break; + } + + return tiff.ToArray (); + } + + public static IEnumerable PairTagsGivenTwice () + { + foreach (var littleEndian in new[] { true, false }) + foreach (var home in new[] { "IFD0", "IFD1", "Exif", "SubIFD", "Interop", "GPS" }) + foreach (var tag in new[] { 0x0111, 0x0117, 0x0144, 0x0145, 0x0201, 0x0202 }) + yield return [littleEndian, home, tag]; + } + + // One table names a strip, tile or thumbnail offset or length twice, as two different inline values. + // Which bytes the pair names cannot be told, so the edit is refused before a plan is built. + [TestMethod] + [DynamicData (nameof (PairTagsGivenTwice))] + public void Edit_RefusesWhenAPairTagIsGivenTwice (bool littleEndian, string home, int pairTag) + { + var tiff = GivenTwice (littleEndian, home, pairTag); + var copy = (byte[])tiff.Clone (); + var where = $"{home} {(littleEndian ? "LE" : "BE")} {pairTag:X4}"; + var title = new ImageTag (MediaFormat.Png, ImageStores.Png); + title.ReadField (ImageStores.Title, "Old"); + title.Title = "New"; + IfdSteps.Count = 0; + Assert.IsTrue (ExifEditor.TryRemove ((byte[])tiff.Clone (), 0, title, "eXIf", out _, out var titleError), $"{where}: {titleError}"); + var idle = IfdSteps.Count; + + IfdSteps.Count = 0; + var tag = new ImageTag (MediaFormat.Png, ImageStores.CommentOnly) { Comment = "n" }; + var saved = ExifEditor.TryRemove (tiff, 0, tag, "eXIf", out var changed, out var error); + + Assert.IsFalse (saved, $"{where}: saved"); + Assert.IsFalse (changed, where); + StringAssert.Contains (error, "cannot be updated", where); + StringAssert.Contains (error, "offset or length more than once", where); + CollectionAssert.AreEqual (copy, tiff, where); + Assert.AreEqual (idle, IfdSteps.Count, $"{where}: a refusal built a plan ({IfdSteps.Count} steps, a title edit took {idle})"); + } + + // The UserComment value is also a GPS entry's value. Removing the comment would share those bytes, so the + // structure is not clean and the edit is refused. Both byte orders. + [TestMethod] + [DataRow (true)] + [DataRow (false)] + public void Edit_RefusesWhenARemovedValueSharesBytesWithAnotherTable (bool littleEndian) + { + const int Ifd0 = 8, Exif = 50, Gps = 90, Value = 120; + var comment = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }; + var tiff = new TiffBuilder (140, bigEndian: !littleEndian).Header (Ifd0) + .Bytes (Value, comment) + .Table (Ifd0, [(0x8769, 4, 1, Exif), (0x8825, 4, 1, Gps)]) + .Table (Exif, [(0x9286, 7, comment.Length, Value)]) + .Table (Gps, [(0x001B, 7, comment.Length, Value)]) + .ToArray (); + var copy = (byte[])tiff.Clone (); + var tag = new ImageTag (MediaFormat.Png, ImageStores.CommentOnly) { Comment = "n" }; + + var saved = ExifEditor.TryRemove (tiff, 0, tag, "eXIf", out var changed, out var error); + + Assert.IsFalse (saved, littleEndian ? "LE: saved" : "BE: saved"); + Assert.IsFalse (changed); + StringAssert.Contains (error, "cannot be updated"); + StringAssert.Contains (error, "IFD structure that removing"); + CollectionAssert.AreEqual (copy, tiff); + } + + // A comment that sits only in a GPS table, or only in the next IFD of an Exif table (protected, not read with + // Exif tags), is not a copy the field edit removes. The block is left as it is. + [TestMethod] + [DataRow (true)] + [DataRow (false)] + public void Edit_OfAComment_LeavesACommentThatSitsOnlyOutsideAReadTable (bool littleEndian) + { + var order = littleEndian ? "LE" : "BE"; + // The comment is the table's first entry. Behind it is a type exiftool does not read, so taking the comment + // out would hide the table. These tables are not edited, so the comment stays and the block is unchanged. + var gps = new TiffBuilder (90, bigEndian: !littleEndian).Header (8) + .Table (8, [(0x010E, 2, 4, 0x41424344), (0x8825, 4, 1, 40)]) + .Table (40, [(0x9286, 7, 4, 0x61626364), (0x010F, 0, 1, 0)]) + .ToArray (); + var protect = new TiffBuilder (110, bigEndian: !littleEndian).Header (8) + .Table (8, [(0x8769, 4, 1, 40)]) + .Table (40, [(0x9003, 2, 4, 0x31323334)], next: 70) + .Table (70, [(0x9286, 7, 4, 0x61626364), (0x010F, 0, 1, 0)]) + .ToArray (); + + foreach (var (name, tiff) in new[] { ("GPS", gps), ("protect-only", protect) }) + AssertLeftAsItIs (tiff, $"{order} {name}"); + } + + static void AssertLeftAsItIs (byte[] tiff, string where) + { + var copy = (byte[])tiff.Clone (); + var tag = new ImageTag (MediaFormat.Png, ImageStores.CommentOnly) { Comment = "n" }; + + var saved = ExifEditor.TryRemove (tiff, 0, tag, "eXIf", out var changed, out var error); + + Assert.IsTrue (saved, $"{where}: {error}"); + Assert.IsFalse (changed, where); + CollectionAssert.AreEqual (copy, tiff, where); + } + + // The next field has one byte, and taking the comment out would hide the table. The cut-short reason is the one + // reported. The first-entry reason is a later check and does not replace it. + [TestMethod] + [DataRow (true)] + [DataRow (false)] + public void Edit_ReportsTheCutShortNextWhenTheFirstEntryWouldAlsoChange (bool littleEndian) + { + var tiff = new TiffBuilder (35, bigEndian: !littleEndian).Header (8) + .Entries (8, (0x9286, 7, 4, 0x61626364), (0x010F, 0, 1, 0)) + .ToArray (); + var copy = (byte[])tiff.Clone (); + var where = littleEndian ? "LE" : "BE"; + var tag = new ImageTag (MediaFormat.Png, ImageStores.CommentOnly) { Comment = "n" }; + + var saved = ExifEditor.TryRemove (tiff, 0, tag, "eXIf", out var changed, out var error); + + Assert.IsFalse (saved, $"{where}: saved"); + Assert.IsFalse (changed, where); + StringAssert.Contains (error, "cannot be updated", where); + StringAssert.Contains (error, "cut short", where); + Assert.IsFalse (error.Contains ("first entry"), where + ": " + error); + CollectionAssert.AreEqual (copy, tiff, where); + } + + public static IEnumerable BudgetAndFirstEntry () + { + foreach (var littleEndian in new[] { true, false }) + foreach (var (offsets, lengths) in new[] { (0x0111, 0x0117), (0x0144, 0x0145), (0x0201, 0x0202) }) + yield return [littleEndian, offsets, lengths]; + } + + // The comment is the only entry exiftool reads, and the pair names more values than half the bytes. The + // first-entry reason is reported. The value budget is used only when no earlier reason was found. + [TestMethod] + [DynamicData (nameof (BudgetAndFirstEntry))] + public void Edit_ReportsTheFirstEntryWhenTheValueBudgetAlsoApplies (bool littleEndian, int offsets, int lengths) + { + var tiff = new TiffBuilder (200, bigEndian: !littleEndian).Header (8) + .Table (8, [(0x9286, 7, 4, 0x61626364), (0x010F, 0, 1, 0), (offsets, 3, 100, 0), (lengths, 3, 1, 1)]) + .ToArray (); + var copy = (byte[])tiff.Clone (); + var where = $"{(littleEndian ? "LE" : "BE")} {offsets:X4}"; + var tag = new ImageTag (MediaFormat.Png, ImageStores.CommentOnly) { Comment = "n" }; + + var saved = ExifEditor.TryRemove (tiff, 0, tag, "eXIf", out var changed, out var error); + + Assert.IsFalse (saved, $"{where}: saved"); + Assert.IsFalse (changed, where); + StringAssert.Contains (error, "cannot be updated", where); + StringAssert.Contains (error, "first entry", where); + Assert.IsFalse (error.Contains ("more strip, tile or thumbnail values than its data holds"), where + ": " + error); + CollectionAssert.AreEqual (copy, tiff, where); + } + + static byte[] GivenTwice (bool littleEndian, string home, int pairTag) + { + const int Ifd0 = 8; + var comment = (0x9286, 7, 4L, 0x61626364L); + var first = (pairTag, 4, 1L, 100L); + var second = (pairTag, 4, 1L, 200L); + var tiff = new TiffBuilder (120, bigEndian: !littleEndian).Header (Ifd0); + switch (home) { + case "IFD0": + tiff.Table (Ifd0, [comment, first, second]); + break; + case "IFD1": + tiff.Table (Ifd0, [comment], 40).Table (40, [first, second]); + break; + case "Exif": + tiff.Table (Ifd0, [comment, (0x8769, 4, 1, 40)]).Table (40, [first, second]); + break; + case "SubIFD": + tiff.Table (Ifd0, [comment, (0x014A, 4, 1, 40)]).Table (40, [first, second]); + break; + case "Interop": + tiff.Table (Ifd0, [comment, (0x8769, 4, 1, 40)]).Table (40, [(0xA005, 4, 1, 70)]).Table (70, [first, second]); + break; + default: + tiff.Table (Ifd0, [comment, (0x8825, 4, 1, 40)]).Table (40, [first, second]); + break; + } + + return tiff.ToArray (); + } +} diff --git a/tests/TagLibSharp2.Tests/Image/ExifReaderGoldenTests.cs b/tests/TagLibSharp2.Tests/Image/ExifReaderGoldenTests.cs new file mode 100644 index 00000000..249a8d49 --- /dev/null +++ b/tests/TagLibSharp2.Tests/Image/ExifReaderGoldenTests.cs @@ -0,0 +1,374 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Globalization; +using System.Security.Cryptography; +using System.Text; + +namespace TagLibSharp2.Tests.Image; + +/// +/// The tests' Exif reader against exiftool's own output. Golden/exif-reader-probes.txt records what exiftool +/// shows for a probe of each reading rule (pointer tags × location × type × count, values of several sizes, the +/// next IFD of every kind of table, unknown formats, value offsets in the header, the data's end and the value's own +/// table, the order tables are read in); Golden/exif-edit-matrix.txt records it for every input of the Exif +/// edit matrix. must give the same field-tag counts for every input, so a rule +/// of the model that is not exiftool's turns these red. Regenerate both with tools/exif/golden.sh. +/// +[TestClass] +[TestCategory ("Unit")] +public class ExifReaderGoldenTests +{ + const string DumpVariable = "TAGLIBSHARP2_EXIF_GOLDEN_DUMP"; + + [TestMethod] + public void ReaderModel_ShowsWhatExiftoolShows_ForEveryProbe () => + AssertMatchesGolden ("probes", "exif-reader-probes.txt", Probes ()); + + [TestMethod] + public void ReaderModel_ShowsWhatExiftoolShows_ForEveryMatrixInput () => + AssertMatchesGolden ("matrix", "exif-edit-matrix.txt", ExifEditMatrixTests.Inputs ()); + + static void AssertMatchesGolden (string set, string golden, IEnumerable<(string Name, byte[] Tiff)> inputs) + { + var list = inputs.ToList (); + if (Environment.GetEnvironmentVariable (DumpVariable) is { Length: > 0 } dump) { + Dump (Path.Combine (dump, set), list); + return; + } + + var (count, sha, summaries, sequence) = Read (golden); + Assert.AreEqual (count, list.Count, $"{golden}: the inputs changed; regenerate with tools/exif/golden.sh"); + Assert.AreEqual (sha, Sha256 (list), $"{golden}: the inputs changed; regenerate with tools/exif/golden.sh"); + var mismatches = new List (); + for (var n = 0; n < list.Count; n++) { + var model = ExifReaderModel.Exiftool (list[n].Tiff).Summary (); + var exiftool = summaries[sequence[n]]; + if (model != exiftool) + mismatches.Add ($"#{n} {list[n].Name}: exiftool {exiftool}, model {model}"); + } + + Assert.AreEqual (0, mismatches.Count, $"{mismatches.Count} of {list.Count} inputs:\n" + string.Join ("\n", mismatches.Take (25))); + } + + static void Dump (string directory, List<(string Name, byte[] Tiff)> inputs) + { + Directory.CreateDirectory (directory); + for (var n = 0; n < inputs.Count; n++) + File.WriteAllBytes (Path.Combine (directory, $"{n:D5}.tif"), inputs[n].Tiff); + } + + static string Sha256 (List<(string Name, byte[] Tiff)> inputs) + { + using var sha = IncrementalHash.CreateHash (HashAlgorithmName.SHA256); + foreach (var (_, tiff) in inputs) + sha.AppendData (tiff); + return Convert.ToHexString (sha.GetHashAndReset ()).ToLowerInvariant (); + } + + static (int Count, string Sha, List Summaries, List Sequence) Read (string golden) + { + using var stream = typeof (ExifReaderGoldenTests).Assembly.GetManifestResourceStream ("Golden." + golden)!; + using var reader = new StreamReader (stream); + var lines = reader.ReadToEnd ().Split ('\n', StringSplitOptions.RemoveEmptyEntries); + var header = lines[1].Split (' '); + var summaries = new List (); + var sequence = new List (); + var section = ""; + foreach (var line in lines.Skip (2)) { + if (line.StartsWith ('@')) { + section = line; + continue; + } + + if (section == "@summaries") + summaries.Add (line[(line.IndexOf (' ') + 1)..]); + else + sequence.AddRange (line.Split (' ').Select (n => int.Parse (n, CultureInfo.InvariantCulture))); + } + + return (int.Parse (header[2], CultureInfo.InvariantCulture), header[4], summaries, sequence); + } + + static readonly byte[] Uc = "ASCII\0\0\0probe-uc!"u8.ToArray (); + + /// A probe of each reading rule, as the golden file lists them. + internal static IEnumerable<(string Name, byte[] Tiff)> Probes () => + PointerTypes ().Concat (PointerValues ()).Concat (NextIfds ()).Concat (ValuePlaces ()).Concat (UnknownFormats ()) + .Concat (FirstEntryByKind ()).Concat (ReadOrder ()).Concat (TooManyWarnings ()); + + // exiftool stops reading a table at its 11th warning: 10 or 11 entries of each kind before an Exif IFD's + // UserComment (the counted kinds and three that are not), the count kept per table, IFD0 stopped before its Exif + // IFD pointer and before its next IFD, and an 11th warning on a table's last entry, which stops nothing. + static IEnumerable<(string, byte[])> TooManyWarnings () + { + var kinds = new (string Name, Func Entry)[] { + ("unknown formats", j => (0xC000 + j, 16, 1, 0)), + ("values past the data", j => (0xC000 + j, 2, 20, 60000)), + ("values in the header", j => (0xC000 + j, 2, 20, 4)), + ("values inside their own table", j => (0xC000 + j, 2, 20, 44)), + ("entries of type 0", j => (0xC000 + j, 0, 1, 0)), + ("tags out of sequence", j => (0x0100 - j, 3, 1, 1)), + }; + (int, int, long, long) good = (0x9000, 7, 4, 0x30333230), uc = (0x9286, 7, Uc.Length, 300); + foreach (var (name, entry) in kinds) { + foreach (var k in new[] { 10, 11 }) { + (int, int, long, long)[] exif = [good, .. Enumerable.Range (0, k).Select (entry), uc]; + yield return ($"{k} {name} before the UserComment", new TiffBuilder (400).Header (8).Table (8, [(0x8769, 4, 1, 40)]).Table (40, exif).Bytes (300, Uc).ToArray ()); + } + } + + var bad = Enumerable.Range (0, 6).Select (kinds[0].Entry).ToArray (); + yield return ("6 warnings in IFD0 and 6 in the Exif IFD", new TiffBuilder (400).Header (8).Table (8, [(0x0100, 4, 1, 1), .. bad, (0x8769, 4, 1, 120)]) + .Table (120, [good, .. bad, uc]).Bytes (300, Uc).ToArray ()); + var eleven = Enumerable.Range (0, 11).Select (kinds[0].Entry).ToArray (); + yield return ("IFD0 stopped before its Exif IFD pointer", new TiffBuilder (400).Header (8).Table (8, [(0x0100, 4, 1, 1), .. eleven, (0x8769, 4, 1, 200)]) + .Table (200, [good, uc]).Bytes (300, Uc).ToArray ()); + yield return ("IFD0's 11th warning on its last entry, then its next IFD", new TiffBuilder (400).Header (8).Table (8, [(0x0100, 4, 1, 1), .. eleven], next: 200) + .Table (200, [uc]).Bytes (300, Uc).ToArray ()); + yield return ("IFD0 stopped, then its next IFD", new TiffBuilder (400).Header (8).Table (8, [(0x0100, 4, 1, 1), .. eleven, (0x0101, 4, 1, 1)], next: 200) + .Table (200, [uc]).Bytes (300, Uc).ToArray ()); + } + + // Each pointer tag in each kind of table, with each type and a count of 0, 1 and 2; the target holds a UserComment + // and an ImageDescription (a GPS target: GPSLatitudeRef). Little-endian, and big-endian for the integer types. + static IEnumerable<(string, byte[])> PointerTypes () + { + int[] types = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 16]; + foreach (var bigEndian in new[] { false, true }) { + foreach (var pointer in new[] { 0x8769, 0xA005, 0x8825, 0x014A }) { + foreach (var where in new[] { "IFD0", "ExifIFD", "InteropIFD", "SubIFD", "GPS", "IFD1" }) { + foreach (var type in bigEndian ? [1, 3, 4, 6, 8, 13] : types) { + foreach (var count in new[] { 0, 1, 2 }) + yield return ($"pointer {pointer:X4} in {where} type {type} count {count} {(bigEndian ? "BE" : "LE")}", PointerProbe (pointer, where, type, count, bigEndian, 200)); + } + } + + yield return ($"pointer {pointer:X4} SBYTE 100 {(bigEndian ? "BE" : "LE")}", PointerProbe (pointer, "IFD0", 6, 1, bigEndian, 100)); + } + } + } + + static byte[] PointerProbe (int pointer, string where, int type, int count, bool bigEndian, int target) + { + var t = new TiffBuilder (400, bigEndian).Header (8); + var carrier = where switch { "IFD0" => 8, "InteropIFD" => 80, _ => 40 }; + switch (where) { + case "ExifIFD": + t.Table (8, [(0x8769, 4, 1, 40)]); + break; + case "InteropIFD": + t.Table (8, [(0x8769, 4, 1, 40)]).Table (40, [(0xA005, 4, 1, 80)]); + break; + case "SubIFD": + t.Table (8, [(0x014A, 4, 1, 40)]); + break; + case "GPS": + t.Table (8, [(0x8825, 4, 1, 40)]); + break; + case "IFD1": + t.Table (8, [(0x0100, 4, 1, 1)], next: 40); + break; + } + + t.Table (carrier, [(pointer, type, count, 0)]).Bytes (carrier + 2 + 8, Field (type, count, target, bigEndian)); + if (pointer == 0x8825) + t.Table (target, [(0x0001, 2, 2, 0)]).Bytes (target + 2 + 8, "N\0"u8); + else + t.Table (target, [(0x9286, 7, Uc.Length, 300), (0x010E, 2, 8, 330)]).Bytes (300, Uc).Bytes (330, "desc-ok\0"u8); + return t.ToArray (); + } + + // The value as the type stores it, left-justified in the 4-byte field (a count of 2 repeats a 1- or 2-byte value). + static byte[] Field (int type, int count, int value, bool bigEndian) + { + var size = type switch { 1 or 2 or 6 or 7 => 1, 3 or 8 => 2, _ => 4 }; + var field = new byte[4]; + if (size == 1) { + field[0] = (byte)value; + } else if (size == 2) { + (field[0], field[1]) = bigEndian ? ((byte)(value >> 8), (byte)value) : ((byte)value, (byte)(value >> 8)); + } else { + for (var k = 0; k < 4; k++) + field[bigEndian ? k : 3 - k] = (byte)(value >> (8 * (3 - k))); + } + + if (count == 2 && size <= 2) + field.AsSpan (0, size).CopyTo (field.AsSpan (size)); + return field; + } + + // Pointers with 1-3 distinct values (BYTE, SHORT, SSHORT, SBYTE inline and out of line) and a LONG array of two, + // each value a table with its own UserComment: which of them a reader follows. Then offsets 0, in the header, at + // the data's end, and negative. + static IEnumerable<(string, byte[])> PointerValues () + { + foreach (var bigEndian in new[] { false, true }) { + foreach (var pointer in new[] { 0x8769, 0xA005, 0x8825, 0x014A }) { + foreach (var (type, size) in new[] { (1, 1), (3, 2), (8, 2), (6, 1) }) { + foreach (var count in new[] { 1, 2, 3 }) + yield return ($"pointer {pointer:X4} type {type} values {count} {(bigEndian ? "BE" : "LE")}", ValuesProbe (pointer, type, size, count, bigEndian)); + } + + yield return ($"pointer {pointer:X4} LONG array of 2 {(bigEndian ? "BE" : "LE")}", ValuesProbe (pointer, 4, 4, 2, bigEndian)); + } + } + + foreach (var (type, value, name) in new[] { (6, 0xC8L, "SBYTE negative"), (8, 0xFF38L, "SSHORT negative"), (9, 0xFFFFFFC8L, "SLONG negative"), (4, 0L, "LONG 0"), (3, 0L, "SHORT 0"), (4, 3L, "LONG into the header"), (4, 399L, "LONG at the data's end") }) { + var t = new TiffBuilder (400).Header (8).Table (8, [(0x8769, type, 1, 0)]); + var field = new byte[4]; + for (var k = 0; k < 4; k++) + field[k] = (byte)(value >> (8 * k)); + yield return ($"pointer value {name}", t.Bytes (8 + 2 + 8, field).ToArray ()); + } + } + + static byte[] ValuesProbe (int pointer, int type, int size, int count, bool bigEndian) + { + var t = new TiffBuilder (600, bigEndian).Header (8); + long[] targets = size == 1 ? [100, 140, 180] : [100, 200, 300]; + var bytes = new byte[count * size]; + for (var k = 0; k < count; k++) { + for (var b = 0; b < size; b++) + bytes[(k * size) + b] = (byte)(targets[k] >> (8 * (bigEndian ? size - 1 - b : b))); + } + + t.Table (8, [(pointer, type, count, 0)]); + if (bytes.Length <= 4) + t.Bytes (8 + 2 + 8, bytes); + else + t.U32 (8 + 2 + 8, 400).Bytes (400, bytes); + string[] names = ["aaaaa", "bbbbb", "ccccc"]; + for (var k = 0; k < count; k++) { + var at = (int)targets[k]; + if (pointer == 0x8825) + t.Table (at, [(0x0001, 2, 2, 0)]).Bytes (at + 2 + 8, [(byte)"NSE"[k], 0]); + else + t.Table (at, [(0x9286, 7, Uc.Length, 450 + (40 * k))]).Bytes (450 + (40 * k), Encoding.ASCII.GetBytes ("ASCII\0\0\0" + names[k] + "-uc!")); + } + + return t.ToArray (); + } + + // The next IFD of each kind of table: only the main chain's is read. + static IEnumerable<(string, byte[])> NextIfds () + { + foreach (var kind in new[] { "ExifIFD", "InteropIFD", "SubIFD", "GPS", "IFD1" }) { + var t = new TiffBuilder (600).Header (8); + _ = kind switch { + "ExifIFD" => t.Table (8, [(0x8769, 4, 1, 40)]).Table (40, [(0x9003, 2, 4, 0x30303032)], next: 200), + "InteropIFD" => t.Table (8, [(0x8769, 4, 1, 40)]).Table (40, [(0xA005, 4, 1, 80)]).Table (80, [(0x0001, 2, 4, 0x00383952)], next: 200), + "SubIFD" => t.Table (8, [(0x014A, 4, 1, 40)]).Table (40, [(0x00FE, 4, 1, 0)], next: 200), + "GPS" => t.Table (8, [(0x8825, 4, 1, 40)]).Table (40, [(0x0001, 2, 2, 0x4E)], next: 200), + _ => t.Table (8, [(0x0100, 4, 1, 1)], next: 40).Table (40, [(0x0100, 4, 1, 1)], next: 200), + }; + yield return ($"next IFD of {kind}", t.Table (200, [(0x9286, 7, Uc.Length, 300)]).Bytes (300, Uc).ToArray ()); + } + } + + // A UserComment value placed in the header, in its own table's count, entries and next offset, before and after + // the table, inside a parent or child table, and past the data's end. + static IEnumerable<(string, byte[])> ValuePlaces () + { + foreach (var at in new[] { 26, 27, 30, 39, 41, 54, 65, 66, 70, 300, 395 }) { + var t = new TiffBuilder (400).Header (8).Table (8, [(0x8769, 4, 1, 40)]) + .Table (40, [(0x9003, 2, 20, 350), (0x9286, 7, Uc.Length, at)]).Bytes (350, "2009:09:09 09:09:09\0"u8); + if (at is <= 26 or >= 70 and < 386) + t.Bytes (at, Uc); + yield return ($"value at {at} by an Exif IFD at 40 to 70", t.ToArray ()); + } + + foreach (var (at, size) in new[] { (0, 8), (2, 8), (4, 8), (7, 8), (8, 8), (2, 17), (80, 17), (83, 17), (84, 17) }) { + var t = new TiffBuilder (400).Header (100).Table (100, [(0x9286, 7, size, at)]); + yield return ($"value of {size} at {at} by IFD0 at 100", t.ToArray ()); + } + + yield return ("value inside the parent table", new TiffBuilder (400).Header (100).Table (100, [(0x8769, 4, 1, 200), (0x9003, 2, 20, 300)]) + .Table (200, [(0x9286, 7, 14, 104)]).ToArray ()); + yield return ("value inside a child table", new TiffBuilder (400).Header (100).Table (100, [(0x8769, 4, 1, 200), (0x9286, 7, 14, 204)]) + .Table (200, [(0x9003, 2, 20, 300)]).ToArray ()); + } + + // A format outside 1-13 drops the whole table when it is the first entry, in every kind of table, and is skipped + // when it is later. An empty IFD0 is read and its next IFD is followed; one dropped for a type-0 first entry is + // not. Little-endian; the editor tests pin both byte orders. ImageDescription and GPSLatitudeRef are what the + // golden summary counts. + static IEnumerable<(string, byte[])> FirstEntryByKind () + { + (int, int, long, long) desc = (0x010E, 2, 4, 0x6C6C6948); + (int, int, long, long) gps = (0x0001, 2, 2, 0x4E); + foreach (var kind in new[] { "IFD0", "IFD1", "Exif", "SubIFD", "Interop" }) { + yield return ($"{kind} type 0 first", KindTable (kind, [(0x0010, 0, 1, 0), desc])); + yield return ($"{kind} type 14 first", KindTable (kind, [(0x0010, 14, 1, 0), desc])); + yield return ($"{kind} type 14 later", KindTable (kind, [desc, (0x0010, 14, 1, 0)])); + } + + yield return ("GPS type 0 first", GpsTable ([(0x0010, 0, 1, 0), gps])); + yield return ("GPS type 14 first", GpsTable ([(0x0010, 14, 1, 0), gps])); + yield return ("GPS type 14 later", GpsTable ([gps, (0x0010, 14, 1, 0)])); + yield return ("the chain after an empty IFD0", new TiffBuilder (80).Header (8).Table (8, [], next: 40).Table (40, [desc]).ToArray ()); + yield return ("the chain after an IFD0 whose first entry is type 0", new TiffBuilder (80).Header (8) + .Table (8, [(0x0010, 0, 1, 0)], next: 40).Table (40, [desc]).ToArray ()); + + static byte[] KindTable (string kind, (int, int, long, long)[] entries) + { + var t = new TiffBuilder (120).Header (8); + switch (kind) { + case "IFD0": t.Table (8, entries); break; + case "IFD1": t.Table (8, [(0x0100, 4, 1, 1)], next: 40).Table (40, entries); break; + case "SubIFD": t.Table (8, [(0x014A, 4, 1, 40)]).Table (40, entries); break; + case "Exif": t.Table (8, [(0x8769, 4, 1, 40)]).Table (40, entries); break; + default: t.Table (8, [(0x8769, 4, 1, 40)]).Table (40, [(0xA005, 4, 1, 80)]).Table (80, entries); break; + } + + return t.ToArray (); + } + + static byte[] GpsTable ((int, int, long, long)[] entries) => + new TiffBuilder (120).Header (8).Table (8, [(0x8825, 4, 1, 40)]).Table (40, entries).ToArray (); + } + + // An entry of each type first, in the middle and last of a table with a UserComment, and a UserComment of each + // type: an unknown format in the first entry drops the table, anywhere else only that entry. + static IEnumerable<(string, byte[])> UnknownFormats () + { + foreach (var type in new[] { 0, 1, 7, 12, 13, 14, 15, 16, 17, 18, 19, 255 }) { + (int, int, long, long) odd = (0x9004, type, 1, 0x31323334), date = (0x9003, 2, 4, 0x30303032), uc = (0x9286, 7, Uc.Length, 300); + foreach (var (where, entries) in new (string, (int, int, long, long)[])[] { ("first", [odd, date, uc]), ("in the middle", [date, odd, uc]), ("last", [date, uc, odd]) }) { + var t = new TiffBuilder (400).Header (8).Table (8, [(0x8769, 4, 1, 40)]).Table (40, entries).Bytes (300, Uc); + yield return ($"type {type} {where}", t.ToArray ()); + } + + var typed = new TiffBuilder (400).Header (8).Table (8, [(0x8769, 4, 1, 40)]).Table (40, [date, (0x9286, type, Uc.Length, 300)]).Bytes (300, Uc); + yield return ($"a UserComment of type {type}", typed.ToArray ()); + } + } + + // One table reached twice, as two kinds, in several orders: the first reach decides, depth-first, the main + // chain's next IFD after the subdirectories. + static IEnumerable<(string, byte[])> ReadOrder () + { + static TiffBuilder Shared (TiffBuilder t) => t.Table (200, [(0x9286, 7, Uc.Length, 300), (0x0001, 2, 2, 0x4E)]).Bytes (300, Uc); + yield return ("GPS first, then Exif", Shared (new TiffBuilder (500).Header (8).Table (8, [(0x8825, 4, 1, 200), (0x8769, 4, 1, 200)])).ToArray ()); + yield return ("Exif first, then GPS", Shared (new TiffBuilder (500).Header (8).Table (8, [(0x8769, 4, 1, 200), (0x8825, 4, 1, 200)])).ToArray ()); + yield return ("Exif in depth before IFD0's GPS", Shared (new TiffBuilder (500).Header (8).Table (8, [(0x8769, 4, 1, 60), (0x8825, 4, 1, 200)]).Table (60, [(0x8769, 4, 1, 200)])).ToArray ()); + yield return ("IFD0's GPS before IFD1's Exif", Shared (new TiffBuilder (500).Header (8).Table (8, [(0x8825, 4, 1, 200)], next: 100).Table (100, [(0x8769, 4, 1, 200)])).ToArray ()); + yield return ("IFD1 is the Exif IFD", new TiffBuilder (500).Header (8).Table (8, [(0x8769, 4, 1, 100)], next: 100).Table (100, [(0x9286, 7, Uc.Length, 300)]).Bytes (300, Uc).ToArray ()); + yield return ("the Exif IFD is IFD0", new TiffBuilder (500).Header (8).Table (8, [(0x8769, 4, 1, 8), (0x9286, 7, Uc.Length, 300)]).Bytes (300, Uc).ToArray ()); + var kinds = new (string Name, int Tag)[] { ("Exif", 0x8769), ("Interop", 0xA005), ("GPS", 0x8825), ("SubIFD", 0x014A) }; + foreach (var first in kinds) { + foreach (var then in kinds.Where (k => k != first)) + yield return ($"{first.Name}, then {then.Name}", Shared (new TiffBuilder (500).Header (8).Table (8, [(first.Tag, 4, 1, 200), (then.Tag, 4, 1, 200)])).ToArray ()); + } + + yield return ("the chain after a table dropped for its first entry", new TiffBuilder (500).Header (8).Table (8, [(0x0100, 4, 1, 1)], next: 40) + .Table (40, [(0x0100, 0x7777, 1, 1)], next: 100).Table (100, [(0x9286, 7, Uc.Length, 300)]).Bytes (300, Uc).ToArray ()); + yield return ("a SubIFD array inside its own table", new TiffBuilder (500).Header (8).Table (8, [(0x014A, 4, 2, 10), (0x9003, 2, 4, 0x30303032)]) + .U32 (22, 200).Table (200, [(0x9286, 7, Uc.Length, 300)]).Bytes (300, Uc).ToArray ()); + yield return ("a SubIFD array after its own table", new TiffBuilder (500).Header (8).Table (8, [(0x014A, 4, 2, 150)]) + .U32 (150, 200).Table (200, [(0x9286, 7, Uc.Length, 300)]).Bytes (300, Uc).ToArray ()); + yield return ("an Interop IFD's Interop and Exif IFDs", new TiffBuilder (500).Header (8).Table (8, [(0x8769, 4, 1, 40)]).Table (40, [(0xA005, 4, 1, 80)]) + .Table (80, [(0xA005, 4, 1, 120), (0x9286, 7, Uc.Length, 300)]).Table (120, [(0x8769, 4, 1, 160)]).Table (160, [(0x9286, 7, Uc.Length, 330)]) + .Bytes (300, Uc).Bytes (330, Uc).ToArray ()); + } +} diff --git a/tests/TagLibSharp2.Tests/Image/ExifReaderModel.cs b/tests/TagLibSharp2.Tests/Image/ExifReaderModel.cs new file mode 100644 index 00000000..592d8a9c --- /dev/null +++ b/tests/TagLibSharp2.Tests/Image/ExifReaderModel.cs @@ -0,0 +1,422 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Globalization; +using System.Text; + +namespace TagLibSharp2.Tests.Image; + +/// +/// The tests' own Exif reader, written from measured reader behaviour and sharing nothing with the code under test. +/// The rules are the ones recorded from exiftool 13.55 in Golden/exif-reader-probes.txt (each row a probe +/// and what exiftool showed), and checks this reader against exiftool's own output +/// for every probe and every matrix input, so a rule that drifts from exiftool turns the tests red. +/// +/// +/// Measured rules: a classic TIFF header; a table is read when it starts at byte 8 or later and its count and +/// entries lie in the data (the next offset may be missing). IFD0 and the chain of next IFDs, Exif IFDs (0x8769), +/// SubIFDs (0x014A) and interoperability IFDs (0xA005) are read with the Exif tags and their pointers are followed; +/// GPS IFDs (0x8825) are read with the GPS tags and nothing is followed from them; the next IFD of anything but the +/// main chain is not read. Pointer values: BYTE, SHORT, LONG, SBYTE, SSHORT, SLONG, IFD, and UNDEFINED with count 1; +/// 0x8769 only with count 1; 0x8825 and 0xA005 by their first value; 0x014A by every value; out-of-line values must +/// all lie in the data; a negative value names nothing. +/// Two views. is exactly what exiftool shows: depth-first in entry order, the main +/// chain's next IFD after a table's subdirectories (not after a table it dropped), each offset read once in the kind +/// it is first reached as (but an interoperability IFD is read as GPS too), a pointer array it hides as a value not +/// followed, a table +/// read without its entries of an unknown format (0, or 14 and above) and not at all when its first entry has one, +/// read only up to its 11th warning (an unknown format other than 0, or a value past the data or suspicious) when +/// entries follow it, an aborted main table ending the chain, and a value hidden when it starts in the +/// 8-byte header, runs past the data, or overlaps its own table's count and entries. is what +/// some reader may read: every table reached in any kind, every entry, every value in the data, and the tables +/// TagLib# reads through IFD0's Exif and GPS pointers, whose 4-byte field it reads as a LONG whatever their type and +/// count (measured: a SHORT, ASCII, RATIONAL, count-0 or count-2 0x8769 or 0x8825 in IFD0). It is the view a save +/// must keep. +/// +sealed class ExifReaderModel +{ + public enum Kind { Main, Exif, SubIfd, Interop, Gps } + + /// The field tags the tests count: UserComment, the XP tags, ImageDescription, Artist, Copyright. + public static readonly int[] FieldTags = [0x9286, 0x9C9B, 0x9C9C, 0x9C9D, 0x010E, 0x013B, 0x8298]; + + public sealed class Table (long at, int count) + { + public long At { get; } = at; + public int Count { get; } = count; + public HashSet Kinds { get; } = []; + + /// + /// The entries a reader reads: all of them, or for exiftool none when the first has an unknown format, and those + /// up to its 11th warning. + /// + public int Read { get; set; } = count; + + /// exiftool stopped reading the table at too many warnings; for IFD0's chain, the chain ends there. + public bool Aborted { get; set; } + + public bool ReadsExifTags => Kinds.Any (k => k != Kind.Gps); + } + + readonly byte[] _t; + readonly bool _le; + readonly bool _exiftool; + + ExifReaderModel (byte[] tiff, bool exiftool) + { + _t = tiff; + _le = tiff.Length >= 2 && tiff[0] == (byte)'I'; + _exiftool = exiftool; + } + + public List Tables { get; } = []; + + /// Pointer targets inside the data where no table can be read. + public List Unread { get; } = []; + + /// Every pointer value read (for the bound of one per 4 bytes). + public long PointerValues { get; private set; } + + public long Entries => Tables.Sum (t => (long)t.Count); + + /// The view a save must keep: everything some reader may read. + public static ExifReaderModel Of (byte[] tiff) => AnyReader (tiff); + + public static ExifReaderModel AnyReader (byte[] tiff) => new ExifReaderModel (tiff, exiftool: false).WalkAll (); + + public static ExifReaderModel Exiftool (byte[] tiff) => new ExifReaderModel (tiff, exiftool: true).WalkDepthFirst (); + + public int U16 (long at) => _le ? _t[at] | (_t[at + 1] << 8) : (_t[at] << 8) | _t[at + 1]; + + public long U32 (long at) => _le + ? _t[at] | ((long)_t[at + 1] << 8) | ((long)_t[at + 2] << 16) | ((long)_t[at + 3] << 24) + : ((long)_t[at] << 24) | ((long)_t[at + 1] << 16) | ((long)_t[at + 2] << 8) | _t[at + 3]; + + bool Classic => _t.Length >= 8 && (_le ? _t[0] == 'I' && _t[1] == 'I' && _t[2] == 42 && _t[3] == 0 : _t[0] == 'M' && _t[1] == 'M' && _t[2] == 0 && _t[3] == 42); + + bool Readable (long at) => at >= 8 && at + 2 <= _t.Length && at + 2 + (12L * U16 (at)) <= _t.Length; + + static Kind? KindOf (int tag) => tag switch { + 0x8769 => Kind.Exif, + 0x014A => Kind.SubIfd, + 0xA005 => Kind.Interop, + 0x8825 => Kind.Gps, + _ => null + }; + + // Bytes per value of a type, for pointers: the integer and IFD types (UNDEFINED is checked by the caller). + static int PointerSize (int type) => type switch { 1 or 6 or 7 => 1, 3 or 8 => 2, 4 or 9 or 13 => 4, _ => 0 }; + + // The tables a pointer entry names, as exiftool follows them. exiftool also ignores an out-of-line array that it + // hides as a value (in the header, or overlapping its own table). + List Targets (Table table, long entry) + { + var targets = new List (); + var tag = U16 (entry); + var type = U16 (entry + 2); + var count = U32 (entry + 4); + var size = PointerSize (type); + if (size == 0 || count == 0 || (type == 7 && count != 1) || (tag == 0x8769 && count != 1)) + return targets; + var at = count * size <= 4 ? entry + 8 : U32 (entry + 8); + if (at + (count * size) > _t.Length || (count * size > 4 && _exiftool && Hidden (table, at, count * size))) + return targets; + var read = tag is 0x8825 or 0xA005 ? 1 : count; + for (var k = 0L; k < read; k++) { + var p = at + (k * size); + long value = size == 1 ? _t[p] : size == 2 ? U16 (p) : U32 (p); + var signed = type is 6 or 8 or 9; + if (!signed || value < (1L << ((8 * size) - 1))) + targets.Add (value); + } + + PointerValues += read; + return targets; + } + + // Every table any reader reaches, breadth-first, with every kind it is reached as. + ExifReaderModel WalkAll () + { + if (!Classic) + return this; + var index = new Dictionary (); + var queue = new Queue<(long At, Kind Kind)> (); + queue.Enqueue ((U32 (4), Kind.Main)); + while (queue.Count > 0) { + var (at, kind) = queue.Dequeue (); + if (!Readable (at)) { + if (at >= 8 && at < _t.Length && !Unread.Contains (at)) + Unread.Add (at); + continue; + } + + if (!index.TryGetValue (at, out var table)) { + table = new Table (at, U16 (at)); + index[at] = table; + Tables.Add (table); + } + + var readBefore = table.ReadsExifTags; + if (!table.Kinds.Add (kind) || kind == Kind.Gps || readBefore) + continue; + for (var n = 0; n < table.Count; n++) { + var e = at + 2 + (12 * n); + if (KindOf (U16 (e)) is Kind child) + foreach (var target in Targets (table, e)) + queue.Enqueue ((target, child)); + if (at == U32 (4) && U16 (e) is 0x8769 or 0x8825) + queue.Enqueue ((U32 (e + 8), U16 (e) == 0x8769 ? Kind.Exif : Kind.Gps)); + } + + if (kind == Kind.Main && at + 2 + (12 * table.Count) + 4 <= _t.Length) + queue.Enqueue ((U32 (at + 2 + (12 * table.Count)), Kind.Main)); + } + + return this; + } + + // exiftool's walk: depth-first in entry order, each offset once, a table stopped at an unknown format. + ExifReaderModel WalkDepthFirst () + { + if (!Classic) + return this; + var seen = new HashSet (); + var frames = new Stack (); + Enter (U32 (4), Kind.Main, seen, frames); + while (frames.Count > 0) { + var frame = frames.Peek (); + if (frame.Pending.Count > 0) { + Enter (frame.Pending.Dequeue (), frame.PendingKind, seen, frames); + continue; + } + + if (frame.Index < frame.Table.Read) { + Step (frame); + continue; + } + + frames.Pop (); + var t = frame.Table; + if (frame.Kind == Kind.Main && !t.Aborted && (t.Read > 0 || t.Count == 0) && t.At + 2 + (12 * t.Count) + 4 <= _t.Length) + Enter (U32 (t.At + 2 + (12 * t.Count)), Kind.Main, seen, frames); + } + + return this; + } + + sealed class Frame (Table table, Kind kind) + { + public Table Table { get; } = table; + public Kind Kind { get; } = kind; + public int Index { get; set; } + public int Warnings { get; set; } + public Queue Pending { get; } = new (); + public Kind PendingKind { get; set; } + } + + void Enter (long at, Kind kind, HashSet seen, Stack frames) + { + if (!seen.Add (at)) { + // The one exception to reading an offset once: a table read as an interoperability IFD is read as GPS too. + if (kind == Kind.Gps && Tables.Find (t => t.At == at) is Table read && read.Kinds.SetEquals ([Kind.Interop])) + read.Kinds.Add (Kind.Gps); + return; + } + + if (!Readable (at)) { + if (at >= 8 && at < _t.Length) + Unread.Add (at); + return; + } + + var table = new Table (at, U16 (at)); + table.Kinds.Add (kind); + Tables.Add (table); + frames.Push (new Frame (table, kind)); + } + + void Step (Frame frame) + { + var t = frame.Table; + var e = t.At + 2 + (12 * frame.Index); + var type = U16 (e + 2); + if (type is 0 or > 13 && frame.Index == 0) { + t.Read = 0; + return; + } + + // exiftool stops reading a table at the entry after its 11th warning ("Too many warnings -- parsing aborted"), + // counted per table: an 11th warning on the last entry stops nothing. + if (frame.Warnings > 10) { + t.Read = frame.Index; + t.Aborted = true; + return; + } + + if (Warns (t, e, type)) + frame.Warnings++; + frame.Index++; + if (type is not (0 or > 13) && frame.Kind != Kind.Gps && KindOf (U16 (e)) is Kind child) { + foreach (var target in Targets (t, e)) + frame.Pending.Enqueue (target); + frame.PendingKind = child; + } + } + + // The entries exiftool counts toward that limit: an unknown format other than 0, and an out-of-line value that runs + // past the data or that it calls suspicious. Pointer warnings and tags out of sequence do not count (measured). + bool Warns (Table table, long e, int type) + { + if (type is 0 or > 13) + return type != 0; + var size = TypeSize (type) * U32 (e + 4); + var at = U32 (e + 8); + return size > 4 && (at + size > _t.Length || Hidden (table, at, size)); + } + + static long TypeSize (int type) => type switch { + 1 or 2 or 6 or 7 => 1, + 3 or 8 => 2, + 4 or 9 or 11 or 13 => 4, + 5 or 10 or 12 => 8, + _ => 0 + }; + + // An entry's value bytes as the view reads them: inline, out of line, or null when exiftool hides it. + byte[]? ValueOf (Table table, long e) + { + var size = TypeSize (U16 (e + 2)) * U32 (e + 4); + if (size <= 4) + return _t[(int)(e + 8)..(int)(e + 12)]; + var at = U32 (e + 8); + if (at + size > _t.Length || (_exiftool && Hidden (table, at, size))) + return null; + return _t[(int)at..(int)(at + size)]; + } + + // exiftool's "suspicious offset": a value that starts in the header or overlaps its own table's count and entries. + static bool Hidden (Table table, long at, long size) => at < 8 || (at < table.At + 2 + (12L * table.Count) && table.At < at + size); + + // The entries a reader shows: exiftool skips an entry of an unknown format, and the whole table when its first + // entry has one. + IEnumerable<(Table Table, long Entry)> Shown () + { + foreach (var t in Tables) { + for (var n = 0; n < t.Read; n++) { + var e = t.At + 2 + (12 * n); + if (!_exiftool || U16 (e + 2) is not (0 or > 13)) + yield return (t, e); + } + } + } + + /// One table offset per copy of one of the tags a reader shows: in a table read with the Exif tags. + public List CopiesOf (params int[] tags) => + [.. Shown ().Where (s => s.Table.ReadsExifTags && Array.IndexOf (tags, U16 (s.Entry)) >= 0 && ValueOf (s.Table, s.Entry) is not null).Select (s => s.Table.At)]; + + /// The ASCII values shown from the tables read with the Exif tags, by tag (a later one replaces an earlier one). + public Dictionary Strings () + { + var strings = new Dictionary (); + foreach (var (table, e) in Shown ()) { + if (table.ReadsExifTags && U16 (e + 2) == 2 && ValueOf (table, e) is byte[] value) + strings[U16 (e)] = Encoding.ASCII.GetString (value).TrimEnd ('\0'); + } + + return strings; + } + + /// + /// What a reader shows, as text: each table in offset order with its kinds, every entry read with its value bytes, + /// its next offset, and the bytes its offset/length pairs name (thumbnail, strips, tiles). Entries with a tag in are left out of tables read with the Exif + /// tags. Nothing is masked: a value that lies on a table is compared too. + /// + public string Visible (HashSet removed) => Visible (removed, anyTable: false); + + /// + /// . When is set, entries of a removed tag are + /// left out of every table, including one read only with the GPS tags: a table reached both ways loses those + /// copies, and that is the edit. + /// + public string Visible (HashSet removed, bool anyTable) + { + var text = new StringBuilder (); + foreach (var t in Tables.OrderBy (t => t.At)) { + text.Append ('[').Append (t.At).Append (' ').Append (string.Join ("+", t.Kinds.OrderBy (k => k))).Append (']'); + foreach (var (_, e) in Shown ().Where (s => s.Table == t)) { + if ((anyTable || t.ReadsExifTags) && removed.Contains (U16 (e))) + continue; + // An out-of-line value in the data is shown with its offset: where it lies decides whether exiftool shows + // it (the suspicious-offset rule). One past the data is shown by no reader, wherever it points, and nor is + // the out-of-line value of an Exif, GPS or interoperability IFD pointer (exiftool: "Bad value"; what it + // leads to is in the tables). + var size = TypeSize (U16 (e + 2)) * U32 (e + 4); + var value = size > 4 && U16 (e) is 0x8769 or 0x8825 or 0xA005 ? null : ValueOf (t, e); + text.Append (U16 (e).ToString ("X4", CultureInfo.InvariantCulture)).Append ('/').Append (U16 (e + 2)).Append ('/').Append (U32 (e + 4)) + .Append ('=').Append (value is null ? "OOR" : Convert.ToHexString (value)); + if (value is not null && size > 4) + text.Append ('@').Append (U32 (e + 8)); + text.Append (';'); + } + + var nextAt = t.At + 2 + (12L * t.Count); + text.Append (" next=").Append (nextAt + 4 <= _t.Length ? U32 (nextAt) : 0).Append (' '); + if (t.ReadsExifTags) + AppendData (text, t); + } + + return text.ToString (); + } + + // TIFF 6.0 offset/length pairs a reader extracts: the IFD1 thumbnail (JPEGInterchangeFormat and its length), + // strips and tiles. Each pair by its first entries; the bytes they name inside the data. + static readonly (int Offsets, int Lengths)[] DataPairs = [(0x0201, 0x0202), (0x0111, 0x0117), (0x0144, 0x0145)]; + + void AppendData (StringBuilder text, Table t) + { + foreach (var (offsetsTag, lengthsTag) in DataPairs) { + var offsets = Integers (t, offsetsTag); + var lengths = Integers (t, lengthsTag); + for (var k = 0; k < offsets.Count && k < lengths.Count; k++) { + var (from, to) = (offsets[k], offsets[k] + lengths[k]); + text.Append (CultureInfo.InvariantCulture, $" data {offsetsTag:X4}=").Append (to <= _t.Length && from < to ? Convert.ToHexString (_t, (int)from, (int)(to - from)) : "OOR"); + } + } + } + + // The SHORT or LONG values of the first entry with the tag. + List Integers (Table t, int tag) + { + for (var n = 0; n < t.Count; n++) { + var e = t.At + 2 + (12 * n); + if (U16 (e) != tag) + continue; + var size = U16 (e + 2) switch { 3 => 2, 4 => 4, _ => 0 }; + var count = U32 (e + 4); + var at = count * size <= 4 ? e + 8 : U32 (e + 8); + if (size == 0 || at + (count * size) > _t.Length) + return []; + return [.. Enumerable.Range (0, (int)count).Select (k => size == 2 ? U16 (at + (2 * k)) : U32 (at + (4 * k)))]; + } + + return []; + } + + /// + /// The field tags shown, counted, as one line of the golden files: "E" for a table read with the Exif tags, "G" + /// for a GPS table (its 0x0001 GPSLatitudeRef), then the tag in hex and the count. + /// + public string Summary () + { + var counts = new SortedDictionary (StringComparer.Ordinal); + foreach (var (table, e) in Shown ()) { + var tag = U16 (e); + var key = table.ReadsExifTags && Array.IndexOf (FieldTags, tag) >= 0 ? "E" + tag.ToString ("X4", CultureInfo.InvariantCulture) + : table.Kinds.Contains (Kind.Gps) && tag == 0x0001 ? "G0001" : null; + if (key is not null && ValueOf (table, e) is not null) + counts[key] = counts.GetValueOrDefault (key) + 1; + } + + return counts.Count == 0 ? "-" : string.Join (" ", counts.Select (c => $"{c.Key}={c.Value}")); + } +} diff --git a/tests/TagLibSharp2.Tests/Image/ExifTestData.cs b/tests/TagLibSharp2.Tests/Image/ExifTestData.cs new file mode 100644 index 00000000..7ec0423b --- /dev/null +++ b/tests/TagLibSharp2.Tests/Image/ExifTestData.cs @@ -0,0 +1,65 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Text; +using System.Xml.Linq; +using TagLibSharp2.Core; +using TagLibSharp2.Image; +using TagLibSharp2.Image.Exif; +using TagLibSharp2.Image.Tiff; +using TagLibSharp2.Image.Xmp; +using TagLibSharp2.Tests.Core; +using TagLibSharp2.Tests.Kit; +using static TagLibSharp2.Tests.Image.ImageTestBuilder; + +namespace TagLibSharp2.Tests.Image; + +/// The Exif inputs, carriers and reader-visible checks the Exif tests share. +static class ExifTestData +{ + // The carriers of an Exif TIFF: a JPEG APP1 segment, a PNG eXIf chunk, and ImageMagick's raw EXIF profile in PNG + // text (with its "Exif\0\0" signature); each file also holds a comment of its own (COM, or tEXt). + internal static byte[] InCarrier (string carrier, byte[] tiff) => carrier switch { + "jpeg" or "jpeg APP1" => Jpeg (JpegExif (tiff), JpegSegment (0xFE, "c"u8.ToArray ())), + "png" or "png eXIf" => Png (PngChunk ("eXIf", tiff), Text ("Comment", "c")), + _ => Png (RawProfile ("exif", Concat ("Exif\0\0"u8.ToArray (), tiff)), Text ("Comment", "c")), + }; + + /// The Exif TIFF a file holds in a carrier (without the "Exif\0\0" signature), or null when it holds none. + internal static byte[]? ExifIn (string carrier, byte[] file) + { + if (carrier.StartsWith ("jpeg", StringComparison.Ordinal)) { + var at = file.AsSpan ().IndexOf ("Exif\0\0"u8); + if (at < 0) + return null; + var length = (file[at - 2] << 8) | file[at - 1]; + return file[(at + 6)..(at - 2 + length)]; + } + + var raw = carrier.Contains ("raw", StringComparison.OrdinalIgnoreCase); + var texts = raw ? PngTexts (file, "Raw profile type exif") : []; + var tiff = raw ? (texts.Count == 0 ? null : DecodeRawProfile (texts[0])) : PngChunks (file).FirstOrDefault (c => c.Type == "eXIf").Payload; + return tiff is not null && tiff.AsSpan ().StartsWith ("Exif\0\0"u8) ? tiff[6..] : tiff; + } + + /// The Exif TIFF of a PNG eXIf chunk or a JPEG APP1 segment. + internal static byte[] ExifOf (byte[] file) => ExifIn (file[0] == 0x89 ? "png" : "jpeg", file)!; + + /// The ASCII values a reader shows from the Exif a file holds in a carrier. + internal static Dictionary ExifStrings (string carrier, byte[] file) => ExifReaderModel.Of (ExifIn (carrier, file)!).Strings (); + + // The full reader-visible result, before vs after, per the tests' own reader: exactly the given tags are gone + // from the tables read with the Exif tags, and every other table, entry, value and next offset any reader sees is + // unchanged (including tables no reader can read, which stay unread). Nothing is masked. + internal static void AssertOnlyTheCopiesAreGone (byte[] before, byte[] after, string message, params int[] removed) => + Assert.AreEqual (ExifReaderModel.AnyReader (before).Visible ([.. removed]), ExifReaderModel.AnyReader (after).Visible ([]), message); + + // UserComment and XPComment, the comment copies, wherever the tests' reader finds them. + internal static List UserCommentsInEveryExifIfd (byte[] tiff) => ExifReaderModel.Of (tiff).CopiesOf (0x9286, 0x9C9C); + + internal static readonly byte[] OldOne = "ASCII\0\0\0old comment one"u8.ToArray (); + internal static readonly byte[] OldTwo = "ASCII\0\0\0old comment two"u8.ToArray (); + + internal static readonly byte[] SecretUc = "ASCII\0\0\0secret-uc\u0001"u8.ToArray (); + internal static readonly byte[] HiddenUc = "ASCII\0\0\0hidden-uc"u8.ToArray (); +} diff --git a/tests/TagLibSharp2.Tests/Image/GainMapClearTests.cs b/tests/TagLibSharp2.Tests/Image/GainMapClearTests.cs new file mode 100644 index 00000000..45e5158f --- /dev/null +++ b/tests/TagLibSharp2.Tests/Image/GainMapClearTests.cs @@ -0,0 +1,388 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Text; +using System.Xml.Linq; +using TagLibSharp2.Core; +using TagLibSharp2.Image; +using TagLibSharp2.Image.Exif; +using TagLibSharp2.Image.Tiff; +using TagLibSharp2.Tests.Core; +using static TagLibSharp2.Tests.Image.GainMapTestData; +using static TagLibSharp2.Tests.Image.ImageTestBuilder; + +namespace TagLibSharp2.Tests.Image; + +/// Clear keeps only the typed gain-map values an HDR decoder needs from the XMP of Ultra HDR, Apple and motion-photo files. +[TestClass] +[TestCategory ("Unit")] +public class GainMapClearTests +{ + [TestMethod] + public void Clear_KeepsTheAppleGainMapXmp_AndDropsThePrimarysOther () + { + var secondImage = Jpeg (GpsExif (), JpegXmpBytes (AppleGainMapXmp)); + var input = MpfJpeg ( + Concat (GpsExif (), JpegXmpBytes (XmpPacket (Seq ("dc:creator", "Jane Private")), [0])), + [], secondImage, out _); + var file = Open (input, "a.jpg"); + file.Tag!.Clear (); + + var output = file.Render ().ToArray (); + + var packets = Packets (output); + Assert.AreEqual (1, packets.Count, "only the gain-map image keeps XMP"); + StringAssert.Contains (packets[0], "urn:com:apple:photo:2020:aux:hdrgainmap"); + var at = MpfSecondImage (output); + // Clear writes a new packet with only the Apple gain-map properties ImageIO reads. + var apple = XDocument.Parse (packets[0].TrimStart ('\uFEFF')).Descendants (Rdf + "Description").Single (); + XNamespace apdi = "http://ns.apple.com/pixeldatainfo/1.0/"; + XNamespace gainMap = "http://ns.apple.com/HDRGainMap/1.0/"; + Assert.AreEqual ("urn:com:apple:photo:2020:aux:hdrgainmap", apple.Element (apdi + "AuxiliaryImageType")?.Value); + Assert.AreEqual ("1278226488", apple.Element (apdi + "NativeFormat")?.Value); + Assert.AreEqual ("1278226488", apple.Element (apdi + "StoredFormat")?.Value); + Assert.AreEqual ("65536", apple.Element (gainMap + "HDRGainMapVersion")?.Value); + Assert.AreEqual ("", apple.Attribute (Rdf + "about")?.Value); + Assert.IsTrue (at > 0); + Assert.IsTrue (output.AsSpan ().IndexOf ("Jane Private"u8) < 0 && output.AsSpan ().IndexOf ("Exif\0\0"u8) < 0); + Assert.AreEqual (output.Length - at, MpfEntries (output)[1].Size); + } + + static string UltraHdrPrimary (int gainMapLength) => + XmpPacket ( + " " + + "" + + $"" + + "\n" + Seq ("dc:creator", "Jane Private"), + " xmlns:Container='http://ns.google.com/photos/1.0/container/' xmlns:Item='http://ns.google.com/photos/1.0/container/item/'" + + " xmlns:hdrgm='http://ns.adobe.com/hdr-gain-map/1.0/' hdrgm:Version='1.0' xmp:Label='private label'"); + + // Ultra HDR v1.0 (https://developer.android.com/media/platform/hdr-image-format): the primary's hdrgm:Version + // and Container:Directory locate the gain map, Item:Length is the gain map's length, and the gain map's + // hdrgm:* properties are its parameters. Clear keeps exactly those and rewrites Item:Length. + [TestMethod] + public void Clear_KeepsUltraHdrGainMapXmp_AndRewritesItemLength () + { + var secondImage = Jpeg (GpsExif (), JpegXmpBytes (UltraHdrGainMap)); + var input = MpfJpeg (Concat (GpsExif (), JpegXmpBytes (UltraHdrPrimary (secondImage.Length))), [], secondImage, out _); + var file = Open (input, "a.jpg"); + file.Tag!.Clear (); + + var output = file.Render ().ToArray (); + + Assert.IsTrue (output.AsSpan ().IndexOf ("Jane Private"u8) < 0 && output.AsSpan ().IndexOf ("private label"u8) < 0, "no personal field in any image"); + var packets = Packets (output).Select (p => XDocument.Parse (p.TrimStart (''))).ToList (); + Assert.AreEqual (2, packets.Count); + var primary = packets[0].Descendants (Rdf + "Description").Single (); + Assert.AreEqual ("1.0", primary.Attribute (Hdrgm + "Version")?.Value); + var items = packets[0].Descendants (Container + "Item").ToList (); + Assert.AreEqual (2, items.Count); + var at = MpfSecondImage (output); + Assert.AreEqual ((output.Length - at).ToString (System.Globalization.CultureInfo.InvariantCulture), items[1].Attribute (Item + "Length")?.Value, "Item:Length is the new gain-map length"); + Assert.AreEqual (output.Length - at, MpfEntries (output)[1].Size); + var gainMap = packets[1].Descendants (Rdf + "Description").Single (); + foreach (var name in new[] { "Version", "GainMapMin", "GainMapMax", "Gamma", "OffsetSDR", "OffsetHDR", "HDRCapacityMin", "HDRCapacityMax", "BaseRenditionIsHDR" }) + Assert.IsNotNull (gainMap.Attribute (Hdrgm + name), name); + Assert.IsFalse (packets.Any (p => p.Descendants (Dc + "creator").Any ())); + } + + [TestMethod] + public void Clear_DropsAnXmpPacketWithNoGainMapProperty () + { + var input = Jpeg (JpegXmpBytes (XmpPacket (Seq ("dc:creator", "Jane"))), JpegSegment (0xFE, "c"u8.ToArray ())); + var file = Open (input, "a.jpg"); + file.Tag!.Clear (); + Assert.AreEqual (0, Packets (file.Render ().ToArray ()).Count); + } + + const string Ns = "xmlns:rdf='http://www.w3.org/1999/02/22-rdf-syntax-ns#' xmlns:hdrgm='http://ns.adobe.com/hdr-gain-map/1.0/' " + + "xmlns:dc='http://purl.org/dc/elements/1.1/' xmlns:exif='http://ns.adobe.com/exif/1.0/' " + + "xmlns:Container='http://ns.google.com/photos/1.0/container/' xmlns:Item='http://ns.google.com/photos/1.0/container/item/' " + + "xmlns:apdi='http://ns.apple.com/pixeldatainfo/1.0/' xmlns:HDRGainMap='http://ns.apple.com/HDRGainMap/1.0/' " + + "xmlns:Camera='http://ns.google.com/photos/1.0/camera/'"; + const string Kept = "hdrgm:Version='1.0' hdrgm:GainMapMax='2.0' hdrgm:HDRCapacityMax='2.0'"; + + static string RdfPacket (string body) => $"{body}"; + + // The reviewer's hostile packets: duplicates, personal data nested inside kept properties, typed nodes, + // rdf:about text, comments and a second RDF, foreign prefixes. Clear never throws, keeps the gain-map + // values and nothing else. + public static IEnumerable HostilePackets () + { + yield return ["duplicate attribute across Descriptions", RdfPacket ($"")]; + yield return ["foreign attributes on a directory item", RdfPacket ($"")]; + yield return ["a struct nested in a kept array", RdfPacket ("2.0Jane Private47,30.0N")]; + yield return ["a typed node next to the gain map", RdfPacket ($"")]; + yield return ["rdf:about text, a comment and trailing text", "" + RdfPacket ($"") + "Jane Private 47N"]; + yield return ["rdf:ID on the Description", RdfPacket ($"")]; + yield return ["a second RDF", $""]; + yield return ["hdrgm prefix bound to another namespace", ""]; + yield return ["attribute and element forms of one property", RdfPacket ($"9.9")]; + yield return ["1,500 foreign properties", RdfPacket ($"" + string.Concat (Enumerable.Range (0, 1500).Select (n => $"Jane Private")) + "")]; + yield return ["a value with markup inside", RdfPacket ($"2.0Jane Private")]; + } + + [TestMethod] + [DynamicData (nameof (HostilePackets))] + public void Clear_OfAHostileGainMapPacket_KeepsOnlyTypedGainMapValues (string shape, string packet) + { + var input = Jpeg (JpegXmpBytes (packet), JpegSegment (0xFE, "c"u8.ToArray ())); + var file = Open (input, "a.jpg"); + file.Tag!.Clear (); + + var save = file.SaveToFile ("/a.jpg", new MockFileSystem ()); + Assert.IsTrue (save.IsSuccess, $"{shape}: {save.Error}"); + var output = file.Render ().ToArray (); + Assert.IsNotNull (Open (output, "a.jpg").ImageProperties, shape); + foreach (var personal in new[] { "Jane", "47,30.0N", "47N", "image/jpeg' dc", "dc:", "exif:", "9.9", "rdf:ID", "Creator" }) + Assert.IsTrue (output.AsSpan ().IndexOf (Encoding.ASCII.GetBytes (personal)) < 0, $"{shape}: '{personal}' survived Clear"); + var kept = XDocument.Parse (Packets (output).Single ().TrimStart ('\uFEFF')); + var description = kept.Descendants (Rdf + "Description").Single (); + Assert.AreEqual ("", description.Attribute (Rdf + "about")?.Value, shape); + Assert.AreEqual ("1.0", description.Attribute (Hdrgm + "Version")?.Value, shape); + Assert.IsTrue (description.Attributes ().All (a => a.IsNamespaceDeclaration || a.Name.Namespace == Hdrgm || a.Name == Rdf + "about"), shape); + Assert.IsTrue (description.Elements ().All (e => e.Name.Namespace == Hdrgm || e.Name.Namespace == Container), shape); + } + + [TestMethod] + public void Clear_KeepsAPerChannelArray_AndDropsAMalformedOne () + { + var packet = RdfPacket ("" + + "00.10" + + "22.5" + + "not a number0.1"); + var file = Open (Jpeg (JpegXmpBytes (packet)), "a.jpg"); + file.Tag!.Clear (); + var description = XDocument.Parse (Packets (file.Render ().ToArray ()).Single ().TrimStart ('\uFEFF')).Descendants (Rdf + "Description").Single (); + Assert.AreSequenceEqual (["0", "0.1", "0"], description.Element (Hdrgm + "GainMapMin")!.Descendants (Rdf + "li").Select (l => l.Value).ToList ()); + Assert.IsNull (description.Element (Hdrgm + "GainMapMax"), "two values is neither one nor three"); + Assert.IsNull (description.Element (Hdrgm + "Gamma")); + Assert.IsNull (description.Attribute (Hdrgm + "Gamma")); + Assert.IsNull (description.Attribute (Hdrgm + "OffsetSDR"), "a value with markup inside is not a Real"); + } + + [TestMethod] + public void Clear_IgnoresGainMapPropertiesOfANestedDescription () + { + // Only a top-level rdf:Description describes the image; one nested in another property does not. + var packet = RdfPacket (""); + var file = Open (Jpeg (JpegXmpBytes (packet), JpegSegment (0xFE, "c"u8.ToArray ())), "a.jpg"); + file.Tag!.Clear (); + Assert.AreEqual (0, Packets (file.Render ().ToArray ()).Count); + } + + [TestMethod] + public void Clear_RewritesAnItemLengthWrittenAsAnElement () + { + // exiftool writes Container:Item as a resource with Item:* child elements. + var gainMap = Jpeg (GpsExif (), JpegXmpBytes (UltraHdrGainMap)); + var primary = RdfPacket ("" + + "Primaryimage/jpeg" + + $"GainMapimage/jpeg{gainMap.Length}" + + ""); + var input = MpfJpeg (JpegXmpBytes (primary), [], gainMap, out _); + var file = Open (input, "a.jpg"); + file.Tag!.Clear (); + var output = file.Render ().ToArray (); + var items = XDocument.Parse (Packets (output)[0].TrimStart ('\uFEFF')).Descendants (Container + "Item").ToList (); + Assert.AreEqual ((output.Length - MpfSecondImage (output)).ToString (System.Globalization.CultureInfo.InvariantCulture), items[1].Attribute (Item + "Length")?.Value); + Assert.AreEqual ("GainMap", items[1].Attribute (Item + "Semantic")?.Value); + } + + // Ultra HDR with a motion photo: Primary, GainMap (the MPF image), MotionPhoto (a video after the last MPF + // image, which Clear copies as it is). Readers find the video by summing the primary's length and the + // preceding items' lengths, so the gain map's Item:Length follows its new length and the video's stays. + [TestMethod] + public void Clear_OfAMotionPhoto_RewritesTheGainMapLength_AndKeepsTheVideosLength () + { + var video = Enumerable.Range (0, 64).Select (n => (byte)(n + 1)).ToArray (); + var gainMap = Jpeg (GpsExif (), JpegXmpBytes (UltraHdrGainMap)); + var primary = RdfPacket ("" + + "" + + $"" + + "" + + ""); + var input = Concat (MpfJpeg (JpegXmpBytes (primary), [], gainMap, out _), video); + var file = Open (input, "a.jpg"); + file.Tag!.Clear (); + + var output = file.Render ().ToArray (); + + var items = XDocument.Parse (Packets (output)[0].TrimStart ('\uFEFF')).Descendants (Container + "Item").ToList (); + Assert.AreEqual (3, items.Count); + var gainMapLength = int.Parse (items[1].Attribute (Item + "Length")!.Value, System.Globalization.CultureInfo.InvariantCulture); + Assert.AreEqual ("64", items[2].Attribute (Item + "Length")?.Value); + Assert.AreSequenceEqual (["Primary", "GainMap", "MotionPhoto"], items.Select (i => i.Attribute (Item + "Semantic")?.Value).ToList ()); + Assert.AreSequenceEqual (["image/jpeg", "image/jpeg", "video/mp4"], items.Select (i => i.Attribute (Item + "Mime")?.Value).ToList ()); + var primaryLength = MpfSecondImage (output); + Assert.IsTrue (gainMapLength < gainMap.Length, "the gain map shrank"); + CollectionAssert.AreEqual (video, output[(primaryLength + gainMapLength)..], "summing the lengths lands on the video"); + var description = XDocument.Parse (Packets (output)[0].TrimStart ('\uFEFF')).Descendants (Rdf + "Description").Single (); + Assert.AreEqual ("1", description.Attribute (Camera + "MotionPhoto")?.Value, "a cleared motion photo is still one"); + Assert.AreEqual ("1", description.Attribute (Camera + "MotionPhotoVersion")?.Value); + Assert.AreEqual ("-1", description.Attribute (Camera + "MotionPhotoPresentationTimestampUs")?.Value); + } + + [TestMethod] + public void Clear_KeepsTheGainMapBehindASpacedXmpSignature () + { + var segment = JpegSegment (0xE1, Concat ("http://ns.adobe.com/xap/1.0/ \0"u8.ToArray (), Encoding.UTF8.GetBytes (RdfPacket ($"")))); + var file = Open (Jpeg (segment, JpegSegment (0xFE, "c"u8.ToArray ())), "a.jpg"); + file.Tag!.Clear (); + var output = file.Render ().ToArray (); + var at = output.AsSpan ().IndexOf ("http://ns.adobe.com/xap/1.0/ \0"u8); + Assert.IsTrue (at > 0, "the gain-map packet is kept behind the same signature"); + Assert.IsTrue (output.AsSpan ().IndexOf ("hdrgm:Version=\"1.0\""u8) > at); + Assert.IsTrue (output.AsSpan ().IndexOf ("dc:format"u8) < 0); + } + + [TestMethod] + public void Clear_OfAGainMapPacketThatWouldOutgrowItsSegment_DropsItAndStillReadsBack () + { + var input = Jpeg (JpegXmpBytes (OutgrowingPacket ()), JpegSegment (0xFE, "c"u8.ToArray ())); + Assert.IsTrue (input.Length < 65_000); + var file = Open (input, "a.jpg"); + file.Tag!.Clear (); + var save = file.SaveToFile ("/a.jpg", new MockFileSystem ()); + Assert.IsTrue (save.IsSuccess, save.Error); + var output = file.Render ().ToArray (); + Assert.IsNotNull (Open (output, "a.jpg").ImageProperties); + Assert.AreEqual (0, Packets (output).Count); + } + + static readonly XNamespace Camera = "http://ns.google.com/photos/1.0/camera/"; + // RDF allows an rdf:li's struct value as rdf:li > rdf:Description (libultrahdr reads it, as does exiftool). The + // item keeps its slot: the first item is the primary and readers sum the lengths before an item to find it. + [TestMethod] + public void Clear_ReadsADirectoryItemInsideAnRdfDescription_AndKeepsItsSlot () + { + var gainMap = Jpeg (GpsExif (), JpegXmpBytes (UltraHdrGainMap)); + var primary = RdfPacket ("" + + "" + + $"" + + ""); + var file = Open (MpfJpeg (Concat (GpsExif (), JpegXmpBytes (primary)), [], gainMap, out _), "a.jpg"); + file.Tag!.Clear (); + + var output = file.Render ().ToArray (); + + var items = XDocument.Parse (Packets (output)[0].TrimStart ('\uFEFF')).Descendants (Container + "Item").ToList (); + Assert.AreSequenceEqual (["Primary", "GainMap"], items.Select (i => i.Attribute (Item + "Semantic")?.Value).ToList ()); + var gainMapLength = output.Length - MpfSecondImage (output); + Assert.IsTrue (gainMapLength < gainMap.Length, "the gain map shrank"); + Assert.AreEqual (gainMapLength.ToString (System.Globalization.CultureInfo.InvariantCulture), items[1].Attribute (Item + "Length")?.Value); + } + + // Item:Semantic and Item:Mime are enumerated (Ultra HDR v1.0, Motion Photo 1.0). Any other value is free text: + // it is dropped, and the item keeps its slot and its length so the offsets of the later items stay right. + [TestMethod] + public void Clear_DropsAnItemValueTheFormatsDoNotEnumerate_AndKeepsTheItemsLength () + { + var video = Enumerable.Range (0, 64).Select (n => (byte)(n + 1)).ToArray (); + var gainMap = Jpeg (GpsExif (), JpegXmpBytes (UltraHdrGainMap)); + var primary = RdfPacket ("" + + "" + + $"" + + "HomeAtElmStreetvideo/mp464" + + ""); + var file = Open (Concat (MpfJpeg (JpegXmpBytes (primary), [], gainMap, out _), video), "a.jpg"); + file.Tag!.Clear (); + + var output = file.Render ().ToArray (); + + foreach (var personal in new[] { "Jane", "jane", "47.30N", "HomeAtElm" }) + Assert.IsTrue (output.AsSpan ().IndexOf (Encoding.ASCII.GetBytes (personal)) < 0, $"'{personal}' survived Clear"); + var items = XDocument.Parse (Packets (output)[0].TrimStart ('\uFEFF')).Descendants (Container + "Item").ToList (); + Assert.AreEqual (3, items.Count, "every slot is kept"); + Assert.IsFalse (items[0].Attributes ().Any (), "the primary keeps its slot with no free text"); + Assert.AreEqual ("video/mp4", items[2].Attribute (Item + "Mime")?.Value); + Assert.AreEqual ("64", items[2].Attribute (Item + "Length")?.Value); + var gainMapLength = int.Parse (items[1].Attribute (Item + "Length")!.Value, System.Globalization.CultureInfo.InvariantCulture); + CollectionAssert.AreEqual (video, output[(MpfSecondImage (output) + gainMapLength)..], "summing the lengths lands on the video"); + } + + // One row per value check of the rebuild: each check alone keeps "Jane Private" (or NaN, a DTD, a second + // directory) out of the cleared file. Every row keeps the valid gain-map values next to the hostile one. + public static IEnumerable WrongShapes () + { + const string Max = "hdrgm:GainMapMax='2.0' hdrgm:HDRCapacityMax='2.0'"; + const string DirectoryFormat = "{0}"; + static string Directory (string items) => string.Format (System.Globalization.CultureInfo.InvariantCulture, DirectoryFormat, items); + yield return ["Item:Mime", RdfPacket ($"{Directory ("")}"), "Jane", true]; + yield return ["Item:Semantic", RdfPacket ($"{Directory ("")}"), "Jane", true]; + yield return ["Item:Length", RdfPacket ($"{Directory ("")}"), "Jane", true]; + yield return ["apdi:AuxiliaryImageType", RdfPacket ($""), "Jane", true]; + yield return ["apdi:NativeFormat (Integer)", RdfPacket ($"Jane Private"), "Jane", true]; + yield return ["hdrgm:BaseRenditionIsHDR (Boolean)", RdfPacket ($""), "Jane", true]; + yield return ["hdrgm:Version", RdfPacket ($""), "Jane", true]; + yield return ["NaN as a Real", RdfPacket ($""), "NaN", true]; + yield return ["Infinity as a Real", RdfPacket ($""), "Infinity", true]; + yield return ["a second Container:Directory", RdfPacket ($"{Directory ("")}"), "424242", true]; + yield return ["a directory slot with no item", RdfPacket ($"{Directory ("Jane Private")}"), "424242", true]; + yield return ["Camera:MotionPhoto (Integer)", RdfPacket ($""), "Camera", true]; + yield return ["Camera:MotionPhotoPresentationTimestampUs (Long)", RdfPacket ($""), "Camera", true]; + yield return ["HDRGainMap:HDRGainMapHeadroom (Real)", RdfPacket ($"Jane Private"), "Jane", true]; + yield return ["a DTD", "]>" + RdfPacket ($""), "Jane", false]; + } + + [TestMethod] + [DynamicData (nameof (WrongShapes))] + public void Clear_DropsAValueOfTheWrongShape_AndKeepsTheRest (string shape, string packet, string marker, bool keepsPacket) + { + var file = Open (Jpeg (JpegXmpBytes (packet), JpegSegment (0xFE, "c"u8.ToArray ())), "a.jpg"); + file.Tag!.Clear (); + + var output = file.Render ().ToArray (); + + Assert.IsTrue (output.AsSpan ().IndexOf (Encoding.ASCII.GetBytes (marker)) < 0, $"{shape}: '{marker}' survived Clear"); + var packets = Packets (output); + Assert.AreEqual (keepsPacket ? 1 : 0, packets.Count, shape); + if (keepsPacket) + Assert.AreEqual ("2.0", XDocument.Parse (packets[0].TrimStart ('\uFEFF')).Descendants (Rdf + "Description").Single ().Attribute (Hdrgm + "GainMapMax")?.Value, shape); + } + + // Motion Photo 1.0: Camera:MotionPhoto and Camera:MotionPhotoVersion are Integers and + // Camera:MotionPhotoPresentationTimestampUs a Long (-1 when unset). Clear keeps them so the photo is still one. + [TestMethod] + [DataRow ("MotionPhoto", "1", true)] + [DataRow ("MotionPhoto", "-1", false)] + [DataRow ("MotionPhotoVersion", "1", true)] + [DataRow ("MotionPhotoVersion", "1.0", false)] + [DataRow ("MotionPhotoPresentationTimestampUs", "-1", true)] + [DataRow ("MotionPhotoPresentationTimestampUs", "1500000", true)] + [DataRow ("MotionPhotoPresentationTimestampUs", "-", false)] + [DataRow ("MotionPhotoPresentationTimestampUs", "--1", false)] + [DataRow ("MotionPhotoPresentationTimestampUs", "1.5", false)] + public void Clear_KeepsATypedMotionPhotoProperty (string name, string value, bool kept) + { + var file = Open (Jpeg (JpegXmpBytes (RdfPacket ($"")), JpegSegment (0xFE, "c"u8.ToArray ())), "a.jpg"); + file.Tag!.Clear (); + + var packets = Packets (file.Render ().ToArray ()); + + Assert.AreEqual (kept ? 1 : 0, packets.Count); + if (kept) + Assert.AreEqual (value, XDocument.Parse (packets[0].TrimStart ('\uFEFF')).Descendants (Rdf + "Description").Single ().Attribute (Camera + name)?.Value); + } + + // Ultra HDR v1.0 and Motion Photo 1.0 enumerate Item:Semantic and Item:Mime; each enumerated value survives Clear. + [TestMethod] + [DataRow ("Mime", "image/jpeg")] + [DataRow ("Mime", "image/heic")] + [DataRow ("Mime", "image/avif")] + [DataRow ("Mime", "video/mp4")] + [DataRow ("Mime", "video/quicktime")] + [DataRow ("Semantic", "Primary")] + [DataRow ("Semantic", "GainMap")] + [DataRow ("Semantic", "MotionPhoto")] + public void Clear_KeepsEveryEnumeratedItemValue (string field, string value) + { + var packet = RdfPacket ($""); + var file = Open (Jpeg (JpegXmpBytes (packet), JpegSegment (0xFE, "c"u8.ToArray ())), "a.jpg"); + file.Tag!.Clear (); + + var item = XDocument.Parse (Packets (file.Render ().ToArray ()).Single ().TrimStart ('')).Descendants (Container + "Item").Single (); + + Assert.AreEqual (value, item.Attribute (Item + field)?.Value); + } +} diff --git a/tests/TagLibSharp2.Tests/Image/GainMapTestData.cs b/tests/TagLibSharp2.Tests/Image/GainMapTestData.cs new file mode 100644 index 00000000..93654680 --- /dev/null +++ b/tests/TagLibSharp2.Tests/Image/GainMapTestData.cs @@ -0,0 +1,71 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Text; +using System.Xml.Linq; +using TagLibSharp2.Core; +using TagLibSharp2.Image; +using TagLibSharp2.Image.Exif; +using TagLibSharp2.Image.Tiff; +using TagLibSharp2.Tests.Core; +using static TagLibSharp2.Tests.Image.ImageTestBuilder; + +namespace TagLibSharp2.Tests.Image; + +/// The gain-map packets and images the Clear tests of HDR files share. +static class GainMapTestData +{ + // The gain-map image's XMP as ImageIO writes it for an HDRGainMap auxiliary image. + internal const string AppleGainMapXmp = """ + + + + 1278226488 + 1278226488 + urn:com:apple:photo:2020:aux:hdrgainmap + 65536 + + + + + """; + + internal static byte[] JpegXmpBytes (string packet, byte[]? tail = null) => + JpegSegment (0xE1, Concat ("http://ns.adobe.com/xap/1.0/\0"u8.ToArray (), Encoding.UTF8.GetBytes (packet), tail ?? [])); + + internal static byte[] GpsExif () => JpegExif (ExifTiff ([(0x010F, "Canon"), (0x013B, "Jane Private")], [(0x8827, "GPS")])); + + internal static List Packets (byte[] jpeg) + { + var packets = new List (); + var at = 0; + while (true) { + var found = jpeg.AsSpan (at).IndexOf ("http://ns.adobe.com/xap/1.0/\0"u8); + if (found < 0) + return packets; + at += found; + var length = (jpeg[at - 2] << 8) | jpeg[at - 1]; + packets.Add (Encoding.UTF8.GetString (jpeg, at + 29, length - 2 - 29).TrimEnd ('\0', ' ', '\n')); + at += 29; + } + } + + internal const string UltraHdrGainMap = """ + + + Jane Private + + """; + + // Compact directory items grow when written in the format's own form; past 64 KB the packet is dropped. + internal static string OutgrowingPacket (string attributes = "") + { + var items = string.Concat (Enumerable.Range (0, 800).Select (_ => "")); + return "" + + $"{items}"; + } +} diff --git a/tests/TagLibSharp2.Tests/Image/GifCommentPinTests.cs b/tests/TagLibSharp2.Tests/Image/GifCommentPinTests.cs new file mode 100644 index 00000000..8142ebf2 --- /dev/null +++ b/tests/TagLibSharp2.Tests/Image/GifCommentPinTests.cs @@ -0,0 +1,440 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Runtime.InteropServices; +using System.Text; +using TagLibSharp2.Core; +using TagLibSharp2.Image; +using TagLibSharp2.Image.Exif; +using TagLibSharp2.Image.Gif; +using TagLibSharp2.Image.Png; +using TagLibSharp2.Image.Svg; +using TagLibSharp2.Image.Tiff; +using TagLibSharp2.Tests.Core; +using TagLibSharp2.Tests.Kit; +using static TagLibSharp2.Tests.Image.ImageTestBuilder; + +namespace TagLibSharp2.Tests.Image; + +public partial class GifCommentTests +{ + [TestMethod] + public void Gif_GlobalColorTable_StaysAheadOfTheComment_AndACharacterIsNotSplit () + { + var gif = GifWithTable (); + var file = Open (gif, "a.gif"); + file.Tag!.Comment = new string ('a', 254) + "é"; + var saved = file.SaveToFile ("/a.gif", new MockFileSystem ()); + Assert.IsTrue (saved.IsSuccess, saved.Error); + var output = file.Render ().ToArray (); + + CollectionAssert.AreEqual (gif.AsSpan (13, 6).ToArray (), output.AsSpan (13, 6).ToArray ()); + var comment = GifCommentBytes (output); + Assert.AreEqual (254, comment[2]); + Assert.AreEqual (2, comment[2 + 1 + 254]); + Assert.AreEqual (0xC3, comment[2 + 1 + 254 + 1]); + Assert.AreEqual (0xA9, comment[2 + 1 + 254 + 2]); + } + + static byte[] GifWithTable () + { + var header = new byte[19]; + "GIF89a"u8.CopyTo (header); + header[6] = 1; + header[8] = 1; + header[10] = 0x80; + for (var i = 0; i < 6; i++) + header[13 + i] = (byte)(10 + i); + return Concat (header, [0x3B]); + } + + static byte[] GifCommentBytes (byte[] gif) + { + var at = gif.AsSpan ().IndexOf ((byte)0x21); + Assert.IsTrue (at > 0); + return gif[at..]; + } + + [TestMethod] + public void Gif87aClear_KeepsThe87aSignature () + { + var old = new byte[14]; + "GIF87a"u8.CopyTo (old); + old[6] = 1; + old[8] = 1; + old[13] = 0x3B; + var file = Open (old, "a.gif"); + file.Tag!.Clear (); + + CollectionAssert.AreEqual ("GIF87a"u8.ToArray (), file.Render ().Span.Slice (0, 6).ToArray ()); + } + + [TestMethod] + public void Gif_NetscapeIdOnADifferentLabelOrBlockLength_IsDroppedOnClear () + { + var wrongLabel = GifWithExtension (ApplicationWithSize (0x99, 11, "NETSCAPE2.0")); + var wrongSize = GifWithExtension (ApplicationWithSize (0xFF, 12, "NETSCAPE2.0" + "X")); + var labelFile = Open (wrongLabel, "a.gif"); + var sizeFile = Open (wrongSize, "b.gif"); + labelFile.Tag!.Clear (); + sizeFile.Tag!.Clear (); + + CollectionAssert.AreEqual (GifTrailerOnly (), labelFile.Render ().Span.ToArray ()); + CollectionAssert.AreEqual (GifTrailerOnly (), sizeFile.Render ().Span.ToArray ()); + } + + [TestMethod] + public void Gif87a_GainsThe89aSignature_AndALocalColorTableStaysWithItsImage () + { + var old = new byte[14]; + "GIF87a"u8.CopyTo (old); + old[6] = 1; + old[8] = 1; + old[13] = 0x3B; + var upgraded = Open (old, "a.gif"); + upgraded.Tag!.Comment = "Z"; + CollectionAssert.AreEqual ("GIF89a"u8.ToArray (), upgraded.Render ().Span.Slice (0, 6).ToArray ()); + + var gif = GifWithLocalTable (); + var file = Open (gif, "b.gif"); + file.Tag!.Comment = "Z"; + var output = file.Render ().ToArray (); + var image = output.AsSpan ().IndexOf ((byte)0x2C); + Assert.IsTrue (image > 0); + CollectionAssert.AreEqual (new byte[] { 0x21, 0xFE, 1, (byte)'Z', 0 }, output.AsSpan (13, 5).ToArray ()); + CollectionAssert.AreEqual (new byte[] { 0xA0, 0xA1, 0xA2, 0xA3, 0xA4, 0xA5 }, output.AsSpan (image + 10, 6).ToArray ()); + } + + [TestMethod] + public void Gif_UnknownIntroducer_IsNotAPlan () + { + var tag = new ImageTag (MediaFormat.Gif, ImageStores.Comment); + tag.Comment = "Z"; + var data = GifWithExtension ([0x2A, 0x00, 0x00]); + + Assert.IsNull (GifRewriter.Plan (data, tag, out var error)); + Assert.AreEqual (GifRewriter.SpliceError, error); + } + + [TestMethod] + public void GifCommentEdit_KeepsAnApplicationBlockThatMentionsUserComment () + { + var block = new byte[3 + 11 + 1 + 11 + 1]; + block[0] = 0x21; + block[1] = 0xFF; + block[2] = 11; + "XXXXXXXXXXX"u8.CopyTo (block.AsSpan (3)); + block[14] = 11; + "UserComment"u8.CopyTo (block.AsSpan (15)); + var data = GifWithExtension (block); + var tag = new ImageTag (MediaFormat.Gif, ImageStores.Comment); + tag.Comment = "Z"; + + var plan = GifRewriter.Plan (data, tag, out var error); + + Assert.IsNotNull (plan, error); + var output = plan!.Materialize (data); + CollectionAssert.AreEqual ("XXXXXXXXXXX"u8.ToArray (), output.AsSpan (13 + 5 + 3, 11).ToArray ()); + } + + [TestMethod] + public void Gif_ShortImageDescriptor_IsNotAPlan () + { + var tag = new ImageTag (MediaFormat.Gif, ImageStores.Comment); + tag.Comment = "Z"; + var header = new byte[13]; + "GIF89a"u8.CopyTo (header); + header[6] = 1; + header[8] = 1; + + Assert.IsNull (GifRewriter.Plan (Concat (header, [0x2C, 0, 0, 0, 0]), tag, out var error)); + Assert.AreEqual (GifRewriter.SpliceError, error); + } + + [TestMethod] + public void Gif_ImageColorTableCutOffBeforeTheTrailer_IsNotAPlan () + { + var tag = new ImageTag (MediaFormat.Gif, ImageStores.Comment); + tag.Comment = "Z"; + var header = new byte[13]; + "GIF89a"u8.CopyTo (header); + header[6] = 1; + header[8] = 1; + var descriptor = new byte[11]; + descriptor[0] = 0x2C; + descriptor[9] = 0x80; + descriptor[10] = 0x3B; + + Assert.IsNull (GifRewriter.Plan (Concat (header, descriptor), tag, out var error)); + Assert.AreEqual (GifRewriter.SpliceError, error); + } + + [TestMethod] + public void Gif_SubBlockLongerThanTheRestOfTheFile_IsNotAPlan () + { + var tag = new ImageTag (MediaFormat.Gif, ImageStores.Comment); + tag.Comment = "Z"; + + Assert.IsNull (GifRewriter.Plan (GifWithExtension ([0x21, 0xFE, 5, 0x3B]), tag, out var error)); + Assert.AreEqual (GifRewriter.SpliceError, error); + } + + [TestMethod] + public void Gif_CommentThenACutOffImage_DoesNotYieldTheComment () + { + var header = new byte[13]; + "GIF89a"u8.CopyTo (header); + header[6] = 1; + header[8] = 1; + var data = Concat (header, [0x21, 0xFE, 2, (byte)'H', (byte)'i', 0, 0x2C, 0, 0]); + var tag = new ImageTag (MediaFormat.Gif, ImageStores.Comment); + tag.Comment = "keep"; + + GifRewriter.Read (data, tag); + + Assert.AreEqual ("keep", tag.Comment); + } + + [TestMethod] + public void Gif_CommentThatEndsTheFileWithoutATrailer_IsNotRead () + { + var header = new byte[13]; + "GIF89a"u8.CopyTo (header); + header[6] = 1; + header[8] = 1; + var data = Concat (header, [0x21, 0xFE, 2, (byte)'H', (byte)'i', 0]); + var tag = new ImageTag (MediaFormat.Gif, ImageStores.Comment); + tag.Comment = "keep"; + + GifRewriter.Read (data, tag); + + Assert.AreEqual ("keep", tag.Comment); + } + + [TestMethod] + public void Gif_ReadOfANonGif_KeepsACommentAlreadySet () + { + var tag = new ImageTag (MediaFormat.Gif, ImageStores.Comment); + tag.Comment = "keep"; + + GifRewriter.Read ([1, 2, 3], tag); + + Assert.AreEqual ("keep", tag.Comment); + } + + [TestMethod] + public void Gif_TenByteSignature_NamesTheTruncatedHeader () + { + var data = new byte[10]; + "GIF89a"u8.CopyTo (data); + var tag = new ImageTag (MediaFormat.Gif, ImageStores.Comment); + tag.Comment = "Z"; + + Assert.IsNull (GifRewriter.Plan (data, tag, out var error)); + Assert.AreEqual (GifRewriter.HeaderError, error); + } + + [TestMethod] + public void Gif_SubBlockThatFillsTheFileWithoutATerminator_IsNotAPlan () + { + var tag = new ImageTag (MediaFormat.Gif, ImageStores.Comment); + tag.Comment = "Z"; + var header = new byte[13]; + "GIF89a"u8.CopyTo (header); + header[6] = 1; + header[8] = 1; + + Assert.IsNull (GifRewriter.Plan (Concat (header, [0x21, 0xFE, 1, (byte)'A']), tag, out var error)); + Assert.AreEqual (GifRewriter.SpliceError, error); + } + + [TestMethod] + public void Gif_CommentSubBlockCutOff_KeepsACommentAlreadySet () + { + var header = new byte[13]; + "GIF89a"u8.CopyTo (header); + header[6] = 1; + header[8] = 1; + var tag = new ImageTag (MediaFormat.Gif, ImageStores.Comment); + tag.Comment = "keep"; + + GifRewriter.Read (Concat (header, [0x21, 0xFE, 5, (byte)'A']), tag); + + Assert.AreEqual ("keep", tag.Comment); + } + + [TestMethod] + public void Gif_CommentLongerThanOneSubBlock_SplitsAt255 () + { + var header = new byte[13]; + "GIF89a"u8.CopyTo (header); + header[6] = 1; + header[8] = 1; + var data = Concat (header, [0x3B]); + var tag = new ImageTag (MediaFormat.Gif, ImageStores.Comment); + tag.Comment = new string ('A', 300); + + var plan = GifRewriter.Plan (data, tag, out var error); + Assert.IsNotNull (plan, error); + var output = plan!.Materialize (data); + + Assert.AreEqual (0x21, output[13]); + Assert.AreEqual (0xFE, output[14]); + Assert.AreEqual (255, output[15]); + Assert.AreEqual ((byte)'A', output[16]); + Assert.AreEqual (45, output[16 + 255]); + } + + // A packet whose UTF-8 length is a multiple of 255 fills whole sub-blocks. The extension still ends on one + // zero; a second zero is the next block and stops the reader before the trailer. + [TestMethod] + public void Gif_XmpSubBlockPacketFillingWholeBlocks_EndsTheExtensionOnce () + { + var packet = "" + + "" + + "Old"; + var data = GifWithExtension (GifSubBlockXmp (packet)); + string? comment = null; + byte[]? output = null; + for (var n = 1; n <= 255 && output is null; n++) { + comment = new string ('B', n); + var tag = new ImageTag (MediaFormat.Gif, ImageStores.Comment); + tag.Comment = comment; + var plan = GifRewriter.Plan (data, tag, out var error); + Assert.IsNotNull (plan, error); + var rendered = plan!.Materialize (data); + if (XmpSubBlockPayload (rendered) % 255 == 0) + output = rendered; + } + + Assert.IsNotNull (output); + var read = new ImageTag (MediaFormat.Gif, ImageStores.Comment); + GifRewriter.Read (output, read); + Assert.AreEqual (comment, read.Comment); + } + + [TestMethod] + public void Gif_XmpPacketThatIsNotXml_RefusesTheCommentEdit () + { + var tag = new ImageTag (MediaFormat.Gif, ImageStores.Comment); + tag.Comment = "Z"; + + Assert.IsNull (GifRewriter.Plan (GifWithExtension (GifXmp ("= 0); + Assert.IsTrue (output.AsSpan ().IndexOf ("XXXXXXXXXXX"u8) < 0); + } + + static byte[] GifWithLocalTable () + { + var data = new byte[32]; + "GIF89a"u8.CopyTo (data); + data[6] = 1; + data[8] = 1; + data[13] = 0x2C; + data[18] = 1; + data[20] = 1; + data[22] = 0x80; + for (var i = 0; i < 6; i++) + data[23 + i] = (byte)(0xA0 + i); + data[29] = 2; + data[31] = 0x3B; + return data; + } + + static int XmpSubBlockPayload (byte[] data) + { + var at = data.AsSpan ().IndexOf ("XMP DataXMP"u8); + Assert.IsTrue (at >= 0); + var i = at + 11; + var payload = 0; + while (i < data.Length && data[i] != 0) { + var size = data[i]; + payload += size; + i += 1 + size; + } + + return payload; + } + + static byte[] GifWithExtension (params byte[][] blocks) + { + var header = new byte[13]; + "GIF89a"u8.CopyTo (header); + header[6] = 1; + header[8] = 1; + return Concat (header, Concat (blocks), [0x3B]); + } + + static byte[] Application (string id) + { + var block = new byte[3 + 11 + 1]; + block[0] = 0x21; + block[1] = 0xFF; + block[2] = 11; + Encoding.ASCII.GetBytes (id).CopyTo (block, 3); + return block; + } + + /// An extension whose first sub-block is , then a zero terminator. + static byte[] ApplicationWithSize (byte label, int size, string payload) + { + var block = new byte[3 + size + 1]; + block[0] = 0x21; + block[1] = label; + block[2] = (byte)size; + Encoding.ASCII.GetBytes (payload).CopyTo (block, 3); + return block; + } + + static byte[] GifTrailerOnly () + { + var data = new byte[14]; + "GIF89a"u8.CopyTo (data); + data[6] = 1; + data[8] = 1; + data[13] = 0x3B; + return data; + } + + static byte[] XmpUserCommentBlock () + { + // A real application extension: the 11-byte id, then one data sub-block, then the terminator. + // The packet is not sub-block XML and has no magic trailer, and it names UserComment. + var block = new byte[3 + 11 + 1 + 11 + 1]; + block[0] = 0x21; + block[1] = 0xFF; + block[2] = 11; + "XMP DataXMP"u8.CopyTo (block.AsSpan (3)); + block[14] = 11; + "UserComment"u8.CopyTo (block.AsSpan (15)); + return block; + } +} diff --git a/tests/TagLibSharp2.Tests/Image/GifCommentTests.cs b/tests/TagLibSharp2.Tests/Image/GifCommentTests.cs new file mode 100644 index 00000000..a69745ef --- /dev/null +++ b/tests/TagLibSharp2.Tests/Image/GifCommentTests.cs @@ -0,0 +1,89 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Buffers.Binary; +using System.IO.Compression; +using System.Text; +using TagLibSharp2.Core; +using TagLibSharp2.Image; +using TagLibSharp2.Tests.Core; +using static TagLibSharp2.Tests.Image.ImageTestBuilder; + +namespace TagLibSharp2.Tests.Image; + +/// The GIF comment extension: reading, writing, and where a new one goes. +[TestClass] +[TestCategory ("Unit")] +public partial class GifCommentTests +{ + [TestMethod] + public void Gif_RoundTripsComment_AndLeavesImageBytesThatLookLikeAComment () + { + var trap = new byte[] { 0x21, 0xFE, 0x00, 0x99 }; + var data = GifWithComment ("hello", trap); + var file = Open (data, "anim.gif"); + Assert.AreEqual ("hello", file.Tag!.Comment); + file.Tag.Comment = "hello"; + CollectionAssert.AreEqual (data, file.Render ().ToArray ()); + + file.Tag.Title = "Nope"; + Assert.IsNull (file.Tag.Title); + CollectionAssert.AreEqual (data, file.Render ().ToArray ()); + + var comment = new string ('A', 300); + file.Tag.Comment = comment; + var rendered = file.Render ().ToArray (); + CollectionAssert.AreEqual (trap, GifImageSubBlock (rendered)); + Assert.AreEqual (comment, Open (rendered, "anim.gif").Tag!.Comment); + Assert.IsNull (Open (rendered, "anim.gif").Tag!.Title); + + file.Tag.Comment = null; + var cleared = file.Render ().ToArray (); + Assert.IsNull (Open (cleared, "anim.gif").Tag!.Comment); + CollectionAssert.AreEqual (trap, GifImageSubBlock (cleared)); + } + + [TestMethod] + public void Gif87a_Comment_IsSavedAsGif89a () + { + var data = new byte[14]; + System.Text.Encoding.ASCII.GetBytes ("GIF87a").CopyTo (data, 0); + data[6] = 4; + data[8] = 2; + data[13] = 0x3B; + var file = Open (data, "old.gif"); + CollectionAssert.AreEqual (data, file.Render ().ToArray ()); + + file.Tag!.Comment = "note"; + var rendered = file.Render ().ToArray (); + CollectionAssert.AreEqual (System.Text.Encoding.ASCII.GetBytes ("GIF89a"), rendered.Take (6).ToArray ()); + Assert.AreEqual (4, Open (rendered, "old.gif").ImageProperties!.Value.Width); + Assert.AreEqual (2, Open (rendered, "old.gif").ImageProperties!.Value.Height); + Assert.AreEqual ("note", Open (rendered, "old.gif").Tag!.Comment); + } + + [TestMethod] + public void Gif_NewComment_IsWrittenBeforeTheImage () + { + var trap = new byte[] { 0x21, 0xFE, 0x00, 0x99 }; + var data = GifWithCommentAfterImage ("old", trap); + var file = Open (data, "anim.gif"); + file.Tag!.Comment = "placed"; + var rendered = file.Render ().ToArray (); + + Assert.IsTrue (IndexOf (rendered, 0x21, 0xFE) < IndexOf (rendered, 0x2C, -1), "comment follows the image"); + Assert.AreEqual ("placed", Open (rendered, "anim.gif").Tag!.Comment); + CollectionAssert.AreEqual (trap, GifImageSubBlock (rendered)); + } + + static byte[] GifWithCommentAfterImage (string comment, byte[] trap) + { + var imageFirst = GifWithComment (comment, trap); + var commentAt = IndexOf (imageFirst, 0x21, 0xFE); + var imageAt = IndexOf (imageFirst, 0x2C, -1); + var header = imageFirst.AsSpan (0, commentAt).ToArray (); + var commentBlock = imageFirst.AsSpan (commentAt, imageAt - commentAt).ToArray (); + var rest = imageFirst.AsSpan (imageAt).ToArray (); + return Concat (header, rest[..^1], commentBlock, [0x3B]); + } +} diff --git a/tests/TagLibSharp2.Tests/Image/Golden/exif-edit-matrix.txt b/tests/TagLibSharp2.Tests/Image/Golden/exif-edit-matrix.txt new file mode 100644 index 00000000..353eeaea --- /dev/null +++ b/tests/TagLibSharp2.Tests/Image/Golden/exif-edit-matrix.txt @@ -0,0 +1,442 @@ +# What exiftool 13.55 shows for each generated input; regenerate with tools/exif/golden.sh. +# inputs 15904 sha256 a3cfcf35feb48a5f812897f46ce60cec6458f76556a3831118ee94ee55db11a1 +@summaries +0 E013B=1 E9286=9 E9C9C=1 G0001=1 +1 E013B=1 E9286=3 E9C9C=1 G0001=1 +2 E013B=1 E9286=4 E9C9C=1 G0001=1 +3 E013B=1 E9286=6 E9C9C=1 G0001=1 +4 E013B=1 E9286=5 E9C9C=1 G0001=1 +5 E013B=1 E9286=6 E9C9C=1 +6 E013B=1 E9286=7 E9C9C=1 +7 E013B=1 E9286=8 E9C9C=1 +8 E013B=1 E9286=9 E9C9C=1 +9 E013B=1 E9286=5 E9C9C=1 +10 E013B=1 E9286=9 G0001=1 +11 E9286=9 G0001=1 +12 E9286=9 E9C9C=1 G0001=1 +13 E9286=4 +14 E9286=8 +15 E013B=1 E9286=7 E9C9C=1 G0001=1 +16 - +17 E013B=1 E9286=4 E9C9C=1 +18 E9286=6 G0001=1 +19 E013B=1 E9286=8 E9C9C=1 G0001=1 +20 E9286=1 +21 E013B=1 E9286=8 G0001=1 +22 E9286=2 +23 E9286=7 +24 E013B=1 E9286=3 E9C9C=1 +25 E9286=5 G0001=1 +26 E9286=2 G0001=1 +27 E013B=1 E9286=10 E9C9C=1 G0001=1 +28 E9286=6 E9C9C=1 G0001=1 +29 E9286=2 E9C9C=1 G0001=1 +30 E9286=7 E9C9C=1 G0001=1 +31 E013B=1 E9286=10 E9C9C=1 +32 E013B=1 E9286=7 G0001=1 +33 E013B=1 E9286=5 G0001=1 +34 E013B=1 E9286=3 G0001=1 +35 E9286=8 G0001=1 +36 E9286=5 E9C9C=1 G0001=1 +37 E9286=3 E9C9C=1 G0001=1 +38 E9286=8 E9C9C=1 G0001=1 +39 E013B=1 E9286=2 E9C9C=1 G0001=1 +@inputs +0 1 2 0 3 4 3 1 1 3 4 4 4 3 1 4 3 4 3 3 3 3 4 4 4 3 3 4 4 1 4 3 3 4 1 1 1 2 3 1 +4 1 4 2 2 4 2 2 2 4 3 2 2 2 2 4 4 2 2 3 3 2 4 3 4 4 4 2 2 4 4 3 3 4 4 3 4 3 4 4 +4 4 3 3 3 4 2 3 5 4 5 4 4 5 4 4 4 5 2 4 5 2 5 5 2 5 4 2 6 2 6 5 5 6 2 4 4 6 5 4 +7 1 7 6 6 7 1 2 4 7 6 4 8 4 8 7 7 8 4 4 4 8 7 4 0 9 0 8 8 0 9 5 6 0 8 6 0 6 0 0 +0 0 6 6 6 0 0 6 0 6 0 6 0 0 7 0 7 0 0 7 0 0 7 0 7 0 0 7 0 0 8 0 8 0 0 8 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 10 0 10 0 0 10 0 0 11 0 11 10 0 11 0 0 11 0 11 11 0 11 10 0 11 +0 11 11 0 11 11 0 11 0 11 11 0 11 11 0 11 0 11 11 0 11 11 0 12 0 11 11 0 12 11 10 0 10 12 12 10 0 11 11 0 +11 0 0 11 13 14 0 15 16 17 15 18 3 3 0 15 19 15 3 3 15 19 19 19 15 19 19 15 3 15 15 19 15 3 3 15 15 15 19 15 +19 15 15 3 15 19 19 19 15 3 19 19 15 19 15 15 19 15 15 15 19 15 15 19 3 19 19 15 19 3 3 15 19 15 15 15 15 15 19 15 +15 15 15 19 15 15 19 3 15 3 15 15 3 15 15 19 3 15 19 3 15 3 3 15 3 3 15 15 15 15 3 3 15 15 15 15 15 19 7 3 +7 15 15 7 3 3 15 7 7 15 8 15 8 7 7 8 15 15 15 8 19 19 7 19 8 8 19 7 7 8 19 0 8 19 8 19 19 19 19 8 +0 0 19 19 0 19 0 19 0 19 19 0 0 0 19 19 0 0 19 19 0 19 0 0 19 0 0 19 0 19 0 0 19 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 20 21 4 1 16 4 1 15 3 3 15 0 1 0 4 15 0 1 1 3 15 0 0 19 15 19 15 19 19 15 15 19 19 19 19 19 19 19 15 +19 19 19 19 19 19 19 15 19 19 15 19 15 15 19 19 19 0 15 0 19 19 0 15 15 19 0 19 19 19 19 0 19 19 19 19 0 19 0 19 +19 19 19 15 19 19 19 19 19 19 19 19 15 19 19 15 19 19 15 19 15 19 3 15 19 19 19 15 19 19 19 3 19 15 19 19 3 3 15 19 +19 8 19 8 19 7 8 19 19 19 8 0 19 0 7 0 8 8 0 7 7 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 19 0 19 0 0 19 19 0 0 0 19 19 0 0 0 19 0 19 0 0 19 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 22 23 4 1 16 24 1 25 +2 1 18 19 26 19 4 4 19 26 26 1 15 3 1 0 1 0 19 19 0 1 4 4 3 15 0 15 19 15 3 3 15 19 19 19 15 3 19 15 +15 15 15 15 15 15 15 15 3 15 15 15 3 15 15 15 15 3 3 3 15 15 3 15 3 15 15 15 15 15 15 15 3 15 15 3 3 3 15 4 +3 15 15 15 3 15 15 3 3 3 3 15 4 3 15 15 15 15 3 3 15 15 15 15 3 15 15 7 4 7 15 15 7 4 4 3 6 7 15 8 +15 8 7 7 8 15 15 15 6 8 15 0 6 0 8 8 0 6 6 7 0 0 8 0 8 0 0 0 0 8 8 8 19 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 20 21 4 1 16 4 1 15 4 +3 15 19 1 19 4 15 19 1 1 3 19 15 15 3 15 19 3 15 3 3 19 19 0 19 0 3 19 15 19 19 3 3 19 19 0 19 19 19 19 +15 19 19 19 19 19 19 0 15 0 19 19 0 15 15 19 0 19 19 19 19 0 19 19 19 19 0 19 0 19 19 19 19 15 19 19 19 19 19 19 +19 19 15 19 19 15 19 19 15 19 15 19 3 15 19 19 19 15 19 19 19 3 19 15 19 19 3 3 15 19 19 8 19 8 19 7 8 19 19 19 +7 0 19 0 7 0 8 8 0 7 7 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 19 0 19 0 0 19 19 0 0 0 19 19 0 0 0 19 0 19 0 0 19 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 20 21 4 1 16 4 1 15 4 3 15 19 1 19 4 15 19 1 +1 3 19 15 15 3 15 19 3 15 3 3 19 19 0 19 19 3 19 15 19 19 3 3 19 19 19 0 19 0 19 19 0 19 19 19 19 0 0 19 +0 19 19 0 19 19 19 0 19 19 19 19 0 19 19 19 19 0 19 0 19 19 19 19 15 19 19 19 19 19 19 19 19 15 19 19 15 19 19 15 +19 15 19 3 15 19 19 19 15 19 19 19 3 19 15 19 19 3 3 15 19 19 8 19 8 19 7 8 19 19 19 7 0 19 0 7 0 8 8 0 +7 7 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 19 0 19 0 0 19 19 0 +0 0 19 19 0 0 0 19 0 19 0 0 19 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 20 21 4 1 16 4 1 3 4 3 15 19 1 19 4 15 19 1 1 3 19 15 15 3 15 19 3 +15 3 3 19 15 0 19 19 3 19 15 19 19 3 3 19 19 19 19 19 19 19 15 19 19 19 19 19 19 0 15 0 19 19 0 15 15 19 0 0 +19 0 19 0 19 19 0 0 0 19 0 19 19 19 19 15 19 19 19 19 19 19 19 19 15 19 19 15 19 19 15 19 15 19 3 15 19 19 19 15 +19 19 19 3 19 15 19 19 3 3 15 19 19 8 19 8 19 7 8 19 19 19 7 0 19 0 7 0 8 8 0 7 7 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 19 +0 19 0 0 19 19 0 0 0 19 19 0 0 0 19 0 19 0 0 19 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 20 21 4 1 16 4 1 15 3 3 15 19 1 19 4 15 19 1 1 3 0 15 15 3 15 19 3 15 3 3 19 19 0 19 19 3 +19 15 19 19 3 3 19 0 19 19 19 19 19 15 19 19 19 19 0 19 19 15 19 19 15 19 15 15 19 0 19 0 15 0 19 19 0 15 15 19 +0 0 19 19 19 19 15 19 19 19 19 19 19 19 19 15 19 19 15 0 19 15 19 15 19 3 15 19 19 19 19 19 19 19 3 19 15 19 19 3 +3 15 0 19 8 19 8 19 7 8 19 19 19 8 0 19 0 7 0 8 8 0 7 7 0 0 0 0 0 0 0 0 0 0 0 0 27 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 20 21 4 1 16 +4 1 15 4 3 15 19 1 19 4 15 19 1 1 3 19 15 15 3 15 19 3 15 3 3 19 15 0 19 19 3 19 15 19 19 3 3 19 19 19 +19 19 19 19 15 19 19 19 19 19 19 19 15 19 19 15 19 15 15 19 19 19 0 15 0 19 19 0 15 15 19 0 19 0 19 0 0 0 0 19 +19 0 19 19 0 19 19 19 19 19 19 19 15 19 15 19 3 15 19 19 19 15 19 19 19 3 19 15 19 19 3 3 15 19 19 8 19 8 19 7 +8 19 19 19 7 0 19 0 7 0 8 8 0 7 7 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 19 0 19 +0 0 19 19 0 0 0 19 19 0 0 0 19 0 19 0 0 19 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 16 19 4 1 16 2 1 3 4 19 15 19 1 19 +4 15 19 1 15 19 19 0 15 19 15 19 19 15 19 19 15 0 0 19 15 19 15 19 19 15 19 19 19 19 19 19 19 19 19 19 19 19 19 19 +0 19 19 19 19 19 19 19 19 19 19 0 0 19 0 19 19 0 19 19 0 0 0 19 0 19 0 0 19 0 0 19 19 0 0 19 0 19 19 0 +19 19 19 19 0 15 19 15 19 19 15 19 19 15 19 0 19 15 19 15 19 19 15 19 19 19 0 8 19 8 19 19 8 19 19 8 0 0 0 8 +0 8 8 0 8 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 20 21 4 1 16 4 1 15 4 3 15 19 1 19 4 15 19 1 1 3 19 15 15 3 +15 19 3 15 3 3 19 15 0 19 19 3 19 15 19 19 3 3 19 19 19 19 19 19 19 15 19 19 19 19 19 19 19 15 19 19 15 19 15 15 +19 19 19 0 15 0 19 19 0 15 15 19 0 19 19 19 19 0 19 19 19 19 0 19 0 19 19 19 19 15 19 19 19 19 19 19 19 0 15 0 +19 15 15 19 0 19 15 19 15 19 19 15 15 15 19 19 8 19 8 19 7 8 19 19 19 7 0 19 0 7 0 8 8 0 7 7 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 19 0 19 0 0 19 19 0 0 0 19 19 0 0 +0 19 0 19 0 0 19 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 22 14 4 1 16 17 1 18 15 28 3 29 3 4 4 3 29 29 4 3 2 4 15 4 15 3 3 15 4 4 3 15 19 +3 15 2 15 15 19 15 2 2 15 15 15 19 15 19 15 15 3 15 19 19 19 15 3 19 19 15 19 15 15 19 15 15 15 19 15 15 19 3 19 +19 15 19 3 3 15 19 15 15 15 15 15 19 15 15 15 15 19 15 15 19 19 15 19 15 15 19 15 15 19 19 15 19 19 15 19 19 15 19 19 +15 0 15 0 19 19 0 15 15 15 7 7 0 8 19 8 7 7 8 19 19 19 0 19 0 7 0 8 8 0 7 7 8 0 0 8 0 8 0 0 +0 0 8 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 19 0 19 0 0 19 19 0 19 0 19 19 0 19 19 0 0 +0 19 19 0 0 19 19 0 19 0 0 19 0 0 19 0 19 0 0 19 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 20 21 4 1 16 4 1 15 3 3 15 19 1 19 4 15 19 1 1 3 19 15 15 3 15 19 3 15 3 3 19 15 0 19 19 3 +19 15 19 19 3 3 19 19 19 19 19 19 19 15 19 19 19 19 19 19 19 15 19 19 15 19 15 15 19 19 19 0 15 0 19 19 0 15 15 19 +0 19 19 19 19 0 19 19 19 19 0 19 0 19 19 19 19 15 19 19 19 19 19 19 19 19 15 19 19 15 19 19 15 19 15 19 3 15 19 19 +19 19 19 19 0 3 0 15 19 0 3 3 15 8 0 0 0 8 0 8 8 0 8 8 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 19 0 19 0 0 19 19 0 0 0 +19 19 0 0 0 19 0 19 0 0 19 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 20 14 4 1 16 +17 1 18 5 30 3 29 3 4 4 3 29 29 4 6 2 4 15 4 15 3 3 15 4 4 3 15 19 3 15 2 15 15 19 15 2 2 15 15 15 +0 15 19 15 15 3 15 19 19 19 15 3 19 19 15 19 15 15 19 15 15 15 19 15 15 19 3 19 19 15 19 3 3 15 19 15 15 15 15 15 +19 15 15 15 15 19 19 19 19 3 15 3 15 15 3 15 15 19 3 15 19 3 15 3 3 15 3 3 19 15 15 15 3 3 15 15 15 15 19 19 +19 3 19 15 15 19 3 3 15 8 19 15 0 15 0 19 19 0 15 15 15 0 0 0 0 0 0 0 0 0 0 0 0 31 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 20 21 4 1 16 4 1 15 +3 3 15 19 1 19 4 15 19 1 1 3 0 15 15 3 15 19 3 15 3 3 19 19 0 19 19 3 19 15 19 19 3 3 19 0 19 19 19 19 +19 15 19 19 19 19 0 19 19 15 19 19 15 19 15 15 19 0 19 0 15 0 19 19 0 15 15 19 0 19 19 19 19 0 19 19 19 19 0 0 +0 19 19 19 19 15 19 19 19 19 19 19 19 19 15 19 19 15 0 19 15 19 15 19 3 15 19 19 19 19 19 19 19 3 19 15 19 19 3 3 +15 0 19 8 19 8 19 7 8 19 19 19 8 0 19 0 7 0 8 8 0 7 7 0 27 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 16 19 0 15 16 4 15 4 15 4 19 0 0 3 0 4 19 +0 19 0 19 19 0 0 0 0 19 0 19 0 15 0 0 0 19 19 15 19 19 19 19 19 19 0 0 0 0 19 0 19 0 19 19 0 0 0 0 +19 0 19 0 19 19 0 0 0 0 19 0 19 0 0 0 0 0 0 0 0 0 0 0 19 19 0 0 0 0 19 0 19 0 19 19 0 0 19 0 +19 19 19 0 0 0 0 19 0 19 0 15 19 0 0 15 0 15 0 0 0 0 19 19 0 0 0 0 19 0 19 0 8 0 0 0 0 0 8 8 +0 8 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 16 32 4 1 16 4 1 15 4 +4 15 19 15 19 4 15 19 1 1 4 19 19 3 15 3 15 3 15 4 19 15 0 19 19 19 19 15 19 19 3 15 19 19 19 19 19 19 19 15 +19 19 19 19 19 19 19 19 19 15 19 15 19 19 19 19 0 19 0 19 0 15 19 0 0 19 19 19 19 19 19 19 0 19 19 0 19 19 19 15 +19 19 19 19 19 19 19 15 19 19 15 19 19 19 15 19 15 3 15 19 19 15 15 19 19 15 19 15 19 19 3 15 15 19 19 19 8 19 8 7 +8 19 19 8 0 19 0 7 0 8 8 0 7 8 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 16 32 4 1 16 4 1 15 4 4 15 19 19 19 4 15 19 1 1 3 19 19 15 15 15 15 3 15 3 19 15 0 19 19 19 +19 15 19 19 3 15 19 19 19 19 19 19 19 15 19 19 19 19 19 19 19 19 19 15 19 15 19 19 19 19 0 19 0 19 0 15 19 0 0 19 +19 19 19 19 19 19 0 19 19 0 19 19 19 15 19 19 19 19 19 19 19 15 19 19 15 19 19 19 15 19 15 3 15 19 19 15 15 19 19 15 +19 15 19 19 3 15 15 19 19 19 8 19 8 7 8 19 19 8 0 19 0 7 0 8 8 0 7 8 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 16 32 4 1 16 4 1 15 4 4 15 19 19 19 4 15 19 1 1 3 19 +19 15 15 15 15 3 15 3 19 15 0 19 19 19 19 15 19 19 3 15 19 19 19 19 19 19 19 15 19 19 19 19 19 19 19 19 19 15 19 15 +19 19 19 19 0 19 0 19 0 15 19 0 0 19 19 19 19 19 19 19 0 19 19 0 19 19 19 15 19 19 19 19 19 19 19 15 19 19 15 19 +19 19 15 19 15 3 15 19 19 15 15 19 19 15 19 15 19 19 3 15 15 19 19 19 8 19 8 7 8 19 19 8 0 19 0 7 0 8 8 0 +7 8 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 16 32 4 1 16 4 1 +15 4 4 15 19 19 19 4 15 19 1 1 3 19 19 15 15 15 15 3 15 3 19 15 0 19 19 19 19 15 19 19 3 15 19 19 19 19 19 19 +19 15 19 19 19 19 19 19 19 19 19 15 19 15 19 19 19 19 0 19 0 19 0 15 19 0 0 19 19 19 19 19 19 19 0 19 19 0 19 19 +19 15 19 19 19 19 19 19 19 15 19 19 15 19 19 19 15 19 15 3 15 19 19 15 15 19 19 15 19 15 19 19 3 15 15 19 19 19 8 19 +8 7 8 19 19 8 0 19 0 7 0 8 8 0 7 8 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 16 32 4 1 16 4 1 15 4 4 15 19 19 19 4 15 19 1 1 3 19 19 15 15 15 15 3 15 3 19 15 0 19 +19 19 19 15 19 19 3 15 19 19 19 19 19 19 19 15 19 19 19 19 19 19 19 19 19 15 19 15 19 19 19 19 0 19 0 19 0 15 19 0 +0 19 19 19 19 19 19 19 0 19 19 0 19 19 19 15 19 19 19 19 19 19 19 15 19 19 15 19 19 19 15 19 15 3 15 19 19 15 15 19 +19 15 19 15 19 19 3 15 15 19 19 19 8 19 8 7 8 19 19 8 0 19 0 7 0 8 8 0 7 8 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 16 32 4 1 16 4 1 15 4 4 15 19 15 19 4 15 19 1 1 +3 19 19 15 15 15 15 3 15 3 19 15 0 19 19 19 19 15 19 19 3 15 19 19 19 19 19 19 19 15 19 19 19 19 19 19 19 19 19 15 +19 15 19 19 19 19 0 19 0 19 0 15 19 0 0 19 19 19 19 19 19 19 0 19 19 0 19 19 19 15 19 19 19 19 19 19 19 15 19 19 +15 19 19 19 15 19 15 3 15 19 19 15 15 19 19 15 19 15 19 19 3 15 15 19 19 19 8 19 8 7 8 19 19 8 0 19 0 7 0 8 +8 0 7 8 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 16 32 4 1 16 +4 1 15 4 4 15 19 19 19 4 15 19 1 1 3 19 19 15 15 3 15 3 15 3 19 15 0 19 19 19 19 15 19 19 3 15 19 19 19 19 +19 19 19 15 19 19 19 19 19 19 19 19 19 15 19 15 19 19 19 19 0 19 0 19 0 15 19 0 0 19 19 19 19 19 19 19 0 19 19 0 +19 19 19 15 19 19 19 19 19 19 19 15 19 19 15 19 19 19 15 19 15 3 15 19 19 15 15 19 19 15 19 15 19 19 3 15 15 19 19 19 +8 19 8 7 8 19 19 8 0 19 0 7 0 8 8 0 7 8 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 16 32 4 1 16 4 1 15 4 4 15 19 19 19 4 15 19 1 1 3 19 19 15 15 15 15 3 15 3 19 15 +0 19 19 15 19 15 19 19 3 15 19 19 19 19 19 19 19 15 19 19 19 19 19 19 19 19 19 15 19 15 19 19 19 19 0 19 0 19 0 15 +19 0 0 19 19 19 19 19 19 19 0 19 19 0 19 19 19 15 19 19 19 19 19 19 19 15 19 19 15 19 19 19 15 19 15 3 15 19 19 15 +15 19 19 15 19 15 19 19 3 15 15 19 19 19 8 19 8 7 8 19 19 8 0 19 0 7 0 8 8 0 7 8 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 16 32 4 1 16 4 1 15 4 4 15 19 19 19 4 15 19 +1 1 3 19 19 15 15 15 15 3 15 3 19 15 0 19 19 19 19 15 19 19 3 15 19 19 19 19 19 19 19 15 19 19 19 19 19 19 19 19 +19 15 19 15 19 19 19 19 0 19 0 19 0 15 19 0 0 19 19 19 19 19 19 19 0 19 19 0 19 19 19 15 19 19 19 19 19 19 19 15 +19 19 15 19 19 19 15 19 15 3 15 19 19 15 15 19 19 15 19 15 19 19 3 15 15 19 19 15 8 15 8 7 8 15 19 8 0 19 0 7 +0 8 8 0 7 8 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 16 32 4 +1 16 4 1 15 4 4 15 19 19 19 4 15 19 1 1 3 19 19 15 15 15 15 3 15 3 19 15 0 19 19 19 19 15 19 19 3 15 19 19 +19 19 19 19 19 15 19 19 19 19 19 19 19 15 19 15 19 15 19 19 19 19 0 19 0 19 0 15 19 0 0 19 19 19 19 19 19 19 0 19 +19 0 19 19 19 15 19 19 19 19 19 19 19 15 19 19 15 19 19 19 15 19 15 3 15 19 19 15 15 19 19 15 19 15 19 19 3 15 15 19 +19 19 8 19 8 7 8 19 19 8 0 19 0 7 0 8 8 0 7 8 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 16 32 4 1 16 4 1 15 4 4 15 19 19 19 4 15 19 1 1 3 19 19 15 15 15 15 3 15 3 +19 15 0 19 19 19 19 15 19 19 3 15 19 19 19 19 19 19 19 15 19 19 19 19 19 19 19 19 19 15 19 15 19 19 19 19 0 19 0 19 +0 15 19 0 0 19 19 19 19 19 19 19 0 19 19 0 19 19 19 15 19 19 19 19 19 19 19 15 19 19 15 19 19 19 15 19 15 3 15 19 +19 15 15 19 19 15 19 15 19 19 3 15 15 19 19 19 8 19 8 7 8 19 19 8 0 19 0 7 0 8 8 0 7 8 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 16 21 4 1 16 33 1 32 4 3 32 19 34 19 4 +15 19 34 1 15 19 19 15 15 3 15 19 19 15 3 19 19 15 0 19 19 3 19 15 19 19 3 15 19 19 19 19 19 19 19 19 19 19 19 19 +19 19 19 19 19 15 19 19 19 19 15 19 19 19 19 19 0 15 0 19 19 0 15 19 19 0 0 19 19 19 19 0 0 19 19 0 0 19 19 0 +19 19 19 19 19 19 19 19 19 19 19 19 19 15 19 19 15 19 19 19 15 19 15 19 19 15 19 19 19 15 15 19 19 3 19 15 19 19 3 15 +19 19 19 19 8 19 8 19 19 8 19 19 19 8 0 19 0 7 0 8 8 0 7 8 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 16 35 4 1 16 36 1 30 4 3 30 19 37 19 4 15 19 37 4 15 19 19 15 15 +3 15 19 19 15 3 19 19 15 0 19 19 3 19 15 19 19 3 15 19 19 19 19 19 19 19 19 19 19 19 19 19 19 19 19 19 15 19 19 19 +19 15 19 19 19 19 19 0 15 0 19 19 0 15 19 19 0 0 19 19 19 19 0 0 19 19 0 0 19 19 0 19 19 19 19 19 19 19 19 19 +19 19 19 19 15 19 19 15 19 19 19 15 19 15 19 19 15 19 19 19 15 15 19 19 3 19 15 19 19 3 15 19 19 19 19 8 19 8 19 19 +8 19 19 19 8 0 19 0 7 0 8 8 0 7 8 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 16 32 4 1 16 4 1 15 4 4 15 19 19 19 4 15 19 1 1 3 19 19 +15 15 15 15 3 15 3 19 15 0 19 19 19 19 15 19 19 3 15 19 19 19 19 19 19 19 15 19 19 19 19 19 19 19 19 19 15 19 15 19 +19 19 19 0 19 0 19 0 15 19 0 0 19 19 19 19 19 19 19 0 19 19 0 19 19 19 15 19 19 19 19 19 19 19 15 19 19 15 19 19 +19 15 19 15 3 15 19 19 15 15 19 19 15 19 15 19 19 3 15 15 19 19 19 8 19 8 7 8 19 19 8 0 19 0 7 0 8 8 0 7 +8 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 3 4 3 1 +1 3 4 4 4 3 1 4 3 4 3 3 3 3 4 4 4 3 3 4 4 1 4 3 3 4 1 1 1 2 3 2 4 2 4 2 2 4 2 2 +2 4 3 2 2 2 2 4 4 2 2 3 3 4 4 3 4 4 4 2 2 4 3 3 3 4 4 3 4 3 4 4 4 4 3 3 3 4 2 3 +5 4 5 4 4 5 4 4 4 5 4 4 5 2 5 5 2 5 4 2 6 4 6 5 5 6 2 4 4 6 5 4 7 2 7 6 6 7 1 2 +4 7 6 4 8 4 8 7 7 8 4 4 4 8 7 4 0 9 0 8 8 0 5 5 6 0 8 6 0 6 0 0 0 0 6 6 6 0 0 6 +0 6 0 7 0 0 7 0 7 0 0 7 0 0 7 0 7 0 0 7 0 0 8 0 8 0 0 8 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 10 0 10 0 0 10 0 0 11 0 11 10 0 11 0 0 11 0 11 11 0 11 10 0 11 0 11 11 0 11 11 0 11 +0 11 11 0 11 11 0 11 0 11 11 0 11 11 0 12 0 11 11 0 12 11 10 0 10 12 12 10 0 11 11 0 11 0 0 11 13 14 0 15 +16 17 15 35 3 3 0 15 0 15 3 15 15 19 19 19 15 19 19 15 19 15 15 19 15 3 3 19 15 15 19 15 19 15 15 15 15 19 19 19 +15 3 19 19 19 19 15 19 19 15 15 15 19 15 15 19 15 19 19 19 19 3 3 15 19 15 15 15 15 15 19 15 15 15 15 19 15 15 19 3 +19 3 15 19 3 15 15 19 3 15 19 3 19 3 3 19 3 3 15 15 15 15 3 15 15 15 15 19 15 19 7 19 7 15 15 7 3 3 15 7 +7 15 8 15 8 7 8 8 15 15 19 8 19 19 19 19 8 0 19 7 7 8 19 0 8 19 8 19 19 19 19 8 0 0 19 19 0 19 0 19 +0 19 19 0 0 0 19 19 0 0 19 19 0 19 0 0 19 0 0 19 0 19 0 0 19 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 20 21 4 1 16 4 1 +19 3 3 15 0 15 0 4 19 0 1 1 3 15 0 0 19 0 19 15 19 19 15 15 0 19 19 19 19 19 19 19 19 19 19 19 19 19 19 19 +19 19 19 19 15 19 19 19 19 0 19 0 19 0 0 15 19 19 0 19 19 19 19 0 19 19 19 0 0 19 0 19 0 19 19 19 19 19 19 19 +19 19 19 19 19 19 19 19 19 19 15 19 15 19 15 15 19 19 19 15 19 19 19 19 19 15 19 19 3 15 15 19 19 8 19 8 19 8 8 19 +19 19 8 0 19 0 19 0 8 0 0 7 8 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 19 0 19 0 0 +19 19 0 0 0 19 19 0 0 0 19 0 19 0 0 19 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 22 23 4 1 16 24 1 25 2 1 18 19 26 19 4 3 +19 26 29 1 15 3 1 0 1 0 19 0 0 1 4 3 3 15 0 15 19 15 3 15 15 19 19 19 15 3 19 15 15 15 15 19 15 15 15 15 +3 15 15 15 3 15 15 19 15 3 3 3 15 15 3 15 15 15 15 15 15 15 15 15 3 15 15 3 15 3 15 3 19 15 15 15 3 15 15 3 +15 3 3 15 4 19 15 15 15 15 3 15 15 15 15 15 3 15 15 7 4 7 15 15 7 4 4 15 6 7 15 8 15 8 7 8 8 15 15 15 +6 8 15 0 6 0 8 0 0 6 6 8 0 0 8 0 8 0 0 0 0 8 8 0 19 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 20 21 4 1 16 4 1 19 4 3 15 19 15 19 4 19 19 +1 1 3 19 15 15 15 15 19 15 15 3 3 19 19 0 19 0 19 19 15 19 19 3 15 0 19 0 19 0 19 19 19 19 19 19 19 19 19 0 +19 0 19 0 0 15 19 19 0 19 19 19 19 0 19 19 19 0 0 19 0 19 0 19 19 19 19 19 19 19 19 19 19 19 19 19 19 19 19 19 +15 19 15 19 15 15 19 19 19 15 19 19 19 19 19 15 19 19 3 15 15 19 19 8 19 8 19 8 8 19 19 19 7 0 19 0 19 0 8 0 +0 7 8 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 19 0 19 0 0 19 19 0 0 0 19 19 0 0 0 19 0 19 0 0 19 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 20 21 4 1 16 4 1 19 4 3 15 19 15 19 4 19 19 1 1 3 19 15 15 15 15 19 +15 15 3 3 19 19 0 19 19 19 19 15 19 19 3 15 0 19 19 0 19 0 19 0 0 19 19 19 19 0 0 0 0 19 0 0 19 19 19 0 +19 19 19 19 0 19 19 19 0 0 19 0 19 0 19 19 19 19 19 19 19 19 19 19 19 19 19 19 19 19 19 15 19 15 19 15 15 19 19 19 +15 19 19 19 19 19 15 19 19 3 15 15 19 19 8 19 8 19 8 8 19 19 19 7 0 19 0 19 0 8 0 0 7 8 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 19 0 19 0 0 19 19 0 0 0 19 19 0 0 0 19 +0 19 0 0 19 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 20 21 4 1 16 4 1 19 4 3 15 19 15 19 4 19 19 1 1 3 19 15 15 15 15 19 15 15 3 3 19 15 0 19 19 +19 19 15 19 19 3 15 0 19 19 19 19 19 19 19 19 19 19 19 19 19 0 19 0 19 0 0 15 19 19 0 0 19 0 19 0 19 19 0 0 +0 19 0 19 0 19 19 19 19 19 19 19 19 19 19 19 19 19 19 19 19 19 15 19 15 19 15 15 19 19 19 15 19 19 19 19 19 15 19 19 +3 15 15 19 19 8 19 8 19 8 8 19 19 19 7 0 19 0 19 0 8 0 0 7 8 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 19 0 19 0 0 19 19 0 0 +0 19 19 0 0 0 19 0 19 0 0 19 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 20 21 4 1 +16 4 1 19 3 3 15 19 15 19 4 19 19 1 1 3 0 15 15 15 15 19 15 15 3 3 19 19 0 19 19 19 19 15 19 19 3 15 0 0 +19 19 19 19 19 19 19 19 19 19 0 19 19 19 19 19 19 19 15 19 19 0 19 0 19 0 19 0 0 15 19 19 0 0 19 0 19 19 19 19 +19 19 19 19 19 19 19 19 19 19 19 0 19 15 19 15 19 15 15 19 19 19 19 19 19 19 19 19 15 19 19 3 15 15 0 19 8 19 8 19 +8 8 19 19 19 8 0 19 0 19 0 8 0 0 7 8 0 0 0 0 0 0 0 0 0 0 0 0 27 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 20 21 4 1 16 4 1 19 4 3 15 19 15 +19 4 19 19 1 1 3 19 15 15 15 15 19 15 15 3 3 19 15 0 19 19 19 19 15 19 19 3 15 0 19 19 19 19 19 19 19 19 19 19 +19 19 19 19 19 19 19 19 19 15 19 19 19 19 0 19 0 19 0 0 15 19 19 0 19 0 19 0 0 0 0 19 0 0 19 19 0 19 0 19 +19 0 19 19 15 19 15 19 15 15 19 19 19 15 19 19 19 19 19 15 19 19 3 15 15 19 19 8 19 8 19 8 8 19 19 19 7 0 19 0 +19 0 8 0 0 7 8 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 19 0 19 0 0 19 19 0 0 0 19 +19 0 0 0 19 0 19 0 0 19 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 16 19 4 1 16 2 1 19 4 19 15 19 15 19 4 19 19 1 15 19 19 0 +15 0 15 19 0 15 19 0 15 0 0 19 0 19 15 19 19 15 0 19 19 19 19 19 19 19 0 19 19 0 19 19 0 19 0 19 19 0 19 19 +0 19 19 0 0 0 0 19 0 0 19 0 0 0 0 19 0 19 0 0 19 0 0 19 19 0 0 0 0 19 0 0 19 0 19 19 0 15 0 15 +19 0 15 19 0 15 19 0 19 0 19 15 19 19 15 19 19 19 0 8 0 8 19 0 8 19 0 8 0 0 0 0 0 8 0 0 8 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 20 21 4 1 16 4 1 19 4 3 15 19 15 19 4 19 19 1 1 3 19 15 15 15 15 19 15 15 3 3 19 15 +0 19 19 19 19 15 19 19 3 15 0 19 19 19 19 19 19 19 19 19 19 19 19 19 19 19 19 19 19 19 15 19 19 19 19 0 19 0 19 0 +0 15 19 19 0 19 19 19 19 0 19 19 19 0 0 19 0 19 0 19 19 19 19 19 19 19 19 19 19 0 19 0 19 19 15 19 0 19 0 19 +15 19 19 15 15 15 19 19 8 19 8 19 8 8 19 19 19 7 0 19 0 19 0 8 0 0 7 8 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 19 0 19 0 0 19 19 0 0 0 19 19 0 0 0 19 0 19 0 0 19 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 22 +14 4 1 16 17 1 38 15 28 3 28 3 4 3 15 29 39 4 3 2 4 15 4 15 3 15 15 4 3 3 15 19 3 15 3 15 15 19 15 2 +2 19 15 15 19 15 19 15 15 15 15 19 19 19 15 3 19 19 19 19 15 19 19 15 15 15 19 15 15 19 15 19 19 19 19 3 15 15 19 15 +15 15 15 15 19 15 15 15 19 19 15 15 19 19 19 19 15 19 19 15 19 19 19 15 19 19 19 19 19 19 19 19 15 0 15 0 19 0 0 15 +15 19 7 7 0 8 0 8 7 8 8 19 19 19 0 19 0 19 0 8 0 0 7 7 8 0 0 8 0 8 0 0 0 0 8 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 19 0 19 0 0 19 19 0 19 0 19 19 0 19 19 0 0 0 19 19 0 0 19 19 0 +19 0 0 19 0 0 19 0 19 0 0 19 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 20 21 4 1 +16 4 1 19 3 3 15 19 15 19 4 19 19 1 1 3 19 15 15 15 15 19 15 15 3 3 19 15 0 19 19 19 19 15 19 19 3 15 0 19 +19 19 19 19 19 19 19 19 19 19 19 19 19 19 19 19 19 19 15 19 19 19 19 0 19 0 19 0 0 15 19 19 0 19 19 19 19 0 19 19 +19 0 0 19 0 19 0 19 19 19 19 19 19 19 19 19 19 19 19 19 19 19 19 19 15 19 15 19 15 15 19 19 19 19 19 19 0 19 0 15 +19 0 3 15 15 8 0 0 0 0 0 8 0 0 8 8 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 19 0 19 0 0 19 19 0 0 0 19 19 0 0 0 19 0 19 +0 0 19 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 20 14 4 1 16 17 1 38 5 30 3 28 3 +4 3 15 29 39 4 6 2 4 15 4 15 3 15 15 4 3 3 15 19 3 15 3 15 15 19 15 2 2 19 15 15 0 15 19 15 15 15 15 19 +19 19 15 3 19 19 19 19 15 19 19 15 15 15 19 15 15 19 15 19 19 19 19 3 15 15 19 15 15 15 15 15 19 15 15 15 19 19 19 19 +19 3 19 3 15 19 3 15 19 19 3 15 19 3 19 3 3 19 3 3 19 15 15 15 3 15 15 15 15 19 19 19 19 19 19 15 15 19 3 3 +15 8 19 15 0 15 0 19 0 0 15 15 19 0 0 0 0 0 0 0 0 0 0 0 0 31 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 20 21 4 1 16 4 1 19 3 3 15 19 15 19 4 19 +19 1 1 3 0 15 15 15 15 19 15 15 3 3 19 19 0 19 19 19 19 15 19 19 3 15 0 0 19 19 19 19 19 19 19 19 19 19 0 19 +19 19 19 19 19 19 15 19 19 0 19 0 19 0 19 0 0 15 19 19 0 19 19 19 19 0 19 19 19 0 0 0 0 19 0 19 19 19 19 19 +19 19 19 19 19 19 19 19 19 19 0 19 15 19 15 19 15 15 19 19 19 19 19 19 19 19 19 15 19 19 3 15 15 0 19 8 19 8 19 8 +8 19 19 19 8 0 19 0 19 0 8 0 0 7 8 0 27 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 16 19 0 15 16 4 15 4 15 4 19 0 0 4 0 4 0 0 19 0 19 0 0 0 19 +0 19 0 19 0 15 0 0 0 15 19 15 19 19 19 19 19 19 0 0 19 0 19 0 19 0 19 19 0 0 19 0 19 0 19 0 19 19 0 0 +19 0 19 0 19 0 0 0 0 0 0 0 0 0 0 0 19 19 0 0 19 0 19 0 19 0 19 19 0 0 19 0 19 19 19 0 0 19 0 19 +0 19 0 15 19 0 0 15 0 15 0 0 0 0 19 19 0 0 19 0 19 0 19 0 8 0 0 0 8 0 8 0 0 8 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 16 32 4 1 16 4 1 15 4 3 15 19 1 19 4 15 19 +1 1 4 19 19 3 15 4 15 3 15 4 19 15 0 19 19 3 19 15 19 19 3 15 19 19 19 19 19 19 19 15 19 19 19 19 19 19 19 15 +19 15 19 15 19 19 19 19 0 15 0 19 0 15 19 0 0 19 19 19 19 19 19 19 0 19 19 0 19 19 19 15 19 19 19 19 19 19 19 15 +19 19 15 19 19 19 15 19 15 3 15 19 19 15 15 19 19 3 19 15 19 19 3 15 19 19 19 19 8 19 8 7 8 19 19 8 0 19 0 7 +0 8 8 0 7 8 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 16 32 4 +1 16 4 1 15 4 3 15 19 1 19 4 15 19 1 1 3 19 19 15 15 3 15 3 15 3 19 15 0 19 19 3 19 15 19 19 3 15 19 19 +19 19 19 19 19 15 19 19 19 19 19 19 19 15 19 15 19 15 19 19 19 19 0 15 0 19 0 15 19 0 0 19 19 19 19 19 19 19 0 19 +19 0 19 19 19 15 19 19 19 19 19 19 19 15 19 19 15 19 19 19 15 19 15 3 15 19 19 15 15 19 19 3 19 15 19 19 3 15 19 19 +19 19 8 19 8 7 8 19 19 8 0 19 0 7 0 8 8 0 7 8 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 16 32 4 1 16 4 1 15 4 3 15 19 1 19 4 15 19 1 1 3 19 19 15 15 3 15 3 15 3 +19 15 0 19 19 3 19 15 19 19 3 15 19 19 19 19 19 19 19 15 19 19 19 19 19 19 19 15 19 15 19 15 19 19 19 19 0 15 0 19 +0 15 19 0 0 19 19 19 19 19 19 19 0 19 19 0 19 19 19 15 19 19 19 19 19 19 19 15 19 19 15 19 19 19 15 19 15 3 15 19 +19 15 15 19 19 3 19 15 19 19 3 15 19 19 19 19 8 19 8 7 8 19 19 8 0 19 0 7 0 8 8 0 7 8 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 16 32 4 1 16 4 1 15 4 3 15 19 1 19 4 +15 19 1 1 3 19 19 15 15 3 15 3 15 3 19 15 0 19 19 3 19 15 19 19 3 15 19 19 19 19 19 19 19 15 19 19 19 19 19 19 +19 15 19 15 19 15 19 19 19 19 0 15 0 19 0 15 19 0 0 19 19 19 19 19 19 19 0 19 19 0 19 19 19 15 19 19 19 19 19 19 +19 15 19 19 15 19 19 19 15 19 15 3 15 19 19 15 15 19 19 3 19 15 19 19 3 15 19 19 19 19 8 19 8 7 8 19 19 8 0 19 +0 7 0 8 8 0 7 8 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 16 +32 4 1 16 4 1 15 4 3 15 19 1 19 4 15 19 1 1 3 19 19 15 15 3 15 3 15 3 19 15 0 19 19 3 19 15 19 19 3 15 +19 19 19 19 19 19 19 15 19 19 19 19 19 19 19 15 19 15 19 15 19 19 19 19 0 15 0 19 0 15 19 0 0 19 19 19 19 19 19 19 +0 19 19 0 19 19 19 15 19 19 19 19 19 19 19 15 19 19 15 19 19 19 15 19 15 3 15 19 19 15 15 19 19 3 19 15 19 19 3 15 +19 19 19 19 8 19 8 7 8 19 19 8 0 19 0 7 0 8 8 0 7 8 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 16 32 4 1 16 4 1 15 4 3 15 19 1 19 4 15 19 1 1 3 19 19 15 15 3 15 3 +15 3 19 15 0 19 19 3 19 15 19 19 3 15 19 19 19 19 19 19 19 15 19 19 19 19 19 19 19 15 19 15 19 15 19 19 19 19 0 15 +0 19 0 15 19 0 0 19 19 19 19 19 19 19 0 19 19 0 19 19 19 15 19 19 19 19 19 19 19 15 19 19 15 19 19 19 15 19 15 3 +15 19 19 15 15 19 19 3 19 15 19 19 3 15 19 19 19 19 8 19 8 7 8 19 19 8 0 19 0 7 0 8 8 0 7 8 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 16 32 4 1 16 4 1 15 4 3 15 19 1 +19 4 15 19 1 1 3 19 19 15 15 3 15 3 15 3 19 15 0 19 19 3 19 15 19 19 3 15 19 19 19 19 19 19 19 15 19 19 19 19 +19 19 19 15 19 15 19 15 19 19 19 19 0 15 0 19 0 15 19 0 0 19 19 19 19 19 19 19 0 19 19 0 19 19 19 15 19 19 19 19 +19 19 19 15 19 19 15 19 19 19 15 19 15 3 15 19 19 15 15 19 19 3 19 15 19 19 3 15 19 19 19 19 8 19 8 7 8 19 19 8 +0 19 0 7 0 8 8 0 7 8 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 16 32 4 1 16 4 1 15 4 3 15 19 1 19 4 15 19 1 1 3 19 19 15 15 3 15 3 15 3 19 15 0 19 19 3 19 15 19 19 +3 15 19 19 19 19 19 19 19 15 19 19 19 19 19 19 19 15 19 15 19 15 19 19 19 19 0 15 0 19 0 15 19 0 0 19 19 19 19 19 +19 19 0 19 19 0 19 19 19 15 19 19 19 19 19 19 19 15 19 19 15 19 19 19 15 19 15 3 15 19 19 15 15 19 19 3 19 15 19 19 +3 15 19 19 19 19 8 19 8 7 8 19 19 8 0 19 0 7 0 8 8 0 7 8 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 16 32 4 1 16 4 1 15 4 3 15 19 1 19 4 15 19 1 1 3 19 19 15 15 3 +15 3 15 3 19 15 0 19 19 3 19 15 19 19 3 15 19 19 19 19 19 19 19 15 19 19 19 19 19 19 19 15 19 15 19 15 19 19 19 19 +0 15 0 19 0 15 19 0 0 19 19 19 19 19 19 19 0 19 19 0 19 19 19 15 19 19 19 19 19 19 19 15 19 19 15 19 19 19 15 19 +15 3 15 19 19 15 15 19 19 3 19 15 19 19 3 15 19 19 19 15 8 15 8 7 8 15 19 8 0 19 0 7 0 8 8 0 7 8 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 16 32 4 1 16 4 1 15 4 3 15 +19 1 19 4 15 19 1 1 3 19 19 15 15 3 15 3 15 3 19 15 0 19 19 3 19 15 19 19 3 15 19 19 19 19 19 19 19 15 19 19 +19 19 19 19 19 15 19 15 19 15 19 19 19 19 0 15 0 19 0 15 19 0 0 19 19 19 19 19 19 19 0 19 19 0 19 19 19 15 19 19 +19 19 19 19 19 15 19 19 15 19 19 19 15 19 15 3 15 19 19 15 15 19 19 3 19 15 19 19 3 15 19 19 19 19 8 19 8 7 8 19 +19 8 0 19 0 7 0 8 8 0 7 8 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 16 32 4 1 16 4 1 15 4 3 15 19 1 19 4 15 19 1 1 3 19 19 15 15 3 15 3 15 3 19 15 0 19 19 3 19 15 +19 19 3 15 19 19 19 19 19 19 19 15 19 19 19 19 19 19 19 15 19 15 19 15 19 19 19 19 0 15 0 19 0 15 19 0 0 19 19 19 +19 19 19 19 0 19 19 0 19 19 19 15 19 19 19 19 19 19 19 15 19 19 15 19 19 19 15 19 15 3 15 19 19 15 15 19 19 3 19 15 +19 19 3 15 19 19 19 19 8 19 8 7 8 19 19 8 0 19 0 7 0 8 8 0 7 8 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 16 21 4 1 16 33 1 10 4 3 32 19 32 19 4 15 19 34 1 15 19 19 15 +15 15 15 19 19 15 3 19 19 15 0 19 19 19 19 15 19 19 3 15 0 19 19 19 19 19 19 19 19 19 19 19 19 19 19 19 19 19 19 19 +19 19 15 19 19 19 19 19 0 19 0 19 19 0 15 19 19 0 0 19 19 19 19 0 0 19 19 0 0 19 19 0 19 0 19 19 19 19 19 19 +19 19 19 19 19 19 19 19 19 19 19 19 15 19 15 19 19 15 19 19 19 15 15 19 19 19 19 15 19 19 3 15 19 19 19 19 8 19 8 19 +19 8 19 19 19 8 0 19 0 19 0 8 8 0 7 8 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 16 35 4 1 16 36 1 30 4 3 30 19 30 19 4 15 19 37 4 15 19 19 15 15 15 15 19 19 15 3 19 19 +15 0 19 19 19 19 15 19 19 3 15 19 19 19 19 19 19 19 19 19 19 19 19 19 19 19 19 19 19 19 19 19 19 15 19 19 19 19 19 0 +19 0 19 19 0 15 19 19 0 0 19 19 19 19 0 0 19 19 0 0 19 19 0 19 0 19 19 19 19 19 19 19 19 19 19 19 19 19 19 19 +19 19 19 15 19 15 19 19 15 19 19 19 15 15 19 19 19 19 15 19 19 3 15 19 19 19 19 8 19 8 19 19 8 19 19 19 8 0 19 0 +19 0 8 8 0 7 8 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 16 32 4 1 16 4 1 15 4 3 15 19 1 19 4 15 19 1 1 3 19 19 15 15 3 15 3 15 3 19 +15 0 19 19 3 19 15 19 19 3 15 19 19 19 19 19 19 19 15 19 19 19 19 19 19 19 15 19 15 19 15 19 19 19 19 0 15 0 19 0 +15 19 0 0 19 19 19 19 19 19 19 0 19 19 0 19 19 19 15 19 19 19 19 19 19 19 15 19 19 15 19 19 19 15 19 15 3 15 19 19 +15 15 19 19 3 19 15 19 19 3 15 19 19 19 19 8 19 8 7 8 19 19 8 0 19 0 7 0 8 8 0 7 8 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 diff --git a/tests/TagLibSharp2.Tests/Image/Golden/exif-reader-probes.txt b/tests/TagLibSharp2.Tests/Image/Golden/exif-reader-probes.txt new file mode 100644 index 00000000..d8af07d4 --- /dev/null +++ b/tests/TagLibSharp2.Tests/Image/Golden/exif-reader-probes.txt @@ -0,0 +1,55 @@ +# What exiftool 13.55 shows for each generated input; regenerate with tools/exif/golden.sh. +# inputs 1692 sha256 f370d22484552afc518c1dff7397922fa882d6f09d854bb508a7d915c272f997 +@summaries +0 - +1 E010E=1 E9286=1 +2 G0001=1 +3 E9286=1 +4 E9286=2 +5 E9286=3 +6 E010E=1 +7 E9286=1 G0001=1 +@inputs +0 0 0 0 1 0 0 0 0 0 1 0 0 1 0 0 0 0 0 0 0 0 1 0 0 1 0 0 1 0 0 0 0 0 0 0 0 1 0 0 +0 0 0 0 0 0 1 0 0 0 0 0 1 0 0 1 0 0 0 0 0 0 0 0 1 0 0 1 0 0 1 0 0 0 0 0 0 0 0 1 +0 0 0 0 0 0 0 0 1 0 0 0 0 0 1 0 0 1 0 0 0 0 0 0 0 0 1 0 0 1 0 0 1 0 0 0 0 0 0 0 +0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 1 0 0 1 0 0 0 0 0 0 0 0 1 0 0 1 0 0 1 0 0 0 0 0 +0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 1 0 0 1 0 0 0 0 0 0 0 0 1 0 0 1 0 0 1 0 +0 0 0 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 1 0 0 0 0 1 1 0 1 0 0 0 0 0 0 0 0 1 0 0 1 1 +0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 1 0 0 0 0 1 1 0 1 0 0 0 0 0 0 0 0 1 0 0 +1 1 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 1 0 0 0 0 1 1 0 1 0 0 0 0 0 0 0 0 1 +0 0 1 1 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 1 0 0 0 0 1 1 0 1 0 0 0 0 0 0 0 +0 1 0 0 1 1 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 1 1 0 1 0 0 0 +0 0 0 0 0 1 0 0 1 1 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 1 0 0 0 0 2 2 0 0 0 0 2 2 0 2 +0 0 0 0 0 0 0 0 2 0 0 2 2 0 2 0 0 0 0 0 0 0 0 2 0 0 0 0 0 0 0 0 2 2 0 0 0 0 2 2 +0 2 0 0 0 0 0 0 0 0 2 0 0 2 2 0 2 0 0 0 0 0 0 0 0 2 0 0 0 0 0 0 0 0 2 2 0 0 0 0 +2 2 0 2 0 0 0 0 0 0 0 0 2 0 0 2 2 0 2 0 0 0 0 0 0 0 0 2 0 0 0 0 0 0 0 0 2 2 0 0 +0 0 2 2 0 2 0 0 0 0 0 0 0 0 2 0 0 2 2 0 2 0 0 0 0 0 0 0 0 2 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +2 2 0 0 0 0 2 2 0 2 0 0 0 0 0 0 0 0 2 0 0 2 2 0 2 0 0 0 0 0 0 0 0 2 0 0 0 0 2 0 +0 0 0 1 1 0 0 0 0 1 1 0 1 0 0 0 0 0 0 0 0 1 0 0 1 1 0 1 0 0 0 0 0 0 0 0 1 0 0 0 +0 0 0 0 0 1 1 0 0 0 0 1 1 0 1 0 0 0 0 0 0 0 0 1 0 0 1 1 0 1 0 0 0 0 0 0 0 0 1 0 +0 0 0 0 0 0 0 1 1 0 0 0 0 1 1 0 1 0 0 0 0 0 0 0 0 1 0 0 1 1 0 1 0 0 0 0 0 0 0 0 +1 0 0 0 0 0 0 0 0 1 1 0 0 0 0 1 1 0 1 0 0 0 0 0 0 0 0 1 0 0 1 1 0 1 0 0 0 0 0 0 +0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 1 1 0 1 0 0 0 0 0 0 0 0 1 0 0 1 1 0 1 0 0 +0 0 0 0 0 0 1 0 0 0 0 1 0 1 0 0 1 0 0 1 0 0 0 0 0 1 0 0 1 0 0 1 0 0 1 0 0 1 0 0 +0 0 0 1 0 0 1 0 0 1 0 0 1 0 0 1 0 0 0 0 0 1 0 0 1 0 0 1 0 0 1 0 0 1 0 0 0 0 0 1 +0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 1 0 0 1 0 0 0 0 0 1 0 0 1 0 +1 0 1 1 0 1 1 0 1 0 0 0 0 0 1 1 0 1 0 0 1 1 0 1 1 0 1 0 0 0 0 0 1 1 0 1 0 0 1 1 +0 1 1 0 1 0 0 0 0 0 1 1 0 1 0 0 1 1 0 1 1 0 1 0 0 0 0 0 1 1 0 1 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 1 1 0 1 0 0 0 0 0 1 1 0 1 0 1 0 2 2 0 2 2 0 2 0 0 +0 0 0 2 2 0 2 0 0 2 2 0 2 2 0 2 0 0 0 0 0 2 2 0 2 0 0 2 2 0 2 2 0 2 0 0 0 0 0 2 +2 0 2 0 0 2 2 0 2 2 0 2 0 0 0 0 0 2 2 0 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 2 2 0 2 2 0 2 0 0 0 0 0 2 2 0 2 0 2 0 1 1 0 1 1 0 1 0 0 0 0 0 1 1 0 1 0 0 1 1 +0 1 1 0 1 0 0 0 0 0 1 1 0 1 0 0 1 1 0 1 1 0 1 0 0 0 0 0 1 1 0 1 0 0 1 1 0 1 1 0 +1 0 0 0 0 0 1 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 1 1 0 1 0 0 0 +0 0 1 1 0 1 0 1 3 0 0 3 0 0 3 0 0 3 0 0 0 3 3 3 3 3 3 3 3 3 3 3 3 3 2 2 2 2 2 2 +2 2 2 2 2 2 2 3 4 5 3 4 5 3 4 5 3 3 3 4 3 0 0 3 0 0 3 0 0 3 0 0 0 3 3 3 3 3 3 3 +3 3 3 3 3 3 2 2 2 2 2 2 2 2 2 2 2 2 2 3 4 5 3 4 5 3 4 5 3 3 3 4 0 0 0 0 0 0 0 0 +0 0 2 3 0 0 0 0 0 0 0 3 3 3 0 0 0 0 0 3 0 3 3 0 3 3 0 3 3 0 3 3 3 3 3 3 3 3 3 3 +3 0 3 3 3 3 0 3 3 0 0 3 3 0 0 3 3 0 0 3 3 0 0 3 3 0 0 3 3 0 0 3 3 0 0 0 6 0 0 6 +0 0 6 0 0 6 0 0 6 0 0 2 6 0 2 3 3 2 3 3 3 3 3 3 7 3 2 2 2 3 3 3 0 0 3 4 3 0 3 0 +3 0 3 0 3 3 3 3 3 0 3 0 diff --git a/tests/TagLibSharp2.Tests/Image/ImageAssert.cs b/tests/TagLibSharp2.Tests/Image/ImageAssert.cs new file mode 100644 index 00000000..3e0afebe --- /dev/null +++ b/tests/TagLibSharp2.Tests/Image/ImageAssert.cs @@ -0,0 +1,46 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Buffers.Binary; +using System.Text; +using TagLibSharp2.Core; +using TagLibSharp2.Image; +using TagLibSharp2.Tests.Kit; +using static TagLibSharp2.Tests.Image.ImageTestBuilder; + +namespace TagLibSharp2.Tests.Image; + +/// Assertions on what an opened image reports. +static class ImageAssert +{ + internal static void AssertSize (byte[] data, string name, int width, int height) + { + var opened = MediaFile.ReadFromData (data, name); + Assert.IsTrue (opened.IsSuccess, opened.Error); + var image = (IMediaFile)opened.File!; + Assert.AreEqual (width, image.ImageProperties!.Value.Width); + Assert.AreEqual (height, image.ImageProperties.Value.Height); + } + + internal static void AssertImage (byte[] data, string name, MediaFormat format, int width, int height, string kind) + { + AssertOne (MediaFile.ReadFromData (data, name), format, width, height, kind); + AssertOne (MediaFile.Read (new MemoryStream (data), name), format, width, height, kind); + } + + internal static void AssertOne (MediaFileResult result, MediaFormat format, int width, int height, string kind) + { + Assert.IsTrue (result.IsSuccess, result.Error); + Assert.AreEqual (format, result.Format); + var file = (IMediaFile)result.File!; + Assert.AreEqual (MediaTypes.Image, file.MediaTypes); + Assert.IsNull (file.AudioProperties); + Assert.IsNotNull (file.ImageProperties); + Assert.AreEqual (width, file.ImageProperties.Value.Width); + Assert.AreEqual (height, file.ImageProperties.Value.Height); + Assert.AreEqual (kind, file.ImageProperties.Value.Format); + } + + internal static IMediaFile ImageOf (byte[] data, string name) => + (IMediaFile)MediaFile.ReadFromData (data, name).File!; +} diff --git a/tests/TagLibSharp2.Tests/Image/ImageClearTests.cs b/tests/TagLibSharp2.Tests/Image/ImageClearTests.cs new file mode 100644 index 00000000..e43e03f7 --- /dev/null +++ b/tests/TagLibSharp2.Tests/Image/ImageClearTests.cs @@ -0,0 +1,219 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Buffers.Binary; +using System.IO.Compression; +using System.Text; +using System.Xml.Linq; +using TagLibSharp2.Core; +using TagLibSharp2.Image; +using TagLibSharp2.Image.Exif; +using TagLibSharp2.Image.Tiff; +using TagLibSharp2.Tests.Core; +using static TagLibSharp2.Tests.Image.ImageTestBuilder; + +namespace TagLibSharp2.Tests.Image; + +/// Clear: every metadata carrier is dropped and what a decoder or colour management needs is kept, in every format. +[TestClass] +[TestCategory ("Unit")] +public class ImageClearTests +{ + [TestMethod] + public void Png_Clear_DropsUnmappedText () + { + var data = MinimalPng (Text ("Software", "camera"), PngChunk ("IDAT", [0x01])); + var file = Open (data, "photo.png"); + Assert.IsNull (file.Tag!.Title); + + file.Tag.Clear (); + var rendered = file.Render ().ToArray (); + + Assert.IsFalse (HasPngChunk (rendered, "tEXt")); + CollectionAssert.AreEqual (new byte[] { 0x01 }, PngPayload (rendered, "IDAT")); + Assert.IsNull (Open (rendered, "photo.png").Tag!.Title); + } + + [TestMethod] + public void Gif_Clear_DropsTheXmpExtension () + { + var trap = new byte[] { 0x11, 0x22 }; + var data = GifWithXmp ("hello", trap); + var file = Open (data, "anim.gif"); + Assert.AreEqual ("hello", file.Tag!.Comment); + + file.Tag.Comment = "next"; + var edited = file.Render ().ToArray (); + Assert.IsTrue (edited.AsSpan ().IndexOf ("XMP Data"u8) >= 0); + Assert.AreEqual ("next", Open (edited, "anim.gif").Tag!.Comment); + + file.Tag.Clear (); + var cleared = file.Render ().ToArray (); + Assert.IsTrue (cleared.AsSpan ().IndexOf ("XMP Data"u8) < 0); + Assert.IsNull (Open (cleared, "anim.gif").Tag!.Comment); + CollectionAssert.AreEqual (trap, GifImageSubBlock (cleared)); + } + + [TestMethod] + public void Jpeg_Clear_DropsExifXmpIptc_AndUnknownApp1 () + { + var data = JpegWithMetadata (); + var file = Open (data, "photo.jpg"); + Assert.AreEqual ("hello", file.Tag!.Comment); + + file.Tag.Clear (); + var rendered = file.Render ().ToArray (); + + Assert.IsTrue (rendered.AsSpan ().IndexOf ("Exif\0\0"u8) < 0); + Assert.IsTrue (rendered.AsSpan ().IndexOf ("http://ns.adobe.com/xap/1.0/\0"u8) < 0); + Assert.IsTrue (IndexOf (rendered, 0xFF, 0xED) < 0); + Assert.IsTrue (rendered.AsSpan ().IndexOf ("keep"u8) < 0, "rule 7: an unknown APP1 is unmapped metadata"); + Assert.IsNull (Open (rendered, "photo.jpg").Tag!.Comment); + Assert.AreEqual (8, Open (rendered, "photo.jpg").ImageProperties!.Value.Width); + } + + static byte[] GifWithXmp (string comment, byte[] trap) + { + var gif = GifWithComment (comment, trap); + var trailer = gif.Length - 1; + var xmp = Encoding.ASCII.GetBytes ("XMP DataXMP"); + var block = new byte[3 + xmp.Length + 1 + 3 + 1]; + block[0] = 0x21; + block[1] = 0xFF; + block[2] = 11; + xmp.CopyTo (block, 3); + block[3 + xmp.Length] = 3; + block[^1] = 0; + return Concat (gif.AsSpan (0, trailer).ToArray (), block, [0x3B]); + } + + static byte[] JpegWithMetadata () + { + var exif = Encoding.ASCII.GetBytes ("Exif\0\0GPS"); + var xmp = Encoding.ASCII.GetBytes ("http://ns.adobe.com/xap/1.0/\0"); + var iptc = Encoding.ASCII.GetBytes ("8BIM"); + var other = Encoding.ASCII.GetBytes ("Other\0keep"); + return Concat ( + [0xFF, 0xD8], + JpegSegment (0xE1, exif), + JpegSegment (0xE1, xmp), + JpegSegment (0xED, iptc), + JpegSegment (0xE1, other), + JpegSegment (0xFE, Encoding.ASCII.GetBytes ("hello")), + JpegSegment (0xC0, [0x08, 0x00, 0x01, 0x00, 0x08, 0x01, 0x01, 0x11, 0x00]), + JpegSegment (0xDA, []), + [0xFF, 0xD9]); + } + + static byte[] JpegSegment (byte marker, byte[] payload) + { + var length = payload.Length + 2; + var segment = new byte[4 + payload.Length]; + segment[0] = 0xFF; + segment[1] = marker; + segment[2] = (byte)(length >> 8); + segment[3] = (byte)length; + payload.CopyTo (segment, 4); + return segment; + } + + public static IEnumerable ClearCases () + { + var exif = ExifTiff ([(0x010F, "Canon"), (0x0110, "EOS")], [(0x9286, "ASCII\0\0\0hi")]); + yield return Png ("eXIf", PngChunk ("eXIf", exif), dropped: true); + yield return Png ("zxIf", PngChunk ("zxIf", Concat ([0, 0], Zlib (exif))), dropped: true); + yield return Png ("tIME", PngChunk ("tIME", [0x07, 0xEA, 11, 22, 10, 0, 0]), dropped: true); + yield return Png ("iTXt XMP", Xmp (XmpPacket (Alt ("dc:title", "T"))), dropped: true); + yield return Png ("raw profile exif", RawProfile ("exif", Concat ("Exif\0\0"u8.ToArray (), exif)), dropped: true); + yield return Png ("raw profile iptc", RawProfile ("iptc", [0x1C, 0x02, 0x19, 0x00, 0x02, 0x6B, 0x77]), dropped: true); + yield return Png ("unmapped tEXt", Text ("Software", "GIMP"), dropped: true); + yield return Png ("iCCP", PngChunk ("iCCP", Concat ("icc"u8.ToArray (), [0, 0], Zlib ([1, 2, 3]))), dropped: false); + yield return Png ("pHYs", PngChunk ("pHYs", [0, 0, 0x0B, 0x13, 0, 0, 0x0B, 0x13, 1]), dropped: false); + yield return Png ("caBX C2PA manifest", PngChunk ("caBX", C2paStore ()), dropped: true); + yield return Png ("dSIG", PngChunk ("dSIG", [1, 2, 3]), dropped: true); + yield return Png ("iDOT", PngChunk ("iDOT", new byte[28]), dropped: true); + yield return Png ("unknown ancillary", PngChunk ("vpAg", [0, 0, 0, 9, 0, 0, 0, 9, 0]), dropped: true); + yield return Png ("sRGB", PngChunk ("sRGB", [0]), dropped: false); + yield return Png ("cICP", PngChunk ("cICP", [1, 13, 0, 1]), dropped: false); + yield return Png ("acTL", PngChunk ("acTL", [0, 0, 0, 1, 0, 0, 0, 0]), dropped: false); + yield return Png ("sTER", PngChunk ("sTER", [0]), dropped: false); + yield return Png ("unknown critical", PngChunk ("CgBI", [0x50, 0x00, 0x20, 0x06]), dropped: false); + + yield return Jpeg ("APP1 Exif", JpegExif (ExifTiff ([(0x010F, "Canon")], [(0x8827, "GPS")])), dropped: true); + yield return Jpeg ("APP1 XMP", JpegXmp (XmpPacket (Alt ("dc:title", "T"))), dropped: true); + yield return Jpeg ("APP1 extended XMP", JpegApp (0xE1, "http://ns.adobe.com/xmp/extension/\0", "0123456789ABCDEF0123456789ABCDEF\0\0\0\x10\0\0\0\0"), dropped: true); + yield return Jpeg ("APP12 Ducky", JpegApp (0xEC, "Ducky\0", "\x03\0\x08\0\0\0\x02\0C\0o"), dropped: true); + yield return Jpeg ("APP12 PictureInfo", JpegApp (0xEC, "[picture info]", "Camera=X"), dropped: true); + yield return Jpeg ("APP13 IPTC", JpegApp (0xED, "Photoshop 3.0\0", "8BIM\x04\x04"), dropped: true); + yield return Jpeg ("APP2 FPXR", JpegApp (0xE2, "FPXR\0", "\0\x01contents"), dropped: true); + yield return Jpeg ("APP0 JFIF", JpegApp (0xE0, "JFIF\0", "\x01\x01\0\0\x01\0\x01\0\0"), dropped: false); + yield return Jpeg ("APP2 ICC", JpegApp (0xE2, "ICC_PROFILE\0", "\x01\x01profile"), dropped: false); + yield return Jpeg ("APP14 Adobe", JpegApp (0xEE, "Adobe", "\0\x64\0\0\0\0\x01"), dropped: false); + // A JPEG XT box is any APP11 box that is not a JUMBF superbox ("jumb"); LCHK is the legacy checksum box. + yield return Jpeg ("APP11 JPEG XT box", Jumbf (1, 1, Box ("LCHK", [0, 0, 0, 1])), dropped: false); + yield return Jpeg ("APP11 JUMBF JSON", Jumbf (2, 1, JumbfStore (JsonUuid, "stds.exif", Box ("json", """{"exif:GPSLatitude":"47,30.0N"}"""u8.ToArray ()))), dropped: true); + yield return Jpeg ("APP11 JUMBF XML", Jumbf (3, 1, JumbfStore (XmlUuid, "xmp", Box ("xml ", "Jane"u8.ToArray ()))), dropped: true); + yield return ["jpeg", "APP11 JPEG XT box sharing En with a C2PA store", ImageTestBuilder.Jpeg (Jumbf (7, 1, C2paStore ()), Jumbf (7, 1, Box ("LCHK", [0, 0, 0, 2])), JpegSegment (0xFE, "c"u8.ToArray ())), Jumbf (7, 1, Box ("LCHK", [0, 0, 0, 2])), false]; + yield return Jpeg ("APP11 without JP", JpegApp (0xEB, "XX", "\0\0\0\0\0\0\0\0\0\0\0\0\0\0"), dropped: true); + // JPEG XT decoding boxes (Artusi et al. 2016, Fig. 3) are kept; any other box type in APP11 is metadata or unknown. + yield return Jpeg ("APP11 JPEG XT SPEC superbox", Jumbf (4, 1, Box ("SPEC", Box ("TONE", [0, 1]))), dropped: false); + yield return Jpeg ("APP11 JPEG XT RESI box", Jumbf (5, 1, Box ("RESI", [0xFF, 0xD8, 0xFF, 0xD9])), dropped: false); + yield return Jpeg ("APP11 JPEG XT ftyp box", Jumbf (6, 1, Box ("ftyp", "jpxt"u8.ToArray ())), dropped: false); + yield return Jpeg ("APP11 xml box", Jumbf (8, 1, Box ("xml ", "Jane"u8.ToArray ())), dropped: true); + yield return Jpeg ("APP11 uuid box (XMP)", Jumbf (9, 1, Box ("uuid", Concat (new byte[] { 0xBE, 0x7A, 0xCF, 0xCB, 0x97, 0xA9, 0x42, 0xE8, 0x9C, 0x71, 0x99, 0x94, 0x91, 0xE3, 0xAF, 0xAC }, ""u8.ToArray ()))), dropped: true); + yield return Jpeg ("APP11 json box", Jumbf (10, 1, Box ("json", """{"Gps":"47N"}"""u8.ToArray ())), dropped: true); + yield return Jpeg ("APP11 Exif box", Jumbf (11, 1, Box ("Exif", Concat (new byte[4], "MM\0*"u8.ToArray ()))), dropped: true); + yield return Jpeg ("APP11 unknown box", Jumbf (12, 1, Box ("ABCD", [1, 2, 3])), dropped: true); + yield return Jpeg ("APP11 C2PA", Jumbf (7, 1, C2paStore ()), dropped: true); + yield return ["jpeg", "APP11 C2PA continuation", ImageTestBuilder.Jpeg (Jumbf (7, 1, C2paStore ()), Jumbf (7, 2, Box ("jumb", [1, 2, 3])), JpegSegment (0xFE, "c"u8.ToArray ())), Jumbf (7, 2, Box ("jumb", [1, 2, 3])), true]; + yield return Jpeg ("APP1 other", JpegApp (0xE1, "Other\0", "drop"), dropped: true); + yield return Jpeg ("APP4 SCALADO", JpegApp (0xE4, "SCALADO\0", "maker data"), dropped: true); + yield return Jpeg ("APP0 AVI1", JpegApp (0xE0, "AVI1", "\0\0"), dropped: true); + yield return Jpeg ("APP15 unknown", JpegApp (0xEF, "??", "x"), dropped: true); + yield return Jpeg ("DRI (not APPn)", JpegSegment (0xDD, [0, 4]), dropped: false); + + yield return Gif ("XMP", GifApplication ("XMP DataXMP", ""u8.ToArray ()), dropped: true); + yield return Gif ("ImageMagick IPTC", GifApplication ("MGKIPTC0000", [0x1C, 0x02, 0x19, 0x00, 0x03, 0x6B, 0x77, 0x31]), dropped: true); + yield return Gif ("ImageMagick 8BIM", GifApplication ("MGK8BIM0000", "8BIM\x04\x04"u8.ToArray ()), dropped: true); + yield return Gif ("NETSCAPE loop", GifApplication ("NETSCAPE2.0", [1, 0, 0]), dropped: false); + yield return Gif ("ICC", GifApplication ("ICCRGBG1012", [1, 2, 3]), dropped: false); + yield return Gif ("XMP with magic trailer", GifXmp (XmpPacket (Alt ("dc:title", "T"))), dropped: true); + yield return Gif ("unknown application", GifApplication ("XYZWABCD1.0", [1, 2]), dropped: true); + yield return Gif ("undefined label", [0x21, 0x77, 2, 1, 2, 0], dropped: true); + yield return Gif ("graphic control", [0x21, 0xF9, 4, 0, 0, 0, 0, 0], dropped: false); + + static object[] Png (string name, byte[] carrier, bool dropped) => + ["png", name, ImageTestBuilder.Png (carrier, Text ("Title", "T")), carrier, dropped]; + static object[] Jpeg (string name, byte[] carrier, bool dropped) => + ["jpeg", name, ImageTestBuilder.Jpeg (carrier, JpegSegment (0xFE, "c"u8.ToArray ())), carrier, dropped]; + static object[] Gif (string name, byte[] carrier, bool dropped) => + ["gif", name, ImageTestBuilder.Gif (GifComment ("c"), carrier), carrier, dropped]; + } + + [TestMethod] + [DynamicData (nameof (ClearCases))] + public void Clear_DropsEveryMetadataCarrier_AndKeepsWhatTheDecoderNeeds (string format, string carrier, byte[] input, byte[] block, bool dropped) + { + var name = "a." + (format == "jpeg" ? "jpg" : format); + var file = Open (input, name); + Assert.IsTrue (input.AsSpan ().IndexOf (block) >= 0, carrier); + + file.Tag!.Clear (); + var output = file.Render ().ToArray (); + + Assert.AreEqual (!dropped, output.AsSpan ().IndexOf (block) >= 0, $"{format} {carrier}: expected {(dropped ? "dropped" : "kept")}"); + var reread = Open (output, name); + Assert.IsTrue (reread.Tag!.IsEmpty); + Assert.IsNotNull (reread.ImageProperties); + } + + [TestMethod] + public void Clear_OfAShortApp11Segment_DropsItWithoutThrowing () + { + var input = Jpeg (JpegSegment (0xEB, "JP\0\u0001\0\0\0\u0001"u8.ToArray ()), JpegSegment (0xFE, "c"u8.ToArray ())); + var file = Open (input, "a.jpg"); + file.Tag!.Clear (); + var output = file.Render ().ToArray (); + Assert.IsTrue (output.AsSpan ().IndexOf (new byte[] { 0xFF, 0xEB }) < 0); + } +} diff --git a/tests/TagLibSharp2.Tests/Image/ImageDetectionTests.cs b/tests/TagLibSharp2.Tests/Image/ImageDetectionTests.cs new file mode 100644 index 00000000..4e7e5a85 --- /dev/null +++ b/tests/TagLibSharp2.Tests/Image/ImageDetectionTests.cs @@ -0,0 +1,116 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Buffers.Binary; +using System.Text; +using TagLibSharp2.Core; +using TagLibSharp2.Image; +using TagLibSharp2.Image.Tiff; +using TagLibSharp2.Tests.Core; +using TagLibSharp2.Tests.Kit; +using static TagLibSharp2.Tests.Image.ImageTestBuilder; + +namespace TagLibSharp2.Tests.Image; + +/// Telling an image format from its first bytes, without copying or decoding what is not an image. +[TestClass] +[TestCategory ("Unit")] +public class ImageDetectionTests +{ + [TestMethod] + public void MalformedContainers_FailToOpen () + { + Reject (new byte[] { 0xFF, 0xD8, 0xFF, 0x00 }, "bad.jpg"); + Reject (new byte[] { 0xFF, 0xD8, 0xFF, 0xFF }, "fill.jpg"); + Reject (new byte[] { 0xFF, 0xD8, 0xFF, 0xD9 }, "eoi.jpg"); + Reject (new byte[] { 0xFF, 0xD8, 0xFF, 0xD0 }, "rst.jpg"); + Reject (new byte[] { 0xFF, 0xD8, 0xFF, 0xE0, 0x00, 0x01 }, "short.jpg"); + Reject (new byte[] { 0xFF, 0xD8, 0xFF, 0xC0, 0x00, 0x0B, 0x08, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x11, 0x00 }, "zero.jpg"); + Reject (new byte[] { 0xFF, 0xD8, 0xFF, 0xDA, 0x00, 0x02 }, "sos.jpg"); + Reject (PngIhdr (0, 1, 8, 0), "zero.png"); + Reject (PngIhdr (1, 1, 8, 1), "type.png"); + Assert.AreEqual (8, Open (PngIhdr (2, 2, 8, 0), "g.png").ImageProperties!.Value.ColorDepth); + Assert.AreEqual (8, Open (PngIhdr (2, 2, 8, 3), "p.png").ImageProperties!.Value.ColorDepth); + Assert.AreEqual (16, Open (PngIhdr (2, 2, 8, 4), "ga.png").ImageProperties!.Value.ColorDepth); + Assert.AreEqual (32, Open (PngIhdr (2, 2, 8, 6), "rgba.png").ImageProperties!.Value.ColorDepth); + Reject (Encoding.ASCII.GetBytes ("GIF89a"), "short.gif"); + Reject (GifScreen (0, 1, flags: 0), "zero.gif"); + } + + static void Reject (byte[] data, string name) + { + var result = MediaFile.ReadFromData (data, name); + Assert.IsFalse (result.IsSuccess, result.Error); + } + + // A classic TIFF header alone is 8 bytes: exiftool 13.55 reports such a file as TIFF ("Bad IFD0 directory"), and + // 7 bytes as a file format error. + [TestMethod] + [DataRow (new byte[] { 0x49, 0x49, 42, 0, 8, 0, 0, 0 }, MediaFormat.Tiff)] + [DataRow (new byte[] { 0x4D, 0x4D, 0, 42, 0, 0, 0, 8 }, MediaFormat.Tiff)] + [DataRow (new byte[] { 0x49, 0x49, 42, 0, 8, 0, 0 }, MediaFormat.Unknown)] + public void DetectFormat_OfATiffHeaderAlone_IsTiffFromEightBytes (byte[] data, MediaFormat format) => + Assert.AreEqual (format, MediaFile.DetectFormat (data)); + + [TestMethod] + public void DetectFormat_DoesNotCopyAnAudioBufferToLookForSvg () + { + var mp3 = new byte[200_000]; + mp3[0] = 0xFF; + mp3[1] = 0xFB; + mp3[2] = 0x90; + var id3 = new byte[200_000]; + Encoding.ASCII.GetBytes ("ID3").CopyTo (id3, 0); + id3[3] = 3; + var asf = new byte[200_000]; + new byte[] { 0x30, 0x26, 0xB2, 0x75, 0x8E, 0x66, 0xCF, 0x11, 0xA6, 0xD9, 0x00, 0xAA, 0x00, 0x62, 0xCE, 0x6C } + .CopyTo (asf, 0); + MediaFile.DetectFormat (mp3); + MediaFile.DetectFormat (id3); + MediaFile.DetectFormat (asf); + + const int limit = 8 * 1024; + Bounds.AssertAllocatesAtMost (limit, () => _ = MediaFile.DetectFormat (mp3), "mp3"); + Bounds.AssertAllocatesAtMost (limit, () => _ = MediaFile.DetectFormat (id3), "id3"); + Bounds.AssertAllocatesAtMost (limit, () => _ = MediaFile.DetectFormat (asf), "asf"); + Assert.AreNotEqual (MediaFormat.Svg, MediaFile.DetectFormat (mp3)); + } + + public static IEnumerable MarkupThatIsNotSvg () + { + yield return ["XML", Encoding.UTF8.GetBytes ("" + new string ('x', Mib) + "")]; + yield return ["HTML", Encoding.UTF8.GetBytes ("" + new string ('x', Mib) + "")]; + yield return ["UTF-16 XML", Concat ([0xFF, 0xFE], Encoding.Unicode.GetBytes ("" + new string ('x', Mib / 2) + ""))]; + yield return ["UTF-16BE XML", Concat ([0xFE, 0xFF], Encoding.BigEndianUnicode.GetBytes ("" + new string ('x', Mib / 2) + ""))]; + yield return ["long comment", Encoding.UTF8.GetBytes ("">]>""")]; + yield return ["svg-utf16", "a.svg", Concat ([0xFE, 0xFF], Encoding.BigEndianUnicode.GetBytes (""""""))]; + } + + static void ReadEverywhere (byte[] data, string name) + { + _ = MediaFile.DetectFormat (data, name); + _ = StillImageFile.IsValidFormat (data); + Exercise (MediaFile.ReadFromData (data, name).File as StillImageFile); + Exercise (StillImageFile.Read (data).File); + using var stream = new MemoryStream (data, writable: false); + Exercise (MediaFile.Read (stream, name).File as StillImageFile); + } + + static void Exercise (StillImageFile? file) + { + if (file?.Tag is not Tag tag) + return; + tag.Title = "t2"; + tag.Artist = "a2"; + tag.Comment = null; + _ = file.Render (); + tag.Clear (); + _ = file.Render (); + } + + [TestMethod] + [DynamicData (nameof (Samples))] + public void EveryTruncation_NeverThrows (string format, string name, byte[] valid) + { + var cases = Hostile.EveryTruncation (valid, data => ReadEverywhere (data, name)); + Assert.IsTrue (cases > 0, format); + } + + [TestMethod] + [DynamicData (nameof (Samples))] + public void ByteFlips_NeverThrow (string format, string name, byte[] valid) + { + var cases = Hostile.ByteFlips (valid, data => ReadEverywhere (data, name)); + Assert.IsTrue (cases > 0, format); + } + + // A flipped PNG byte usually fails its chunk CRC and the chunk is skipped. Recomputing the CRCs sends the + // flipped bytes into the text, XMP and Exif parsers instead. + [TestMethod] + public void Png_ByteFlipsWithValidCrcs_NeverThrow () + { + var valid = (byte[])Samples ().First ()[2]; + Hostile.ByteFlips (valid, data => { + var fixedCrcs = (byte[])data.Clone (); + FixPngCrcs (fixedCrcs); + ReadEverywhere (fixedCrcs, "a.png"); + }); + Hostile.EveryTruncation (valid, data => { + FixPngCrcs (data); + ReadEverywhere (data, "a.png"); + }); + } + + static void FixPngCrcs (byte[] png) + { + var i = 8; + while (i + 12 <= png.Length) { + var length = BinaryPrimitives.ReadInt32BigEndian (png.AsSpan (i)); + if (length < 0 || i + 12L + length > png.Length) + return; + BinaryPrimitives.WriteUInt32BigEndian (png.AsSpan (i + 8 + length), BinaryData.ComputeCrc32 (png.AsSpan (i + 4, 4 + length))); + i += 12 + length; + } + } + + public static IEnumerable GrowingInputs () + { + yield return ["png text chunks", (Func)(n => Png ([.. Enumerable.Range (0, n).Select (i => Text ("Comment", "value " + i))])), "a.png", 200]; + yield return ["png XMP properties", (Func)(n => Png (Xmp (XmpPacket (Alt ("dc:title", "t") + string.Concat (Enumerable.Range (0, n).Select (i => $" {i}\n")))))), "a.png", 200]; + yield return ["png eXIf entries", (Func)(n => Png (PngChunk ("eXIf", ExifTiff ([.. Enumerable.Range (0, n).Select (i => (0x0100 + i, "v" + i)), (0x013B, "artist")], [])))), "a.png", 200]; + yield return ["gif comment sub-blocks", (Func)(n => Gif ([.. Enumerable.Range (0, n).Select (i => GifComment (new string ('c', 200)))])), "a.gif", 200]; + yield return ["gif application extensions", (Func)(n => Gif ([.. Enumerable.Range (0, n).Select (i => GifApplication ("MGKIPTC0000", new byte[200]))])), "a.gif", 200]; + yield return ["jpeg APP segments", (Func)(n => Jpeg ([.. Enumerable.Range (0, n).Select (i => JpegApp (0xE1, "Exif\0\0", new string ('e', 200)))])), "a.jpg", 200]; + yield return ["jpeg DNL scan", (Func)(n => Concat (ZeroHeightJpeg.AsSpan (0, 25).ToArray (), Enumerable.Repeat (new byte[] { 0x11, 0xFF, 0x00 }, n * 50).SelectMany (b => b).ToArray (), [0xFF, 0xDC, 0x00, 0x04, 0x00, 0x05])), "a.jpg", 200]; + yield return ["tiff IFD chain", (Func)(n => TiffChain ([[(254, 1), (256, 2), (257, 2)], .. Enumerable.Range (0, n).Select (_ => Array.Empty<(int, int)> ())])), "a.tif", 200]; + yield return ["svg prolog", (Func)(n => Encoding.UTF8.GetBytes ("""")), "a.svg", 100]; + yield return ["netpbm comments", (Func)(n => Encoding.ASCII.GetBytes ("P5\n" + string.Concat (Enumerable.Repeat ("# comment line\n", n)) + "2 3\n255\n")), "a.pgm", 200]; + } + + [TestMethod] + [DoNotParallelize] + [DynamicData (nameof (GrowingInputs))] + public void ReadAndRewrite_AllocateLinearly (string shape, Func build, string name, int n) + { + Bounds.AssertLinearAllocation (build, data => { + var file = (StillImageFile)MediaFile.ReadFromData (data, name).File!; + if (file.Tag is not Tag tag) + return; + tag.Artist = "new artist"; + tag.Comment = "new comment"; + _ = file.Render (); + tag.Clear (); + _ = file.Render (); + }, n, runs: 3); + Assert.IsNotNull (shape); + } +} diff --git a/tests/TagLibSharp2.Tests/Image/ImagePathSaveCancellationTests.cs b/tests/TagLibSharp2.Tests/Image/ImagePathSaveCancellationTests.cs new file mode 100644 index 00000000..7eef55cd --- /dev/null +++ b/tests/TagLibSharp2.Tests/Image/ImagePathSaveCancellationTests.cs @@ -0,0 +1,263 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using TagLibSharp2.Core; +using TagLibSharp2.Image; +using TagLibSharp2.Tests.Core; +using static TagLibSharp2.Tests.Image.ImageTestBuilder; + +namespace TagLibSharp2.Tests.Image; + +/// +/// Image path-save cases the shared cancellation rows do not cover: no source path, an unreadable open, +/// a splice that fails before the copy, and a cancel between chunks. Every still-image format is a row. +/// +[TestClass] +[TestCategory ("Unit")] +public sealed class ImagePathSaveCancellationTests +{ + const int PastOneChunk = 80 * 1024; + + [TestMethod] + [DataRow ("jpeg")] + [DataRow ("png")] + [DataRow ("gif")] + [DataRow ("tiff")] + [DataRow ("dng")] + [DataRow ("bmp")] + [DataRow ("pcx")] + [DataRow ("netpbm")] + [DataRow ("svg")] + public async Task PathSave_CancelledTokenWithoutASourcePath_DoesNotWrite (string format) + { + var file = ReadHeld (format); + var fs = new ProbeFileSystem (); + using var cts = new CancellationTokenSource (); + cts.Cancel (); + + var save = await file.SaveToFileAsync ("/out." + format, fs, cts.Token); + + Assert.IsFalse (save.IsSuccess); + Assert.AreEqual ("Operation was cancelled", save.Error); + Assert.IsFalse (fs.FileExists ("/out." + format)); + } + + [TestMethod] + [DynamicData (nameof (UnreadableSources))] + public async Task PathSave_UnreadableSource_BeatsAnAlreadyCancelledToken (string format, string fault, string expected) + { + var (file, fs) = Open (format); + fs.ArmOpenTracking = true; + if (fault.StartsWith ("open", StringComparison.Ordinal)) + fs.OpenReadFault = fault == "open-io" ? "io" : "denied"; + else + fs.LengthFault = fault == "length-io" ? "io" : "denied"; + + var save = await file.SaveToFileAsync ("/out." + format, fs, Cancelled ()); + + Assert.IsFalse (save.IsSuccess); + Assert.AreEqual (expected, save.Error, format); + Assert.IsFalse (fs.FileExists ("/out." + format)); + Assert.AreEqual (0, fs.CreateCalls); + if (fault.StartsWith ("length", StringComparison.Ordinal)) { + Assert.IsNotNull (fs.SaveOpen); + Assert.IsTrue (fs.SaveOpen.WasDisposed); + } else { + Assert.IsNull (fs.SaveOpen); + } + } + + [TestMethod] + [DataRow ( + "jpeg", + "The JPEG marker list before the scan is truncated or malformed, so the comment cannot be spliced in.")] + [DataRow ( + "png", + "The PNG chunk list does not reach IEND, so the text cannot be spliced in.")] + [DataRow ( + "gif", + "The GIF block list is truncated or holds an unknown block, so the comment cannot be spliced in.")] + public async Task PathSave_SpliceFailure_BeatsAnAlreadyCancelledToken (string format, string expected) + { + var (file, fs) = OpenTruncated (format); + fs.ArmOpenTracking = true; + if (format == "png") + file.Tag!.Title = "PathSave"; + else + file.Tag!.Comment = "PathSave"; + + var save = await file.SaveToFileAsync ("/out." + format, fs, Cancelled ()); + + Assert.IsFalse (save.IsSuccess); + Assert.AreEqual (expected, save.Error); + Assert.IsFalse (fs.FileExists ("/out." + format)); + Assert.AreEqual (0, fs.CreateCalls); + Assert.IsNotNull (fs.SaveOpen); + Assert.IsTrue (fs.SaveOpen.WasDisposed); + CollectionAssert.AreEqual (fs.Original, fs.Store.ReadAllBytes ("/in." + format)); + } + + [TestMethod] + [DataRow ("jpeg")] + [DataRow ("png")] + [DataRow ("gif")] + [DataRow ("tiff")] + [DataRow ("dng")] + [DataRow ("bmp")] + [DataRow ("pcx")] + [DataRow ("netpbm")] + [DataRow ("svg")] + public async Task PathSave_CancelDuringCopy_DoesNotReplaceTheDestination (string format) + { + var data = LargerThanOneChunk (format); + var (file, fs) = Open (format, data); + fs.ArmOpenTracking = true; + using var cts = new CancellationTokenSource (); + fs.CancelOnWrite = cts; + + var save = await file.SaveToFileAsync ("/out." + format, fs, cts.Token); + + Assert.IsFalse (save.IsSuccess, format); + Assert.AreEqual ("Operation was cancelled", save.Error, format); + Assert.IsGreaterThanOrEqualTo (1, fs.CreateCalls); + Assert.IsLessThanOrEqualTo (ChunkBoundedFileSystem.MaxChunk, fs.MaxWrite); + Assert.IsFalse (fs.FileExists ("/out." + format)); + Assert.IsNotNull (fs.SaveOpen); + Assert.IsTrue (fs.SaveOpen.WasDisposed); + CollectionAssert.AreEqual (data, fs.Store.ReadAllBytes ("/in." + format)); + } + + [TestMethod] + [DataRow ("jpeg")] + [DataRow ("png")] + [DataRow ("gif")] + [DataRow ("tiff")] + [DataRow ("dng")] + [DataRow ("bmp")] + [DataRow ("pcx")] + [DataRow ("netpbm")] + [DataRow ("svg")] + public async Task PathSave_SuccessfulCopy_DisposesTheSource (string format) + { + var (file, fs) = Open (format); + fs.ArmOpenTracking = true; + + var save = await file.SaveToFileAsync ("/out." + format, fs); + + Assert.IsTrue (save.IsSuccess, format + ": " + save.Error); + Assert.IsNotNull (fs.SaveOpen); + Assert.IsTrue (fs.SaveOpen.WasDisposed); + Assert.IsTrue (fs.FileExists ("/out." + format)); + } + + [TestMethod] + [DataRow ("jpeg")] + [DataRow ("png")] + [DataRow ("gif")] + [DataRow ("tiff")] + [DataRow ("dng")] + [DataRow ("bmp")] + [DataRow ("pcx")] + [DataRow ("netpbm")] + [DataRow ("svg")] + public async Task PathSave_ShortSource_DisposesTheSource (string format) + { + var (file, fs) = Open (format); + fs.Add ("/in." + format, [1]); + fs.ArmOpenTracking = true; + + var save = await file.SaveToFileAsync ("/out." + format, fs, Cancelled ()); + + Assert.IsFalse (save.IsSuccess); + Assert.AreEqual ("The source ended before the requested bytes were copied", save.Error, format); + Assert.IsFalse (fs.FileExists ("/out." + format)); + Assert.IsNotNull (fs.SaveOpen); + Assert.IsTrue (fs.SaveOpen.WasDisposed); + } + + public static IEnumerable UnreadableSources () + { + (string Fault, string Expected)[] faults = [ + ("open-io", "Failed to re-read source file: Failed to read file: disk fault"), + ("open-denied", "Failed to re-read source file: Access denied: Access denied"), + ("length-io", "Failed to re-read source file: Failed to read file: disk fault"), + ("length-denied", "Failed to re-read source file: Access denied: Access denied") + ]; + foreach (var format in new[] { "jpeg", "png", "gif", "tiff", "dng", "bmp", "pcx", "netpbm", "svg" }) { + foreach (var (fault, expected) in faults) + yield return new object[] { format, fault, expected }; + } + } + + static (StillImageFile File, ProbeFileSystem Fs) Open (string format, byte[]? data = null) + { + data ??= Small (format); + var fs = new ProbeFileSystem (); + fs.Add ("/in." + format, data); + var read = StillImageFile.ReadFromFile ("/in." + format, fs); + Assert.IsTrue (read.IsSuccess, format + ": " + read.Error); + return (read.File!, fs); + } + + static StillImageFile ReadHeld (string format) + { + var read = StillImageFile.Read (Small (format)); + Assert.IsTrue (read.IsSuccess, format + ": " + read.Error); + return read.File!; + } + + static (StillImageFile File, ProbeFileSystem Fs) OpenTruncated (string format) + { + byte[] data = format switch { + "png" => Concat (PngSignature, PngChunk ("IHDR", [0, 0, 0, 2, 0, 0, 0, 3, 8, 0, 0, 0, 0])), + "gif" => GifScreen (1, 1, flags: 0), + _ => Concat ( + [0xFF, 0xD8], + JpegSegment (0xC0, [0x08, 0x00, 0x01, 0x00, 0x01, 0x01, 0x01, 0x11, 0x00]), + [0xFF, 0xFE, 0x00, 0x10]) + }; + return Open (format, data); + } + + static byte[] LargerThanOneChunk (string format) + { + if (format == "svg") + return SvgPastOneChunk (); + + var header = Small (format); + var data = new byte[PastOneChunk]; + header.CopyTo (data, 0); + return data; + } + + static byte[] SvgPastOneChunk () + { + var open = ""u8; + var close = ""u8; + var data = new byte[PastOneChunk]; + open.CopyTo (data); + Array.Fill (data, (byte)' ', open.Length, PastOneChunk - open.Length - close.Length); + close.CopyTo (data.AsSpan (PastOneChunk - close.Length)); + return data; + } + + static byte[] Small (string format) => format switch { + "jpeg" => Jpeg (), + "png" => Png (), + "gif" => Gif (), + "tiff" => TiffImage (2, 3), + "dng" => TiffImage (2, 3, dng: true), + "bmp" => Bmp (4, 2), + "pcx" => Pcx (0, 0, 1, 1, planes: 1), + "netpbm" => "P4\n1 1\n"u8.ToArray (), + "svg" => ""u8.ToArray (), + _ => throw new InvalidOperationException (format) + }; + + static CancellationToken Cancelled () + { + var cts = new CancellationTokenSource (); + cts.Cancel (); + return cts.Token; + } +} diff --git a/tests/TagLibSharp2.Tests/Image/ImagePathSaveTests.cs b/tests/TagLibSharp2.Tests/Image/ImagePathSaveTests.cs new file mode 100644 index 00000000..13d64ba6 --- /dev/null +++ b/tests/TagLibSharp2.Tests/Image/ImagePathSaveTests.cs @@ -0,0 +1,864 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Security.Cryptography; +using TagLibSharp2.Core; +using TagLibSharp2.Image; +using TagLibSharp2.Tests.Core; +using TagLibSharp2.Tests.Kit; +using static TagLibSharp2.Tests.Image.ImageTestBuilder; + +namespace TagLibSharp2.Tests.Image; + +/// +/// A still-image path save writes the same bytes as . +/// The hashes are the bytes a path save wrote at 1322374a. +/// +[TestClass] +[TestCategory ("Unit")] +public sealed class ImagePathSaveTests +{ + [TestMethod] + [DataRow ("noop", "E8B358D41E5ED04327921256E0EC031B72CC47AE60BBCF45B0EB7C739D88967E")] + [DataRow ("comment", "0E5079562AE988F2A93272CCC5DD0E82BD92727095EF7359A9AD6CDD7743CDEC")] + [DataRow ("comment-same", "E8B358D41E5ED04327921256E0EC031B72CC47AE60BBCF45B0EB7C739D88967E")] + [DataRow ("comment-null", "062950C028B973C6C06C3A17B0F838301A5539EAF7D1C9938378B46541A53078")] + [DataRow ("clear", "062950C028B973C6C06C3A17B0F838301A5539EAF7D1C9938378B46541A53078")] + [DataRow ("exif-comment", "358C2938529D405CCB82B5CE947C93ACAE3BCEAA67CFFBF27C902731C49D5E6B")] + [DataRow ("xmp-comment", "234F5E081BF9BCFF60BFF5A985102CF3C64DA5FE37B0951E3E1C73077469DA53")] + [DataRow ("mpf-comment", "1C29BCB8D4CBF18C45909542F66327247C0FE6A0D7223CCF869EB16322A1FD9A")] + public void JpegPathSave_BytesEqualRender (string op, string expectedHash) + { + var data = JpegInput (op); + var fs = new MockFileSystem (); + fs.AddFile ("/in.jpg", data); + var read = StillImageFile.ReadFromFile ("/in.jpg", fs); + Assert.IsTrue (read.IsSuccess, read.Error); + Apply (read.File!, op); + var rendered = read.File!.Render ().ToArray (); + + var save = read.File.SaveToFile ("/out.jpg", fs); + + Assert.IsTrue (save.IsSuccess, save.Error); + var written = fs.ReadAllBytes ("/out.jpg"); + CollectionAssert.AreEqual (rendered, written, op); + Assert.AreEqual (expectedHash, Convert.ToHexString (SHA256.HashData (written)), op); + } + + // An empty source path is not a file to re-open. The save writes the bytes already read, even if that path + // later holds something shorter. + [TestMethod] + public void JpegPathSave_EmptySourcePath_WritesTheOpenedBytes () + { + var data = Jpeg (JpegSegment (0xFE, "old"u8.ToArray ())); + var fs = new MockFileSystem (); + fs.AddFile ("", data); + var read = StillImageFile.ReadFromFile ("", fs); + Assert.IsTrue (read.IsSuccess, read.Error); + fs.AddFile ("", [0x00]); + + var save = read.File!.SaveToFile ("/out.jpg", fs); + + Assert.IsTrue (save.IsSuccess, save.Error); + CollectionAssert.AreEqual (data, fs.ReadAllBytes ("/out.jpg")); + } + + /// The scan is 80 KB of 0x11. The hash is the path save of that edit at 1322374a. + [TestMethod] + [DataRow (false)] + [DataRow (true)] + public async Task JpegPathSave_OverOneChunk_CopiesTheScanInChunks (bool saveAsync) + { + var (file, fs) = OpenEditedScan (80 * 1024); + fs.ResetSourceLengthGets (); + var rendered = file.Render ().ToArray (); + + var save = saveAsync + ? await file.SaveToFileAsync ("/out.jpg", fs) + : file.SaveToFile ("/out.jpg", fs); + + Assert.IsTrue (save.IsSuccess, save.Error); + Assert.AreEqual (1, fs.SourceLengthGets); + var written = fs.Bytes ("/out.jpg"); + CollectionAssert.AreEqual (rendered, written); + Assert.AreEqual ("45C76CF7112DCCD5B2595DE1CFA0374CCD05E60FF8B1A0A7B147B3FB160A3937", Convert.ToHexString (SHA256.HashData (written))); + } + + /// + /// SOS, the entropy bytes and EOI are one range. Twelve of those bytes are SOS and EOI, so 65524 + /// entropy bytes make a range of one chunk. The hash is that edit's Render at 1322374a. + /// + [TestMethod] + [DataRow (false)] + [DataRow (true)] + public async Task JpegPathSave_ScanRangeOfOneChunk_CopiesInChunks (bool saveAsync) + { + var (file, fs) = OpenEditedScan (65524); + const string expected = "0789A82CD7EDB1141E9DF9809F92C7470E96865DD9F135345B5814E35140C4F1"; + await AssertEditedRangeCopiedInChunks (file, fs, "/out.jpg", saveAsync, 65563, expected); + } + + /// One entropy byte more makes the scan range one byte past a chunk. + [TestMethod] + [DataRow (false)] + [DataRow (true)] + public async Task JpegPathSave_ScanRangeOneBytePastOneChunk_CopiesInChunks (bool saveAsync) + { + var (file, fs) = OpenEditedScan (65525); + const string expected = "B0F6D0E18A3A25868EA7A2803561336258F7BE6140CADCF132039882171AF7F1"; + await AssertEditedRangeCopiedInChunks (file, fs, "/out.jpg", saveAsync, 65564, expected); + } + + /// + /// A path save stays under a fixed ceiling at three scan sizes. Render of the same edit grows with the scan. + /// + [TestMethod] + [DoNotParallelize] + public void JpegPathSave_AllocationStaysUnderTheCeilingWhileRenderGrows () + { + const int n = 1024 * 1024; + const long ceiling = 256 * 1024; + // SOI 2 + SOF0 13 + COM "PathSave" 12 + SOS 10 + EOI 2. + const int framing = 39; + var saves = new long[3]; + var renders = new long[3]; + for (var size = 0; size < 3; size++) { + var scanLength = n << size; + var (file, fs) = OpenEditedScan (scanLength); + var path = $"/out-{scanLength}.jpg"; + var warm = file.SaveToFile (path, fs); + Assert.IsTrue (warm.IsSuccess, warm.Error); + _ = file.Render (); + + FileWriteResult save = default; + saves[size] = LeastAllocated (() => save = file.SaveToFile (path, fs)); + Assert.IsTrue (save.IsSuccess, save.Error); + Assert.AreEqual (scanLength + framing, fs.Bytes (path).Length); + Assert.IsLessThanOrEqualTo (ceiling, saves[size]); + + ReadOnlyMemory rendered = default; + renders[size] = LeastAllocated (() => rendered = file.Render ()); + GC.KeepAlive (rendered); + } + + var high = Math.Max (saves[0], Math.Max (saves[1], saves[2])); + var low = Math.Min (saves[0], Math.Min (saves[1], saves[2])); + Assert.IsLessThan (64 * 1024, high - low, $"path save allocated {saves[0]}, {saves[1]}, {saves[2]}"); + Assert.IsGreaterThanOrEqualTo (n, renders[2] - renders[0], $"render allocated {renders[0]} then {renders[2]}"); + } + + [TestMethod] + [DataRow ("noop", "52B843CD828B9210F16992640E8C8BA9704B65E8F1C6F1D46492DCF130D6A55B")] + [DataRow ("title", "E9CF8A0A5A10EBA6CBF52534CB14F8F4E91764FE6CA2CA1D43E12AD83F0BD060")] + [DataRow ("comment", "9C0BB256C7E77EDFB89A1B83F2058F7C775881C389EA783A93752E7C10B01DEA")] + [DataRow ("comment-same", "0B09E5A56B0EDE41FCF1C6C6E835F80CD87AE103BBE932F4F6E2E315FB7E4B59")] + [DataRow ("comment-null", "67C719D3156D1CC53B47E4BCD0374DE29B16AEAB7747C9762BFD85172905891A")] + [DataRow ("clear", "67C719D3156D1CC53B47E4BCD0374DE29B16AEAB7747C9762BFD85172905891A")] + [DataRow ("xmp-title", "33C2B1D6DE01593E899AE1BD9A30E42388AB253C6A6E533289248A2C47F91BD3")] + [DataRow ("exif-artist", "AF12D9DE982466B70759290B53AE91276A86EDE9C5C56F8FDFFD7E0EB5C2D547")] + [DataRow ("raw-title", "927B1D44F059523F1CC166920FA476701A8EDC234BEDFF816FC74F035E89BA80")] + [DataRow ("idot-title", "F777A6B4481C719D125F9A369F3CCC412B754A0D072982B68776D5CC5679A1FF")] + [DataRow ("idot-comment", "CD31C8775AC912BECDB0EDABC7C0396431472F9649ACF506738B233712C23C77")] + public void PngPathSave_BytesEqualRender (string op, string expectedHash) + { + var data = PngInput (op); + var fs = new MockFileSystem (); + fs.AddFile ("/in.png", data); + var read = StillImageFile.ReadFromFile ("/in.png", fs); + Assert.IsTrue (read.IsSuccess, read.Error); + ApplyPng (read.File!, op); + var rendered = read.File!.Render ().ToArray (); + + var save = read.File.SaveToFile ("/out.png", fs); + + Assert.IsTrue (save.IsSuccess, save.Error); + var written = fs.ReadAllBytes ("/out.png"); + CollectionAssert.AreEqual (rendered, written, op); + Assert.AreEqual (expectedHash, Convert.ToHexString (SHA256.HashData (written)), op); + } + + /// The IDAT chunk is 80 KB. The hash is the path save of that title edit at 1322374a. + [TestMethod] + [DataRow (false)] + [DataRow (true)] + public async Task PngPathSave_OverOneChunk_CopiesTheImageDataInChunks (bool saveAsync) + { + var payload = new byte[80 * 1024 - 12]; + var data = Concat ( + PngSignature, + PngChunk ("IHDR", [0, 0, 0, 2, 0, 0, 0, 3, 8, 0, 0, 0, 0]), + Text ("Title", "Old"), + PngChunk ("IDAT", payload), + PngChunk ("IEND", [])); + var fs = new ChunkBoundedFileSystem (data.Length + ChunkBoundedFileSystem.MaxChunk); + fs.Add ("/in.png", data); + fs.MaxRead = data.Length; + var read = StillImageFile.ReadFromFile ("/in.png", fs); + fs.MaxRead = ChunkBoundedFileSystem.MaxChunk; + Assert.IsTrue (read.IsSuccess, read.Error); + fs.ResetSourceLengthGets (); + read.File!.Tag!.Title = "PathSave"; + var rendered = read.File.Render ().ToArray (); + + var save = saveAsync + ? await read.File.SaveToFileAsync ("/out.png", fs) + : read.File.SaveToFile ("/out.png", fs); + + Assert.IsTrue (save.IsSuccess, save.Error); + Assert.AreEqual (1, fs.SourceLengthGets); + var written = fs.Bytes ("/out.png"); + CollectionAssert.AreEqual (rendered, written); + const string expected = "6911679D573A41B74F5D62F67F8E7861D80EF89E84BC57A7A43229FB2D2C7E24"; + Assert.AreEqual (expected, Convert.ToHexString (SHA256.HashData (written))); + } + + /// + /// The IDAT chunk and IEND are one range. A payload of 65512 leaves that range at one chunk. + /// The hash is that title edit's Render at 1322374a. + /// + [TestMethod] + [DataRow (false)] + [DataRow (true)] + public async Task PngPathSave_ImageRangeOfOneChunk_CopiesInChunks (bool saveAsync) + { + var (file, fs) = OpenEditedPng (65512); + const string expected = "D11C553A3DF6AE66BC3F86FAB1BB822287AE291E1D94C2EE76ADBBC0A827B7E7"; + await AssertEditedRangeCopiedInChunks (file, fs, "/out.png", saveAsync, 65595, expected); + } + + /// One payload byte more makes the IDAT and IEND range one byte past a chunk. + [TestMethod] + [DataRow (false)] + [DataRow (true)] + public async Task PngPathSave_ImageRangeOneBytePastOneChunk_CopiesInChunks (bool saveAsync) + { + var (file, fs) = OpenEditedPng (65513); + const string expected = "60CBAB68F8587CEE857A432094822F613C1AA69888C645DDA24BBA7CA163018B"; + await AssertEditedRangeCopiedInChunks (file, fs, "/out.png", saveAsync, 65596, expected); + } + + [TestMethod] + [DoNotParallelize] + public void PngPathSave_AllocationStaysUnderTheCeilingWhileRenderGrows () + { + const int n = 1024 * 1024; + const long ceiling = 256 * 1024; + // Signature 8 + IHDR 25 + tEXt "PathSave" 26 + IDAT overhead 12 + IEND 12. + const int framing = 83; + var saves = new long[3]; + var renders = new long[3]; + for (var size = 0; size < 3; size++) { + var payloadLength = n << size; + var (file, fs) = OpenEditedPng (payloadLength); + var path = $"/out-{payloadLength}.png"; + var warm = file.SaveToFile (path, fs); + Assert.IsTrue (warm.IsSuccess, warm.Error); + _ = file.Render (); + + FileWriteResult save = default; + saves[size] = LeastAllocated (() => save = file.SaveToFile (path, fs)); + Assert.IsTrue (save.IsSuccess, save.Error); + Assert.AreEqual (payloadLength + framing, fs.Bytes (path).Length); + Assert.IsLessThanOrEqualTo (ceiling, saves[size]); + + ReadOnlyMemory rendered = default; + renders[size] = LeastAllocated (() => rendered = file.Render ()); + GC.KeepAlive (rendered); + } + + var high = Math.Max (saves[0], Math.Max (saves[1], saves[2])); + var low = Math.Min (saves[0], Math.Min (saves[1], saves[2])); + Assert.IsLessThan (64 * 1024, high - low, $"path save allocated {saves[0]}, {saves[1]}, {saves[2]}"); + Assert.IsGreaterThanOrEqualTo (n, renders[2] - renders[0], $"render allocated {renders[0]} then {renders[2]}"); + } + + [TestMethod] + [DataRow ("tiff", "59753EFEE53644237F9F0F4299A3B7178C949D9447626418365C7D4E15005DBC")] + [DataRow ("dng", "96507B9AA0101B7949BE6B6E9761FE0B57B58BB977DED0232CD9096A1374BE5C")] + public void TiffPathSave_BytesEqualRender (string format, string expectedHash) => + AssertPathSaveMatchesRender (TiffHeader (format), format, expectedHash); + + /// The file is a TIFF or DNG header followed by 80 KB. A path save copies that range in chunks. + [TestMethod] + [DataRow ("tiff", false)] + [DataRow ("tiff", true)] + [DataRow ("dng", false)] + [DataRow ("dng", true)] + public async Task TiffPathSave_OverOneChunk_CopiesTheFileInChunks (string format, bool saveAsync) + { + var data = HeaderAndTrailingBytes (TiffHeader (format)); + await AssertWholeFileCopiedInChunks (data, "/in." + format, "/out." + format, saveAsync); + } + + [TestMethod] + [DataRow ("noop", "5B86097573C47754ABA72DC155E0C91A7862DD79EE5E83CA5A0C0D0CB533F4AE")] + [DataRow ("comment", "675CA34F2FA30837B29FEEE2FA9EF5A9788FF5759D567A80B93765CD9C3048D2")] + [DataRow ("comment-same", "5B86097573C47754ABA72DC155E0C91A7862DD79EE5E83CA5A0C0D0CB533F4AE")] + [DataRow ("comment-null", "C08F79AFFAC974D0C787A60E8E07EC2434A587AA7A1AEAAF030A89792307C272")] + [DataRow ("clear", "C08F79AFFAC974D0C787A60E8E07EC2434A587AA7A1AEAAF030A89792307C272")] + [DataRow ("xmp-comment", "8A5AF0623A623754A1F5FA84B55846FF5AF5DB7E568C7C487780E0FBB77DD391")] + public void GifPathSave_BytesEqualRender (string op, string expectedHash) + { + var data = GifInput (op); + var fs = new MockFileSystem (); + fs.AddFile ("/in.gif", data); + var read = StillImageFile.ReadFromFile ("/in.gif", fs); + Assert.IsTrue (read.IsSuccess, read.Error); + ApplyGif (read.File!, op); + var rendered = read.File!.Render ().ToArray (); + + var save = read.File.SaveToFile ("/out.gif", fs); + + Assert.IsTrue (save.IsSuccess, save.Error); + var written = fs.ReadAllBytes ("/out.gif"); + CollectionAssert.AreEqual (rendered, written, op); + Assert.AreEqual (expectedHash, Convert.ToHexString (SHA256.HashData (written)), op); + } + + /// The image block is 80 KB. The hash is the path save of that comment edit at 1322374a. + [TestMethod] + [DataRow (false)] + [DataRow (true)] + public async Task GifPathSave_OverOneChunk_CopiesTheImageInChunks (bool saveAsync) + { + var data = Concat (GifScreen (1, 1, flags: 0), GifComment ("Old"), GifImage (80 * 1024), [0x3B]); + var fs = new ChunkBoundedFileSystem (data.Length + ChunkBoundedFileSystem.MaxChunk); + fs.Add ("/in.gif", data); + fs.MaxRead = data.Length; + var read = StillImageFile.ReadFromFile ("/in.gif", fs); + fs.MaxRead = ChunkBoundedFileSystem.MaxChunk; + Assert.IsTrue (read.IsSuccess, read.Error); + fs.ResetSourceLengthGets (); + read.File!.Tag!.Comment = "PathSave"; + var rendered = read.File.Render ().ToArray (); + + var save = saveAsync + ? await read.File.SaveToFileAsync ("/out.gif", fs) + : read.File.SaveToFile ("/out.gif", fs); + + Assert.IsTrue (save.IsSuccess, save.Error); + Assert.AreEqual (1, fs.SourceLengthGets); + var written = fs.Bytes ("/out.gif"); + CollectionAssert.AreEqual (rendered, written); + const string expected = "742A2C24C2F5A7CC72B01607DCB6B3517A46B7FD146388CF59F68A8AE175D287"; + Assert.AreEqual (expected, Convert.ToHexString (SHA256.HashData (written))); + } + + /// + /// The image descriptor through its terminator, plus the trailer, are one range. + /// An image block of 65535 leaves that range at one chunk. The hash is that comment edit's Render at 1322374a. + /// + [TestMethod] + [DataRow (false)] + [DataRow (true)] + public async Task GifPathSave_ImageRangeOfOneChunk_CopiesInChunks (bool saveAsync) + { + var (file, fs) = OpenEditedGif (65535); + const string expected = "685707F53F93F751577058C2EE4FB3B5AEFDC772DD11902075DC5ADD89089161"; + await AssertEditedRangeCopiedInChunks (file, fs, "/out.gif", saveAsync, 65561, expected); + } + + /// One image byte more makes that range one byte past a chunk. + [TestMethod] + [DataRow (false)] + [DataRow (true)] + public async Task GifPathSave_ImageRangeOneBytePastOneChunk_CopiesInChunks (bool saveAsync) + { + var (file, fs) = OpenEditedGif (65536); + const string expected = "9BC4E3D57E9C451D715CA2D1D26E68CFB543A01D0C087AD6C166480774E8C93B"; + await AssertEditedRangeCopiedInChunks (file, fs, "/out.gif", saveAsync, 65562, expected); + } + + [TestMethod] + [DoNotParallelize] + public void GifPathSave_AllocationStaysUnderTheCeilingWhileRenderGrows () + { + const int n = 1024 * 1024; + const long ceiling = 256 * 1024; + // Screen 13 + comment extension for "PathSave" 12 + trailer 1. + const int framing = 26; + var saves = new long[3]; + var renders = new long[3]; + for (var size = 0; size < 3; size++) { + var imageLength = n << size; + var (file, fs) = OpenEditedGif (imageLength); + var path = $"/out-{imageLength}.gif"; + var warm = file.SaveToFile (path, fs); + Assert.IsTrue (warm.IsSuccess, warm.Error); + _ = file.Render (); + + FileWriteResult save = default; + saves[size] = LeastAllocated (() => save = file.SaveToFile (path, fs)); + Assert.IsTrue (save.IsSuccess, save.Error); + Assert.AreEqual (imageLength + framing, fs.Bytes (path).Length); + Assert.IsLessThanOrEqualTo (ceiling, saves[size]); + + ReadOnlyMemory rendered = default; + renders[size] = LeastAllocated (() => rendered = file.Render ()); + GC.KeepAlive (rendered); + } + + var high = Math.Max (saves[0], Math.Max (saves[1], saves[2])); + var low = Math.Min (saves[0], Math.Min (saves[1], saves[2])); + Assert.IsLessThan (64 * 1024, high - low, $"path save allocated {saves[0]}, {saves[1]}, {saves[2]}"); + Assert.IsGreaterThanOrEqualTo (n, renders[2] - renders[0], $"render allocated {renders[0]} then {renders[2]}"); + } + + [TestMethod] + [DataRow ("A838D2A6E158A95650468B27AE71DADC92C08B08C5173C822A932E7B7703E774")] + public void BmpPathSave_BytesEqualRender (string expectedHash) => + AssertPathSaveMatchesRender (Bmp (4, 2), "bmp", expectedHash); + + /// + /// The file is a BMP header followed by pixels out to 80 KB. A path save copies that range in chunks. + /// + [TestMethod] + [DataRow (false)] + [DataRow (true)] + public async Task BmpPathSave_OverOneChunk_CopiesTheFileInChunks (bool saveAsync) + { + var data = HeaderAndTrailingBytes (Bmp (1, 1)); + await AssertWholeFileCopiedInChunks (data, "/in.bmp", "/out.bmp", saveAsync); + } + + [TestMethod] + [DataRow ("70D06D76319B1B57A94CE8A15C61DDBA97CAE09449EDCCFF98DDA08CBC790AF6")] + public void PcxPathSave_BytesEqualRender (string expectedHash) => + AssertPathSaveMatchesRender (Pcx (0, 0, 1, 1, planes: 1), "pcx", expectedHash); + + /// An 80 KB PCX is a header and the bytes after it. A path save copies that range in chunks. + [TestMethod] + [DataRow (false)] + [DataRow (true)] + public async Task PcxPathSave_OverOneChunk_CopiesTheFileInChunks (bool saveAsync) + { + var data = HeaderAndTrailingBytes (Pcx (0, 0, 1, 1, planes: 1)); + await AssertWholeFileCopiedInChunks (data, "/in.pcx", "/out.pcx", saveAsync); + } + + [TestMethod] + [DataRow ("P4", "pbm", "D4A32CD03B3F1505B9C4F1C75FA6486FCA66966838AC6CF05116F187D0B67F26")] + [DataRow ("P5", "pgm", "163DA6D87F525A13D835FACB08F325319D1B1A27EEB3449C357902F2475B9019")] + [DataRow ("P6", "ppm", "418B52874B4A321F1008AFE7BE2880BF8BE33DF6EA82B04FB122E0D0F902ED36")] + public void NetpbmPathSave_BytesEqualRender (string magic, string extension, string expectedHash) => + AssertPathSaveMatchesRender (NetpbmHeader (magic), extension, expectedHash); + + /// + /// An 80 KB Netpbm file is a header and the bytes after it. A path save copies that range in chunks. + /// + [TestMethod] + [DataRow ("P4", "pbm", false)] + [DataRow ("P4", "pbm", true)] + [DataRow ("P5", "pgm", false)] + [DataRow ("P5", "pgm", true)] + [DataRow ("P6", "ppm", false)] + [DataRow ("P6", "ppm", true)] + public async Task NetpbmPathSave_OverOneChunk_CopiesTheFileInChunks (string magic, string extension, bool saveAsync) + { + var data = HeaderAndTrailingBytes (NetpbmHeader (magic)); + await AssertWholeFileCopiedInChunks (data, "/in." + extension, "/out." + extension, saveAsync); + } + + [TestMethod] + [DataRow ("41E5A673AEAFEF7655FF3785442EF6EFB7469DAC0D9E86FE9E5840832FC8541F")] + public void SvgPathSave_BytesEqualRender (string expectedHash) => + AssertPathSaveMatchesRender (""u8.ToArray (), "svg", expectedHash); + + /// + /// The padding sits inside the root element, so the file stays an SVG and is longer than one chunk. + /// + [TestMethod] + [DataRow (false)] + [DataRow (true)] + public async Task SvgPathSave_OverOneChunk_CopiesTheFileInChunks (bool saveAsync) + { + await AssertWholeFileCopiedInChunks (SvgOfLength (BytesPastOneChunk), "/in.svg", "/out.svg", saveAsync); + } + + /// + /// A file of exactly one chunk used to be a single write. The path save still re-reads the source once. + /// + [TestMethod] + [DataRow ("tiff", false)] + [DataRow ("tiff", true)] + [DataRow ("dng", false)] + [DataRow ("dng", true)] + [DataRow ("bmp", false)] + [DataRow ("bmp", true)] + [DataRow ("pcx", false)] + [DataRow ("pcx", true)] + [DataRow ("pbm", false)] + [DataRow ("pbm", true)] + [DataRow ("pgm", false)] + [DataRow ("pgm", true)] + [DataRow ("ppm", false)] + [DataRow ("ppm", true)] + [DataRow ("svg", false)] + [DataRow ("svg", true)] + public async Task WholeFilePathSave_ExactChunk_RereadsTheSource (string format, bool saveAsync) + { + var data = WholeFile (format, ChunkBoundedFileSystem.MaxChunk); + await AssertWholeFileCopiedInChunks (data, "/in." + format, "/out." + format, saveAsync); + } + + /// One byte past a chunk is still copied from the source, not written as one buffer. + [TestMethod] + [DataRow ("tiff", false)] + [DataRow ("tiff", true)] + [DataRow ("dng", false)] + [DataRow ("dng", true)] + [DataRow ("bmp", false)] + [DataRow ("bmp", true)] + [DataRow ("pcx", false)] + [DataRow ("pcx", true)] + [DataRow ("pbm", false)] + [DataRow ("pbm", true)] + [DataRow ("pgm", false)] + [DataRow ("pgm", true)] + [DataRow ("ppm", false)] + [DataRow ("ppm", true)] + [DataRow ("svg", false)] + [DataRow ("svg", true)] + public async Task WholeFilePathSave_OneBytePastOneChunk_CopiesInChunks (string format, bool saveAsync) + { + var data = WholeFile (format, ChunkBoundedFileSystem.MaxChunk + 1); + await AssertWholeFileCopiedInChunks (data, "/in." + format, "/out." + format, saveAsync); + } + + /// + /// These formats copy one range and Render shares that buffer. + /// The path save of a 1, 2 and 4 MiB file stays under a fixed ceiling. + /// + [TestMethod] + [DoNotParallelize] + [DataRow ("tiff")] + [DataRow ("dng")] + [DataRow ("bmp")] + [DataRow ("pcx")] + [DataRow ("pbm")] + [DataRow ("pgm")] + [DataRow ("ppm")] + [DataRow ("svg")] + public void WholeFilePathSave_AllocationStaysUnderTheCeiling (string format) + { + const int n = 1024 * 1024; + const long ceiling = 256 * 1024; + var saves = new long[3]; + for (var size = 0; size < 3; size++) { + var length = n << size; + var data = WholeFile (format, length); + var fs = new ChunkBoundedFileSystem (data.Length + ChunkBoundedFileSystem.MaxChunk); + var source = "/in." + format; + var path = "/out-" + length + "." + format; + fs.Add (source, data); + fs.MaxRead = data.Length; + var read = StillImageFile.ReadFromFile (source, fs); + fs.MaxRead = ChunkBoundedFileSystem.MaxChunk; + Assert.IsTrue (read.IsSuccess, read.Error); + var warm = read.File!.SaveToFile (path, fs); + Assert.IsTrue (warm.IsSuccess, warm.Error); + + FileWriteResult save = default; + saves[size] = LeastAllocated (() => save = read.File.SaveToFile (path, fs)); + Assert.IsTrue (save.IsSuccess, save.Error); + Assert.AreEqual (length, fs.Bytes (path).Length); + Assert.IsLessThanOrEqualTo (ceiling, saves[size]); + } + + var high = Math.Max (saves[0], Math.Max (saves[1], saves[2])); + var low = Math.Min (saves[0], Math.Min (saves[1], saves[2])); + Assert.IsLessThan (64 * 1024, high - low, $"{format} allocated {saves[0]}, {saves[1]}, {saves[2]}"); + } + + /// + /// These formats have no tag, so a field edit and Clear cannot run. + /// A path save writes the original bytes. The hashes are those files at 1322374a. + /// + [TestMethod] + [DataRow ("tiff", "59753EFEE53644237F9F0F4299A3B7178C949D9447626418365C7D4E15005DBC")] + [DataRow ("dng", "96507B9AA0101B7949BE6B6E9761FE0B57B58BB977DED0232CD9096A1374BE5C")] + [DataRow ("bmp", "A838D2A6E158A95650468B27AE71DADC92C08B08C5173C822A932E7B7703E774")] + [DataRow ("pcx", "70D06D76319B1B57A94CE8A15C61DDBA97CAE09449EDCCFF98DDA08CBC790AF6")] + [DataRow ("pbm", "D4A32CD03B3F1505B9C4F1C75FA6486FCA66966838AC6CF05116F187D0B67F26")] + [DataRow ("pgm", "163DA6D87F525A13D835FACB08F325319D1B1A27EEB3449C357902F2475B9019")] + [DataRow ("ppm", "418B52874B4A321F1008AFE7BE2880BF8BE33DF6EA82B04FB122E0D0F902ED36")] + [DataRow ("svg", "41E5A673AEAFEF7655FF3785442EF6EFB7469DAC0D9E86FE9E5840832FC8541F")] + public void WholeFilePathSave_HasNoTag_AndSavedBytesEqualTheOriginal (string format, string expectedHash) + { + var data = OriginalWholeFile (format); + var fs = new MockFileSystem (); + var source = "/in." + format; + fs.AddFile (source, data); + var read = StillImageFile.ReadFromFile (source, fs); + Assert.IsTrue (read.IsSuccess, read.Error); + Assert.IsNull (read.File!.Tag, format); + + var save = read.File.SaveToFile ("/out." + format, fs); + + Assert.IsTrue (save.IsSuccess, save.Error); + var written = fs.ReadAllBytes ("/out." + format); + CollectionAssert.AreEqual (data, written, format); + CollectionAssert.AreEqual (read.File.Render ().ToArray (), written, format); + Assert.AreEqual (expectedHash, Convert.ToHexString (SHA256.HashData (written)), format); + } + + static async Task AssertEditedRangeCopiedInChunks ( + StillImageFile file, + ChunkBoundedFileSystem fs, + string destination, + bool saveAsync, + int writtenLength, + string expectedHash) + { + fs.ResetSourceLengthGets (); + var rendered = file.Render ().ToArray (); + + var save = saveAsync + ? await file.SaveToFileAsync (destination, fs) + : file.SaveToFile (destination, fs); + + Assert.IsTrue (save.IsSuccess, save.Error); + Assert.AreEqual (1, fs.SourceLengthGets); + var written = fs.Bytes (destination); + Assert.AreEqual (writtenLength, written.Length); + CollectionAssert.AreEqual (rendered, written); + Assert.AreEqual (expectedHash, Convert.ToHexString (SHA256.HashData (written))); + } + + static byte[] OriginalWholeFile (string format) => format switch { + "tiff" => TiffHeader ("tiff"), + "dng" => TiffHeader ("dng"), + "bmp" => Bmp (4, 2), + "pcx" => Pcx (0, 0, 1, 1, planes: 1), + "pbm" => NetpbmHeader ("P4"), + "pgm" => NetpbmHeader ("P5"), + "ppm" => NetpbmHeader ("P6"), + _ => ""u8.ToArray () + }; + + static byte[] WholeFile (string format, int length) => format switch { + "tiff" => HeaderAndTrailingBytes (TiffHeader ("tiff"), length), + "dng" => HeaderAndTrailingBytes (TiffHeader ("dng"), length), + "bmp" => HeaderAndTrailingBytes (Bmp (1, 1), length), + "pcx" => HeaderAndTrailingBytes (Pcx (0, 0, 1, 1, planes: 1), length), + "pbm" => HeaderAndTrailingBytes (NetpbmHeader ("P4"), length), + "pgm" => HeaderAndTrailingBytes (NetpbmHeader ("P5"), length), + "ppm" => HeaderAndTrailingBytes (NetpbmHeader ("P6"), length), + _ => SvgOfLength (length) + }; + + static byte[] SvgOfLength (int length) + { + var open = ""u8; + var close = ""u8; + var data = new byte[length]; + open.CopyTo (data); + Array.Fill (data, (byte)' ', open.Length, length - open.Length - close.Length); + close.CopyTo (data.AsSpan (length - close.Length)); + return data; + } + + const int BytesPastOneChunk = 80 * 1024; + + static byte[] HeaderAndTrailingBytes (byte[] header, int length = BytesPastOneChunk) + { + var data = new byte[length]; + header.CopyTo (data, 0); + return data; + } + + static byte[] NetpbmHeader (string magic) => magic switch { + "P5" => "P5\n1 1\n"u8.ToArray (), + "P6" => "P6\n1 1\n"u8.ToArray (), + _ => "P4\n1 1\n"u8.ToArray () + }; + + static void AssertPathSaveMatchesRender (byte[] data, string extension, string expectedHash) + { + var fs = new MockFileSystem (); + var source = "/in." + extension; + var destination = "/out." + extension; + fs.AddFile (source, data); + var read = StillImageFile.ReadFromFile (source, fs); + Assert.IsTrue (read.IsSuccess, read.Error); + var rendered = read.File!.Render ().ToArray (); + + var save = read.File.SaveToFile (destination, fs); + + Assert.IsTrue (save.IsSuccess, save.Error); + var written = fs.ReadAllBytes (destination); + CollectionAssert.AreEqual (rendered, written, extension); + Assert.AreEqual (expectedHash, Convert.ToHexString (SHA256.HashData (written)), extension); + } + + static async Task AssertWholeFileCopiedInChunks (byte[] data, string source, string destination, bool saveAsync) + { + var fs = new ChunkBoundedFileSystem (data.Length + ChunkBoundedFileSystem.MaxChunk); + fs.Add (source, data); + fs.MaxRead = data.Length; + var read = StillImageFile.ReadFromFile (source, fs); + fs.MaxRead = ChunkBoundedFileSystem.MaxChunk; + Assert.IsTrue (read.IsSuccess, read.Error); + fs.ResetSourceLengthGets (); + + var save = saveAsync + ? await read.File!.SaveToFileAsync (destination, fs) + : read.File!.SaveToFile (destination, fs); + + Assert.IsTrue (save.IsSuccess, save.Error); + Assert.AreEqual (1, fs.SourceLengthGets); + CollectionAssert.AreEqual (data, fs.Bytes (destination)); + } + + static (StillImageFile File, ChunkBoundedFileSystem Fs) OpenEditedGif (int imageLength) + { + var data = Concat (GifScreen (1, 1, flags: 0), GifComment ("Old"), GifImage (imageLength), [0x3B]); + var fs = new ChunkBoundedFileSystem (data.Length + ChunkBoundedFileSystem.MaxChunk); + fs.Add ("/in.gif", data); + fs.MaxRead = data.Length; + var read = StillImageFile.ReadFromFile ("/in.gif", fs); + fs.MaxRead = ChunkBoundedFileSystem.MaxChunk; + Assert.IsTrue (read.IsSuccess, read.Error); + read.File!.Tag!.Comment = "PathSave"; + return (read.File, fs); + } + + static (StillImageFile File, ChunkBoundedFileSystem Fs) OpenEditedPng (int payloadLength) + { + var data = Concat ( + PngSignature, + PngChunk ("IHDR", [0, 0, 0, 2, 0, 0, 0, 3, 8, 0, 0, 0, 0]), + Text ("Title", "Old"), + PngChunk ("IDAT", new byte[payloadLength]), + PngChunk ("IEND", [])); + var fs = new ChunkBoundedFileSystem (data.Length + ChunkBoundedFileSystem.MaxChunk); + fs.Add ("/in.png", data); + fs.MaxRead = data.Length; + var read = StillImageFile.ReadFromFile ("/in.png", fs); + fs.MaxRead = ChunkBoundedFileSystem.MaxChunk; + Assert.IsTrue (read.IsSuccess, read.Error); + read.File!.Tag!.Title = "PathSave"; + return (read.File, fs); + } + + static (StillImageFile File, ChunkBoundedFileSystem Fs) OpenEditedScan (int scanLength) + { + var scan = new byte[scanLength]; + Array.Fill (scan, (byte)0x11); + var data = Concat ( + [0xFF, 0xD8], + JpegSegment (0xFE, "Old"u8.ToArray ()), + JpegSegment (0xC0, [0x08, 0x00, 0x01, 0x00, 0x01, 0x01, 0x01, 0x11, 0x00]), + JpegSegment (0xDA, [0x01, 0x01, 0x00, 0x00, 0x3F, 0x00]), + scan, + [0xFF, 0xD9]); + var fs = new ChunkBoundedFileSystem (data.Length + ChunkBoundedFileSystem.MaxChunk); + fs.Add ("/in.jpg", data); + fs.MaxRead = data.Length; + var read = StillImageFile.ReadFromFile ("/in.jpg", fs); + fs.MaxRead = ChunkBoundedFileSystem.MaxChunk; + Assert.IsTrue (read.IsSuccess, read.Error); + read.File!.Tag!.Comment = "PathSave"; + return (read.File, fs); + } + + static long LeastAllocated (Action action) => Bounds.LeastAllocated (action); + + static byte[] JpegInput (string op) => op switch { + "exif-comment" => Jpeg (JpegExif (ExifTiff ([(0x010F, "Canon")], [])), JpegSegment (0xFE, "Old"u8.ToArray ())), + "xmp-comment" => Jpeg (JpegXmp (XmpPacket (Alt ("exif:UserComment", "Old")))), + "mpf-comment" => MpfJpeg (JpegSegment (0xFE, "Old"u8.ToArray ()), [], out _), + _ => Jpeg (JpegSegment (0xFE, "Old"u8.ToArray ())) + }; + + static byte[] TiffHeader (string format) => format == "dng" ? TiffImage (2, 3, dng: true) : TiffImage (2, 3); + + static byte[] GifInput (string op) => op switch { + "clear" => Gif (GifComment ("Old")), + "xmp-comment" => Gif (GifXmp (XmpPacket (Alt ("exif:UserComment", "Old")))), + _ => Gif (GifComment ("Old")) + }; + + static void ApplyGif (StillImageFile file, string op) + { + if (op is "comment" or "xmp-comment") + file.Tag!.Comment = "PathSave"; + else if (op == "comment-same") + file.Tag!.Comment = file.Tag.Comment; + else if (op == "comment-null") + file.Tag!.Comment = null; + else if (op == "clear") + file.Tag!.Clear (); + } + + static byte[] GifImage (int length) + { + var data = new byte[length]; + data[0] = 0x2C; + data[6] = 1; + data[8] = 1; + var at = 11; + var remain = length - 12; + while (remain > 0) { + var take = Math.Min (255, remain - 1); + if (take <= 0) + break; + data[at++] = (byte)take; + at += take; + remain -= 1 + take; + } + + return data; + } + + static byte[] PngInput (string op) => op switch { + "noop" or "clear" => Png (Text ("Title", "Old"), Text ("Comment", "Old")), + "title" => Png (Text ("Title", "Old")), + "xmp-title" => Png (Xmp (XmpPacket (Alt ("dc:title", "Old")))), + "exif-artist" => Png ( + PngChunk ("eXIf", ExifTiff ([(0x010F, "Canon"), (0x013B, "Jane")], [])), + Text ("Author", "Jane")), + "raw-title" => Png (RawProfile ("xmp", "abcd"u8.ToArray ()), Text ("Title", "Old")), + "idot-title" => IdotPng (), + "idot-comment" => IdotPng (Text ("Comment", "Old")), + _ => Png (Text ("Comment", "Old")) + }; + + static byte[] IdotPng (params byte[][] between) => + Concat ( + PngSignature, + PngChunk ("IHDR", [0, 0, 0, 2, 0, 0, 0, 3, 8, 0, 0, 0, 0]), + Text ("Title", "Old"), + PngChunk ("iDOT", new byte[28]), + Concat (between), + PngChunk ("IDAT", [0x78, 0x9C, 0x03, 0x00]), + PngChunk ("IEND", [])); + + static void ApplyPng (StillImageFile file, string op) + { + if (op is "title" or "xmp-title" or "raw-title" or "idot-title") + file.Tag!.Title = "PathSave"; + else if (op is "comment" or "idot-comment") + file.Tag!.Comment = op == "idot-comment" ? "A longer comment" : "PathSave"; + else if (op == "comment-same") + file.Tag!.Comment = file.Tag.Comment; + else if (op == "comment-null") + file.Tag!.Comment = null; + else if (op == "exif-artist") + file.Tag!.Artist = "New"; + else if (op == "clear") + file.Tag!.Clear (); + } + + static void Apply (StillImageFile file, string op) + { + if (op is "comment" or "exif-comment" or "xmp-comment" or "mpf-comment") + file.Tag!.Comment = "PathSave"; + else if (op == "comment-same") + file.Tag!.Comment = file.Tag.Comment; + else if (op == "comment-null") + file.Tag!.Comment = null; + else if (op == "clear") + file.Tag!.Clear (); + } +} diff --git a/tests/TagLibSharp2.Tests/Image/ImagePlanTests.cs b/tests/TagLibSharp2.Tests/Image/ImagePlanTests.cs new file mode 100644 index 00000000..dad40539 --- /dev/null +++ b/tests/TagLibSharp2.Tests/Image/ImagePlanTests.cs @@ -0,0 +1,253 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Runtime.InteropServices; +using System.Text; +using TagLibSharp2.Core; +using TagLibSharp2.Image; +using TagLibSharp2.Image.Exif; +using TagLibSharp2.Image.Gif; +using TagLibSharp2.Image.Png; +using TagLibSharp2.Image.Svg; +using TagLibSharp2.Image.Tiff; +using TagLibSharp2.Tests.Core; +using TagLibSharp2.Tests.Kit; +using static TagLibSharp2.Tests.Image.ImageTestBuilder; + +namespace TagLibSharp2.Tests.Image; + +/// Image plan bounds: empty pieces, ranges past , and the bytes beside a cut. +[TestClass] +[TestCategory ("Unit")] +public class ImagePlanTests +{ + [TestMethod] + public void ImagePlan_EmptyAppendsAndAZeroCopy_AddNothing () + { + var plan = new ImagePlan (); + plan.Add (ReadOnlySpan.Empty); + plan.Add ([]); + plan.Copy (5, 0); + + Assert.AreEqual (0, plan.Length); + Assert.AreEqual (0, plan.SourceEnd); + } + + [TestMethod] + public void ImagePlan_NegativeCopy_Throws () + { + var plan = new ImagePlan (); + + Assert.ThrowsExactly (() => plan.Copy (0, -1)); + } + + [TestMethod] + public void ImagePlan_LengthPastInt32_ThrowsBeforeAllocatingANegativeArray () + { + var plan = new ImagePlan (); + plan.Copy (0, (long)int.MaxValue + 1); + + var error = Assert.ThrowsExactly (() => plan.Materialize ([])); + + Assert.AreEqual ("Arithmetic operation resulted in an overflow.", error.Message); + } + + [TestMethod] + public void ImagePlan_HeldOffsetPastInt32_ThrowsBeforeSlicing () + { + var plan = new ImagePlan (); + plan.Copy ((long)int.MaxValue + 1, 1); + using var destination = new MemoryStream (); + var chunk = StreamCopy.Rent (); + try { + var error = Assert.ThrowsExactly (() => plan.Write (null, new byte[1], destination, chunk)); + Assert.AreEqual ("Arithmetic operation resulted in an overflow.", error.Message); + } finally { + StreamCopy.Return (chunk); + } + } + + [TestMethod] + public void ImagePlan_LengthAtTwoToTheThirtyTwo_ThrowsBeforeAllocating () + { + var plan = new ImagePlan (); + plan.Copy (0, int.MaxValue); + plan.Copy (0, int.MaxValue); + plan.Copy (0, 2); + + Assert.AreEqual (1L << 32, plan.Length); + var error = Assert.ThrowsExactly (() => plan.Materialize ([])); + Assert.AreEqual ("Arithmetic operation resulted in an overflow.", error.Message); + } + + [TestMethod] + public void ImagePlan_RangeOfTwoToTheThirtyTwo_ThrowsBeforeAllocating () + { + var plan = new ImagePlan (); + plan.Copy (0, int.MaxValue); + plan.Copy (0, int.MaxValue); + plan.Copy (0, 2); + + var error = Assert.ThrowsExactly (() => plan.MaterializeRange (0, 1L << 32, [])); + Assert.AreEqual ("Arithmetic operation resulted in an overflow.", error.Message); + } + + [TestMethod] + public void ImagePlan_HeldLengthPastInt32_ThrowsBeforeSlicing () + { + var plan = new ImagePlan (); + plan.Copy (0, (long)int.MaxValue + 1); + using var destination = new MemoryStream (); + var chunk = StreamCopy.Rent (); + try { + var error = Assert.ThrowsExactly (() => plan.Write (null, new byte[1], destination, chunk)); + Assert.AreEqual ("Arithmetic operation resulted in an overflow.", error.Message); + } finally { + StreamCopy.Return (chunk); + } + } + + [TestMethod] + public void ImagePlan_WindowWhosePiecePassesInt32_ThrowsBeforeSlicing () + { + var plan = new ImagePlan (); + plan.Copy (0, (long)int.MaxValue - 5); + plan.Copy ((long)int.MaxValue - 5, 20); + + var error = Assert.ThrowsExactly (() => plan.MaterializeRange ((long)int.MaxValue + 1, 5, [])); + Assert.AreEqual ("Arithmetic operation resulted in an overflow.", error.Message); + } + + [TestMethod] + public void ImagePlan_MaterializeShared_ReturnsTheSourceOnlyForTheWholeFile () + { + var source = new byte[] { 1, 2, 3, 4 }; + var whole = new ImagePlan (); + whole.Copy (0, 2); + whole.Copy (2, 2); + Assert.IsTrue (MemoryMarshal.TryGetArray (whole.MaterializeShared (source), out ArraySegment shared)); + Assert.AreSame (source, shared.Array); + + var half = new ImagePlan (); + half.Copy (0, 2); + CollectionAssert.AreEqual (new byte[] { 1, 2 }, half.MaterializeShared (source).ToArray ()); + + var literal = new ImagePlan (); + literal.Add (new byte[] { 9, 9, 9, 9 }); + CollectionAssert.AreEqual (new byte[] { 9, 9, 9, 9 }, literal.MaterializeShared (source).ToArray ()); + + var shifted = new ImagePlan (); + shifted.Copy (1, source.Length); + Assert.ThrowsExactly (() => shifted.MaterializeShared (source)); + } + + [TestMethod] + public void ImagePlan_MaterializeRange_HonoursEmptyExactAndPieceBoundaries () + { + var source = new byte[] { 1, 2, 3, 4 }; + var plan = new ImagePlan (); + plan.Copy (0, 4); + plan.Add ([5, 6]); + + Assert.AreEqual (0, plan.MaterializeRange (0, 0, source).Length); + Assert.AreEqual (0, plan.MaterializeRange (plan.Length, 0, source).Length); + CollectionAssert.AreEqual (new byte[] { 1, 2, 3, 4, 5, 6 }, plan.MaterializeRange (0, 6, source)); + CollectionAssert.AreEqual (new byte[] { 1 }, plan.MaterializeRange (0, 1, source)); + CollectionAssert.AreEqual (new byte[] { 2, 3 }, plan.MaterializeRange (1, 2, source)); + CollectionAssert.AreEqual (new byte[] { 5, 6 }, plan.MaterializeRange (4, 2, source)); + Assert.ThrowsExactly (() => plan.MaterializeRange (-1, 1, source)); + Assert.ThrowsExactly (() => plan.MaterializeRange (0, -1, source)); + Assert.ThrowsExactly (() => plan.MaterializeRange (7, 0, source)); + Assert.ThrowsExactly (() => plan.MaterializeRange (0, 7, source)); + Assert.ThrowsExactly (() => plan.MaterializeRange (4, 3, source)); + } + + [TestMethod] + public void ImagePlan_CutAndSplice_KeepBytesOutsideTheSpan () + { + var source = new byte[] { 1, 2, 3, 4, 5, 6 }; + var plan = new ImagePlan (); + plan.Copy (0, 3); + plan.Copy (3, 3); + plan.Cut (0, 0); + plan.Cut (3, 2); + CollectionAssert.AreEqual (new byte[] { 1, 2, 3, 6 }, plan.Materialize (source)); + + var spliced = new ImagePlan (); + spliced.Copy (0, 4); + spliced.Splice (0, 0, []); + spliced.Splice (1, 2, [9, 8]); + CollectionAssert.AreEqual (new byte[] { 1, 9, 8, 4 }, spliced.Materialize (source)); + Assert.ThrowsExactly (() => spliced.Cut (-1, 1)); + Assert.ThrowsExactly (() => spliced.Cut (0, -1)); + Assert.ThrowsExactly (() => spliced.Splice (0, 1, [1, 2])); + Assert.ThrowsExactly (() => spliced.Splice (4, 1, [1])); + } + + [TestMethod] + public void ImagePlan_LiteralSpliceAndExactEndCut_KeepTheBytesBesideTheEdit () + { + var source = new byte[] { 1, 2, 3, 4 }; + var literal = new ImagePlan (); + literal.Add ([1, 2, 3, 4, 5]); + literal.Splice (1, 2, [9, 8]); + CollectionAssert.AreEqual (new byte[] { 1, 9, 8, 4, 5 }, literal.Materialize (source)); + + var across = new ImagePlan (); + across.Copy (0, 4); + across.Add ([5, 6]); + CollectionAssert.AreEqual (new byte[] { 2, 3, 4, 5, 6 }, across.MaterializeRange (1, 5, source)); + + var second = new ImagePlan (); + second.Add ([1, 2]); + second.Add ([3, 4, 5, 6, 7]); + CollectionAssert.AreEqual (new byte[] { 2, 3, 4 }, second.MaterializeRange (1, 3, [])); + + var cut = new ImagePlan (); + cut.Copy (0, 4); + cut.Cut (8, 0); + cut.Cut (0, 1); + cut.Cut (0, cut.Length); + Assert.AreEqual (0, cut.Length); + + var end = new ImagePlan (); + end.Copy (0, 4); + end.Splice (0, 2, [7, 7]); + end.Splice (2, 2, [6, 6]); + CollectionAssert.AreEqual (new byte[] { 7, 7, 6, 6 }, end.Materialize (source)); + + var over = new ImagePlan (); + over.Copy (0, 4); + var error = Assert.ThrowsExactly (() => over.MaterializeRange (1, 4, source)); + Assert.AreEqual ("start", error.ParamName); + Assert.ThrowsExactly (() => over.Cut (1, 4)); + Assert.ThrowsExactly (() => over.Splice (1, 4, [9, 9, 9, 9])); + Assert.ThrowsExactly (() => over.Splice (-1, 1, [9])); + Assert.ThrowsExactly (() => over.Splice (-5, 6, new byte[6])); + Assert.ThrowsExactly (() => over.Cut (-1, 1)); + } + + [TestMethod] + public void ImagePlan_WriteFromHeld_WritesTheRangeAndTheLiteral_AndACancelledTokenWritesNothing () + { + var source = new byte[] { 1, 2, 3, 4 }; + var plan = new ImagePlan (); + plan.Copy (1, 2); + plan.Add ([9]); + using var destination = new MemoryStream (); + var chunk = StreamCopy.Rent (); + try { + plan.Write (null, source, destination, chunk); + CollectionAssert.AreEqual (new byte[] { 2, 3, 9 }, destination.ToArray ()); + + var blocked = new ImagePlan (); + blocked.Add ([1, 2, 3]); + using var second = new MemoryStream (); + Assert.ThrowsExactly (() => + blocked.Write (null, [], second, chunk, new CancellationToken (true))); + Assert.AreEqual (0, second.Length); + } finally { + StreamCopy.Return (chunk); + } + } +} diff --git a/tests/TagLibSharp2.Tests/Image/ImageRenderShareTests.cs b/tests/TagLibSharp2.Tests/Image/ImageRenderShareTests.cs new file mode 100644 index 00000000..c9a82239 --- /dev/null +++ b/tests/TagLibSharp2.Tests/Image/ImageRenderShareTests.cs @@ -0,0 +1,84 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Runtime.InteropServices; +using TagLibSharp2.Image; +using TagLibSharp2.Tests.Kit; +using static TagLibSharp2.Tests.Image.ImageTestBuilder; + +namespace TagLibSharp2.Tests.Image; + +/// +/// An unedited render is the buffer the file already holds. Two renders share that one array. An edit allocates +/// its own. +/// +[TestClass] +[TestCategory ("Unit")] +public class ImageRenderShareTests +{ + public static IEnumerable Formats { get; } = [ + ["jpeg"], ["png"], ["gif"], ["tiff"], ["dng"], ["bmp"], ["pcx"], ["netpbm"], ["svg"], + ]; + + [TestMethod] + [DynamicData (nameof (Formats))] + public void UneditedRender_SharesOneBuffer (string format) + { + var opened = StillImageFile.Read (Small (format)); + Assert.IsTrue (opened.IsSuccess, opened.Error); + var file = opened.File!; + + Assert.IsTrue (MemoryMarshal.TryGetArray (file.Render (), out ArraySegment first), format); + Assert.IsTrue (MemoryMarshal.TryGetArray (file.Render (), out ArraySegment second), format); + + Assert.AreSame (first.Array, second.Array, format); + Assert.AreEqual (0, first.Offset, format); + Assert.AreEqual (Small (format).Length, first.Count, format); + } + + [TestMethod] + [DataRow ("jpeg")] + [DataRow ("png")] + [DataRow ("gif")] + public void EditedRender_AllocatesItsOwnBuffer (string format) + { + var opened = StillImageFile.Read (Small (format)); + Assert.IsTrue (opened.IsSuccess, opened.Error); + var file = opened.File!; + Assert.IsTrue (MemoryMarshal.TryGetArray (file.Render (), out ArraySegment original), format); + + file.Tag!.Comment = "edited"; + var edited = file.Render (); + + Assert.IsTrue (MemoryMarshal.TryGetArray (edited, out ArraySegment copy), format); + Assert.AreNotSame (original.Array, copy.Array, format); + Assert.IsFalse (edited.Span.SequenceEqual (original.AsSpan ()), format); + } + + // A 256 KiB BMP. The second render of an unedited file must not allocate another copy of it. + [TestMethod] + public void UneditedRender_OfALargeFile_StaysUnderThePlan () + { + var opened = StillImageFile.Read (Bmp (2, 3, length: 256 * 1024)); + Assert.IsTrue (opened.IsSuccess, opened.Error); + var file = opened.File!; + _ = file.Render (); + + // Measured: the plan for the whole file, and no copy of the 262,144 bytes. + var allocated = Bounds.AssertAllocatesAtMost (216, () => _ = file.Render (), "second render of a 256 KiB BMP"); + Assert.AreEqual (216, allocated); + } + + static byte[] Small (string format) => format switch { + "jpeg" => Jpeg (), + "png" => Png (), + "gif" => Gif (), + "tiff" => TiffImage (2, 3), + "dng" => TiffImage (2, 3, dng: true), + "bmp" => Bmp (4, 2), + "pcx" => Pcx (0, 0, 1, 1, planes: 1), + "netpbm" => "P4\n1 1\n"u8.ToArray (), + "svg" => ""u8.ToArray (), + _ => throw new InvalidOperationException (format) + }; +} diff --git a/tests/TagLibSharp2.Tests/Image/ImageSaveContractTests.cs b/tests/TagLibSharp2.Tests/Image/ImageSaveContractTests.cs new file mode 100644 index 00000000..6ec27b47 --- /dev/null +++ b/tests/TagLibSharp2.Tests/Image/ImageSaveContractTests.cs @@ -0,0 +1,208 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Buffers.Binary; +using System.IO.Compression; +using System.Text; +using TagLibSharp2.Core; +using TagLibSharp2.Image; +using TagLibSharp2.Tests.Core; +using static TagLibSharp2.Tests.Image.ImageTestBuilder; + +namespace TagLibSharp2.Tests.Image; + +/// What a save keeps: every byte it does not edit, the bytes after the image, byte identity of a no-op save, and refusals with their own reason. +[TestClass] +[TestCategory ("Unit")] +public partial class ImageSaveContractTests +{ + [TestMethod] + public void SaveToFile_WhenTheContainerCannotBeUpdated_FailsAndDoesNotWrite () + { + var data = Concat (PngSignature, PngChunk ("IHDR", PngHeader (1, 1, 8, 0)), Text ("Title", "Door")); + var fs = new MockFileSystem (); + fs.AddFile ("/photo.png", data); + var file = Open (data, "photo.png"); + file.Tag!.Title = "Other"; + var wrote = file.SaveToFile ("/photo.png", fs); + Assert.IsFalse (wrote.IsSuccess, wrote.Error); + CollectionAssert.AreEqual (data, fs.ReadAllBytes ("/photo.png")); + CollectionAssert.AreEqual (data, file.Render ().ToArray (), "Render returns the unchanged file"); + Assert.AreEqual ("Other", file.Tag.Title); + + var asyncWrote = file.SaveToFileAsync ("/photo.png", fs).GetAwaiter ().GetResult (); + Assert.IsFalse (asyncWrote.IsSuccess, asyncWrote.Error); + CollectionAssert.AreEqual (data, fs.ReadAllBytes ("/photo.png")); + } + + [TestMethod] + public void FormatsWithoutATextStore_KeepTheOriginalBytes () + { + AssertNoStore (Bmp (4, 2), "a.bmp"); + AssertNoStore (Pcx (0, 0, 1, 1, planes: 1), "a.pcx"); + AssertNoStore (Encoding.ASCII.GetBytes ("P4\n1 1\n"), "a.pbm"); + AssertNoStore (TiffImage (2, 3), "a.tif"); + AssertNoStore (TiffImage (2, 3), "a.dng"); + AssertNoStore (Encoding.UTF8.GetBytes (""), "a.svg"); + } + + static void AssertNoStore (byte[] data, string name) + { + var file = Open (data, name); + Assert.IsNull (file.Tag); + CollectionAssert.AreEqual (data, file.Render ().ToArray ()); + } + + static readonly (string Name, byte[] Bytes)[] Trailers = [ + ("zip", Concat ("PK\u0003\u0004"u8.ToArray (), "appended-archive-bytes......"u8.ToArray ())), + ("text", "TAIL"u8.ToArray ()), + ("zeros", new byte[100]), + ("one", [0x00]), + ("chunk-shaped", PngChunk ("tEXt", Concat ("Title"u8.ToArray (), [0], "after IEND"u8.ToArray ()))), + ]; + + static readonly (string Name, Func Build, string File)[] Images = [ + ("png", () => Png (Text ("Title", "Old"), Text ("Comment", "Old")), "a.png"), + ("gif", () => Gif (GifComment ("Old")), "a.gif"), + ("jpeg", () => Jpeg (JpegSegment (0xFE, "Old"u8.ToArray ())), "a.jpg"), + ]; + + static readonly (string Name, Action Apply)[] Edits = [ + ("title", t => t.Title = "New"), + ("comment", t => t.Comment = "New"), + ("null", t => t.Comment = null), + ("clear", t => t.Clear ()), + ]; + + public static IEnumerable TrailerCases () => + from image in Images + from trailer in Trailers + from edit in Edits + select new object[] { image.Name, trailer.Name, edit.Name }; + + [TestMethod] + [DynamicData (nameof (TrailerCases))] + public void Save_KeepsTheBytesAfterTheImage (string image, string trailer, string edit) + { + var (_, build, name) = Images.Single (i => i.Name == image); + var tail = Trailers.Single (t => t.Name == trailer).Bytes; + var input = Concat (build (), tail); + var file = Open (input, name); + Edits.Single (e => e.Name == edit).Apply (file.Tag!); + + var output = file.Render ().ToArray (); + + CollectionAssert.AreEqual (tail, output.AsSpan (output.Length - tail.Length).ToArray (), $"{image} {edit} lost the {trailer} trailer"); + var reread = Open (output, name); + if (edit == "clear" || edit == "null") + Assert.IsNull (reread.Tag!.Comment); + else if (edit == "comment") + Assert.AreEqual ("New", reread.Tag!.Comment); + if (image == "png" && edit == "title") + Assert.AreEqual ("New", reread.Tag!.Title); + Assert.IsTrue (file.SaveToFile ("/out" + name, new MockFileSystem ()).IsSuccess); + } + + [TestMethod] + public void Png_AChunkAfterIend_IsNotReadOrEdited () + { + var after = Text ("Title", "after IEND"); + var input = Concat (Png (Text ("Title", "Before")), after); + var file = Open (input, "a.png"); + Assert.AreEqual ("Before", file.Tag!.Title); + + file.Tag.Clear (); + var output = file.Render ().ToArray (); + + Assert.IsTrue (output.AsSpan ().EndsWith (after)); + Assert.IsNull (Open (output, "a.png").Tag!.Title); + } + + [TestMethod] + public void Png_WithoutIend_RefusesTheSaveWithItsOwnReason () + { + var png = Png (Text ("Title", "Old")); + var truncated = png.AsSpan (0, png.Length - 12).ToArray (); + var file = Open (truncated, "a.png"); + file.Tag!.Title = "New"; + + var result = file.SaveToFile ("/a.png", new MockFileSystem ()); + + Assert.IsFalse (result.IsSuccess); + StringAssert.Contains (result.Error, "IEND"); + CollectionAssert.AreEqual (truncated, file.Render ().ToArray ()); + } + + [TestMethod] + [DynamicData (nameof (ImageClearTests.ClearCases), typeof (ImageClearTests))] + public void FieldEdit_KeepsEveryOtherBlockByteForByte (string format, string carrier, byte[] input, byte[] block, bool dropped) + { + _ = dropped; + var name = "a." + (format == "jpeg" ? "jpg" : format); + var file = Open (input, name); + // PNG Year has no copy in XMP or Exif (a Comment edit also changes Exif UserComment); GIF and JPEG store + // only the comment. + if (format == "png") + file.Tag!.Year = "2024"; + else + file.Tag!.Comment = "edited"; + + var output = file.Render ().ToArray (); + + Assert.IsTrue (output.AsSpan ().IndexOf (block) >= 0, $"{format} {carrier} lost on a field edit"); + var reread = Open (output, name); + Assert.AreEqual (format == "png" ? "2024" : "edited", format == "png" ? reread.Tag!.Year : reread.Tag!.Comment); + } + + [TestMethod] + public void NoOpSave_IsByteIdentical_ForEveryRewriter () + { + foreach (var (name, build, file) in Images) { + var input = Concat (build (), "TAIL"u8.ToArray ()); + var image = Open (input, file); + image.Tag!.Comment = image.Tag.Comment; + image.Tag.Title = image.Tag.Title; + CollectionAssert.AreEqual (input, image.Render ().ToArray (), name); + } + } + + // A container whose blocks cannot be walked refuses the save, and the reason names the format: a GIF block with + // an unknown introducer, and a JPEG whose marker list runs into bytes that are not a marker. + [TestMethod] + [DataRow ("gif", false)] + [DataRow ("jpeg", true)] + public void UnspliceableSave_NamesTheFormat (string format, bool saveAsync) + { + var gif = Gif (GifComment ("c")); + gif[^1] = 0x99; + var jpeg = Concat ([0xFF, 0xD8], JpegSegment (0xFE, "c"u8.ToArray ()), JpegSegment (0xC0, [8, 0, 1, 0, 1, 1, 1, 0x11, 0]), [0x00, 0x01]); + var name = format == "gif" ? "a.gif" : "a.jpg"; + var file = Open (format == "gif" ? gif : jpeg, name); + file.Tag!.Comment = "x"; + + var result = saveAsync ? file.SaveToFileAsync ("/" + name, new MockFileSystem ()).GetAwaiter ().GetResult () : file.SaveToFile ("/" + name, new MockFileSystem ()); + + Assert.IsFalse (result.IsSuccess); + StringAssert.Contains (result.Error, format.ToUpperInvariant ()); + } + + static byte[] IdotPng (params byte[][] between) => + Concat (PngSignature, PngChunk ("IHDR", [0, 0, 0, 2, 0, 0, 0, 3, 8, 0, 0, 0, 0]), Text ("Title", "Old"), + PngChunk ("iDOT", new byte[28]), Concat (between), PngChunk ("IDAT", [0x78, 0x9C, 0x03, 0x00]), PngChunk ("IEND", [])); + + [TestMethod] + public void Png_AppleIdot_IsKeptOnlyWhileItStillPointsAtTheImageData () + { + // New text goes before iDOT, so the distance from iDOT to IDAT is unchanged and iDOT stays. + var file = Open (IdotPng (), "a.png"); + file.Tag!.Title = "New"; + Assert.IsTrue (PngChunks (file.Render ().ToArray ()).Exists (c => c.Type == "iDOT")); + + // A changed chunk between iDOT and IDAT would leave iDOT pointing at the wrong place, so iDOT goes. + var between = Open (IdotPng (Text ("Comment", "Old")), "a.png"); + between.Tag!.Comment = "A longer comment"; + var output = between.Render ().ToArray (); + Assert.IsFalse (PngChunks (output).Exists (c => c.Type == "iDOT")); + Assert.AreEqual ("A longer comment", Open (output, "a.png").Tag!.Comment); + } +} diff --git a/tests/TagLibSharp2.Tests/Image/ImageSavePinTests.cs b/tests/TagLibSharp2.Tests/Image/ImageSavePinTests.cs new file mode 100644 index 00000000..11de7801 --- /dev/null +++ b/tests/TagLibSharp2.Tests/Image/ImageSavePinTests.cs @@ -0,0 +1,48 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Runtime.InteropServices; +using System.Text; +using TagLibSharp2.Core; +using TagLibSharp2.Image; +using TagLibSharp2.Image.Exif; +using TagLibSharp2.Image.Gif; +using TagLibSharp2.Image.Png; +using TagLibSharp2.Image.Svg; +using TagLibSharp2.Image.Tiff; +using TagLibSharp2.Tests.Core; +using TagLibSharp2.Tests.Kit; +using static TagLibSharp2.Tests.Image.ImageTestBuilder; + +namespace TagLibSharp2.Tests.Image; + +public partial class ImageSaveContractTests +{ + [TestMethod] + public void RenderTag_UsesTheFormatComment_AndAnUnknownContainerIsRefused () + { + var gif = new ImageTag (MediaFormat.Gif, ImageStores.Comment); + gif.Comment = "Hi"; + var gifBytes = ImageRewrite.RenderTag (gif); + Assert.AreEqual (0x21, gifBytes[0]); + Assert.AreEqual (0xFE, gifBytes[1]); + + var jpeg = new ImageTag (MediaFormat.Jpeg, ImageStores.Comment); + jpeg.Comment = "Hi"; + var jpegBytes = ImageRewrite.RenderTag (jpeg); + Assert.AreEqual (0xFF, jpegBytes[0]); + Assert.AreEqual (0xFE, jpegBytes[1]); + + Assert.IsFalse (ImageRewrite.TryPlan ([1, 2, 3, 4], MediaFormat.Unknown, null, out var plan, out var error)); + Assert.IsNull (plan); + Assert.AreEqual ("The image container could not be updated.", error); + + var carrier = new byte[14]; + "GIF89a"u8.CopyTo (carrier); + carrier[6] = 1; + carrier[8] = 1; + carrier[13] = 0x3B; + Assert.IsTrue (ImageRewrite.TryPlan (carrier, MediaFormat.Gif, gif, out var edited, out var editError), editError); + Assert.IsNotNull (edited); + } +} diff --git a/tests/TagLibSharp2.Tests/Image/ImageTagTests.cs b/tests/TagLibSharp2.Tests/Image/ImageTagTests.cs new file mode 100644 index 00000000..a019454e --- /dev/null +++ b/tests/TagLibSharp2.Tests/Image/ImageTagTests.cs @@ -0,0 +1,43 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Text; +using TagLibSharp2.Core; +using TagLibSharp2.Image; +using TagLibSharp2.Tests.Core; +using static TagLibSharp2.Tests.Image.ImageTestBuilder; + +namespace TagLibSharp2.Tests.Image; + +/// The image tag on its own: clearing and rendering the stored fields. +[TestClass] +[TestCategory ("Unit")] +public class ImageTagTests +{ + [TestMethod] + public void Tag_ClearAndRender_RoundTripTheStoredFields () + { + var file = Open (TitledPng ("Door"), "photo.png"); + var tag = file.Tag!; + tag.Artist = "Ada"; + tag.Album = "Room"; + tag.Genre = "Rock"; + tag.Track = 2; + tag.Genre = ""; + tag.Track = null; + Assert.IsNull (tag.Genre); + Assert.IsNull (tag.Track); + Assert.IsNull (tag.Album); + Assert.IsFalse (tag.IsEmpty); + + var rendered = tag.Render ().ToArray (); + Assert.IsTrue (Encoding.Latin1.GetString (rendered).Contains ("Door")); + + tag.Clear (); + Assert.IsTrue (tag.IsEmpty); + Assert.IsNull (tag.Title); + Assert.IsNull (tag.Album); + var cleared = file.Render ().ToArray (); + Assert.IsNull (Open (cleared, "photo.png").Tag!.Title); + } +} diff --git a/tests/TagLibSharp2.Tests/Image/ImageTestBuilder.cs b/tests/TagLibSharp2.Tests/Image/ImageTestBuilder.cs new file mode 100644 index 00000000..3ad23a41 --- /dev/null +++ b/tests/TagLibSharp2.Tests/Image/ImageTestBuilder.cs @@ -0,0 +1,764 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Buffers.Binary; +using System.IO.Compression; +using System.Text; +using System.Xml.Linq; +using TagLibSharp2.Core; +using TagLibSharp2.Image; + +namespace TagLibSharp2.Tests.Image; + +/// +/// Builds small still-image files in code: PNG chunks, GIF blocks, JPEG segments, TIFF IFDs, and the +/// XMP and Exif blocks that copy a PNG text field. +/// +static class ImageTestBuilder +{ + public static readonly byte[] PngSignature = [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]; + + public static byte[] Png (params byte[][] chunks) => + Concat (PngSignature, PngChunk ("IHDR", [0, 0, 0, 2, 0, 0, 0, 3, 8, 0, 0, 0, 0]), Concat (chunks), PngChunk ("IDAT", [0x78, 0x9C, 0x03, 0x00]), PngChunk ("IEND", [])); + + public static byte[] PngChunk (string type, byte[] payload) + { + var typeBytes = Encoding.ASCII.GetBytes (type); + var chunk = new byte[12 + payload.Length]; + BinaryPrimitives.WriteInt32BigEndian (chunk, payload.Length); + typeBytes.CopyTo (chunk, 4); + payload.CopyTo (chunk, 8); + BinaryPrimitives.WriteUInt32BigEndian (chunk.AsSpan (8 + payload.Length), BinaryData.ComputeCrc32 (chunk.AsSpan (4, 4 + payload.Length))); + return chunk; + } + + public static byte[] Text (string keyword, string text) => + PngChunk ("tEXt", Concat (Encoding.Latin1.GetBytes (keyword), [0], Encoding.Latin1.GetBytes (text))); + + public static byte[] CompressedText (string keyword, byte[] raw) => + PngChunk ("zTXt", Concat (Encoding.Latin1.GetBytes (keyword), [0, 0], Zlib (raw))); + + public static byte[] InternationalText (string keyword, string text, bool compressed = false) + { + var body = Encoding.UTF8.GetBytes (text); + return PngChunk ("iTXt", Concat (Encoding.Latin1.GetBytes (keyword), [0, (byte)(compressed ? 1 : 0), 0, 0, 0], compressed ? Zlib (body) : body)); + } + + public static byte[] Xmp (string packet, bool compressed = false) => InternationalText ("XML:com.adobe.xmp", packet, compressed); + + /// ImageMagick's form: zTXt "Raw profile type xmp" holding the packet as hexadecimal lines. + public static byte[] RawProfile (string name, byte[] profile) + { + var text = new StringBuilder (); + text.Append ('\n').Append (name).Append ('\n').Append (profile.Length.ToString (System.Globalization.CultureInfo.InvariantCulture).PadLeft (8)).Append ('\n'); + for (var n = 0; n < profile.Length; n++) { + text.Append (profile[n].ToString ("x2", System.Globalization.CultureInfo.InvariantCulture)); + if (n % 36 == 35 || n == profile.Length - 1) + text.Append ('\n'); + } + + return CompressedText ("Raw profile type " + name, Encoding.ASCII.GetBytes (text.ToString ())); + } + + public static string XmpPacket (string properties, string descriptionAttributes = "") => + "\n" + + "\n" + + " \n" + + " \n" + + properties + + " \n" + + " \n" + + "\n" + + ""; + + public static string Alt (string name, string value) => + $" <{name}>{value}{value} de\n"; + + public static string Seq (string name, params string[] values) => + $" <{name}>{string.Concat (values.Select (v => $"{v}"))}\n"; + + /// A little-endian TIFF with IFD0 ASCII entries, and an Exif IFD with the given ASCII entries. + public static byte[] ExifTiff (IReadOnlyList<(int Tag, string Value)> ifd0, IReadOnlyList<(int Tag, string Value)> exifIfd) + { + var entries0 = ifd0.Count + (exifIfd.Count > 0 ? 1 : 0); + var ifd0Size = 2 + (12 * entries0) + 4; + var exifSize = exifIfd.Count == 0 ? 0 : 2 + (12 * exifIfd.Count) + 4; + var valuesAt = 8 + ifd0Size + exifSize; + var values = new List (); + var data = new byte[valuesAt]; + data[0] = (byte)'I'; + data[1] = (byte)'I'; + data[2] = 42; + BinaryPrimitives.WriteInt32LittleEndian (data.AsSpan (4), 8); + var all = ifd0.Select (e => (e.Tag, (string?)e.Value)).ToList (); + if (exifIfd.Count > 0) + all.Add ((0x8769, null)); + all.Sort ((a, b) => a.Item1.CompareTo (b.Item1)); + WriteIfd (data, 8, all, valuesAt, values, exifAt: 8 + ifd0Size); + if (exifIfd.Count > 0) + WriteIfd (data, 8 + ifd0Size, exifIfd.Select (e => (e.Tag, (string?)e.Value)).ToList (), valuesAt, values, exifAt: 0); + return Concat (data, [.. values]); + } + + static void WriteIfd (byte[] data, int at, List<(int Tag, string? Value)> entries, int valuesAt, List values, int exifAt) + { + BinaryPrimitives.WriteUInt16LittleEndian (data.AsSpan (at), (ushort)entries.Count); + for (var n = 0; n < entries.Count; n++) { + var e = at + 2 + (12 * n); + BinaryPrimitives.WriteUInt16LittleEndian (data.AsSpan (e), (ushort)entries[n].Tag); + if (entries[n].Value is not string value) { + BinaryPrimitives.WriteUInt16LittleEndian (data.AsSpan (e + 2), 4); + BinaryPrimitives.WriteInt32LittleEndian (data.AsSpan (e + 4), 1); + BinaryPrimitives.WriteInt32LittleEndian (data.AsSpan (e + 8), exifAt); + continue; + } + + var bytes = Concat (Encoding.ASCII.GetBytes (value), [0]); + BinaryPrimitives.WriteUInt16LittleEndian (data.AsSpan (e + 2), 2); + BinaryPrimitives.WriteInt32LittleEndian (data.AsSpan (e + 4), bytes.Length); + if (bytes.Length <= 4) { + bytes.CopyTo (data, e + 8); + } else { + BinaryPrimitives.WriteInt32LittleEndian (data.AsSpan (e + 8), valuesAt + values.Count); + values.AddRange (bytes); + } + } + } + + public static List<(string Type, byte[] Payload)> PngChunks (byte[] file) + { + var chunks = new List<(string, byte[])> (); + var i = 8; + while (i + 12 <= file.Length) { + var length = BinaryPrimitives.ReadInt32BigEndian (file.AsSpan (i)); + var type = Encoding.ASCII.GetString (file, i + 4, 4); + Assert.AreEqual (BinaryData.ComputeCrc32 (file.AsSpan (i + 4, 4 + length)), BinaryPrimitives.ReadUInt32BigEndian (file.AsSpan (i + 8 + length)), $"{type} CRC"); + chunks.Add ((type, file.AsSpan (i + 8, length).ToArray ())); + i += 12 + length; + if (type == "IEND") + break; + } + + return chunks; + } + + /// The decoded text of every PNG text chunk with . + public static List PngTexts (byte[] file, string keyword) + { + var texts = new List (); + foreach (var (type, payload) in PngChunks (file)) { + if (type is not ("tEXt" or "zTXt" or "iTXt")) + continue; + var zero = Array.IndexOf (payload, (byte)0); + if (Encoding.Latin1.GetString (payload, 0, zero) != keyword) + continue; + var rest = payload.AsSpan (zero + 1); + if (type == "tEXt") { + texts.Add (Encoding.Latin1.GetString (rest)); + } else if (type == "zTXt") { + texts.Add (Encoding.Latin1.GetString (Inflate (rest.Slice (1).ToArray ()))); + } else { + var compressed = rest[0] == 1; + var i = 2; + i += rest.Slice (i).IndexOf ((byte)0) + 1; + i += rest.Slice (i).IndexOf ((byte)0) + 1; + var body = rest.Slice (i).ToArray (); + texts.Add (Encoding.UTF8.GetString (compressed ? Inflate (body) : body)); + } + } + + return texts; + } + + /// Decodes an ImageMagick raw profile's hexadecimal lines. + public static byte[] DecodeRawProfile (string text) + { + var lines = text.Split ('\n', StringSplitOptions.RemoveEmptyEntries); + var length = int.Parse (lines[1].Trim (), System.Globalization.CultureInfo.InvariantCulture); + var hex = string.Concat (lines.Skip (2)); + Assert.AreEqual (length * 2, hex.Length, "raw profile length"); + return Convert.FromHexString (hex); + } + + public static byte[] Gif (params byte[][] blocks) + { + var header = new byte[13]; + Encoding.ASCII.GetBytes ("GIF89a").CopyTo (header, 0); + header[6] = 1; + header[8] = 1; + byte[] image = [0x2C, 0, 0, 0, 0, 1, 0, 1, 0, 0, 2, 2, 0x4C, 0x01, 0]; + return Concat (header, Concat (blocks), image, [0x3B]); + } + + public static byte[] GifComment (string text) + { + var bytes = Encoding.UTF8.GetBytes (text); + return Concat ([0x21, 0xFE, (byte)bytes.Length], bytes, [0]); + } + + public static byte[] GifApplication (string identifier, byte[] data) => + Concat ([0x21, 0xFF, 11], Encoding.ASCII.GetBytes (identifier), [(byte)data.Length], data, [0]); + + public static byte[] Jpeg (params byte[][] segments) => + Concat ( + [0xFF, 0xD8], + Concat (segments), + JpegSegment (0xC0, [0x08, 0x00, 0x03, 0x00, 0x02, 0x01, 0x01, 0x11, 0x00]), + JpegSegment (0xDA, [0x01, 0x01, 0x00, 0x00, 0x3F, 0x00]), + [0x12, 0x34, 0xFF, 0x00, 0x56], + [0xFF, 0xD9]); + + public static byte[] JpegSegment (byte marker, byte[] payload) + { + var segment = new byte[4 + payload.Length]; + segment[0] = 0xFF; + segment[1] = marker; + BinaryPrimitives.WriteUInt16BigEndian (segment.AsSpan (2), (ushort)(payload.Length + 2)); + payload.CopyTo (segment, 4); + return segment; + } + + public static byte[] JpegApp (byte marker, string signature, string body) => + JpegSegment (marker, Encoding.ASCII.GetBytes (signature + body)); + + /// A classic little-endian TIFF: IFD0 has the given entries, all LONG with one value. + public static byte[] Tiff (params (int Tag, int Value)[] entries) => TiffChain ([entries]); + + /// A chain of IFDs linked by their next-IFD offsets, each with LONG entries. + public static byte[] TiffChain (IReadOnlyList<(int Tag, int Value)[]> ifds) + { + var size = 8 + ifds.Sum (e => 2 + (12 * e.Length) + 4); + var data = new byte[size]; + data[0] = (byte)'I'; + data[1] = (byte)'I'; + data[2] = 42; + BinaryPrimitives.WriteInt32LittleEndian (data.AsSpan (4), 8); + var at = 8; + for (var n = 0; n < ifds.Count; n++) { + var entries = ifds[n]; + BinaryPrimitives.WriteUInt16LittleEndian (data.AsSpan (at), (ushort)entries.Length); + for (var e = 0; e < entries.Length; e++) + WriteLong (data, at + 2 + (12 * e), entries[e].Tag, entries[e].Value); + var next = at + 2 + (12 * entries.Length) + 4; + BinaryPrimitives.WriteInt32LittleEndian (data.AsSpan (next - 4), n + 1 < ifds.Count ? next : 0); + at = next; + } + + return data; + } + + public static void WriteLong (byte[] data, int at, int tag, int value) + { + BinaryPrimitives.WriteUInt16LittleEndian (data.AsSpan (at), (ushort)tag); + BinaryPrimitives.WriteUInt16LittleEndian (data.AsSpan (at + 2), 4); + BinaryPrimitives.WriteInt32LittleEndian (data.AsSpan (at + 4), 1); + BinaryPrimitives.WriteInt32LittleEndian (data.AsSpan (at + 8), value); + } + + public static byte[] Zlib (byte[] raw) => Zlib (raw, CompressionLevel.Optimal); + + public static byte[] Zlib (byte[] raw, CompressionLevel level) + { + using var output = new MemoryStream (); + using (var z = new ZLibStream (output, level, leaveOpen: true)) + z.Write (raw); + return output.ToArray (); + } + + /// A PNG text chunk around raw bytes: compressed (zTXt, or iTXt when ) at a given level. + public static byte[] CompressedChunk (string keyword, byte[] raw, CompressionLevel level, bool itxt) => + itxt + ? PngChunk ("iTXt", Concat (Encoding.Latin1.GetBytes (keyword), [0, 1, 0, 0, 0], Zlib (raw, level))) + : PngChunk ("zTXt", Concat (Encoding.Latin1.GetBytes (keyword), [0, 0], Zlib (raw, level))); + + /// An uncompressed iTXt chunk around raw bytes, which need not be valid UTF-8. + public static byte[] RawItxt (string keyword, byte[] raw) => + PngChunk ("iTXt", Concat (Encoding.Latin1.GetBytes (keyword), [0, 0, 0, 0, 0], raw)); + + /// ImageMagick's raw profile with bytes per hex line, compressed at a given level. + public static byte[] RawProfile (string name, byte[] profile, int perLine, CompressionLevel level) + { + var text = new StringBuilder (); + text.Append ('\n').Append (name).Append ('\n').Append (profile.Length.ToString (System.Globalization.CultureInfo.InvariantCulture).PadLeft (8)).Append ('\n'); + for (var n = 0; n < profile.Length; n++) { + text.Append (profile[n].ToString ("x2", System.Globalization.CultureInfo.InvariantCulture)); + if (n % perLine == perLine - 1 || n == profile.Length - 1) + text.Append ('\n'); + } + + return CompressedChunk ("Raw profile type " + name, Encoding.ASCII.GetBytes (text.ToString ()), level, itxt: false); + } + + public static byte[] Inflate (byte[] zlib) + { + using var input = new MemoryStream (zlib); + using var z = new ZLibStream (input, CompressionMode.Decompress); + using var output = new MemoryStream (); + z.CopyTo (output); + return output.ToArray (); + } + + /// A GIF XMP application extension: the packet bytes, then the 258-byte magic trailer (XMP Part 3 §1.1.2). + public static byte[] GifXmp (string packet) + { + var trailer = new byte[258]; + trailer[0] = 0x01; + for (var n = 0; n < 256; n++) + trailer[1 + n] = (byte)(0xFF - n); + return Concat ([0x21, 0xFF, 11], "XMP DataXMP"u8.ToArray (), Encoding.UTF8.GetBytes (packet), trailer); + } + + /// A GIF XMP application extension written as ordinary data sub-blocks, as ImageIO writes it. + public static byte[] GifSubBlockXmp (string packet) + { + var bytes = Encoding.UTF8.GetBytes (packet); + var blocks = new List (); + for (var at = 0; at < bytes.Length; at += 255) { + var take = Math.Min (255, bytes.Length - at); + blocks.Add ((byte)take); + blocks.AddRange (bytes.AsSpan (at, take).ToArray ()); + } + + return Concat ([0x21, 0xFF, 11], "XMP DataXMP"u8.ToArray (), [.. blocks], [0]); + } + + public static byte[] JpegXmp (string packet) => + JpegSegment (0xE1, Concat ("http://ns.adobe.com/xap/1.0/\0"u8.ToArray (), Encoding.UTF8.GetBytes (packet))); + + public static byte[] JpegExif (byte[] tiff) => JpegSegment (0xE1, Concat ("Exif\0\0"u8.ToArray (), tiff)); + + /// An Exif SRATIONAL (TIFF 6.0 type 10), big-endian. + public static byte[] SRational (int numerator, int denominator) + { + var value = new byte[8]; + BinaryPrimitives.WriteInt32BigEndian (value, numerator); + BinaryPrimitives.WriteInt32BigEndian (value.AsSpan (4), denominator); + return value; + } + + public static readonly byte[] AppleMakerNoteHeader = "Apple iOS\0\0\u0001MM"u8.ToArray (); + + /// + /// An Apple maker note as iPhones write it: "Apple iOS", NUL, version 1, "MM", then a big-endian IFD whose + /// value offsets count from the start of the maker note. + /// + public static byte[] AppleMakerNote (IReadOnlyList<(int Tag, int Type, int Count, byte[] Value)> entries, byte[]? header = null) + { + header ??= AppleMakerNoteHeader; + var valuesAt = header.Length + 2 + (12 * entries.Count) + 4; + var table = new byte[valuesAt]; + header.CopyTo (table, 0); + BinaryPrimitives.WriteUInt16BigEndian (table.AsSpan (header.Length), (ushort)entries.Count); + var values = new List (); + for (var n = 0; n < entries.Count; n++) { + var e = header.Length + 2 + (12 * n); + var (tag, type, count, value) = entries[n]; + BinaryPrimitives.WriteUInt16BigEndian (table.AsSpan (e), (ushort)tag); + BinaryPrimitives.WriteUInt16BigEndian (table.AsSpan (e + 2), (ushort)type); + BinaryPrimitives.WriteInt32BigEndian (table.AsSpan (e + 4), count); + if (value.Length <= 4) { + value.CopyTo (table, e + 8); + } else { + BinaryPrimitives.WriteInt32BigEndian (table.AsSpan (e + 8), valuesAt + values.Count); + values.AddRange (value); + } + } + + return Concat (table, [.. values]); + } + + /// + /// An Exif TIFF shaped like an iPhone's (big-endian unless asked): IFD0 with Make, Model, DateTime and the Exif + /// and GPS IFD pointers, a GPS IFD with a latitude, and an Exif IFD with DateTimeOriginal and the maker note. + /// + public static byte[] AppleExifTiff (byte[] makerNote, int makerNoteType = 7, int? makerNoteCount = null, int? exifIfd = null, bool littleEndian = false) + { + static byte[] Ascii (string s) => Concat (Encoding.ASCII.GetBytes (s), [0]); + const int Ifd0 = 8; + const int Gps = Ifd0 + 2 + (12 * 5) + 4; + const int Exif = Gps + 2 + (12 * 2) + 4; + const int ValuesAt = Exif + 2 + (12 * 2) + 4; + var data = new byte[ValuesAt]; + (littleEndian ? "II*\0"u8 : "MM\0*"u8).CopyTo (data); + U32 (data.AsSpan (4), Ifd0); + var values = new List (); + void Ifd (int at, (int Tag, int Type, int Count, byte[] Value)[] entries) + { + U16 (data.AsSpan (at), entries.Length); + for (var n = 0; n < entries.Length; n++) { + var e = at + 2 + (12 * n); + var (tag, type, count, value) = entries[n]; + U16 (data.AsSpan (e), tag); + U16 (data.AsSpan (e + 2), type); + U32 (data.AsSpan (e + 4), count); + if (value.Length <= 4) { + value.CopyTo (data, e + 8); + } else { + U32 (data.AsSpan (e + 8), ValuesAt + values.Count); + values.AddRange (value); + if (values.Count % 2 == 1) + values.Add (0); + } + } + } + + void U16 (Span at, int value) + { + if (littleEndian) + BinaryPrimitives.WriteUInt16LittleEndian (at, (ushort)value); + else + BinaryPrimitives.WriteUInt16BigEndian (at, (ushort)value); + } + + void U32 (Span at, int value) + { + if (littleEndian) + BinaryPrimitives.WriteInt32LittleEndian (at, value); + else + BinaryPrimitives.WriteInt32BigEndian (at, value); + } + + byte[] Long (int value) + { + var bytes = new byte[4]; + U32 (bytes, value); + return bytes; + } + + // RATIONAL values in the TIFF's byte order (the maker note keeps its own big-endian order). + byte[] Rational (int numerator, int denominator) + { + var bytes = new byte[8]; + U32 (bytes, numerator); + U32 (bytes.AsSpan (4), denominator); + return bytes; + } + + Ifd (Ifd0, [ + (0x010F, 2, 6, Ascii ("Apple")), + (0x0110, 2, 15, Ascii ("iPhone 13 Jane")), + (0x0132, 2, 20, Ascii ("2024:05:01 10:00:00")), + (0x8769, 4, 1, Long (exifIfd ?? Exif)), + (0x8825, 4, 1, Long (Gps))]); + Ifd (Gps, [(0x0001, 2, 2, Ascii ("N")), (0x0002, 5, 3, Concat (Rational (47, 1), Rational (30, 1), Rational (0, 1)))]); + Ifd (Exif, [(0x9003, 2, 20, Ascii ("2024:05:01 10:00:00")), (0x927C, makerNoteType, makerNoteCount ?? makerNote.Length, makerNote)]); + return Concat (data, [.. values]); + } + + /// An APP11 JUMBF segment (ISO/IEC 19566-5): "JP", box instance En, sequence Z, then the box bytes. + public static byte[] Jumbf (int en, int z, byte[] box) + { + var head = new byte[8]; + head[0] = (byte)'J'; + head[1] = (byte)'P'; + BinaryPrimitives.WriteUInt16BigEndian (head.AsSpan (2), (ushort)en); + BinaryPrimitives.WriteInt32BigEndian (head.AsSpan (4), z); + return JpegSegment (0xEB, Concat (head, box)); + } + + public static byte[] Box (string type, byte[] payload) + { + var box = new byte[8 + payload.Length]; + BinaryPrimitives.WriteInt32BigEndian (box, box.Length); + Encoding.ASCII.GetBytes (type).CopyTo (box, 4); + payload.CopyTo (box, 8); + return box; + } + + /// A JUMBF superbox (ISO/IEC 19566-5) whose description box has the given content type, holding one box. + public static byte[] JumbfStore (byte[] type, string label, byte[] content) => + Box ("jumb", Concat (Box ("jumd", Concat (type, [3], Encoding.ASCII.GetBytes (label + "\0"))), content)); + + public static readonly byte[] JsonUuid = [0x6A, 0x73, 0x6F, 0x6E, 0x00, 0x11, 0x00, 0x10, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71]; + public static readonly byte[] XmlUuid = [0x78, 0x6D, 0x6C, 0x20, 0x00, 0x11, 0x00, 0x10, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71]; + + public static readonly byte[] C2paUuid = [0x63, 0x32, 0x70, 0x61, 0x00, 0x11, 0x00, 0x10, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71]; + + /// A C2PA manifest store: a jumb superbox whose jumd has the C2PA type, holding a JSON assertion. + public static byte[] C2paStore (byte[]? type = null) => + Box ("jumb", Concat ( + Box ("jumd", Concat (type ?? C2paUuid, [3], "c2pa\0"u8.ToArray ())), + Box ("json", """{"dc:creator":"Jane Private","exif:GPSLatitude":"47,30.0N"}"""u8.ToArray ()))); + + /// + /// A two-image MPF file (CIPA DC-007): the first image's APP2 MPF index points at the second image after + /// its EOI. sits between the MPF segment and the frame. + /// + public static byte[] MpfJpeg (byte[] before, byte[] between, out byte[] second) => + MpfJpeg (before, between, Jpeg (JpegSegment (0xFE, "second image"u8.ToArray ())), out second); + + public static byte[] MpfJpeg (byte[] before, byte[] between, byte[] secondImage, out byte[] second) + { + second = secondImage; + return MpfJpegMany (before, between, secondImage); + } + + /// A multi-picture file whose first image's MPF index lists after its EOI. + public static byte[] MpfJpegMany (byte[] before, byte[] between, params byte[][] later) + { + var count = later.Length + 1; + // MP header (big-endian TIFF), IFD with one entry: MPEntry (0xB002), UNDEFINED, 16 bytes per image at offset 26. + var mp = new byte[8 + 2 + 12 + 4 + (16 * count)]; + "MM\0*"u8.CopyTo (mp); + BinaryPrimitives.WriteInt32BigEndian (mp.AsSpan (4), 8); + BinaryPrimitives.WriteUInt16BigEndian (mp.AsSpan (8), 1); + BinaryPrimitives.WriteUInt16BigEndian (mp.AsSpan (10), 0xB002); + BinaryPrimitives.WriteUInt16BigEndian (mp.AsSpan (12), 7); + BinaryPrimitives.WriteInt32BigEndian (mp.AsSpan (14), 16 * count); + BinaryPrimitives.WriteInt32BigEndian (mp.AsSpan (18), 26); + var segment = JpegSegment (0xE2, Concat ("MPF\0"u8.ToArray (), mp)); + var first = Concat ([0xFF, 0xD8], before, segment, between, + JpegSegment (0xC0, [0x08, 0x00, 0x03, 0x00, 0x02, 0x01, 0x01, 0x11, 0x00]), + JpegSegment (0xDA, [0x01, 0x01, 0x00, 0x00, 0x3F, 0x00]), [0x12, 0x34], [0xFF, 0xD9]); + var header = 2 + before.Length + 4 + 4; + var entries = header + 26; + BinaryPrimitives.WriteInt32BigEndian (first.AsSpan (entries + 4), first.Length); + var at = first.Length; + for (var n = 0; n < later.Length; n++) { + var entry = entries + (16 * (n + 1)); + BinaryPrimitives.WriteInt32BigEndian (first.AsSpan (entry + 4), later[n].Length); + BinaryPrimitives.WriteInt32BigEndian (first.AsSpan (entry + 8), at - header); + at += later[n].Length; + } + + return Concat ([first, .. later]); + } + + /// Writes MP entry 's size and offset (relative to the MP header). + public static void SetMpEntry (byte[] jpeg, int n, int size, int offset) + { + var entry = jpeg.AsSpan ().IndexOf ("MPF\0"u8) + 4 + 26 + (16 * n); + BinaryPrimitives.WriteInt32BigEndian (jpeg.AsSpan (entry + 4), size); + BinaryPrimitives.WriteInt32BigEndian (jpeg.AsSpan (entry + 8), offset); + } + + public static (int Size, int Offset) GetMpEntry (byte[] jpeg, int n) + { + var entry = jpeg.AsSpan ().IndexOf ("MPF\0"u8) + 4 + 26 + (16 * n); + return (BinaryPrimitives.ReadInt32BigEndian (jpeg.AsSpan (entry + 4)), BinaryPrimitives.ReadInt32BigEndian (jpeg.AsSpan (entry + 8))); + } + + /// The MP entries of : each image's absolute start and its size. + public static List<(int Start, int Size)> MpfEntries (byte[] jpeg) + { + var header = jpeg.AsSpan ().IndexOf ("MPF\0"u8) + 4; + var entries = header + 26; + var list = new List<(int, int)> (); + for (var n = 0; n < 2; n++) { + var size = BinaryPrimitives.ReadInt32BigEndian (jpeg.AsSpan (entries + (16 * n) + 4)); + var offset = BinaryPrimitives.ReadInt32BigEndian (jpeg.AsSpan (entries + (16 * n) + 8)); + list.Add ((offset == 0 ? 0 : header + offset, size)); + } + + return list; + } + + /// Where the MPF index of says the second image starts. + public static int MpfSecondImage (byte[] jpeg) + { + var at = jpeg.AsSpan ().IndexOf ("MPF\0"u8); + var header = at + 4; + var entries = header + 26; + return header + BinaryPrimitives.ReadInt32BigEndian (jpeg.AsSpan (entries + 16 + 8)); + } + + public static StillImageFile Open (byte[] data, string name) + { + var result = MediaFile.ReadFromData (data, name); + Assert.IsTrue (result.IsSuccess, result.Error); + return (StillImageFile)result.File!; + } + + // The XMP namespaces the tests read packets with. + public static readonly XNamespace Rdf = "http://www.w3.org/1999/02/22-rdf-syntax-ns#"; + public static readonly XNamespace Dc = "http://purl.org/dc/elements/1.1/"; + public static readonly XNamespace Exif = "http://ns.adobe.com/exif/1.0/"; + public static readonly XNamespace Hdrgm = "http://ns.adobe.com/hdr-gain-map/1.0/"; + public static readonly XNamespace Container = "http://ns.google.com/photos/1.0/container/"; + public static readonly XNamespace Item = "http://ns.google.com/photos/1.0/container/item/"; + public static readonly XNamespace AppleGainMap = "http://ns.apple.com/HDRGainMap/1.0/"; + + /// A PNG IHDR payload (PNG 3rd ed. §11.2.1). + public static byte[] PngHeader (int width, int height, byte depth, byte color) + { + var ihdr = new byte[13]; + BinaryPrimitives.WriteInt32BigEndian (ihdr, width); + BinaryPrimitives.WriteInt32BigEndian (ihdr.AsSpan (4), height); + ihdr[8] = depth; + ihdr[9] = color; + return ihdr; + } + + /// The signature and an IHDR chunk, and nothing else. + public static byte[] PngIhdr (int width, int height, byte depth, byte color) => + Concat (PngSignature, PngChunk ("IHDR", PngHeader (width, height, depth, color))); + + /// The signature, then an IHDR chunk without its CRC: all the size reader looks at. + public static byte[] PngIhdrWithoutCrc (int width, int height, byte depth, byte color) => + Concat (PngSignature, [0, 0, 0, 13], "IHDR"u8.ToArray (), PngHeader (width, height, depth, color)); + + /// A 1x1 grayscale PNG with the given chunks between IHDR and IEND, and no IDAT. + public static byte[] MinimalPng (params byte[][] chunks) => + Concat (PngSignature, PngChunk ("IHDR", PngHeader (1, 1, 8, 0)), Concat (chunks), PngChunk ("IEND", [])); + + /// A 1x1 RGB PNG with a tEXt Title. + public static byte[] TitledPng (string title) => + Concat (PngSignature, PngChunk ("IHDR", PngHeader (1, 1, 8, 2)), Text ("Title", title), PngChunk ("IEND", [])); + + /// A GIF89a header and logical screen descriptor (GIF89a §18) and nothing else. + public static byte[] GifScreen (int width, int height, byte flags = 0x80 | (7 << 4) | 7) + { + var data = new byte[13]; + "GIF89a"u8.CopyTo (data); + BinaryPrimitives.WriteUInt16LittleEndian (data.AsSpan (6), (ushort)width); + BinaryPrimitives.WriteUInt16LittleEndian (data.AsSpan (8), (ushort)height); + data[10] = flags; + return data; + } + + /// A BMP file header and BITMAPINFOHEADER, 24 bits per pixel. + public static byte[] Bmp (int width, int height, int length = 54) + { + var data = new byte[length]; + "BM"u8.CopyTo (data); + BinaryPrimitives.WriteInt32LittleEndian (data.AsSpan (14), 40); + BinaryPrimitives.WriteInt32LittleEndian (data.AsSpan (18), width); + BinaryPrimitives.WriteInt32LittleEndian (data.AsSpan (22), height); + data[28] = 24; + return data; + } + + /// A 128-byte PCX header: version 5, RLE, 8 bits, the window, and the colour planes. + public static byte[] Pcx (int xmin, int ymin, int xmax, int ymax, byte planes = 3) + { + var data = new byte[128]; + data[0] = 0x0A; + data[1] = 5; + data[2] = 1; + data[3] = 8; + BinaryPrimitives.WriteUInt16LittleEndian (data.AsSpan (4), (ushort)xmin); + BinaryPrimitives.WriteUInt16LittleEndian (data.AsSpan (6), (ushort)ymin); + BinaryPrimitives.WriteUInt16LittleEndian (data.AsSpan (8), (ushort)xmax); + BinaryPrimitives.WriteUInt16LittleEndian (data.AsSpan (10), (ushort)ymax); + data[65] = planes; + return data; + } + + /// A TIFF whose IFD0 holds LONG ImageWidth and ImageLength (and the DNG version tag). + public static byte[] TiffImage (int width, int height, bool littleEndian = true, bool dng = false) + { + (int, int, long, long)[] entries = dng ? [(256, 4, 1, width), (257, 4, 1, height), (0xC612, 4, 1, 1)] : [(256, 4, 1, width), (257, 4, 1, height)]; + return new TiffBuilder (8 + 2 + (12 * entries.Length) + 4, bigEndian: !littleEndian).Header (8).Table (8, entries).ToArray (); + } + + /// A BigTIFF whose IFD0 holds SHORT ImageWidth and ImageLength. + public static byte[] BigTiff (int width, int height, bool littleEndian) => + new TiffBuilder (72, bigEndian: !littleEndian, big: true).Header (16) + .Table (16, [(256, 3, 1, 0), (257, 3, 1, 0)]).U16 (24 + 12, width).U16 (44 + 12, height).ToArray (); + + /// The data of the first PNG chunk of a type, or empty. + public static byte[] PngPayload (byte[] file, string type) => + PngChunkAt (file, (chunkType, _) => chunkType == type) is var (at, length) && at >= 0 ? file[(at + 8)..(at + 8 + length)] : []; + + public static bool HasPngChunk (byte[] file, string type) + { + var i = 8; + while (i + 8 <= file.Length) { + if (Encoding.ASCII.GetString (file, i + 4, 4) == type) + return true; + i += 12 + BinaryPrimitives.ReadInt32BigEndian (file.AsSpan (i)); + } + + return false; + } + + /// The whole first text chunk of a type with a keyword, or empty. + public static byte[] PngTextChunk (byte[] file, string type, string keyword) + { + var key = Encoding.ASCII.GetBytes (keyword); + var (at, length) = PngChunkAt (file, (chunkType, at) => chunkType == type && BinaryPrimitives.ReadInt32BigEndian (file.AsSpan (at)) >= key.Length + 1 + && file.AsSpan (at + 8, key.Length).SequenceEqual (key) && file[at + 8 + key.Length] == 0); + return at < 0 ? [] : file[at..(at + 12 + length)]; + } + + // The first chunk the test matches, walking lengths without checking them: (-1, 0) when there is none. + static (int At, int Length) PngChunkAt (byte[] file, Func matches) + { + var i = 8; + while (i + 12 <= file.Length) { + var length = BinaryPrimitives.ReadInt32BigEndian (file.AsSpan (i)); + if (matches (Encoding.ASCII.GetString (file, i + 4, 4), i)) + return (i, length); + i += 12 + length; + } + + return (-1, 0); + } + + /// The first byte equal to followed by (any byte when negative). + public static int IndexOf (byte[] data, byte first, int second) + { + for (var i = 0; i + 1 < data.Length; i++) { + if (data[i] == first && (second < 0 || data[i + 1] == second)) + return i; + } + + return -1; + } + + /// The data of the first sub-block of a GIF's last image. + public static byte[] GifImageSubBlock (byte[] gif) + { + var i = gif.Length - 1; + while (i > 0 && gif[i] != 0x2C) + i--; + i += 11; + var size = gif[i++]; + return gif[i..(i + size)]; + } + + public static byte[] Concat (params byte[][] parts) + { + var data = new byte[parts.Sum (p => p.Length)]; + var i = 0; + foreach (var part in parts) { + part.CopyTo (data, i); + i += part.Length; + } + + return data; + } + + internal const int Mib = 1024 * 1024; + + // The runtime itself can allocate about 1 KB on the thread (tiering, net8.0). The regressions these pin cost + // 49 KB (TIFF scratch) to 131 KB (a decoded 64 KB markup window). + internal const int Noise = 4 * 1024; + + internal static byte[] GifWithComment (string comment, byte[] trap) + { + var text = Encoding.UTF8.GetBytes (comment); + var data = new byte[13 + 2 + 1 + text.Length + 1 + 10 + 1 + 1 + trap.Length + 1 + 1]; + Encoding.ASCII.GetBytes ("GIF89a").CopyTo (data, 0); + data[6] = 1; + data[8] = 1; + var i = 13; + data[i++] = 0x21; + data[i++] = 0xFE; + data[i++] = (byte)text.Length; + text.CopyTo (data, i); + i += text.Length; + data[i++] = 0; + data[i++] = 0x2C; + data[i + 4] = 1; + data[i + 6] = 1; + i += 9; + data[i++] = 2; + data[i++] = (byte)trap.Length; + trap.CopyTo (data, i); + i += trap.Length; + data[i++] = 0; + data[i] = 0x3B; + return data; + } +} diff --git a/tests/TagLibSharp2.Tests/Image/JpegCommentTests.cs b/tests/TagLibSharp2.Tests/Image/JpegCommentTests.cs new file mode 100644 index 00000000..2a3e40fb --- /dev/null +++ b/tests/TagLibSharp2.Tests/Image/JpegCommentTests.cs @@ -0,0 +1,75 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Buffers.Binary; +using System.IO.Compression; +using System.Text; +using TagLibSharp2.Core; +using TagLibSharp2.Image; +using TagLibSharp2.Tests.Core; +using static TagLibSharp2.Tests.Image.ImageTestBuilder; + +namespace TagLibSharp2.Tests.Image; + +/// The JPEG COM segment: reading and writing the comment before the scan. +[TestClass] +[TestCategory ("Unit")] +public class JpegCommentTests +{ + [TestMethod] + public void Jpeg_RoundTripsComment_AndLeavesTheScan () + { + var scan = new byte[] { 0xFF, 0xFE, 0x00, 0x03, 0x99, 0x88, 0xFF, 0xD9, 0xAA, 0xBB }; + var data = Jpeg ("old", scan); + var file = Open (data, "photo.jpg"); + Assert.AreEqual ("old", file.Tag!.Comment); + Assert.AreEqual (8, file.ImageProperties!.Value.Width); + file.Tag.Comment = "old"; + CollectionAssert.AreEqual (data, file.Render ().ToArray ()); + + file.Tag.Comment = "門"; + var rendered = file.Render ().ToArray (); + CollectionAssert.AreEqual (scan, rendered.Skip (rendered.Length - scan.Length).ToArray ()); + Assert.AreEqual ("門", Open (rendered, "photo.jpg").Tag!.Comment); + Assert.AreEqual (8, Open (rendered, "photo.jpg").ImageProperties!.Value.Width); + + var longComment = new string ('B', 65534); + file.Tag.Comment = longComment; + var split = file.Render ().ToArray (); + CollectionAssert.AreEqual (scan, split.Skip (split.Length - scan.Length).ToArray ()); + Assert.AreEqual (longComment, Open (split, "photo.jpg").Tag!.Comment); + } + + static byte[] Jpeg (string comment, byte[] scan) + { + var text = Encoding.UTF8.GetBytes (comment); + var data = new byte[2 + 4 + text.Length + 2 + 11 + 4 + scan.Length]; + data[0] = 0xFF; + data[1] = 0xD8; + data[2] = 0xFF; + data[3] = 0xFE; + data[4] = (byte)((text.Length + 2) >> 8); + data[5] = (byte)(text.Length + 2); + text.CopyTo (data, 6); + var i = 6 + text.Length; + data[i++] = 0xFF; + data[i++] = 0xC0; + data[i++] = 0x00; + data[i++] = 0x0B; + data[i++] = 0x08; + data[i++] = 0x00; + data[i++] = 0x01; + data[i++] = 0x00; + data[i++] = 0x08; + data[i++] = 0x01; + data[i++] = 0x01; + data[i++] = 0x11; + data[i++] = 0x00; + data[i++] = 0xFF; + data[i++] = 0xDA; + data[i++] = 0x00; + data[i++] = 0x02; + scan.CopyTo (data, i); + return data; + } +} diff --git a/tests/TagLibSharp2.Tests/Image/JpegSizeTests.cs b/tests/TagLibSharp2.Tests/Image/JpegSizeTests.cs new file mode 100644 index 00000000..3b3d6bbf --- /dev/null +++ b/tests/TagLibSharp2.Tests/Image/JpegSizeTests.cs @@ -0,0 +1,101 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Buffers.Binary; +using System.Text; +using TagLibSharp2.Core; +using TagLibSharp2.Image; +using TagLibSharp2.Tests.Kit; +using static TagLibSharp2.Tests.Image.ImageAssert; +using static TagLibSharp2.Tests.Image.ImageTestBuilder; + +namespace TagLibSharp2.Tests.Image; + +/// JPEG width, height and bit depth from the start-of-frame segment, or the DNL segment after the first scan. +[TestClass] +[TestCategory ("Unit")] +public class JpegSizeTests +{ + // ITU-T T.81 §B.2.5: the DNL segment "shall immediately follow the first scan". + static readonly byte[] ZeroHeightSof = [0xFF, 0xD8, 0xFF, 0xC0, 0x00, 0x0B, 0x08, 0x00, 0x00, 0x00, 0x08, 0x01, 0x01, 0x11, 0x00]; + static readonly byte[] Sos = [0xFF, 0xDA, 0x00, 0x08, 0x01, 0x01, 0x00, 0x00, 0x3F, 0x00]; + static readonly byte[] Dnl = [0xFF, 0xDC, 0x00, 0x04, 0x00, 0x05]; + + public static IEnumerable DnlLayouts () + { + yield return ["spec layout", Concat (ZeroHeightSof, Sos, [0x12, 0x34], Dnl, [0xFF, 0xD9]), 5]; + yield return ["stuffed 0xFF in the scan", Concat (ZeroHeightSof, Sos, [0xFF, 0x00, 0xFF, 0x00, 0x7F], Dnl, [0xFF, 0xD9]), 5]; + yield return ["restart markers in the scan", Concat (ZeroHeightSof, Sos, [0x01, 0xFF, 0xD0, 0x02, 0xFF, 0xD7, 0x03], Dnl, [0xFF, 0xD9]), 5]; + yield return ["fill bytes before DNL", Concat (ZeroHeightSof, Sos, [0x01, 0xFF, 0xFF, 0xFF], Dnl, [0xFF, 0xD9]), 5]; + yield return ["empty scan", Concat (ZeroHeightSof, Sos, Dnl), 5]; + yield return ["no EOI", Concat (ZeroHeightSof, Sos, [0x01], Dnl), 5]; + yield return ["DNL before the scan", Concat (ZeroHeightSof, Dnl, Sos, [0x01], [0xFF, 0xD9]), 0]; + yield return ["no DNL", Concat (ZeroHeightSof, Sos, [0x01, 0x02], [0xFF, 0xD9]), 0]; + yield return ["another marker before DNL", Concat (ZeroHeightSof, Sos, [0x01], [0xFF, 0xC4, 0x00, 0x02], Dnl, [0xFF, 0xD9]), 0]; + yield return ["DNL of zero lines", Concat (ZeroHeightSof, Sos, [0x01], [0xFF, 0xDC, 0x00, 0x04, 0x00, 0x00]), 0]; + yield return ["DNL with a wrong length", Concat (ZeroHeightSof, Sos, [0x01], [0xFF, 0xDC, 0x00, 0x05, 0x00, 0x05, 0x00]), 0]; + yield return ["DNL cut short", Concat (ZeroHeightSof, Sos, [0x01], [0xFF, 0xDC, 0x00, 0x04, 0x00]), 0]; + yield return ["scan ends in 0xFF", Concat (ZeroHeightSof, Sos, [0x01, 0xFF]), 0]; + yield return ["scan header cut short", Concat (ZeroHeightSof, [0xFF, 0xDA, 0x00, 0x08, 0x01]), 0]; + } + + [TestMethod] + [DynamicData (nameof (DnlLayouts))] + public void Jpeg_ZeroSofHeight_ReadsTheDnlAfterTheFirstScan (string layout, byte[] data, int height) + { + var opened = MediaFile.ReadFromData (data, "a.jpg"); + if (height == 0) { + Assert.IsFalse (opened.IsSuccess, layout); + return; + } + + Assert.IsTrue (opened.IsSuccess, $"{layout}: {opened.Error}"); + var image = (IMediaFile)opened.File!; + Assert.AreEqual (8, image.ImageProperties!.Value.Width, layout); + Assert.AreEqual (height, image.ImageProperties.Value.Height, layout); + } + + [TestMethod] + public void Jpeg_DnlScan_DoesNotAllocatePerScanByte () + { + static byte[] Build (int n) => Concat (ZeroHeightSof, Sos, Enumerable.Repeat (new byte[] { 0xFF, 0x00, 0x11 }, n).SelectMany (b => b).ToArray (), Dnl); + var data = Build (200_000); + MediaFileResult? opened = null; + var allocated = Bounds.LeastAllocated (() => opened = MediaFile.ReadFromData (data, "a.jpg")); + Assert.IsTrue (opened!.IsSuccess, opened.Error); + Assert.IsTrue (allocated < 16 * 1024, $"a 600 KB scan allocated {allocated} bytes"); + } + + [TestMethod] + public void Read_Jpeg_ReportsSofSize () + { + // APP0 before SOF, so the size is not in the first 32 bytes. + var data = Jpeg (width: 320, height: 240, app0: 40); + AssertImage (data, "photo.jpg", MediaFormat.Jpeg, 320, 240, "JPEG"); + Assert.AreEqual (8, ImageOf (data, "photo.jpg").ImageProperties!.Value.ColorDepth); + } + + [TestMethod] + public void Read_Jpeg_ColorDepthIsPrecisionTimesComponents () + { + var data = Jpeg (width: 10, height: 4, app0: 0, components: 3); + AssertImage (data, "photo.jpg", MediaFormat.Jpeg, 10, 4, "JPEG"); + Assert.AreEqual (24, ImageOf (data, "photo.jpg").ImageProperties!.Value.ColorDepth); + } + + static byte[] Jpeg (int width, int height, int app0, int components = 1) + { + using var ms = new MemoryStream (); + ms.Write ([0xFF, 0xD8, 0xFF, 0xE0]); + ushort length = (ushort)(2 + app0); + ms.Write ([(byte)(length >> 8), (byte)length]); + ms.Write (new byte[app0]); + var sofLength = 8 + (components * 3); + ms.Write ([0xFF, 0xC0, (byte)(sofLength >> 8), (byte)sofLength, 0x08]); + ms.Write ([(byte)(height >> 8), (byte)height, (byte)(width >> 8), (byte)width]); + ms.Write ([(byte)components]); + for (var component = 0; component < components; component++) + ms.Write ([0x01, 0x11, 0x00]); + return ms.ToArray (); + } +} diff --git a/tests/TagLibSharp2.Tests/Image/MakerNoteByteTests.cs b/tests/TagLibSharp2.Tests/Image/MakerNoteByteTests.cs new file mode 100644 index 00000000..1575015b --- /dev/null +++ b/tests/TagLibSharp2.Tests/Image/MakerNoteByteTests.cs @@ -0,0 +1,807 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Diagnostics; +using TagLibSharp2.Core; +using TagLibSharp2.Image; +using TagLibSharp2.Image.Exif; +using TagLibSharp2.Image.Tiff; +using TagLibSharp2.Tests.Core; +using TagLibSharp2.Tests.Kit; +using static TagLibSharp2.Tests.Image.ImageTestBuilder; + +namespace TagLibSharp2.Tests.Image; + +/// +/// A removed value is cleared only on bytes no other structure uses. A maker note's value, and a value its entries +/// name outside that blob, stay. The entry itself is still removed. +/// +[TestClass] +[TestCategory ("Unit")] +public partial class MakerNoteByteTests +{ + static readonly byte[] Marker = "ASCII\0\0\0"u8.ToArray (); + static readonly byte[] Private = "KEEPKEEP"u8.ToArray (); + + [TestMethod] + [DataRow ("comment", false, true)] + [DataRow ("comment", true, true)] + [DataRow ("artist", false, true)] + [DataRow ("copyright", false, true)] + [DataRow ("description", false, true)] + [DataRow ("xpcomment", false, true)] + [DataRow ("comment", false, false)] + public void Edit_KeepsBytesAMakerNoteEntryNames (string field, bool bigEndian, bool shared) + { + var tiff = NoteTiff (field, bigEndian, entries: 1, shared); + var file = Open (Png (PngChunk ("eXIf", tiff)), "a.png"); + SetField (file.Tag!, field); + var save = file.SaveToFile ("/a.png", new MockFileSystem ()); + Assert.IsTrue (save.IsSuccess, $"{field} {(bigEndian ? "BE" : "LE")} shared={shared}: {save.Error}"); + var output = PngPayload (file.Render ().ToArray (), "eXIf"); + var sharedAt = SharedAt (entries: 1, field); + Assert.AreEqual (0, CountTag (output, FieldTag (field), bigEndian), $"{field}: the entry is removed"); + CollectionAssert.AreEqual (Marker, output[sharedAt..(sharedAt + Marker.Length)], $"{field}: the named bytes stay"); + if (!shared) + CollectionAssert.AreEqual (new byte[Private.Length], output[(sharedAt + Marker.Length)..(sharedAt + Marker.Length + Private.Length)], $"{field}: an unshared value is cleared"); + } + + // The note's only out-of-line value uses offset 80 counted from the note, so the bytes sit inside the note. + // The comment sits at absolute offset 80. Reading 80 from the TIFF start would keep the comment. + [TestMethod] + [DataRow (false)] + [DataRow (true)] + public void Edit_NoteRelativeValue_DoesNotKeepAnOutsideComment (bool bigEndian) + { + const int commentAt = 80; + const int noteAt = 200; + const int relative = 80; + const int noteLen = 100; + var marker = "NOTEDATA"u8.ToArray (); + var comment = "COMMENT!"u8.ToArray (); + var tiff = new TiffBuilder (noteAt + noteLen, bigEndian).Header (8); + tiff.Table (8, [(0x8769, 4, 1L, 26L)]); + tiff.Table (26, [(0x927C, 7, (long)noteLen, (long)noteAt), (0x9286, 7, (long)comment.Length, (long)commentAt)]); + tiff.Table (noteAt, [(0x0001, 7, (long)marker.Length, (long)relative)]); + tiff.Bytes (noteAt + relative, marker); + tiff.Bytes (commentAt, comment); + var file = Open (Png (PngChunk ("eXIf", tiff.ToArray ())), "a.png"); + file.Tag!.Comment = "New"; + var save = file.SaveToFile ("/a.png", new MockFileSystem ()); + Assert.IsTrue (save.IsSuccess, save.Error); + var output = PngPayload (file.Render ().ToArray (), "eXIf"); + CollectionAssert.AreEqual (marker, output[(noteAt + relative)..(noteAt + relative + marker.Length)], "the note's own value stays"); + CollectionAssert.AreEqual (new byte[comment.Length], output[commentAt..(commentAt + comment.Length)], "the comment is not the note"); + } + + // exiftool 13.55 reads this Panasonic note's 0x004E as FaceDetInfo. The comment value is those bytes. + [TestMethod] + public void Edit_PanasonicFaceInfo_StaysForExiftool () + { + if (!ExiftoolPresent ()) + Assert.Inconclusive ("exiftool is not on PATH."); + var path = Path.GetTempFileName (); + try { + File.WriteAllBytes (path, Jpeg (JpegExif (NoteTiff ("comment", bigEndian: false, entries: 1, shared: true)))); + var before = Exiftool (path); + var file = Open (File.ReadAllBytes (path), "a.jpg"); + file.Tag!.Comment = "New"; + Assert.IsTrue (file.SaveToFile (path, new MockFileSystem ()).IsSuccess); + File.WriteAllBytes (path, file.Render ().ToArray ()); + var after = Exiftool (path); + Assert.AreEqual (Group (before, "Panasonic", "NumFacePositions"), Group (after, "Panasonic", "NumFacePositions")); + Assert.AreEqual ("21313", Group (after, "Panasonic", "NumFacePositions")); + Assert.AreEqual (Group (before, "Panasonic", "Face1Position"), Group (after, "Panasonic", "Face1Position")); + Assert.IsNull (Group (after, "ExifIFD", "UserComment"), after); + StringAssert.Contains (after, "New"); + } finally { + File.Delete (path); + } + } + + // Sony tag 0x2001 names the preview after the main image. A comment edit saves, as exiftool does. + // The pointer is left stale (#163). The maker-note bytes and the trailer bytes keep their contents. + [TestMethod] + public void Edit_SampleSony1_SavesACommentAndKeepsTheMakerNoteAndTrailer () + { + AssertSonyCommentMovesTheTrailer ("sample_sony1.jpg"); + } + + // Sony tag 0x2001 names an offset past the file, and a trailer follows the main image. + [TestMethod] + public void Edit_SampleSony2_SavesACommentAndKeepsTheMakerNoteAndTrailer () + { + AssertSonyCommentMovesTheTrailer ("sample_sony2.jpg"); + } + + // The same shape as the Sony samples, built in the test so CI runs it: a "SONY DSC" note whose second + // entry is tag 0x2001. One row names the trailer inside the file; the other names an offset past the file. + [TestMethod] + [DataRow (false, DisplayName = "0x2001 names the trailer")] + [DataRow (true, DisplayName = "0x2001 names past the file, trailer follows EOI")] + public void Comment_OfASonyPreviewPointer_SavesAndMovesTheTrailer (bool offsetPastFile) + { + var preview = "PREVIEW!"u8.ToArray (); + var fileBytes = SonyPreviewJpeg (preview, offsetPastFile); + var file = Open (fileBytes, "a.jpg"); + file.Tag!.Comment = "New"; + var save = file.SaveToFile ("/a.jpg", new MockFileSystem ()); + + Assert.IsTrue (save.IsSuccess, save.Error); + var output = file.Render ().ToArray (); + Assert.AreEqual ("New", Open (output, "a.jpg").Tag!.Comment); + AssertSameNoteAndTrailer (fileBytes, output); + Assert.AreEqual (fileBytes.Length + 7, output.Length); + } + + static void AssertSonyCommentMovesTheTrailer (string name) + { + if (!ExiftoolPresent ()) + Assert.Inconclusive ("exiftool is not on PATH."); + var sample = CorpusSample (name); + var before = ExiftoolVerbose (sample); + StringAssert.Contains (before, "PreviewImage", before); + var original = File.ReadAllBytes (sample); + var file = Open (original, name); + file.Tag!.Comment = "New"; + var save = file.SaveToFile ("/a.jpg", new MockFileSystem ()); + + Assert.IsTrue (save.IsSuccess, save.Error); + var output = file.Render ().ToArray (); + Assert.AreEqual ("New", Open (output, name).Tag!.Comment); + AssertSameNoteAndTrailer (original, output); + Assert.IsTrue (output.Length > original.Length); + } + + // The maker-note blob and the bytes after the main image's EOI are the same sequence. Their positions may differ. + static void AssertSameNoteAndTrailer (byte[] before, byte[] after) + { + var noteBefore = MakerNoteBlob (before); + var noteAfter = MakerNoteBlob (after); + CollectionAssert.AreEqual (noteBefore, noteAfter); + var trailerBefore = before[(MainEoi (before) + 2)..]; + var trailerAfter = after[(MainEoi (after) + 2)..]; + CollectionAssert.AreEqual (trailerBefore, trailerAfter); + Assert.AreNotEqual (MainEoi (before), MainEoi (after)); + } + + static byte[] MakerNoteBlob (byte[] jpeg) + { + var exif = jpeg.AsSpan ().IndexOf ("Exif\0\0"u8); + Assert.IsTrue (exif >= 0, "Exif"); + var tiffAt = exif + 6; + var tiff = jpeg.AsSpan (tiffAt); + Assert.IsTrue (tiff[0] == (byte)'I' && tiff[1] == (byte)'I' && tiff[2] == 42); + var ifd0 = System.Buffers.Binary.BinaryPrimitives.ReadInt32LittleEndian (tiff.Slice (4)); + var exifIfd = IfdPointer (tiff, ifd0, 0x8769).Offset; + var note = IfdPointer (tiff, exifIfd, 0x927C); + return jpeg[(tiffAt + note.Offset)..(tiffAt + note.Offset + note.Count)]; + } + + static (int Offset, int Count) IfdPointer (ReadOnlySpan tiff, int ifd, int tag) + { + var count = System.Buffers.Binary.BinaryPrimitives.ReadUInt16LittleEndian (tiff.Slice (ifd)); + for (var n = 0; n < count; n++) { + var entry = ifd + 2 + (12 * n); + if (System.Buffers.Binary.BinaryPrimitives.ReadUInt16LittleEndian (tiff.Slice (entry)) != tag) + continue; + var values = System.Buffers.Binary.BinaryPrimitives.ReadInt32LittleEndian (tiff.Slice (entry + 4)); + var offset = System.Buffers.Binary.BinaryPrimitives.ReadInt32LittleEndian (tiff.Slice (entry + 8)); + return (offset, values); + } + + Assert.Fail ($"tag {tag:X4} is missing"); + return (0, 0); + } + + static int MainEoi (byte[] data) + { + var i = 2; + while (i + 1 < data.Length) { + if (data[i] != 0xFF) { + i++; + continue; + } + + while (i < data.Length && data[i] == 0xFF) + i++; + if (i >= data.Length) + break; + var marker = data[i++]; + if (marker == 0x00) + continue; + if (marker == 0xD9) + return i - 2; + if (marker == 0x01 || marker is >= 0xD0 and <= 0xD8) + continue; + if (i + 1 >= data.Length) + break; + var length = (data[i] << 8) | data[i + 1]; + if (length < 2 || i + length > data.Length) + break; + if (marker == 0xDA) { + for (var j = i + length; j + 1 < data.Length; j++) { + if (data[j] != 0xFF) + continue; + if (data[j + 1] == 0x00) { + j++; + continue; + } + + if (data[j + 1] == 0xD9) + return j; + } + + break; + } + + i += length; + } + + Assert.Fail ("no EOI"); + return 0; + } + + // "SONY DSC", three NULs, then a two-entry IFD. Entry 0 is inline ASCII. Entry 1 is tag 0x2001 and names + // after the image, or an offset past the file. + static byte[] SonyPreviewJpeg (byte[] preview, bool offsetPastFile) + { + var header = "SONY DSC \0\0\0"u8.ToArray (); + const int ifd0 = 8; + var exif = ifd0 + 2 + 12 + 4; + var note = exif + 2 + (2 * 12) + 4; + // Header, then a two-entry IFD (count, two entries, next offset). The comment sits after that. + var noteLen = header.Length + 2 + (2 * 12) + 4; + var commentAt = note + noteLen; + var length = commentAt + 8; + + byte[] Tiff (int previewOffset) + { + var tiff = new TiffBuilder (length).Header (ifd0); + tiff.Table (ifd0, [(0x8769, 4, 1, exif)]); + tiff.Table (exif, [(0x927C, 7, noteLen, note), (0x9286, 7, 8, commentAt)]); + tiff.Bytes (note, header); + tiff.Entries (note + header.Length, (0x0001, 2, 4, 0x64636261), (0x2001, 7, preview.Length, previewOffset)); + tiff.Bytes (commentAt, "COMMENT!"u8); + return tiff.ToArray (); + } + + byte[] Wrap (byte[] tiff) => Jpeg (JpegExif (tiff)); + var probe = Concat (Wrap (Tiff (0)), preview); + var tiffBase = probe.AsSpan ().IndexOf ("II*"u8); + var offset = offsetPastFile ? 0x100000 : probe.Length - preview.Length - tiffBase; + return Concat (Wrap (Tiff (offset)), preview); + } + + // The real sample: UserComment's 8 bytes are also Panasonic tag 0x004E. Face positions stay, the comment changes. + [TestMethod] + public void Edit_SamplePanasonic_KeepsFacePositions () + { + if (!ExiftoolPresent ()) + Assert.Inconclusive ("exiftool is not on PATH."); + var sample = CorpusSample ("sample_panasonic.jpg"); + + var before = Exiftool (sample); + var edited = Path.GetTempFileName (); + try { + var file = Open (File.ReadAllBytes (sample), "sample_panasonic.jpg"); + file.Tag!.Comment = "New"; + var save = file.SaveToFile (edited, new MockFileSystem ()); + Assert.IsTrue (save.IsSuccess, save.Error); + File.WriteAllBytes (edited, file.Render ().ToArray ()); + var after = Exiftool (edited); + foreach (var name in new[] { "NumFacePositions", "Face1Position", "Face2Position", "Face3Position", "Face4Position", "Face5Position" }) + Assert.AreEqual (Group (before, "Panasonic", name), Group (after, "Panasonic", name), name); + Assert.AreEqual ("21313", Group (after, "Panasonic", "NumFacePositions")); + Assert.IsNull (Group (after, "ExifIFD", "UserComment"), after); + } finally { + File.Delete (edited); + } + } + + // A version byte, a type past 12, or a spent entry budget means the note was not fully located, so the whole + // removed value stays. A header of ASCII and NUL (Panasonic, Sony, Canon at 0) is located: only the bytes + // the entry names stay, and the tail is cleared. + [TestMethod] + [DataRow ("olympus", true)] + [DataRow ("sanyo", true)] + [DataRow ("epson", true)] + [DataRow ("nikon", true)] + [DataRow ("panasonic", false)] + [DataRow ("sony", false)] + [DataRow ("canon", false)] + [DataRow ("flipped", true)] + public void Edit_UnlocatedMakerNote_LeavesTheValueOutsideTheTables (string kind, bool keepTail) + { + var (tiff, at) = VendorNote (kind, tail: true); + var file = Open (Png (PngChunk ("eXIf", tiff)), "a.png"); + file.Tag!.Comment = "New"; + var save = file.SaveToFile ("/a.png", new MockFileSystem ()); + Assert.IsTrue (save.IsSuccess, $"{kind}: {save.Error}"); + var output = PngPayload (file.Render ().ToArray (), "eXIf"); + CollectionAssert.AreEqual (Marker, output[at..(at + Marker.Length)], $"{kind}: the named bytes stay"); + var tail = output[(at + Marker.Length)..(at + Marker.Length + Private.Length)]; + if (keepTail) + CollectionAssert.AreEqual (Private, tail, $"{kind}: a note that was not located leaves the rest"); + else + CollectionAssert.AreEqual (new byte[Private.Length], tail, $"{kind}: a located note clears bytes it does not name"); + } + + // The overlapping notes of notes2.py are more entries than the block has bytes, so the walk stops. + [TestMethod] + public void Edit_WhenMakerNoteEntriesPassTheBlock_LeavesTheValueOutsideTheTables () + { + var tiff = OverlappingMakerNotes (200, bigEndian: false); + var file = Open (Png (PngChunk ("eXIf", tiff)), "a.png"); + file.Tag!.Description = "x"; + var save = file.SaveToFile ("/a.png", new MockFileSystem ()); + Assert.IsTrue (save.IsSuccess, save.Error); + var output = PngPayload (file.Render ().ToArray (), "eXIf"); + CollectionAssert.AreEqual ("old-desc"u8.ToArray (), output[^8..], "a note past the budget is not located, so the description stays"); + } + + // exiftool 13.55 -v3. The line is the maker-note value measured on the unedited file. + [TestMethod] + [DataRow ("olympus", "SpecialMode = ASCII")] + [DataRow ("sanyo", "SpecialMode = ASCII")] + [DataRow ("epson", "SpecialMode = ASCII")] + [DataRow ("nikon", "Quality = ASCII")] + [DataRow ("panasonic", "NumFacePositions = 21313")] + [DataRow ("sony", "PreviewImage = ASCII")] + [DataRow ("canon", "41 53 43 49 49 00 00 00")] + public void Edit_VendorMakerNote_StaysForExiftool (string kind, string line) + { + if (!ExiftoolPresent ()) + Assert.Inconclusive ("exiftool is not on PATH."); + var path = Path.GetTempFileName (); + try { + File.WriteAllBytes (path, Jpeg (JpegExif (VendorNote (kind, tail: false).Tiff))); + var before = ExiftoolVerbose (path); + StringAssert.Contains (before, line, $"{kind} before\n{before}"); + var file = Open (File.ReadAllBytes (path), "a.jpg"); + file.Tag!.Comment = "New"; + Assert.IsTrue (file.SaveToFile (path, new MockFileSystem ()).IsSuccess); + File.WriteAllBytes (path, file.Render ().ToArray ()); + var after = ExiftoolVerbose (path); + StringAssert.Contains (after, line, $"{kind} after\n{after}"); + } finally { + File.Delete (path); + } + } + + // One pass over the maker-note entries: 4x the entries stays under 6x the steps. + [TestMethod] + [DataRow (false)] + [DataRow (true)] + public void Edit_MakerNoteEntries_AreLinearInTheEntries (bool bigEndian) + { + const int n = 500; + long Steps (int entries) + { + var tiff = NoteTiff ("comment", bigEndian, entries, shared: true); + var file = Open (Png (PngChunk ("eXIf", tiff)), "a.png"); + file.Tag!.Comment = "New"; + IfdSteps.Count = 0; + var save = file.SaveToFile ("/a.png", new MockFileSystem ()); + var steps = IfdSteps.Count; + Assert.IsTrue (save.IsSuccess, $"{entries}: {save.Error}"); + var output = PngPayload (file.Render ().ToArray (), "eXIf"); + var at = SharedAt (entries, "comment"); + CollectionAssert.AreEqual (Marker, output[at..(at + Marker.Length)], $"{entries}: the named bytes stay"); + return steps; + } + + var small = Steps (n); + var large = Steps (4 * n); + var row = bigEndian ? "BE" : "LE"; + Assert.IsTrue (large <= Math.Max (6 * small, 64), $"{row}: 4x the entries took {large / (double)Math.Max (small, 1):F1}x the steps ({small} -> {large})"); + } + + // T notes name one blob of T entries (notes.py). Each note used to walk that blob again. + [TestMethod] + [DataRow (false)] + [DataRow (true)] + public void Edit_MakerNotesSharingOneBlob_AreLinearInTheNotes (bool bigEndian) + { + const int n = 200; + long Steps (int count) + { + var tiff = SharedMakerNotes (count, bigEndian); + var file = Open (Png (PngChunk ("eXIf", tiff)), "a.png"); + file.Tag!.Description = "x"; + IfdSteps.Count = 0; + var save = file.SaveToFile ("/a.png", new MockFileSystem ()); + var steps = IfdSteps.Count; + Assert.IsTrue (save.IsSuccess, $"{count}: {save.Error}"); + var output = PngPayload (file.Render ().ToArray (), "eXIf"); + var at = output.Length - 8; + CollectionAssert.AreEqual (new byte[8], output[at..], $"{count}: the description value is cleared"); + return steps; + } + + var small = Steps (n); + var large = Steps (4 * n); + var row = bigEndian ? "BE" : "LE"; + Assert.IsTrue (large <= Math.Max (6 * small, 64), $"{row}: 4x the notes took {large / (double)Math.Max (small, 1):F1}x the steps ({small} -> {large})"); + } + + // T notes name one blob of T ASCII entries, and every entry names the same 8 bytes outside the note. + // Recording that blob again on each later note copies those ranges again (notes3.py, the 240 KB shape). + [TestMethod] + [DoNotParallelize] + public void Edit_MakerNotesSharingOutsideTargets_AllocatesLinearlyInTheNotes () + { + const int n = 250; + Bounds.AssertLinearAllocation ( + count => Png (PngChunk ("eXIf", OutsideTargetNotes (count))), + data => { + var opened = MediaFile.ReadFromData (data, "a.png"); + if (!opened.IsSuccess || opened.File is not StillImageFile file) + return; + file.Tag!.Description = "x"; + _ = file.Render (); + }, + n, + runs: 3); + + var check = Open (Png (PngChunk ("eXIf", OutsideTargetNotes (n))), "a.png"); + check.Tag!.Description = "x"; + var save = check.SaveToFile ("/a.png", new MockFileSystem ()); + Assert.IsTrue (save.IsSuccess, save.Error); + var output = PngPayload (check.Render ().ToArray (), "eXIf"); + CollectionAssert.AreEqual ("zzzzzzz\0"u8.ToArray (), output.AsSpan (output.Length - 16, 8).ToArray (), "the bytes the note names stay"); + CollectionAssert.AreEqual (new byte[8], output[^8..], "the description value is cleared"); + } + + // T out-of-line descriptions and one maker note whose blob starts at 0x01, so the note is not located + // (quad2.py, the 3.3 MB shape). Each removed value was checked against every table. + [TestMethod] + public void Edit_UnlocatedNoteWithManyRemovedValues_IsLinearInTheTables () + { + const int n = 200; + long Steps (int count) + { + var file = Open (Png (PngChunk ("eXIf", UnlocatedRemovedValues (count))), "a.png"); + file.Tag!.Description = "x"; + IfdSteps.Count = 0; + var save = file.SaveToFile ("/a.png", new MockFileSystem ()); + var steps = IfdSteps.Count; + Assert.IsTrue (save.IsSuccess, $"{count}: {save.Error}"); + var output = PngPayload (file.Render ().ToArray (), "eXIf"); + Assert.IsTrue (output.AsSpan ().IndexOf ("old-des\0"u8) >= 0, $"{count}: a value outside the tables stays"); + return steps; + } + + var small = Steps (n); + var large = Steps (4 * n); + Assert.IsTrue (large <= Math.Max (6 * small, 64), $"4x the tables took {large / (double)Math.Max (small, 1):F1}x the steps ({small} -> {large})"); + } + + // Note k is the suffix of one IFD starting at entry k (notes2.py). The ranges overlap, so they are not one blob. + [TestMethod] + [DataRow (false)] + [DataRow (true)] + public void Edit_OverlappingMakerNotes_AreLinearInTheNotes (bool bigEndian) + { + const int n = 200; + long Steps (int count) + { + var tiff = OverlappingMakerNotes (count, bigEndian); + var file = Open (Png (PngChunk ("eXIf", tiff)), "a.png"); + file.Tag!.Description = "x"; + IfdSteps.Count = 0; + var save = file.SaveToFile ("/a.png", new MockFileSystem ()); + var steps = IfdSteps.Count; + Assert.IsTrue (save.IsSuccess, $"{count}: {save.Error}"); + return steps; + } + + var small = Steps (n); + var large = Steps (4 * n); + var row = bigEndian ? "BE" : "LE"; + Assert.IsTrue (large <= Math.Max (6 * small, 64), $"{row}: 4x the notes took {large / (double)Math.Max (small, 1):F1}x the steps ({small} -> {large})"); + } + + static void SetField (Tag tag, string field) + { + switch (field) { + case "artist": tag.Artist = "New"; break; + case "copyright": tag.Copyright = "New"; break; + case "description": tag.Description = "New"; break; + default: tag.Comment = "New"; break; + } + } + + static int FieldTag (string field) => field switch { + "artist" => 0x013B, + "copyright" => 0x8298, + "description" => 0x010E, + "xpcomment" => 0x9C9C, + _ => 0x9286, + }; + + // IFD0, an Exif IFD, a Panasonic-shaped maker note of `entries` entries, then the shared 8 bytes. + static byte[] NoteTiff (string field, bool bigEndian, int entries, bool shared) + { + var commentInExif = field is "comment"; + var ifd0Count = commentInExif ? 1 : 2; + var exifCount = commentInExif ? 2 : 1; + var ifd0 = 8; + var exif = ifd0 + 2 + (12 * ifd0Count) + 4; + var note = exif + 2 + (12 * exifCount) + 4; + var noteLen = 12 + 2 + (12 * entries) + 4; + var sharedAt = note + noteLen; + var valueLen = Marker.Length + (shared ? 0 : Private.Length); + var length = sharedAt + valueLen; + var tiff = new TiffBuilder (length, bigEndian).Header (ifd0); + var exifPointer = (0x8769, 4, 1L, (long)exif); + var value = (FieldTag (field), field == "xpcomment" ? 1 : field == "comment" ? 7 : 2, (long)valueLen, (long)sharedAt); + if (commentInExif) + tiff.Table (ifd0, [exifPointer]); + else if (FieldTag (field) < 0x8769) + tiff.Table (ifd0, [value, exifPointer]); + else + tiff.Table (ifd0, [exifPointer, value]); + + var notePointer = (0x927C, 7, (long)noteLen, (long)note); + var userComment = (0x9286, 7, (long)valueLen, (long)sharedAt); + if (commentInExif) + tiff.Table (exif, [notePointer, userComment]); + else + tiff.Table (exif, [notePointer]); + + var noteEntries = new (int Tag, int Type, long Count, long Value)[entries]; + for (var i = 0; i < entries - 1; i++) + noteEntries[i] = (i + 1, 3, 1, 0); + // The note always names the marker. An unshared edit continues the field past those bytes, and only that tail is cleared. + noteEntries[^1] = (Math.Max (0x004E, entries), 7, Marker.Length, sharedAt); + tiff.Bytes (note, "Panasonic\0\0\0"u8.ToArray ()).Table (note + 12, noteEntries); + tiff.Bytes (sharedAt, Marker); + if (!shared) + tiff.Bytes (sharedAt + Marker.Length, Private); + return tiff.ToArray (); + } + + static int SharedAt (int entries, string field) + { + var commentInExif = field is "comment"; + var ifd0Count = commentInExif ? 1 : 2; + var exifCount = commentInExif ? 2 : 1; + var exif = 8 + 2 + (12 * ifd0Count) + 4; + var note = exif + 2 + (12 * exifCount) + 4; + return note + 12 + 2 + (12 * entries) + 4; + } + + static int CountTag (byte[] tiff, int tag, bool bigEndian) + { + var type = tag == 0x9C9C ? 1 : tag == 0x9286 ? 7 : 2; + var needle = bigEndian + ? new[] { (byte)(tag >> 8), (byte)tag, (byte)0, (byte)type } + : new[] { (byte)tag, (byte)(tag >> 8), (byte)type, (byte)0 }; + return Bytes.Count (tiff, needle); + } + + static string CorpusSample (string name) + { + var roots = Environment.GetEnvironmentVariable ("TAGLIBSHARP2_TEST_CORPUS"); + if (!string.IsNullOrEmpty (roots)) { + foreach (var root in roots.Split (':', StringSplitOptions.RemoveEmptyEntries)) { + var path = Path.Combine (root, name); + if (File.Exists (path)) + return path; + path = Path.Combine (root, "tests", "TaglibSharp.Tests", "samples", name); + if (File.Exists (path)) + return path; + } + } + + Assert.Inconclusive ($"Set TAGLIBSHARP2_TEST_CORPUS to a directory that contains {name}."); + return ""; + } + + static bool ExiftoolPresent () + { + var path = Environment.GetEnvironmentVariable ("PATH"); + if (string.IsNullOrEmpty (path)) + return false; + foreach (var dir in path.Split (Path.PathSeparator, StringSplitOptions.RemoveEmptyEntries)) { + if (File.Exists (Path.Combine (dir, "exiftool"))) + return true; + } + + return false; + } + + static string Exiftool (string path) + { + using var process = Process.Start (new ProcessStartInfo ("exiftool", ["-a", "-G1", "-s", path]) { + RedirectStandardOutput = true, + RedirectStandardError = true, + })!; + var text = process.StandardOutput.ReadToEnd (); + process.WaitForExit (); + Assert.AreEqual (0, process.ExitCode, process.StandardError.ReadToEnd ()); + return text; + } + + // The reviewer's vendor headers. A tail after the 8 named bytes shows whether the whole value was left alone. + static (byte[] Tiff, int Shared) VendorNote (string kind, bool tail) + { + var header = kind switch { + "olympus" => "OLYMP\0\u0001\0"u8.ToArray (), + "sanyo" => "SANYO\0\u0001\0"u8.ToArray (), + "epson" => "EPSON\0\u0001\0"u8.ToArray (), + "nikon" => "Nikon\0\u0001\0"u8.ToArray (), + "panasonic" or "flipped" => "Panasonic\0\0\0"u8.ToArray (), + "sony" => "SONY DSC \0\0\0"u8.ToArray (), + "canon" => [], + _ => throw new ArgumentException (kind), + }; + var make = kind switch { + "olympus" => "OLYMPUS\0"u8.ToArray (), + "sanyo" => "SANYO Electric Co.,Ltd.\0"u8.ToArray (), + "epson" => "SEIKO EPSON CORP.\0"u8.ToArray (), + "nikon" => "NIKON\0"u8.ToArray (), + "panasonic" or "flipped" => "Panasonic\0"u8.ToArray (), + "sony" => "SONY\0"u8.ToArray (), + _ => "Canon\0"u8.ToArray (), + }; + if (make.Length > 16) + make = [.. make.AsSpan (0, 15).ToArray (), 0]; + var tag = kind switch { + "nikon" => 0x0003, + "panasonic" or "flipped" => 0x004E, + "sony" => 0x2001, + "canon" => 0x0004, + _ => 0x0200, + }; + const int ifd0 = 8; + var exif = ifd0 + 2 + (2 * 12) + 4; + var note = exif + 2 + (2 * 12) + 4; + var noteLen = header.Length + 2 + 12 + 4; + var shared = note + noteLen; + var valueLen = Marker.Length + (tail ? Private.Length : 0); + var makeAt = Math.Max (200, shared + valueLen); + var length = makeAt + make.Length; + var tiff = new TiffBuilder (length).Header (ifd0); + tiff.Table (ifd0, [(0x010F, 2, make.Length, makeAt), (0x8769, 4, 1, exif)]); + tiff.Table (exif, [(0x927C, 7, noteLen, note), (0x9286, 7, valueLen, shared)]); + tiff.Bytes (note, header); + tiff.Entries (note + header.Length, (tag, kind == "flipped" ? 13 : 7, Marker.Length, shared)); + tiff.Bytes (shared, Marker); + if (tail) + tiff.Bytes (shared + Marker.Length, Private); + tiff.Bytes (makeAt, make); + return (tiff.ToArray (), shared); + } + + static string ExiftoolVerbose (string path) + { + using var process = Process.Start (new ProcessStartInfo ("exiftool", ["-v3", "-a", "-U", path]) { + RedirectStandardOutput = true, + RedirectStandardError = true, + })!; + var text = process.StandardOutput.ReadToEnd () + process.StandardError.ReadToEnd (); + process.WaitForExit (); + Assert.AreEqual (0, process.ExitCode, text); + return text; + } + + // IFD0 (ImageDescription, MakerNote) and T one-entry tables, each naming one blob of T inline SHORT entries. + static byte[] SharedMakerNotes (int count, bool bigEndian) + { + const int ifd0 = 8; + var first = ifd0 + 2 + (2 * 12) + 4; + var chain = new int[count]; + for (var k = 0; k < count; k++) + chain[k] = first + (18 * k); + var blob = count == 0 ? first : chain[count - 1] + 18; + var blobLen = 2 + (12 * count) + 4; + var descAt = blob + blobLen; + var tiff = new TiffBuilder (descAt + 8, bigEndian).Header (ifd0); + tiff.Table (ifd0, [(0x010E, 2, 8, descAt), (0x927C, 7, blobLen, blob)], count > 0 ? chain[0] : 0); + for (var k = 0; k < count; k++) + tiff.Table (chain[k], [(0x927C, 7, blobLen, blob)], k + 1 < count ? chain[k + 1] : 0); + var entries = new (int Tag, int Type, long Count, long Value)[count]; + for (var n = 0; n < count; n++) + entries[n] = (n + 1, 3, 1, 0); + tiff.Table (blob, entries); + tiff.Bytes (descAt, "old-desc"u8); + return tiff.ToArray (); + } + + // notes3.py: IFD0 is an out-of-line ImageDescription plus a MakerNote, then T one-entry tables that name the + // same blob. The blob is a classic IFD of T ASCII entries, each pointing at one shared 8-byte value. + static byte[] OutsideTargetNotes (int count) + { + const int ifd0 = 8; + var first = ifd0 + 2 + (2 * 12) + 4; + var chain = new int[count]; + for (var k = 0; k < count; k++) + chain[k] = first + (18 * k); + var blob = count == 0 ? first : chain[count - 1] + 18; + var blobLen = 2 + (12 * count) + 4; + var shared = blob + blobLen; + var descAt = shared + 8; + var tiff = new TiffBuilder (descAt + 8).Header (ifd0); + tiff.Table (ifd0, [(0x010E, 2, 8, descAt), (0x927C, 7, blobLen, blob)], count > 0 ? chain[0] : 0); + for (var k = 0; k < count; k++) + tiff.Table (chain[k], [(0x927C, 7, blobLen, blob)], k + 1 < count ? chain[k + 1] : 0); + var entries = new (int Tag, int Type, long Count, long Value)[count]; + for (var n = 0; n < count; n++) + entries[n] = (n + 1, 2, 8, shared); + tiff.Table (blob, entries); + tiff.Bytes (shared, "zzzzzzz\0"u8); + tiff.Bytes (descAt, "old-desc"u8); + return tiff.ToArray (); + } + + // quad2.py: IFD0 holds an ImageDescription and a maker note that is not a classic IFD, then T one-entry + // tables, each an ImageDescription of its own 8 bytes. + static byte[] UnlocatedRemovedValues (int count) + { + const int ifd0 = 8; + var first = ifd0 + 2 + (2 * 12) + 4; + var chain = new int[count]; + for (var k = 0; k < count; k++) + chain[k] = first + (18 * k); + var blob = count == 0 ? first : chain[count - 1] + 18; + const int blobLen = 16; + var values = blob + blobLen; + var tiff = new TiffBuilder (values + (8 * (count + 1))).Header (ifd0); + tiff.Table (ifd0, [(0x010E, 2, 8, values), (0x927C, 7, blobLen, blob)], count > 0 ? chain[0] : 0); + for (var k = 0; k < count; k++) + tiff.Table (chain[k], [(0x010E, 2, 8, values + (8 * (k + 1)))], k + 1 < count ? chain[k + 1] : 0); + var note = new byte[blobLen]; + note[0] = 0x01; + note[1] = 0x02; + note[2] = 0x03; + note[3] = 0x04; + for (var i = 4; i < blobLen; i++) + note[i] = 0xEE; + tiff.Bytes (blob, note); + for (var k = 0; k <= count; k++) + tiff.Bytes (values + (8 * k), "old-des\0"u8); + return tiff.ToArray (); + } + + // One IFD of C LONG entries whose high half is the count of the suffix IFD that starts at the next entry. + static byte[] OverlappingMakerNotes (int count, bool bigEndian) + { + var first = 8 + 2 + (2 * 12) + 4; + var chain = new int[count]; + for (var k = 0; k < count; k++) + chain[k] = first + (18 * k); + var blob = chain[count - 1] + 18; + var end = blob + 2 + (12 * count) + 4; + var tiff = new TiffBuilder (end + 8, bigEndian).Header (8); + tiff.Table (8, [(0x010E, 2, 8, end), (0x927C, 7, end - blob, blob)], chain[0]); + for (var k = 0; k < count; k++) + tiff.Table (chain[k], [(0x927C, 7, end - (blob + (12 * k)), blob + (12 * k))], k + 1 < count ? chain[k + 1] : 0); + var entries = new (int Tag, int Type, long Count, long Value)[count]; + for (var n = 0; n < count; n++) { + // The suffix count has to land on the first two bytes of the next entry, which is the high half + // of this value in little-endian and the low half in big-endian. + var suffix = count - (n + 1); + entries[n] = (n + 1, 4, 1, bigEndian ? suffix : (long)suffix << 16); + } + tiff.Table (blob, entries); + tiff.Bytes (end, "old-desc"u8); + return tiff.ToArray (); + } + + static string? Group (string dump, string group, string name) + { + foreach (var line in dump.Split ('\n')) { + if (!line.StartsWith ($"[{group}]", StringComparison.Ordinal)) + continue; + var rest = line[(group.Length + 2)..].TrimStart (); + if (!rest.StartsWith (name, StringComparison.Ordinal)) + continue; + var colon = rest.IndexOf (':'); + return colon < 0 ? "" : rest[(colon + 1)..].Trim (); + } + + return null; + } +} diff --git a/tests/TagLibSharp2.Tests/Image/MakerNotePinTests.cs b/tests/TagLibSharp2.Tests/Image/MakerNotePinTests.cs new file mode 100644 index 00000000..467ca5ba --- /dev/null +++ b/tests/TagLibSharp2.Tests/Image/MakerNotePinTests.cs @@ -0,0 +1,388 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Runtime.InteropServices; +using System.Text; +using TagLibSharp2.Core; +using TagLibSharp2.Image; +using TagLibSharp2.Image.Exif; +using TagLibSharp2.Image.Gif; +using TagLibSharp2.Image.Png; +using TagLibSharp2.Image.Svg; +using TagLibSharp2.Image.Tiff; +using TagLibSharp2.Tests.Core; +using TagLibSharp2.Tests.Kit; +using static TagLibSharp2.Tests.Image.ImageTestBuilder; + +namespace TagLibSharp2.Tests.Image; + +public partial class MakerNoteByteTests +{ + [TestMethod] + public void MakerTargetCoveringTheMiddleOfAComment_KeepsOnlyThatMiddle () + { + var bytes = CommentBesideMakerNote (ifdAt: 80, prefix: 0, commentAt: 160, comment: [0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88], targetAt: 162, targetCount: 6); + bytes[168] = 0x5A; + + IfdSteps.Count = 0; + Assert.IsTrue (ExifEditor.TryRemove (bytes, 0, CommentTag (), "eXIf", out var changed, out var error), error); + + Assert.IsTrue (changed); + CollectionAssert.AreEqual (new byte[] { 0x00, 0x00, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88 }, bytes[160..168]); + Assert.AreEqual (0x5A, bytes[168]); + // Two fewer than the old second copy of the tables: that list was only there to scan them again. + Assert.AreEqual (134L, IfdSteps.Count); + } + + [TestMethod] + public void MakerTargetsBeforeAndAfterAComment_KeepOnlyTheOverlap () + { + var comment = new byte[] { 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88 }; + var bytes = MakerNoteWithTargets (96, 230, comment, [ + (0x0001, 7, 8, 180), + (0x0002, 7, 8, 190), + (0x0003, 7, 8, 200), + (0x0004, 7, 8, 210), + (0x004E, 7, 6, 232), + (0x0100, 7, 5, 250), + ]); + bytes[238] = 0x5A; + bytes[249] = 0xA5; + + Assert.IsTrue (ExifEditor.TryRemove (bytes, 0, CommentTag (), "eXIf", out var changed, out var error), error); + + Assert.IsTrue (changed); + CollectionAssert.AreEqual (new byte[] { 0x00, 0x00, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88 }, bytes[230..238]); + Assert.AreEqual (0x5A, bytes[238]); + Assert.AreEqual (0xA5, bytes[249]); + } + + [TestMethod] + public void MakerNoteThatIsNotUndefined_DoesNotKeepItsTarget () + { + var bytes = CommentBesideMakerNote (ifdAt: 80, prefix: 0, commentAt: 160, comment: [0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88], targetAt: 162, targetCount: 6, noteType: 2); + bytes[168] = 0x5A; + + Assert.IsTrue (ExifEditor.TryRemove (bytes, 0, CommentTag (), "eXIf", out var changed, out var error), error); + + Assert.IsTrue (changed); + CollectionAssert.AreEqual (new byte[] { 0, 0, 0, 0, 0, 0, 0, 0 }, bytes[160..168]); + Assert.AreEqual (0x5A, bytes[168]); + } + + [TestMethod] + public void MakerIfdWhoseNextFieldSticksOutOfTheNote_LeavesTheComment () + { + // The entry fits in the 14-byte note. The 4-byte next field does not, so the note is not located and the + // comment, which sits outside the tables, stays. + var comment = new byte[] { 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88 }; + var bytes = new TiffBuilder (200).Header (8) + .Table (8, [(0x8769, 4, 1, 26)]) + .Table (26, [(0x927C, 7, 14, 80), (0x9286, 7, comment.Length, 160)]) + .Entries (80, (0x004E, 7, comment.Length, 160)) + .Bytes (160, comment) + .ToArray (); + + Assert.IsTrue (ExifEditor.TryRemove (bytes, 0, CommentTag (), "eXIf", out var changed, out var error), error); + + Assert.IsTrue (changed); + CollectionAssert.AreEqual (comment, bytes[160..168]); + } + + [TestMethod] + public void MakerTargetAtOffsetZero_KeepsTheComment () + { + var comment = new byte[] { 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88 }; + var bytes = CommentBesideMakerNote (ifdAt: 80, prefix: 0, commentAt: 160, comment: comment, targetAt: 0, targetCount: 180); + + Assert.IsTrue (ExifEditor.TryRemove (bytes, 0, CommentTag (), "eXIf", out var changed, out var error), error); + + Assert.IsTrue (changed); + CollectionAssert.AreEqual (comment, bytes[160..168]); + } + + [TestMethod] + public void MakerIfdAtTheLastPrefixByte_KeepsTheComment () + { + var comment = new byte[] { 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88 }; + var prefix = new byte[32]; + Array.Fill (prefix, (byte)'A'); + var bytes = new TiffBuilder (220).Header (8) + .Table (8, [(0x8769, 4, 1, 26)]) + .Table (26, [(0x927C, 7, 50, 80), (0x9286, 7, comment.Length, 160)]) + .Bytes (80, prefix) + .Entries (112, (0x004E, 7, comment.Length, 160)) + .Bytes (160, comment) + .ToArray (); + + Assert.IsTrue (ExifEditor.TryRemove (bytes, 0, CommentTag (), "eXIf", out var changed, out var error), error); + + Assert.IsTrue (changed); + CollectionAssert.AreEqual (comment, bytes[160..168]); + } + + [TestMethod] + public void MakerIfdWithARepeatedTag_LeavesTheComment () + { + var comment = new byte[] { 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88 }; + var bytes = new TiffBuilder (200).Header (8) + .Table (8, [(0x8769, 4, 1, 26)]) + .Table (26, [(0x927C, 7, 30, 80), (0x9286, 7, comment.Length, 160)]) + .Entries (80, (0x004E, 7, 4, 120), (0x004E, 7, comment.Length, 160)) + .Bytes (160, comment) + .ToArray (); + + Assert.IsTrue (ExifEditor.TryRemove (bytes, 0, CommentTag (), "eXIf", out var changed, out var error), error); + + Assert.IsTrue (changed); + CollectionAssert.AreEqual (comment, bytes[160..168]); + } + + [TestMethod] + public void MakerIfdOfTypeDouble_KeepsTheComment () + { + var comment = new byte[] { 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88 }; + var bytes = new TiffBuilder (200).Header (8) + .Table (8, [(0x8769, 4, 1, 26)]) + .Table (26, [(0x927C, 7, 18, 80), (0x9286, 7, comment.Length, 160)]) + .Entries (80, (0x004E, 12, 1, 160)) + .Bytes (160, comment) + .ToArray (); + + Assert.IsTrue (ExifEditor.TryRemove (bytes, 0, CommentTag (), "eXIf", out var changed, out var error), error); + + Assert.IsTrue (changed); + CollectionAssert.AreEqual (comment, bytes[160..168]); + } + + [TestMethod] + public void MakerValueThatRunsPastTheFile_DoesNotKeepTheComment () + { + var comment = new byte[] { 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88 }; + var bytes = new TiffBuilder (200).Header (8) + .Table (8, [(0x8769, 4, 1, 26)]) + .Table (26, [(0x927C, 7, 30, 80), (0x9286, 7, comment.Length, 180)]) + .Entries (80, (0x0001, 7, 50, 160), (0x004E, 7, comment.Length, 180)) + .Bytes (180, comment) + .ToArray (); + + Assert.IsTrue (ExifEditor.TryRemove (bytes, 0, CommentTag (), "eXIf", out var changed, out var error), error); + + Assert.IsTrue (changed); + CollectionAssert.AreEqual (new byte[comment.Length], bytes[180..188]); + } + + [TestMethod] + public void MakerNoteAtTheStartOfTheFile_KeepsTheCommentItsIfdNames () + { + // The note is the first 40 bytes, so it does not touch IFD0. Its pointer bytes are ASCII, and the IFD at + // offset 8 names the comment, which sits outside the note. + var comment = new byte[] { 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88 }; + var bytes = new TiffBuilder (200).Header (40) + .Entries (8, (0x004E, 7, comment.Length, 160)) + .Table (40, [(0x927C, 7, 40, 0), (0x9286, 7, comment.Length, 160)]) + .Bytes (160, comment) + .ToArray (); + + Assert.IsTrue (ExifEditor.TryRemove (bytes, 0, CommentTag (), "eXIf", out var changed, out var error), error); + + Assert.IsTrue (changed); + CollectionAssert.AreEqual (comment, bytes[160..168]); + } + + [TestMethod] + public void MakerTargetThatStartsBeforeTheNote_KeepsTheComment () + { + var comment = new byte[] { 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88 }; + var bytes = new TiffBuilder (220).Header (8) + .Table (8, [(0x8769, 4, 1, 26)]) + .Table (26, [(0x927C, 7, 18, 180), (0x9286, 7, comment.Length, 160)]) + .Entries (180, (0x004E, 7, comment.Length, 160)) + .Bytes (160, comment) + .ToArray (); + + Assert.IsTrue (ExifEditor.TryRemove (bytes, 0, CommentTag (), "eXIf", out var changed, out var error), error); + + Assert.IsTrue (changed); + CollectionAssert.AreEqual (comment, bytes[160..168]); + } + + [TestMethod] + [DataRow (0x20)] + [DataRow (0x7E)] + public void MakerPrefixOfABoundaryAsciiByte_StillReachesTheIfd (int prefix) + { + var comment = new byte[] { 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88 }; + var bytes = new TiffBuilder (200).Header (8) + .Table (8, [(0x8769, 4, 1, 26)]) + .Table (26, [(0x927C, 7, 19, 80), (0x9286, 7, comment.Length, 160)]) + .Bytes (80, [(byte)prefix]) + .Entries (81, (0x004E, 7, comment.Length, 160)) + .Bytes (160, comment) + .ToArray (); + + Assert.IsTrue (ExifEditor.TryRemove (bytes, 0, CommentTag (), "eXIf", out var changed, out var error), error); + + Assert.IsTrue (changed); + CollectionAssert.AreEqual (comment, bytes[160..168]); + } + + [TestMethod] + public void SameArrayNamedByBothSidesOfAPair_KeepsTheCommentThatArrayCovers () + { + var comment = new byte[] { 0xAB, 0xAB, 0xAB, 0xAB, 0xAB, 0xAB, 0xAB, 0xAB }; + var bytes = new TiffBuilder (200).Header (8) + .Table (8, [(0x0111, 3, 60, 50), (0x0117, 3, 60, 50), (0x9286, 7, comment.Length, 180)]) + .Bytes (180, comment) + .ToArray (); + for (var n = 0; n < 60; n++) + System.Buffers.Binary.BinaryPrimitives.WriteUInt16LittleEndian (bytes.AsSpan (50 + (n * 2)), 100); + + ExifEditor.SkipCheck = true; + try { + Assert.IsTrue (ExifEditor.TryRemove (bytes, 0, CommentTag (), "eXIf", out var changed, out var error), error); + Assert.IsTrue (changed); + CollectionAssert.AreEqual (comment, bytes[180..188]); + } finally { + ExifEditor.SkipCheck = false; + } + } + + [TestMethod] + public void BinaryByte_StopsTheMakerNote_AndLeavesTheComment () + { + var comment = new byte[] { 0xAB, 0xAB, 0xAB, 0xAB, 0xAB, 0xAB }; + var bytes = CommentBesideMakerNote (ifdAt: 81, prefix: 0x1F, commentAt: 160, comment: comment, targetAt: 160, targetCount: 6); + + Assert.IsTrue (ExifEditor.TryRemove (bytes, 0, CommentTag (), "eXIf", out var changed, out var error), error); + + Assert.IsTrue (changed); + CollectionAssert.AreEqual (comment, bytes[160..166]); + } + + /// + /// IFD0 points at an Exif IFD that holds an out-of-line UserComment and a maker note. The note's one entry + /// names bytes at . + /// + static byte[] CommentBesideMakerNote (int ifdAt, byte prefix, int commentAt, byte[] comment, int targetAt, int targetCount, int noteType = 7) + { + var blob = new byte[40]; + blob[0] = prefix; + var built = new TiffBuilder (200).Header (8) + .Table (8, [(0x8769, 4, 1, 26)]) + .Table (26, [(0x927C, noteType, blob.Length, 80), (0x9286, 7, comment.Length, commentAt)]) + .Bytes (80, blob) + .Entries (ifdAt, (0x004E, 7, targetCount, targetAt)) + .Bytes (commentAt, comment); + return built.ToArray (); + } + + static byte[] MakerNoteWithTargets (int blobLength, int commentAt, byte[] comment, (int Tag, int Type, long Count, long Value)[] entries) + { + return new TiffBuilder (320).Header (8) + .Table (8, [(0x8769, 4, 1, 26)]) + .Table (26, [(0x927C, 7, blobLength, 80), (0x9286, 7, comment.Length, commentAt)]) + .Bytes (80, new byte[blobLength]) + .Entries (80, entries) + .Bytes (commentAt, comment) + .ToArray (); + } + + [TestMethod] + public void CommentBeforeTheFirstTable_StaysWhenTheNoteIsNotLocated () + { + var comment = new byte[] { 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA }; + var bytes = new TiffBuilder (120).Header (8) + .Table (8, [(0x8769, 4, 1, 30)], 100) + .Table (30, [(0x927C, 7, 18, 60), (0x9286, 7, comment.Length, 90)]) + .Entries (60, (0x0001, 0, 1, 0)) + .Bytes (90, comment) + .Table (100, []) + .ToArray (); + + Assert.IsTrue (ExifEditor.TryRemove (bytes, 0, CommentTag (), "eXIf", out var changed, out var error), error); + + Assert.IsTrue (changed); + CollectionAssert.AreEqual (comment, bytes[90..100]); + } + + [TestMethod] + public void CommentPastAnUnreadTable_IsCleared () + { + var comment = new byte[] { 0x11, 0x22, 0x33, 0x44, 0x55 }; + const int length = 80; + var bytes = new TiffBuilder (length).Header (8) + .Table (8, [(0x8769, 4, 1, 60), (0x9286, 2, comment.Length, length)]) + .U16 (60, 50) + .ToArray (); + + Assert.IsTrue (ExifEditor.TryRemove (bytes, 0, CommentTag (), "eXIf", out var changed, out var error), error); + + Assert.IsTrue (changed); + } + + [TestMethod] + public void SecondWalkOfAnUnlocatedNote_StillLeavesTheComment () + { + var comment = new byte[] { 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88 }; + var bytes = new TiffBuilder (220).Header (8) + .Table (8, [(0x8769, 4, 1, 38), (0x927C, 7, 18, 80)]) + .Table (38, [(0x927C, 7, 18, 80), (0x9286, 7, comment.Length, 180)]) + .Entries (80, (0x0001, 0, 1, 0)) + .Bytes (180, comment) + .ToArray (); + + Assert.IsTrue (ExifEditor.TryRemove (bytes, 0, CommentTag (), "eXIf", out var changed, out var error), error); + + Assert.IsTrue (changed); + CollectionAssert.AreEqual (comment, bytes[180..188]); + } + + // Twenty-four maker notes share one IFD and differ by a byte, so each walk counts its entries again. The reads + // reach the TIFF length on the last entry of the last note, and that entry is not read. + static byte[] NotesWhoseEntryReadsEqualTheTiffLength () + { + const int notes = 24; + const int entries = 34; + const int length = (notes * entries) - 1; + const int exif = 26; + var exifCount = notes + 1; + var commentAt = exif + 2 + (exifCount * 12) + 4; + var noteAt = commentAt + 8; + var table = 2 + (entries * 12) + 4; + var maker = new (int Tag, int Type, long Count, long Value)[entries]; + for (var n = 0; n < entries; n++) + maker[n] = (n + 1, 1, 1, 0); + var exifEntries = new (int Tag, int Type, long Count, long Value)[exifCount]; + for (var n = 0; n < notes; n++) + exifEntries[n] = (0x927C, 7, table + n, noteAt); + exifEntries[notes] = (0x9286, 7, 8, commentAt); + return new TiffBuilder (length).Header (8) + .Table (8, [(0x8769, 4, 1, exif)]) + .Table (exif, exifEntries) + .Entries (noteAt, maker) + .Bytes (commentAt, [0xC1, 0xC2, 0xC3, 0xC4, 0xC5, 0xC6, 0xC7, 0xC8]) + .ToArray (); + } + + [TestMethod] + public void Comment_StaysWhenMakerNoteEntryReadsReachTheTiffLength () + { + var sentinel = new byte[] { 0xC1, 0xC2, 0xC3, 0xC4, 0xC5, 0xC6, 0xC7, 0xC8 }; + var fileBytes = Png (PngChunk ("eXIf", NotesWhoseEntryReadsEqualTheTiffLength ())); + var file = Open (fileBytes, "a.png"); + file.Tag!.Comment = "New"; + + var save = file.SaveToFile ("/a.png", new MockFileSystem ()); + + Assert.IsTrue (save.IsSuccess, save.Error); + Assert.IsTrue (file.Render ().Span.IndexOf (sentinel) >= 0); + } + + static ImageTag CommentTag () + { + var tag = new ImageTag (MediaFormat.Png, ImageStores.Comment); + tag.Comment = "New"; + return tag; + } +} diff --git a/tests/TagLibSharp2.Tests/Image/MirrorCopyTests.cs b/tests/TagLibSharp2.Tests/Image/MirrorCopyTests.cs new file mode 100644 index 00000000..5017136b --- /dev/null +++ b/tests/TagLibSharp2.Tests/Image/MirrorCopyTests.cs @@ -0,0 +1,366 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Text; +using System.Xml.Linq; +using TagLibSharp2.Core; +using TagLibSharp2.Image; +using TagLibSharp2.Image.Exif; +using TagLibSharp2.Image.Tiff; +using TagLibSharp2.Image.Xmp; +using TagLibSharp2.Tests.Core; +using TagLibSharp2.Tests.Kit; +using static TagLibSharp2.Tests.Image.ExifTestData; +using static TagLibSharp2.Tests.Image.ImageTestBuilder; + +namespace TagLibSharp2.Tests.Image; + +/// The copies of a changed field in other blocks of the same file (XMP, Exif, keyword copies) change with it, and only those. +[TestClass] +[TestCategory ("Unit")] +public class MirrorCopyTests +{ + // field, XMP property, Exif tags that copy it + static readonly (string Field, XName Xmp, bool Ordered, int[] ExifTags)[] Fields = [ + ("Title", Dc + "title", false, [0x9C9B]), + ("Artist", Dc + "creator", true, [0x013B, 0x9C9D]), + ("Description", Dc + "description", false, [0x010E]), + ("Copyright", Dc + "rights", false, [0x8298]), + ("Comment", Exif + "UserComment", false, [0x9C9C, 0x9286]), + ]; + + static string AllProperties () => + Alt ("dc:title", "Old title") + Seq ("dc:creator", "Old one", "Old two") + Alt ("dc:description", "Old desc") + + Alt ("dc:rights", "Old rights") + Alt ("exif:UserComment", "Old comment") + " Keep label\n"; + + static byte[] AllExif () => ExifTiff ( + [(0x010E, "Old desc"), (0x010F, "Canon"), (0x013B, "Old artist"), (0x8298, "Old rights"), (0x9C9B, "XP title"), (0x9C9C, "XP comment"), (0x9C9D, "XP author")], + [(0x9003, "2001:01:01 00:00:00"), (0x9286, "ASCII\0\0\0Old comment")]); + + static readonly (string Name, Func Build)[] Carriers = [ + ("iTXt XMP", () => Xmp (XmpPacket (AllProperties ()))), + ("compressed iTXt XMP", () => Xmp (XmpPacket (AllProperties ()), compressed: true)), + ("ImageMagick raw XMP", () => RawProfile ("xmp", Encoding.UTF8.GetBytes (XmpPacket (AllProperties ())))), + ("eXIf", () => PngChunk ("eXIf", AllExif ())), + ("eXIf with Exif prefix", () => PngChunk ("eXIf", Concat ("Exif\0\0"u8.ToArray (), AllExif ()))), + ("ImageMagick raw EXIF", () => RawProfile ("exif", Concat ("Exif\0\0"u8.ToArray (), AllExif ()))), + ("exiftool Artist keyword", () => Text ("Artist", "Old artist")), + ]; + + public static IEnumerable Cases () => + from carrier in Carriers + from field in Fields + from value in new[] { "New ✓ <&>", null } + select new object?[] { carrier.Name, field.Field, value }; + + [TestMethod] + [DynamicData (nameof (Cases))] + public void Edit_ChangesTheMirroredCopy_AndOnlyThatOne (string carrier, string field, string? value) + { + // Each field holds a tEXt value too, so that null is a change (writing back the null read is not). + var input = Png ( + Carriers.Single (c => c.Name == carrier).Build (), Text ("Software", "keep"), Text ("Title", "t"), Text ("Author", "a"), + Text ("Description", "d"), Text ("Copyright", "c"), Text ("Comment", "m")); + var file = Open (input, "a.png"); + typeof (Tag).GetProperty (field)!.SetValue (file.Tag, value); + + var save = file.SaveToFile ("/a.png", new MockFileSystem ()); + Assert.IsTrue (save.IsSuccess, save.Error); + var output = file.Render ().ToArray (); + + var reread = Open (output, "a.png"); + Assert.AreEqual (value, typeof (Tag).GetProperty (field)!.GetValue (reread.Tag)); + Assert.AreSequenceEqual (["keep"], PngTexts (output, "Software")); + var spec = Fields.Single (f => f.Field == field); + if (carrier.StartsWith ("exiftool", StringComparison.Ordinal)) + Assert.AreSequenceEqual (field == "Artist" ? [] : ["Old artist"], PngTexts (output, "Artist")); + else if (carrier.Contains ("XMP", StringComparison.Ordinal)) + AssertXmp (Packet (input, carrier), Packet (output, carrier), spec.Xmp, spec.Ordered, value); + else + AssertExif (ExifStrings (carrier, input), ExifStrings (carrier, output), spec.ExifTags, ExifIn (carrier, output)!); + } + + static void AssertXmp (string before, string after, XName property, bool ordered, string? value) + { + var old = XDocument.Parse (before); + var updated = XDocument.Parse (after); + var found = updated.Descendants (property).ToList (); + if (value is null) { + Assert.AreEqual (0, found.Count, $"{property} should be removed"); + } else { + Assert.AreEqual (1, found.Count, $"{property} should be written once"); + var items = found[0].Element (Rdf + (ordered ? "Seq" : "Alt"))!.Elements (Rdf + "li").ToList (); + Assert.AreEqual (1, items.Count, "every old alternative or array item is replaced"); + Assert.AreEqual (value, items[0].Value); + if (!ordered) + Assert.AreEqual ("x-default", items[0].Attribute (XNamespace.Xml + "lang")!.Value); + } + + // Every other property keeps its exact text. + foreach (var other in old.Descendants ().Where (e => e.Parent?.Name == Rdf + "Description" && e.Name != property)) { + var text = Slice (before, other.Name); + StringAssert.Contains (after, text, $"{other.Name} changed"); + } + } + + static string Slice (string packet, XName name) + { + var prefix = name.Namespace == Dc ? "dc" : name.Namespace == Exif ? "exif" : "xmp"; + var open = $"<{prefix}:{name.LocalName}>"; + var close = $""; + var start = packet.IndexOf (open, StringComparison.Ordinal); + var end = packet.IndexOf (close, start, StringComparison.Ordinal) + close.Length; + return packet[start..end]; + } + + static void AssertExif (Dictionary before, Dictionary after, int[] removed, byte[] tiff) + { + foreach (var (tag, text) in before) { + if (removed.Contains (tag)) { + Assert.IsFalse (after.ContainsKey (tag), $"Exif tag 0x{tag:X4} should be removed"); + Assert.IsTrue (tiff.AsSpan ().IndexOf (Encoding.ASCII.GetBytes (text)) < 0, $"the removed value of 0x{tag:X4} is still in the block"); + } else + Assert.AreEqual (text, after[tag], $"Exif tag 0x{tag:X4} changed"); + } + } + + static string Packet (byte[] png, string carrier) + { + if (carrier.Contains ("raw", StringComparison.OrdinalIgnoreCase)) + return Encoding.UTF8.GetString (DecodeRawProfile (PngTexts (png, "Raw profile type xmp").Single ())); + return PngTexts (png, "XML:com.adobe.xmp").Single (); + } + + [TestMethod] + public void Edit_LeavesTheMirrorsOfUnchangedFieldsByteForByte () + { + var xmp = Xmp (XmpPacket (AllProperties ())); + var exif = PngChunk ("eXIf", AllExif ()); + var file = Open (Png (xmp, exif), "a.png"); + file.Tag!.Year = "2024"; + + var output = file.Render ().ToArray (); + + Assert.IsTrue (output.AsSpan ().IndexOf (xmp) >= 0); + Assert.IsTrue (output.AsSpan ().IndexOf (exif) >= 0); + } + + public static IEnumerable CopiesWithoutTheField () + { + // Each block would change if it were rebuilt: the packet holds a byte that is not UTF-8 (0xE9, as a + // Latin-1 writer leaves it), the compressed ones use another compressor level, and the raw profiles + // another hex line width. + var marked = Encoding.UTF8.GetBytes (XmpPacket (Seq ("dc:creator", "Someone") + " caf#\n")); + var packet = marked.Select (b => b == (byte)'#' ? (byte)0xE9 : b).ToArray (); + var utf8 = Encoding.UTF8.GetBytes (XmpPacket (Seq ("dc:creator", "Someone"))); + var exif = ExifTiff ([(0x010F, "Canon"), (0x013B, "Someone")], []); + var fast = System.IO.Compression.CompressionLevel.Fastest; + var itxt = RawItxt ("XML:com.adobe.xmp", packet); + var itxtZ = CompressedChunk ("XML:com.adobe.xmp", utf8, fast, itxt: true); + var ztxt = CompressedChunk ("XML:com.adobe.xmp", utf8, fast, itxt: false); + var rawXmp = RawProfile ("xmp", utf8, 32, fast); + var rawExif = RawProfile ("exif", Concat ("Exif\0\0"u8.ToArray (), exif), 32, fast); + var jpegXmp = JpegSegment (0xE1, Concat ("http://ns.adobe.com/xap/1.0/\0"u8.ToArray (), packet)); + var gifXmp = Concat (GifXmp ("").AsSpan (0, 14).ToArray (), packet, GifXmp ("").AsSpan (14).ToArray ()); + yield return ["png", "iTXt XMP with a Latin-1 byte", Png (itxt), itxt]; + yield return ["png", "compressed iTXt XMP", Png (itxtZ), itxtZ]; + yield return ["png", "zTXt XMP", Png (ztxt), ztxt]; + yield return ["png", "ImageMagick raw XMP", Png (rawXmp), rawXmp]; + yield return ["png", "eXIf", Png (PngChunk ("eXIf", exif)), PngChunk ("eXIf", exif)]; + yield return ["png", "ImageMagick raw EXIF", Png (rawExif), rawExif]; + yield return ["jpeg", "APP1 XMP with a Latin-1 byte", Jpeg (jpegXmp, JpegSegment (0xFE, "c"u8.ToArray ())), jpegXmp]; + yield return ["jpeg", "APP1 Exif", Jpeg (JpegExif (exif), JpegSegment (0xFE, "c"u8.ToArray ())), JpegExif (exif)]; + // T.81 §B.1.1.2: fill bytes (0xFF) may precede a marker; they belong to the kept bytes. + var filled = Concat ([0xFF, 0xFF], JpegExif (exif)); + yield return ["jpeg", "APP1 Exif after fill bytes", Jpeg (filled, JpegSegment (0xFE, "c"u8.ToArray ())), filled]; + yield return ["gif", "XMP with a Latin-1 byte", Gif (GifComment ("c"), gifXmp), gifXmp]; + } + + // The field edited (Title on PNG, Comment on JPEG and GIF) has no copy in the block, which keeps its bytes: + // a compressed chunk is not recompressed, and an Exif block is not rewritten. + [TestMethod] + [DynamicData (nameof (CopiesWithoutTheField))] + public void Edit_OfAFieldTheBlockDoesNotHold_KeepsTheBlockBytes (string format, string carrier, byte[] input, byte[] block) + { + var file = Open (input, format == "png" ? "a.png" : format == "jpeg" ? "a.jpg" : "a.gif"); + if (format == "png") + file.Tag!.Title = "New"; + else + file.Tag!.Comment = "New"; + Assert.IsTrue (file.Render ().ToArray ().AsSpan ().IndexOf (block) >= 0, carrier); + } + + // A copy no reader decodes holds nothing to update, so the edit saves and keeps its bytes: an ImageMagick raw + // profile that is not hexadecimal (exiftool: "Unknown raw profile"), and an XMP packet that is not well-formed + // (exiftool: "Empty XMP") whose text names none of the changed field's properties. A malformed packet that does + // name it is refused. Compressed XMP that is not zlib data, or an iTXt whose header is cut short, is decoded by + // no reader either (exiftool: "Error inflating"; no packet), and is kept. + [TestMethod] + [DataRow ("XMP that is not zlib data", "Title", true)] + [DataRow ("XMP whose iTXt header is cut short", "Comment", true)] + [DataRow ("raw EXIF profile that is not hex", "Title", true)] + [DataRow ("raw EXIF profile that is not hex", "Comment", true)] + [DataRow ("raw EXIF profile that is not hex", "Artist", true)] + [DataRow ("raw XMP profile that is not hex", "Title", true)] + [DataRow ("malformed XMP with only a creator", "Title", true)] + [DataRow ("malformed XMP with only a creator", "Comment", true)] + [DataRow ("malformed XMP with only a creator", "Artist", false)] + public void Edit_OfACopyNoReaderDecodes_SavesAndKeepsItsBytes (string shape, string field, bool saves) + { + var (chunk, type, keyword) = shape switch { + "XMP that is not zlib data" => (PngChunk ("zTXt", Concat ("XML:com.adobe.xmp\0\0"u8.ToArray (), [0x78, 0x9C, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0, 0, 0, 0])), "zTXt", "XML:com.adobe.xmp"), + "XMP whose iTXt header is cut short" => (PngChunk ("iTXt", Concat ("XML:com.adobe.xmp\0"u8.ToArray (), [1, 0, (byte)'e', (byte)'n'])), "iTXt", "XML:com.adobe.xmp"), + "raw EXIF profile that is not hex" => (CompressedText ("Raw profile type exif", "\nexif\n 4\nzzzz\n"u8.ToArray ()), "zTXt", "Raw profile type exif"), + "raw XMP profile that is not hex" => (CompressedText ("Raw profile type xmp", "\nxmp\n 4\nzzzz\n"u8.ToArray ()), "zTXt", "Raw profile type xmp"), + _ => (Xmp ("Jane"), "iTXt", "XML:com.adobe.xmp"), + }; + var input = Png (chunk); + var file = Open (input, "a.png"); + typeof (Tag).GetProperty (field)!.SetValue (file.Tag, "New"); + + var save = file.SaveToFile ("/a.png", new MockFileSystem ()); + + Assert.AreEqual (saves, save.IsSuccess, $"{shape} {field}: {save.Error}"); + if (saves) + CollectionAssert.AreEqual (chunk, PngTextChunk (file.Render ().ToArray (), type, keyword), $"{shape} {field}: the block keeps its bytes"); + else + StringAssert.Contains (save.Error, "not well-formed"); + } + + public static IEnumerable Refusals () + { + yield return ["not well-formed", Png (Xmp (XmpPacket (Alt ("dc:title", "Old")).Replace ("", "", StringComparison.Ordinal))), "Title", "New", "XMP"]; + yield return ["DTD", Png (Xmp ("]>" + XmpPacket (Alt ("dc:title", "&e;")))), "Title", "New", "DTD"]; + yield return ["value XML cannot store", Png (Xmp (XmpPacket (Alt ("dc:title", "Old")))), "Title", "bad\u0001", "XML cannot store"]; + yield return ["lone surrogate", Png (Xmp (XmpPacket (Alt ("dc:title", "Old")))), "Title", "bad\uD800", "XML cannot store"]; + // Not TIFF, and an entry for Artist (tag 0x013B, type 2) is in its bytes: a reader of another form could hold a copy. + yield return ["eXIf that is not TIFF", Png (PngChunk ("eXIf", [1, 2, 3, 4, 0x01, 0x3B, 0, 2, 9])), "Artist", "New", "not a TIFF structure"]; + yield return ["compressed XMP past the inflation cap", Png (Xmp (XmpPacket (Alt ("dc:title", "Old") + new string (' ', 1_100_000)), compressed: true)), "Title", "New", "all compressed text"]; + } + + [TestMethod] + [DynamicData (nameof (Refusals))] + public void Edit_ThatCannotUpdateAMirror_IsRefusedWithItsOwnReason (string shape, byte[] input, string field, string value, string reason) + { + var file = Open (input, "a.png"); + typeof (Tag).GetProperty (field)!.SetValue (file.Tag, value); + + var fs = new MockFileSystem (); + var save = file.SaveToFile ("/a.png", fs); + var saveAsync = file.SaveToFileAsync ("/b.png", fs).GetAwaiter ().GetResult (); + + Assert.IsFalse (save.IsSuccess, shape); + Assert.IsFalse (saveAsync.IsSuccess, shape); + StringAssert.Contains (save.Error, reason, shape); + Assert.AreEqual (save.Error, saveAsync.Error); + Assert.IsFalse (fs.FileExists ("/a.png")); + CollectionAssert.AreEqual (input, file.Render ().ToArray (), "Render returns the unchanged file"); + + file.Tag!.Clear (); + Assert.IsTrue (file.SaveToFile ("/a.png", fs).IsSuccess, $"{shape}: Clear drops the block instead"); + } + + [TestMethod] + public void Edit_BadCrcMirror_IsCopiedAsIs () + { + var xmp = Xmp (XmpPacket (Alt ("dc:title", "Old"))); + xmp[^1] ^= 0xFF; + var file = Open (Png (xmp), "a.png"); + file.Tag!.Title = "New"; + Assert.IsTrue (file.Render ().ToArray ().AsSpan ().IndexOf (xmp) >= 0); + } + + static readonly string CommentPacket = XmpPacket (Alt ("exif:UserComment", "Old xmp comment") + Alt ("dc:title", "Keep title")); + static byte[] CommentExif () => ExifTiff ([(0x010F, "Canon"), (0x9C9C, "Old XP comment")], [(0x9286, "ASCII\0\0\0Old user comment")]); + + public static IEnumerable CommentCopies () + { + foreach (var value in new[] { "New ✓ <&>", null }) { + yield return ["jpeg", "APP1 Exif", Jpeg (JpegExif (CommentExif ()), JpegSegment (0xFE, "Old"u8.ToArray ())), value!]; + yield return ["jpeg", "APP1 XMP", Jpeg (JpegXmp (CommentPacket), JpegSegment (0xFE, "Old"u8.ToArray ())), value!]; + yield return ["jpeg", "APP1 XMP with a space in its signature", Jpeg (JpegSegment (0xE1, Concat ("http://ns.adobe.com/xap/1.0/ \0"u8.ToArray (), Encoding.UTF8.GetBytes (CommentPacket))), JpegSegment (0xFE, "Old"u8.ToArray ())), value!]; + yield return ["gif", "XMP", Gif (GifComment ("Old"), GifXmp (CommentPacket)), value!]; + yield return ["gif", "XMP as data sub-blocks (ImageIO)", Gif (GifComment ("Old"), GifSubBlockXmp (CommentPacket)), value!]; + } + } + + // A JPEG or GIF stores only the comment, and its Exif and XMP copies are changed with it (rule 4). + [TestMethod] + [DynamicData (nameof (CommentCopies))] + public void JpegAndGif_CommentEdit_ChangesTheExifAndXmpCopies (string format, string carrier, byte[] input, string? value) + { + var name = format == "jpeg" ? "a.jpg" : "a.gif"; + var file = Open (input, name); + file.Tag!.Comment = value; + var save = file.SaveToFile ("/" + name, new MockFileSystem ()); + Assert.IsTrue (save.IsSuccess, save.Error); + var output = file.Render ().ToArray (); + Assert.AreEqual (value, Open (output, name).Tag!.Comment); + + if (carrier == "APP1 Exif") { + var at = output.AsSpan ().IndexOf ("Exif\0\0"u8) + 6; + var exif = ExifReaderModel.Of (output[at..]).Strings (); + Assert.IsFalse (exif.ContainsKey (0x9286) || exif.ContainsKey (0x9C9C), "UserComment and XPComment are removed"); + Assert.AreEqual ("Canon", exif[0x010F]); + Assert.IsTrue (output.AsSpan ().IndexOf ("Old user comment"u8) < 0 && output.AsSpan ().IndexOf ("Old XP comment"u8) < 0); + return; + } + + var text = Encoding.UTF8.GetString (carrier.Contains ("sub-blocks", StringComparison.Ordinal) ? JoinGifXmpSubBlocks (output) : output); + var packet = text.Split ("", StringComparison.Ordinal) + 19)]; + var doc = XDocument.Parse (packet); + var comments = doc.Descendants (Exif + "UserComment").ToList (); + if (value is null) { + Assert.AreEqual (0, comments.Count); + } else { + Assert.AreEqual (1, comments.Count); + Assert.AreEqual (value, comments[0].Value); + } + + Assert.AreEqual ("Keep title", doc.Descendants (Dc + "title").Single ().Element (Rdf + "Alt")!.Elements ().First ().Value); + if (carrier == "XMP") + Assert.IsTrue (output.AsSpan ().IndexOf (GifXmp ("").AsSpan (GifXmp ("").Length - 258)) > 0, "the magic trailer follows the new packet"); + } + + [TestMethod] + public void Jpeg_CommentEdit_ThatCannotUpdateACopy_IsRefusedWithItsOwnReason () + { + var extended = Jpeg (JpegApp (0xE1, "http://ns.adobe.com/xmp/extension/\0", "0123456789ABCDEF0123456789ABCDEF\0\0\0\x10\0\0\0\0"), JpegSegment (0xFE, "Old"u8.ToArray ())); + var full = Jpeg (JpegXmp (XmpPacket (Alt ("exif:UserComment", "Old"))), JpegSegment (0xFE, "Old"u8.ToArray ())); + var gif = Gif (GifComment ("Old"), GifApplication ("XMP DataXMP", ""u8.ToArray ())); + foreach (var (input, name, value, reason) in new[] { + (extended, "a.jpg", "New", "extended XMP"), + (full, "a.jpg", new string ('x', 70_000), "no longer fit"), + (gif, "a.gif", "New", "GIF XMP packet is not well-formed"), + }) { + var file = Open (input, name); + file.Tag!.Comment = value; + var result = file.SaveToFile ("/" + name, new MockFileSystem ()); + Assert.IsFalse (result.IsSuccess, reason); + StringAssert.Contains (result.Error, reason); + } + } + + [TestMethod] + public void JpegAndGif_TitleIsNotStored_SoItsCopiesAreNotTouched () + { + var jpeg = Jpeg (JpegXmp (CommentPacket), JpegSegment (0xFE, "Old"u8.ToArray ())); + var file = Open (jpeg, "a.jpg"); + file.Tag!.Title = "New"; + Assert.IsNull (file.Tag.Title); + CollectionAssert.AreEqual (jpeg, file.Render ().ToArray ()); + } + + static byte[] JoinGifXmpSubBlocks (byte[] gif) + { + var i = gif.AsSpan ().IndexOf ("XMP DataXMP"u8) + 11; + var joined = new List (); + while (gif[i] != 0) { + joined.AddRange (gif.AsSpan (i + 1, gif[i]).ToArray ()); + i += 1 + gif[i]; + } + + return [.. joined]; + } +} diff --git a/tests/TagLibSharp2.Tests/Image/MpfIndexTests.cs b/tests/TagLibSharp2.Tests/Image/MpfIndexTests.cs new file mode 100644 index 00000000..e7bf6671 --- /dev/null +++ b/tests/TagLibSharp2.Tests/Image/MpfIndexTests.cs @@ -0,0 +1,364 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Buffers.Binary; +using TagLibSharp2.Image.Jpeg; +using TagLibSharp2.Tests.Core; +using static TagLibSharp2.Tests.Image.ImageTestBuilder; + +namespace TagLibSharp2.Tests.Image; + +/// +/// The rules of the MP index (CIPA DC-007 §5.2): where it is found, when it can be followed, and how its entries +/// are rewritten. Image starts are the MPImageStart values exiftool shows for the same files (measured). +/// +[TestClass] +[TestCategory ("Unit")] +public class MpfIndexTests +{ + static readonly byte[] Two = Jpeg (JpegSegment (0xFE, "two"u8.ToArray ())); + static readonly byte[] Three = Jpeg (JpegSegment (0xFE, "three"u8.ToArray ())); + + /// How a test MP header is laid out. + internal sealed record Layout + { + public string Mark { get; init; } = "MM\0*"; + public bool VersionFirst { get; init; } + public bool EntryTag { get; init; } = true; + public int ListShift { get; init; } + public int Tail { get; init; } + public bool Reverse { get; init; } + public byte[] Before { get; init; } = []; + public byte[] Between { get; init; } = []; + public int Next { get; init; } + public int ExtraEntries { get; init; } + public bool? LittleEndianValues { get; init; } + public byte[] Scan { get; init; } = [0x12, 0x34]; + } + + // A multi-picture file: the first image, whose APP2 "MPF" segment holds the MP header laid out as asked, then the + // later images; the MP entries hold each image's size and offset from the MP header (0 for the first). + internal static byte[] File (Layout layout, params byte[][] later) + { + var le = layout.LittleEndianValues ?? layout.Mark.StartsWith ("II", StringComparison.Ordinal); + var count = later.Length + 1; + var tags = (layout.VersionFirst ? 1 : 0) + (layout.EntryTag ? 1 : 0); + var ifdEnd = 8 + 2 + (12 * tags) + 4; + var list = ifdEnd + layout.ListShift; + var mp = new byte[Math.Max (ifdEnd, list + (16 * count)) + layout.Tail]; + System.Text.Encoding.Latin1.GetBytes (layout.Mark).CopyTo (mp, 0); + void U16 (int at, int value) { if (le) BinaryPrimitives.WriteUInt16LittleEndian (mp.AsSpan (at), (ushort)value); else BinaryPrimitives.WriteUInt16BigEndian (mp.AsSpan (at), (ushort)value); } + void U32 (int at, int value) { if (le) BinaryPrimitives.WriteInt32LittleEndian (mp.AsSpan (at), value); else BinaryPrimitives.WriteInt32BigEndian (mp.AsSpan (at), value); } + U32 (4, 8); + U16 (8, tags); + var entry = 10; + if (layout.VersionFirst) { + U16 (entry, 0xB000); + U16 (entry + 2, 7); + U32 (entry + 4, 4); + "0100"u8.CopyTo (mp.AsSpan (entry + 8)); + entry += 12; + } + + if (layout.EntryTag) { + U16 (entry, 0xB002); + U16 (entry + 2, 7); + U32 (entry + 4, 16 * (count + layout.ExtraEntries)); + U32 (entry + 8, list); + entry += 12; + } + + U32 (entry, layout.Next); + + var first = Concat ([0xFF, 0xD8], layout.Before, JpegSegment (0xE2, Concat ("MPF\0"u8.ToArray (), mp)), layout.Between, + JpegSegment (0xC0, [0x08, 0x00, 0x03, 0x00, 0x02, 0x01, 0x01, 0x11, 0x00]), + JpegSegment (0xDA, [0x01, 0x01, 0x00, 0x00, 0x3F, 0x00]), layout.Scan, [0xFF, 0xD9]); + var header = 2 + layout.Before.Length + 4 + 4; + void Entry (int n, int size, int offset) + { + var at = header + list + (16 * n); + if (le) { + BinaryPrimitives.WriteInt32LittleEndian (first.AsSpan (at + 4), size); + BinaryPrimitives.WriteInt32LittleEndian (first.AsSpan (at + 8), offset); + } else { + BinaryPrimitives.WriteInt32BigEndian (first.AsSpan (at + 4), size); + BinaryPrimitives.WriteInt32BigEndian (first.AsSpan (at + 8), offset); + } + } + + if (layout.EntryTag && list + (16 * count) <= mp.Length) { + Entry (0, first.Length, 0); + var start = first.Length; + for (var n = 0; n < later.Length; n++) { + Entry (layout.Reverse ? later.Length - n : n + 1, later[n].Length, start - header); + start += later[n].Length; + } + } + + return Concat ([first, .. later]); + } + + static int Header (byte[] file) => file.AsSpan ().IndexOf ("MPF\0"u8) + 4; + + [TestMethod] + [DataRow ("big-endian, MPFVersion first", "MM\0*", true, false, new[] { 1, 123, 39, 2, 162, 41 })] + [DataRow ("little-endian", "II*\0", false, false, new[] { 1, 111, 39, 2, 150, 41 })] + [DataRow ("entries in reverse file order", "MM\0*", false, true, new[] { 2, 111, 39, 1, 150, 41 })] + public void Read_ListsTheLaterImages_WhereExiftoolShowsThem_InFileOrder (string shape, string mark, bool versionFirst, bool reverse, int[] expected) + { + var file = File (new Layout { Mark = mark, VersionFirst = versionFirst, Reverse = reverse }, Two, Three); + + var index = MpfIndex.Read (file); + + Assert.IsFalse (index.Unreadable, shape); + CollectionAssert.AreEqual (expected, index.Images.SelectMany (i => new[] { i.Entry, i.Start, i.Size }).ToArray (), shape); + } + + // An MP header that cannot be followed makes the index unreadable: a byte order other than "II" or "MM", too + // few bytes for the header and the IFD offset, or an entry list that starts in the header or ends past the + // segment. + [TestMethod] + [DataRow ("XX\0*", 0, 0)] + [DataRow ("IM*\0", 0, 0)] + [DataRow ("MI\0*", 0, 0)] + [DataRow ("MM\0*", -16, 0)] + [DataRow ("MM\0*", 0, 1)] + public void Read_OfAnIndexThatCannotBeFollowed_IsUnreadable (string mark, int listShift, int extraEntries) + { + var file = File (new Layout { Mark = mark, ListShift = listShift, ExtraEntries = extraEntries }, Two); + + Assert.IsTrue (MpfIndex.Read (file).Unreadable); + } + + [TestMethod] + public void Read_OfAnMpHeaderTooShortForItsIfdOffset_IsUnreadable () + { + var file = Concat ([0xFF, 0xD8], JpegSegment (0xE2, Concat ("MPF\0"u8.ToArray (), "MM\0*\0\0\0"u8.ToArray ())), Jpeg ()[2..]); + + Assert.IsTrue (MpfIndex.Read (file).Unreadable); + } + + // An index without an MP Entry tag lists no image; one whose IFD ends where the next bytes read B0 02 (an MP + // Entry tag) still has none, since an IFD holds only its counted entries. + [TestMethod] + [DataRow (0)] + [DataRow (unchecked((int)0xB0020007))] + public void Read_OfAnIndexWithoutAnMpEntryTag_ListsNoImage (int next) + { + var file = File (new Layout { VersionFirst = true, EntryTag = false, Next = next }, Two); + + var index = MpfIndex.Read (file); + + Assert.IsFalse (index.Unreadable); + Assert.AreEqual (0, index.Images.Count); + } + + // Fill bytes (FF FF) and a standalone marker (TEM, FF 01) before the APP2 segment are stepped over. + [TestMethod] + public void Read_FindsTheIndexAfterFillBytesAndAStandaloneMarker () + { + var file = File (new Layout { Before = [0xFF, 0xFF, 0x01] }, Two); + + var index = MpfIndex.Read (file); + + Assert.AreEqual (1, index.Images.Count); + Assert.AreEqual (Header (file) + (int)BinaryPrimitives.ReadUInt32BigEndian (file.AsSpan (Header (file) + 26 + 16 + 8)), index.Images[0].Start); + } + + [TestMethod] + public void Read_OfAFileThatEndsWithTheMpfSegment_IsUnreadable () + { + var file = File (new Layout (), Two); + var end = Header (file) - 8 + 2 + ((file[Header (file) - 6] << 8) | file[Header (file) - 5]); + + Assert.IsTrue (MpfIndex.Read (file.AsSpan (0, end)).Unreadable); + } + + // The smallest JPEG, SOI then EOI, is an image of 4 bytes. + [TestMethod] + public void Read_ALaterImageOfFourBytes_IsAnImage () + { + var index = MpfIndex.Read (File (new Layout (), [0xFF, 0xD8, 0xFF, 0xD9])); + + Assert.IsFalse (index.Unreadable); + Assert.AreEqual (4, index.Images.Single ().Size); + } + + // Each entry's new offset and size must fit the 4-byte fields: a negative or larger value is refused. + [TestMethod] + [DataRow (-1L, 0L)] + [DataRow (1L + uint.MaxValue, 0L)] + [DataRow (0L, -1L)] + [DataRow (0L, 1L + uint.MaxValue)] + [DataRow (0L, (long)uint.MaxValue)] + public void RewriteEntries_RefusesAValueTheFieldsCannotHold (long offset, long size) + { + var file = File (new Layout (), Two); + var header = Header (file); + var limit = header - 8 + 2 + ((file[header - 6] << 8) | file[header - 5]); + + var rewritten = MpfIndex.TryRewriteEntries (file, header, limit, (n, _, _) => n == 1 ? (offset, size) : (0, 1)); + + Assert.AreEqual (size == uint.MaxValue, rewritten); + } + + // Only the listed entries are rewritten: bytes after the list, inside the segment, are kept. + [TestMethod] + public void RewriteEntries_WritesOnlyTheListedEntries () + { + var file = File (new Layout { Tail = 16 }, Two); + var header = Header (file); + var limit = header - 8 + 2 + ((file[header - 6] << 8) | file[header - 5]); + var before = file[(limit - 16)..limit]; + + Assert.IsTrue (MpfIndex.TryRewriteEntries (file, header, limit, (_, _, _) => (7, 9))); + + CollectionAssert.AreEqual (before, file[(limit - 16)..limit]); + Assert.AreEqual (9u, BinaryPrimitives.ReadUInt32BigEndian (file.AsSpan (limit - 16 - 16 + 4))); + } + // An MP index IFD of 0 entries whose 2-byte count is the last bytes of the segment. A table is read when the + // count fits; the next-IFD offset may be absent. Clear saves. A check that required the next offset would refuse. + [TestMethod] + [DataRow (false)] + [DataRow (true)] + public void Read_EmptyIndexThatEndsItsSegment_IsReadable_AndClearSaves (bool littleEndian) + { + var tiff = new byte[10]; + if (littleEndian) { + "II*\0"u8.CopyTo (tiff); + tiff[4] = 8; + } else { + "MM\0*"u8.CopyTo (tiff); + tiff[7] = 8; + } + + var file = Jpeg (JpegSegment (0xE2, Concat ("MPF\0"u8.ToArray (), tiff)), JpegSegment (0xFE, "c"u8.ToArray ())); + var index = MpfIndex.Read (file); + var order = littleEndian ? "little-endian" : "big-endian"; + Assert.IsFalse (index.Unreadable, order); + Assert.AreEqual (0, index.Images.Count, order); + + var image = Open (file, "a.jpg"); + Assert.AreEqual ("c", image.Tag!.Comment, order); + image.Tag.Clear (); + var save = image.SaveToFile ("/a.jpg", new MockFileSystem ()); + Assert.IsTrue (save.IsSuccess, save.Error); + Assert.IsNull (Open (image.Render ().ToArray (), "a.jpg").Tag!.Comment, order); + } + + // "IM" is no byte order, even with little-endian values after it. + [TestMethod] + public void Read_OfAnIndexMarkedIm_IsUnreadable_ThoughItsValuesReadAsLittleEndian () => + Assert.IsTrue (MpfIndex.Read (File (new Layout { Mark = "IM*\0", LittleEndianValues = true }, Two)).Unreadable); + + // The first image ends at its EOI: a "JPEG" inside its entropy-coded data, after the SOS, overlaps it and is not + // an image the index can list (Clear would cut the first image there). + [TestMethod] + public void Read_OfAnImageInsideTheFirstImagesScanData_IsUnreadable () + { + var file = File (new Layout { Scan = [0x12, 0xFF, 0xD8, 0xFF, 0xD9, 0x34] }, Two); + var header = Header (file); + var inner = file.AsSpan ().IndexOf (new byte[] { 0x12, 0xFF, 0xD8 }) + 1; + BinaryPrimitives.WriteInt32BigEndian (file.AsSpan (header + 26 + 16 + 4), 4); + BinaryPrimitives.WriteInt32BigEndian (file.AsSpan (header + 26 + 16 + 8), inner - header); + + Assert.IsTrue (MpfIndex.Read (file).Unreadable); + } + + // Before the APP2 segment: standalone markers RST0 and SOI are stepped over, an empty segment (length 2) is + // passed, and an APP1 whose payload starts "MPF" is not the index. + [TestMethod] + [DataRow (new byte[] { 0xFF, 0xD0 })] + [DataRow (new byte[] { 0xFF, 0xD8 })] + [DataRow (new byte[] { 0xFF, 0xE1, 0x00, 0x02 })] + [DataRow (new byte[] { 0xFF, 0xE1, 0x00, 0x0E, 0x4D, 0x50, 0x46, 0x00, 0x4D, 0x4D, 0x00, 0x2A, 0x00, 0x00, 0x00, 0x08 })] + public void Read_FindsTheIndexAfter (byte[] before) + { + var file = File (new Layout { Before = before }, Two); + + var index = MpfIndex.Read (file); + + Assert.IsFalse (index.Unreadable); + Assert.AreEqual (file.Length - Two.Length, index.Images.Single ().Start); + } + + // A segment length below 2 ends the marker walk (no index, nothing thrown), and so does an APP2 that runs past + // the data. + [TestMethod] + public void Read_StopsAtASegmentLengthItCannotFollow () + { + var file = File (new Layout { Before = [0xFF, 0xE1, 0x00, 0x00] }, Two); + var index = MpfIndex.Read (file); + Assert.IsFalse (index.Unreadable); + Assert.AreEqual (0, index.Images.Count); + + byte[] cut = [0xFF, 0xD8, 0xFF, 0xE2, 0x7F, 0xFF, 0x4D, 0x50, 0x46, 0x00]; + Assert.AreEqual (0, MpfIndex.Read (cut).Images.Count); + } + + // An APP2 "MPF" segment whose length runs 1 to 4 bytes past the data is cut short: it is not an index, and reading + // it reads nothing past the data. + [TestMethod] + [DataRow (1)] + [DataRow (2)] + [DataRow (4)] + public void Read_OfAnMpfSegmentThatRunsPastTheData_FindsNoIndex (int past) + { + byte[] data = [0xFF, 0xD8, 0xFF, 0xE2, 0x00, 0x00, 0x4D, 0x50, 0x46, 0x00, 0x4D, 0x4D, 0x00, 0x2A, 0x00, 0x00, 0x00, 0x08]; + var length = data.Length - 4 + past; + data[4] = (byte)(length >> 8); + data[5] = (byte)length; + + var index = MpfIndex.Read (data); + + Assert.IsFalse (index.Unreadable); + Assert.AreEqual (0, index.Images.Count); + } + + // The 4-byte fields take 0 to 2^32 - 1. + [TestMethod] + [DataRow ((long)uint.MaxValue, 0L)] + [DataRow (0L, 0L)] + public void RewriteEntries_WritesTheFieldsLimits (long offset, long size) + { + var file = File (new Layout (), Two); + var header = Header (file); + var limit = header - 8 + 2 + ((file[header - 6] << 8) | file[header - 5]); + + Assert.IsTrue (MpfIndex.TryRewriteEntries (file, header, limit, (n, _, _) => n == 1 ? (offset, size) : (0, 1))); + Assert.AreEqual ((uint)offset, BinaryPrimitives.ReadUInt32BigEndian (file.AsSpan (header + 26 + 16 + 8))); + } + + // An entry list that starts in the 8-byte MP header is not rewritten; one that starts right after it is. + [TestMethod] + [DataRow (4, false)] + [DataRow (8, true)] + public void RewriteEntries_OfAListStartingAt (int listAt, bool rewritten) + { + var file = File (new Layout (), Two); + var header = Header (file); + var limit = header - 8 + 2 + ((file[header - 6] << 8) | file[header - 5]); + BinaryPrimitives.WriteInt32BigEndian (file.AsSpan (header + 18), listAt); + var before = file.ToArray (); + + Assert.AreEqual (rewritten, MpfIndex.TryRewriteEntries (file, header, limit, (_, _, _) => (7, 9))); + if (!rewritten) + CollectionAssert.AreEqual (before, file); + } + // The index is the first APP2 "MPF" segment: a second one, whose own index lists only the first image, is not it. + [TestMethod] + public void Read_UsesTheFirstMpfSegment () + { + var mp = new byte[8 + 2 + 12 + 4 + 16]; + "MM\0*"u8.CopyTo (mp); + BinaryPrimitives.WriteInt32BigEndian (mp.AsSpan (4), 8); + BinaryPrimitives.WriteUInt16BigEndian (mp.AsSpan (8), 1); + BinaryPrimitives.WriteUInt16BigEndian (mp.AsSpan (10), 0xB002); + BinaryPrimitives.WriteUInt16BigEndian (mp.AsSpan (12), 7); + BinaryPrimitives.WriteInt32BigEndian (mp.AsSpan (14), 16); + BinaryPrimitives.WriteInt32BigEndian (mp.AsSpan (18), 26); + var file = File (new Layout { Between = JpegSegment (0xE2, Concat ("MPF\0"u8.ToArray (), mp)) }, Two); + + Assert.AreEqual (1, MpfIndex.Read (file).Images.Count); + } +} diff --git a/tests/TagLibSharp2.Tests/Image/MultiPictureTests.cs b/tests/TagLibSharp2.Tests/Image/MultiPictureTests.cs new file mode 100644 index 00000000..a3660ae5 --- /dev/null +++ b/tests/TagLibSharp2.Tests/Image/MultiPictureTests.cs @@ -0,0 +1,166 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Text; +using System.Xml.Linq; +using TagLibSharp2.Core; +using TagLibSharp2.Image; +using TagLibSharp2.Image.Exif; +using TagLibSharp2.Image.Tiff; +using TagLibSharp2.Tests.Core; +using static TagLibSharp2.Tests.Image.ImageTestBuilder; + +namespace TagLibSharp2.Tests.Image; + +/// Multi-picture JPEG files: the MPF index is read only inside its segment, and every image it lists stays where it points after a save. +[TestClass] +[TestCategory ("Unit")] +public class MultiPictureTests +{ + public static IEnumerable MpfEdits () + { + yield return ["comment edit after the MPF segment", new Action (t => t.Comment = "a much longer comment than before")]; + yield return ["comment removed", new Action (t => t.Comment = null)]; + yield return ["clear drops Exif before and APP13 after", new Action (t => t.Clear ())]; + } + + static byte[] SecondImage () => Jpeg ( + JpegExif (ExifTiff ([(0x010F, "Canon"), (0x013B, "Jane Private")], [(0x8827, "GPS")])), + JpegXmp (XmpPacket (Seq ("dc:creator", "Jane Private"))), + JpegApp (0xE2, "urn:iso:std:iso:ts:21496:-1\0", "\0\0\0\0gain map"), + JpegApp (0xE2, "ICC_PROFILE\0", "\x01\x01profile"), + JpegSegment (0xFE, "second image comment"u8.ToArray ())); + + [TestMethod] + [DynamicData (nameof (MpfEdits))] + public void Jpeg_MultiPictureIndex_StillPointsAtEachImage (string edit, Action apply) + { + var input = MpfJpeg ( + JpegExif (ExifTiff ([(0x010F, "Canon")], [])), + Concat (JpegApp (0xED, "Photoshop 3.0\0", "8BIM"), JpegSegment (0xFE, "c"u8.ToArray ())), + SecondImage (), + out var second); + Assert.IsTrue (input.AsSpan (MpfSecondImage (input)).SequenceEqual (second), "fixture"); + var file = Open (input, "a.jpg"); + apply (file.Tag!); + + var output = file.Render ().ToArray (); + + Assert.AreNotEqual (input.Length, output.Length, edit); + var entries = MpfEntries (output); + var at = entries[1].Start; + Assert.AreEqual (at, entries[0].Size, $"{edit}: image 1's size is its new length"); + Assert.AreEqual (output.Length - at, entries[1].Size, $"{edit}: image 2's size"); + var image2 = output[at..]; + Assert.AreEqual (0xFF, image2[0]); + Assert.AreEqual (0xD8, image2[1]); + Assert.IsTrue (Open (image2, "b.jpg").ImageProperties is not null, $"{edit}: image 2 still parses"); + if (edit.StartsWith ("clear", StringComparison.Ordinal)) { + // Rule 7 reaches every image of the file; image 2 keeps what its decoder needs. + foreach (var gone in new[] { "Exif\0\0"u8.ToArray (), "http://ns.adobe.com/xap/1.0/"u8.ToArray (), "Jane Private"u8.ToArray (), "second image comment"u8.ToArray () }) + Assert.IsTrue (image2.AsSpan ().IndexOf (gone) < 0, $"image 2 still holds {Encoding.ASCII.GetString (gone)}"); + Assert.IsTrue (image2.AsSpan ().IndexOf ("urn:iso:std:iso:ts:21496:-1"u8) > 0 && image2.AsSpan ().IndexOf ("ICC_PROFILE"u8) > 0); + Assert.IsTrue (image2.AsSpan ().EndsWith (second.AsSpan (second.Length - 12)), "the scan of image 2 is copied as it is"); + } else { + CollectionAssert.AreEqual (second, image2, $"{edit}: an edit leaves image 2 as it is"); + } + } + + [TestMethod] + public void Jpeg_ClearOfAMultiPictureFile_WhoseIndexCannotBeFollowed_IsRefused () + { + var input = MpfJpeg ([], JpegSegment (0xFE, "c"u8.ToArray ()), SecondImage (), out _); + var entries = input.AsSpan ().IndexOf ("MPF\0"u8) + 4 + 26; + System.Buffers.Binary.BinaryPrimitives.WriteInt32BigEndian (input.AsSpan (entries + 16 + 4), input.Length); + var file = Open (input, "a.jpg"); + file.Tag!.Clear (); + var result = file.SaveToFile ("/a.jpg", new MockFileSystem ()); + Assert.IsFalse (result.IsSuccess); + StringAssert.Contains (result.Error, "other images cannot be cleared"); + } + + [TestMethod] + public void Jpeg_UnreadableMpfIndex_RefusesAnEditThatMovesTheSecondImage () + { + var input = Concat ([0xFF, 0xD8], JpegApp (0xE2, "MPF\0", "MM\0*\0\0\0\x08"), JpegSegment (0xFE, "c"u8.ToArray ()), + JpegSegment (0xC0, [0x08, 0x00, 0x03, 0x00, 0x02, 0x01, 0x01, 0x11, 0x00]), JpegSegment (0xDA, [0x01, 0x01, 0x00, 0x00, 0x3F, 0x00]), [0xFF, 0xD9]); + var file = Open (input, "a.jpg"); + file.Tag!.Comment = "longer comment"; + var result = file.SaveToFile ("/a.jpg", new MockFileSystem ()); + Assert.IsFalse (result.IsSuccess); + StringAssert.Contains (result.Error, "MPF"); + } + + // CIPA DC-007 §5.2: the MP index lies inside its APP2 segment. An index that points out of it is not followed. + [TestMethod] + public void MpIndexOutsideItsSegment_IsUnreadable_ForClearAndEdits () + { + var input = MpfJpegMany ([], JpegSegment (0xFE, "comment that the edit makes longer"u8.ToArray ()), Jpeg ()); + var header = input.AsSpan ().IndexOf ("MPF\0"u8) + 4; + var segmentEnd = header - 8 + 2 + ((input[header - 6] << 8) | input[header - 5]); + // Point the entry list at the COM segment that follows the APP2 segment. + System.Buffers.Binary.BinaryPrimitives.WriteInt32BigEndian (input.AsSpan (header + 18), segmentEnd + 4 - header); + var original = (byte[])input.Clone (); + + var clear = Open (input, "a.jpg"); + clear.Tag!.Clear (); + var cleared = clear.SaveToFile ("/a.jpg", new MockFileSystem ()); + Assert.IsFalse (cleared.IsSuccess); + StringAssert.Contains (cleared.Error, "MPF index cannot be read"); + + var edit = Open (input, "a.jpg"); + edit.Tag!.Comment = "a longer comment than the old one"; + var edited = edit.SaveToFile ("/a.jpg", new MockFileSystem ()); + Assert.IsFalse (edited.IsSuccess); + StringAssert.Contains (edited.Error, "MPF index cannot be read"); + CollectionAssert.AreEqual (original, edit.Render ().ToArray (), "no byte outside the segment is written"); + } + + public static IEnumerable UnfollowableIndexes () + { + var two = Jpeg (JpegSegment (0xFE, "two"u8.ToArray ())); + var three = Jpeg (JpegSegment (0xFE, "three"u8.ToArray ())); + var dup = MpfJpegMany ([], [], two, three); + var (_, offset2) = GetMpEntry (dup, 1); + SetMpEntry (dup, 2, three.Length, offset2); + yield return ["two entries at the same image", dup]; + var overlap = MpfJpegMany ([], [], two, three); + var (size2, offset) = GetMpEntry (overlap, 1); + SetMpEntry (overlap, 1, size2 + 10, offset); + yield return ["overlapping images", overlap]; + // An SOI inside a comment before the first image's scan. + var into = MpfJpegMany ([], JpegSegment (0xFE, [0xFF, 0xD8, 0xFF, 0xFE, 0x00, 0x04, 0x00, 0x00]), two); + var header = into.AsSpan ().IndexOf ("MPF\0"u8) + 4; + var soi = into.AsSpan (header).IndexOf (new byte[] { 0xFF, 0xD8, 0xFF, 0xFE }) + header; + SetMpEntry (into, 1, 8, soi - header); + yield return ["an image inside the first image's header", into]; + } + + [TestMethod] + [DynamicData (nameof (UnfollowableIndexes))] + public void Clear_OfAnIndexThatCannotBeFollowed_IsRefusedWithTheMpfReason (string shape, byte[] input) + { + var file = Open (input, "a.jpg"); + file.Tag!.Clear (); + var result = file.SaveToFile ("/a.jpg", new MockFileSystem ()); + Assert.IsFalse (result.IsSuccess, shape); + StringAssert.Contains (result.Error, "other images cannot be cleared", shape); + } + + [TestMethod] + public void SecondMpfSegment_IsNotTheIndex () + { + var second = Jpeg (JpegSegment (0xFE, "second"u8.ToArray ())); + var input = MpfJpegMany ([], Concat (JpegApp (0xE2, "MPF\0", "II*\0\u0008\0\0\0\0\0"), JpegSegment (0xFE, "c"u8.ToArray ())), second); + foreach (var apply in new Action[] { t => t.Comment = "a longer comment", t => t.Clear () }) { + var file = Open (input, "a.jpg"); + apply (file.Tag!); + var output = file.Render ().ToArray (); + Assert.AreNotEqual (input.Length, output.Length); + var at = MpfSecondImage (output); + Assert.IsTrue (at < output.Length && output[at] == 0xFF && output[at + 1] == 0xD8, "the first MPF segment's index is the one rewritten"); + Assert.AreEqual (at, MpfEntries (output)[0].Size); + Assert.AreEqual (output.Length - at, MpfEntries (output)[1].Size); + } + } +} diff --git a/tests/TagLibSharp2.Tests/Image/PngTextPinTests.cs b/tests/TagLibSharp2.Tests/Image/PngTextPinTests.cs new file mode 100644 index 00000000..2d36ff0a --- /dev/null +++ b/tests/TagLibSharp2.Tests/Image/PngTextPinTests.cs @@ -0,0 +1,178 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Runtime.InteropServices; +using System.Text; +using TagLibSharp2.Core; +using TagLibSharp2.Image; +using TagLibSharp2.Image.Exif; +using TagLibSharp2.Image.Gif; +using TagLibSharp2.Image.Png; +using TagLibSharp2.Image.Svg; +using TagLibSharp2.Image.Tiff; +using TagLibSharp2.Tests.Core; +using TagLibSharp2.Tests.Kit; +using static TagLibSharp2.Tests.Image.ImageTestBuilder; + +namespace TagLibSharp2.Tests.Image; + +public partial class PngTextTests +{ + [TestMethod] + public void Png_EmptyArtistText_DoesNotEraseTheEarlierArtist () + { + var png = Png (Text ("Artist", "Ada"), Text ("Artist", "")); + var opened = StillImageFile.Read (png); + + Assert.IsTrue (opened.IsSuccess, opened.Error); + Assert.AreEqual ("Ada", opened.File!.Tag!.Artist); + } + + [TestMethod] + public void Png_SignatureOnly_RefusesTheSpliceWithoutThrowing () + { + var tag = new ImageTag (MediaFormat.Png, ImageStores.Title); + tag.Title = "t"; + + var plan = TagLibSharp2.Image.Png.PngRewriter.Plan (PngSignature, tag, out var error); + + Assert.IsNull (plan); + Assert.AreEqual (TagLibSharp2.Image.Png.PngRewriter.SpliceError, error); + } + + [TestMethod] + public void PngClear_KeepsGama_AndDropsALookalikeAncillaryChunk () + { + var cleared = Open (Png (PngChunk ("gAMA", [0, 0, 0, 1]), PngChunk ("aaaS", [1]), Text ("Comment", "hi")), "a.png"); + cleared.Tag!.Clear (); + var afterClear = cleared.Render ().ToArray (); + Assert.IsTrue (afterClear.AsSpan ().IndexOf ("gAMA"u8) >= 0); + Assert.IsTrue (afterClear.AsSpan ().IndexOf ("aaaS"u8) < 0); + } + + [TestMethod] + public void Png_DropsAnEmptyIdotWhenAChunkBetweenItAndIdatChanges () + { + var file = Open (Png (PngChunk ("iDOT", []), Text ("Comment", "old")), "b.png"); + file.Tag!.Comment = "Z"; + var output = file.Render ().ToArray (); + + Assert.IsTrue (output.AsSpan ().IndexOf ("iDOT"u8) < 0); + Assert.IsTrue (output.AsSpan ().IndexOf ("IDAT"u8) >= 0); + Assert.IsTrue (output.AsSpan ().IndexOf ("old"u8) < 0); + Assert.IsTrue (output.AsSpan ().IndexOf ("Comment"u8) >= 0); + } + + [TestMethod] + public void PngWithoutIdat_KeepsIdotWhenTextIsInserted () + { + var file = Open (PngEndingAtIend (PngChunk ("iDOT", [0, 0, 0, 1])), "a.png"); + file.Tag!.Title = "t"; + var output = file.Render ().ToArray (); + + Assert.IsTrue (output.AsSpan ().IndexOf ("iDOT"u8) >= 0); + Assert.IsTrue (output.AsSpan ().IndexOf ("Title"u8) >= 0); + } + + [TestMethod] + public void PngText_IsInsertedBeforeTheFirstIdat () + { + var file = Open (Png (PngChunk ("IDAT", [1]), PngChunk ("iDOT", [0, 0, 0, 1])), "a.png"); + file.Tag!.Title = "t"; + var output = file.Render ().ToArray (); + var title = output.AsSpan ().IndexOf ("Title"u8); + var idat = output.AsSpan ().IndexOf ("IDAT"u8); + + Assert.IsTrue (title >= 0); + Assert.IsTrue (idat > title); + } + + [TestMethod] + public void Png_BadCrcChunk_IsKeptWhenAnotherFieldChanges () + { + var gama = PngChunk ("gAMA", [0, 0, 0, 1]); + gama[^1] ^= 0xFF; + var file = Open (Png (gama), "a.png"); + file.Tag!.Title = "t"; + var output = file.Render ().ToArray (); + + Assert.IsTrue (output.AsSpan ().IndexOf ("Title"u8) >= 0); + Assert.IsTrue (output.AsSpan ().IndexOf ("gAMA"u8) >= 0); + } + + [TestMethod] + public void Png_ExifThatIsNotTiff_NamesTheExifChunk () + { + var data = Png (PngChunk ("eXIf", [1, 2, 3, 4, 0x01, 0x3B, 0, 2, 9])); + var tag = new ImageTag (MediaFormat.Png, ImageStores.Artist); + tag.Artist = "N"; + + Assert.IsNull (PngRewriter.Plan (data, tag, out var error)); + Assert.AreEqual ("The eXIf block is not a TIFF structure, so its copy of Artist cannot be updated.", error); + } + + [TestMethod] + public void Png_CompressedXmpPastTheSharedBudget_NamesOneMebibyte () + { + var data = Png (Xmp (new string (' ', PngText.MaxInflatedText + 1), compressed: true)); + var tag = new ImageTag (MediaFormat.Png, ImageStores.Title); + tag.Title = "t"; + + Assert.IsNull (PngRewriter.Plan (data, tag, out var error)); + Assert.AreEqual ( + "The PNG XML:com.adobe.xmp chunk does not fit in the 1 MiB that all compressed text in the file shares, so its copy of a changed field cannot be updated.", + error); + } + + [TestMethod] + public void PngClear_DropsAChunkWhoseThirdByteMatchesAKeptName () + { + // "xxNS" shares tRNS's last two letters. A clear keeps tRNS and drops this ancillary chunk. + var png = Png (PngChunk ("gAMA", [0, 0, 0, 1]), PngChunk ("xxNS", [1])); + var file = Open (png, "a.png"); + file.Tag!.Clear (); + var output = file.Render ().ToArray (); + + Assert.IsTrue (output.AsSpan ().IndexOf ("gAMA"u8) > 0); + Assert.AreEqual (-1, output.AsSpan ().IndexOf ("xxNS"u8)); + } + + [TestMethod] + public void Png_TextWithoutAKeyword_StaysWhenAnotherFieldChanges () + { + var marker = new byte[] { 0xAB, 0xCD, 0xEF, 0x11 }; + var file = Open (Png (PngChunk ("tEXt", marker), Text ("Comment", "old")), "a.png"); + file.Tag!.Comment = "Z"; + var output = file.Render ().ToArray (); + + Assert.IsTrue (output.AsSpan ().IndexOf (marker) >= 0); + Assert.IsTrue (output.AsSpan ().IndexOf ("old"u8) < 0); + } + + [TestMethod] + public void Png_TextWithABadCrc_IsNotAComment () + { + var chunk = Text ("Comment", "Secret"); + chunk[^1] ^= 0xFF; + var opened = StillImageFile.Read (Png (chunk)); + + Assert.IsTrue (opened.IsSuccess, opened.Error); + Assert.IsNull (opened.File!.Tag!.Comment); + } + + [TestMethod] + public void Png_RawXmpThatNamesTheEditedFieldAndIsNotXml_IsRefused () + { + var packet = XmpPacket (Alt ("dc:title", "Old")).Replace ("", "", StringComparison.Ordinal); + var file = Open (Png (RawProfile ("xmp", Encoding.UTF8.GetBytes (packet))), "a.png"); + file.Tag!.Title = "New"; + + var saved = file.SaveToFile ("/a.png", new MockFileSystem ()); + + Assert.IsFalse (saved.IsSuccess, saved.Error); + StringAssert.Contains (saved.Error, "not well-formed"); + } + + static byte[] PngEndingAtIend (params byte[][] chunks) => + Concat (PngSignature, PngChunk ("IHDR", [0, 0, 0, 2, 0, 0, 0, 3, 8, 0, 0, 0, 0]), Concat (chunks), PngChunk ("IEND", [])); +} diff --git a/tests/TagLibSharp2.Tests/Image/PngTextTests.cs b/tests/TagLibSharp2.Tests/Image/PngTextTests.cs new file mode 100644 index 00000000..473d6038 --- /dev/null +++ b/tests/TagLibSharp2.Tests/Image/PngTextTests.cs @@ -0,0 +1,317 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Buffers.Binary; +using System.IO.Compression; +using System.Text; +using System.Xml.Linq; +using TagLibSharp2.Core; +using TagLibSharp2.Image; +using TagLibSharp2.Image.Exif; +using TagLibSharp2.Image.Tiff; +using TagLibSharp2.Image.Xmp; +using TagLibSharp2.Tests.Core; +using TagLibSharp2.Tests.Kit; +using static TagLibSharp2.Tests.Image.ImageTestBuilder; + +namespace TagLibSharp2.Tests.Image; + +/// PNG text chunks: reading and writing the mapped keywords, compression, the shared inflation budget, and keyword copies. +[TestClass] +[TestCategory ("Unit")] +public partial class PngTextTests +{ + [TestMethod] + public void Png_InflationBudget_SpentLeavesLaterChunksUncompressed () + { + // One Title chunk inflates to exactly the 1 MiB budget; every later compressed text chunk must be skipped + // without decompressing anything. + var bomb = CompressedText ("Title", Enumerable.Repeat ((byte)'a', Mib).ToArray ()); + var small = CompressedText ("Title", "x"u8.ToArray ()); + static byte[] With (byte[] bomb, byte[] small, int n) => Png ([bomb, .. Enumerable.Repeat (small, n)]); + var none = With (bomb, small, 0); + var many = With (bomb, small, 2000); + _ = MediaFile.ReadFromData (none, "a.png"); + _ = MediaFile.ReadFromData (many, "a.png"); + + var baseline = Bounds.AllocatedBytes (() => MediaFile.ReadFromData (none, "a.png")); + var withMore = Bounds.AllocatedBytes (() => MediaFile.ReadFromData (many, "a.png")); + + Assert.IsTrue (withMore - baseline < 2000 * 256, $"2000 chunks after the budget cost {withMore - baseline} bytes"); + Assert.AreEqual (Mib, MediaFile.ReadFromData (many, "a.png").Tag!.Title!.Length); + } + + [TestMethod] + public void Png_RoundTripsMappedText_AndLeavesPixelsAndUntouchedChunks () + { + var idat = new byte[] { 0x01, 0x02, 0x03, 0x04 }; + var software = Text ("Software", "camera"); + var data = MinimalPng ( + Text ("Title", "Door"), + Text ("Author", "Ada"), + software, + PngChunk ("IDAT", idat)); + var file = Open (data, "photo.png"); + Assert.IsNotNull (file.Tag); + Assert.AreEqual ("Door", file.Tag.Title); + Assert.AreEqual ("Ada", file.Tag.Artist); + + file.Tag.Album = "Not stored"; + file.Tag.Genre = "Rock"; + file.Tag.Track = 4; + Assert.IsNull (file.Tag.Album); + Assert.IsNull (file.Tag.Genre); + Assert.IsNull (file.Tag.Track); + CollectionAssert.AreEqual (data, file.Render ().ToArray ()); + + file.Tag.Description = "A door"; + file.Tag.Copyright = "Ada"; + file.Tag.Year = "2020-01-02"; + file.Tag.Comment = "hi"; + file.Tag.Title = "Tür"; + var rendered = file.Render ().ToArray (); + AssertPng (rendered); + CollectionAssert.AreEqual (idat, PngPayload (rendered, "IDAT")); + CollectionAssert.AreEqual (software, PngTextChunk (rendered, "tEXt", "Software")); + + var again = Open (rendered, "photo.png"); + Assert.AreEqual ("Tür", again.Tag!.Title); + Assert.AreEqual ("Ada", again.Tag.Artist); + Assert.AreEqual ("A door", again.Tag.Description); + Assert.AreEqual ("Ada", again.Tag.Copyright); + Assert.AreEqual ("2020-01-02", again.Tag.Year); + Assert.AreEqual ("hi", again.Tag.Comment); + Assert.IsNull (again.Tag.Album); + Assert.IsFalse (HasPngChunk (rendered, "iTXt")); + + again.Tag.Title = null; + var cleared = again.Render ().ToArray (); + Assert.IsNull (Open (cleared, "photo.png").Tag!.Title); + Assert.AreEqual ("Ada", Open (cleared, "photo.png").Tag!.Artist); + CollectionAssert.AreEqual (idat, PngPayload (cleared, "IDAT")); + } + + [TestMethod] + public void Png_UnicodeAndCompressedText_RoundTrip () + { + var title = Encoding.Latin1.GetBytes ("Door"); + var zlib = Zlib (title, CompressionLevel.SmallestSize); + var compressed = new byte[1 + 1 + "Title".Length + zlib.Length]; + Encoding.ASCII.GetBytes ("Title").CopyTo (compressed, 0); + compressed["Title".Length + 1] = 0; + zlib.CopyTo (compressed, "Title".Length + 2); + var ztxt = PngChunk ("zTXt", compressed); + var data = MinimalPng (ztxt, PngChunk ("IDAT", [0x09])); + var file = Open (data, "photo.png"); + Assert.AreEqual ("Door", file.Tag!.Title); + + file.Tag.Comment = "note"; + var kept = file.Render ().ToArray (); + CollectionAssert.AreEqual (ztxt, PngTextChunk (kept, "zTXt", "Title")); + Assert.AreEqual ("Door", Open (kept, "photo.png").Tag!.Title); + Assert.AreEqual ("note", Open (kept, "photo.png").Tag!.Comment); + + file.Tag.Title = "門"; + var replaced = file.Render ().ToArray (); + Assert.IsFalse (HasPngChunk (replaced, "zTXt")); + CollectionAssert.AreEqual (new byte[] { 0xE9, 0x96, 0x80 }, TextBytes (replaced, "iTXt", "Title")); + Assert.AreEqual ("門", Open (replaced, "photo.png").Tag!.Title); + Assert.AreEqual ("note", Open (replaced, "photo.png").Tag!.Comment); + CollectionAssert.AreEqual (new byte[] { 0x09 }, PngPayload (replaced, "IDAT")); + } + + [TestMethod] + public void Png_CompressedTextOverTheCap_IsLeftUnread () + { + var huge = new byte[1024 * 1024 + 1]; + var ztxt = MinimalPng (CompressedTextChunk ("zTXt", "Title", huge, utf8: false), PngChunk ("IDAT", [0x11])); + var itxt = MinimalPng (CompressedTextChunk ("iTXt", "Comment", huge, utf8: true), PngChunk ("IDAT", [0x11])); + var zTitle = Open (ztxt, "bomb.png").Tag!.Title; + var iComment = Open (itxt, "bomb.png").Tag!.Comment; + Assert.IsTrue (zTitle is null, $"zTXt inflated to {zTitle?.Length}"); + Assert.IsTrue (iComment is null, $"iTXt inflated to {iComment?.Length}"); + Assert.AreEqual (1, Open (ztxt, "bomb.png").ImageProperties!.Value.Width); + CollectionAssert.AreEqual (new byte[] { 0x11 }, PngPayload (ztxt, "IDAT")); + } + + [TestMethod] + public void Png_SmallCompressedInternationalText_IsRead () + { + var data = MinimalPng (CompressedTextChunk ("iTXt", "Title", System.Text.Encoding.UTF8.GetBytes ("門"), utf8: true)); + Assert.AreEqual ("門", Open (data, "photo.png").Tag!.Title); + } + + [TestMethod] + public void Png_NewText_IsWrittenBeforeThePixelData () + { + var data = MinimalPng (PngChunk ("IDAT", [0x0A, 0x0B])); + var file = Open (data, "photo.png"); + file.Tag!.Title = "Door"; + var rendered = file.Render ().ToArray (); + + var text = ChunkAt (rendered, "tEXt"); + var pixels = ChunkAt (rendered, "IDAT"); + Assert.IsTrue (text >= 0 && pixels > text, $"text {text} idat {pixels}"); + Assert.AreEqual ("Door", Open (rendered, "photo.png").Tag!.Title); + CollectionAssert.AreEqual (new byte[] { 0x0A, 0x0B }, PngPayload (rendered, "IDAT")); + } + + [TestMethod] + public void Png_TextWithABadCrc_IsNotLoaded () + { + var chunk = Text ("Title", "Door"); + chunk[^1] ^= 0xFF; + var data = MinimalPng (chunk, PngChunk ("IDAT", [0x01])); + + var opened = Open (data, "photo.png"); + + Assert.IsNull (opened.Tag!.Title); + Assert.AreEqual (1, opened.ImageProperties!.Value.Width); + } + + [TestMethod] + public void Png_InflationBudget_IsSharedAcrossChunks () + { + var author = new byte[700_000]; + var description = new byte[700_000]; + var comment = new byte[1000]; + Array.Fill (author, (byte)'A'); + Array.Fill (description, (byte)'D'); + Array.Fill (comment, (byte)'n'); + var data = MinimalPng ( + Text ("Title", "one"), + CompressedTextChunk ("zTXt", "Author", author, utf8: false), + CompressedTextChunk ("zTXt", "Description", description, utf8: false), + CompressedTextChunk ("zTXt", "Comment", comment, utf8: false), + PngChunk ("IDAT", [0x01])); + + var tag = Open (data, "photo.png").Tag!; + + Assert.AreEqual ("one", tag.Title); + Assert.AreEqual (700_000, tag.Artist?.Length); + Assert.IsNull (tag.Description); + Assert.AreEqual (new string ('n', 1000), tag.Comment); + } + + static void AssertPng (byte[] file) + { + var i = 8; + while (i + 12 <= file.Length) { + var length = BinaryPrimitives.ReadInt32BigEndian (file.AsSpan (i)); + var crcInput = new byte[4 + length]; + Array.Copy (file, i + 4, crcInput, 0, crcInput.Length); + var actual = BinaryPrimitives.ReadInt32BigEndian (file.AsSpan (i + 8 + length)); + Assert.AreEqual (new BinaryData (crcInput).ComputeCrc32 (), (uint)actual); + i += 12 + length; + if (Encoding.ASCII.GetString (file, i - 12 - length + 4, 4) == "IEND") + return; + } + + Assert.Fail ("PNG has no IEND"); + } + + static byte[] TextBytes (byte[] file, string type, string keyword) + { + var chunk = PngTextChunk (file, type, keyword); + var key = Encoding.ASCII.GetBytes (keyword); + var start = 8 + key.Length + 1; + if (type == "iTXt") { + start += 2; + while (start < chunk.Length - 4 && chunk[start] != 0) + start++; + start++; + while (start < chunk.Length - 4 && chunk[start] != 0) + start++; + start++; + } + + var count = chunk.Length - 4 - start; + var text = new byte[count]; + Array.Copy (chunk, start, text, 0, count); + return text; + } + + static int ChunkAt (byte[] file, string type) + { + var i = 8; + while (i + 12 <= file.Length) { + if (Encoding.ASCII.GetString (file, i + 4, 4) == type) + return i; + i += 12 + BinaryPrimitives.ReadInt32BigEndian (file.AsSpan (i)); + } + + return -1; + } + + static byte[] CompressedTextChunk (string type, string keyword, byte[] raw, bool utf8) + { + var key = System.Text.Encoding.ASCII.GetBytes (keyword); + var zlib = Zlib (raw, CompressionLevel.SmallestSize); + if (type == "zTXt") { + var payload = new byte[key.Length + 2 + zlib.Length]; + key.CopyTo (payload, 0); + zlib.CopyTo (payload, key.Length + 2); + return PngChunk ("zTXt", payload); + } + + var text = new byte[key.Length + 5 + zlib.Length]; + key.CopyTo (text, 0); + text[key.Length + 1] = 1; + zlib.CopyTo (text, key.Length + 5); + return PngChunk (utf8 ? "iTXt" : type, text); + } + + [TestMethod] + public void Read_ExiftoolArtistKeyword_IsTheArtistWhenThereIsNoAuthor () + { + Assert.AreEqual ("From exiftool", Open (Png (Text ("Artist", "From exiftool")), "a.png").Tag!.Artist); + Assert.AreEqual ("Author wins", Open (Png (Text ("Artist", "From exiftool"), Text ("Author", "Author wins")), "a.png").Tag!.Artist); + Assert.AreEqual ("Author wins", Open (Png (Text ("Author", "Author wins"), Text ("Artist", "From exiftool")), "a.png").Tag!.Artist); + + var file = Open (Png (Text ("Artist", "From exiftool")), "a.png"); + file.Tag!.Artist = null; + var output = file.Render ().ToArray (); + Assert.AreEqual (0, PngTexts (output, "Artist").Count, "null clears the exiftool keyword"); + Assert.IsNull (Open (output, "a.png").Tag!.Artist); + } + + [TestMethod] + public void Edit_ImageMagickExifTextKeyword_IsDroppedWithTheField () + { + var file = Open (Png (Text ("exif:Artist", "Old"), Text ("exif:ImageDescription", "Old"), Text ("exif:Make", "Canon")), "a.png"); + file.Tag!.Artist = "New"; + var output = file.Render ().ToArray (); + Assert.AreEqual (0, PngTexts (output, "exif:Artist").Count); + Assert.AreSequenceEqual (["Old"], PngTexts (output, "exif:ImageDescription")); + Assert.AreSequenceEqual (["Canon"], PngTexts (output, "exif:Make")); + } + + static byte[] ManyCompressedPackets (int n, int spaces) => + Png ([Text ("Title", "Old"), .. Enumerable.Range (0, n).Select (_ => Xmp (XmpPacket (Alt ("dc:title", "Old") + new string (' ', spaces)), compressed: true))]); + + // One 1 MiB inflation budget for the whole file, shared by every compressed copy, as when it is read. + [TestMethod] + [DoNotParallelize] + public void Edit_CompressedCopies_ShareOneInflationBudget () + { + var bombs = ManyCompressedPackets (10, 1_000_000); + var file = Open (bombs, "a.png"); + file.Tag!.Title = "New"; + _ = file.SaveToFile ("/a.png", new MockFileSystem ()); + var result = default (FileWriteResult); + var allocated = Bounds.AllocatedBytes (() => result = file.SaveToFile ("/a.png", new MockFileSystem ())); + Assert.IsFalse (result.IsSuccess); + StringAssert.Contains (result.Error, "all compressed text"); + Assert.IsTrue (allocated < 24L * 1024 * 1024, $"ten 1 MB packets cost {allocated} bytes"); + + string? error = null; + Bounds.AssertLinearAllocation (n => ManyCompressedPackets (n, 2000), data => { + var png = Open (data, "a.png"); + png.Tag!.Title = "New"; + var save = png.SaveToFile ("/a.png", new MockFileSystem ()); + if (!save.IsSuccess) + error = save.Error; + }, 20, runs: 3); + Assert.IsNull (error, error); + } +} diff --git a/tests/TagLibSharp2.Tests/Image/RasterSizeTests.cs b/tests/TagLibSharp2.Tests/Image/RasterSizeTests.cs new file mode 100644 index 00000000..8236be51 --- /dev/null +++ b/tests/TagLibSharp2.Tests/Image/RasterSizeTests.cs @@ -0,0 +1,93 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Buffers.Binary; +using System.Text; +using TagLibSharp2.Core; +using TagLibSharp2.Image; +using TagLibSharp2.Tests.Kit; +using static TagLibSharp2.Tests.Image.ImageAssert; +using static TagLibSharp2.Tests.Image.ImageTestBuilder; + +namespace TagLibSharp2.Tests.Image; + +/// PNG, GIF, BMP, PCX and Netpbm width, height and bit depth from their headers. +[TestClass] +[TestCategory ("Unit")] +public class RasterSizeTests +{ + [TestMethod] + public void Netpbm_WidthThatOverflowsInt32_Fails () + { + Assert.IsFalse (MediaFile.ReadFromData (Encoding.ASCII.GetBytes ("P5\n4300000000 1\n255\n"), "a.pgm").IsSuccess); + Assert.IsFalse (MediaFile.ReadFromData (Encoding.ASCII.GetBytes ("P5\n5000000000 1\n255\n"), "a.pgm").IsSuccess); + Assert.IsFalse (MediaFile.ReadFromData (Encoding.ASCII.GetBytes ("P5\n2147483648 1\n255\n"), "a.pgm").IsSuccess); + var opened = MediaFile.ReadFromData (Encoding.ASCII.GetBytes ("P5\n2 3\n255\n"), "a.pgm"); + Assert.IsTrue (opened.IsSuccess, opened.Error); + var image = (IMediaFile)opened.File!; + Assert.AreEqual (2, image.ImageProperties!.Value.Width); + Assert.AreEqual (3, image.ImageProperties.Value.Height); + } + + [TestMethod] + public void Read_Png_ReportsIhdrSize () + { + var data = PngIhdrWithoutCrc (width: 8, height: 5, depth: 8, color: 2); + AssertImage (data, "photo.png", MediaFormat.Png, 8, 5, "PNG"); + Assert.AreEqual (24, ImageOf (data, "photo.png").ImageProperties!.Value.ColorDepth); + } + + [TestMethod] + public void Read_Gif_ReportsLogicalScreen () + { + var data = GifScreen (width: 16, height: 9); + AssertImage (data, "photo.gif", MediaFormat.Gif, 16, 9, "GIF"); + } + + [TestMethod] + public void Read_Bmp_ReportsInfoHeaderAndAbsoluteHeight () + { + AssertImage (Bmp (width: 7, height: -3), "photo.bmp", MediaFormat.Bmp, 7, 3, "BMP"); + Assert.AreEqual (24, ImageOf (Bmp (width: 7, height: -3), "photo.bmp").ImageProperties!.Value.ColorDepth); + } + + [TestMethod] + public void Read_Bmp_Os2CoreHeader_ReportsSizeAndBitCount () + { + var data = new byte[26]; + "BM"u8.CopyTo (data); + BinaryPrimitives.WriteInt32LittleEndian (data.AsSpan (14), 12); + data[18] = 11; + data[20] = 6; + data[24] = 4; + AssertImage (data, "photo.bmp", MediaFormat.Bmp, 11, 6, "BMP"); + Assert.AreEqual (4, ImageOf (data, "photo.bmp").ImageProperties!.Value.ColorDepth); + } + + [TestMethod] + public void Read_Bmp_ExtremeTopDownHeight_Fails () + { + var opened = MediaFile.ReadFromData (Bmp (width: 1, height: int.MinValue), "photo.bmp"); + Assert.IsFalse (opened.IsSuccess); + } + + [TestMethod] + public void Read_Pcx_ReportsWindow () + { + AssertImage (Pcx (xmin: 1, ymin: 2, xmax: 10, ymax: 6), "photo.pcx", MediaFormat.Pcx, 10, 5, "PCX"); + } + + [TestMethod] + [DataRow ("P1", "PBM", "dot.pbm")] + [DataRow ("P2", "PGM", "dot.pgm")] + [DataRow ("P3", "PPM", "dot.ppm")] + [DataRow ("P4", "PBM", "dot.pbm")] + [DataRow ("P5", "PGM", "dot.pgm")] + [DataRow ("P6", "PPM", "dot.ppm")] + [DataRow ("P6", "PPM", "dot.pnm")] + public void Read_Netpbm_ReportsRasterSize (string magic, string kind, string name) + { + var data = System.Text.Encoding.ASCII.GetBytes (magic + "\n# note\n12 9\n255\n"); + AssertImage (data, name, MediaFormat.Netpbm, 12, 9, kind); + } +} diff --git a/tests/TagLibSharp2.Tests/Image/StillImageFileEntryTests.cs b/tests/TagLibSharp2.Tests/Image/StillImageFileEntryTests.cs new file mode 100644 index 00000000..2482b73a --- /dev/null +++ b/tests/TagLibSharp2.Tests/Image/StillImageFileEntryTests.cs @@ -0,0 +1,243 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Buffers.Binary; +using System.IO.Compression; +using System.Text; +using TagLibSharp2.Core; +using TagLibSharp2.Image; +using TagLibSharp2.Image.Tiff; +using TagLibSharp2.Tests.Core; +using TagLibSharp2.Tests.Kit; +using static TagLibSharp2.Tests.Image.ImageTestBuilder; + +namespace TagLibSharp2.Tests.Image; + +/// Opening and saving a still image through every entry point: data, path, stream, sync and async, cancellation, and results. +[TestClass] +[TestCategory ("Unit")] +public partial class StillImageFileEntryTests +{ + [TestMethod] + public void Save_WithoutASourcePath_Fails () + { + var file = Open (TitledPng ("Door"), "photo.png"); + Assert.IsNull (file.VideoProperties); + var sync = file.SaveToFile (); + var async = file.SaveToFileAsync ().GetAwaiter ().GetResult (); + Assert.IsFalse (sync.IsSuccess, sync.Error); + Assert.IsFalse (async.IsSuccess, async.Error); + file.Dispose (); + } + + [TestMethod] + public void SaveToFileAsync_WritesTheRenderedBytes () + { + var data = TitledPng ("Door"); + var fs = new MockFileSystem (); + fs.AddFile ("/photo.png", data); + var opened = MediaFile.Read ("/photo.png", fs); + var file = (StillImageFile)opened.File!; + file.Tag!.Comment = "async"; + var wrote = file.SaveToFileAsync ().GetAwaiter ().GetResult (); + Assert.IsTrue (wrote.IsSuccess, wrote.Error); + Assert.AreEqual ("async", MediaFile.Read ("/photo.png", fs).Tag!.Comment); + Assert.AreEqual ("Door", MediaFile.Read ("/photo.png", fs).Tag!.Title); + } + + [TestMethod] + public void ReadAsync_OpensAnImageAndHonoursCancellationDuringTheBodyRead () + { + var png = MinimalPng (PngChunk ("IDAT", [0x01])); + using (var stream = new MemoryStream (png, writable: false)) { + var opened = MediaFile.ReadAsync (stream, "a.png").GetAwaiter ().GetResult (); + Assert.IsTrue (opened.IsSuccess, opened.Error); + var image = (IMediaFile)opened.File!; + Assert.AreEqual (1, image.ImageProperties!.Value.Width); + Assert.AreEqual (1, image.ImageProperties.Value.Height); + } + + using var cancel = new CancelAfterPeek (png); + Assert.ThrowsExactly (() => + MediaFile.ReadAsync (cancel, "a.png").GetAwaiter ().GetResult ()); + } + + sealed class CancelAfterPeek : MemoryStream + { + int _asyncReads; + + public CancelAfterPeek (byte[] data) + : base (data, writable: false) + { + } + + public override ValueTask ReadAsync (Memory buffer, CancellationToken cancellationToken = default) + { + if (++_asyncReads > 1) + throw new OperationCanceledException (cancellationToken); + return base.ReadAsync (buffer, cancellationToken); + } + } + + static byte[] LargePng () => Png (PngChunk ("IDAT", new byte[8 * Mib])); + + [TestMethod] + public void ReadFromData_KeepsTheCallersArray () + { + var png = LargePng (); + _ = MediaFile.ReadFromData (png, "a.png"); + Bounds.AssertAllocatesAtMost (64 * 1024, () => MediaFile.ReadFromData (png, "a.png")); + } + + [TestMethod] + public void ReadFromAPath_CopiesTheFileOnce () + { + var png = LargePng (); + var fs = new MockFileSystem (); + fs.AddFile ("/a.png", png); + _ = MediaFile.Read ("/a.png", fs); + _ = StillImageFile.ReadFromFile ("/a.png", fs); + var limit = png.Length + (256 * 1024); + + var read = MediaFile.Read ("/a.png", fs); + Bounds.AssertAllocatesAtMost (limit, () => read = MediaFile.Read ("/a.png", fs), "MediaFile.Read"); + Assert.IsTrue (read.IsSuccess, read.Error); + var fromFile = StillImageFile.ReadFromFile ("/a.png", fs); + Bounds.AssertAllocatesAtMost (limit, () => fromFile = StillImageFile.ReadFromFile ("/a.png", fs), "StillImageFile.ReadFromFile"); + Assert.IsTrue (fromFile.IsSuccess, fromFile.Error); + using var stream = new MemoryStream (png, writable: false); + var fromStream = MediaFile.Read (stream, "a.png"); + stream.Position = 0; + Bounds.AssertAllocatesAtMost (limit, () => fromStream = MediaFile.Read (stream, "a.png"), "MediaFile.Read (stream)"); + Assert.IsTrue (fromStream.IsSuccess, fromStream.Error); + } + + [TestMethod] + public void Render_ReturnsTheOriginalBytes () + { + var data = PngIhdrWithoutCrc (width: 2, height: 2, depth: 8, color: 0); + var opened = MediaFile.ReadFromData (data, "a.png"); + var file = (StillImageFile)opened.File!; + CollectionAssert.AreEqual (data, file.Render ().ToArray ()); + } + + [TestMethod] + public void SaveToFile_WritesTheRenderedBytes () + { + var data = MinimalPng (PngChunk ("IDAT", [0x07])); + var fs = new MockFileSystem (); + fs.AddFile ("/photo.png", data); + var opened = MediaFile.Read ("/photo.png", fs); + Assert.IsTrue (opened.IsSuccess, opened.Error); + var file = (StillImageFile)opened.File!; + file.Tag!.Title = "Saved"; + var wrote = file.SaveToFile (); + Assert.IsTrue (wrote.IsSuccess, wrote.Error); + Assert.AreEqual ("Saved", MediaFile.Read ("/photo.png", fs).Tag!.Title); + CollectionAssert.AreEqual (new byte[] { 0x07 }, PngPayload (fs.ReadAllBytes ("/photo.png"), "IDAT")); + } + + public static IEnumerable Images () + { + yield return ["/a.png", Png (Text ("Title", "T")), MediaFormat.Png, 2, 3]; + yield return ["/a.gif", Gif (GifComment ("C")), MediaFormat.Gif, 1, 1]; + yield return ["/a.jpg", Jpeg (JpegSegment (0xFE, "C"u8.ToArray ())), MediaFormat.Jpeg, 2, 3]; + yield return ["/a.tif", Tiff ((256, 4), (257, 5)), MediaFormat.Tiff, 4, 5]; + yield return ["/a.dng", Tiff ((256, 4), (257, 5)), MediaFormat.Dng, 4, 5]; + yield return ["/a.svg", Encoding.UTF8.GetBytes (""), MediaFormat.Svg, 6, 7]; + yield return ["/a.pgm", Encoding.ASCII.GetBytes ("P5 8 9 255\n"), MediaFormat.Netpbm, 8, 9]; + } + + [TestMethod] + [DynamicData (nameof (Images))] + public void EveryEntryPoint_OpensTheSameImage (string path, byte[] data, MediaFormat format, int width, int height) + { + var fs = new MockFileSystem (); + fs.AddFile (path, data); + var opened = new[] { + StillImageFile.ReadFromFile (path, fs).File, + StillImageFile.ReadFromFileAsync (path, fs).GetAwaiter ().GetResult ().File, + (StillImageFile?)MediaFile.Read (path, fs).File, + }; + foreach (var file in opened) { + Assert.IsNotNull (file, path); + Assert.AreEqual (format, file.Format, path); + Assert.AreEqual (width, file.ImageProperties!.Value.Width, path); + Assert.AreEqual (height, file.ImageProperties.Value.Height, path); + Assert.AreEqual (path, file.SourcePath); + } + + var fromBytes = StillImageFile.Read (data); + Assert.IsTrue (fromBytes.IsSuccess, fromBytes.Error); + Assert.AreEqual (format == MediaFormat.Dng ? MediaFormat.Tiff : format, fromBytes.File!.Format, "bytes alone cannot name a DNG without its version tag"); + Assert.IsNull (fromBytes.File.SourcePath); + Assert.IsTrue (StillImageFile.TryRead (data, out var tried)); + Assert.AreEqual (width, tried!.ImageProperties!.Value.Width); + Assert.IsTrue (StillImageFile.IsValidFormat (data)); + } + + [TestMethod] + public void ReadFromFile_ThenSave_WritesBackToTheSource () + { + var fs = new MockFileSystem (); + fs.AddFile ("/a.png", Png (Text ("Title", "Old"))); + var file = StillImageFile.ReadFromFile ("/a.png", fs).File!; + file.Tag!.Title = "New"; + Assert.IsTrue (file.SaveToFile ().IsSuccess); + Assert.AreEqual ("New", StillImageFile.ReadFromFile ("/a.png", fs).File!.Tag!.Title); + + var again = StillImageFile.ReadFromFileAsync ("/a.png", fs).GetAwaiter ().GetResult ().File!; + again.Tag!.Title = "Async"; + Assert.IsTrue (again.SaveToFileAsync ().GetAwaiter ().GetResult ().IsSuccess); + Assert.AreEqual ("Async", StillImageFile.ReadFromFile ("/a.png", fs).File!.Tag!.Title); + } + + [TestMethod] + public void Failures_ReturnAResultWithTheirOwnReason () + { + var fs = new MockFileSystem (); + fs.AddFile ("/a.mp3", [0xFF, 0xFB, 0x90, 0x00]); + fs.AddFile ("/locked.png", Png ()); + fs.MarkInaccessible ("/locked.png"); + fs.AddFile ("/bad.png", Concat (PngSignature, PngChunk ("IHDR", [0, 0, 0, 0, 0, 0, 0, 0, 8, 0, 0, 0, 0]))); + + StringAssert.Contains (StillImageFile.ReadFromFile ("/missing.png", fs).Error, "not found"); + StringAssert.Contains (StillImageFile.ReadFromFileAsync ("/missing.png", fs).GetAwaiter ().GetResult ().Error, "not found"); + StringAssert.Contains (StillImageFile.ReadFromFile ("/a.mp3", fs).Error, "Not a still image"); + StringAssert.Contains (StillImageFile.ReadFromFile ("/locked.png", fs).Error, "Access denied"); + StringAssert.Contains (StillImageFile.ReadFromFileAsync ("/locked.png", fs).GetAwaiter ().GetResult ().Error, "Access denied"); + StringAssert.Contains (StillImageFile.ReadFromFile ("/bad.png", fs).Error, "Not a Png image"); + Assert.IsFalse (StillImageFile.TryRead ([], out var none)); + Assert.IsNull (none); + Assert.IsFalse (StillImageFile.IsValidFormat ("ID3"u8)); + Assert.ThrowsExactly (() => StillImageFile.ReadFromFile (null!, fs)); + } + + [TestMethod] + public void ReadFromFileAsync_IsCancelled () + { + var fs = new MockFileSystem (); + fs.AddFile ("/a.png", Png ()); + using var cancel = new CancellationTokenSource (); + cancel.Cancel (); + var result = StillImageFile.ReadFromFileAsync ("/a.png", fs, cancel.Token).GetAwaiter ().GetResult (); + Assert.IsFalse (result.IsSuccess); + StringAssert.Contains (result.Error, "cancelled"); + } + + [TestMethod] + public void ReadResult_HasValueEquality () + { + var file = StillImageFile.Read (Png ()).File!; + var a = StillImageFileReadResult.Success (file); + var b = StillImageFileReadResult.Success (file); + var failed = StillImageFileReadResult.Failure ("x"); + Assert.IsTrue (a == b); + Assert.IsFalse (a != b); + Assert.IsTrue (a.Equals ((object)b)); + Assert.AreEqual (a.GetHashCode (), b.GetHashCode ()); + Assert.IsTrue (a != failed); + Assert.IsFalse (failed.IsSuccess); + Assert.IsFalse (a.Equals ("x")); + } +} diff --git a/tests/TagLibSharp2.Tests/Image/StillImageFilePinTests.cs b/tests/TagLibSharp2.Tests/Image/StillImageFilePinTests.cs new file mode 100644 index 00000000..e70447cf --- /dev/null +++ b/tests/TagLibSharp2.Tests/Image/StillImageFilePinTests.cs @@ -0,0 +1,163 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Runtime.InteropServices; +using System.Text; +using TagLibSharp2.Core; +using TagLibSharp2.Image; +using TagLibSharp2.Image.Exif; +using TagLibSharp2.Image.Gif; +using TagLibSharp2.Image.Png; +using TagLibSharp2.Image.Svg; +using TagLibSharp2.Image.Tiff; +using TagLibSharp2.Tests.Core; +using TagLibSharp2.Tests.Kit; +using static TagLibSharp2.Tests.Image.ImageTestBuilder; + +namespace TagLibSharp2.Tests.Image; + +public partial class StillImageFileEntryTests +{ + [TestMethod] + public void InvalidProperties_AreNotStored () + { + var file = new StillImageFile ([1, 2, 3], MediaFormat.Svg, new ImageProperties (0, 0, 0, "SVG"), null); + + Assert.IsNull (file.ImageProperties); + } + + [TestMethod] + public void ReadFromFile_NullPathThrows_AndAMissingFileNamesItself () + { + Assert.ThrowsExactly (() => StillImageFile.ReadFromFile (null!)); + var missing = StillImageFile.ReadFromFile ("/no/such.jpg", new MockFileSystem ()); + + Assert.IsFalse (missing.IsSuccess); + Assert.AreEqual ("File not found: /no/such.jpg", missing.Error); + } + + [TestMethod] + public void SaveWithoutASourcePath_NamesTheMissingPath_OnBothOverloads () + { + var opened = StillImageFile.Read (Bmp (1, 1)); + Assert.IsTrue (opened.IsSuccess, opened.Error); + + var sync = opened.File!.SaveToFile (); + var async = opened.File.SaveToFileAsync ().GetAwaiter ().GetResult (); + + Assert.AreEqual ("No source path available. Use SaveToFile(path) instead.", sync.Error); + Assert.AreEqual ("No source path available. Use SaveToFile(path) instead.", async.Error); + Assert.ThrowsExactly (() => opened.File.SaveToFile ((string)null!)); + Assert.ThrowsExactly (() => opened.File.SaveToFileAsync ((string)null!).GetAwaiter ().GetResult ()); + } + + [TestMethod] + public void SaveToFile_UsesTheFileSystemItWasGiven () + { + var bmp = Bmp (1, 1); + var store = new MockFileSystem (); + var opened = StillImageFile.Read (bmp); + Assert.IsTrue (opened.IsSuccess, opened.Error); + + var saved = opened.File!.SaveToFile ("/out.bmp", store); + + Assert.IsTrue (saved.IsSuccess, saved.Error); + CollectionAssert.AreEqual (bmp, store.ReadAllBytes ("/out.bmp")); + + var asyncSaved = opened.File.SaveToFileAsync ("/out-async.bmp", store).GetAwaiter ().GetResult (); + + Assert.IsTrue (asyncSaved.IsSuccess, asyncSaved.Error); + CollectionAssert.AreEqual (bmp, store.ReadAllBytes ("/out-async.bmp")); + } + + [TestMethod] + public void SaveToFile_NullPathThrowsBeforeTheFileSystemIsUsed () + { + var opened = StillImageFile.Read (Bmp (1, 1)); + Assert.IsTrue (opened.IsSuccess, opened.Error); + var files = FaultFileSystem.RootDirectory (); + + var sync = Assert.ThrowsExactly (() => opened.File!.SaveToFile ((string)null!, files)); + var async = Assert.ThrowsExactly ( + () => opened.File!.SaveToFileAsync ((string)null!, files).GetAwaiter ().GetResult ()); + + Assert.AreEqual ("path", sync.ParamName); + Assert.AreEqual ("path", async.ParamName); + Assert.AreEqual (0, files.Calls); + } + + [TestMethod] + public void Save_SecondWriteReusesTheRentedBuffer () + { + var bmp = Bmp (1, 1); + var memory = new MockFileSystem (); + var opened = StillImageFile.Read (bmp); + Assert.IsTrue (opened.IsSuccess, opened.Error); + Assert.IsTrue (opened.File!.SaveToFile ("/a.bmp", memory).IsSuccess); + FileWriteResult again = default; + Bounds.AssertAllocatesAtMost (32768, () => again = opened.File.SaveToFile ("/b.bmp", memory), "held save"); + Assert.IsTrue (again.IsSuccess, again.Error); + + var stored = new MockFileSystem (); + stored.AddFile ("/in.bmp", bmp); + var fromFile = StillImageFile.ReadFromFile ("/in.bmp", stored); + Assert.IsTrue (fromFile.IsSuccess, fromFile.Error); + Assert.IsTrue (fromFile.File!.SaveToFile ("/out1.bmp", stored).IsSuccess); + FileWriteResult sourceAgain = default; + Bounds.AssertAllocatesAtMost (32768, () => sourceAgain = fromFile.File.SaveToFile ("/out2.bmp", stored), "source save"); + Assert.IsTrue (sourceAgain.IsSuccess, sourceAgain.Error); + } + + [TestMethod] + public void EmptySourcePath_IsAMissingPath () + { + var opened = StillImageFile.Read (Bmp (1, 1)); + Assert.IsTrue (opened.IsSuccess, opened.Error); + opened.File!.SetSource ("", null); + + var saved = opened.File.SaveToFile (); + + Assert.AreEqual ("No source path available. Use SaveToFile(path) instead.", saved.Error); + } + + [TestMethod] + public void SpliceFailure_DisposesTheSourceItOpened () + { + var png = Concat (PngSignature, PngChunk ("IHDR", [0, 0, 0, 1, 0, 0, 0, 1, 8, 2, 0, 0, 0])); + var fs = new ProbeFileSystem { ArmOpenTracking = true }; + fs.Add ("/a.png", png); + var opened = StillImageFile.ReadFromFile ("/a.png", fs); + Assert.IsTrue (opened.IsSuccess, opened.Error); + opened.File!.Tag!.Title = "new"; + + var saved = opened.File.SaveToFile ("/b.jpg", fs); + + Assert.IsFalse (saved.IsSuccess, saved.Error); + Assert.IsNotNull (fs.SaveOpen); + Assert.IsTrue (fs.SaveOpen!.WasDisposed); + } + + [TestMethod] + public void ReadResult_DefaultIsNotSuccess_AndFailuresDifferByError () + { + Assert.IsFalse (default (StillImageFileReadResult).IsSuccess); + Assert.IsFalse (StillImageFileReadResult.Failure ("a").Equals (StillImageFileReadResult.Failure ("b"))); + var opened = StillImageFile.Read (Bmp (1, 1)); + Assert.IsTrue (opened.IsSuccess, opened.Error); + Assert.IsFalse (opened.Equals (StillImageFile.Read (Bmp (2, 2)))); + } + + [TestMethod] + public void ReadFromFile_NamesAnIoFailure () + { + var broken = FaultFileSystem.Io (new IOException ("disk")); + var sync = StillImageFile.ReadFromFile ("/a.jpg", broken); + var async = StillImageFile.ReadFromFileAsync ("/a.jpg", broken).GetAwaiter ().GetResult (); + + Assert.AreEqual ("Failed to read file: disk", sync.Error); + Assert.AreEqual ("Failed to read file: disk", async.Error); + + var denied = StillImageFile.ReadFromFile ("/a.jpg", FaultFileSystem.Io (new UnauthorizedAccessException ("no"))); + Assert.AreEqual ("Access denied: no", denied.Error); + } +} diff --git a/tests/TagLibSharp2.Tests/Image/SvgSizePinTests.cs b/tests/TagLibSharp2.Tests/Image/SvgSizePinTests.cs new file mode 100644 index 00000000..afb70deb --- /dev/null +++ b/tests/TagLibSharp2.Tests/Image/SvgSizePinTests.cs @@ -0,0 +1,139 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Runtime.InteropServices; +using System.Text; +using TagLibSharp2.Core; +using TagLibSharp2.Image; +using TagLibSharp2.Image.Exif; +using TagLibSharp2.Image.Gif; +using TagLibSharp2.Image.Png; +using TagLibSharp2.Image.Svg; +using TagLibSharp2.Image.Tiff; +using TagLibSharp2.Tests.Core; +using TagLibSharp2.Tests.Kit; +using static TagLibSharp2.Tests.Image.ImageTestBuilder; + +namespace TagLibSharp2.Tests.Image; + +public partial class SvgSizeTests +{ + [TestMethod] + [DataRow (" ")] + [DataRow ("")] + [DataRow ("")] + [DataRow ("")] + [DataRow ("")] + [DataRow ("")] + [DataRow (" b\" width=\"3\" height=\"4\"/>")] + [DataRow ("")] + [DataRow ("")] + [DataRow ("")] + [DataRow ("")] + [DataRow ("")] + public void Svg_BoundaryDocuments_KeepTheirSize (string markup) + { + var data = Encoding.UTF8.GetBytes (markup); + var read = SvgSize.TryRead (data, out var properties); + var detect = SvgSize.IsSvg (data); + Assert.AreEqual (ExpectedSvg (markup), Describe (detect, read, properties), markup); + } + + [TestMethod] + public void Svg_Utf16Spaces_AreNotAnImage () + { + var data = Encoding.Unicode.GetPreamble ().Concat (Encoding.Unicode.GetBytes (" ")).ToArray (); + + Assert.IsFalse (SvgSize.IsSvg (data)); + Assert.IsFalse (SvgSize.TryRead (data, out var properties)); + Assert.IsNull (properties); + } + + static string Describe (bool detect, bool read, ImageProperties? properties) => + $"{detect}|{read}|{(properties is { } size ? $"{size.Width}x{size.Height}" : "none")}"; + + static string ExpectedSvg (string markup) => markup switch { + " " => "False|False|none", + "" => "True|True|1x2", + "" => "True|True|1x2", + "" => "True|True|1x2", + "" => "False|False|none", + " "True|True|none", + " "False|False|none", + "" => "False|False|none", + " b\" width=\"3\" height=\"4\"/>" => "True|True|3x4", + "" => "True|True|2147483647x1", + "" => "True|True|none", + "" => "True|True|38x38", + "" => "True|True|96x1", + "" => "True|True|16x1", + _ => "?", + }; + + [TestMethod] + public void Svg_UnclosedXmlDeclaration_IsNotSvg () + { + Assert.IsFalse (SvgSize.TryRead (""u8, out var properties)); + Assert.IsNull (properties); + } + + [TestMethod] + public void Svg_ProcessingInstructionBeforeTheRoot_StillHasTheSize () + { + Assert.IsTrue (SvgSize.TryRead (" "u8, out var properties)); + Assert.AreEqual ("1x1", properties is { } size ? $"{size.Width}x{size.Height}" : "none"); + } + + [TestMethod] + public void Svg_UnclosedProcessingInstruction_IsNotSvg () + { + Assert.IsFalse (SvgSize.TryRead (""u8, out var properties)); + Assert.IsNull (properties); + } + + [TestMethod] + [DataRow ("", "True|True|100x1")] + [DataRow ("", "True|True|2x1")] + [DataRow ("", "True|True|none")] + [DataRow ("", "True|True|none")] + public void Svg_MoreBoundaries (string markup, string expected) + { + var data = Encoding.UTF8.GetBytes (markup); + var read = SvgSize.TryRead (data, out var properties); + Assert.AreEqual (expected, $"{SvgSize.IsSvg (data)}|{read}|{(properties is { } size ? $"{size.Width}x{size.Height}" : "none")}"); + } + + [TestMethod] + [DataRow ("", "True|True|none")] + [DataRow ("", "True|True|none")] + [DataRow ("", "True|True|1x1")] + [DataRow ("", "True|True|100x1")] + [DataRow ("", "True|True|2x3")] + [DataRow ("", "True|True|10x20")] + [DataRow ("", "True|True|none")] + [DataRow ("", "True|True|none")] + [DataRow ("", "True|True|none")] + [DataRow (" ", "True|True|1x2")] + [DataRow ("\"> ", "True|True|1x2")] + [DataRow ("", "True|True|none")] + [DataRow ("", "True|True|none")] + [DataRow ("", "True|True|none")] + [DataRow ("", "True|True|2x1")] + [DataRow ("SVG width and height from the root element or its viewBox, decoding only the root start tag. +[TestClass] +[TestCategory ("Unit")] +public partial class SvgSizeTests +{ + [TestMethod] + public void Svg_ReadsScientificLengthsNamespacedRootsUtf16AndALongPrologue () + { + AssertSize (Encoding.UTF8.GetBytes (""""""), "a.svg", 100, 50); + AssertSize (Encoding.UTF8.GetBytes (""""""), "a.svg", 10, 20); + var utf16 = Encoding.Unicode.GetPreamble ().Concat (Encoding.Unicode.GetBytes ("""""")).ToArray (); + AssertSize (utf16, "a.svg", 4, 6); + var late = Encoding.UTF8.GetBytes (""""); + AssertSize (late, "a.svg", 3, 4); + AssertSize (Encoding.UTF8.GetBytes (""""""), "a.svg", 9, 8); + } + + public static IEnumerable SvgThatIsLarge () + { + yield return ["root after a 60 KB comment", Encoding.UTF8.GetBytes ("""" + new string ('y', Mib) + "")]; + yield return ["UTF-16 root after a doctype", Concat ([0xFF, 0xFE], Encoding.Unicode.GetBytes ("""">]>""" + new string ('y', Mib / 2) + ""))]; + yield return ["UTF-16BE", Concat ([0xFE, 0xFF], Encoding.BigEndianUnicode.GetBytes ("""""" + new string ('y', Mib / 2) + ""))]; + yield return ["UTF-8 BOM and a prefix", Concat ([0xEF, 0xBB, 0xBF], Encoding.UTF8.GetBytes ("""""" + new string ('y', Mib) + ""))]; + } + + [TestMethod] + [DynamicData (nameof (SvgThatIsLarge))] + public void Svg_DetectionCopiesNothing_AndReadingDecodesOnlyTheRootTag (string name, byte[] data) + { + _ = MediaFile.DetectFormat (data); + var format = MediaFile.DetectFormat (data); + Bounds.AssertAllocatesAtMost (Noise, () => format = MediaFile.DetectFormat (data), name); + Assert.AreEqual (MediaFormat.Svg, format, name); + + ImageProperties? properties = null; + _ = ImageHeader.TryRead (data, MediaFormat.Svg, out _); + var read = false; + Bounds.AssertAllocatesAtMost (2 * Noise, () => read = ImageHeader.TryRead (data, MediaFormat.Svg, out properties), name); + Assert.IsTrue (read, name); + Assert.AreEqual (7, properties!.Value.Width, name); + Assert.AreEqual (9, properties.Value.Height, name); + } + + [TestMethod] + public void Read_Svg_ReportsWidthOrViewBox () + { + var sized = System.Text.Encoding.UTF8.GetBytes (""""""); + AssertImage (sized, "drawing.svg", MediaFormat.Svg, 12, 8, "SVG"); + + var box = System.Text.Encoding.UTF8.GetBytes (""""""); + AssertImage (box, "drawing.svg", MediaFormat.Svg, 20, 11, "SVG"); + + var bare = System.Text.Encoding.UTF8.GetBytes (""); + var opened = MediaFile.ReadFromData (bare, "drawing.svg"); + Assert.IsTrue (opened.IsSuccess, opened.Error); + Assert.AreEqual (MediaFormat.Svg, opened.Format); + Assert.IsNull (((IMediaFile)opened.File!).ImageProperties); + + var percent = System.Text.Encoding.UTF8.GetBytes (""""""); + AssertImage (percent, "drawing.svg", MediaFormat.Svg, 30, 10, "SVG"); + + var named = System.Text.Encoding.UTF8.GetBytes (""""""); + AssertImage (named, "drawing.svg", MediaFormat.Svg, 9, 8, "SVG"); + + var bom = new byte[] { 0xEF, 0xBB, 0xBF }; + var body = System.Text.Encoding.UTF8.GetBytes (""""""); + var withBom = new byte[bom.Length + body.Length]; + bom.CopyTo (withBom, 0); + body.CopyTo (withBom, bom.Length); + AssertImage (withBom, "drawing.svg", MediaFormat.Svg, 4, 5, "SVG"); + + var prologue = new string (' ', 80); + var late = System.Text.Encoding.UTF8.GetBytes ($"""{prologue}"""); + AssertImage (late, "drawing.svg", MediaFormat.Svg, 3, 4, "SVG"); + + var comment = System.Text.Encoding.UTF8.GetBytes (""""""); + AssertImage (comment, "drawing.svg", MediaFormat.Svg, 6, 7, "SVG"); + var declared = System.Text.Encoding.UTF8.GetBytes (""""""); + AssertImage (declared, "drawing.svg", MediaFormat.Svg, 2, 3, "SVG"); + var inches = System.Text.Encoding.UTF8.GetBytes (""""""); + AssertImage (inches, "drawing.svg", MediaFormat.Svg, 96, 192, "SVG"); + var points = System.Text.Encoding.UTF8.GetBytes (""""""); + AssertImage (points, "drawing.svg", MediaFormat.Svg, 16, 16, "SVG"); + var relative = System.Text.Encoding.UTF8.GetBytes (""""""); + AssertImage (relative, "drawing.svg", MediaFormat.Svg, 9, 8, "SVG"); + var commas = System.Text.Encoding.UTF8.GetBytes (""""""); + AssertImage (commas, "drawing.svg", MediaFormat.Svg, 100, 50, "SVG"); + + // A '>' inside an earlier quoted attribute is not the end of the start tag. + var quoted = System.Text.Encoding.UTF8.GetBytes (""""""); + AssertImage (quoted, "drawing.svg", MediaFormat.Svg, 7, 9, "SVG"); + } +} diff --git a/tests/TagLibSharp2.Tests/Image/TiffBuilder.cs b/tests/TagLibSharp2.Tests/Image/TiffBuilder.cs new file mode 100644 index 00000000..fc7ca1fe --- /dev/null +++ b/tests/TagLibSharp2.Tests/Image/TiffBuilder.cs @@ -0,0 +1,97 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Buffers.Binary; + +namespace TagLibSharp2.Tests.Image; + +/// +/// The test side's TIFF writer: a header, IFD tables, values and raw bytes at chosen offsets, in either byte order, +/// classic TIFF or BigTIFF. It writes exactly what it is told (overlaps, bad counts and missing next offsets +/// included) and shares no code with the library. +/// +/// The size of the TIFF in bytes. +/// "MM" (big-endian) instead of "II". +/// BigTIFF (version 43: 8-byte counts and offsets, 20-byte entries) instead of classic TIFF. +sealed class TiffBuilder (int length, bool bigEndian = false, bool big = false) +{ + readonly byte[] _data = new byte[length]; + + public int Length => _data.Length; + + /// The byte-order mark and version (42, or 43 for BigTIFF), then the first IFD's offset. + public TiffBuilder Header (long ifd0) + { + (bigEndian ? "MM"u8 : "II"u8).CopyTo (_data); + U16 (2, big ? 43 : 42); + if (!big) + return U32 (4, ifd0); + return U16 (4, 8).U16 (6, 0).U64 (8, ifd0); + } + + /// + /// A table at : the count, each entry's tag, type, count and value (or value offset), then + /// the next-IFD offset, which is not written when is null. + /// + public TiffBuilder Table (int at, (int Tag, int Type, long Count, long Value)[] entries, long? next = 0) + { + var entrySize = big ? 20 : 12; + var countSize = big ? 8 : 2; + Word (at, entries.Length, countSize); + for (var n = 0; n < entries.Length; n++) { + var e = at + countSize + (entrySize * n); + U16 (e, entries[n].Tag).U16 (e + 2, entries[n].Type); + Word (e + 4, entries[n].Count, big ? 8 : 4); + Word (e + (big ? 12 : 8), entries[n].Value, big ? 8 : 4); + } + + if (next is long offset) + Word (at + countSize + (entrySize * entries.Length), offset, big ? 8 : 4); + return this; + } + + /// A table's count and entries only: whatever is after them stays as it is. + public TiffBuilder Entries (int at, params (int Tag, int Type, long Count, long Value)[] entries) => + Table (at, entries, next: null); + + public TiffBuilder Bytes (int at, ReadOnlySpan bytes) + { + bytes.CopyTo (_data.AsSpan (at)); + return this; + } + + public TiffBuilder U16 (int at, int value) + { + if (bigEndian) + BinaryPrimitives.WriteUInt16BigEndian (_data.AsSpan (at), (ushort)value); + else + BinaryPrimitives.WriteUInt16LittleEndian (_data.AsSpan (at), (ushort)value); + return this; + } + + public TiffBuilder U32 (int at, long value) + { + if (bigEndian) + BinaryPrimitives.WriteUInt32BigEndian (_data.AsSpan (at), (uint)value); + else + BinaryPrimitives.WriteUInt32LittleEndian (_data.AsSpan (at), (uint)value); + return this; + } + + public TiffBuilder U64 (int at, long value) + { + if (bigEndian) + BinaryPrimitives.WriteUInt64BigEndian (_data.AsSpan (at), (ulong)value); + else + BinaryPrimitives.WriteUInt64LittleEndian (_data.AsSpan (at), (ulong)value); + return this; + } + + public byte[] ToArray () => _data; + + TiffBuilder Word (int at, long value, int size) => size switch { + 2 => U16 (at, (int)value), + 4 => U32 (at, value), + _ => U64 (at, value) + }; +} diff --git a/tests/TagLibSharp2.Tests/Image/TiffHeaderPinTests.cs b/tests/TagLibSharp2.Tests/Image/TiffHeaderPinTests.cs new file mode 100644 index 00000000..91101f2b --- /dev/null +++ b/tests/TagLibSharp2.Tests/Image/TiffHeaderPinTests.cs @@ -0,0 +1,39 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Runtime.InteropServices; +using System.Text; +using TagLibSharp2.Core; +using TagLibSharp2.Image; +using TagLibSharp2.Image.Exif; +using TagLibSharp2.Image.Gif; +using TagLibSharp2.Image.Png; +using TagLibSharp2.Image.Svg; +using TagLibSharp2.Image.Tiff; +using TagLibSharp2.Tests.Core; +using TagLibSharp2.Tests.Kit; +using static TagLibSharp2.Tests.Image.ImageTestBuilder; + +namespace TagLibSharp2.Tests.Image; + +public partial class TiffHeaderTests +{ + [TestMethod] + public void AsciiPointer_IsNotFollowed_AndAnArrayPastTheData_IsNotAPointer () + { + var ascii = new TiffBuilder (40).Header (8).Table (8, [(0x8769, 2, 1, 1)]).ToArray (); + Assert.IsTrue (TiffReader.TryOpen (ascii, out var text, out _)); + Assert.IsFalse (text.TryPointers (text.Entry (8, 0), out _)); + + var past = new TiffBuilder (40).Header (8).Table (8, [(0x014A, 4, 5, 30)]).ToArray (); + Assert.IsTrue (TiffReader.TryOpen (past, out var wide, out _)); + Assert.IsFalse (wide.TryPointers (wide.Entry (8, 0), out _)); + } + + [TestMethod] + public void MotorolaOrder_RequiresBothBytes () + { + Assert.IsFalse (TiffReader.IsTiff ([(byte)'M', (byte)'I', 0, 42, 0, 0, 0, 8])); + Assert.IsTrue (TiffReader.IsTiff ([(byte)'M', (byte)'M', 0, 42, 0, 0, 0, 8])); + } +} diff --git a/tests/TagLibSharp2.Tests/Image/TiffHeaderTests.cs b/tests/TagLibSharp2.Tests/Image/TiffHeaderTests.cs new file mode 100644 index 00000000..fa833036 --- /dev/null +++ b/tests/TagLibSharp2.Tests/Image/TiffHeaderTests.cs @@ -0,0 +1,74 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using TagLibSharp2.Core; +using TagLibSharp2.Image; + +namespace TagLibSharp2.Tests.Image; + +/// The TIFF and BigTIFF headers a file is detected by, and the 8-byte reads BigTIFF needs. +[TestClass] +[TestCategory ("Unit")] +public partial class TiffHeaderTests +{ + // A BigTIFF header is "II" 43 0 or "MM" 0 43 (byte order, then version 43 in that order), then offset size 8, + // reserved 0 and the first IFD's 8-byte offset: 16 bytes. Anything else, or fewer bytes, is not TIFF. + [TestMethod] + [DataRow (new byte[] { 0x49, 0x49, 0x2B, 0x00, 8, 0, 0, 0, 16, 0, 0, 0, 0, 0, 0, 0 }, true)] + [DataRow (new byte[] { 0x4D, 0x4D, 0x00, 0x2B, 0, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16 }, true)] + [DataRow (new byte[] { 0x49, 0x49, 0x2B, 0x00, 8, 0, 0, 0, 16, 0, 0, 0, 0, 0, 0 }, false)] + [DataRow (new byte[] { 0x4D, 0x4D, 0x2B, 0x00, 0, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16 }, false)] + [DataRow (new byte[] { 0x49, 0x49, 0x00, 0x2B, 8, 0, 0, 0, 16, 0, 0, 0, 0, 0, 0, 0 }, false)] + [DataRow (new byte[] { 0x4D, 0x49, 0x00, 0x2B, 0, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16 }, false)] + [DataRow (new byte[] { 0x49, 0x4D, 0x2B, 0x00, 8, 0, 0, 0, 16, 0, 0, 0, 0, 0, 0, 0 }, false)] + [DataRow (new byte[] { 0x4D, 0x4D, 0x01, 0x2B, 0, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16 }, false)] + [DataRow (new byte[] { 0x4D, 0x4D, 0x00, 0x2A, 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 0, 0 }, true)] + [DataRow (new byte[] { 0x4D, 0x4D, 0x2A, 0x00, 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 0, 0 }, false)] + [DataRow (new byte[] { 0x49, 0x4D, 0x2A, 0x00, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, false)] + public void Detection_OfATiffHeader (byte[] header, bool isTiff) => + Assert.AreEqual (isTiff ? MediaFormat.Tiff : MediaFormat.Unknown, MediaFile.DetectFormat (header)); + + // A file named .tif that is not TIFF has no size, whatever its length. + [TestMethod] + [DataRow (new byte[0])] + [DataRow (new byte[] { 0x49, 0x49, 0x2B, 0x00 })] + [DataRow (new byte[] { 0x4D, 0x4D, 0x00, 0x2B, 0, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0 })] + public void Size_OfDataThatIsNotTiff_IsNone (byte[] data) => + Assert.IsFalse (TagLibSharp2.Image.Tiff.TiffSize.TryRead (data, dng: false, out _)); + + // An 8-byte value is read only when all 8 bytes are there, in the file's byte order, and only up to 2^63 - 1. + [TestMethod] + public void TryU64_ReadsEightBytesInEitherOrder_UpToTheLargestLong () + { + byte[] data = [0, 1, 2, 3, 4, 5, 6, 7, 8]; + + Assert.IsTrue (Endian.TryU64 (data, 1, le: true, out var little)); + Assert.AreEqual (0x0807060504030201, little); + Assert.IsTrue (Endian.TryU64 (data, 1, le: false, out var big)); + Assert.AreEqual (0x0102030405060708, big); + Assert.IsFalse (Endian.TryU64 (data, 2, le: true, out _), "one byte short"); + Assert.IsFalse (Endian.TryU64 (data, -1, le: true, out _), "before the data"); + Assert.IsTrue (Endian.TryU64 ([0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x7F], 0, le: true, out var largest)); + Assert.AreEqual (long.MaxValue, largest); + Assert.IsFalse (Endian.TryU64 ([0, 0, 0, 0, 0, 0, 0, 0x80], 0, le: true, out var past), "above 2^63 - 1"); + Assert.AreEqual (0, past); + } +} + +/// The walks' counted list: indexes past its count are refused, read or written, though its array is larger. +[TestClass] +[TestCategory ("Unit")] +public class CountedListTests +{ + [TestMethod] + public void Index_PastTheCount_IsRefused () + { + var list = new TagLibSharp2.Image.Tiff.CountedList (); + list.Add (5); + + Assert.AreEqual (5, list[0]); + Assert.ThrowsExactly (() => list[1]); + Assert.ThrowsExactly (() => list[1] = 2); + Assert.ThrowsExactly (() => list[-1]); + } +} diff --git a/tests/TagLibSharp2.Tests/Image/TiffSizePinTests.cs b/tests/TagLibSharp2.Tests/Image/TiffSizePinTests.cs new file mode 100644 index 00000000..a5213084 --- /dev/null +++ b/tests/TagLibSharp2.Tests/Image/TiffSizePinTests.cs @@ -0,0 +1,26 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Runtime.InteropServices; +using System.Text; +using TagLibSharp2.Core; +using TagLibSharp2.Image; +using TagLibSharp2.Image.Exif; +using TagLibSharp2.Image.Gif; +using TagLibSharp2.Image.Png; +using TagLibSharp2.Image.Svg; +using TagLibSharp2.Image.Tiff; +using TagLibSharp2.Tests.Core; +using TagLibSharp2.Tests.Kit; +using static TagLibSharp2.Tests.Image.ImageTestBuilder; + +namespace TagLibSharp2.Tests.Image; + +public partial class TiffSizeTests +{ + [TestMethod] + public void Ifd0NextCutShort_IsNullForAJpeg () + { + Assert.IsNull (TiffSize.Ifd0NextCutShort (Jpeg ())); + } +} diff --git a/tests/TagLibSharp2.Tests/Image/TiffSizeRuleTests.cs b/tests/TagLibSharp2.Tests/Image/TiffSizeRuleTests.cs new file mode 100644 index 00000000..c6d6e856 --- /dev/null +++ b/tests/TagLibSharp2.Tests/Image/TiffSizeRuleTests.cs @@ -0,0 +1,305 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using TagLibSharp2.Core; +using TagLibSharp2.Image; +using TagLibSharp2.Image.Tiff; + +namespace TagLibSharp2.Tests.Image; + +/// +/// Which IFD's width and height a TIFF reports. Every expected size is exiftool 13.55's ImageSize for the same bytes +/// (measured), except where a case's name gives exiftool's answer and says why it differs. +/// +[TestClass] +[TestCategory ("Unit")] +public class TiffSizeRuleTests +{ + static (int, int, long, long) L (int tag, long value) => (tag, 4, 1, value); + + static (int, int, long, long)[] Image (long subfileType, long width, long height) => + [L (254, subfileType), L (256, width), L (257, height)]; + + static (int, int, long, long)[] Size (long width, long height) => [L (256, width), L (257, height)]; + + // Little-endian classic TIFF, IFD0 first; a table's next offset, then raw bytes. + static byte[] Classic ((int At, (int, int, long, long)[] Entries, long Next)[] ifds, params (int At, byte[] Bytes)[] raw) + { + var length = Math.Max (ifds.Max (i => i.At + 2 + (12 * i.Entries.Length) + 4), raw.Length == 0 ? 0 : raw.Max (r => r.At + r.Bytes.Length)) + 8; + var tiff = new TiffBuilder (length).Header (ifds[0].At); + foreach (var (at, entries, next) in ifds) + tiff.Table (at, entries, next); + foreach (var (at, bytes) in raw) + tiff.Bytes (at, bytes); + return tiff.ToArray (); + } + + static byte[] Longs (params long[] values) => [.. values.SelectMany (v => BitConverter.GetBytes ((uint)v))]; + + /// Every case: its name, its bytes, and the size it reports ("none" for no size). + internal static IEnumerable<(string Name, byte[] Tiff, string Size)> Cases () + { + yield return ("IFD0, SHORT", Classic ([(8, [(256, 3, 1, 30), (257, 3, 1, 31)], 0)]), "30x31"); + yield return ("IFD0, LONG 2^31 - 1", Classic ([(8, Size (int.MaxValue, 31), 0)]), "2147483647x31"); + yield return ("IFD0, LONG 2^31 (exiftool: 2147483648x31, past an int)", Classic ([(8, Size (1L << 31, 31), 0)]), "none"); + yield return ("IFD0, width 0 (exiftool: 0x5, no image)", Classic ([(8, Size (0, 5), 0)]), "none"); + yield return ("IFD0, width only", Classic ([(8, [L (256, 30)], 0)]), "none"); + yield return ("IFD0, width with 2 values", Classic ([(8, [(256, 4, 2, 100), L (257, 31)], 0)]), "none"); + yield return ("IFD0, SSHORT and SLONG", Classic ([(8, [(256, 8, 1, 30), (257, 9, 1, 31)], 0)]), "30x31"); + yield return ("IFD0, SSHORT width -1 (exiftool: -1x31, no image)", Classic ([(8, [(256, 8, 1, 0xFFFF), L (257, 31)], 0)]), "none"); + yield return ("IFD0, SLONG width -1 (exiftool: -1x31, no image)", Classic ([(8, [(256, 9, 1, 0xFFFFFFFF), L (257, 31)], 0)]), "none"); + yield return ("IFD0, width RATIONAL", Classic ([(8, [(256, 5, 1, 100), L (257, 31)], 0)]), "none"); + yield return ("an entry with 2^31 values after the size", Classic ([(8, [(256, 3, 1, 3), (257, 3, 1, 2), (0x010E, 2, 1L << 31, 100)], 0)]), "3x2"); + yield return ("IFD0 inside the header", new TiffBuilder (200).Header (2).Table (16, Size (30, 31)).ToArray (), "none"); + yield return ("IFD0's entries past the data", Classic ([(8, Size (30, 31), 0)])[..30], "none"); + // exiftool 13.55: a classic IFD whose next field has 1 or 3 bytes is an illegal directory and is not read. + // 0, 2 or 4 bytes are read. Measured for IFD0 (either endian, including an odd offset), IFD1 and a SubIFD. + foreach (var bigEndian in new[] { false, true }) { + var order = bigEndian ? "BE" : "LE"; + foreach (var present in new[] { 0, 1, 2, 3, 4 }) { + var tiff = new TiffBuilder (64, bigEndian).Header (8).Table (8, Size (64, 48), 0).ToArray (); + yield return ($"IFD0 next field has {present} of 4 bytes, {order}", tiff[..(34 + present)], present is 1 or 3 ? "none" : "64x48"); + } + } + + foreach (var present in new[] { 0, 1, 2, 3, 4 }) { + var odd = new TiffBuilder (64).Header (9).Table (9, Size (64, 48), 0).ToArray (); + yield return ($"IFD0 at an odd offset, next field has {present} of 4 bytes", odd[..(35 + present)], present is 1 or 3 ? "none" : "64x48"); + var ifd1 = Classic ([(8, Image (1, 10, 10), 80), (80, Image (0, 64, 48), 0)]); + yield return ($"IFD1 next field has {present} of 4 bytes", ifd1[..(118 + present)], present is 1 or 3 ? "10x10" : "64x48"); + var sub = Classic ([(8, [.. Image (1, 10, 10), L (330, 80)], 0), (80, Image (0, 64, 48), 0)]); + yield return ($"SubIFD next field has {present} of 4 bytes", sub[..(118 + present)], present is 1 or 3 ? "10x10" : "64x48"); + } + + yield return ("BigTIFF LE, IFD0 next field has 1 of 8 bytes", Big (false, [(16, [(256, 16, 1, 64), (257, 16, 1, 48)], 0)])[..65], "64x48"); + + yield return ("full IFD0", Classic ([(8, [.. Image (0, 5, 5), L (330, 100)], 0), (100, Image (0, 6, 6), 0)]), "5x5"); + yield return ("reduced IFD0, smaller full SubIFD", Classic ([(8, [.. Image (1, 10, 10), L (330, 100)], 0), (100, Image (0, 5, 5), 0)]), "5x5"); + yield return ("reduced IFD0, larger reduced SubIFD", Classic ([(8, [.. Image (1, 5, 5), L (330, 100)], 0), (100, Image (1, 6, 6), 0)]), "5x5"); + yield return ("IFD0 without a subfile type, full SubIFD", Classic ([(8, [.. Size (10, 10), L (330, 100)], 0), (100, Image (0, 30, 30), 0)]), "30x30"); + yield return ("reduced IFD0, SubIFD without a subfile type", Classic ([(8, [.. Image (1, 10, 10), L (330, 100)], 0), (100, Size (30, 30), 0)]), "10x10"); + yield return ("IFD0 without a size, full SubIFD", Classic ([(8, [L (254, 1), L (330, 100)], 0), (100, Image (0, 30, 30), 0)]), "30x30"); + yield return ("two full SubIFDs: the first", Classic ([(8, [.. Image (1, 10, 10), (330, 4, 2, 300)], 0), (100, Image (0, 20, 20), 0), (200, Image (0, 30, 30), 0)], (300, Longs (100, 200))), "20x20"); + yield return ("a full SubIFD of a reduced SubIFD", Classic ([(8, [.. Image (1, 10, 10), L (330, 100)], 0), (100, [.. Image (1, 20, 20), L (330, 200)], 0), (200, Image (0, 30, 30), 0)]), "30x30"); + yield return ("a SubIFD's full next IFD", Classic ([(8, [.. Image (1, 10, 10), L (330, 100)], 0), (100, Image (1, 20, 20), 200), (200, Image (0, 40, 40), 0)]), "40x40"); + yield return ("a full SubIFD before a full IFD1", Classic ([(8, [.. Image (1, 10, 10), L (330, 100)], 200), (100, Image (0, 30, 30), 0), (200, Image (0, 40, 40), 0)]), "30x30"); + yield return ("reduced IFD0, full IFD1", Classic ([(8, Image (1, 10, 10), 100), (100, Image (0, 50, 40), 0)]), "50x40"); + yield return ("reduced IFD0, IFD1 without a subfile type", Classic ([(8, Image (1, 10, 10), 100), (100, Size (50, 40), 0)]), "10x10"); + yield return ("a page IFD0 (subfile type 2), full IFD1", Classic ([(8, Image (2, 10, 10), 100), (100, Image (0, 100, 100), 0)]), "100x100"); + yield return ("subfile type SHORT 0", Classic ([(8, [.. Image (1, 10, 10), L (330, 100)], 0), (100, [(254, 3, 1, 0), L (256, 30), L (257, 30)], 0)]), "30x30"); + yield return ("subfile type with 2 values", Classic ([(8, [.. Image (1, 10, 10), L (330, 100)], 0), (100, [(254, 4, 2, 0), L (256, 30), L (257, 30)], 0)]), "10x10"); + yield return ("SubIFD offset typed SHORT", Classic ([(8, [.. Image (1, 256, 171), (330, 3, 1, 100)], 0), (100, Image (0, 6000, 4000), 0)]), "6000x4000"); + yield return ("SubIFD offset SHORT 40,000, a full image there", Classic ([(8, [.. Image (1, 10, 10), (330, 3, 1, 40000)], 0), (40000, Image (0, 30, 31), 0)]), "30x31"); + yield return ("SubIFD offset typed ASCII", Classic ([(8, [.. Image (1, 256, 171), (330, 2, 1, 100)], 0), (100, Image (0, 6000, 4000), 0)]), "256x171"); + yield return ("full SubIFD without a width (exiftool: 10x30, a width and a height from two IFDs)", Classic ([(8, [.. Image (1, 10, 10), L (330, 100)], 0), (100, [L (254, 0), L (257, 30)], 0)]), "10x10"); + yield return ("full SubIFD whose last width is 0 (exiftool: 0x31; as in exiftool the last width counts, and 0 is no size)", Classic ([(8, [.. Image (1, 10, 10), L (330, 100)], 0), (100, [.. Image (0, 30, 31), L (256, 0)], 0)]), "10x10"); + yield return ("IFD0, height 2^31 - 1", Classic ([(8, Size (31, int.MaxValue), 0)]), "31x2147483647"); + yield return ("IFD0, a second width typed ASCII", Classic ([(8, [L (256, 30), L (257, 31), (256, 2, 4, 0x00303034)], 0)]), "30x31"); + yield return ("IFD0, a second height typed ASCII", Classic ([(8, [L (256, 30), L (257, 31), (257, 2, 4, 0x00303034)], 0)]), "30x31"); + yield return ("subfile type typed ASCII (exiftool: 30x30, it reads the text as a number)", Classic ([(8, [.. Image (1, 10, 10), L (330, 100)], 0), (100, [(254, 2, 1, 0), L (256, 30), L (257, 30)], 0)]), "10x10"); + + yield return ("IFD0 of 4,097 entries", Classic ([(8, [.. Size (77, 55), .. Filler (4095)], 0)]), "77x55"); + yield return ("IFD0 of 65,535 entries, the size last", Classic ([(8, [.. Filler (65533), .. Size (77, 55)], 0)]), "77x55"); + yield return ("a full SubIFD of 5,000 entries", Classic ([(8, [.. Image (1, 10, 10), L (330, 100)], 0), (100, [.. Image (0, 300, 200), .. Filler (4997)], 0)]), "300x200"); + foreach (var (type, name) in new[] { (16, "LONG8"), (17, "SLONG8"), (18, "IFD8") }) + yield return ($"SubIFD offset typed {name} (BigTIFF only)", Classic ([(8, [.. Image (1, 10, 10), (330, type, 1, 100)], 0), (100, Image (0, 30, 31), 0)]), "10x10"); + yield return ("SubIFD offset SBYTE -16, a full image at 240", Classic ([(8, [.. Image (1, 10, 10), (330, 6, 1, 0xF0)], 0), (240, Image (0, 30, 31), 0)]), "10x10"); + yield return ("SubIFD offset SSHORT -16, a full image at 65,520", Classic ([(8, [.. Image (1, 10, 10), (330, 8, 1, 0xFFF0)], 0), (65520, Image (0, 30, 31), 0)]), "10x10"); + yield return ("three LONG SubIFD offsets, the first a full image, the third past the data", Classic ([(8, [.. Image (1, 10, 10), (330, 4, 3, 400)], 0), (200, Image (0, 30, 31), 0), (300, [L (254, 1)], 0)], (400, Longs (200, 300)))[..408], "10x10"); + + foreach (var bigEndian in new[] { false, true }) { + var order = bigEndian ? "BE" : "LE"; + yield return ($"BigTIFF {order}, LONG8", Big (bigEndian, [(16, [(256, 16, 1, 70), (257, 16, 1, 46)], 0)]), "70x46"); + yield return ($"BigTIFF {order}, reduced IFD0, full SubIFD as one LONG8", Big (bigEndian, [(16, [(254, 16, 1, 1), (256, 16, 1, 10), (257, 16, 1, 10), (330, 16, 1, 200)], 0), (200, [(254, 16, 1, 0), (256, 16, 1, 30), (257, 16, 1, 31)], 0)]), "30x31"); + yield return ($"BigTIFF {order}, full SubIFD as one IFD8", Big (bigEndian, [(16, [(254, 16, 1, 1), (256, 16, 1, 10), (257, 16, 1, 10), (330, 18, 1, 200)], 0), (200, [(254, 16, 1, 0), (256, 16, 1, 30), (257, 16, 1, 31)], 0)]), "30x31"); + yield return ($"BigTIFF {order}, SubIFDs as two LONG8 at an offset", Big (bigEndian, [(16, [(254, 16, 1, 1), (256, 16, 1, 10), (257, 16, 1, 10), (330, 16, 2, 400)], 0), (200, [(254, 16, 1, 1)], 0), (300, [(254, 16, 1, 0), (256, 16, 1, 30), (257, 16, 1, 31)], 0)], (400, 200, 8), (408, 300, 8)), "30x31"); + yield return ($"BigTIFF {order}, SubIFDs as two LONG8 ending at the data's end", Big (bigEndian, [(16, [(254, 16, 1, 1), (256, 16, 1, 10), (257, 16, 1, 10), (330, 16, 2, 400)], 0), (200, [(254, 16, 1, 1)], 0), (300, [(254, 16, 1, 0), (256, 16, 1, 30), (257, 16, 1, 31)], 0)], (400, 200, 8), (408, 300, 8))[..416], "30x31"); + yield return ($"BigTIFF {order}, SubIFDs at an offset above 2^63 - 1", Big (bigEndian, [(16, [(254, 16, 1, 1), (256, 16, 1, 10), (257, 16, 1, 10), (330, 16, 2, -1)], 0)]), "10x10"); + yield return ($"BigTIFF {order}, a SubIFD array past the data", Big (bigEndian, [(16, [(254, 16, 1, 1), (256, 16, 1, 10), (257, 16, 1, 10), (330, 16, 2, 4000)], 0)]), "10x10"); + yield return ($"BigTIFF {order}, LONG8 width 2^31 (exiftool: 2147483648x46, past an int)", Big (bigEndian, [(16, [(256, 16, 1, 1L << 31), (257, 16, 1, 46)], 0)]), "none"); + foreach (var (type, name, size) in new[] { (1, "BYTE", 1), (6, "SBYTE", 1), (3, "SHORT", 2), (8, "SSHORT", 2), (4, "LONG", 4), (9, "SLONG", 4), (13, "IFD", 4), (16, "LONG8", 8), (17, "SLONG8", 8), (18, "IFD8", 8) }) + yield return ($"BigTIFF {order}, SubIFD typed {name}", Big (bigEndian, [(16, [.. BigReduced, (330, type, 1, InEntry (120, size, bigEndian))], 0), (120, BigFull, 0)]), "30x31"); + foreach (var (type, name) in new[] { (7, "UNDEFINED"), (2, "ASCII"), (5, "RATIONAL"), (10, "SRATIONAL"), (11, "FLOAT"), (12, "DOUBLE") }) + yield return ($"BigTIFF {order}, SubIFD typed {name} (exiftool reads none)", Big (bigEndian, [(16, [.. BigReduced, (330, type, 1, InEntry (120, 1, bigEndian))], 0), (120, BigFull, 0)]), "10x10"); + yield return ($"BigTIFF {order}, SubIFD SBYTE -16, a full image at 240", Big (bigEndian, [(16, [.. BigReduced, (330, 6, 1, InEntry (0xF0, 1, bigEndian))], 0), (240, BigFull, 0)]), "10x10"); + yield return ($"BigTIFF {order}, SubIFD BYTE 240, a full image there", Big (bigEndian, [(16, [.. BigReduced, (330, 1, 1, InEntry (0xF0, 1, bigEndian))], 0), (240, BigFull, 0)]), "30x31"); + yield return ($"BigTIFF {order}, SubIFD SSHORT -16, a full image at 65,520", Big (bigEndian, [(16, [.. BigReduced, (330, 8, 1, InEntry (0xFFF0, 2, bigEndian))], 0), (65520, BigFull, 0)]), "10x10"); + yield return ($"BigTIFF {order}, SubIFD BYTE count 0", Big (bigEndian, [(16, [.. BigReduced, (330, 1, 0, InEntry (120, 1, bigEndian))], 0), (120, BigFull, 0)]), "10x10"); + yield return ($"BigTIFF {order}, two BYTE SubIFD offsets in the entry", Big (bigEndian, [(16, [.. BigReduced, (330, 1, 2, InEntry (120, 1, bigEndian))], 0), (120, BigFull, 0)]), "30x31"); + yield return ($"BigTIFF {order}, three LONG8 SubIFD offsets, the first a full image, the third past the data", Big (bigEndian, [(16, [.. BigReduced, (330, 16, 3, 400)], 0), (200, BigFull, 0), (300, [(254, 16, 1, 1)], 0)], (400, 200, 8), (408, 300, 8))[..416], "10x10"); + yield return ($"BigTIFF {order}, three LONG SubIFD offsets, the first a full image, the third past the data", Big (bigEndian, [(16, [.. BigReduced, (330, 4, 3, 400)], 0), (200, BigFull, 0), (300, [(254, 16, 1, 1)], 0)], (400, 200, 4), (404, 300, 4))[..408], "10x10"); + yield return ($"BigTIFF {order}, IFD0 of 4,097 entries", Big (bigEndian, [(16, [(256, 16, 1, 77), (257, 16, 1, 55), .. Filler (4095)], 0)]), "77x55"); + yield return ($"BigTIFF {order}, reduced IFD0, a next IFD above 2^63 - 1", Big (bigEndian, [(16, [(254, 16, 1, 1), (256, 16, 1, 10), (257, 16, 1, 10)], -1)]), "10x10"); + } + + yield return ("BigTIFF LE, SHORT", Big (false, [(16, [(256, 3, 1, 70), (257, 3, 1, 46)], 0)]), "70x46"); + yield return ("BigTIFF LE, LONG with two SubIFDs in the entry", Big (false, [(16, [(254, 16, 1, 1), (256, 16, 1, 10), (257, 16, 1, 10), (330, 4, 2, 200L | (300L << 32))], 0), (200, [(254, 16, 1, 1)], 0), (300, [(254, 16, 1, 0), (256, 16, 1, 30), (257, 16, 1, 31)], 0)]), "30x31"); + yield return ("BigTIFF LE, SubIFD typed SHORT", Big (false, [(16, [(254, 16, 1, 1), (256, 16, 1, 10), (257, 16, 1, 10), (330, 3, 1, 200)], 0), (200, [(254, 16, 1, 0), (256, 16, 1, 30), (257, 16, 1, 31)], 0)]), "30x31"); + yield return ("BigTIFF LE, SubIFD typed ASCII", Big (false, [(16, [(254, 16, 1, 1), (256, 16, 1, 10), (257, 16, 1, 10), (330, 2, 1, 200)], 0), (200, [(254, 16, 1, 0), (256, 16, 1, 30), (257, 16, 1, 31)], 0)]), "10x10"); + yield return ("BigTIFF LE, a width whose value count is above 2^63 - 1", Big (false, [(16, [(256, 16, -1, 70), (257, 16, 1, 46)], 0)]), "none"); + yield return ("BigTIFF LE, LONG8 width 2^32 + 5 (exiftool: 4294967301x46, past an int)", Big (false, [(16, [(256, 16, 1, (1L << 32) + 5), (257, 16, 1, 46)], 0)]), "none"); + yield return ("BigTIFF LE, three LONG SubIFD offsets, the third past the data", new TiffBuilder (168, big: true).Header (16) + .Table (16, [(254, 16, 1, 1), (256, 16, 1, 10), (257, 16, 1, 10), (330, 4, 3, 160)]).Table (120, [(254, 16, 1, 1)]) + .U32 (160, 120).U32 (164, 120).ToArray (), "10x10"); + yield return ("BigTIFF LE, a SubIFD count of 1 then bytes that read as a full IFD's offset", Big (false, [(16, [(254, 16, 1, 1), (256, 16, 1, 10), (257, 16, 1, 10), (330, 16, 1, 200), (500, 0, 0, 0)], 0), (200, [(254, 16, 1, 1)], 0), (500, Image (0, 30, 31), 0)]), "10x10"); + yield return ("BigTIFF LE, LONG8 width above 2^63 - 1 (exiftool: 18446744073709551615x46, past an int)", Big (false, [(16, [(256, 16, 1, -1), (257, 16, 1, 46)], 0)]), "none"); + yield return ("BigTIFF, offset size 4", Big (false, [(16, Size (70, 46), 0)]).Patch (4, 4), "none"); + yield return ("BigTIFF, reserved 1", Big (false, [(16, Size (70, 46), 0)]).Patch (6, 1), "none"); + yield return ("BigTIFF header only", Big (false, [(16, [], 0)])[..16], "none"); + yield return ("BigTIFF, an IFD0 count above 2^63 - 1 before a full IFD's offset", Big (false, [(16, [], 0), (100, Image (0, 70, 46), 0)], (16, -1, 8), (24, 100, 8)), "none"); + } + + // A chain of nested SubIFDs below a reduced IFD0, each the only SubIFD of the one above; only the deepest is full. + static byte[] Nested (int depth) + { + var ifds = new List<(int At, (int, int, long, long)[] Entries, long Next)> (); + for (var d = 0; d <= depth; d++) { + var at = 8 + (d * 64); + ifds.Add ((at, d == depth ? Image (0, 900, 600) : [.. Image (1, 2, 2), L (330, at + 64)], 0)); + } + + return Classic ([.. ifds]); + } + + // The walk reads SubIFDs 64 levels below IFD0 and no deeper (exiftool reads deeper; this is the walk's bound). + [TestMethod] + [DataRow (64, 900)] + [DataRow (65, 2)] + public void Tiff_FullImage_IsFoundDownToTheDepthBound (int depth, int width) + { + Assert.IsTrue (TiffSize.TryRead (Nested (depth), dng: false, out var properties)); + Assert.AreEqual (width, properties!.Value.Width); + } + + // 20 SubIFDs of a reduced IFD0, all reduced but the last: more offsets wait than the stack span holds, and the one + // pushed first, at the bottom, is the full image. + [TestMethod] + public void Tiff_FullImage_AfterMoreSubIfdsThanTheStackSpanHolds_IsFound () + { + var subs = Enumerable.Range (0, 20).Select (n => (long)(400 + (n * 64))).ToArray (); + var ifds = new List<(int At, (int, int, long, long)[] Entries, long Next)> { (8, [.. Image (1, 2, 2), (330, 4, 20, 200)], 0) }; + for (var n = 0; n < 20; n++) + ifds.Add (((int)subs[n], n == 19 ? Image (0, 900, 600) : Image (1, 3, 3), 0)); + var tiff = Classic ([.. ifds], (200, Longs (subs))); + + Assert.IsTrue (TiffSize.TryRead (tiff, dng: false, out var properties)); + Assert.AreEqual (900, properties!.Value.Width); + } + + // A chain of 20 reduced IFDs whose last names IFD0 again: past the 16 offsets kept on the stack the walk still + // knows IFD0, so it reads each IFD once and stops. + [TestMethod] + public void Tiff_ChainBackToIfd0AfterSixteenIfds_IsReadOnce () + { + var ifds = Enumerable.Range (0, 20).Select (n => (8 + (n * 64), Image (1, 2 + n, 2), n == 19 ? 8L : 8 + ((n + 1) * 64))).ToArray (); + var tiff = Classic (ifds); + TiffSize.IfdReads = 0; + + Assert.IsTrue (TiffSize.TryRead (tiff, dng: false, out var properties)); + + Assert.AreEqual (2, properties!.Value.Width, "no full image: IFD0's size"); + Assert.AreEqual (20, TiffSize.IfdReads, "each of the 20 once, IFD0 included"); + } + + // The walk reads at most 4,096 IFDs: a full image that is the 4,096th IFD read is found, the 4,097th is not. + // IFD0 (reduced) has a reduced SubIFD whose next offset is 0, the end of its chain, which takes no part in the + // bound; then IFD0's chain of empty IFDs ends in the full image. + [TestMethod] + [DataRow (4096, 900)] + [DataRow (4097, 2)] + public void Tiff_FullImage_IsFoundUpToTheIfdBound (int position, int width) + { + const int Ifd0 = 8, Sub = Ifd0 + 2 + (4 * 12) + 4, Chain = Sub + 2 + (3 * 12) + 4; + var ifds = new List<(int At, (int, int, long, long)[] Entries, long Next)> { + (Ifd0, [.. Image (1, 2, 2), L (330, Sub)], Chain), + (Sub, Image (1, 3, 3), 0), + }; + var at = Chain; + for (var n = 3; n < position; n++, at += 6) + ifds.Add ((at, [], at + 6)); + ifds.Add ((at, Image (0, 900, 600), 0)); + + Assert.IsTrue (TiffSize.TryRead (Classic ([.. ifds]), dng: false, out var properties)); + Assert.AreEqual (width, properties!.Value.Width); + } + + // A reduced TIFF of up to 16 IFDs is walked on the stack: reading its size allocates nothing. Past 16 the visited + // set is sized by the IFDs the data can hold (6 bytes each), not by the bound of 4,096. + [TestMethod] + public void Tiff_SizeWalk_AllocatesNothingUpToSixteenIfds_AndByTheDataPast () + { + static byte[] Chain (int ifds) => Classic ([.. Enumerable.Range (0, ifds).Select (n => (8 + (n * 64), Image (1, 2 + n, 2), n == ifds - 1 ? 0L : 8 + ((n + 1) * 64)))]); + var small = Chain (16); + var large = Chain (20); + _ = TiffSize.TryRead (small, dng: false, out _); + _ = TiffSize.TryRead (large, dng: false, out _); + + TagLibSharp2.Tests.Kit.Bounds.AssertAllocatesAtMost (0, () => TiffSize.TryRead (small, dng: false, out _)); + TagLibSharp2.Tests.Kit.Bounds.AssertAllocatesAtMost (large.Length * 8, () => TiffSize.TryRead (large, dng: false, out _)); + } + + // DNG is TIFF whose IFD0 holds the DNG version tag, or a TIFF named .dng; the tag in a SubIFD alone is not DNG. + [TestMethod] + [DataRow ("IFD0", false, "DNG")] + [DataRow ("SubIFD", false, "TIFF")] + [DataRow ("none", true, "DNG")] + public void Tiff_IsDng_ByIfd0sVersionTagOrTheName (string where, bool named, string format) + { + (int, int, long, long)[] dng = [(0xC612, 1, 4, 0x00000401)]; + var tiff = Classic ([(8, [.. Image (1, 2, 2), L (330, 100), .. where == "IFD0" ? dng : []], 0), (100, [.. Image (0, 30, 31), .. where == "SubIFD" ? dng : []], 0)]); + + Assert.IsTrue (TiffSize.TryRead (tiff, named, out var properties)); + Assert.AreEqual (format, properties!.Value.Format); + Assert.AreEqual (where == "IFD0", TiffSize.HasDngVersion (tiff)); + } + + // Entries of a tag no reader knows, to make a table large. + static (int, int, long, long)[] Filler (int count) => [.. Enumerable.Repeat ((0xEEEE, 3, 1L, 0L), count)]; + + static readonly (int, int, long, long)[] BigReduced = [(254, 16, 1, 1), (256, 16, 1, 10), (257, 16, 1, 10)]; + static readonly (int, int, long, long)[] BigFull = [(254, 16, 1, 0), (256, 16, 1, 30), (257, 16, 1, 31)]; + + // A value of the given size at the start of a BigTIFF entry's 8-byte field, as the builder writes the field as + // one 8-byte word in the file's byte order. + static long InEntry (long value, int size, bool bigEndian) => bigEndian ? value << (8 * (8 - size)) : value; + + // BigTIFF, IFD0 first; raw 8-byte words (at, value, size) after the tables. + static byte[] Big (bool bigEndian, (int At, (int, int, long, long)[] Entries, long Next)[] ifds, params (int At, long Value, int Size)[] words) + { + var length = Math.Max (ifds.Max (i => i.At + 8 + (20 * i.Entries.Length) + 8), words.Length == 0 ? 0 : words.Max (w => w.At + w.Size)) + 8; + var tiff = new TiffBuilder (length, bigEndian, big: true).Header (ifds[0].At); + foreach (var (at, entries, next) in ifds) + tiff.Table (at, entries, next); + foreach (var (at, value, size) in words) { + if (size == 4) + tiff.U32 (at, value); + else + tiff.U64 (at, value); + } + return tiff.ToArray (); + } + + [TestMethod] + public void Tiff_ReportsTheSizeExiftoolReports () + { + var wrong = new List (); + foreach (var (name, tiff, size) in Cases ()) { + var got = TiffSize.TryRead (tiff, dng: false, out var properties) ? $"{properties!.Value.Width}x{properties.Value.Height}" : "none"; + if (got != size) + wrong.Add ($"{name}: {got}, expected {size}"); + } + + Assert.AreEqual (0, wrong.Count, string.Join ("\n", wrong)); + } +} + +static class TiffBytes +{ + /// The bytes with one byte changed. + public static byte[] Patch (this byte[] data, int at, byte value) + { + var copy = (byte[])data.Clone (); + copy[at] = value; + return copy; + } +} diff --git a/tests/TagLibSharp2.Tests/Image/TiffSizeTests.cs b/tests/TagLibSharp2.Tests/Image/TiffSizeTests.cs new file mode 100644 index 00000000..5eb6ec6c --- /dev/null +++ b/tests/TagLibSharp2.Tests/Image/TiffSizeTests.cs @@ -0,0 +1,403 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Buffers.Binary; +using System.Text; +using TagLibSharp2.Core; +using TagLibSharp2.Image; +using TagLibSharp2.Image.Tiff; +using TagLibSharp2.Tests.Core; +using TagLibSharp2.Tests.Kit; +using static TagLibSharp2.Tests.Image.ImageAssert; +using static TagLibSharp2.Tests.Image.ImageTestBuilder; + +namespace TagLibSharp2.Tests.Image; + +/// TIFF, DNG and BigTIFF width and height: IFD0, the reduced-preview rule, and the bounds of the IFD walk. +[TestClass] +[TestCategory ("Unit")] +public partial class TiffSizeTests +{ + // A TIFF whose only IFD has no next-IFD offset, or only 2 of its 4 bytes: exiftool reads ImageWidth 3 and + // ImageHeight 2 from it, so the file opens with those dimensions. + [TestMethod] + [DataRow (4)] + [DataRow (2)] + public void Tiff_WhoseIfdHasNoNextOffset_ReportsItsSize (int cut) + { + byte[] tiff = [ + (byte)'I', (byte)'I', 42, 0, 8, 0, 0, 0, + 2, 0, + 0x00, 0x01, 3, 0, 1, 0, 0, 0, 3, 0, 0, 0, + 0x01, 0x01, 3, 0, 1, 0, 0, 0, 2, 0, 0, 0, + 0, 0, 0, 0]; + + var file = Open (tiff[..^cut], "a.tif"); + + Assert.AreEqual (3, file.ImageProperties!.Value.Width); + Assert.AreEqual (2, file.ImageProperties!.Value.Height); + } + + // A classic IFD0 whose next-IFD field has 1 or 3 of its 4 bytes is not read, so the file has no size. The header + // is still TIFF. The open failure names that cut. 0, 2 and 4 bytes still open. BigTIFF is unaffected. + [TestMethod] + [DataRow (false, 1, 8)] + [DataRow (false, 3, 8)] + [DataRow (true, 1, 8)] + [DataRow (true, 3, 8)] + [DataRow (false, 1, 9)] + [DataRow (false, 3, 9)] + public void Tiff_WhoseIfd0NextFieldIsCutShort_NamesTheCutAndStaysClosed (bool bigEndian, int present, int ifd0) + { + var nextAt = ifd0 + 2 + (2 * 12); + var full = new TiffBuilder (nextAt + 4, bigEndian).Header (ifd0).Table (ifd0, [(256, 4, 1, 64), (257, 4, 1, 48)], 0).ToArray (); + var cut = full.AsSpan (0, nextAt + present).ToArray (); + var expected = $"IFD0's next-IFD field has {present} of its 4 bytes, so IFD0 is not read and the image has no size."; + + var opened = StillImageFile.Read (cut); + Assert.IsNull (opened.File); + Assert.AreEqual (expected, opened.Error); + + var tiff = MediaFile.ReadFromData (cut, "photo.tif"); + Assert.IsNull (tiff.File); + Assert.AreEqual (expected, tiff.Error); + + var dng = MediaFile.ReadFromData (cut, "photo.dng"); + Assert.IsNull (dng.File); + Assert.AreEqual (expected, dng.Error); + } + + [TestMethod] + [DataRow (0)] + [DataRow (2)] + [DataRow (4)] + public void Tiff_WhoseIfd0NextFieldHasAnEvenShare_Opens (int present) + { + var nextAt = 34; + var full = new TiffBuilder (nextAt + 4).Header (8).Table (8, [(256, 4, 1, 64), (257, 4, 1, 48)], 0).ToArray (); + var cut = full.AsSpan (0, nextAt + present).ToArray (); + var opened = StillImageFile.Read (cut); + Assert.IsTrue (opened.IsSuccess, opened.Error); + Assert.AreEqual (64, opened.File!.ImageProperties!.Value.Width); + Assert.AreEqual (48, opened.File.ImageProperties!.Value.Height); + } + + [TestMethod] + public void BigTiff_WhoseNextFieldHasOneByte_StillOpens () + { + var opened = StillImageFile.Read (BigTiff (64, 48, littleEndian: true).AsSpan (0, 65).ToArray ()); + Assert.IsTrue (opened.IsSuccess, opened.Error); + Assert.AreEqual (64, opened.File!.ImageProperties!.Value.Width); + Assert.AreEqual (48, opened.File.ImageProperties!.Value.Height); + } + + [TestMethod] + public void Tiff_WhoseSizeIsNotAPositiveInt_SaysItIsNotATiffImage () + { + AssertClosedAsNotTiff (TiffImage (0, 5)); + AssertClosedAsNotTiff (new TiffBuilder (64).Header (8).Table (8, [(256, 9, 1, 0xFFFFFFFF), (257, 4, 1, 31)], 0).ToArray ()); + AssertClosedAsNotTiff (new TiffBuilder (64).Header (8).Table (8, [(256, 4, 1, 1L << 31), (257, 4, 1, 31)], 0).ToArray ()); + } + + static void AssertClosedAsNotTiff (byte[] tiff) + { + var opened = StillImageFile.Read (tiff); + Assert.IsNull (opened.File); + Assert.AreEqual ("Not a Tiff image", opened.Error); + } + + [TestMethod] + public void Tiff_ReducedPreview_YieldsToTheFullResolutionImage () + { + var dng = PreviewIfd (dng: true, fullWidth: 6000, fullHeight: 4000); + AssertSize (dng, "a.dng", 6000, 4000); + Assert.AreEqual ("DNG", ((IMediaFile)MediaFile.ReadFromData (dng, "a.dng").File!).ImageProperties!.Value.Format); + + var tiff = PreviewIfd (dng: false, fullWidth: 6000, fullHeight: 4000); + AssertSize (tiff, "a.tif", 6000, 4000); + Assert.AreEqual ("TIFF", ((IMediaFile)MediaFile.ReadFromData (tiff, "a.tif").File!).ImageProperties!.Value.Format); + + var firstPage = LinkedTiff (); + AssertSize (firstPage, "a.tif", 10, 10); + + var cycle = CyclicSubIfd (); + AssertSize (cycle, "a.tif", 4, 5); + } + + [TestMethod] + public void BigTiff_ReportsIfd0Size () + { + AssertSize (BigTiff (70, 46, littleEndian: true), "a.tif", 70, 46); + } + + // A reduced preview IFD0 (NewSubfileType 1, 256x171) whose SubIFD is the full-resolution image. + static byte[] PreviewIfd (bool dng, int fullWidth, int fullHeight) + { + (int, int, long, long)[] root = [(254, 4, 1, 1), (256, 4, 1, 256), (257, 4, 1, 171), (330, 4, 1, 0)]; + if (dng) + root = [.. root, (0xC612, 4, 1, 1)]; + var sub = 8 + 2 + (root.Length * 12) + 4; + root[3] = (330, 4, 1, sub); + return new TiffBuilder (sub + 2 + (3 * 12) + 4).Header (8).Table (8, root) + .Table (sub, [(254, 4, 1, 0), (256, 4, 1, fullWidth), (257, 4, 1, fullHeight)]).ToArray (); + } + + // IFD0 (10x10) and IFD1 (100x100) linked by IFD0's next offset. + static byte[] LinkedTiff () => + new TiffBuilder (8 + 30 + 30).Header (8).Table (8, [(256, 4, 1, 10), (257, 4, 1, 10)], next: 38) + .Table (38, [(256, 4, 1, 100), (257, 4, 1, 100)]).ToArray (); + + // A reduced IFD0 whose SubIFD is IFD0 itself. + static byte[] CyclicSubIfd () => + new TiffBuilder (8 + 2 + (4 * 12) + 4).Header (8).Table (8, [(254, 4, 1, 1), (256, 4, 1, 4), (257, 4, 1, 5), (330, 4, 1, 8)]).ToArray (); + + [TestMethod] + public void Tiff_DetectionOfAReducedImageOrDng_AllocatesNoScratch () + { + var reduced = Tiff ((254, 1), (256, 4), (257, 3)); + var dng = TiffChain ([[(254, 1), (256, 4), (257, 3), (330, 8 + 2 + (5 * 12) + 4), (0xC612, 1)], [(254, 0), (256, 400), (257, 300)]]); + foreach (var data in new[] { reduced, dng }) { + _ = MediaFile.DetectFormat (data); + Bounds.AssertAllocatesAtMost (Noise, () => MediaFile.DetectFormat (data)); + } + + Assert.AreEqual (MediaFormat.Dng, MediaFile.DetectFormat (dng)); + } + + static int IfdReads (byte[] tiff) + { + TiffSize.IfdReads = 0; + _ = ImageHeader.TryRead (tiff, MediaFormat.Tiff, out _); + return TiffSize.IfdReads; + } + + // A reduced IFD0 followed by N IFDs, the last of them without its next-IFD offset: the size walk reads each IFD + // once, so the reads grow linearly, as does the allocation. + [TestMethod] + [DoNotParallelize] + public void Tiff_IfdChainEndingWithoutANextOffset_IsReadLinearly () + { + static byte[] Chain (int n) + { + var tiff = TiffChain ([[(254, 1), (256, 2), (257, 2)], .. Enumerable.Range (0, n).Select (k => new[] { (254, 1), (256, 3 + k), (257, 3) })]); + return tiff[..^4]; + } + + var small = IfdReads (Chain (50)); + var large = IfdReads (Chain (200)); + Assert.IsTrue (large <= 201 + 1, $"{large} IFD reads for 201 IFDs"); + Assert.IsTrue (large < 5 * small, $"4x the IFDs took {large / (double)small:F1}x the reads"); + Bounds.AssertLinearAllocation (Chain, data => ImageHeader.TryRead (data, MediaFormat.Tiff, out _), 50, runs: 3); + } + + [TestMethod] + public void Tiff_CyclicIfds_AreReadOnce () + { + // IFD0 is a reduced image whose SubIFD and next IFD are itself. + var cycle = Tiff ((254, 1), (256, 4), (257, 5), (330, 8)); + BitConverter.GetBytes (8).CopyTo (cycle, cycle.Length - 4); + Assert.IsTrue (IfdReads (cycle) <= 2, $"{IfdReads (cycle)} IFD reads"); + + // A SubIFD that names itself as its next IFD comes before the full-resolution SubIFD. + var loopFirst = SubIfdTree (out var full); + var opened = MediaFile.ReadFromData (loopFirst, "a.tif"); + Assert.AreEqual (full, ((IMediaFile)opened.File!).ImageProperties!.Value.Width, "the full-resolution SubIFD after the loop is reached"); + Assert.IsTrue (IfdReads (loopFirst) <= 4, $"{IfdReads (loopFirst)} IFD reads"); + } + + // IFD0 (reduced, 2x2) with SubIFDs [A, B]. A has no size and its next IFD is A. B is 900x600, not reduced. + static byte[] SubIfdTree (out int fullWidth) + { + fullWidth = 900; + const int Ifd0 = 8; + const int Ifd0Size = 2 + (4 * 12) + 4; + const int Subs = Ifd0 + Ifd0Size; + const int A = Subs + 8; + const int ASize = 2 + 4; + const int B = A + ASize; + var data = new byte[B + 2 + (3 * 12) + 4]; + data[0] = (byte)'I'; + data[1] = (byte)'I'; + data[2] = 42; + BitConverter.GetBytes (Ifd0).CopyTo (data, 4); + BitConverter.GetBytes ((ushort)4).CopyTo (data, Ifd0); + WriteLong (data, Ifd0 + 2, 254, 1); + WriteLong (data, Ifd0 + 14, 256, 2); + WriteLong (data, Ifd0 + 26, 257, 2); + WriteLong (data, Ifd0 + 38, 330, Subs); + BitConverter.GetBytes (2).CopyTo (data, Ifd0 + 42); + BitConverter.GetBytes (A).CopyTo (data, Subs); + BitConverter.GetBytes (B).CopyTo (data, Subs + 4); + BitConverter.GetBytes (A).CopyTo (data, A + 2); + BitConverter.GetBytes ((ushort)3).CopyTo (data, B); + WriteLong (data, B + 2, 254, 0); + WriteLong (data, B + 14, 256, fullWidth); + WriteLong (data, B + 26, 257, 600); + return data; + } + + [TestMethod] + public void Tiff_IfdWalk_StopsAtTheIfdCap () + { + // 5000 linked IFDs after a reduced IFD0. The last one is the full-resolution image. + var ifds = new List<(int, int)[]> { new[] { (254, 1), (256, 2), (257, 2) } }; + for (var n = 0; n < 4998; n++) + ifds.Add ([]); + ifds.Add ([(254, 0), (256, 900), (257, 600)]); + var chain = TiffChain (ifds); + + var reads = IfdReads (chain); + + Assert.IsTrue (reads <= 4097, $"{reads} IFD reads"); + Assert.AreEqual (2, ((IMediaFile)MediaFile.ReadFromData (chain, "a.tif").File!).ImageProperties!.Value.Width, "IFDs past the cap are not read"); + } + + [TestMethod] + public void Tiff_SubIfdNesting_StopsAtTheDepthCap () + { + // IFD0 (reduced 2x2) -> SubIFD -> SubIFD ... 80 deep; only the deepest is a full-resolution image. + const int Depth = 80; + var ifds = new List<(int Tag, int Value)[]> (); + var offsets = new int[Depth + 1]; + offsets[0] = 8; + for (var d = 0; d <= Depth; d++) { + var count = d == 0 ? 4 : d == Depth ? 3 : 2; + if (d < Depth) + offsets[d + 1] = offsets[d] + 2 + (12 * count) + 4; + } + + for (var d = 0; d <= Depth; d++) { + ifds.Add (d == 0 ? [(254, 1), (256, 2), (257, 2), (330, offsets[1])] + : d == Depth ? [(254, 0), (256, 900), (257, 600)] + : [(254, 1), (330, offsets[d + 1])]); + } + + var data = TiffChain (ifds); + for (var d = 0; d <= Depth; d++) + BitConverter.GetBytes (0).CopyTo (data, offsets[d] + 2 + (12 * ifds[d].Length)); + + var reads = IfdReads (data); + + Assert.IsTrue (reads <= 67, $"{reads} IFD reads"); + Assert.AreEqual (2, ((IMediaFile)MediaFile.ReadFromData (data, "a.tif").File!).ImageProperties!.Value.Width, "SubIFDs deeper than the cap are not read"); + } + + [TestMethod] + public void Tiff_MoreSubIfdsThanAreFollowed_StillReadsTheFirstOnes () + { + // IFD0 (reduced) lists 40 SubIFDs; the first is the full-resolution image. + const int Ifd0Size = 2 + (4 * 12) + 4; + const int Array = 8 + Ifd0Size; + const int Full = Array + (40 * 4); + var data = new byte[Full + 2 + (3 * 12) + 4]; + data[0] = (byte)'I'; + data[1] = (byte)'I'; + data[2] = 42; + BitConverter.GetBytes (8).CopyTo (data, 4); + BitConverter.GetBytes ((ushort)4).CopyTo (data, 8); + WriteLong (data, 10, 254, 1); + WriteLong (data, 22, 256, 2); + WriteLong (data, 34, 257, 2); + WriteLong (data, 46, 330, Array); + BitConverter.GetBytes (40).CopyTo (data, 50); + for (var n = 0; n < 40; n++) + BitConverter.GetBytes (Full).CopyTo (data, Array + (4 * n)); + BitConverter.GetBytes ((ushort)3).CopyTo (data, Full); + WriteLong (data, Full + 2, 254, 0); + WriteLong (data, Full + 14, 256, 900); + WriteLong (data, Full + 26, 257, 600); + + Assert.AreEqual (900, ((IMediaFile)MediaFile.ReadFromData (data, "a.tif").File!).ImageProperties!.Value.Width); + } + + [TestMethod] + public void Tiff_ManyOverlappingSubIfds_AreBoundedByTheIfdCap () + { + // 4500 IFDs at distinct offsets, each listing 32 of the others as SubIFDs. + const int Count = 4500; + const int Size = 2 + 12 + 4; + var arrayAt = 8 + (Count * Size); + var data = new byte[arrayAt + (Count * 32 * 4)]; + data[0] = (byte)'I'; + data[1] = (byte)'I'; + data[2] = 42; + BitConverter.GetBytes (8).CopyTo (data, 4); + for (var n = 0; n < Count; n++) { + var at = 8 + (n * Size); + BitConverter.GetBytes ((ushort)1).CopyTo (data, at); + var list = arrayAt + (n * 32 * 4); + WriteLong (data, at + 2, 330, list); + BitConverter.GetBytes (32).CopyTo (data, at + 6); + for (var s = 0; s < 32; s++) + BitConverter.GetBytes (8 + ((((n * 31) + s + 1) % Count) * Size)).CopyTo (data, list + (4 * s)); + } + + // IFD0 must be reduced to start the walk: replace its single SubIFD entry with NewSubFileType and keep the + // SubIFD list by pointing the next-IFD at IFD 1. + WriteLong (data, 10, 254, 1); + BitConverter.GetBytes (8 + Size).CopyTo (data, 8 + 2 + 12); + + var reads = IfdReads (data); + Assert.IsTrue (reads <= 4097, $"{reads} IFD reads"); + Bounds.AssertAllocatesAtMost (512 * 1024, () => ImageHeader.TryRead (data, MediaFormat.Tiff, out _)); + } + + // K tables at distinct offsets 4 bytes apart, each with 1,000 entries that overlap the next table's, reached + // through a chain of IFDs whose SubIFD arrays list 32 of them each. Tables that do not overlap hold at most one + // entry per 12 bytes, so a walk that reads more than that has met tables that overlap: the entries the size walk + // reads stay within the data's bound, at K and 4K tables alike, instead of K x 1,000. + static byte[] OverlappingTables (int tables) + { + const int Entries = 1000; + var chain = tables / 32; + const int ChainAt = 8, ChainSize = 2 + 12 + 4; + var arraysAt = ChainAt + (chain * ChainSize); + var regionAt = arraysAt + (chain * 32 * 4); + var tiff = new TiffBuilder (regionAt + (4 * tables) + 2 + (12 * Entries) + 8).Header (ChainAt); + for (var j = 0; j < chain; j++) { + var at = ChainAt + (j * ChainSize); + tiff.Table (at, [(330, 4, 32, arraysAt + (j * 128))], j == chain - 1 ? 0 : at + ChainSize); + for (var s = 0; s < 32; s++) + tiff.U32 (arraysAt + (j * 128) + (4 * s), regionAt + (4 * ((32 * j) + s))); + } + + for (var i = 0; i < tables; i++) + tiff.U16 (regionAt + (4 * i), Entries); + return tiff.ToArray (); + } + + [TestMethod] + [DataRow (512)] + [DataRow (2048)] + public void Tiff_OverlappingTables_AreReadWithinTheEntryBoundOfTheData (int tables) + { + var data = OverlappingTables (tables); + TiffSize.EntryReads = 0; + + _ = TiffSize.TryRead (data, dng: false, out _); + + Console.WriteLine ($"STEPS overlapping tables {tables}: {TiffSize.EntryReads} entries for {data.Length} bytes"); + Assert.IsTrue (TiffSize.EntryReads <= data.Length / 12, $"{TiffSize.EntryReads} entries read from {data.Length} bytes"); + Assert.IsTrue (TiffSize.EntryReads >= 1000, $"{TiffSize.EntryReads} entries read: the first table, within the bound, is read whole"); + } + + [TestMethod] + [DoNotParallelize] + public void Tiff_OverlappingTables_AllocateLinearly () => + Bounds.AssertLinearAllocation (OverlappingTables, data => TiffSize.TryRead (data, dng: false, out _), 512, runs: 3); + + [TestMethod] + public void Read_Tiff_ReportsIfdSize () + { + AssertImage (TiffImage (width: 64, height: 48, littleEndian: true), "photo.tif", MediaFormat.Tiff, 64, 48, "TIFF"); + AssertImage (TiffImage (width: 20, height: 10, littleEndian: false), "photo.tiff", MediaFormat.Tiff, 20, 10, "TIFF"); + } + + [TestMethod] + public void Read_Dng_IsTiffWithTheDngVersionTag () + { + AssertImage (TiffImage (width: 32, height: 16, littleEndian: true, dng: true), "photo.dng", MediaFormat.Dng, 32, 16, "DNG"); + AssertImage (TiffImage (width: 32, height: 16, littleEndian: true, dng: true), "photo.tif", MediaFormat.Dng, 32, 16, "DNG"); + AssertImage (TiffImage (width: 32, height: 16, littleEndian: true), "photo.dng", MediaFormat.Dng, 32, 16, "DNG"); + } +} diff --git a/tests/TagLibSharp2.Tests/Image/TiffValueArrayTests.cs b/tests/TagLibSharp2.Tests/Image/TiffValueArrayTests.cs new file mode 100644 index 00000000..8658c498 --- /dev/null +++ b/tests/TagLibSharp2.Tests/Image/TiffValueArrayTests.cs @@ -0,0 +1,88 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using TagLibSharp2.Image.Exif; +using TagLibSharp2.Image.Tiff; + +namespace TagLibSharp2.Tests.Image; + +/// +/// One decoder locates a SHORT or LONG array, and one comparison decides the value budget. Both the plainness +/// check and the removal plan use those, so a second copy cannot drift. +/// +[TestClass] +[TestCategory ("Unit")] +public class TiffValueArrayTests +{ + // IFD at 8, two entries. The SHORT count of 1 is the entry's own value field (byte 18). The LONG count of 2 + // is eight bytes, so it is the offset the entry stores (40). + [TestMethod] + [DataRow (false)] + [DataRow (true)] + public void ShortAndLongArrays_AreTheEntryValueOrTheOffsetTheyName (bool bigEndian) + { + var tiff = new TiffBuilder (48, bigEndian).Header (8) + .Table (8, [(0x0111, 3, 1, 1), (0x0117, 4, 2, 40)]) + .ToArray (); + Assert.IsTrue (TiffReader.TryClassic (tiff, out var reader, out var ifd0)); + Assert.AreEqual (8, ifd0); + + Assert.IsTrue (reader.TryValueArray (reader.Entry (8, 0), out var inline)); + Assert.AreEqual (18, inline.At, bigEndian ? "big-endian" : "little-endian"); + Assert.AreEqual (1, inline.Count); + Assert.AreEqual (2, inline.Size); + + Assert.IsTrue (reader.TryValueArray (reader.Entry (8, 1), out var outside)); + Assert.AreEqual (40, outside.At); + Assert.AreEqual (2, outside.Count); + Assert.AreEqual (4, outside.Size); + } + + // Offset 40 and eight bytes, in a block that ends at 44. + [TestMethod] + public void AnArrayThatRunsPastTheData_IsNotLocated () + { + var tiff = new TiffBuilder (44).Header (8) + .Table (8, [(0x0111, 4, 2, 40)]) + .ToArray (); + Assert.IsTrue (TiffReader.TryClassic (tiff, out var reader, out _)); + + Assert.IsFalse (reader.TryValueArray (reader.Entry (8, 0), out _)); + } + + [TestMethod] + [DataRow (1)] + [DataRow (7)] + [DataRow (8)] + public void ATypeOtherThanShortOrLong_IsNotAValueArray (int type) + { + var tiff = new TiffBuilder (40).Header (8) + .Table (8, [(0x0111, type, 1, 1)]) + .ToArray (); + Assert.IsTrue (TiffReader.TryClassic (tiff, out var reader, out _)); + + Assert.IsFalse (reader.TryValueArray (reader.Entry (8, 0), out _), $"type {type}"); + } + + [TestMethod] + public void AZeroCount_IsNotAValueArray () + { + var tiff = new TiffBuilder (40).Header (8) + .Table (8, [(0x0111, 3, 0, 0)]) + .ToArray (); + Assert.IsTrue (TiffReader.TryClassic (tiff, out var reader, out _)); + + Assert.IsFalse (reader.TryValueArray (reader.Entry (8, 0), out _)); + } + + // Half the bytes still fits (two arrays can). One more value, from either side of the sum, does not. + [TestMethod] + public void HalfTheBytesStillFits_OneMoreDoesNot () + { + Assert.IsFalse (ValueBudget.PastHalf (0, 100, 200)); + Assert.IsTrue (ValueBudget.PastHalf (0, 101, 200)); + Assert.IsFalse (ValueBudget.PastHalf (50, 50, 200)); + Assert.IsTrue (ValueBudget.PastHalf (50, 51, 200)); + Assert.IsTrue (ValueBudget.PastHalf (101, 0, 200)); + } +} diff --git a/tests/TagLibSharp2.Tests/Image/XmpMirrorTests.cs b/tests/TagLibSharp2.Tests/Image/XmpMirrorTests.cs new file mode 100644 index 00000000..0873a7c0 --- /dev/null +++ b/tests/TagLibSharp2.Tests/Image/XmpMirrorTests.cs @@ -0,0 +1,213 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Text; +using System.Xml.Linq; +using TagLibSharp2.Core; +using TagLibSharp2.Image; +using TagLibSharp2.Image.Exif; +using TagLibSharp2.Image.Tiff; +using TagLibSharp2.Image.Xmp; +using TagLibSharp2.Tests.Core; +using TagLibSharp2.Tests.Kit; +using static TagLibSharp2.Tests.Image.GainMapTestData; +using static TagLibSharp2.Tests.Image.ImageTestBuilder; + +namespace TagLibSharp2.Tests.Image; + +/// Editing a field inside an XMP packet: every property shape, compression, the packet tail, and one pass over the text. +[TestClass] +[TestCategory ("Unit")] +public class XmpMirrorTests +{ + public static IEnumerable PacketShapes () + { + yield return ["attribute form", XmpPacket ("", " dc:title='Old & attr' xmp:Label='keep'"), "keep"]; + yield return ["empty description with attribute", XmpPacket ("").Replace ("'>\n ", "' dc:title='Old'/>", StringComparison.Ordinal), null!]; + yield return ["two descriptions", XmpPacket (Alt ("dc:title", "One")).Replace (" \n", " \n " + Alt ("dc:title", "Two") + " \n", StringComparison.Ordinal), null!]; + yield return ["CRLF and a wide character first", XmpPacket (" 🎵 日本\r\n\t" + Alt ("dc:title", "Old")).Replace ("\n", "\r\n", StringComparison.Ordinal), null!]; + yield return ["rdf as the default namespace", "
  • Old
  • ", null!]; + yield return ["empty property element", XmpPacket (" \n"), null!]; + yield return ["byte order mark before the packet", "\uFEFF" + XmpPacket (Alt ("dc:title", "Old")), null!]; + yield return ["simple property text", XmpPacket (" Old\n"), null!]; + yield return ["property declares its own namespace", XmpPacket (" Old\n"), "xmlns:dc='http://purl.org/dc/elements/1.1/'>"]; + yield return ["RDF prefix declared on the property", XmpPacket (" Old\n"), "xmlns:r="]; + yield return ["rdf prefix rebound on the property", XmpPacket (" Old\n"), "xmlns:rdf='urn:other'"]; + yield return ["resource attribute on the property", XmpPacket (" \n"), null!]; + yield return ["parseType on the property", XmpPacket (" Old\n"), null!]; + yield return ["end tag with white space", XmpPacket (" Old\n"), ""]; + yield return ["nested description is not a property", XmpPacket (" nested\n" + Alt ("dc:title", "Old")), "nested"]; + } + + [TestMethod] + [DynamicData (nameof (PacketShapes))] + public void Edit_UpdatesTheTitleInEveryPacketShape (string shape, string packet, string? kept) + { + var file = Open (Png (Xmp (packet)), "a.png"); + file.Tag!.Title = "New"; + + var save = file.SaveToFile ("/a.png", new MockFileSystem ()); + Assert.IsTrue (save.IsSuccess, $"{shape}: {save.Error}"); + var updated = PngTexts (file.Render ().ToArray (), "XML:com.adobe.xmp").Single (); + Assert.AreEqual (packet.StartsWith ('\uFEFF'), updated.StartsWith ('\uFEFF'), "the byte order mark is kept"); + var doc = XDocument.Parse (updated.TrimStart ('\uFEFF')); + var titles = doc.Descendants () + .Where (e => e.Name.LocalName == "Description" && e.Name.Namespace == Rdf) + .Where (e => e.Parent?.Name.LocalName == "RDF") + .SelectMany (d => d.Elements (Dc + "title").Select (t => t.Value).Concat (d.Attributes (Dc + "title").Select (a => a.Value))) + .ToList (); + Assert.AreEqual (1, titles.Count, $"{shape}: {updated}"); + Assert.AreEqual ("New", titles[0], shape); + foreach (var element in doc.Descendants (Dc + "title").Where (e => e.Parent?.Parent?.Name.LocalName == "RDF")) { + Assert.AreEqual ("New", element.Element (Rdf + "Alt")?.Element (Rdf + "li")?.Value, $"{shape}: an rdf:Alt in the RDF namespace"); + Assert.IsFalse (element.Attributes ().Any (a => a.Name.Namespace == Rdf), $"{shape}: no rdf attribute contradicts the new content"); + } + if (kept is not null) + StringAssert.Contains (updated, kept, shape); + + file.Tag.Title = null; + var cleared = PngTexts (file.Render ().ToArray (), "XML:com.adobe.xmp").Single (); + var left = XDocument.Parse (cleared.TrimStart ('\uFEFF')).Descendants () + .Where (e => e.Name.LocalName == "Description" && e.Parent?.Name.LocalName == "RDF") + .SelectMany (d => d.Elements (Dc + "title").Cast ().Concat (d.Attributes (Dc + "title"))) + .Count (); + Assert.AreEqual (0, left, $"{shape}: {cleared}"); + } + + [TestMethod] + public void Edit_ZtxtXmpPacket_IsUpdatedAndStaysCompressed () + { + var packet = XmpPacket (Alt ("dc:title", "Old")); + var file = Open (Png (CompressedText ("XML:com.adobe.xmp", Encoding.UTF8.GetBytes (packet))), "a.png"); + file.Tag!.Title = "New"; + var output = file.Render ().ToArray (); + Assert.AreEqual ("zTXt", PngChunks (output).Single (c => c.Type is "zTXt" or "iTXt" or "tEXt" && Encoding.Latin1.GetString (c.Payload).StartsWith ("XML:", StringComparison.Ordinal)).Type); + StringAssert.Contains (PngTexts (output, "XML:com.adobe.xmp").Single (), ">New<"); + } + + // The splice writes each character of the new packet once, however many copies it replaces. + [TestMethod] + public void Edit_XmpSplice_IsOnePass () + { + foreach (var n in new[] { 1000, 4000 }) { + var descriptions = string.Concat (Enumerable.Range (0, n).Select (_ => "")); + var packet = $"{descriptions}"; + foreach (var value in new[] { null, "New" }) { + var tag = new ImageTag (MediaFormat.Png, (ImageStores)0x3F); + tag.ReadField ((ImageStores)1, "Old"); + tag.Title = value; + XmpMirror.SpliceWrites = 0; + Assert.IsTrue (XmpMirror.TryUpdate (packet, tag, "PNG XMP packet", out var updated, out var error), error); + Assert.AreEqual (updated.Length, XmpMirror.SpliceWrites, $"n={n} value={value}"); + Assert.AreEqual (value is null ? 0 : 1, XDocument.Parse (updated).Descendants ().Count (e => e.Attribute (Dc + "title") is not null)); + } + } + } + + // N mirrored XMP copies sit next to each other, so each one is a new piece appended to the last. Appending + // copies the bytes gathered so far; four times the copies then adds about four times as much, and the bound + // is three. A list of pieces adds about twice as much. + [TestMethod] + [DoNotParallelize] + [DataRow ("png")] + [DataRow ("gif")] + [DataRow ("jpeg")] + public void Edit_ManyMirroredXmpCopies_AllocatesLinearly (string format) + { + var sample = ManyMirroredXmp (format, 2); + var check = Open (sample, SampleName (format)); + SetMirroredField (check.Tag!, format); + var saved = check.SaveToFile ("/a" + SampleName (format), new MockFileSystem ()); + Assert.IsTrue (saved.IsSuccess, saved.Error); + var output = check.Render ().ToArray (); + Assert.AreEqual (2, CountPacketTitles (output, "New"), $"{format}: both packets hold the new value"); + Assert.AreEqual (0, CountPacketTitles (output, "Old"), $"{format}: the old value is gone"); + if (format == "png") + CollectionAssert.AreEqual (PngPayload (sample, "IDAT"), PngPayload (output, "IDAT")); + + const int n = 200; + Bounds.AssertLinearAllocation (count => ManyMirroredXmp (format, count), data => { + var file = Open (data, SampleName (format)); + SetMirroredField (file.Tag!, format); + _ = file.SaveToFile ("/a" + SampleName (format), new MockFileSystem ()); + }, n, runs: 3); + var sized = ManyMirroredXmp (format, n); + var copies = CountPacketTitles (sized, "Old"); + var sizedFile = Open (sized, SampleName (format)); + SetMirroredField (sizedFile.Tag!, format); + var sizedSave = sizedFile.SaveToFile ("/a" + SampleName (format), new MockFileSystem ()); + Assert.IsTrue (sizedSave.IsSuccess, $"{format}: {sizedSave.Error}"); + Assert.AreEqual (copies, CountPacketTitles (sizedFile.Render ().ToArray (), "New"), $"{format} N={n}"); + } + + // PNG stores a title, so dc:title is the mirrored copy. JPEG and GIF store a comment, so the copy is UserComment. + static void SetMirroredField (Tag tag, string format) + { + if (format == "png") + tag.Title = "New"; + else + tag.Comment = "New"; + } + + static string SampleName (string format) => format switch { + "gif" => "a.gif", + "jpeg" => "a.jpg", + _ => "a.png", + }; + + // Uncompressed copies of one dc:title packet: PNG tEXt, GIF application extension, JPEG APP1. + static byte[] ManyMirroredXmp (string format, int n) + { + var packet = format == "png" + ? "Old" + : "Old"; + var chunks = new byte[n][]; + for (var i = 0; i < n; i++) { + chunks[i] = format switch { + "gif" => GifXmp (packet), + "jpeg" => JpegXmp (packet), + _ => Text ("XML:com.adobe.xmp", packet), + }; + } + + return format switch { + "gif" => Gif (chunks), + "jpeg" => Jpeg (chunks), + _ => Png (chunks), + }; + } + + static int CountPacketTitles (byte[] data, string title) => + Bytes.Count (data, Encoding.ASCII.GetBytes (">" + title + "<")); + + public static IEnumerable PacketTails () + { + yield return ["jpeg", "NUL after the trailer (ImageIO)", new byte[] { 0 }]; + yield return ["jpeg", "line feed and NUL (sample_xmpnullended.jpg)", new byte[] { 0x0A, 0 }]; + yield return ["jpeg", "several NULs and spaces", new byte[] { 0x20, 0, 0, 0 }]; + yield return ["png", "NUL after the trailer", new byte[] { 0 }]; + } + + // XMP Part 1 §7.3: the packet ends with its trailer; bytes after it are not XML and keep their place. + [TestMethod] + [DynamicData (nameof (PacketTails))] + public void CommentEdit_OfAPacketFollowedByNulOrPadding_UpdatesItAndKeepsTheTail (string format, string shape, byte[] tail) + { + var packet = XmpPacket (Alt ("exif:UserComment", "Old")); + byte[] input; + if (format == "jpeg") + input = Jpeg (JpegXmpBytes (packet, tail), JpegSegment (0xFE, "Old"u8.ToArray ())); + else + input = Png (RawItxt ("XML:com.adobe.xmp", Concat (Encoding.UTF8.GetBytes (packet), tail)), Text ("Comment", "Old")); + var name = format == "jpeg" ? "a.jpg" : "a.png"; + var file = Open (input, name); + file.Tag!.Comment = "New"; + + var save = file.SaveToFile ("/" + name, new MockFileSystem ()); + Assert.IsTrue (save.IsSuccess, $"{shape}: {save.Error}"); + var output = file.Render ().ToArray (); + var end = output.AsSpan ().IndexOf (""u8) + 19; + Assert.IsTrue (output.AsSpan (end, tail.Length).SequenceEqual (tail), $"{shape}: the tail is kept after the packet"); + Assert.IsTrue (output.AsSpan ().IndexOf (">New<"u8) > 0, shape); + } +} diff --git a/tests/TagLibSharp2.Tests/Kit/Bounds.cs b/tests/TagLibSharp2.Tests/Kit/Bounds.cs index 244454a6..2a447a88 100644 --- a/tests/TagLibSharp2.Tests/Kit/Bounds.cs +++ b/tests/TagLibSharp2.Tests/Kit/Bounds.cs @@ -42,27 +42,95 @@ public static long AssertAllocatesAtMost (long limit, Action action, string? wha /// /// Measures the inputs built for n, 2n and 4n and compares the increments, so a /// fixed cost cannot hide a quadratic one: linear work adds twice as much from 2n to 4n as from n to 2n, - /// quadratic work adds four times as much. The bound is 2 × slack. A parser that copies each - /// nested payload, or rescans a list per item, fails here. Building the input is not measured, and each - /// size runs once before it is measured so one-time JIT and static allocations do not count. + /// quadratic work adds four times as much. The bound is 2 × slack. An increment under the noise + /// floor (1 KB, or 1% of the n allocation) counts as no growth, so a flat series passes and a flat series + /// that then jumps still fails (). A parser that copies each nested + /// payload, or rescans a list per item, fails here. Building the input is not measured. Each size is warmed + /// once, then the action alone is measured, and the least of the runs is kept + /// (). /// - public static void AssertLinearAllocation (Func build, Action run, int n, double slack = 1.5) + /// Runs measured per size; the least is kept. Above 1 it drops a one-off extra allocation. + public static void AssertLinearAllocation (Func build, Action run, int n, double slack = 1.5, int runs = 1) { ArgumentNullException.ThrowIfNull (build); ArgumentNullException.ThrowIfNull (run); - var one = Measure (build (n), run); - var two = Measure (build (n * 2), run); - var four = Measure (build (n * 4), run); - var first = Math.Max (two - one, 1); + var builtOne = build (n); + var builtTwo = build (n * 2); + var builtFour = build (n * 4); + var one = LeastAllocated (() => run (builtOne), runs); + var two = LeastAllocated (() => run (builtTwo), runs); + var four = LeastAllocated (() => run (builtFour), runs); + AssertGrowsLinearly (one, two, four, slack); + } + + /// + /// Fails when the allocations measured for inputs of n, 2n and 4n grow faster than the input. + /// + /// + /// An increment under the noise floor — 1 KB, or 1% of the n allocation, whichever is larger — counts as no + /// growth, so a flat or noisy-flat series passes. A series that is flat and then jumps still fails. When the + /// first increment is below the floor, the baseline is the floor, so a linear step just under it passes. A step + /// above the absolute 1 KB floor whose successor reaches 2 × slack still fails when both steps sit under + /// 1% of a large n: zeroing both would hide that superlinear series. Linear work adds twice as much from 2n to + /// 4n as from n to 2n; the bound is 2 × slack. + /// + public static void AssertGrowsLinearly (long one, long two, long four, double slack = 1.5) + { + var noise = Math.Max (1024L, one / 100); + var first = two - one; var second = four - two; - if (second > first * 2 * slack) - Assert.Fail ($"allocation grew {second / (double)first:F1}x as fast from 2n to 4n as from n to 2n ({one} -> {two} -> {four} bytes); linear is 2x, the bound {2 * slack:F1}x"); + var bound = 2 * slack; + // Both steps are inside the floor. Compare them to each other when the first step is above the absolute + // 1 KB floor: a 3x jump under 1% of a large baseline is still superlinear, and the strict bound would miss + // a ratio that lands on 2 × slack exactly. + if (second <= noise && Math.Abs (first) <= noise) { + if (first > 1024 && second >= first * bound) + Assert.Fail ($"allocation grew {second / (double)first:F1}x as fast from 2n to 4n as from n to 2n ({one} -> {two} -> {four} bytes); linear is 2x, the bound {bound:F1}x"); + return; + } + + var baseline = Math.Max (first, noise); + if (second > baseline * bound) + Assert.Fail ($"allocation grew {second / (double)baseline:F1}x as fast from 2n to 4n as from n to 2n ({one} -> {two} -> {four} bytes); linear is 2x, the bound {bound:F1}x"); + } + + /// + /// Bytes allocated by alone: one warm-up, then the least of + /// measured calls. + /// + /// + /// The warm-up pays for JIT and static caches. Before each measured call, one array is returned to every + /// shared bucket. A rewriter rents a buffer that grows with the + /// input and returns it; the next call's smaller rent takes that larger buffer when its own bucket is empty, + /// and the following rent allocates a new one. Measured on the compacted IFD chain, that miss is one bucket: + /// 64 KB, 128 KB and 256 KB at 2,000, 4,000 and 8,000 tables. Counted only at 8,000, the second increment is + /// 3.0x the first, on the slack bound. With every rent a hit the same edit is 2.6x. A test that compares + /// sizes is marked not to run beside other tests, because another test's rent during the sample can still + /// take the buffer just returned. + /// + public static long LeastAllocated (Action action, int runs = 3) + { + ArgumentNullException.ThrowIfNull (action); + action (); + var least = long.MaxValue; + for (var r = 0; r < Math.Max (runs, 1); r++) { + ReturnOneBufferToEachPoolBucket (); + least = Math.Min (least, AllocatedBytes (action)); + } + + return least; } - static long Measure (byte[] input, Action run) + // Rent from the largest bucket down while holding the arrays, so a small rent cannot take a larger bucket's + // only buffer, then return them smallest first so each bucket has one. + static void ReturnOneBufferToEachPoolBucket () { - run (input); - return AllocatedBytes (() => run (input)); + var held = new byte[17][]; + var count = 0; + for (var size = 1024 * 1024; size >= 16; size >>= 1) + held[count++] = System.Buffers.ArrayPool.Shared.Rent (size); + for (var i = count - 1; i >= 0; i--) + System.Buffers.ArrayPool.Shared.Return (held[i]); } } diff --git a/tests/TagLibSharp2.Tests/Kit/BoundsTests.cs b/tests/TagLibSharp2.Tests/Kit/BoundsTests.cs index 46d43b66..6d93ee92 100644 --- a/tests/TagLibSharp2.Tests/Kit/BoundsTests.cs +++ b/tests/TagLibSharp2.Tests/Kit/BoundsTests.cs @@ -102,6 +102,44 @@ public void AssertLinearAllocation_OneTimeSetup_IsNotCounted () Assert.IsNotNull (cache); } + [TestMethod] + public void AssertLinearAllocation_QuadraticWork_FailsWithSeveralRuns () + { + // Keeping the least of three runs does not hide work that is quadratic on every run. + static void Quadratic (byte[] data) + { + for (var i = 0; i < data.Length; i += 16) + _ = data.AsSpan (i).ToArray (); + } + + var error = Assert.ThrowsExactly ( + () => Bounds.AssertLinearAllocation (n => new byte[n], Quadratic, 4_096, runs: 3)); + + Assert.Contains ("grew", error.Message); + } + + // Linear work whose first measured run at 4n also allocates 4 MB, as when another thread emptied a shared + // pool: one run sees the noise and fails, the least of three does not. + static Action LinearWithOneNoisyRun (int n) + { + var calls = new Dictionary (); + return data => { + calls[data.Length] = calls.GetValueOrDefault (data.Length) + 1; + if (data.Length == 4 * n && calls[data.Length] == 2) + GC.KeepAlive (new byte[4 * 1024 * 1024]); + GC.KeepAlive ((byte[])data.Clone ()); + }; + } + + [TestMethod] + public void AssertLinearAllocation_OneNoisyRun_FailsWithOneRun_AndPassesWithSeveral () + { + Assert.ThrowsExactly ( + () => Bounds.AssertLinearAllocation (n => new byte[n], LinearWithOneNoisyRun (10_000), 10_000)); + + Bounds.AssertLinearAllocation (n => new byte[n], LinearWithOneNoisyRun (10_000), 10_000, runs: 3); + } + [TestMethod] public void AssertLinearAllocation_LinearWorkBehindAFixedCost_Passes () { @@ -111,6 +149,53 @@ public void AssertLinearAllocation_LinearWorkBehindAFixedCost_Passes () }, 10_000); } + // Ubuntu CI measured these on EveryIfdWalk_IsLinearInTheEntries: the n-to-2n step is zero or negative, and + // treating that step as 1 made an 80-byte bump at 4n look like 80x growth. + [TestMethod] + public void AssertGrowsLinearly_FlatSeries_Passes () + { + Bounds.AssertGrowsLinearly (24936, 24856, 24936); + Bounds.AssertGrowsLinearly (24968, 24968, 25048); + Bounds.AssertGrowsLinearly (1584, 1584, 1584); + } + + [TestMethod] + public void AssertGrowsLinearly_SuperlinearSeries_Fails () + { + var error = Assert.ThrowsExactly ( + () => Bounds.AssertGrowsLinearly (1_000_000, 2_000_000, 8_000_000)); + + Assert.Contains ("grew", error.Message); + } + + // A first increment inside the noise floor must not excuse a jump at 4n. + [TestMethod] + public void AssertGrowsLinearly_FlatThenASpike_Fails () + { + var error = Assert.ThrowsExactly ( + () => Bounds.AssertGrowsLinearly (24936, 24856, 1_000_000)); + + Assert.Contains ("grew", error.Message); + } + + // The 1% floor must not hide a doubling that is still above the absolute 1 KB floor, and it must not + // turn a genuinely linear step that sits under that floor into a failure against a baseline of 1. + [TestMethod] + [DataRow (10_000L, 11_000L, 13_000L, false)] + [DataRow (1_000_000L, 1_008_000L, 1_024_000L, false)] + [DataRow (10_000_000L, 10_030_000L, 10_090_000L, false)] + [DataRow (10_000_000L, 10_030_000L, 10_120_000L, true)] + public void AssertGrowsLinearly_NoiseFloorEdges_MatchTheSeries (long one, long two, long four, bool superlinear) + { + if (!superlinear) { + Bounds.AssertGrowsLinearly (one, two, four); + return; + } + + var error = Assert.ThrowsExactly (() => Bounds.AssertGrowsLinearly (one, two, four)); + Assert.Contains ("grew", error.Message); + } + [TestMethod] public void CountingStream_CountsReadsSeeksAndBytes () { diff --git a/tests/TagLibSharp2.Tests/Kit/Bytes.cs b/tests/TagLibSharp2.Tests/Kit/Bytes.cs new file mode 100644 index 00000000..0eb90633 --- /dev/null +++ b/tests/TagLibSharp2.Tests/Kit/Bytes.cs @@ -0,0 +1,22 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +namespace TagLibSharp2.Tests.Kit; + +/// Byte-sequence counts shared by the tests. +public static class Bytes +{ + /// How many times occurs in , including overlaps. + public static int Count (byte[] data, ReadOnlySpan needle) + { + if (needle.Length == 0 || needle.Length > data.Length) + return 0; + var count = 0; + for (var i = 0; i + needle.Length <= data.Length; i++) { + if (data.AsSpan (i, needle.Length).SequenceEqual (needle)) + count++; + } + + return count; + } +} diff --git a/tests/TagLibSharp2.Tests/Kit/DepthCaseTests.cs b/tests/TagLibSharp2.Tests/Kit/DepthCaseTests.cs index 285f7e2c..6688d0ca 100644 --- a/tests/TagLibSharp2.Tests/Kit/DepthCaseTests.cs +++ b/tests/TagLibSharp2.Tests/Kit/DepthCaseTests.cs @@ -25,7 +25,10 @@ public void Build_Shallow_IsReadAsItsFormatWithATag (string name) Assert.IsTrue (result.IsSuccess, result.Error); Assert.AreEqual (depthCase.Format, result.Format); - Assert.IsNotNull (result.Tag); + if (depthCase.Format == MediaFormat.Tiff) + Assert.IsNull (result.Tag); + else + Assert.IsNotNull (result.Tag); } [TestMethod] diff --git a/tests/TagLibSharp2.Tests/Kit/DepthCases.cs b/tests/TagLibSharp2.Tests/Kit/DepthCases.cs index 3fdd4235..2a146a63 100644 --- a/tests/TagLibSharp2.Tests/Kit/DepthCases.cs +++ b/tests/TagLibSharp2.Tests/Kit/DepthCases.cs @@ -16,7 +16,8 @@ namespace TagLibSharp2.Tests.Kit; /// Extension for the path hint and the saved file. /// What repeats, for the test name and the report. /// Builds the file at a depth. -public sealed record DepthCase (string Name, MediaFormat Format, string Extension, string Structure, Func Build); +/// The edit to save; null sets and checks it reads back. +public sealed record DepthCase (string Name, MediaFormat Format, string Extension, string Structure, Func Build, Action? Edit = null); /// /// Every structure in a supported format whose depth the file controls. @@ -55,8 +56,40 @@ public static class DepthCases "ID3v2.4 CHAP embedded in CHAP (ID3v2 Chapter Frame Addendum §3.1)", Id3Chapters), new ("mp3-id3v2-ctoc", MediaFormat.Mp3, ".mp3", "ID3v2.4 CTOC embedded in CTOC (ID3v2 Chapter Frame Addendum §3.2)", Id3Tocs), + new ("tiff-subifd", MediaFormat.Tiff, ".tif", + "TIFF/DNG SubIFD (tag 330) nested in SubIFD", TiffSubIfds), + new ("jpeg-xmp-gainmap-clear", MediaFormat.Jpeg, ".jpg", + "XMP elements nested in a gain-map property (hdrgm:GainMapMax), saved with Clear", JpegDeepXmp, t => t.Clear ()), + new ("jpeg-xmp-comment", MediaFormat.Jpeg, ".jpg", + "XMP elements nested next to exif:UserComment, saved with a Comment edit", JpegDeepXmp, t => t.Comment = "edited"), ]; + // One APP1 segment holds at most 65,533 bytes, so the nesting stops where the packet would no longer fit. + static byte[] JpegDeepXmp (int depth) + { + const string Head = "http://ns.adobe.com/xap/1.0/\0" + + "" + + "old"; + const string Tail = ""; + var levels = Math.Min (depth, (65_533 - Head.Length - Tail.Length) / 7); + var xmp = new System.Text.StringBuilder (Head); + for (var n = 0; n < levels; n++) + xmp.Append (""); + for (var n = 0; n < levels; n++) + xmp.Append (""); + xmp.Append (Tail); + var payload = System.Text.Encoding.ASCII.GetBytes (xmp.ToString ()); + var app1 = new byte[4 + payload.Length]; + app1[0] = 0xFF; + app1[1] = 0xE1; + app1[2] = (byte)((payload.Length + 2) >> 8); + app1[3] = (byte)(payload.Length + 2); + payload.CopyTo (app1, 4); + byte[] frame = [0xFF, 0xC0, 0x00, 0x0B, 0x08, 0x00, 0x01, 0x00, 0x01, 0x01, 0x01, 0x11, 0x00]; + byte[] scan = [0xFF, 0xDA, 0x00, 0x08, 0x01, 0x01, 0x00, 0x00, 0x3F, 0x00, 0x12, 0x34, 0xFF, 0xD9]; + return [0xFF, 0xD8, .. app1, 0xFF, 0xFE, 0x00, 0x05, (byte)'o', (byte)'l', (byte)'d', .. frame, .. scan]; + } + /// Finds a case by name. public static DepthCase Find (string name) => All.FirstOrDefault (c => c.Name == name) @@ -211,6 +244,71 @@ static byte[] Mp3File (byte[] frames) frame[2] = 0x90; return Nesting.Concat (Nesting.Id3v2Tag (frames), frame, frame); } + + /// + /// Little-endian TIFF whose first IFD is a reduced-resolution preview pointing at a chain of SubIFDs. + /// The outermost IFD also stores width and height, so a depth cap still opens the file. + /// + static byte[] TiffSubIfds (int depth) + { + if (depth < 1) + depth = 1; + const int outerSize = 2 + (4 * 12) + 4; + const int middleSize = 2 + 12 + 4; + const int leafSize = 2 + (2 * 12) + 4; + var total = depth == 1 ? 8 + leafSize : 8 + outerSize + ((depth - 2) * middleSize) + leafSize; + var data = new byte[total]; + data[0] = (byte)'I'; + data[1] = (byte)'I'; + data[2] = 42; + System.Buffers.Binary.BinaryPrimitives.WriteInt32LittleEndian (data.AsSpan (4), 8); + if (depth == 1) { + WriteLeaf (data, 8); + return data; + } + + var leafAt = 8 + outerSize + ((depth - 2) * middleSize); + WriteCount (data, 8, 4); + WriteLong (data, 10, 254, 1); + WriteShort (data, 22, 256, 7); + WriteShort (data, 34, 257, 11); + WriteLong (data, 46, 330, 8 + outerSize); + for (var level = 0; level < depth - 2; level++) { + var at = 8 + outerSize + (level * middleSize); + var child = level + 1 < depth - 2 ? at + middleSize : leafAt; + WriteCount (data, at, 1); + WriteLong (data, at + 2, 330, child); + } + + WriteLeaf (data, leafAt); + return data; + + static void WriteLeaf (byte[] data, int at) + { + WriteCount (data, at, 2); + WriteShort (data, at + 2, 256, 7); + WriteShort (data, at + 14, 257, 11); + } + + static void WriteCount (byte[] data, int at, int count) => + System.Buffers.Binary.BinaryPrimitives.WriteUInt16LittleEndian (data.AsSpan (at), (ushort)count); + + static void WriteShort (byte[] data, int at, int tag, int value) + { + System.Buffers.Binary.BinaryPrimitives.WriteUInt16LittleEndian (data.AsSpan (at), (ushort)tag); + System.Buffers.Binary.BinaryPrimitives.WriteUInt16LittleEndian (data.AsSpan (at + 2), 3); + System.Buffers.Binary.BinaryPrimitives.WriteUInt32LittleEndian (data.AsSpan (at + 4), 1); + System.Buffers.Binary.BinaryPrimitives.WriteUInt16LittleEndian (data.AsSpan (at + 8), (ushort)value); + } + + static void WriteLong (byte[] data, int at, int tag, int value) + { + System.Buffers.Binary.BinaryPrimitives.WriteUInt16LittleEndian (data.AsSpan (at), (ushort)tag); + System.Buffers.Binary.BinaryPrimitives.WriteUInt16LittleEndian (data.AsSpan (at + 2), 4); + System.Buffers.Binary.BinaryPrimitives.WriteUInt32LittleEndian (data.AsSpan (at + 4), 1); + System.Buffers.Binary.BinaryPrimitives.WriteInt32LittleEndian (data.AsSpan (at + 8), value); + } + } } /// @@ -260,8 +358,12 @@ public static int Run (DepthCase depthCase, int depth, TextWriter output) line += $" path={Outcome (opened)}"; if (opened.IsSuccess) { step = "edit"; - if (opened.Tag is not null) - opened.Tag.Title = DepthCases.LongTitle; + if (opened.Tag is not null) { + if (depthCase.Edit is not null) + depthCase.Edit (opened.Tag); + else + opened.Tag.Title = DepthCases.LongTitle; + } line += $" edit={(opened.Tag is null ? "no-tag" : "ok")}"; step = "save"; @@ -272,7 +374,7 @@ public static int Run (DepthCase depthCase, int depth, TextWriter output) if (write.IsSuccess) { var again = MediaFile.Read (saved, files); line += $" reread={Outcome (again)}"; - if (again.IsSuccess && opened.Tag is not null && again.Tag?.Title != DepthCases.LongTitle) + if (again.IsSuccess && opened.Tag is not null && depthCase.Edit is null && again.Tag?.Title != DepthCases.LongTitle) line += " title-lost"; } } diff --git a/tests/TagLibSharp2.Tests/Kit/KitChildTests.cs b/tests/TagLibSharp2.Tests/Kit/KitChildTests.cs index 82ca041d..a1a83f29 100644 --- a/tests/TagLibSharp2.Tests/Kit/KitChildTests.cs +++ b/tests/TagLibSharp2.Tests/Kit/KitChildTests.cs @@ -30,7 +30,11 @@ public void Run_AChildThatOverflowsTheStack_IsAFailureAndTheHostSurvives () Assert.AreNotEqual (0, result.ExitCode, result.Describe ()); Assert.IsFalse (result.TimedOut); - Assert.IsTrue (result.Error.Contains ("stack overflow", StringComparison.OrdinalIgnoreCase), result.Describe ()); + // Unix prints "Stack overflow." Windows often dies on the guard page with + // STATUS_STACK_OVERFLOW or STATUS_ACCESS_VIOLATION and writes nothing. + var stackOverflow = result.Error.Contains ("stack overflow", StringComparison.OrdinalIgnoreCase) + || result.ExitCode is -1073741571 or -1073741819; + Assert.IsTrue (stackOverflow, result.Describe ()); } [TestMethod] diff --git a/tests/TagLibSharp2.Tests/Kit/KitProgram.cs b/tests/TagLibSharp2.Tests/Kit/KitProgram.cs index 8a46600f..139f20f3 100644 --- a/tests/TagLibSharp2.Tests/Kit/KitProgram.cs +++ b/tests/TagLibSharp2.Tests/Kit/KitProgram.cs @@ -49,8 +49,11 @@ static int Run (string[] args) return OnSmallStack (() => DepthProbe.Run (DepthCases.Find (args[1]), depth, Console.Out)); if (args.Length == 2 && args[0] == "kit-selftest") return OnSmallStack (() => SelfTest (args[1])); + if (args.Length == 2 && args[0] == "kit-exif-cross" + && int.TryParse (args[1], NumberStyles.None, CultureInfo.InvariantCulture, out var tables)) + return Image.ExifPlainTests.CrossInChild (tables); - Console.Error.WriteLine ("usage: TagLibSharp2.Tests kit-depth | kit-selftest ok|overflow|stack|throw|allocate|hang"); + Console.Error.WriteLine ("usage: TagLibSharp2.Tests kit-depth | kit-selftest ok|overflow|stack|throw|allocate|hang | kit-exif-cross "); Console.Error.WriteLine ($"cases: {string.Join (", ", DepthCases.All.Select (c => c.Name))}"); return UsageExitCode; } diff --git a/tests/TagLibSharp2.Tests/Mpeg/MpegPsAppendedTagTests.cs b/tests/TagLibSharp2.Tests/Mpeg/MpegPsAppendedTagTests.cs index 75b0fdf4..6e7a7bd3 100644 --- a/tests/TagLibSharp2.Tests/Mpeg/MpegPsAppendedTagTests.cs +++ b/tests/TagLibSharp2.Tests/Mpeg/MpegPsAppendedTagTests.cs @@ -426,14 +426,5 @@ internal static byte[] UpdateTag (string title, int flagBytes = 1, byte flags = return Concat (header, extended, body, footer); } - internal static int Count (byte[] data, ReadOnlySpan needle) - { - var count = 0; - for (var i = 0; i + needle.Length <= data.Length; i++) { - if (data.AsSpan (i, needle.Length).SequenceEqual (needle)) - count++; - } - - return count; - } + internal static int Count (byte[] data, ReadOnlySpan needle) => TagLibSharp2.Tests.Kit.Bytes.Count (data, needle); } diff --git a/tests/TagLibSharp2.Tests/PublicApi/Snapshots/TagLibSharp2.PublicApi.verified.txt b/tests/TagLibSharp2.Tests/PublicApi/Snapshots/TagLibSharp2.PublicApi.verified.txt index e758be6a..48b223f3 100644 --- a/tests/TagLibSharp2.Tests/PublicApi/Snapshots/TagLibSharp2.PublicApi.verified.txt +++ b/tests/TagLibSharp2.Tests/PublicApi/Snapshots/TagLibSharp2.PublicApi.verified.txt @@ -1291,6 +1291,15 @@ namespace TagLibSharp2.Core Aac = 17, Audible = 18, Avi = 19, + Jpeg = 20, + Png = 21, + Gif = 22, + Bmp = 23, + Pcx = 24, + Netpbm = 25, + Tiff = 26, + Dng = 27, + Svg = 28, } [System.Flags] public enum MediaTypes @@ -1470,6 +1479,7 @@ namespace TagLibSharp2.Core FlacMetadata = 256, Xmp = 512, Audible = 1024, + Image = 2048, AllTags = -1, } public sealed class ValidationIssue @@ -2421,6 +2431,43 @@ namespace TagLibSharp2.Id3.Id3v2 Utf8 = 3, } } +namespace TagLibSharp2.Image +{ + public sealed class StillImageFile : System.IDisposable, TagLibSharp2.Core.IMediaFile + { + public TagLibSharp2.Core.IMediaProperties? AudioProperties { get; } + public TagLibSharp2.Core.MediaFormat Format { get; } + public TagLibSharp2.Core.ImageProperties? ImageProperties { get; } + public TagLibSharp2.Core.MediaTypes MediaTypes { get; } + public string? SourcePath { get; } + public TagLibSharp2.Core.Tag? Tag { get; } + public TagLibSharp2.Core.VideoProperties? VideoProperties { get; } + public void Dispose() { } + public System.ReadOnlyMemory Render() { } + public TagLibSharp2.Core.FileWriteResult SaveToFile(TagLibSharp2.Core.IFileSystem? fileSystem = null) { } + public TagLibSharp2.Core.FileWriteResult SaveToFile(string path, TagLibSharp2.Core.IFileSystem? fileSystem = null) { } + public System.Threading.Tasks.Task SaveToFileAsync(TagLibSharp2.Core.IFileSystem? fileSystem = null, System.Threading.CancellationToken cancellationToken = default) { } + public System.Threading.Tasks.Task SaveToFileAsync(string path, TagLibSharp2.Core.IFileSystem? fileSystem = null, System.Threading.CancellationToken cancellationToken = default) { } + public static bool IsValidFormat(System.ReadOnlySpan data) { } + public static TagLibSharp2.Image.StillImageFileReadResult Read(System.ReadOnlySpan data) { } + public static TagLibSharp2.Image.StillImageFileReadResult ReadFromFile(string path, TagLibSharp2.Core.IFileSystem? fileSystem = null) { } + public static System.Threading.Tasks.Task ReadFromFileAsync(string path, TagLibSharp2.Core.IFileSystem? fileSystem = null, System.Threading.CancellationToken cancellationToken = default) { } + public static bool TryRead(System.ReadOnlySpan data, out TagLibSharp2.Image.StillImageFile? file) { } + } + public readonly struct StillImageFileReadResult : System.IEquatable + { + public string? Error { get; } + public TagLibSharp2.Image.StillImageFile? File { get; } + public bool IsSuccess { get; } + public bool Equals(TagLibSharp2.Image.StillImageFileReadResult other) { } + public override bool Equals(object? obj) { } + public override int GetHashCode() { } + public static TagLibSharp2.Image.StillImageFileReadResult Failure(string error) { } + public static TagLibSharp2.Image.StillImageFileReadResult Success(TagLibSharp2.Image.StillImageFile file) { } + public static bool operator !=(TagLibSharp2.Image.StillImageFileReadResult left, TagLibSharp2.Image.StillImageFileReadResult right) { } + public static bool operator ==(TagLibSharp2.Image.StillImageFileReadResult left, TagLibSharp2.Image.StillImageFileReadResult right) { } + } +} namespace TagLibSharp2.Matroska { public sealed class MatroskaChapter diff --git a/tests/TagLibSharp2.Tests/TagLibSharp2.Tests.csproj b/tests/TagLibSharp2.Tests/TagLibSharp2.Tests.csproj index 7710673f..080d2a38 100644 --- a/tests/TagLibSharp2.Tests/TagLibSharp2.Tests.csproj +++ b/tests/TagLibSharp2.Tests/TagLibSharp2.Tests.csproj @@ -20,6 +20,11 @@ + + + + + diff --git a/tools/README.md b/tools/README.md index ecd54431..3969ef63 100644 --- a/tools/README.md +++ b/tools/README.md @@ -8,6 +8,7 @@ runs in CI, and none of them belongs in the package. | [`compare/grid.cs`](compare/grid.cs) | Before/after grid: detection, key tags and a hash of each fixed edit's saved bytes, one TSV line per file | | [`compare/readers.sh`](compare/readers.sh) | Shows what ffprobe, exiftool, mutagen and mediainfo read for common fields, side by side | | [`fuzz/fuzz.cs`](fuzz/fuzz.cs) | Truncation and byte-flip fuzz over real files: span read, stream read and a no-op save | +| [`exif/golden.sh`](exif/golden.sh) | Regenerates the exiftool golden files the Exif reader model is checked against; [`exif/README.md`](exif/README.md) lists the measured rules | | [`mutation.sh`](mutation.sh) | Stryker.NET mutation testing of the library files a branch changes | | [`GenerateApiMatrix`](GenerateApiMatrix.cs) | Writes the API matrix from a built assembly | diff --git a/tools/Shared/ToolSupport.cs b/tools/Shared/ToolSupport.cs index 9a4c15ae..a0412714 100644 --- a/tools/Shared/ToolSupport.cs +++ b/tools/Shared/ToolSupport.cs @@ -22,6 +22,8 @@ static class ToolSupport ".flac", ".ogg", ".oga", ".ogv", ".opus", ".spx", ".wav", ".aif", ".aiff", ".aifc", ".dsf", ".dff", ".wv", ".ape", ".mpc", ".mp+", ".mpp", ".wma", ".wmv", ".asf", ".mpg", ".mpeg", ".mpe", ".vob", ".mpv", ".m1v", ".m2v", ".avi", ".aac", ".aa", ".aax", ".tta", + ".jpg", ".jpeg", ".jpe", ".png", ".gif", ".bmp", ".dib", ".pcx", + ".pbm", ".pgm", ".ppm", ".pnm", ".tif", ".tiff", ".dng", ".svg", }; // Never opened, even with --all: source and text that sits beside sample media. diff --git a/tools/exif/README.md b/tools/exif/README.md new file mode 100644 index 00000000..9fca2c48 --- /dev/null +++ b/tools/exif/README.md @@ -0,0 +1,80 @@ +# How exiftool reads Exif tables + +The Exif editor removes a field's copies from every table exiftool reads with its Exif tags, and the tests' reader +model (`tests/TagLibSharp2.Tests/Image/ExifReaderModel.cs`) is the oracle for what that means. Each rule below +was measured with exiftool 13.55 (`exiftool -a -G1 -H -s -U -EXIF:All` on the TIFF wrapped in a JPEG APP1). The +probe column names the input in `Golden/exif-reader-probes.txt` that records it, as `ExifReaderGoldenTests.Probes` +names it, and the result is the field-tag counts exiftool showed (`-` for none). In the probes, `E9286` is a +UserComment and `E010E` an ImageDescription in the pointed-at table, and `G0001` is GPSLatitudeRef in a GPS table. + +`golden.sh` regenerates both golden files: it has the tests write each input, runs exiftool over them with +`golden.cs`, and writes the counts as text. No media is committed. `ReaderModel_ShowsWhatExiftoolShows_ForEveryProbe` +and `..._ForEveryMatrixInput` fail when the model and exiftool differ on any input. + +## Which tables are read + +| rule | probe | exiftool | +|------|-------|----------| +| IFD0 and its next chain, and the Exif (0x8769), SubIFD (0x014A) and interoperability (0xA005) IFDs any of them names, are read with Exif tags and their pointers followed | `pointer 8769 in IFD0 type 4 count 1 LE`, `... in ExifIFD ...`, `... in InteropIFD ...`, `... in SubIFD ...`, `... in IFD1 ...` | `E010E=1 E9286=1` each | +| A GPS IFD (0x8825) is read with GPS tags | `pointer 8825 in IFD0 type 4 count 1 LE` | `G0001=1` | +| Nothing inside a GPS IFD is followed | `pointer 8769 in GPS type 4 count 1 LE` (and `A005`, `8825`, `014A`) | `-` | +| The next IFD of an Exif, interoperability, SubIFD or GPS table is not read; IFD1's is | `next IFD of ExifIFD`, `... InteropIFD`, `... SubIFD`, `... GPS`, `... IFD1` | `-`, `-`, `-`, `G0001=1` (the GPS table only), `E9286=1` | +| A classic table is read when 0, 2 or 4 bytes of its next-IFD field are present, and dropped when 1 or 3 are | measured for IFD0, IFD1 and the Exif, GPS and interoperability IFDs (exiftool 13.55); size pinned by the TIFF size tests | read for 0, 2 and 4; dropped for 1 and 3 | + +The field editor is stricter than that read. It refuses a field edit when 1, 2 or 3 bytes of a classic next-IFD field are present, and it still edits when the next field is wholly absent. `Clear` does not use this rule. A strip, tile or thumbnail array that does not lie wholly in the data is refused on its own, before the value budget. A first entry whose format would change whether exiftool reads the table is refused even when the change shows no new tag. + +## How a pointer is decoded + +| rule | probe | exiftool | +|------|-------|----------| +| Followed types: BYTE, SHORT, LONG, SSHORT, SLONG, IFD, and UNDEFINED with count 1 | `pointer 8769 in IFD0 type T count 1 LE` for T in 0-11, 13, 16 | read for 1, 3, 4, 7, 8, 9, 13; `-` for 0, 2, 5, 6 (value 200 is negative as SBYTE), 10, 11, 16 | +| SBYTE is followed when its value is not negative | `pointer 8769 SBYTE 100 LE` | `E010E=1 E9286=1` | +| An Exif IFD pointer needs count 1 | `pointer 8769 type 3 values 2 LE`, `pointer 8769 LONG array of 2 LE` | `-` | +| A GPS or interoperability pointer uses its first value only | `pointer A005 type 3 values 3 LE`, `pointer 8825 LONG array of 2 LE` | `E9286=1`, `G0001=1` | +| SubIFDs use every value, inline or out of line | `pointer 014A type 3 values 3 LE`, `pointer 014A LONG array of 2 LE` | `E9286=3`, `E9286=2` | +| UNDEFINED with count 2 names nothing | `pointer 014A in IFD0 type 7 count 2 LE` | `-` | +| Negative, zero, header and end-of-data offsets name nothing | `pointer value SBYTE negative`, `... SSHORT negative`, `... SLONG negative`, `... LONG 0`, `... SHORT 0`, `... LONG into the header`, `... LONG at the data's end` | `-` | +| An out-of-line SubIFD array inside its own table names nothing | `a SubIFD array inside its own table`, `a SubIFD array after its own table` | `-`, `E9286=1` | + +| Two pointer arrays at one offset, one count, different types, are each read by their type | pinned by `ExifEditTests.Edit_TwoPointerArraysAtOneOffset_AreEachReadByTheirOwnType` | both | + +## The order tables are read in, and tables reached twice + +| rule | probe | exiftool | +|------|-------|----------| +| Depth first, in entry order; IFD0's next IFD after IFD0's subdirectories | `Exif in depth before IFD0's GPS`, `IFD0's GPS before IFD1's Exif` | `E9286=1`, `G0001=1` | +| A table is read once, in the first kind it is reached as | `GPS first, then Exif`, `Exif first, then GPS`, `IFD1 is the Exif IFD`, `the Exif IFD is IFD0`, and every `, then ` pair | the first kind's tags only | +| ... except that a table first read as interoperability is read again as GPS | `Interop, then GPS` | `E9286=1 G0001=1` | +| An interoperability IFD's own pointers are followed | `an Interop IFD's Interop and Exif IFDs` | `E9286=2` | + +## Entries and values + +| rule | probe | exiftool | +|------|-------|----------| +| An entry of type 0 or 14 and above is skipped | `type 0 in the middle`, `type 19 last`, `type 255 in the middle` | the other entries are read | +| A table whose first entry has such a type is dropped whole | `type 0 first`, `type 14 first` ... `type 255 first` | `-` | +| The same drop, for a first entry of type 0 or 14, in IFD0, IFD1, an Exif IFD, a SubIFD, an interoperability IFD and a GPS IFD. A later type-14 entry in each is skipped. Both byte orders do this (the probes are little-endian; the editor tests pin both) | `IFD0 type 0 first`, `IFD0 type 14 first`, `IFD0 type 14 later`, and the same three for `IFD1`, `Exif`, `SubIFD`, `Interop` and `GPS` | `-` when the bad format is first; `E010E=1`, or `G0001=1` for GPS, when it is later | +| An empty IFD0 is read and its next IFD is followed. An IFD0 whose first entry is type 0 is dropped and its next IFD is not | `the chain after an empty IFD0`, `the chain after an IFD0 whose first entry is type 0` | `E010E=1`, `-` | +| A dropped main table ends the chain | `the chain after a table dropped for its first entry` | `-` | +| An out-of-line value is hidden when its offset is under 8 | `value of 8 at 0 by IFD0 at 100` ... `at 7`, `value of 8 at 8 by IFD0 at 100` | `-`, `E9286=1` | +| ... or when it overlaps its own table's count and entries (not the next offset) | `value at 41 by an Exif IFD at 40 to 70`, `... at 65`, `... at 66`, `... at 70` | `-`, `-`, `E9286=1`, `E9286=1` | +| ... or when it runs past the data | `value at 395 by an Exif IFD at 40 to 70` | `-` | +| A value inside another table is shown | `value inside the parent table`, `value inside a child table` | `E9286=1` | +| A table is read only up to its 11th warning (an unknown format other than 0, a value past the data, a suspicious value; counted per table), when entries follow it | `10 unknown formats before the UserComment`, `11 unknown formats ...`, `11 values past the data ...`, `11 values in the header ...`, `11 values inside their own table ...` | `E9286=1`, then `-` for each 11 | +| Type 0 entries and tags out of sequence do not count | `11 entries of type 0 ...`, `11 tags out of sequence ...` | `E9286=1` | +| The count is per table | `6 warnings in IFD0 and 6 in the Exif IFD` | `E9286=1` | +| A stopped IFD0 follows no later pointer and no next IFD; an 11th warning on the last entry stops nothing | `IFD0 stopped before its Exif IFD pointer`, `IFD0 stopped, then its next IFD`, `IFD0's 11th warning on its last entry, then its next IFD` | `-`, `-`, `E9286=1` | + +## Other readers + +Measured on the same probes wrapped in JPEG (`TagLib.File.Create` 2.3.0 run as a black box; ImageIO's +`CGImageSourceCopyPropertiesAtIndex`, which needs a decodable JPEG, so for it each probe replaced the Exif of a real +photo); not in the golden files, since neither tool is part of this repository. + +| rule | measured on | result | +|------|-------------|--------| +| TagLib# reads IFD0's 0x8769 and 0x8825 as the 4-byte field taken as a LONG, whatever the type and count | every `pointer 8769 in IFD0 type T count C` probe, and GPS probes of each type and count 0-2 | it follows type 0, 2, 5, 10, 11, 16 and count 0 or 2 when that LONG names a table, and no SHORT whose LONG does not | +| TagLib# follows no Exif or GPS pointer outside IFD0 | the `in ExifIFD`, `in InteropIFD`, `in SubIFD`, `in IFD1` probes | not followed | +| TagLib# reads a UserComment of a type exiftool skips | `a UserComment of type 0`, `... 12`, `... 14` to `... 19`, `... 255`, `type 14 first` ... | shown (not types 1 or 13); ImageIO shows only type 7 | +| ImageIO shows a UserComment exiftool does not only from a table exiftool drops for its first entry's format, or reads as GPS first and Exif after; every reader view used here reads both | the 1,656 pointer, value, format and order probes | 43 shown by both, 10 by ImageIO only (`type 0 first` ... `type 255 first`, `GPS first, then Exif`, `GPS, then Exif`), 318 by exiftool only | +| No reader reads the next IFD of an Exif IFD | an Exif IFD whose next IFD holds DateTimeOriginal and a UserComment | none of exiftool, TagLib#, ImageIO | diff --git a/tools/exif/golden.cs b/tools/exif/golden.cs new file mode 100755 index 00000000..99b1ba6c --- /dev/null +++ b/tools/exif/golden.cs @@ -0,0 +1,90 @@ +#!/usr/bin/env dotnet +#:property PublishAot=false +#:property NoWarn=$(NoWarn);CA1308;CA1031;CA1303;CA1305;CA1307;CA1310;CA1515;CA1812;CA1849;CA2007;CA5394;CS1591 +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +// Records what exiftool shows for every Exif input the tests generate. Usage: golden.cs +// holds NNNNN.tif files (raw TIFF) written by the tests' dump mode (see golden.sh). Each is wrapped in a +// JPEG APP1 segment, exiftool reads them all, and the golden file gets one summary per input, in order: the field tags +// shown in tables read with Exif tags ("E" and the tag in hex) and GPSLatitudeRef in GPS tables ("G0001"), counted. +// The summaries are stored once each and the inputs refer to them by number, with the inputs' SHA-256 to catch drift. +using System.Diagnostics; +using System.Security.Cryptography; +using System.Text; +using System.Text.RegularExpressions; + +var dump = args[0]; +var output = args[1]; +var tiffs = Directory.GetFiles (dump, "*.tif").OrderBy (f => f, StringComparer.Ordinal).ToArray (); +var jpegs = Path.Combine (Path.GetTempPath (), "exif-golden-" + Guid.NewGuid ().ToString ("N")); +Directory.CreateDirectory (jpegs); +using var sha = IncrementalHash.CreateHash (HashAlgorithmName.SHA256); +foreach (var path in tiffs) { + var tiff = File.ReadAllBytes (path); + sha.AppendData (tiff); + var app1 = new byte[6 + tiff.Length]; + "Exif\0\0"u8.CopyTo (app1); + tiff.CopyTo (app1, 6); + using var jpeg = new MemoryStream (); + jpeg.Write ([0xFF, 0xD8, 0xFF, 0xE1, (byte)((app1.Length + 2) >> 8), (byte)(app1.Length + 2)]); + jpeg.Write (app1); + jpeg.Write ([0xFF, 0xD9]); + File.WriteAllBytes (Path.Combine (jpegs, Path.GetFileNameWithoutExtension (path) + ".jpg"), jpeg.ToArray ()); +} + +int[] fieldTags = [0x9286, 0x9C9B, 0x9C9C, 0x9C9D, 0x010E, 0x013B, 0x8298]; +var counts = new Dictionary> (); +var start = new ProcessStartInfo ("exiftool", ["-a", "-G1", "-H", "-s", "-U", "-EXIF:All", jpegs]) { RedirectStandardOutput = true, RedirectStandardError = true }; +using (var exiftool = Process.Start (start)!) { + _ = exiftool.StandardError.ReadToEndAsync (); + string? current = null; + while (exiftool.StandardOutput.ReadLine () is string line) { + var file = Regex.Match (line, @"^======== .*[/\\](\d+)\.jpg$"); + if (file.Success) { + current = file.Groups[1].Value; + counts[current] = new (StringComparer.Ordinal); + continue; + } + + var tag = Regex.Match (line, @"^\[(\w+)\]\s+0x([0-9a-f]{4}) "); + if (current is null || !tag.Success) + continue; + var group = tag.Groups[1].Value; + var id = Convert.ToInt32 (tag.Groups[2].Value, 16); + var key = group.StartsWith ("GPS", StringComparison.Ordinal) ? (id == 0x0001 ? "G0001" : null) + : Array.IndexOf (fieldTags, id) >= 0 ? "E" + id.ToString ("X4") : null; + if (key is not null) + counts[current][key] = counts[current].GetValueOrDefault (key) + 1; + } + + exiftool.WaitForExit (); +} + +var version = Process.Start (new ProcessStartInfo ("exiftool", ["-ver"]) { RedirectStandardOutput = true })!.StandardOutput.ReadToEnd ().Trim (); +var summaries = new List (); +var sequence = new List (); +foreach (var path in tiffs) { + var name = Path.GetFileNameWithoutExtension (path); + var summary = counts.TryGetValue (name, out var c) && c.Count > 0 ? string.Join (" ", c.Select (p => $"{p.Key}={p.Value}")) : "-"; + var index = summaries.IndexOf (summary); + if (index < 0) { + index = summaries.Count; + summaries.Add (summary); + } + + sequence.Add (index); +} + +var text = new StringBuilder (); +text.Append ($"# What exiftool {version} shows for each generated input; regenerate with tools/exif/golden.sh.\n"); +text.Append ($"# inputs {tiffs.Length} sha256 {Convert.ToHexString (sha.GetHashAndReset ()).ToLowerInvariant ()}\n"); +text.Append ("@summaries\n"); +for (var n = 0; n < summaries.Count; n++) + text.Append ($"{n} {summaries[n]}\n"); +text.Append ("@inputs\n"); +for (var n = 0; n < sequence.Count; n += 40) + text.Append (string.Join (" ", sequence.Skip (n).Take (40))).Append ('\n'); +File.WriteAllText (output, text.ToString ()); +Directory.Delete (jpegs, recursive: true); +Console.WriteLine ($"{tiffs.Length} inputs, {summaries.Count} distinct summaries -> {output}"); diff --git a/tools/exif/golden.sh b/tools/exif/golden.sh new file mode 100755 index 00000000..4c8eb641 --- /dev/null +++ b/tools/exif/golden.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Copyright (c) 2025-2026 Stephen Shaw and contributors +# Licensed under the MIT License. See LICENSE file in the project root for full license information. +# +# Regenerates the exiftool golden files the Exif reader tests check against: +# tests/TagLibSharp2.Tests/Image/Golden/exif-reader-probes.txt (the probes of each reading rule) +# tests/TagLibSharp2.Tests/Image/Golden/exif-edit-matrix.txt (every input of the Exif edit matrix) +# The tests write their inputs when TAGLIBSHARP2_EXIF_GOLDEN_DUMP names a directory; golden.cs runs exiftool over them. +# Needs exiftool on PATH. Text only: no media is written to the repository. +set -euo pipefail +root=$(git rev-parse --show-toplevel) +dump=$(mktemp -d) +trap 'rm -rf "$dump"' EXIT +TAGLIBSHARP2_EXIF_GOLDEN_DUMP="$dump" dotnet test "$root/tests/TagLibSharp2.Tests" -c Release -f net10.0 \ + --filter "FullyQualifiedName~ExifReaderGoldenTests" > /dev/null || true +for set in probes matrix; do + name=$([[ $set == probes ]] && echo exif-reader-probes || echo exif-edit-matrix) + dotnet "$root/tools/exif/golden.cs" "$dump/$set" "$root/tests/TagLibSharp2.Tests/Image/Golden/$name.txt" +done