diff --git a/CHANGELOG.md b/CHANGELOG.md index 52d44dd8..e8175cee 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). - Limits: a save loads the whole file (about the file's size in memory when nothing moves, twice that when data moves), so AVI files of 2 GiB or more cannot be saved yet. `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. DNG, and a TIFF whose first image is a reduced-resolution preview, report the full-resolution 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`. Saving 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. 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 IFD0 and from every Exif IFD an IFD0 entry points at (ImageIO merges them, exiftool lists each), and their old bytes are zeroed unless the TIFF header, an IFD table (of IFD0, every Exif, GPS and interoperability IFD, IFD1), another entry's value, or the thumbnail, strip or tile data shares them, or an offset/length pair is given twice (then nothing is zeroed); each IFD table is walked once however many entries point at it, so the work is linear-logarithmic in the entries; a pointer (IFD0, Exif, GPS, interoperability, IFD1) whose table is not inside the data is skipped, as readers skip it; IFD tables that overlap beyond the data refuse the save, before any is walked; and the `Artist` and ImageMagick `exif:*` text keywords are dropped. 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, a value XML cannot hold, an Exif block that is not TIFF, 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. 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 scan, 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) 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..e9d03887 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 (`ImageMirrors.KeepAppleHeadroom`); 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. diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index 42478ab3..d87a9363 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -2,11 +2,11 @@ > Generated: January 2026 > Last Updated: January 2026 (v0.5.0 release) -> 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). Matroska/WebM saves tag values; it does not rewrite attachments or chapters. AVI saves INFO and ID3v2 tags; saving loads the whole file, so files of 2 GiB or more cannot be saved yet. +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. EXIF, IPTC, XMP, and SVG metadata are 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. AVI saves INFO and ID3v2 tags; saving loads the whole file, so files of 2 GiB or more cannot be saved yet. --- @@ -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. Saves load the whole file (under 2 GiB) | +| JPEG, PNG, GIF, BMP, PCX, Netpbm, TIFF, DNG, SVG | P2 | ✅ | Dimensions | PNG text, GIF comment, JPEG COM | - | Other image 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/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 c2f5caf4..214b38c7 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; } @@ -623,6 +632,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}" : "")}") }; @@ -747,6 +758,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 (); @@ -770,6 +786,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 }; } @@ -946,6 +971,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); @@ -1137,5 +1184,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/ImageGainMap.cs b/src/TagLibSharp2/Image/ImageGainMap.cs new file mode 100644 index 00000000..bf2ddbb5 --- /dev/null +++ b/src/TagLibSharp2/Image/ImageGainMap.cs @@ -0,0 +1,476 @@ +// 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 stack = new List (); + List>? items = null; + Dictionary? item = null; + var directoryDone = false; + while (reader.Read ()) { + Steps++; + switch (reader.NodeType) { + case XmlNodeType.Element: { + var parent = stack.Count > 0 ? stack[^1] : null; + var frame = Classify (reader, parent, found, directoryDone); + if (frame.Role == Role.Description) + ReadAttributes (reader, found.Values); + if (frame.Role == Role.Directory) + items = []; + if (frame.Role == Role.DirectoryLi && items is not null) { + item = []; + items.Add (item); + } + + if (frame.Role is Role.ItemNode or Role.ItemDescription && item is not null) { + item[ItemSeen] = ""; + ReadItemAttributes (reader, 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, item, ref items, ref directoryDone); + else + stack.Add (frame); + break; + } + + case XmlNodeType.Text: + case XmlNodeType.CDATA: + case XmlNodeType.SignificantWhitespace: + case XmlNodeType.Whitespace: + if (stack.Count > 0 && stack[^1].Role is Role.Property or Role.PropertyLi or Role.ItemField) { + var top = stack[^1]; + top.Text ??= new StringBuilder (); + if (top.Text.Length <= 64) + top.Text.Append (reader.Value); + } + + break; + + case XmlNodeType.EndElement: { + var frame = stack[^1]; + stack.RemoveAt (stack.Count - 1); + Close (frame, stack, found, item, ref items, ref directoryDone); + break; + } + } + } + } + + 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 (" (); + 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. + foreach (var property in Properties) { + var key = Key (property.Prefix, property.Name); + if (property.Ns is Hdrgm or Camera && found.Values.TryGetValue (key, out var values) && values.Count == 1) + builder.Append (' ').Append (key).Append ("=\"").Append (Escape (values[0])).Append ('"'); + } + + builder.Append ('>'); + foreach (var property in Properties) { + var key = Key (property.Prefix, property.Name); + if (!found.Values.TryGetValue (key, out var values) || (property.Ns is Hdrgm or Camera && values.Count == 1)) + 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 ("'); + } + + if (found.Items is not null) { + builder.Append (""); + foreach (var item in found.Items) { + builder.Append (""); + } + + builder.Append (""); + } + + builder.Append (""); + return builder.ToString (); + } + + 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..6e266a47 --- /dev/null +++ b/src/TagLibSharp2/Image/ImageHeader.cs @@ -0,0 +1,1107 @@ +// 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; + +/// +/// Container headers for the still-image formats. Dimensions come from the +/// container, not from EXIF. JPEG SOF is ITU-T T.81. PNG IHDR is the PNG +/// specification. GIF is the logical screen in GIF89a. BMP is the DIB header. +/// PCX is the ZSoft window. Netpbm is the P1-P6 raster header. TIFF and DNG +/// width and height are IFD tags 256 and 257. A reduced-resolution IFD yields +/// to a full-resolution SubIFD. DNG is TIFF plus tag 50706. +/// SVG uses the root width and height, or the viewBox. +/// +internal static class ImageHeader +{ + const int DngVersionTag = 0xC612; + + public static bool TryDetect (ReadOnlySpan data, out MediaFormat format) + { + format = MediaFormat.Unknown; + if (IsJpeg (data)) { + format = MediaFormat.Jpeg; + return true; + } + + if (IsPng (data)) { + format = MediaFormat.Png; + return true; + } + + if (IsGif (data)) { + format = MediaFormat.Gif; + return true; + } + + if (IsBmp (data)) { + format = MediaFormat.Bmp; + return true; + } + + if (IsPcx (data)) { + format = MediaFormat.Pcx; + return true; + } + + if (IsNetpbm (data)) { + format = MediaFormat.Netpbm; + return true; + } + + if (IsTiff (data)) { + format = HasDngVersion (data) ? MediaFormat.Dng : MediaFormat.Tiff; + return true; + } + + if (IsSvg (data)) { + format = MediaFormat.Svg; + return true; + } + + return false; + } + + public static bool TryRead (ReadOnlySpan data, MediaFormat format, out ImageProperties? properties) + { + properties = null; + return format switch { + MediaFormat.Jpeg => TryJpeg (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 => TryTiff (data, dng: false, out properties), + MediaFormat.Dng => TryTiff (data, dng: true, out properties), + MediaFormat.Svg => TrySvg (data, out properties), + _ => false + }; + } + + static bool IsJpeg (ReadOnlySpan data) => + data.Length >= 3 && data[0] == 0xFF && data[1] == 0xD8 && data[2] == 0xFF; + + static bool TryJpeg (ReadOnlySpan data, out ImageProperties? properties) + { + properties = null; + if (!IsJpeg (data)) + return false; + + var i = 2; + var waitingForDnl = false; + var pendingWidth = 0; + var precision = 0; + var components = 1; + 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; + + var 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; + + var length = (data[i] << 8) | data[i + 1]; + if (length < 2 || i + length > data.Length) + return false; + + if (IsStartOfFrame (marker)) { + if (length < 7) + return false; + precision = data[i + 2]; + var height = (data[i + 3] << 8) | data[i + 4]; + var width = (data[i + 5] << 8) | data[i + 6]; + if (width <= 0 || height < 0) + return false; + components = 1; + if (length >= 8) { + var count = data[i + 7]; + if (count is >= 1 and <= 4) + components = count; + } + + if (height > 0) { + properties = JpegSize (width, height, precision, components); + 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. + pendingWidth = width; + waitingForDnl = true; + i += length; + continue; + } + + if (marker == 0xDA) { + if (!waitingForDnl || !TryDnlHeight (data, i + length, out var lines)) + return false; + properties = JpegSize (pendingWidth, lines, precision, components); + return true; + } + + i += length; + } + + return false; + } + + // 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 = (data[i] << 8) | data[i + 1]; + if (length != 4) + return false; + lines = (data[i + 2] << 8) | data[i + 3]; + return lines > 0; + } + + return false; + } + + static ImageProperties JpegSize (int width, int height, int precision, int components) + { + var depth = precision; + if (components is >= 1 and <= 4 && precision <= int.MaxValue / components) + depth = precision * components; + return new ImageProperties (width, height, depth, "JPEG"); + } + + 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; + + // 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 = ReadBe32 (data, 16); + var height = ReadBe32 (data, 20); + 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 = data[6] | (data[7] << 8); + var height = data[8] | (data[9] << 8); + 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 = ReadLe32 (data, 14); + int width; + int height; + var depth = 0; + if (header == 12) { + if (data.Length < 26) + return false; + width = data[18] | (data[19] << 8); + height = data[20] | (data[21] << 8); + depth = data[24] | (data[25] << 8); + } else if (header >= 16 && data.Length >= 26) { + width = ReadLe32 (data, 18); + var rawHeight = ReadLe32 (data, 22); + if (rawHeight == int.MinValue) + return false; + height = rawHeight < 0 ? -rawHeight : rawHeight; + if (data.Length >= 30) + depth = data[28] | (data[29] << 8); + } 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 = data[4] | (data[5] << 8); + var ymin = data[6] | (data[7] << 8); + var xmax = data[8] | (data[9] << 8); + var ymax = data[10] | (data[11] << 8); + 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; + } + + const int MaxTiffIfds = 4096; + const int MaxTiffDepth = 64; + const int NewSubFileTypeTag = 254; + const int SubIfdTag = 330; + + static bool IsTiff (ReadOnlySpan data) => + IsClassicTiff (data) || IsBigTiff (data); + + static bool IsClassicTiff (ReadOnlySpan data) => + data.Length >= 8 && ( + (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)); + + // BigTIFF: version 43, 8-byte offsets, 20-byte IFD entries. + static bool IsBigTiff (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)); + + static bool HasDngVersion (ReadOnlySpan data) => + TryTiff (data, dng: false, out var properties) && properties?.Format == "DNG"; + + static bool TryTiff (ReadOnlySpan data, bool dng, out ImageProperties? properties) + { + properties = null; + if (!TryTiffHeader (data, out var le, out var big, out var first)) + return false; + Span subs = stackalloc long[32]; + if (!TryReadIfd (data, first, le, big, subs, out _, out var root)) + return false; + + var sawDng = dng || root.SawDng; + int width; + int height; + if (dng || root.Reduced) { + if (!TryBestImage (data, first, le, big, out width, out height, out var deepDng)) + return false; + sawDng |= deepDng; + } else if (!root.HasSize) { + return false; + } else { + width = root.Width; + height = root.Height; + } + + if (width <= 0 || height <= 0) + return false; + + properties = new ImageProperties (width, height, 0, sawDng ? "DNG" : "TIFF"); + return true; + } + + static bool TryTiffHeader (ReadOnlySpan data, out bool le, out bool big, out long first) + { + le = false; + big = false; + first = 0; + if (!IsTiff (data)) + return false; + le = data[0] == (byte)'I'; + big = IsBigTiff (data); + if (!big) { + if (!TryU32 (data, 4, le, out var small)) + return false; + first = small; + return true; + } + + if (!TryU16 (data, 4, le, out var offsetSize) || offsetSize != 8) + return false; + if (!TryU16 (data, 6, le, out var reserved) || reserved != 0) + return false; + return TryU64 (data, 8, le, out first); + } + + // IFD0 of a DNG is often a reduced preview. The raw image is a SubIFD whose + // NewSubFileType bit 0 is clear. The walk is iterative: a file-controlled chain must not recurse. + static bool TryBestImage (ReadOnlySpan data, long first, bool le, bool big, out int width, out int height, out bool sawDng) + { + width = 0; + height = 0; + sawDng = false; + // A DNG or a reduced TIFF has a handful of IFDs, so the work stack and the visited set start on the + // stack and grow on the heap only when a file holds more. Detection reaches this for every DNG. + Span offsets = stackalloc long[SmallIfdCount]; + Span depths = stackalloc int[SmallIfdCount]; + Span visitedSmall = stackalloc long[SmallIfdCount]; + Dictionary? visited = null; + // The smallest IFD is a 2-byte count and a 4-byte next offset, so a file holds at most this many. + var room = (int)Math.Min (MaxTiffIfds, (data.Length / 6) + 1); + var sp = 0; + PushIfd (ref offsets, ref depths, ref sp, first, 0, room); + var seen = 0; + var have = false; + var bestReduced = true; + long bestArea = 0; + Span subs = stackalloc long[MaxSubIfds]; + while (sp > 0 && seen < MaxTiffIfds) { + sp--; + var offset = offsets[sp]; + var depth = depths[sp]; + if (!Visit (visitedSmall, ref visited, seen, offset, room)) + continue; + seen++; + if (!TryReadIfd (data, offset, le, big, subs, out var subCount, out var info)) + continue; + sawDng |= info.SawDng; + if (info.HasSize) { + var area = (long)info.Width * info.Height; + if (!have || (!info.Reduced && bestReduced) || (info.Reduced == bestReduced && area > bestArea)) { + width = info.Width; + height = info.Height; + bestReduced = info.Reduced; + bestArea = area; + have = true; + } + } + + if (depth >= MaxTiffDepth) + continue; + if (info.Next > 0) + PushIfd (ref offsets, ref depths, ref sp, info.Next, depth, room); + for (var s = subCount - 1; s >= 0; s--) + PushIfd (ref offsets, ref depths, ref sp, subs[s], depth + 1, room); + } + + return have; + } + + const int SmallIfdCount = 16; + const int MaxSubIfds = 32; + + // True the first time an offset is seen. The first SmallIfdCount offsets are kept in a stack span and + // scanned; past that one set is made, sized by the IFDs the file can hold. + static bool Visit (Span small, ref Dictionary? set, int seen, long offset, int room) + { + 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.Max (room, small.Length + 1)); + foreach (var known in small) + set[known] = true; + } + + if (set.ContainsKey (offset)) + return false; + set[offset] = true; + return true; + } + + static void PushIfd (ref Span offsets, ref Span depths, ref int sp, long offset, int depth, int room) + { + if (offset <= 0) + return; + if (sp >= offsets.Length) { + if (offsets.Length >= room) + return; + var size = room; + var grownOffsets = new long[size]; + var grownDepths = new int[size]; + offsets.CopyTo (grownOffsets); + depths.CopyTo (grownDepths); + offsets = grownOffsets; + depths = grownDepths; + } + + offsets[sp] = offset; + depths[sp] = depth; + sp++; + } + + readonly struct IfdInfo + { + public int Width { get; init; } + public int Height { get; init; } + public bool HasSize { get; init; } + public bool Reduced { get; init; } + public bool SawDng { get; init; } + public long Next { get; init; } + } + + /// IFDs read on this thread, for tests that bound the walk by an operation count. + [ThreadStatic] + internal static int IfdReads; + + static bool TryReadIfd (ReadOnlySpan data, long offset, bool le, bool big, Span subs, out int subCount, out IfdInfo info) + { + IfdReads++; + subCount = 0; + info = default; + if (offset < 0 || offset > int.MaxValue) + return false; + var word = big ? 8 : 4; + var entrySize = big ? 20 : 12; + var countSize = big ? 8 : 2; + var at = (int)offset; + if ((long)at + countSize > data.Length) + return false; + + long count; + if (big) { + if (!TryU64 (data, at, le, out count) || count > MaxTiffIfds) + return false; + } else if (!TryU16 (data, at, le, out var narrow) || narrow > MaxTiffIfds) { + return false; + } else { + count = narrow; + } + + var table = at + countSize; + var tableBytes = count * entrySize; + if (table > data.Length || tableBytes > (long)data.Length - table) + return false; + var nextAt = table + (int)tableBytes; + if ((long)nextAt + word > data.Length) + return false; + + var width = 0; + var height = 0; + var sawWidth = false; + var sawHeight = false; + var reduced = false; + var sawDng = false; + for (var n = 0; n < count; n++) { + var entry = table + (int)(n * entrySize); + if (!TryU16 (data, entry, le, out var tag) || !TryU16 (data, entry + 2, le, out var type)) + return false; + long valueCount; + int valueAt; + if (big) { + if (!TryU64 (data, entry + 4, le, out valueCount)) + return false; + valueAt = entry + 12; + } else if (!TryU32 (data, entry + 4, le, out var narrowCount)) { + return false; + } else { + valueCount = narrowCount; + valueAt = entry + 8; + } + + if (tag == DngVersionTag) + sawDng = true; + if (tag is 256 or 257 && valueCount == 1 && TryScalar (data, valueAt, type, le, word, out var scalar) && scalar is > 0 and <= int.MaxValue) { + if (tag == 256) { + width = (int)scalar; + sawWidth = true; + } else { + height = (int)scalar; + sawHeight = true; + } + } else if (tag == NewSubFileTypeTag && valueCount == 1 && TryScalar (data, valueAt, type, le, word, out var subfile)) { + reduced = (subfile & 1) != 0; + } else if (tag == SubIfdTag) { + ReadSubIfds (data, valueAt, type, valueCount, le, word, subs, ref subCount); + } + } + + long next; + if (word == 4) { + if (!TryU32 (data, nextAt, le, out var small)) + return false; + next = small; + } else if (!TryU64 (data, nextAt, le, out next)) { + return false; + } + + info = new IfdInfo { + Width = width, + Height = height, + HasSize = sawWidth && sawHeight, + Reduced = reduced, + SawDng = sawDng, + Next = next + }; + return true; + } + + static void ReadSubIfds (ReadOnlySpan data, int valueAt, int type, long valueCount, bool le, int word, Span subs, ref int subCount) + { + // Only the first subs.Length SubIFDs are followed: a DNG has one or two. + var size = type is 16 or 18 ? 8 : type is 4 or 13 ? 4 : 0; + if (size == 0 || valueCount <= 0) + return; + var bytes = valueCount * size; + int dataAt; + if (bytes <= word) { + dataAt = valueAt; + } else if (!TryUnsigned (data, valueAt, word, le, out var pointer) || pointer > int.MaxValue) { + return; + } else { + dataAt = (int)pointer; + } + + for (long n = 0; n < valueCount && subCount < subs.Length; n++) { + var at = dataAt + (int)(n * size); + if (!TryUnsigned (data, at, size, le, out var child)) + return; + if (child > 0) + subs[subCount++] = child; + } + } + + static bool TryScalar (ReadOnlySpan data, int valueAt, int type, bool le, int word, out long value) + { + value = 0; + var size = TypeSize (type); + if (size is not (2 or 4 or 8) || size > word) + return false; + return TryUnsigned (data, valueAt, size, le, out value); + } + + static int TypeSize (int type) => type switch { + 1 or 2 or 6 or 7 => 1, + 3 or 8 => 2, + 4 or 9 or 13 => 4, + 5 or 10 or 16 or 17 or 18 => 8, + _ => 0 + }; + + static bool TryUnsigned (ReadOnlySpan data, int offset, int size, bool le, out long value) + { + value = 0; + if (offset < 0 || (long)offset + size > data.Length) + return false; + if (size == 2) { + if (!TryU16 (data, offset, le, out var small)) + return false; + value = small; + return true; + } + + if (size == 4) { + if (!TryU32 (data, offset, le, out var medium)) + return false; + value = medium; + return true; + } + + return size == 8 && TryU64 (data, offset, le, out value); + } + + static bool TryU64 (ReadOnlySpan data, int offset, bool le, out long value) + { + value = 0; + if ((uint)offset + 7 >= (uint)data.Length) + return false; + ulong raw = 0; + if (le) { + for (var i = 0; i < 8; i++) + raw |= (ulong)data[offset + i] << (8 * i); + } else { + for (var i = 0; i < 8; i++) + raw = (raw << 8) | data[offset + i]; + } + + if (raw > long.MaxValue) + return false; + value = (long)raw; + return true; + } + + // Reads only until the first code unit that cannot start a prolog, so an audio buffer stops at byte 0. + static bool IsSvg (ReadOnlySpan data) => TrySvgRoot (new Markup (data), out _); + + static bool TrySvg (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] + : _bigEndian ? (_data[2 * index] << 8) | _data[(2 * index) + 1] : _data[2 * index] | (_data[(2 * index) + 1] << 8); + + /// 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; + var sawDigit = false; + var sawDot = false; + while (i < tag.Length) { + if (char.IsDigit (tag[i])) { + sawDigit = true; + i++; + } else if (tag[i] == '.' && !sawDot) { + sawDot = true; + i++; + } else { + break; + } + } + + 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; + } + } + + if (!sawDigit || i == start) + return false; + var unitStart = i; + while (i < tag.Length && char.IsLetter (tag[i])) + i++; + if (i < tag.Length && tag[i] == '%') + return false; +#if NETSTANDARD2_0 + if (!double.TryParse (tag.Substring (start, unitStart - start), NumberStyles.Float, CultureInfo.InvariantCulture, out var number)) +#else + if (!double.TryParse (tag.AsSpan (start, unitStart - start), NumberStyles.Float, CultureInfo.InvariantCulture, out var number)) +#endif + return false; + if (!TrySvgPixels (number, tag.Substring (unitStart, i - unitStart), out value)) + return false; + return quote == '\0' || (i < tag.Length && tag[i] == quote); + } + + 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 + } + + static bool TryU16 (ReadOnlySpan data, int offset, bool le, out int value) + { + value = 0; + if ((uint)offset + 1 >= (uint)data.Length) + return false; + value = le ? data[offset] | (data[offset + 1] << 8) : (data[offset] << 8) | data[offset + 1]; + return true; + } + + static bool TryU32 (ReadOnlySpan data, int offset, bool le, out int value) + { + value = 0; + if ((uint)offset + 3 >= (uint)data.Length) + return false; + value = le ? ReadLe32 (data, offset) : ReadBe32 (data, offset); + return value >= 0; + } + + static int ReadBe32 (ReadOnlySpan data, int offset) => + (data[offset] << 24) | (data[offset + 1] << 16) | (data[offset + 2] << 8) | data[offset + 3]; + + static int ReadLe32 (ReadOnlySpan data, int offset) => + data[offset] | (data[offset + 1] << 8) | (data[offset + 2] << 16) | (data[offset + 3] << 24); + + static bool IsSpace (byte value) => value is (byte)' ' or (byte)'\t' or (byte)'\r' or (byte)'\n'; +} diff --git a/src/TagLibSharp2/Image/ImageMirrors.cs b/src/TagLibSharp2/Image/ImageMirrors.cs new file mode 100644 index 00000000..79085eca --- /dev/null +++ b/src/TagLibSharp2/Image/ImageMirrors.cs @@ -0,0 +1,1243 @@ +// 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.IO.Compression; +using System.Text; +using System.Xml; + +namespace TagLibSharp2.Image; + +/// +/// The copies of a PNG text field that other blocks of the same file hold. macOS ImageIO shows the XMP +/// (dc:title, dc:creator, dc:description, dc:rights) and the Exif IFD0 values +/// (ImageDescription, Artist, Copyright) in preference to 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. +/// +static class ImageMirrors +{ + internal const string DcNamespace = "http://purl.org/dc/elements/1.1/"; + internal const string ExifNamespace = "http://ns.adobe.com/exif/1.0/"; + const string RdfNamespace = "http://www.w3.org/1999/02/22-rdf-syntax-ns#"; + + internal static readonly MirrorField[] Fields = [ + 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"]), + ]; + + /// A text keyword that copies a mapped field (ImageMagick writes these as plain tEXt). + internal static bool IsMirrorKeyword (string keyword, ImageTag tag) + { + foreach (var field in Fields) { + if (!tag.Changed (field.Store)) + continue; + foreach (var text in field.Text) { + if (string.Equals (text, keyword, StringComparison.Ordinal)) + return true; + } + } + + return false; + } + + internal static bool AnyChanged (ImageTag tag) + { + foreach (var field in Fields) { + if (tag.Changed (field.Store)) + return true; + } + + return false; + } + + /// Characters the XMP splice has written on this thread, for tests that pin it to one pass. + [ThreadStatic] + internal static long SpliceWrites; + + /// + /// 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 byte of the packet is kept. + /// + /// 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 TryUpdateXmp (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] == '\uFEFF') { + if (!TryUpdateXmp (packet.Substring (1), tag, carrier, out var body, out error)) { + updated = packet; + return false; + } + + updated = body.Length == packet.Length - 1 && string.CompareOrdinal (body, 0, packet, 1, body.Length) == 0 ? packet : "\uFEFF" + body; + return true; + } + + // 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)) { + if (!TryUpdateXmp (packet.Substring (0, last + 1), tag, carrier, out var head, out error)) { + updated = packet; + return false; + } + + updated = head.Length == last + 1 && string.CompareOrdinal (head, 0, packet, 0, head.Length) == 0 ? packet : Join (head, packet, last + 1); + return true; + } + + updated = packet; + error = null; + var edits = new List (); + if (!TryFindXmpProperties (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 && !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; + } + + if (!keep) { + // Removed: an attribute takes the white space before it with it. + Append (builder, packet, at, edit.Attribute ? edit.LeadStart : edit.Start); + at = edit.End; + continue; + } + + Append (builder, packet, at, edit.Start); + if (edit.Attribute) { + Write (builder, $"{edit.Name}=\"{EscapeXml (value!, attribute: true)}\""); + } else { + // 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); + } + + at = edit.End; + } + + Append (builder, packet, at, packet.Length); + updated = builder.ToString (); + if (!IsWellFormed (updated)) { + error = $"The {carrier} could not be updated: the edited packet is not well-formed XML."; + return false; + } + + return true; + } + + 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' && !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 = 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=\"{RdfNamespace}\"" : ""; + return edit.Field.Ordered + ? $"<{rdf}Seq{declare}><{rdf}li>{item}" + : $"<{rdf}Alt{declare}><{rdf}li xml:lang=\"x-default\">{item}"; + } + + static bool TryFindXmpProperties (string packet, ImageTag tag, string carrier, List edits, out string? error) + { + error = null; + var lines = 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); + 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) + continue; + var field = FieldFor (reader.NamespaceURI, reader.LocalName, tag); + if (field is null) + continue; + if (!TryElementEdit (packet, lines, reader, info, field, out var edit)) { + error = $"The {carrier} holds {field.Name}, and the property could not be located in the packet text, so the copy there cannot be updated."; + return false; + } + + edits.Add (edit!); + } + } catch (XmlException ex) { + error = $"The {carrier} is not well-formed XML ({ex.Message}), so its copy of a changed field cannot be updated."; + return false; + } + + return true; + } + + 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 = $"The {carrier} holds {field.Name}, and the property could not be located in the packet text, so the copy there cannot be updated."; + 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 = Offset (lines, info.LineNumber, info.LinePosition); + lead = start; + var name = reader.Name; + if (start < 0 || !At (packet, start, name) || !TryAttributeEnd (packet, start + name.Length, out end)) + return false; + while (lead > 0 && IsXmlSpace (packet[lead - 1])) + lead--; + return true; + } + + static readonly string[] ContradictingRdfAttributes = ["resource", "parseType", "datatype", "nodeID"]; + + static bool TryElementEdit (string packet, int[] lines, XmlReader reader, IXmlLineInfo info, MirrorField field, out XmpEdit? edit) + { + edit = null; + var name = reader.Name; + var nameAt = Offset (lines, info.LineNumber, info.LinePosition); + var start = nameAt - 1; + if (start < 0 || packet[start] != '<' || !At (packet, nameAt, name) || !TryTagEnd (packet, nameAt + name.Length, out var startTagEnd)) + return false; + var rdfPrefix = (reader as IXmlNamespaceResolver)?.LookupPrefix (RdfNamespace); + var empty = reader.IsEmptyElement; + var cuts = new List<(int, int)> (); + if (reader.MoveToFirstAttribute ()) { + 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 (); + } + + if (empty) { + // "": the start tag is kept up to the "/". + var slash = startTagEnd - 2; + if (packet[slash] != '/') + return false; + edit = new XmpEdit (field, name, attribute: false) { + Start = start, + StartTagEnd = slash, + ContentEnd = startTagEnd, + End = startTagEnd, + Empty = true, + RdfPrefix = rdfPrefix, + Cuts = cuts + }; + return true; + } + + var depth = reader.Depth; + while (reader.Read ()) { + if (reader.NodeType != XmlNodeType.EndElement || reader.Depth != depth) + continue; + var closeAt = Offset (lines, info.LineNumber, info.LinePosition); + if (closeAt < 2 || packet[closeAt - 2] != '<' || packet[closeAt - 1] != '/' || !At (packet, closeAt, name) || !TryTagEnd (packet, closeAt + name.Length, out var end)) + return false; + edit = new XmpEdit (field, name, attribute: false) { + Start = start, + StartTagEnd = startTagEnd, + ContentEnd = closeAt - 2, + End = end, + RdfPrefix = rdfPrefix, + Cuts = cuts + }; + return true; + } + + return false; + } + + static MirrorField? FieldFor (string ns, string localName, ImageTag tag) + { + foreach (var field in Fields) { + if (tag.Changed (field.Store) && field.XmpNamespace == ns && field.XmpName == localName) + return field; + } + + return null; + } + + // IXmlLineInfo counts a line break as CR LF, CR or LF (XML 1.0 §2.11) and columns from 1. + 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]; + } + + 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; + } + + 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. + 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; + } + + 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; + } + + static bool IsXmlSpace (char c) => c is ' ' or '\t' or '\r' or '\n'; + + 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. + 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; + } + + 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 (); + } + + /// + /// Removes each changed field's Exif entries from IFD0 and from every Exif IFD an IFD0 0x8769 entry points at + /// (each table once; ImageIO merges them and exiftool lists each, so a copy in any of them would still show). + /// The entry table shrinks in place, so no offset moves. A removed value is zeroed only where its bytes belong + /// to it alone: past the header, outside every IFD table (IFD0, every Exif, GPS and interoperability IFD, + /// IFD1), and outside every kept entry's value and the data every offset/length pair names; when a pair is + /// given twice, nothing is zeroed. Otherwise the entry is removed and its bytes are left, unreachable. + /// + /// False, with an error, when the block is not classic TIFF, or when IFD tables overlap beyond what + /// the data holds. A pointer (IFD0, Exif, GPS, interoperability, IFD1) whose table is not inside the data is + /// skipped: no reader follows it, so it holds no copy. + internal static bool TryRemoveExif (byte[] tiff, int start, ImageTag tag, string carrier, out bool changed, out string? error) + { + changed = false; + error = null; + var ifd0Tags = new List (); + var exifTags = new List (); + var names = new List (); + foreach (var field in Fields) { + if (!tag.Changed (field.Store)) + continue; + ifd0Tags.AddRange (field.Ifd0); + exifTags.AddRange (field.ExifIfd); + names.Add (field.Name); + } + + if (ifd0Tags.Count == 0 && exifTags.Count == 0) + return true; + var what = string.Join (", ", names); + + // 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. + if (!TryTiffHeader (tiff, start, out var le, out var ifd0)) { + error = $"The {carrier} block is not a TIFF structure, so its copy of {what} cannot be updated."; + return false; + } + + // An IFD0 whose table is not inside the data is read by no one (exiftool reports a bad IFD0 directory and + // reads none of it), and every other IFD is reached through it: there is no copy to update. + var tables = new List<(long At, int Count)> (); + if (!TryTable (tiff, start, ifd0, le, out var ifd0Count)) + return true; + + // Every table is walked once, however many entries point at it, and the removal tags of every role it has + // apply to it (an Exif IFD may be IFD0 itself). + var removeIn = new Dictionary> { [ifd0] = [.. ifd0Tags] }; + tables.Add ((ifd0, ifd0Count)); + + // Every Exif IFD an IFD0 0x8769 entry points at: ImageIO merges them and exiftool lists each, so a copy + // in any of them would still show. Each distinct table is taken once, however many entries point at it; + // a pointer whose table is not inside the data is skipped, as readers skip it (it can hold no copy). + var exifIfds = new CountedList (); + if (exifTags.Count > 0) { + var pointers = new CountedList (); + PointersIn (tiff, start, ifd0, ifd0Count, le, ExifIfdPointer, pointers); + var seen = new HashSet (); + for (var n = 0; n < pointers.Count; n++) { + var exifIfd = pointers[n]; + if (!seen.Add (exifIfd) || !TryTable (tiff, start, exifIfd, le, out var exifCount)) + continue; + exifIfds.Add (exifIfd); + if (!removeIn.TryGetValue (exifIfd, out var remove)) { + removeIn[exifIfd] = remove = []; + tables.Add ((exifIfd, exifCount)); + } + + remove.AddRange (exifTags); + } + } + + // Tables that do not overlap hold at most one entry per 12 bytes; more means hostile overlap, refused + // before any of them is walked (walking each would read the same bytes again and again). Refused rather + // than skipped: which of the overlapping tables a reader takes, and so which bytes may be zeroed, is unknown. + if (Overlap (tables, tiff.Length - start)) { + error = $"The {carrier} block has IFD tables that overlap each other, so its copy of {what} cannot be updated."; + return false; + } + + // Every other IFD a reader walks: IFD1 (the thumbnail), every GPS IFD, every interoperability IFD of every + // Exif IFD (each Exif IFD walked once). Their tables and values are kept, so they are protected from + // zeroing. A pointer whose table is not inside the data is not read by anyone and is skipped. + var others = new CountedList (); + others.Add (NextIfd (tiff, start, ifd0, ifd0Count, le)); + PointersIn (tiff, start, ifd0, ifd0Count, le, GpsIfdPointer, others); + for (var n = 0; n < exifIfds.Count; n++) { + _ = TryTable (tiff, start, exifIfds[n], le, out var exifCount); + PointersIn (tiff, start, exifIfds[n], exifCount, le, InteropIfdPointer, others); + } + + var walked = new HashSet (removeIn.Keys); + for (var n = 0; n < others.Count; n++) { + var other = others[n]; + if (other > 0 && walked.Add (other) && TryTable (tiff, start, other, le, out var count)) + tables.Add ((other, count)); + } + + if (Overlap (tables, tiff.Length - start)) { + error = $"The {carrier} block has IFD tables that overlap each other, so its copy of {what} cannot be updated."; + return false; + } + + // The header, every walked IFD table, every kept entry's value, and the data that offset/length pairs + // name (the IFD1 thumbnail, strips, tiles) are protected from zeroing. + var protectedRanges = new CountedList<(long Start, long End)> (); + protectedRanges.Add ((0, 8)); + var removedRanges = new CountedList<(long Start, long End)> (); + var removing = new Dictionary> (); + var ambiguous = false; + foreach (var (at, count) in tables) { + protectedRanges.Add ((at, at + 2 + (count * 12L) + 4)); + ambiguous |= !AddDataRanges (tiff, start, at, count, le, protectedRanges); + var remove = removeIn.TryGetValue (at, out var tags) ? tags : null; + for (var n = 0; n < count; n++) { + ExifSteps++; + var entry = start + (int)at + 2 + (n * 12); + var range = ValueRange (tiff, start, entry, le); + if (remove is not null && remove.Contains (ReadU16 (tiff, entry, le))) { + if (!removing.TryGetValue (at, out var marks)) + removing[at] = marks = CountedList.Filled (count); + marks[n] = true; + if (range.End > range.Start) + removedRanges.Add (range); + } else if (range.End > range.Start) { + protectedRanges.Add (range); + } + } + } + + if (removing.Count == 0) + return true; + changed = true; + foreach (var (at, count) in tables) { + if (removing.TryGetValue (at, out var marks)) + CompactTable (tiff, start, at, count, le, marks); + } + + // An offset/length pair given twice cannot be matched up, so which bytes the strips or thumbnail use is + // unknown: nothing is zeroed, and the removed values are left unreachable. + if (ambiguous) + return true; + + // One sort, then a binary search per removed value: linear-logarithmic in the entries, whatever their number. + var merged = Merge (protectedRanges); + for (var n = 0; n < removedRanges.Count; n++) { + var range = removedRanges[n]; + if (range.Start >= 8 && range.End <= tiff.Length - start && !Overlaps (merged, range)) + Array.Clear (tiff, start + (int)range.Start, (int)(range.End - range.Start)); + } + + return true; + } + + // More entries than the data holds when no two tables share bytes. + static bool Overlap (List<(long At, int Count)> tables, int length) + { + var entries = 0L; + foreach (var (_, count) in tables) { + ExifSteps++; + entries += count; + } + + return entries > length / 12; + } + + /// Steps of the Exif removal on this thread, for tests that bound it by an operation count. + [ThreadStatic] + internal static long ExifSteps; + + const int MakerNoteTag = 0x927C; + const int AppleHdrHeadroomTag = 0x0021; + const int AppleHdrGainTag = 0x0030; + const int SRationalType = 10; + + static ReadOnlySpan AppleMakerNoteHeader => "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[]? KeepAppleHeadroom (byte[] tiff, int start) + { + // A header that is not TIFF (byte order and magic 42) leaves IFD0 at 0, which TryTable refuses: no IFD can + // start inside the 8-byte header. So only the table check decides. + _ = TryTiffHeader (tiff, start, out var le, out var ifd0); + if (!TryTable (tiff, start, ifd0, le, out var ifd0Count)) + return null; + var length = tiff.Length - start; + var budget = length / 12; + var pointers = ExifIfdPointers (tiff, start, ifd0, ifd0Count, le); + + // 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. + var seen = new HashSet (); + long headroomAt = -1, headroomCount = 0, gainAt = -1, gainCount = 0; + for (var p = pointers.Count - 1; p >= 0 && (headroomAt < 0 || gainAt < 0); p--) { + var ifd = pointers[p]; + if (!seen.Add (ifd)) + continue; + _ = TryTable (tiff, start, ifd, le, out var count); + budget -= count; + if (budget < 0) + return null; + var (noteAt, noteSize) = LastMakerNote (tiff, start, ifd, count, le); + if (noteAt < 0 || noteSize < AppleMakerNoteHeader.Length + 2 || !tiff.AsSpan (start + (int)noteAt).StartsWith (AppleMakerNoteHeader)) + continue; + var span = tiff.AsSpan (start + (int)noteAt, (int)noteSize); + budget -= ReadU16 (span, AppleMakerNoteHeader.Length); + if (budget < 0) + return null; + var entries = HeadroomEntries (span); + if (headroomAt < 0 && entries.HeadroomAt >= 0) + (headroomAt, headroomCount) = (noteAt + entries.HeadroomAt, entries.HeadroomCount); + if (gainAt < 0 && entries.GainAt >= 0) + (gainAt, gainCount) = (noteAt + entries.GainAt, entries.GainCount); + } + + if (headroomAt < 0 || gainAt < 0 || headroomCount != 1 || gainCount != 1) + return null; + return AppleHeadroomTiff (tiff.AsSpan (start + (int)headroomAt, 8), tiff.AsSpan (start + (int)gainAt, 8)); + } + + // The Exif IFD pointers ImageIO follows: LONG or IFD, count 1, a table inside the data; in IFD0 order. + static CountedList ExifIfdPointers (byte[] tiff, int start, long ifd0, int ifd0Count, bool le) + { + var pointers = new CountedList (); + for (var n = 0; n < ifd0Count; n++) { + ExifSteps++; + var entry = start + (int)ifd0 + 2 + (n * 12); + if (ReadU16 (tiff, entry, le) != ExifIfdPointer || ReadU16 (tiff, entry + 2, le) is not (4 or 13) || ReadU32 (tiff, entry + 4, le) != 1) + continue; + var at = ReadU32 (tiff, entry + 8, le); + if (TryTable (tiff, start, at, le, 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 At -1. + static (long At, long Size) LastMakerNote (byte[] tiff, int start, long ifd, int count, bool le) + { + var length = tiff.Length - start; + (long At, long Size) note = (-1, 0); + for (var n = 0; n < count; n++) { + ExifSteps++; + var entry = start + (int)ifd + 2 + (n * 12); + if (ReadU16 (tiff, entry, le) != MakerNoteTag || ReadU16 (tiff, entry + 2, le) != 7) + continue; + var size = ReadU32 (tiff, entry + 4, le); + var at = ReadU32 (tiff, entry + 8, le); + if (size <= 4 || at > length || size > length - at) + continue; + var bytes = tiff.AsSpan (start + (int)at, (int)size); + if (bytes.StartsWith (AppleMakerNoteHeader.Slice (0, 10))) { + if (!bytes.StartsWith (AppleMakerNoteHeader) || bytes.Length < AppleMakerNoteHeader.Length + 2 + || AppleMakerNoteHeader.Length + 2 + (12L * ReadU16 (bytes, AppleMakerNoteHeader.Length)) > bytes.Length) + continue; + } + + note = (at, size); + } + + return note; + } + + // 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; -1 when there is none. + static (long HeadroomAt, long HeadroomCount, long GainAt, long GainCount) HeadroomEntries (ReadOnlySpan note) + { + var count = ReadU16 (note, AppleMakerNoteHeader.Length); + var table = AppleMakerNoteHeader.Length + 2; + long headroomAt = -1, headroomCount = 0, gainAt = -1, gainCount = 0; + for (var n = 0; n < count; n++) { + ExifSteps++; + var entry = table + (n * 12); + var tag = ReadU16 (note, entry); + if ((tag != AppleHdrHeadroomTag && tag != AppleHdrGainTag) || ReadU16 (note, entry + 2) != SRationalType) + continue; + var values = ReadU32 (note, entry + 4); + var offset = ReadU32 (note, entry + 8); + if (values == 0 || offset > note.Length || values > (note.Length - offset) / 8) + continue; + if (tag == AppleHdrHeadroomTag) + (headroomAt, headroomCount) = (offset, values); + else + (gainAt, gainCount) = (offset, values); + } + + return (headroomAt, headroomCount, gainAt, gainCount); + } + + static byte[] AppleHeadroomTiff (ReadOnlySpan headroom, ReadOnlySpan 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. + 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); + WriteU32 (output, 4, 8, le: false); + WriteU16 (output, 8, 1, le: false); + WriteEntry (output, 10, ExifIfdPointer, 4, 1, ExifAt); + WriteU16 (output, ExifAt, 1, le: false); + WriteEntry (output, ExifAt + 2, MakerNoteTag, 7, NoteLength, NoteAt); + AppleMakerNoteHeader.CopyTo (output.AsSpan (NoteAt)); + WriteU16 (output, NoteAt + 14, 2, le: false); + WriteEntry (output, NoteAt + 16, AppleHdrHeadroomTag, SRationalType, 1, 44); + WriteEntry (output, NoteAt + 28, AppleHdrGainTag, 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) + { + WriteU16 (data, at, tag, le: false); + WriteU16 (data, at + 2, type, le: false); + WriteU32 (data, at + 4, count, le: false); + WriteU32 (data, at + 8, value, le: false); + } + } + + static int ReadU16 (ReadOnlySpan data, int at) => (data[at] << 8) | data[at + 1]; + + static long ReadU32 (ReadOnlySpan data, int at) => + ((long)data[at] << 24) | ((long)data[at + 1] << 16) | ((long)data[at + 2] << 8) | data[at + 3]; + + 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 only collection the Exif removal keeps 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 { + ExifSteps++; + if ((uint)index >= (uint)Count) + throw new ArgumentOutOfRangeException (nameof (index)); + return _items[index]; + } + set { + ExifSteps++; + if ((uint)index >= (uint)Count) + throw new ArgumentOutOfRangeException (nameof (index)); + _items[index] = value; + } + } + + public void Add (T item) + { + ExifSteps++; + if (Count == _items.Length) + Array.Resize (ref _items, _items.Length * 2); + _items[Count++] = item; + } + + public void Sort (Comparison comparison) + { + ExifSteps += Count; + Array.Sort (_items, 0, Count, Comparer.Create (comparison)); + } + } + + // The merged ranges are disjoint and sorted, so their ends are sorted too: find the first that ends after + // the range starts, and check that it starts before the range ends. + static bool Overlaps (CountedList<(long Start, long End)> merged, (long Start, long End) range) + { + int low = 0, high = merged.Count; + while (low < high) { + ExifSteps++; + var mid = low + ((high - low) / 2); + if (merged[mid].End <= range.Start) + low = mid + 1; + else + high = mid; + } + + return low < merged.Count && merged[low].Start < range.End; + } + + // TIFF 6.0 offset/length pairs: JPEGInterchangeFormat and its length (0x0201/0x0202, the IFD1 thumbnail, + // Exif 2.32 §4.6.5), StripOffsets/StripByteCounts (0x0111/0x0117) and TileOffsets/TileByteCounts (0x0144/0x0145). + static readonly (int Offsets, int Lengths)[] DataPairs = [(0x0201, 0x0202), (0x0111, 0x0117), (0x0144, 0x0145)]; + + // False when a tag of a pair appears more than once, so its ranges cannot be told. + static bool AddDataRanges (byte[] tiff, int start, long ifd, int count, bool le, CountedList<(long Start, long End)> ranges) + { + var single = true; + foreach (var (offsetsTag, lengthsTag) in DataPairs) { + var offsets = EntryValues (tiff, start, ifd, count, le, offsetsTag, ref single); + var lengths = EntryValues (tiff, start, ifd, count, le, lengthsTag, ref single); + for (var n = 0; n < offsets.Count && n < lengths.Count; n++) + ranges.Add ((offsets[n], offsets[n] + lengths[n])); + } + + return single; + } + + // The SHORT or LONG values of the first entry with the given tag, or none; bounded by the bytes present. + // turns false when a second entry has the tag. + static CountedList EntryValues (byte[] tiff, int start, long ifd, int count, bool le, int tag, ref bool single) + { + var values = new CountedList (); + var found = -1; + for (var n = 0; n < count; n++) { + ExifSteps++; + if (ReadU16 (tiff, start + (int)ifd + 2 + (n * 12), le) != tag) + continue; + if (found >= 0) { + single = false; + break; + } + + found = n; + } + + if (found >= 0) { + var entry = start + (int)ifd + 2 + (found * 12); + var type = ReadU16 (tiff, entry + 2, le); + var size = type == 3 ? 2 : type == 4 ? 4 : 0; + var items = ReadU32 (tiff, entry + 4, le); + if (size == 0) + return values; + var at = items * size <= 4 ? entry + 8 : start + ReadU32 (tiff, entry + 8, le); + if (at + (items * size) > tiff.Length) + return values; + for (var k = 0; k < items; k++) { + ExifSteps++; + var p = (int)at + (int)(k * size); + values.Add (size == 2 ? ReadU16 (tiff, p, le) : ReadU32 (tiff, p, le)); + } + + return values; + } + + return values; + } + + static bool TryTiffHeader (byte[] tiff, int start, out bool le, out long ifd0) + { + le = false; + ifd0 = 0; + if (tiff.Length - start < 8) + return false; + if (tiff[start] == (byte)'I' && tiff[start + 1] == (byte)'I' && tiff[start + 2] == 42 && tiff[start + 3] == 0) + le = true; + else if (!(tiff[start] == (byte)'M' && tiff[start + 1] == (byte)'M' && tiff[start + 2] == 0 && tiff[start + 3] == 42)) + return false; + ifd0 = ReadU32 (tiff, start + 4, le); + return true; + } + + const int ExifIfdPointer = 0x8769; + const int GpsIfdPointer = 0x8825; + const int InteropIfdPointer = 0xA005; + + static bool TryTable (byte[] tiff, int start, long ifd, bool le, out int count) + { + count = 0; + var length = tiff.Length - start; + if (ifd < 8 || ifd + 2 > length) + return false; + count = ReadU16 (tiff, start + (int)ifd, le); + return ifd + 2 + (count * 12L) + 4 <= length; + } + + // Adds the value of every entry with the given tag (each a pointer to another IFD), in table order. + static void PointersIn (byte[] tiff, int start, long ifd, int count, bool le, int pointer, CountedList pointers) + { + for (var n = 0; n < count; n++) { + ExifSteps++; + var entry = start + (int)ifd + 2 + (n * 12); + if (ReadU16 (tiff, entry, le) == pointer) + pointers.Add (ReadU32 (tiff, entry + 8, le)); + } + } + + static long NextIfd (byte[] tiff, int start, long ifd, int count, bool le) => + ReadU32 (tiff, start + (int)ifd + 2 + (count * 12), le); + + // The out-of-line value of an entry, relative to the TIFF header; empty when the value fits in the entry. + static (long Start, long End) ValueRange (byte[] tiff, int start, int entry, bool le) + { + var size = ReadU16 (tiff, entry + 2, le) switch { + 1 or 2 or 6 or 7 => 1L, + 3 or 8 => 2L, + 4 or 9 or 11 or 13 => 4L, + 5 or 10 or 12 => 8L, + _ => 0L + }; + var bytes = size * ReadU32 (tiff, entry + 4, le); + if (bytes <= 4) + return (0, 0); + var offset = ReadU32 (tiff, entry + 8, le); + return (offset, offset + bytes); + } + + // Moves the kept entries up and the next-IFD offset after them, then zeroes the freed tail of the table. + static void CompactTable (byte[] tiff, int start, long ifd, int count, bool le, CountedList removing) + { + var at = start + (int)ifd; + var table = at + 2; + var kept = 0; + for (var n = 0; n < count; n++) { + var entry = table + (n * 12); + if (removing[n]) + continue; + if (kept != n) + Array.Copy (tiff, entry, tiff, table + (kept * 12), 12); + kept++; + } + + if (kept == count) + return; + var nextAt = table + (count * 12); + var next = ReadU32 (tiff, nextAt, le); + WriteU16 (tiff, at, kept, le); + var newNext = table + (kept * 12); + WriteU32 (tiff, newNext, next, le); + Array.Clear (tiff, newNext + 4, (nextAt + 4) - (newNext + 4)); + } + + static int ReadU16 (byte[] data, int at, bool le) => + le ? data[at] | (data[at + 1] << 8) : (data[at] << 8) | data[at + 1]; + + static long ReadU32 (byte[] data, int at, bool le) => + le + ? data[at] | ((long)data[at + 1] << 8) | ((long)data[at + 2] << 16) | ((long)data[at + 3] << 24) + : ((long)data[at] << 24) | ((long)data[at + 1] << 16) | ((long)data[at + 2] << 8) | data[at + 3]; + + static void WriteU16 (byte[] data, int at, int value, bool le) + { + if (le) { + data[at] = (byte)value; + data[at + 1] = (byte)(value >> 8); + } else { + data[at] = (byte)(value >> 8); + data[at + 1] = (byte)value; + } + } + + static void WriteU32 (byte[] data, int at, long value, bool le) + { + for (var i = 0; i < 4; i++) + data[at + (le ? i : 3 - i)] = (byte)(value >> (8 * i)); + } + + /// + /// Decodes an ImageMagick raw profile: a line feed, the profile name, a line feed, the byte count, a line + /// feed, then the bytes as hexadecimal pairs split across lines. + /// + internal static bool TryDecodeRawProfile (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) + return false; +#if NETSTANDARD2_0 + if (!int.TryParse (text.Substring (i, countEnd - i), NumberStyles.None, CultureInfo.InvariantCulture, out var count)) +#else + if (!int.TryParse (text.AsSpan (i, countEnd - i), NumberStyles.None, CultureInfo.InvariantCulture, out var count)) +#endif + return false; + if (count < 0 || count > (text.Length - countEnd) / 2) + return false; + bytes = new byte[count]; + i = countEnd + 1; + for (var n = 0; n < count; 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 EncodeRawProfile (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; + } + + /// 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 (); + } + + 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; + } + + sealed class XmpEdit (MirrorField field, string name, bool attribute) + { + public MirrorField Field { get; } = field; + public string Name { get; } = name; + public bool Attribute { get; } = 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/Image/ImageRewrite.cs b/src/TagLibSharp2/Image/ImageRewrite.cs new file mode 100644 index 00000000..6b525969 --- /dev/null +++ b/src/TagLibSharp2/Image/ImageRewrite.cs @@ -0,0 +1,1411 @@ +// 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; + +/// +/// Reads and splices the text blocks an image format already defines. +/// PNG uses tEXt, zTXt, and iTXt. GIF uses the comment extension. +/// JPEG uses the 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) + ReadPng (data, tag); + else if (format == MediaFormat.Gif) + ReadGif (data, tag); + else + ReadJpeg (data, tag); + return tag; + } + + internal static byte[] RenderTag (ImageTag tag) + { + using var builder = new BinaryDataBuilder (); + if (tag.Format == MediaFormat.Png) + AddPngFields (builder, tag, onlyChanged: false); + else if (tag.Field (ImageStores.Comment) is string comment) { + if (tag.Format == MediaFormat.Gif) + AddGifComment (builder, comment); + else + builder.Add (EncodeJpegComment (comment)); + } + + return builder.ToArray (); + } + + /// + /// Splices the edited text into . Every byte the edit does not concern is copied, + /// including anything after the last chunk, the GIF trailer, or the JPEG EOI. + /// + /// The new file, or null with naming why the container cannot be updated. + internal static byte[]? Rewrite (ReadOnlySpan data, ImageTag tag, out string? error) + { + error = null; + if (!tag.AffectsFile) + return null; + var rewritten = tag.Format switch { + MediaFormat.Png => RewritePng (data, tag, out error), + MediaFormat.Gif => RewriteGif (data, tag, out error), + MediaFormat.Jpeg => RewriteJpeg (data, tag, out error), + _ => null + }; + if (rewritten is null && error is null) + error = tag.Format switch { + MediaFormat.Gif => "The GIF block list is truncated or holds an unknown block, so the comment cannot be spliced in.", + MediaFormat.Jpeg => "The JPEG marker list before the scan is truncated or malformed, so the comment cannot be spliced in.", + _ => "The image container could not be updated." + }; + return rewritten; + } + + static void ReadPng (ReadOnlySpan data, ImageTag tag) + { + if (!TryWalkPng (data, out var chunks)) + return; + var budget = MaxInflatedText; + string? artist = null; + foreach (var chunk in chunks) + ReadPngChunk (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); + } + + const string ExiftoolArtistKeyword = "Artist"; + + static void ReadPngChunk (ReadOnlySpan chunk, ImageTag tag, ref int budget, ref string? artist) + { + if (chunk.Length < 12) + return; + var length = ReadLength (chunk, 0); + if (length < 0 || 12 + length != chunk.Length) + return; + var type = chunk.Slice (4, 4); + if (!IsTextChunk (type) || !CrcMatches (chunk)) + return; + var payload = chunk.Slice (8, length); + if (!TryKeyword (payload, out var keyword, out var rest)) + return; + var field = FieldFor (keyword); + if (field == ImageStores.None && keyword != ExiftoolArtistKeyword) + return; + if (!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); + } + + static byte[]? RewritePng (ReadOnlySpan data, ImageTag tag, out string? error) + { + error = null; + if (!TryWalkPng (data, out var chunks) || chunks.Count == 0 || !TypeEquals (data, chunks[^1], "IEND"u8)) { + error = "The PNG chunk list does not reach IEND, so the text cannot be spliced in."; + return null; + } + + // New text goes before the pixel data, and before Apple's iDOT, which records where the IDAT chunks are. + var insert = chunks[^1].Start; + var idot = -1; + var idat = -1; + foreach (var chunk in chunks) { + if (TypeEquals (data, chunk, "IDAT"u8)) { + idat = chunk.Start; + insert = idot >= 0 ? idot : chunk.Start; + break; + } + + if (TypeEquals (data, chunk, "iDOT"u8)) + idot = chunk.Start; + } + + var mirrors = !tag.DropUnmapped && ImageMirrors.AnyChanged (tag); + // One inflation budget for every compressed copy in the file, as when it is read. + var budget = MaxInflatedText; + using var builder = new BinaryDataBuilder (data.Length + 64); + builder.Add (data.Slice (0, 8)); + var outIdot = -1; + var outIdat = -1; + foreach (var chunk in chunks) { + if (chunk.Start == insert) + AddPngFields (builder, tag, onlyChanged: true); + if (chunk.Start == idot) + outIdot = builder.Length; + if (chunk.Start == idat) + outIdat = builder.Length; + if (IsDroppedChunk (data, chunk, tag)) + continue; + if (mirrors) { + if (!TryMirrorChunk (data, chunk, tag, ref budget, out var edited, out error)) + return null; + if (edited is not null) { + builder.Add (edited); + continue; + } + } + + builder.Add (data.Slice (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 end = chunks[^1].Start + chunks[^1].Length; + builder.Add (data.Slice (end)); + var output = 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). + var idotKept = outIdot >= 0 && outIdot + 8 <= output.Length && output.AsSpan (outIdot + 4, 4).SequenceEqual ("iDOT"u8); + if (idotKept && idat >= 0 && outIdat - outIdot != idat - idot) { + var size = 12 + ReadLength (output, outIdot); + var trimmed = new byte[output.Length - size]; + output.AsSpan (0, outIdot).CopyTo (trimmed); + output.AsSpan (outIdot + size).CopyTo (trimmed.AsSpan (outIdot)); + output = trimmed; + } + + return output; + } + + static bool IsTextChunk (ReadOnlySpan type) => + type.SequenceEqual ("tEXt"u8) || type.SequenceEqual ("zTXt"u8) || type.SequenceEqual ("iTXt"u8); + + // 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[] PngKeptOnClear = [ + "tRNS", "gAMA", "cHRM", "sRGB", "iCCP", "cICP", "mDCV", "cLLI", "sBIT", + "bKGD", "hIST", "pHYs", "sPLT", "acTL", "fcTL", "fdAT", "oFFs", "pCAL", "sCAL", "sTER", + ]; + + static bool IsKeptOnClear (ReadOnlySpan type) + { + if ((type[0] & 0x20) == 0) + return true; + foreach (var kept in PngKeptOnClear) { + if (type[0] == kept[0] && type[1] == kept[1] && type[2] == kept[2] && type[3] == kept[3]) + return true; + } + + return false; + } + + static bool IsDroppedChunk (ReadOnlySpan data, PngChunk chunk, ImageTag tag) + { + var type = data.Slice (chunk.Start + 4, 4); + if (tag.DropUnmapped) + return !IsKeptOnClear (type); + if (!IsTextChunk (type)) + return false; + var payload = data.Slice (chunk.Start + 8, chunk.Length - 12); + if (!TryKeyword (payload, out var keyword, out _)) + return false; + var field = FieldFor (keyword); + if (field != ImageStores.None) + return tag.Changed (field); + return ImageMirrors.IsMirrorKeyword (keyword, tag); + } + + 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"; + + // 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 data, PngChunk chunk, ImageTag tag, ref int budget, out byte[]? edited, out string? error) + { + edited = null; + error = null; + var whole = data.Slice (chunk.Start, chunk.Length); + var type = whole.Slice (4, 4); + if (!CrcMatches (whole)) + return true; + var payload = whole.Slice (8, whole.Length - 12); + if (type.SequenceEqual ("eXIf"u8)) + return TryMirrorExif (payload, tag, out edited, out error); + if (!IsTextChunk (type) || !TryKeyword (payload, out var keyword, out var rest)) + return true; + if (keyword is not (XmpKeyword or RawXmpKeyword or RawExifKeyword or RawApp1Keyword)) + return true; + + if (!TryTextBody (type, payload.Slice (rest), ref budget, out var body, out var header)) { + error = $"The PNG {keyword} chunk is not valid zlib data, or does not fit in the {MaxInflatedText / (1024 * 1024)} MiB that all compressed text in the file shares, so its copy of a changed field cannot be updated."; + return false; + } + + string updated; + if (keyword == XmpKeyword) { + var packet = Encoding.UTF8.GetString (body); + if (!ImageMirrors.TryUpdateXmp (packet, tag, "PNG XMP packet", out updated, out error)) + return false; + if (ReferenceEquals (updated, packet)) + return true; + edited = TextChunk (type, keyword, header, Encoding.UTF8.GetBytes (updated)); + return true; + } + + var raw = Polyfills.Latin1.GetString (body); + if (!ImageMirrors.TryDecodeRawProfile (raw, out var name, out var profile)) { + error = $"The PNG {keyword} chunk is not a hexadecimal profile, so its copy of a changed field cannot be updated."; + return false; + } + + if (keyword == RawXmpKeyword) { + var packet = Encoding.UTF8.GetString (profile); + if (!ImageMirrors.TryUpdateXmp (packet, tag, "PNG XMP packet", out updated, out error)) + return false; + if (ReferenceEquals (updated, packet)) + return true; + profile = Encoding.UTF8.GetBytes (updated); + } else { + var start = profile.AsSpan ().StartsWith ("Exif\0\0"u8) ? 6 : 0; + if (!ImageMirrors.TryRemoveExif (profile, start, tag, keyword, out var changed, out error)) + return false; + if (!changed) + return true; + } + + edited = TextChunk (type, keyword, header, Polyfills.Latin1.GetBytes (ImageMirrors.EncodeRawProfile (name, profile))); + return true; + } + + static bool TryMirrorExif (ReadOnlySpan payload, ImageTag tag, out byte[]? edited, out string? error) + { + edited = null; + var exif = payload.ToArray (); + var start = payload.StartsWith ("Exif\0\0"u8) ? 6 : 0; + if (!ImageMirrors.TryRemoveExif (exif, start, tag, "eXIf", out var changed, out error)) + return false; + if (!changed) + return true; + using var builder = new BinaryDataBuilder (exif.Length + 12); + AddChunk (builder, "eXIf"u8, exif); + edited = builder.ToArray (); + return true; + } + + // Rebuilds a text chunk of the same type around new text. Compression and the iTXt language tags are kept. + static byte[] TextChunk (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 ? ImageMirrors.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); + using var builder = new BinaryDataBuilder (payload.Length + 12); + AddChunk (builder, type, payload); + return builder.ToArray (); + } + + static void AddPngFields (BinaryDataBuilder builder, ImageTag tag, bool onlyChanged) + { + AddPngField (builder, tag, onlyChanged, ImageStores.Title); + AddPngField (builder, tag, onlyChanged, ImageStores.Artist); + AddPngField (builder, tag, onlyChanged, ImageStores.Description); + AddPngField (builder, tag, onlyChanged, ImageStores.Copyright); + AddPngField (builder, tag, onlyChanged, ImageStores.Year); + AddPngField (builder, tag, onlyChanged, ImageStores.Comment); + } + + static void AddPngField (BinaryDataBuilder builder, ImageTag tag, bool onlyChanged, ImageStores field) + { + if ((onlyChanged && !tag.Changed (field)) || tag.Field (field) is not string value) + return; + var keyword = Keyword (field); + if (IsLatin1 (value)) + AddChunk (builder, "tEXt"u8, Latin1Text (keyword, value)); + else + AddChunk (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 void ReadGif (ReadOnlySpan data, ImageTag tag) + { + if (!TryGifComments (data, out var text)) + return; + tag.ReadField (ImageStores.Comment, text); + } + + static byte[]? RewriteGif (ReadOnlySpan data, ImageTag tag, out string? error) + { + error = null; + var replaceComment = tag.Changed (ImageStores.Comment); + if (!replaceComment && !tag.DropUnmapped) + return null; + if (!TryGifHeader (data, out var header)) { + error = "The GIF header is truncated, so the comment cannot be spliced in."; + return null; + } + + var mirrors = replaceComment && !tag.DropUnmapped; + var comment = replaceComment ? tag.Field (ImageStores.Comment) : null; + using var builder = new BinaryDataBuilder (data.Length + 32); + if (comment is not null && data.StartsWith ("GIF87a"u8)) { + builder.Add ("GIF89a"u8); + builder.Add (data.Slice (6, header - 6)); + } else { + builder.Add (data.Slice (0, header)); + } + + if (comment is not null) + AddGifComment (builder, comment); + var i = header; + while (i < data.Length) { + var start = i; + var introducer = data[i]; + if (introducer == 0x3B) { + builder.Add (data.Slice (start)); + return builder.ToArray (); + } + + if (introducer == 0x21) { + if (i + 2 > data.Length || !SkipSubBlocks (data, ref i, startAtLabel: true)) + break; + var block = data.Slice (start, i - start); + if ((replaceComment && block[1] == 0xFE) || (tag.DropUnmapped && !IsGifKeptOnClear (block))) + continue; + if (mirrors && IsGifXmp (block)) { + if (!TryMirrorGifXmp (block, tag, out var edited, out error)) + return null; + builder.Add (edited ?? block.ToArray ()); + continue; + } + + builder.Add (block); + continue; + } + + if (introducer == 0x2C) { + if (!SkipImage (data, ref i)) + break; + builder.Add (data.Slice (start, i - start)); + continue; + } + + break; + } + + error = "The GIF block list is truncated or holds an unknown block, so the comment cannot be spliced in."; + return null; + } + + // 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 IsGifKeptOnClear (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 IsGifXmp (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[] GifXmpTrailer () + { + var trailer = new byte[258]; + trailer[0] = 0x01; + for (var n = 0; n < 256; n++) + trailer[1 + n] = (byte)(0xFF - n); + return trailer; + } + + // 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 TryMirrorGifXmpSubBlocks (ReadOnlySpan block, ImageTag tag, out byte[]? edited, out string? error) + { + edited = null; + error = null; + 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; + } + + var packet = Encoding.UTF8.GetString ([.. joined]); + if (i != 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; + } + + if (!ImageMirrors.TryUpdateXmp (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; + } + + static bool TryMirrorGifXmp (ReadOnlySpan block, ImageTag tag, out byte[]? edited, out string? error) + { + edited = null; + error = null; + var trailer = GifXmpTrailer (); + if (block.Length < 14 + trailer.Length || !block.Slice (block.Length - trailer.Length).SequenceEqual (trailer)) + return TryMirrorGifXmpSubBlocks (block, tag, out edited, out error); + + var packet = Encoding.UTF8.GetString (block.Slice (14, block.Length - 14 - trailer.Length)); + if (!ImageMirrors.TryUpdateXmp (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; + } + + static bool TryGifComments (ReadOnlySpan data, out string? text) + { + text = null; + if (!TryGifHeader (data, out var header)) + return false; + var collected = new List (); + var i = header; + var sawTrailer = false; + while (i < data.Length) { + var introducer = data[i]; + if (introducer == 0x3B) { + sawTrailer = true; + break; + } + + if (introducer == 0x21) { + if (i + 2 > data.Length) + return false; + var label = data[i + 1]; + var payload = label == 0xFE ? collected : null; + if (!SkipSubBlocks (data, ref i, startAtLabel: true, payload)) + return false; + continue; + } + + if (introducer == 0x2C) { + if (!SkipImage (data, ref i)) + return false; + continue; + } + + return false; + } + + if (!sawTrailer) + return false; + text = collected.Count == 0 ? null : Encoding.UTF8.GetString (collected.ToArray ()); + return true; + } + + static bool TryGifHeader (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; + } + + static void AddGifComment (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); + } + + static void ReadJpeg (ReadOnlySpan data, ImageTag tag) + { + if (TryJpegComment (data, out var text)) + tag.ReadField (ImageStores.Comment, text); + } + + static byte[]? RewriteJpeg (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 ? EncodeJpegComment (comment) : [] + : null; + return TryRewriteJpeg (data, tag, replacement, out error); + } + + static bool TryJpegComment (ReadOnlySpan data, out string? text) + { + text = null; + if (data.Length < 2 || data[0] != 0xFF || data[1] != 0xD8) + 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 = (data[i] << 8) | data[i + 1]; + if (length < 2 || i + length > data.Length) + return false; + if (marker == 0xDA) + break; + if (marker == 0xFE) { + for (var n = 2; n < length; n++) + collected.Add (data[i + n]); + } + + i += length; + } + + text = collected.Count == 0 ? null : Encoding.UTF8.GetString (collected.ToArray ()); + return true; + } + + const string JpegSpliceError = "The JPEG marker list before the scan is truncated or malformed, so the comment cannot be spliced in."; + + static byte[]? TryRewriteJpeg (ReadOnlySpan data, ImageTag tag, byte[]? comment, out string? error) + { + error = null; + var dropMetadata = tag.DropUnmapped; + if (data.Length < 2 || data[0] != 0xFF || data[1] != 0xD8) { + error = JpegSpliceError; + 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 = ReadMpIndex (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 : []; + var primaryEnd = images.Count > 0 ? images[0].Start : data.Length; + + // The later images are cleaned first: an Ultra HDR primary lists their lengths (Item:Length). + var cleanedImages = new List (); + foreach (var image in images) { + var cleaned = RewriteJpegImage (data.Slice (image.Start, image.Size), tag, [], dropMetadata: true, mirrors: false, null, out _); + if (cleaned is null) { + error = $"Image {image.Entry + 1} of the JPEG MPF index cannot be parsed, so its metadata cannot be cleared."; + return null; + } + + cleanedImages.Add (cleaned); + } + + var lengths = cleanedImages.ConvertAll (c => (long)c.Bytes.Length); + // 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 (ImageMirrors.KeepAppleHeadroom). + var appleHeadroom = cleanedImages.Exists (c => c.HeadroomInMakerNote); + var primary = RewriteJpegImage (data.Slice (0, primaryEnd), tag, comment, dropMetadata, mirrors: comment is not null && !dropMetadata, dropMetadata ? lengths : null, out error, appleHeadroom); + if (primary is null) + return null; + if (primary.InMpf < 0) + return primary.Bytes; + + if (images.Count == 0) { + // 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. + 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.Bytes; + if (!TryRewriteMpEntries (primary.Bytes, primary.OutMpf, primary.OutMpfEnd, (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; + } + + return primary.Bytes; + } + + using var builder = new BinaryDataBuilder (data.Length); + builder.Add (primary.Bytes); + var placed = new Dictionary (); + var at = primaryEnd; + for (var n = 0; n < images.Count; n++) { + var image = images[n]; + var cleaned = cleanedImages[n]; + builder.Add (data.Slice (at, image.Start - at)); + placed[image.Entry] = (builder.Length, cleaned.Bytes.Length); + builder.Add (cleaned.Bytes); + at = image.Start + image.Size; + } + + builder.Add (data.Slice (at)); + var output = builder.ToArray (); + var primaryDelta = primary.Bytes.Length - (long)primaryEnd; + var header = primary.OutMpf; + if (!TryRewriteMpEntries (output, header, primary.OutMpfEnd, (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; + } + + return output; + } + + sealed class JpegImage + { + public byte[] Bytes { get; init; } = []; + 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? RewriteJpegImage (ReadOnlySpan data, ImageTag tag, byte[]? comment, bool dropMetadata, bool mirrors, IReadOnlyList? itemLengths, out string? error, bool appleHeadroom = false) + { + error = null; + if (data.Length < 2 || data[0] != 0xFF || data[1] != 0xD8) { + error = JpegSpliceError; + return null; + } + + using var builder = new BinaryDataBuilder (data.Length + (comment?.Length ?? 0)); + builder.Add (data.Slice (0, 2)); + var inMpf = -1; + var outMpf = -1; + var mpfLength = 0; + var headroomInMakerNote = false; + var firstExif = true; + var i = 2; + while (i < data.Length) { + var start = i; + if (data[i] != 0xFF) { + error = JpegSpliceError; + return null; + } + + while (i < data.Length && data[i] == 0xFF) + i++; + if (i >= data.Length) { + error = JpegSpliceError; + return null; + } + + var marker = data[i++]; + if (marker is 0x01 or (>= 0xD0 and <= 0xD8)) { + builder.Add (data.Slice (start, i - start)); + continue; + } + + if (marker == 0xD9) + return Finish (builder, data, start, comment, inMpf, outMpf, mpfLength, headroomInMakerNote); + + if (i + 1 >= data.Length) { + error = JpegSpliceError; + return null; + } + + var length = (data[i] << 8) | data[i + 1]; + if (length < 2 || i + length > data.Length) { + error = JpegSpliceError; + return null; + } + + if (marker == 0xDA) + return Finish (builder, data, start, comment, inMpf, outMpf, mpfLength, headroomInMakerNote); + + // Fill bytes (0xFF) before the marker (T.81 §B.1.1.2) are part of what is kept or rewritten. + var fill = data.Slice (start, i - 2 - start); + var segment = data.Slice (start, i + length - start); + var payload = data.Slice (i + 2, length - 2); + i += length; + if (dropMetadata && marker == 0xE1 && TryXmpSignature (payload, out var signature)) { + // Clear keeps only the gain-map XMP an HDR decoder needs (ImageGainMap). + var kept = ImageGainMap.KeepForClear (payload.Slice (signature), itemLengths, out var makerNote); + if (kept is null || 2 + signature + kept.Length > MaxJpegSegment) + continue; + headroomInMakerNote |= makerNote; + builder.Add (fill); + builder.Add (JpegSegmentBytes (0xE1, [.. payload.Slice (0, signature), .. kept])); + continue; + } + + // Clear keeps the Apple maker-note headroom of the first Exif (the one readers use), and nothing else of it. + if (dropMetadata && marker == 0xE1 && payload.StartsWith ("Exif\0\0"u8) && firstExif) { + firstExif = false; + if (appleHeadroom && ImageMirrors.KeepAppleHeadroom (payload.ToArray (), 6) is byte[] headroom) { + builder.Add (fill); + builder.Add (JpegSegmentBytes (0xE1, [.. "Exif\0\0"u8, .. headroom])); + } + + continue; + } + + if ((comment is not null && marker == 0xFE) || (dropMetadata && marker is >= 0xE0 and <= 0xEF && !IsJpegKeptOnClear (marker, payload))) + continue; + if (marker == 0xE2 && inMpf < 0 && payload.StartsWith ("MPF\0"u8)) { + inMpf = start + (segment.Length - payload.Length) + 4; + outMpf = builder.Length + (segment.Length - payload.Length) + 4; + mpfLength = payload.Length - 4; + } + + if (mirrors && marker == 0xE1) { + if (!TryMirrorJpegApp1 (payload, tag, out var edited, out error)) + return null; + if (edited is not null) { + builder.Add (fill); + builder.Add (edited); + continue; + } + } + + builder.Add (segment); + } + + return Finish (builder, data, data.Length, comment, inMpf, outMpf, mpfLength, headroomInMakerNote); + + static JpegImage Finish (BinaryDataBuilder builder, ReadOnlySpan data, int rest, byte[]? comment, int inMpf, int outMpf, int mpfLength, bool headroomInMakerNote) + { + if (comment is { Length: > 0 }) + builder.Add (comment); + var outRest = builder.Length; + builder.Add (data.Slice (rest)); + return new JpegImage { + Bytes = builder.ToArray (), + InMpf = inMpf, + OutMpf = outMpf, + OutMpfEnd = outMpf < 0 ? -1 : outMpf + mpfLength, + InRest = rest, + OutRest = outRest, + HeadroomInMakerNote = headroomInMakerNote + }; + } + } + + readonly record struct MpImage (int Entry, int Start, int Size); + + sealed class MpIndex + { + public bool Unreadable { get; init; } + public List Images { get; init; } = []; + } + + // 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). For Clear, every later image must be a whole + // JPEG inside the file, after the first image's MP header, without overlapping another. + static MpIndex ReadMpIndex (ReadOnlySpan data) + { + var header = FindMpfHeader (data, out var limit, out var scan); + if (header < 0) + return new MpIndex (); + var images = new List (); + var entries = new List<(long Offset, long Size)> (); + if (!TryReadMpEntries (data, header, limit, entries)) + return new MpIndex { Unreadable = true }; + for (var n = 0; n < entries.Count; n++) { + var (offset, size) = entries[n]; + if (offset == 0) + continue; + var start = header + offset; + if (start < scan || size < 4 || start + size > data.Length || data[(int)start] != 0xFF || data[(int)start + 1] != 0xD8) + return new MpIndex { 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 MpIndex { Unreadable = true }; + } + + return new MpIndex { Images = images }; + } + + // The MP header of the first APP2 "MPF" segment, the end of that segment's payload, and where the first + // image's scan starts (a later image cannot start before it). + static int FindMpfHeader (ReadOnlySpan data, out int limit, out int scan) + { + limit = -1; + scan = data.Length; + var header = -1; + var i = 2; + while (i + 4 <= data.Length && data[i] == 0xFF) { + var marker = data[i + 1]; + if (marker is 0xDA or 0xD9) { + scan = i; + break; + } + + if (marker is 0x01 or (>= 0xD0 and <= 0xD8) or 0xFF) { + i += marker == 0xFF ? 1 : 2; + continue; + } + + var length = (data[i + 2] << 8) | data[i + 3]; + if (length < 2 || i + 2 + length > data.Length) + break; + if (header < 0 && marker == 0xE2 && data.Slice (i + 4, length - 2).StartsWith ("MPF\0"u8)) { + header = i + 8; + limit = i + 2 + length; + } + + i += 2 + length; + } + + return header; + } + + static bool TryReadMpEntries (ReadOnlySpan data, int header, int limit, List<(long Offset, long Size)> entries) + { + if (!TryMpEntryList (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 ((U32 (data, at + 8, le), U32 (data, at + 4, 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. + static bool TryMpEntryList (ReadOnlySpan data, int header, int limit, out bool le, out long list, out int count) + { + le = false; + list = 0; + count = 0; + if (header < 0 || header + 8 > limit || limit > data.Length) + return false; + if (data[header] == (byte)'I' && data[header + 1] == (byte)'I') + le = true; + else if (!(data[header] == (byte)'M' && data[header + 1] == (byte)'M')) + return false; + var ifd = header + U32 (data, header + 4, le); + if (ifd < header + 8 || ifd + 2 > limit) + return false; + var tags = U16 (data, (int)ifd, le); + if (ifd + 2 + (tags * 12L) > limit) + return false; + for (var n = 0; n < tags; n++) { + var entry = (int)ifd + 2 + (n * 12); + if (U16 (data, entry, le) != 0xB002) + continue; + var bytes = U32 (data, entry + 4, le); + list = header + U32 (data, entry + 8, le); + if (bytes % 16 != 0 || list < header + 8 || list + bytes > limit) + return false; + count = (int)(bytes / 16); + return true; + } + + return true; + } + + // Rewrites every MP entry's offset and size with update (entry number, offset, size). + static bool TryRewriteMpEntries (byte[] output, int header, int limit, Func update) + { + if (!TryMpEntryList (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, U32 (span, at + 8, le), U32 (span, at + 4, le)); + if (offset < 0 || offset > uint.MaxValue || size < 0 || size > uint.MaxValue) + return false; + W32 (span, at + 8, (uint)offset, le); + W32 (span, at + 4, (uint)size, le); + } + + return true; + } + + static int U16 (ReadOnlySpan data, int at, bool le) => + le ? data[at] | (data[at + 1] << 8) : (data[at] << 8) | data[at + 1]; + + static long U32 (ReadOnlySpan data, int at, bool le) => + le + ? data[at] | ((long)data[at + 1] << 8) | ((long)data[at + 2] << 16) | ((long)data[at + 3] << 24) + : ((long)data[at] << 24) | ((long)data[at + 1] << 16) | ((long)data[at + 2] << 8) | data[at + 3]; + + static void W32 (Span data, int at, uint value, bool le) + { + for (var n = 0; n < 4; n++) + data[at + (le ? n : 3 - n)] = (byte)(value >> (8 * n)); + } + + const int MaxJpegSegment = 65535; + + // 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. + // "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. + 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; + } + + static bool TryMirrorJpegApp1 (ReadOnlySpan payload, ImageTag tag, out byte[]? edited, out string? error) + { + edited = null; + error = null; + if (payload.StartsWith ("Exif\0\0"u8)) { + var exif = payload.ToArray (); + if (!ImageMirrors.TryRemoveExif (exif, 6, tag, "JPEG Exif", out var changed, out error)) + return false; + if (changed) + edited = JpegSegmentBytes (0xE1, exif); + return true; + } + + // Some writers put a space before the NUL; exiftool and ImageIO read that packet too. + var xmpSignature = payload.StartsWith ("http://ns.adobe.com/xap/1.0/ \0"u8) ? "http://ns.adobe.com/xap/1.0/ \0"u8 : "http://ns.adobe.com/xap/1.0/\0"u8; + if (payload.StartsWith (xmpSignature)) { + var packet = Encoding.UTF8.GetString (payload.Slice (xmpSignature.Length)); + if (!ImageMirrors.TryUpdateXmp (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 + xmpSignature.Length + bytes.Length > MaxJpegSegment) { + error = "The JPEG XMP packet would no longer fit in one APP1 segment after the comment edit."; + return false; + } + + var body = new byte[xmpSignature.Length + bytes.Length]; + xmpSignature.CopyTo (body); + bytes.CopyTo (body, xmpSignature.Length); + edited = JpegSegmentBytes (0xE1, body); + return true; + } + + 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 byte[] JpegSegmentBytes (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, ImageMirrors.KeepAppleHeadroom), 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 IsJpegKeptOnClear (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' && IsJpegXtDecodingBox (payload.Slice (12, 4)), + 0xEE => payload.StartsWith ("Adobe"u8), + _ => false + }; + + static readonly string[] JpegXtDecodingBoxes = ["ftyp", "TONE", "RTRF", "LTRF", "LCHK", "SPEC", "RESI"]; + + static bool IsJpegXtDecodingBox (ReadOnlySpan type) + { + foreach (var box in JpegXtDecodingBoxes) { + if (type[0] == box[0] && type[1] == box[1] && type[2] == box[2] && type[3] == box[3]) + return true; + } + + return false; + } + + static byte[] EncodeJpegComment (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 (); + } + + 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 (rest.Length < 2) + return false; + var compressed = rest[0] == 1; + var i = 2; + if (!SkipToNull (rest, ref i) || !SkipToNull (rest, ref 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. + static bool TryTextBody (ReadOnlySpan type, ReadOnlySpan rest, ref int budget, out byte[] body, out byte[] header) + { + body = []; + header = []; + 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)) + return false; + header = [0]; + return true; + } + + if (rest.Length < 2) + return false; + var compressed = rest[0] == 1; + var i = 2; + if (!SkipToNull (rest, ref i) || !SkipToNull (rest, ref i)) + return false; + header = rest.Slice (0, i).ToArray (); + if (compressed) + return TryInflate (rest.Slice (i), ref budget, out body); + body = rest.Slice (i).ToArray (); + return true; + } + + const int MaxInflatedText = 1024 * 1024; + + static bool TryInflate (ReadOnlySpan zlib, ref int budget, out byte[] raw) + { + raw = []; + if (budget <= 0 || 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 { + var deflate = zlib.Slice (header, zlib.Length - header - 4).ToArray (); + using var input = new MemoryStream (deflate); + using var stream = new DeflateStream (input, CompressionMode.Decompress); + 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 (); + budget -= raw.Length; + return true; + } catch (InvalidDataException) { + return false; + } catch (IOException) { + return false; + } + } + + 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; + } + + 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; + } + + static bool TryWalkPng (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; + } + + static bool CrcMatches (ReadOnlySpan chunk) + { + var length = chunk.Length - 12; + var actual = ReadU32 (chunk, 8 + length); + return BinaryData.ComputeCrc32 (chunk.Slice (4, 4 + length)) == actual; + } + + static uint ReadU32 (ReadOnlySpan data, int offset) => + ((uint)data[offset] << 24) | ((uint)data[offset + 1] << 16) | ((uint)data[offset + 2] << 8) | data[offset + 3]; + + static void AddChunk (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 ()); + } + + static bool TypeEquals (ReadOnlySpan data, PngChunk chunk, ReadOnlySpan type) => + data.Slice (chunk.Start + 4, 4).SequenceEqual (type); + + static int ReadLength (ReadOnlySpan data, int offset) + { + uint value = ((uint)data[offset] << 24) | ((uint)data[offset + 1] << 16) | ((uint)data[offset + 2] << 8) | data[offset + 3]; + return value > int.MaxValue ? -1 : (int)value; + } + + 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 + }; + + static string Keyword (ImageStores field) => field switch { + ImageStores.Artist => "Author", + ImageStores.Description => "Description", + ImageStores.Copyright => "Copyright", + ImageStores.Year => "Creation Time", + ImageStores.Comment => "Comment", + _ => "Title" + }; + + static bool IsLatin1 (string value) + { + foreach (var c in value) { + if (c > 0xFF) + return false; + } + + return true; + } + + readonly struct PngChunk (int start, int length) + { + public int Start { get; } = start; + public int Length { get; } = length; + } +} 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/StillImageFile.cs b/src/TagLibSharp2/Image/StillImageFile.cs new file mode 100644 index 00000000..b09e3542 --- /dev/null +++ b/src/TagLibSharp2/Image/StillImageFile.cs @@ -0,0 +1,309 @@ +// 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; + +/// +/// 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. 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)) + return StillImageFileReadResult.Failure ($"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 (!TryPrepare (out var bytes, out _)) + return _data; + return bytes; + } + + /// 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 + if (!TryPrepare (out var bytes, out var error)) + return FileWriteResult.Failure (error!); + var fs = fileSystem ?? _fileSystem ?? DefaultFileSystem.Instance; + return AtomicFileWriter.Write (path, bytes.Span, fs); + } + + /// 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 + if (!TryPrepare (out var bytes, out var error)) + return Task.FromResult (FileWriteResult.Failure (error!)); + var fs = fileSystem ?? _fileSystem ?? DefaultFileSystem.Instance; + return AtomicFileWriter.WriteAsync (path, bytes, fs, cancellationToken); + } + + bool TryPrepare (out ReadOnlyMemory bytes, out string? error) + { + error = null; + if (_tag is null || !_tag.AffectsFile) { + bytes = _data; + return true; + } + + if (ImageRewrite.Rewrite (_data, _tag, out error) is byte[] rewritten) { + bytes = rewritten; + return true; + } + + bytes = default; + error ??= "The image container could not be updated."; + return false; + } + + /// 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/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/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/ImageBoundsTests.cs b/tests/TagLibSharp2.Tests/Image/ImageBoundsTests.cs new file mode 100644 index 00000000..546341d2 --- /dev/null +++ b/tests/TagLibSharp2.Tests/Image/ImageBoundsTests.cs @@ -0,0 +1,284 @@ +// 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 TagLibSharp2.Tests.Kit; +using static TagLibSharp2.Tests.Image.ImageTestBuilder; + +namespace TagLibSharp2.Tests.Image; + +/// +/// Memory and work bounds of the image parsers (rule 2), each pinned by an allocation or operation count. +/// +[TestClass] +[TestCategory ("Unit")] +public class ImageBoundsTests +{ + 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). + const int Noise = 4 * 1024; + + 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 ("""" + 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); + Bounds.AssertAllocatesAtMost (Noise, () => Assert.AreEqual (MediaFormat.Svg, MediaFile.DetectFormat (data)), name); + + ImageProperties? properties = null; + _ = ImageHeader.TryRead (data, MediaFormat.Svg, out _); + Bounds.AssertAllocatesAtMost (2 * Noise, () => Assert.IsTrue (ImageHeader.TryRead (data, MediaFormat.Svg, out properties)), name); + Assert.AreEqual (7, properties!.Value.Width, name); + Assert.AreEqual (9, properties.Value.Height, name); + } + + [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) + { + ImageHeader.IfdReads = 0; + _ = ImageHeader.TryRead (tiff, MediaFormat.Tiff, out _); + return ImageHeader.IfdReads; + } + + [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 _)); + } + + [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); + } + + 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); + + Bounds.AssertAllocatesAtMost (limit, () => Assert.IsTrue (MediaFile.Read ("/a.png", fs).IsSuccess), "MediaFile.Read"); + Bounds.AssertAllocatesAtMost (limit, () => Assert.IsTrue (StillImageFile.ReadFromFile ("/a.png", fs).IsSuccess), "StillImageFile.ReadFromFile"); + using var stream = new MemoryStream (png, writable: false); + Bounds.AssertAllocatesAtMost (limit, () => Assert.IsTrue (MediaFile.Read (stream, "a.png").IsSuccess), "MediaFile.Read (stream)"); + } +} diff --git a/tests/TagLibSharp2.Tests/Image/ImageEdgeTests.cs b/tests/TagLibSharp2.Tests/Image/ImageEdgeTests.cs new file mode 100644 index 00000000..1ed8ec6b --- /dev/null +++ b/tests/TagLibSharp2.Tests/Image/ImageEdgeTests.cs @@ -0,0 +1,175 @@ +// 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; + +namespace TagLibSharp2.Tests.Image; + +[TestClass] +[TestCategory ("Unit")] +public class ImageEdgeTests +{ + [TestMethod] + public void Tag_ClearAndRender_RoundTripTheStoredFields () + { + var file = Open (PngText ("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); + } + + [TestMethod] + public void Save_WithoutASourcePath_Fails () + { + var file = Open (PngText ("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 = PngText ("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 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 (Png (0, 1, 8, 0), "zero.png"); + Reject (Png (1, 1, 8, 1), "type.png"); + Assert.AreEqual (8, Open (Png (2, 2, 8, 0), "g.png").ImageProperties!.Value.ColorDepth); + Assert.AreEqual (8, Open (Png (2, 2, 8, 3), "p.png").ImageProperties!.Value.ColorDepth); + Assert.AreEqual (16, Open (Png (2, 2, 8, 4), "ga.png").ImageProperties!.Value.ColorDepth); + Assert.AreEqual (32, Open (Png (2, 2, 8, 6), "rgba.png").ImageProperties!.Value.ColorDepth); + Reject (Encoding.ASCII.GetBytes ("GIF89a"), "short.gif"); + Reject (Gif (0, 1), "zero.gif"); + } + + static void Reject (byte[] data, string name) + { + var result = MediaFile.ReadFromData (data, name); + Assert.IsFalse (result.IsSuccess, result.Error); + } + + static StillImageFile Open (byte[] data, string name) + { + var result = MediaFile.ReadFromData (data, name); + Assert.IsTrue (result.IsSuccess, result.Error); + return (StillImageFile)result.File!; + } + + static byte[] PngText (string title) + { + var key = Encoding.Latin1.GetBytes ("Title"); + var value = Encoding.Latin1.GetBytes (title); + var payload = new byte[key.Length + 1 + value.Length]; + key.CopyTo (payload, 0); + value.CopyTo (payload, key.Length + 1); + return Concat (Signature (), Chunk ("IHDR", Ihdr ()), Chunk ("tEXt", payload), Chunk ("IEND", [])); + } + + static byte[] Png (int width, int height, byte depth, byte color) + { + var ihdr = new byte[13]; + WriteBe (ihdr, 0, width); + WriteBe (ihdr, 4, height); + ihdr[8] = depth; + ihdr[9] = color; + return Concat (Signature (), Chunk ("IHDR", ihdr)); + } + + static byte[] Gif (int width, int height) + { + var data = new byte[13]; + Encoding.ASCII.GetBytes ("GIF89a").CopyTo (data, 0); + data[6] = (byte)width; + data[8] = (byte)height; + return data; + } + + static byte[] Signature () + { + var data = new byte[8]; + data[0] = 0x89; + Encoding.ASCII.GetBytes ("PNG\r\n\x1a\n").CopyTo (data, 1); + return data; + } + + static byte[] Ihdr () => [0, 0, 0, 1, 0, 0, 0, 1, 8, 2, 0, 0, 0]; + + static byte[] Chunk (string type, byte[] payload) + { + var typeBytes = Encoding.ASCII.GetBytes (type); + var crcInput = new byte[4 + payload.Length]; + typeBytes.CopyTo (crcInput, 0); + payload.CopyTo (crcInput, 4); + var crc = new BinaryData (crcInput).ComputeCrc32 (); + var chunk = new byte[12 + payload.Length]; + WriteBe (chunk, 0, payload.Length); + typeBytes.CopyTo (chunk, 4); + payload.CopyTo (chunk, 8); + WriteBe (chunk, 8 + payload.Length, unchecked((int)crc)); + return chunk; + } + + static byte[] Concat (params byte[][] parts) + { + var data = new byte[parts.Sum (part => part.Length)]; + var at = 0; + foreach (var part in parts) { + part.CopyTo (data, at); + at += part.Length; + } + + return data; + } + + static void WriteBe (byte[] data, int offset, int value) + { + data[offset] = (byte)(value >> 24); + data[offset + 1] = (byte)(value >> 16); + data[offset + 2] = (byte)(value >> 8); + data[offset + 3] = (byte)value; + } +} diff --git a/tests/TagLibSharp2.Tests/Image/ImageFileTests.cs b/tests/TagLibSharp2.Tests/Image/ImageFileTests.cs new file mode 100644 index 00000000..205ace50 --- /dev/null +++ b/tests/TagLibSharp2.Tests/Image/ImageFileTests.cs @@ -0,0 +1,331 @@ +// 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; + +[TestClass] +[TestCategory ("Unit")] +public class ImageFileTests +{ + [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); + } + + [TestMethod] + public void Read_Png_ReportsIhdrSize () + { + var data = Png (width: 8, height: 5, bitDepth: 8, colorType: 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 = Gif (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); + WriteLe (data, 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); + } + + [TestMethod] + public void Read_Tiff_ReportsIfdSize () + { + AssertImage (Tiff (width: 64, height: 48, littleEndian: true), "photo.tif", MediaFormat.Tiff, 64, 48, "TIFF"); + AssertImage (Tiff (width: 20, height: 10, littleEndian: false), "photo.tiff", MediaFormat.Tiff, 20, 10, "TIFF"); + } + + [TestMethod] + public void Read_Dng_IsTiffWithTheDngVersionTag () + { + AssertImage (Tiff (width: 32, height: 16, littleEndian: true, dng: true), "photo.dng", MediaFormat.Dng, 32, 16, "DNG"); + AssertImage (Tiff (width: 32, height: 16, littleEndian: true, dng: true), "photo.tif", MediaFormat.Dng, 32, 16, "DNG"); + AssertImage (Tiff (width: 32, height: 16, littleEndian: true), "photo.dng", MediaFormat.Dng, 32, 16, "DNG"); + } + + [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"); + } + + [TestMethod] + public void Render_ReturnsTheOriginalBytes () + { + var data = Png (width: 2, height: 2, bitDepth: 8, colorType: 0); + var opened = MediaFile.ReadFromData (data, "a.png"); + var file = (StillImageFile)opened.File!; + CollectionAssert.AreEqual (data, file.Render ().ToArray ()); + } + + [TestMethod] + public void Read_BytesNamedJpegThatAreNotJpeg_Fails () + { + var opened = MediaFile.ReadFromData (new byte[] { 0x01, 0x02, 0x03 }, "nope.jpg"); + Assert.IsFalse (opened.IsSuccess); + } + + [TestMethod] + public void Read_FlacMagicNamedPng_StaysFlac () + { + var data = new byte[] { 0x66, 0x4C, 0x61, 0x43, 0, 0, 0, 0 }; + Assert.AreEqual (MediaFormat.Flac, MediaFile.DetectFormat (data, "cover.png")); + } + + 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); + } + + 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); + } + + static IMediaFile ImageOf (byte[] data, string name) => + (IMediaFile)MediaFile.ReadFromData (data, name).File!; + + 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 (); + } + + static byte[] Png (int width, int height, byte bitDepth, byte colorType) + { + var data = new byte[8 + 8 + 13]; + data[0] = 0x89; + "PNG\r\n\x1a\n"u8.CopyTo (data.AsSpan (1)); + data[11] = 13; + "IHDR"u8.CopyTo (data.AsSpan (12)); + WriteBe (data, 16, width); + WriteBe (data, 20, height); + data[24] = bitDepth; + data[25] = colorType; + return data; + } + + static byte[] Gif (int width, int height) + { + var data = new byte[13]; + "GIF89a"u8.CopyTo (data); + data[6] = (byte)width; + data[7] = (byte)(width >> 8); + data[8] = (byte)height; + data[9] = (byte)(height >> 8); + data[10] = 0x80 | (7 << 4) | 7; + return data; + } + + static byte[] Bmp (int width, int height) + { + var data = new byte[54]; + "BM"u8.CopyTo (data); + WriteLe (data, 14, 40); + WriteLe (data, 18, width); + WriteLe (data, 22, height); + data[28] = 24; + return data; + } + + static byte[] Pcx (int xmin, int ymin, int xmax, int ymax) + { + var data = new byte[128]; + data[0] = 0x0A; + data[1] = 5; + data[2] = 1; + data[3] = 8; + WriteLe (data, 4, xmin); + WriteLe (data, 6, ymin); + WriteLe (data, 8, xmax); + WriteLe (data, 10, ymax); + data[65] = 3; + return data; + } + + static byte[] Tiff (int width, int height, bool littleEndian, bool dng = false) + { + int entries = dng ? 3 : 2; + var data = new byte[8 + 2 + (entries * 12) + 4]; + if (littleEndian) { + data[0] = (byte)'I'; + data[1] = (byte)'I'; + data[2] = 42; + } else { + data[0] = (byte)'M'; + data[1] = (byte)'M'; + data[3] = 42; + } + + WriteU32 (data, 4, 8, littleEndian); + WriteU16 (data, 8, entries, littleEndian); + WriteEntry (data, 10, 256, width, littleEndian); + WriteEntry (data, 22, 257, height, littleEndian); + if (dng) + WriteEntry (data, 34, 0xC612, 1, littleEndian); + return data; + } + + static void WriteEntry (byte[] data, int offset, int tag, int value, bool littleEndian) + { + WriteU16 (data, offset, tag, littleEndian); + WriteU16 (data, offset + 2, 4, littleEndian); + WriteU32 (data, offset + 4, 1, littleEndian); + WriteU32 (data, offset + 8, value, littleEndian); + } + + static void WriteBe (byte[] data, int offset, int value) + { + data[offset] = (byte)(value >> 24); + data[offset + 1] = (byte)(value >> 16); + data[offset + 2] = (byte)(value >> 8); + data[offset + 3] = (byte)value; + } + + static void WriteLe (byte[] data, int offset, int value) + { + data[offset] = (byte)value; + data[offset + 1] = (byte)(value >> 8); + data[offset + 2] = (byte)(value >> 16); + data[offset + 3] = (byte)(value >> 24); + } + + static void WriteU16 (byte[] data, int offset, int value, bool littleEndian) + { + if (littleEndian) { + data[offset] = (byte)value; + data[offset + 1] = (byte)(value >> 8); + } else { + data[offset] = (byte)(value >> 8); + data[offset + 1] = (byte)value; + } + } + + static void WriteU32 (byte[] data, int offset, int value, bool littleEndian) + { + if (littleEndian) + WriteLe (data, offset, value); + else + WriteBe (data, offset, value); + } +} diff --git a/tests/TagLibSharp2.Tests/Image/ImageGainMapTests.cs b/tests/TagLibSharp2.Tests/Image/ImageGainMapTests.cs new file mode 100644 index 00000000..d7907d01 --- /dev/null +++ b/tests/TagLibSharp2.Tests/Image/ImageGainMapTests.cs @@ -0,0 +1,1132 @@ +// 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.Tests.Core; +using static TagLibSharp2.Tests.Image.ImageTestBuilder; + +namespace TagLibSharp2.Tests.Image; + +/// +/// HDR gain maps survive Clear (rule 7: what a decoder needs), the XMP packet tail written by ImageIO, the MP +/// index bound to its segment, and the guards on malformed multi-picture files. +/// +[TestClass] +[TestCategory ("Unit")] +public class ImageGainMapTests +{ + static readonly XNamespace Rdf = "http://www.w3.org/1999/02/22-rdf-syntax-ns#"; + static readonly XNamespace Hdrgm = "http://ns.adobe.com/hdr-gain-map/1.0/"; + static readonly XNamespace Container = "http://ns.google.com/photos/1.0/container/"; + static readonly XNamespace Item = "http://ns.google.com/photos/1.0/container/item/"; + static readonly XNamespace Dc = "http://purl.org/dc/elements/1.1/"; + + // The gain-map image's XMP as ImageIO writes it for an HDRGainMap auxiliary image. + const string AppleGainMapXmp = """ + + + + 1278226488 + 1278226488 + urn:com:apple:photo:2020:aux:hdrgainmap + 65536 + + + + + """; + + 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 ?? [])); + + static byte[] GpsExif () => JpegExif (ExifTiff ([(0x010F, "Canon"), (0x013B, "Jane Private")], [(0x8827, "GPS")])); + + 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; + } + } + + [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'"); + + const string UltraHdrGainMap = """ + + + Jane Private + + """; + + // 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); + } + + 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); + } + + // 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); + } + } + + [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); + } + + [TestMethod] + public void Edit_ExifWithStripOffsetsPastTheData_DoesNotThrow () + { + // StripOffsets (0x0111) as two LONGs at an offset past the block, and its byte counts likewise. + 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 file = Open (Png (PngChunk ("eXIf", far), Text ("Author", "a")), "a.png"); + file.Tag!.Artist = "New"; + var save = file.SaveToFile ("/a.png", new MockFileSystem ()); + Assert.IsTrue (save.IsSuccess, save.Error); + Assert.AreEqual ("Canon", ReadExif (PngChunks (file.Render ().ToArray ()).Single (c => c.Type == "eXIf").Payload)[0x010F]); + } + + 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); + } + + // Compact directory items grow when written in the format's own form; past 64 KB the packet is dropped. + static string OutgrowingPacket (string attributes = "") + { + var items = string.Concat (Enumerable.Range (0, 800).Select (_ => "")); + return "" + + $"{items}"; + } + + [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/"; + static readonly XNamespace AppleGainMap = "http://ns.apple.com/HDRGainMap/1.0/"; + + // 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); + } + + // 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); + } + + // 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); + } + + // 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 } + + 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 (); + ImageMirrors.ExifSteps = 0; + var output = file.Render ().ToArray (); + Assert.AreEqual (1, ExifSegments (output).Count, $"N={n}: the headroom is kept"); + return ImageMirrors.ExifSteps; + } + + var small = Steps (300); + var large = Steps (2400); + 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))); + } + + ImageMirrors.ExifSteps = 0; + var kept = ImageMirrors.KeepAppleHeadroom (tiff, 0); + + Assert.IsNull (kept, shape); + Assert.IsTrue (ImageMirrors.ExifSteps <= tiff.Length, $"{shape}: {ImageMirrors.ExifSteps} steps for {tiff.Length} bytes"); + } + + // 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 ImageMirrors.ExifSteps), 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 (); + ImageMirrors.ExifSteps = 0; + var output = file.Render ().ToArray (); + Assert.AreEqual (1, ExifSegments (output).Count, $"N={n}: the headroom is kept"); + return ImageMirrors.ExifSteps; + } + + var small = Steps (500); + var large = Steps (4000); + 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"); + } +} diff --git a/tests/TagLibSharp2.Tests/Image/ImageHostileTests.cs b/tests/TagLibSharp2.Tests/Image/ImageHostileTests.cs new file mode 100644 index 00000000..4b1e888b --- /dev/null +++ b/tests/TagLibSharp2.Tests/Image/ImageHostileTests.cs @@ -0,0 +1,210 @@ +// 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; + +/// +/// Every truncation and byte flip of a sample of each image format, through detection, every read entry +/// point (span, stream, ), and every rewrite (edit, mirror edit, clear). +/// Nothing may throw (rule 3). Allocation grows linearly with the input (rule 2). +/// +[TestClass] +[TestCategory ("Unit")] +public class ImageHostileTests +{ + static readonly byte[] ZeroHeightJpeg = Concat ( + [0xFF, 0xD8, 0xFF, 0xC0, 0x00, 0x0B, 0x08, 0x00, 0x00, 0x00, 0x08, 0x01, 0x01, 0x11, 0x00], + [0xFF, 0xDA, 0x00, 0x08, 0x01, 0x01, 0x00, 0x00, 0x3F, 0x00], + [0x12, 0xFF, 0x00, 0xFF, 0xD0, 0x34], + [0xFF, 0xDC, 0x00, 0x04, 0x00, 0x05, 0xFF, 0xD9]); + + public static IEnumerable Samples () + { + var exif = ExifTiff ([(0x010E, "desc"), (0x013B, "artist")], [(0x9286, "ASCII\0\0\0c")]); + yield return ["png", "a.png", Png ( + Text ("Title", "t"), + Xmp (XmpPacket (Alt ("dc:title", "x") + Seq ("dc:creator", "a"))), + PngChunk ("eXIf", exif), + CompressedText ("Comment", "c"u8.ToArray ()), + RawProfile ("xmp", Encoding.UTF8.GetBytes (XmpPacket (Alt ("dc:rights", "r")))), + RawProfile ("exif", Concat ("Exif\0\0"u8.ToArray (), exif)), + InternationalText ("Description", "d ✓", compressed: true), + Text ("Artist", "exiftool artist"), + PngChunk ("caBX", C2paStore ()), + PngChunk ("iDOT", new byte[28]))]; + yield return ["gif", "a.gif", Gif (GifComment ("c"), GifApplication ("XMP DataXMP", ""u8.ToArray ()), GifApplication ("MGKIPTC0000", [1, 2]), GifApplication ("NETSCAPE2.0", [1, 0, 0]))]; + yield return ["jpeg", "a.jpg", Jpeg (JpegSegment (0xFE, "c"u8.ToArray ()), JpegApp (0xE1, "Exif\0\0", "MM\0*"), JpegApp (0xE1, "http://ns.adobe.com/xmp/extension/\0", "x"), JpegApp (0xEC, "Ducky\0", "x"))]; + yield return ["jpeg-dnl", "a.jpg", ZeroHeightJpeg]; + yield return ["jpeg-mirrors", "a.jpg", MpfJpeg ( + Concat (JpegExif (ExifTiff ([(0x010F, "Canon"), (0x9C9C, "xp")], [(0x9286, "ASCII\0\0\0uc")])), JpegXmp (XmpPacket (Alt ("exif:UserComment", "x")))), + Concat (Jumbf (3, 1, C2paStore ()), JpegSegment (0xFE, "c"u8.ToArray ())), out _)]; + // A version-65536 Apple gain map: Clear keeps the primary's maker-note headroom (ImageMirrors.KeepAppleHeadroom). + var appleNote = AppleMakerNote ([(0x000B, 2, 5, "Jane\0"u8.ToArray ()), (0x0021, 10, 1, SRational (4, 5)), (0x0030, 10, 1, SRational (0, 1))]); + yield return ["jpeg-apple-v1", "a.jpg", MpfJpeg ( + JpegExif (AppleExifTiff (appleNote)), + [], + Jpeg (JpegXmp ("")), + out _)]; + yield return ["gif-xmp", "a.gif", Gif (GifComment ("c"), GifXmp (XmpPacket (Alt ("exif:UserComment", "x"))))]; + yield return ["bmp", "a.bmp", Bmp ()]; + yield return ["pcx", "a.pcx", Pcx ()]; + yield return ["netpbm", "a.pgm", Encoding.ASCII.GetBytes ("P5\n# comment\n2 3\n255\n\0\0\0\0\0\0")]; + yield return ["tiff", "a.tif", TiffChain ([[(254, 1), (256, 4), (257, 3), (330, 8 + 2 + 48 + 4)], [(254, 0), (256, 40), (257, 30)]])]; + yield return ["dng", "a.dng", TiffChain ([[(254, 1), (256, 4), (257, 3), (330, 8 + 2 + 60 + 4), (0xC612, 1)], [(254, 0), (256, 40), (257, 30)]])]; + yield return ["bigtiff", "a.tif", BigTiff ()]; + yield return ["svg", "a.svg", 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] + [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); + Assert.IsNotNull (shape); + } + + static byte[] Bmp () + { + var data = new byte[58]; + data[0] = (byte)'B'; + data[1] = (byte)'M'; + BinaryPrimitives.WriteInt32LittleEndian (data.AsSpan (14), 40); + BinaryPrimitives.WriteInt32LittleEndian (data.AsSpan (18), 2); + BinaryPrimitives.WriteInt32LittleEndian (data.AsSpan (22), -3); + data[28] = 24; + return data; + } + + static byte[] Pcx () + { + var data = new byte[128]; + data[0] = 0x0A; + data[1] = 5; + data[2] = 1; + data[3] = 8; + data[8] = 3; + data[10] = 2; + data[65] = 3; + return data; + } + + static byte[] BigTiff () + { + var data = new byte[72]; + data[0] = (byte)'M'; + data[1] = (byte)'M'; + data[3] = 0x2B; + BinaryPrimitives.WriteUInt16BigEndian (data.AsSpan (4), 8); + BinaryPrimitives.WriteInt64BigEndian (data.AsSpan (8), 16); + BinaryPrimitives.WriteInt64BigEndian (data.AsSpan (16), 2); + WriteBig (data, 24, 256, 70); + WriteBig (data, 44, 257, 46); + return data; + } + + static void WriteBig (byte[] data, int at, int tag, int value) + { + BinaryPrimitives.WriteUInt16BigEndian (data.AsSpan (at), (ushort)tag); + BinaryPrimitives.WriteUInt16BigEndian (data.AsSpan (at + 2), 3); + BinaryPrimitives.WriteInt64BigEndian (data.AsSpan (at + 4), 1); + BinaryPrimitives.WriteUInt16BigEndian (data.AsSpan (at + 12), (ushort)value); + } +} diff --git a/tests/TagLibSharp2.Tests/Image/ImageMirrorTests.cs b/tests/TagLibSharp2.Tests/Image/ImageMirrorTests.cs new file mode 100644 index 00000000..690fc6d7 --- /dev/null +++ b/tests/TagLibSharp2.Tests/Image/ImageMirrorTests.cs @@ -0,0 +1,961 @@ +// 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.Tests.Core; +using TagLibSharp2.Tests.Kit; +using static TagLibSharp2.Tests.Image.ImageTestBuilder; + +namespace TagLibSharp2.Tests.Image; + +/// +/// A PNG text edit also changes the XMP and Exif copies of the same field, so that no reader (macOS ImageIO +/// prefers them to tEXt) shows the old value. Rule 4: no stale duplicate survives. +/// +[TestClass] +[TestCategory ("Unit")] +public class ImageMirrorTests +{ + static readonly XNamespace Rdf = "http://www.w3.org/1999/02/22-rdf-syntax-ns#"; + static readonly XNamespace Dc = "http://purl.org/dc/elements/1.1/"; + static readonly XNamespace Exif = "http://ns.adobe.com/exif/1.0/"; + + // 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 (ExifOf (input, carrier), ExifOf (output, carrier), spec.ExifTags, ExifBytes (output, carrier)); + } + + 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 (); + } + + static Dictionary ExifOf (byte[] png, string carrier) => ReadExif (ExifBytes (png, carrier)); + + static byte[] ExifBytes (byte[] png, string carrier) + { + byte[] tiff; + if (carrier.Contains ("raw", StringComparison.OrdinalIgnoreCase)) + tiff = DecodeRawProfile (PngTexts (png, "Raw profile type exif").Single ()); + else + tiff = PngChunks (png).Single (c => c.Type == "eXIf").Payload; + if (tiff.AsSpan ().StartsWith ("Exif\0\0"u8)) + tiff = tiff[6..]; + return tiff; + } + + [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); + } + + [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")); + } + + 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}"); + } + + 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"]; + yield return ["eXIf that is not TIFF", Png (PngChunk ("eXIf", [1, 2, 3, 4, 5, 6, 7, 8, 9])), "Artist", "New", "not a TIFF structure"]; + yield return ["raw profile that is not hex", Png (CompressedText ("Raw profile type xmp", "\nxmp\n 4\nzzzz\n"u8.ToArray ())), "Title", "New", "hexadecimal"]; + 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); + } + + [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<"); + } + + 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 = ReadExif (output[at..]); + 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[] 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] + 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 allocated = Bounds.AllocatedBytes (() => { + var 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"); + + Bounds.AssertLinearAllocation (n => ManyCompressedPackets (n, 2000), data => { + var png = Open (data, "a.png"); + png.Tag!.Title = "New"; + Assert.IsTrue (png.SaveToFile ("/a.png", new MockFileSystem ()).IsSuccess); + }, 20); + } + + // 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; + ImageMirrors.SpliceWrites = 0; + Assert.IsTrue (ImageMirrors.TryUpdateXmp (packet, tag, "PNG XMP packet", out var updated, out var error), error); + Assert.AreEqual (updated.Length, ImageMirrors.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)); + } + } + } + + 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 is zeroed only where its bytes belong to it alone (rule 6: the other values keep theirs). + [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 file = Open (Png (PngChunk ("eXIf", tiff), Text ("Author", "a")), "a.png"); + file.Tag!.Artist = "New"; + + var save = file.SaveToFile ("/a.png", new MockFileSystem ()); + 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 = ReadExif (exif); + 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)]; + } + + [TestMethod] + [DataRow ("IFD1 value")] + [DataRow ("thumbnail")] + [DataRow ("GPS value")] + public void Edit_RemovedExifValue_KeepsBytesTheThumbnailIfd1OrGpsUse (string shape) + { + var tiff = SharedArtistTiff (shape); + var file = Open (Png (PngChunk ("eXIf", tiff), Text ("Author", "a")), "a.png"); + file.Tag!.Artist = "New"; + var save = file.SaveToFile ("/a.png", new MockFileSystem ()); + Assert.IsTrue (save.IsSuccess, save.Error); + var exif = PngChunks (file.Render ().ToArray ()).Single (c => c.Type == "eXIf").Payload; + Assert.IsTrue (exif.AsSpan ().IndexOf ("OldArtist\0"u8) > 0, $"{shape}: the shared bytes are kept"); + Assert.IsFalse (ReadExif (exif).ContainsKey (0x013B), $"{shape}: Artist is removed"); + Assert.AreEqual ("CanonMake", ReadExif (exif)[0x010F]); + } + + // 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"; + ImageMirrors.ExifSteps = 0; + Assert.IsTrue (ImageMirrors.TryRemoveExif (data, 0, tag, "eXIf", out var changed, out var error), error); + Assert.IsTrue (changed); + return ImageMirrors.ExifSteps; + } + + 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. + foreach (var (n, count) in steps) + Assert.IsTrue (count <= 8L * 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"); + } + + 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); + } + + 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]; + } + + // A little-endian TIFF laid out by hand: each table at its own offset, then the data. + sealed class HandTiff + { + readonly byte[] _data; + + public HandTiff (int length) + { + _data = new byte[length]; + "II*\0"u8.CopyTo (_data); + BitConverter.GetBytes (8).CopyTo (_data, 4); + } + + public HandTiff Table (int at, params (int Tag, int Type, int Count, int Value)[] entries) + { + BitConverter.GetBytes ((ushort)entries.Length).CopyTo (_data, at); + for (var n = 0; n < entries.Length; n++) { + var e = at + 2 + (12 * n); + BitConverter.GetBytes ((ushort)entries[n].Tag).CopyTo (_data, e); + BitConverter.GetBytes ((ushort)entries[n].Type).CopyTo (_data, e + 2); + BitConverter.GetBytes (entries[n].Count).CopyTo (_data, e + 4); + BitConverter.GetBytes (entries[n].Value).CopyTo (_data, e + 8); + } + + return this; + } + + public HandTiff Bytes (int at, ReadOnlySpan bytes) + { + bytes.CopyTo (_data.AsSpan (at)); + return this; + } + + public byte[] ToArray () => _data; + } + + // The UserComment entries a reader finds in every table an IFD0 0x8769 entry points at, IFD0 included. + static List UserCommentsInEveryExifIfd (byte[] tiff) + { + var found = new List (); + var ifd0 = BitConverter.ToInt32 (tiff, 4); + var tables = new List { ifd0 }; + for (var n = 0; n < BitConverter.ToUInt16 (tiff, ifd0); n++) { + var e = ifd0 + 2 + (12 * n); + var at = BitConverter.ToInt32 (tiff, e + 8); + if (BitConverter.ToUInt16 (tiff, e) == 0x8769 && at >= 8 && at + 2 <= tiff.Length && at + 6 + (12 * BitConverter.ToUInt16 (tiff, at)) <= tiff.Length) + tables.Add (at); + } + + foreach (var table in tables) { + for (var n = 0; n < BitConverter.ToUInt16 (tiff, table); n++) { + if (BitConverter.ToUInt16 (tiff, table + 2 + (12 * n)) == 0x9286) + found.Add (table); + } + } + + return found; + } + + static readonly byte[] OldOne = "ASCII\0\0\0old comment one"u8.ToArray (); + static readonly byte[] OldTwo = "ASCII\0\0\0old comment two"u8.ToArray (); + + // 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, and + // when an offset/length pair is given twice nothing is zeroed (which bytes it names cannot be told). + [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")] + 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 HandTiff (300).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.Table (Ifd0, (0x8769, 4, 1, ExifA), (0x8769, 4, 1, ExifB)).Table (ExifA, Comment (One, OldOne)).Table (ExifB, Comment (Two, OldTwo)); + break; + case "two Exif IFDs, the other way round": + tiff.Table (Ifd0, (0x8769, 4, 1, ExifB), (0x8769, 4, 1, ExifA)).Table (ExifA, Comment (One, OldOne)).Table (ExifB, Comment (Two, OldTwo)); + break; + case "the same Exif IFD twice": + tiff.Table (Ifd0, (0x8769, 4, 1, ExifA), (0x8769, 4, 1, ExifA)).Table (ExifA, Comment (One, OldOne), (0x9003, 7, 4, 0x31303032), Comment (Two, OldTwo), (0x9004, 7, 4, 0x31303032)); + break; + case "the Exif IFD is IFD0": + tiff.Table (Ifd0, (0x8769, 4, 1, Ifd0), Comment (One, OldOne), Comment (Two, OldTwo)); + break; + case "a second GPS IFD shares the old comment's bytes": + tiff.Table (Ifd0, (0x8769, 4, 1, ExifA), (0x8825, 4, 1, Gps), (0x8825, 4, 1, Gps + 20)).Table (ExifA, Comment (One, OldOne), Comment (Two, OldTwo)) + .Table (Gps, (0x0001, 2, 2, 0x4E)).Table (Gps + 20, (0x001B, 7, OldTwo.Length, Two)); + shared = true; + break; + case "a second Exif IFD's interoperability IFD shares them": + tiff.Table (Ifd0, (0x8769, 4, 1, ExifA), (0x8769, 4, 1, ExifB)).Table (ExifA, Comment (One, OldOne)) + .Table (ExifB, Comment (Two, OldTwo), (0xA005, 4, 1, Interop)).Table (Interop, (0x0002, 7, OldTwo.Length, Two)); + shared = true; + break; + case "an empty Exif IFD pointer before the real one": + tiff.Table (Ifd0, (0x8769, 4, 1, 0), (0x8769, 4, 1, ExifA)).Table (ExifA, Comment (One, OldOne), Comment (Two, OldTwo)); + break; + default: + tiff.Table (Ifd0, (0x8769, 4, 1, ExifA), (0x0111, 4, 1, Gps), (0x0117, 4, 1, 4), (0x0111, 4, 1, Two), (0x0117, 4, 1, 4)).Table (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 ()); + 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"); + 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)); + } + + var zeroesNothing = shape == "StripOffsets given twice"; + Assert.AreEqual (zeroesNothing, exif.AsSpan ().IndexOf ("old comment one"u8) >= 0, $"{shape}: the first comment's bytes are zeroed unless nothing can be"); + Assert.AreEqual (shared || zeroesNothing, exif.AsSpan ().IndexOf ("old comment two"u8) >= 0, $"{shape}: the second comment's bytes are kept only when another IFD uses them"); + } + + // 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). + [TestMethod] + [DataRow (0x8769)] + [DataRow (0x8825)] + public void Edit_IfdsThatOverlap_AreRefusedBeforeTheyAreWalked (int tag) + { + // 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 ((0x9C9C, 1, 4, 0x41424344)); + var tiff = new HandTiff (9100).Table (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"; + + ImageMirrors.ExifSteps = 0; + var save = file.SaveToFile ("/a.png", new MockFileSystem ()); + + Assert.IsFalse (save.IsSuccess); + StringAssert.Contains (save.Error, "overlap"); + Assert.IsTrue (ImageMirrors.ExifSteps <= 9100, $"{ImageMirrors.ExifSteps} steps before the refusal"); + } + + // 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) + { + 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 HandTiff (value + OldOne.Length); + var comment = (0x9286, 7, OldOne.Length, value); + switch (shape) { + case "self": + tiff.Table (Ifd0, [.. Enumerable.Range (0, n).Select (_ => (0x8769, 4, 1, Ifd0)), comment]); + break; + case "one": + tiff.Table (Ifd0, [.. Enumerable.Range (0, n).Select (_ => (0x8769, 4, 1, exif))]); + tiff.Table (exif, [.. Enumerable.Range (0, n - 1).Select (k => (0x9003, 7, 4, k)), comment]); + break; + case "many": + tiff.Table (Ifd0, [.. Enumerable.Range (0, n).Select (k => (0x8769, 4, 1, exif + (18 * k))), comment]); + for (var k = 0; k < n; k++) + tiff.Table (exif + (18 * k), (0x9003, 7, 4, k)); + break; + case "gps-mix": + tiff.Table (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.Table (Ifd0, [.. Enumerable.Range (0, n).Select (k => k % 2 == 0 ? (0x8769, 4, 1, Ifd0) : (0xA005, 4, 1, interop)), comment]); + break; + } + + tiff.Table (interop, (0x0001, 2, 4, 0x00383952)); + tiff.Table (gps, (0x0001, 2, 2, 0x4E)); + return tiff.Bytes (value, OldOne).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"; + ImageMirrors.ExifSteps = 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 ImageMirrors.ExifSteps; + } + + // 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] + [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 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 HandTiff (160).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.Table (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.Table (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); + Assert.IsTrue (exifOut.AsSpan ().IndexOf ("old comment one"u8) < 0, shape); + } + + // 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") { + Assert.IsNotNull (file.ImageProperties); + return; + } + + if (op == "clear") + file.Tag!.Clear (); + else + file.Tag!.Comment = "New"; + _ = file.Render (); + } + + // Every walk over IFD pointers and tables (read, 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. + public static IEnumerable Walks () + { + foreach (var op in new[] { "read", "clear", "edit" }) { + foreach (var shape in new[] { "self", "one", "mix", "many", "gps-mix" }) { + yield return [op, "png", shape, 600]; + yield return [op, "jpeg", shape, 300]; + } + } + } + + [TestMethod] + [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); + ImageMirrors.ExifSteps = 0; + RunWalk (op, data, name); + return ImageMirrors.ExifSteps; + } + + 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"); + Assert.IsTrue (large <= 40L * 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); + } +} diff --git a/tests/TagLibSharp2.Tests/Image/ImageReviewTests.cs b/tests/TagLibSharp2.Tests/Image/ImageReviewTests.cs new file mode 100644 index 00000000..1b1f3295 --- /dev/null +++ b/tests/TagLibSharp2.Tests/Image/ImageReviewTests.cs @@ -0,0 +1,323 @@ +// 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.Tests.Kit; + +namespace TagLibSharp2.Tests.Image; + +[TestClass] +[TestCategory ("Unit")] +public class ImageReviewTests +{ + [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)); + } + + [TestMethod] + public void ReadAsync_OpensAnImageAndHonoursCancellationDuringTheBodyRead () + { + var png = Png (); + 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 ()); + } + + [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 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); + } + + // 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); + _ = MediaFile.ReadFromData (data, "a.jpg"); + var allocated = Bounds.AllocatedBytes (() => Assert.IsTrue (MediaFile.ReadFromData (data, "a.jpg").IsSuccess)); + Assert.IsTrue (allocated < 16 * 1024, $"a 600 KB scan allocated {allocated} bytes"); + } + + [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), "a.tif", 70, 46); + } + + 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); + } + + static byte[] Png () + { + var ihdr = new byte[] { 0, 0, 0, 1, 0, 0, 0, 1, 8, 0, 0, 0, 0 }; + return Concat (new byte[] { 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A }, Chunk ("IHDR", ihdr), Chunk ("IDAT", [0x01]), Chunk ("IEND", [])); + } + + static byte[] Chunk (string type, byte[] payload) + { + var typeBytes = Encoding.ASCII.GetBytes (type); + var crcInput = new byte[4 + payload.Length]; + typeBytes.CopyTo (crcInput, 0); + payload.CopyTo (crcInput, 4); + var crc = new BinaryData (crcInput).ComputeCrc32 (); + var chunk = new byte[12 + payload.Length]; + chunk[0] = (byte)(payload.Length >> 24); + chunk[1] = (byte)(payload.Length >> 16); + chunk[2] = (byte)(payload.Length >> 8); + chunk[3] = (byte)payload.Length; + typeBytes.CopyTo (chunk, 4); + payload.CopyTo (chunk, 8); + chunk[^4] = (byte)(crc >> 24); + chunk[^3] = (byte)(crc >> 16); + chunk[^2] = (byte)(crc >> 8); + chunk[^1] = (byte)crc; + return chunk; + } + + static byte[] PreviewIfd (bool dng, int fullWidth, int fullHeight) + { + var entries = dng ? 5 : 4; + var root = 2 + (entries * 12) + 4; + var child = 2 + (3 * 12) + 4; + var data = new byte[8 + root + child]; + data[0] = (byte)'I'; + data[1] = (byte)'I'; + data[2] = 42; + WriteInt (data, 4, 8); + WriteShort (data, 8, entries); + var entry = 10; + WriteLong (data, entry, 254, 1); + entry += 12; + WriteLong (data, entry, 256, 256); + entry += 12; + WriteLong (data, entry, 257, 171); + entry += 12; + WriteLong (data, entry, 330, 8 + root); + entry += 12; + if (dng) + WriteLong (data, entry, 0xC612, 1); + var sub = 8 + root; + WriteShort (data, sub, 3); + WriteLong (data, sub + 2, 254, 0); + WriteLong (data, sub + 14, 256, fullWidth); + WriteLong (data, sub + 26, 257, fullHeight); + return data; + } + + static byte[] LinkedTiff () + { + var data = new byte[8 + 30 + 30]; + data[0] = (byte)'I'; + data[1] = (byte)'I'; + data[2] = 42; + WriteInt (data, 4, 8); + WriteShort (data, 8, 2); + WriteLong (data, 10, 256, 10); + WriteLong (data, 22, 257, 10); + WriteInt (data, 34, 38); + WriteShort (data, 38, 2); + WriteLong (data, 40, 256, 100); + WriteLong (data, 52, 257, 100); + return data; + } + + static byte[] CyclicSubIfd () + { + var data = new byte[8 + 2 + (4 * 12) + 4]; + data[0] = (byte)'I'; + data[1] = (byte)'I'; + data[2] = 42; + WriteInt (data, 4, 8); + WriteShort (data, 8, 4); + WriteLong (data, 10, 254, 1); + WriteLong (data, 22, 256, 4); + WriteLong (data, 34, 257, 5); + WriteLong (data, 46, 330, 8); + return data; + } + + static byte[] BigTiff (int width, int height) + { + var data = new byte[72]; + data[0] = (byte)'I'; + data[1] = (byte)'I'; + data[2] = 0x2B; + System.Buffers.Binary.BinaryPrimitives.WriteUInt16LittleEndian (data.AsSpan (4), 8); + System.Buffers.Binary.BinaryPrimitives.WriteInt64LittleEndian (data.AsSpan (8), 16); + System.Buffers.Binary.BinaryPrimitives.WriteInt64LittleEndian (data.AsSpan (16), 2); + WriteBigShort (data, 24, 256, width); + WriteBigShort (data, 44, 257, height); + return data; + } + + static void WriteBigShort (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.WriteInt64LittleEndian (data.AsSpan (at + 4), 1); + System.Buffers.Binary.BinaryPrimitives.WriteUInt16LittleEndian (data.AsSpan (at + 12), (ushort)value); + } + + static void WriteShort (byte[] data, int offset, int value) + { + data[offset] = (byte)value; + data[offset + 1] = (byte)(value >> 8); + } + + static void WriteInt (byte[] data, int offset, int value) + { + data[offset] = (byte)value; + data[offset + 1] = (byte)(value >> 8); + data[offset + 2] = (byte)(value >> 16); + data[offset + 3] = (byte)(value >> 24); + } + + static void WriteLong (byte[] data, int offset, int tag, int value) + { + WriteShort (data, offset, tag); + WriteShort (data, offset + 2, 4); + WriteInt (data, offset + 4, 1); + WriteInt (data, offset + 8, value); + } + + 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; + } + + 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); + } + } +} diff --git a/tests/TagLibSharp2.Tests/Image/ImageSaveContractTests.cs b/tests/TagLibSharp2.Tests/Image/ImageSaveContractTests.cs new file mode 100644 index 00000000..a3040739 --- /dev/null +++ b/tests/TagLibSharp2.Tests/Image/ImageSaveContractTests.cs @@ -0,0 +1,338 @@ +// 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; + +/// +/// What every image save keeps and what Clear removes, over each rewriter (PNG, GIF, JPEG). +/// +[TestClass] +[TestCategory ("Unit")] +public class ImageSaveContractTests +{ + 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 ()); + } + + 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] + [DynamicData (nameof (ClearCases))] + 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); + } + } + + [TestMethod] + public void Gif_UnspliceableSave_NamesTheReason () + { + var gif = Gif (GifComment ("c")); + gif[^1] = 0x99; + var file = Open (gif, "a.gif"); + file.Tag!.Comment = "x"; + var result = file.SaveToFile ("/a.gif", new MockFileSystem ()); + Assert.IsFalse (result.IsSuccess); + StringAssert.Contains (result.Error, "GIF"); + } + + [TestMethod] + public void Jpeg_UnspliceableSave_NamesTheReason () + { + var jpeg = Concat ([0xFF, 0xD8], JpegSegment (0xFE, "c"u8.ToArray ()), JpegSegment (0xC0, [8, 0, 1, 0, 1, 1, 1, 0x11, 0]), [0x00, 0x01]); + var file = Open (jpeg, "a.jpg"); + file.Tag!.Comment = "x"; + var result = file.SaveToFileAsync ("/a.jpg", new MockFileSystem ()).GetAwaiter ().GetResult (); + Assert.IsFalse (result.IsSuccess); + StringAssert.Contains (result.Error, "JPEG"); + } + + 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"); + } + + 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/ImageTestBuilder.cs b/tests/TagLibSharp2.Tests/Image/ImageTestBuilder.cs new file mode 100644 index 00000000..0413abb5 --- /dev/null +++ b/tests/TagLibSharp2.Tests/Image/ImageTestBuilder.cs @@ -0,0 +1,613 @@ +// 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; + +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); + } + } + } + + /// Reads the ASCII values of IFD0 and the Exif IFD of a little-endian TIFF, as a reader would. + public static Dictionary ReadExif (byte[] tiff) + { + var result = new Dictionary (); + var ifd0 = BinaryPrimitives.ReadInt32LittleEndian (tiff.AsSpan (4)); + var exif = ReadIfd (tiff, ifd0, result); + if (exif > 0) + ReadIfd (tiff, exif, result); + return result; + } + + static int ReadIfd (byte[] tiff, int at, Dictionary result) + { + var exif = 0; + var count = BinaryPrimitives.ReadUInt16LittleEndian (tiff.AsSpan (at)); + for (var n = 0; n < count; n++) { + var e = at + 2 + (12 * n); + var tag = BinaryPrimitives.ReadUInt16LittleEndian (tiff.AsSpan (e)); + var type = BinaryPrimitives.ReadUInt16LittleEndian (tiff.AsSpan (e + 2)); + var length = BinaryPrimitives.ReadInt32LittleEndian (tiff.AsSpan (e + 4)); + if (tag == 0x8769) + exif = BinaryPrimitives.ReadInt32LittleEndian (tiff.AsSpan (e + 8)); + if (type != 2) + continue; + var valueAt = length <= 4 ? e + 8 : BinaryPrimitives.ReadInt32LittleEndian (tiff.AsSpan (e + 8)); + result[tag] = Encoding.ASCII.GetString (tiff, valueAt, length).TrimEnd ('\0'); + } + + return exif; + } + + 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!; + } + + 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; + } +} diff --git a/tests/TagLibSharp2.Tests/Image/ImageWriteTests.cs b/tests/TagLibSharp2.Tests/Image/ImageWriteTests.cs new file mode 100644 index 00000000..9fcbf822 --- /dev/null +++ b/tests/TagLibSharp2.Tests/Image/ImageWriteTests.cs @@ -0,0 +1,749 @@ +// 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; +using TagLibSharp2.Image; +using TagLibSharp2.Tests.Core; + +namespace TagLibSharp2.Tests.Image; + +[TestClass] +[TestCategory ("Unit")] +public class ImageWriteTests +{ + [TestMethod] + public void Png_RoundTripsMappedText_AndLeavesPixelsAndUntouchedChunks () + { + var idat = new byte[] { 0x01, 0x02, 0x03, 0x04 }; + var software = TextChunk ("Software", "camera"); + var data = Png ( + TextChunk ("Title", "Door"), + TextChunk ("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, Payload (rendered, "IDAT")); + CollectionAssert.AreEqual (software, Chunk (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 (HasChunk (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, Payload (cleared, "IDAT")); + } + + [TestMethod] + public void Png_UnicodeAndCompressedText_RoundTrip () + { + var title = Encoding.Latin1.GetBytes ("Door"); + var zlib = Zlib (title); + 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 = Png (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, Chunk (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 (HasChunk (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 }, Payload (replaced, "IDAT")); + } + + [TestMethod] + public void Png_WithoutAnEndChunk_KeepsTheOriginalBytes () + { + var data = Concat (Signature (), PngChunk ("IHDR", Ihdr ()), TextChunk ("Title", "Door")); + var file = Open (data, "photo.png"); + file.Tag!.Title = "Other"; + CollectionAssert.AreEqual (data, file.Render ().ToArray ()); + } + + [TestMethod] + public void Png_CompressedTextOverTheCap_IsLeftUnread () + { + var huge = new byte[1024 * 1024 + 1]; + var ztxt = Png (CompressedText ("zTXt", "Title", huge, utf8: false), PngChunk ("IDAT", [0x11])); + var itxt = Png (CompressedText ("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 }, Payload (ztxt, "IDAT")); + } + + [TestMethod] + public void Png_SmallCompressedInternationalText_IsRead () + { + var data = Png (CompressedText ("iTXt", "Title", System.Text.Encoding.UTF8.GetBytes ("門"), utf8: true)); + Assert.AreEqual ("門", Open (data, "photo.png").Tag!.Title); + } + + [TestMethod] + public void SaveToFile_WhenTheContainerCannotBeUpdated_FailsAndDoesNotWrite () + { + var data = Concat (Signature (), PngChunk ("IHDR", Ihdr ()), TextChunk ("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")); + 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 Gif_RoundTripsComment_AndLeavesImageBytesThatLookLikeAComment () + { + var trap = new byte[] { 0x21, 0xFE, 0x00, 0x99 }; + var data = Gif ("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, ImageSubBlock (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, ImageSubBlock (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 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); + } + + [TestMethod] + public void Png_NewText_IsWrittenBeforeThePixelData () + { + var data = Png (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 }, Payload (rendered, "IDAT")); + } + + [TestMethod] + public void Png_TextWithABadCrc_IsNotLoaded () + { + var chunk = TextChunk ("Title", "Door"); + chunk[^1] ^= 0xFF; + var data = Png (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_Clear_DropsUnmappedText () + { + var data = Png (TextChunk ("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 (HasChunk (rendered, "tEXt")); + CollectionAssert.AreEqual (new byte[] { 0x01 }, Payload (rendered, "IDAT")); + Assert.IsNull (Open (rendered, "photo.png").Tag!.Title); + } + + [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 = Png ( + TextChunk ("Title", "one"), + CompressedText ("zTXt", "Author", author, utf8: false), + CompressedText ("zTXt", "Description", description, utf8: false), + CompressedText ("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); + } + + [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, ImageSubBlock (rendered)); + } + + [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, ImageSubBlock (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); + } + + [TestMethod] + public void FormatsWithoutATextStore_KeepTheOriginalBytes () + { + AssertNoStore (Bmp (4, 2), "a.bmp"); + AssertNoStore (Pcx (), "a.pcx"); + AssertNoStore (Encoding.ASCII.GetBytes ("P4\n1 1\n"), "a.pbm"); + AssertNoStore (Tiff (), "a.tif"); + AssertNoStore (Tiff (), "a.dng"); + AssertNoStore (Encoding.UTF8.GetBytes (""), "a.svg"); + } + + [TestMethod] + public void SaveToFile_WritesTheRenderedBytes () + { + var data = Png (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 }, Payload (fs.ReadAllBytes ("/photo.png"), "IDAT")); + } + + static void AssertNoStore (byte[] data, string name) + { + var file = Open (data, name); + Assert.IsNull (file.Tag); + CollectionAssert.AreEqual (data, file.Render ().ToArray ()); + } + + static StillImageFile Open (byte[] data, string name) + { + var result = MediaFile.ReadFromData (data, name); + Assert.IsTrue (result.IsSuccess, result.Error); + return (StillImageFile)result.File!; + } + + static void AssertPng (byte[] file) + { + var i = 8; + while (i + 12 <= file.Length) { + var length = ReadBe (file, i); + var crcInput = new byte[4 + length]; + Array.Copy (file, i + 4, crcInput, 0, crcInput.Length); + var actual = ReadBe (file, 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[] Png (params byte[][] chunks) => Concat (Signature (), PngChunk ("IHDR", Ihdr ()), Concat (chunks), PngChunk ("IEND", [])); + + static byte[] Signature () => [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]; + + static byte[] Ihdr () => [0, 0, 0, 1, 0, 0, 0, 1, 8, 0, 0, 0, 0]; + + static byte[] TextChunk (string keyword, string text) + { + var key = Encoding.Latin1.GetBytes (keyword); + var value = Encoding.Latin1.GetBytes (text); + var payload = new byte[key.Length + 1 + value.Length]; + key.CopyTo (payload, 0); + value.CopyTo (payload, key.Length + 1); + return PngChunk ("tEXt", payload); + } + + static byte[] PngChunk (string type, byte[] payload) + { + var typeBytes = Encoding.ASCII.GetBytes (type); + var crcInput = new byte[4 + payload.Length]; + typeBytes.CopyTo (crcInput, 0); + payload.CopyTo (crcInput, 4); + var crc = new BinaryData (crcInput).ComputeCrc32 (); + var chunk = new byte[12 + payload.Length]; + chunk[0] = (byte)(payload.Length >> 24); + chunk[1] = (byte)(payload.Length >> 16); + chunk[2] = (byte)(payload.Length >> 8); + chunk[3] = (byte)payload.Length; + typeBytes.CopyTo (chunk, 4); + payload.CopyTo (chunk, 8); + chunk[^4] = (byte)(crc >> 24); + chunk[^3] = (byte)(crc >> 16); + chunk[^2] = (byte)(crc >> 8); + chunk[^1] = (byte)crc; + return chunk; + } + + static byte[] Gif (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; + } + + static byte[] ImageSubBlock (byte[] gif) + { + var i = gif.Length - 1; + while (i > 0 && gif[i] != 0x2C) + i--; + i += 10; + i++; + var size = gif[i++]; + var block = new byte[size]; + Array.Copy (gif, i, block, 0, size); + return block; + } + + 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; + } + + static byte[] Bmp (int width, int height) + { + var data = new byte[54]; + data[0] = (byte)'B'; + data[1] = (byte)'M'; + WriteLe (data, 14, 40); + WriteLe (data, 18, width); + WriteLe (data, 22, height); + data[28] = 24; + return data; + } + + static byte[] Pcx () + { + var data = new byte[128]; + data[0] = 0x0A; + data[1] = 5; + data[2] = 1; + data[3] = 8; + data[8] = 1; + data[10] = 1; + data[65] = 1; + return data; + } + + static byte[] Tiff () + { + var data = new byte[8 + 2 + 24 + 4]; + data[0] = (byte)'I'; + data[1] = (byte)'I'; + data[2] = 42; + data[4] = 8; + data[8] = 2; + data[10] = 0; + data[11] = 1; + data[12] = 4; + data[14] = 1; + data[18] = 2; + data[22] = 1; + data[23] = 1; + data[24] = 4; + data[26] = 1; + data[30] = 3; + return data; + } + + static byte[] Chunk (byte[] file, string type, string keyword) + { + var i = 8; + var key = Encoding.ASCII.GetBytes (keyword); + while (i + 12 <= file.Length) { + var length = ReadBe (file, i); + var matches = Encoding.ASCII.GetString (file, i + 4, 4) == type + && length >= key.Length + 1 + && file.AsSpan (i + 8, key.Length).SequenceEqual (key) + && file[i + 8 + key.Length] == 0; + var next = i + 12 + length; + if (matches) { + var chunk = new byte[next - i]; + Array.Copy (file, i, chunk, 0, chunk.Length); + return chunk; + } + + i = next; + } + + return []; + } + + static byte[] TextBytes (byte[] file, string type, string keyword) + { + var chunk = Chunk (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 byte[] Payload (byte[] file, string type) + { + var i = 8; + while (i + 12 <= file.Length) { + var length = ReadBe (file, i); + if (Encoding.ASCII.GetString (file, i + 4, 4) == type) { + var payload = new byte[length]; + Array.Copy (file, i + 8, payload, 0, length); + return payload; + } + + i += 12 + length; + } + + return []; + } + + static bool HasChunk (byte[] file, string type) + { + var i = 8; + while (i + 8 <= file.Length) { + var length = ReadBe (file, i); + if (Encoding.ASCII.GetString (file, i + 4, 4) == type) + return true; + i += 12 + length; + } + + return false; + } + + 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 + ReadBe (file, i); + } + + return -1; + } + + 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; + } + + static byte[] GifWithCommentAfterImage (string comment, byte[] trap) + { + var imageFirst = Gif (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]); + } + + static byte[] GifWithXmp (string comment, byte[] trap) + { + var gif = Gif (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; + } + + static int ReadBe (byte[] data, int offset) => + (data[offset] << 24) | (data[offset + 1] << 16) | (data[offset + 2] << 8) | data[offset + 3]; + + static byte[] CompressedText (string type, string keyword, byte[] raw, bool utf8) + { + var key = System.Text.Encoding.ASCII.GetBytes (keyword); + var zlib = Zlib (raw); + 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); + } + + static byte[] Zlib (byte[] raw) + { + using var output = new MemoryStream (); + using (var zlib = new ZLibStream (output, CompressionLevel.SmallestSize, leaveOpen: true)) + zlib.Write (raw, 0, raw.Length); + return output.ToArray (); + } + + static byte[] Concat (params byte[][] parts) + { + var length = 0; + foreach (var part in parts) + length += part.Length; + var data = new byte[length]; + var i = 0; + foreach (var part in parts) { + part.CopyTo (data, i); + i += part.Length; + } + + return data; + } + + static void WriteLe (byte[] data, int offset, int value) + { + data[offset] = (byte)value; + data[offset + 1] = (byte)(value >> 8); + data[offset + 2] = (byte)(value >> 16); + data[offset + 3] = (byte)(value >> 24); + } +} diff --git a/tests/TagLibSharp2.Tests/Image/StillImageFileEntryTests.cs b/tests/TagLibSharp2.Tests/Image/StillImageFileEntryTests.cs new file mode 100644 index 00000000..326d507d --- /dev/null +++ b/tests/TagLibSharp2.Tests/Image/StillImageFileEntryTests.cs @@ -0,0 +1,123 @@ +// 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; + +/// +/// opens directly, like every other file class (NEW-FORMAT-CHECKLIST: Read, +/// ReadFromFile, ReadFromFileAsync), and agrees with . +/// +[TestClass] +[TestCategory ("Unit")] +public class StillImageFileEntryTests +{ + 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/Kit/Bounds.cs b/tests/TagLibSharp2.Tests/Kit/Bounds.cs index 244454a6..efa07074 100644 --- a/tests/TagLibSharp2.Tests/Kit/Bounds.cs +++ b/tests/TagLibSharp2.Tests/Kit/Bounds.cs @@ -46,23 +46,28 @@ public static long AssertAllocatesAtMost (long limit, Action action, string? wha /// 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. /// - 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 filters allocations another + /// thread causes, such as a shared that another test emptied. + 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 one = Measure (build (n), run, runs); + var two = Measure (build (n * 2), run, runs); + var four = Measure (build (n * 4), run, runs); var first = Math.Max (two - one, 1); 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"); } - static long Measure (byte[] input, Action run) + static long Measure (byte[] input, Action run, int runs) { run (input); - return AllocatedBytes (() => run (input)); + var least = long.MaxValue; + for (var r = 0; r < Math.Max (runs, 1); r++) + least = Math.Min (least, AllocatedBytes (() => run (input))); + return least; } } 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/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/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.