diff --git a/CHANGELOG.md b/CHANGELOG.md index 94b0fab9..722c56aa 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,9 +13,19 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - **Changed**: `MediaFile.ReadAsync (path, default)` and `MediaFile.ReadAsync (stream, default)` no longer compile: `default` now matches both the old overload and the new one that takes `MediaReadOptions` (CS0121). Pass `null`, or name the parameter (#157) - **Changed**: `AiffFile.Tag` is now a get-only `Tag?` view over the ID3 chunk and the native AIFF text chunks (it was a settable `Id3v2Tag?`). Assign or read the ID3 tag through the new `AiffFile.Id3v2Tag` property; code that assigned `AiffFile.Tag` or used ID3-only members on it no longer compiles. `AiffFile.Tag.Render()` throws `NotSupportedException`, as the other combined views do; render the `AiffFile` instead - **Changed**: `Id3v2Tag.IsEmpty` is false when the tag holds any frame, including lyrics, ratings, pictures, comments, user text, URLs and private frames. It used to check only the basic fields, so WAV and AIFF saves dropped an ID3 chunk that held only, for example, a composer, a publisher or a BPM +- **Changed**: `Tag` is no longer null on a tagless `Mp3File`, `AacFile`, `DsfFile`, `DffFile`, `MpegPsFile`, `AiffFile`, `FlacFile`, `WavPackFile`, `MonkeysAudioFile` or `MusepackFile`, nor `IMediaFile.Tag` on a tagless `WavFile` or on an `Mp4File` with no `ilst`. It is an empty view whose `TagType` is `None`: test `Tag.IsEmpty` (no standard field and no picture), or the format's stored-tag properties, to find an untagged file. Reading the view does not change the file; the first value written creates the format's tag on save (ID3v2 for MP3, AAC, DSF, DFF and MPEG-PS, the ID3 chunk for AIFF and WAV, a Vorbis comment for FLAC, APEv2 for WavPack, Monkey's Audio and Musepack, an `ilst` for MP4; `Mp4File.Tag` itself stays null until then). On WAV that is an `id3 ` chunk rather than RIFF INFO, which holds one Latin-1 value per field; reading the view leaves `WavFile.InfoTag` null. A write that leaves the tag the view created empty (null, `Clear`, writing back an empty value, or a value set and later cleared) removes it again, so the save writes the file as a save with no edit does; a save also writes nothing for a created tag emptied through the stored-tag property (`Id3v2Tag`, `ApeTag`, `VorbisComment`, `Mp4File.Tag`), and a reference to a tag the view dropped no longer reaches the file. The view's `SupportsCustomFields` answers for the tag its first write creates. `Tag` is null after `Dispose`. On a tagless DSF, DFF, WavPack, Monkey's Audio or Musepack file it is a `CombinedTag`, not an `Id3v2Tag` or `ApeTag`, and so is `IMediaFile.Tag` on an MP4 with no `ilst`. Still images that have no text store (TIFF, DNG, BMP, PCX, Netpbm, SVG) still return null. `MediaFileResult.Tag` is the opened file's `Tag`, read each time it is read, so it is that view too (it was null for a tagless WAV, DSF or DFF file). +- **Changed**: ID3v2 text lists split on NUL only, in v2.2, v2.3 and v2.4. `Performers`, `AlbumArtists`, `Composers`, `Genres` and `GetTextFrameValues` no longer split on `/`, so a v2.3 `AC/DC` reads as one value, as ffprobe, exiftool and MediaInfo read it. Writes join on NUL in every version. This applies to ID3v2 in MP3, WAV, AIFF, DSF, DFF, raw AAC, MPEG-PS and AVI; `n/m` numbers and `(17)` genres are unchanged +- **Changed**: `ApePicture.GetKeyForPictureType` and `GetKey` return `Cover Art ()` for a role without its own key, instead of `Cover Art (Front)`; `LeadArtist` is `Cover Art (LeadArtist)`, no longer `Cover Art (Artist)`. `GetPictureTypeForKey` reads those names in any case and with a space between words (`Cover Art (Lead Artist)`), and returns `Other` for a null key and for a key that is not a role's name, such as `Cover Art (3)` or `Cover Art (Other, BackCover)` +- **Changed**: an `Mp4File` with a video track reports it: `IMediaFile.VideoProperties` is no longer always null, `MediaTypes` includes `Video` (and is `Video` alone for a file with no audio), and `Properties` describes the audio track only. A track that another track names as chapters (`tref`/`chap`), such as Apple's chapter images in an `.m4a`, is neither the video nor the audio, so such an `.m4a` still reports `Audio` alone +- **Changed**: `Mp4Picture.PictureType` returns the role this library stored in the `covr` data atom's locale (see Added) instead of always `FrontCover`. A picture whose locale is 0, or any real country or language, is still `FrontCover` ### Added +- `Mp4File.VideoProperties` (`VideoProperties?`) gives the width, height, codec, duration and rotation of the first video track, or null without one. Width and height are the sample entry's coded size, as ffprobe and MediaInfo report it: the track matrix is not applied and the pixel aspect ratio is ignored. An `mp4v` track's codec comes from its `esds` object type (MPEG-4, MPEG-1 Video, MPEG-2 Video, JPEG, PNG, JPEG 2000) +- `VideoProperties.Rotation`: the clockwise rotation, 0 to 359 degrees, that the file asks a player to apply. MP4 and QuickTime read it from the track header matrix (0 when the matrix mirrors or skews the picture); Matroska reads `ProjectionPoseRoll` for a rectangular projection with no yaw or pitch. Other formats report 0 +- JPEG `Tag.Title` reads and writes the title. It is stored in XMP `dc:title` as one `x-default` item, in a new XMP segment after the JFIF and Exif segments when the file has none, and read from there or from IFD0 `XPTitle` (0x9C9B) when the XMP has none. A set or a clear removes every `XPTitle` through the plain-structure Exif edit, so ExifTool, Exiv2, macOS ImageIO, Spotlight and TagLib# show the new title. A title whose XMP would not fit in one 64 KB APP1 segment, or that XML cannot hold, is refused, as is an edit when extended XMP holds a title. IPTC `ObjectName` and Exif `ImageDescription` are not changed, so after a clear ImageIO can still show an IPTC `ObjectName` as the title +- MP4 `covr` pictures keep a role other than front cover by a private convention: the data atom's locale holds the role, one higher than the ID3 picture type, in its top byte, a country byte no real locale uses. AVFoundation, QuickLook, ffprobe, ExifTool and MediaInfo still show the image as a cover; a reader that matched the locale to the user's country would skip it. APE cover items keep every picture role +- Tagless MP3, AAC, DSF, DFF, MPEG-PS, AIFF, WAV, FLAC, WavPack, Monkey's Audio, Musepack and MP4 files accept `file.Tag.Title = …` and the other tag setters without a tag being created first - `MediaReadOptions.SkipPictures` reads a file without its embedded pictures (#157). `MediaFile.Read`, `ReadAsync` and `ReadFromData` take the options; the existing overloads read every picture as before. A skip read returns what a full read returns once its pictures are cleared, `Tag.Pictures` is empty and `PicturesLoaded` is false; a file that a full read rejects is rejected with the same error. Three things differ from clearing a full read with `Tag.Pictures = []`: an APE text or locator item under a "Cover Art" key is kept, because only a binary one is a picture; `Tag.TagType` and `Tag.IsEmpty` describe what remains, so a tag that held only pictures reads as absent; and `AiffFile.AllChunks` holds the ID3 chunk without its picture frames. The pictures left out are FLAC PICTURE blocks, `METADATA_BLOCK_PICTURE` comments in FLAC, Ogg Vorbis, Opus and Ogg FLAC (a value that does not decode as a picture stays a text field, as in a full read), Ogg FLAC PICTURE blocks, ID3v2 APIC and PIC frames in MP3, WAV, AIFF, DSF, DFF, raw AAC, MPEG-PS and AVI, MP4 `covr` items and QuickTime artwork keys, ASF `WM/Picture` descriptors and Metadata and Metadata Library records, APE binary "Cover Art" items in Monkey's Audio, WavPack, Musepack and raw AAC, Matroska image attachments, and the Audible cover. Each walk takes its decisions from the full reader's own rules for that structure, and what it cannot walk it hands to that reader unchanged, so both reads parse the same items. A file path or seekable stream seeks past each picture payload; an ID3 tag unsynchronised as a whole (v2.2, v2.3) and a `METADATA_BLOCK_PICTURE` value are read through once to decode them, and are not kept. Where a walk cannot decide without the picture bytes (a comment value it dropped turns out not to be a picture, Ogg pages that the packet scan would stop on, or Ogg pages that leave a packet open at the end), that part is read as a full read reads it and its pictures are dropped. `ReadFromData` and a stream that cannot seek are walked the same way in memory, so they return what a stream read of the same bytes returns, and keep no copy of a picture. Saving a file read this way fails with "Cannot save because pictures were not loaded. Read the file again without SkipPictures." and writes nothing. `Render` stays available and writes what a full read with its pictures cleared writes, except that it also leaves out Ogg FLAC PICTURE blocks and ASF Metadata Library `WM/Picture` records, which a full read keeps as raw blocks; the Audible cover chunk, which `Render` never changes, stays. A WAV, AIFF, DSF or DFF file read with `SkipPictures` by `ReadFromData` or from a stream keeps no copy of its sound, as a stream read keeps none, so its `Render` throws `InvalidOperationException` when it has sound to write; read it from a path to render it. A still image is the picture, so it keeps its bytes and saves. `ReadAsync` for MP3, FLAC, MPEG-PS, Audible and AVI calls the synchronous skip reader - `Tag.GetCustomField`, `Tag.SetCustomField`, `Tag.RemoveCustomField`, and `Tag.SupportsCustomFields` read, write, and remove a named field with one or more values on any tag (#112). The field lives in the format's @@ -70,7 +80,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - AVI INFO text honours a `CSET` chunk (code page 65001, 1252, 0 or 28591); without one, valid UTF-8 (ffmpeg's and TagLib#'s encoding) is read as UTF-8 and other text as Windows-1252. On save, an unchanged value keeps its exact bytes and the file keeps its `CSET` (or its absence); changed values are written in the file's code page when they fit it (ASCII only when there is no `CSET`), otherwise the list becomes UTF-8 with a `CSET` of code page 65001 before it. When the list becomes UTF-8, untouched text in a declared code page decoded exactly (1252, 28591, 0) is rewritten as the same text in UTF-8; a save that would have to rewrite untouched text whose code page is a guess (no `CSET`), is not decoded here (for example Shift-JIS or cp1251), or that holds a byte its declared code page leaves undefined (0x81, 0x8D, 0x8F, 0x90, 0x9D in 1252; 0x80-0x9F under code page 0) is refused, and the error names the field and which of those reasons applies. A CSET rewritten to 65001 keeps the file's country, language and dialect codes. The five undefined 1252 code points are never written as 1252 bytes; a value holding one goes to UTF-8. WAV INFO is unchanged (Latin-1). - A path save copies `movi` in 64 KB pieces and patches `idx1` and OpenDML indexes from the source, so it no longer loads the file. `Render` and `SaveToFile(path, span)` still build one buffer. `MediaFile.Read` and `AviFile.ReadFromFile` read only the header and tag chunks. - Matroska `AlbumArtistSort` and `ComposerSort`: `SORT_WITH` nested in the album-level `ARTIST` (`TargetTypeValue` 50) and in `COMPOSER`, with flat `ALBUM_ARTIST_SORT` / `COMPOSER_SORT` as the fallback. Clearing removes both forms at every level the getter reads. When the track inherits the album's `ARTIST`, writing either `ArtistSort` or `AlbumArtistSort` first copies that `ARTIST` to the track level, so the other sort is kept (#116). -- Still images: `MediaFile.Read` and `StillImageFile.Read`/`ReadFromFile`/`ReadFromFileAsync` open JPEG, PNG, GIF, BMP, PCX, Netpbm (PBM, PGM, PPM, PNM), TIFF, DNG, and SVG and report width and height. A TIFF or DNG reports the size exiftool's ImageSize gives (measured case by case): the width and height of the first IFD whose NewSubfileType is 0, the full-resolution image, in the order exiftool reads them (IFD0, its SubIFDs depth first with their next IFDs, then IFD0's next IFD), or else IFD0's; unlike exiftool, a width and a height come from one IFD, and a size of 0, a negative one or one past 2^31 - 1 is none. DNG is TIFF with the DNG version tag in IFD0. A table of any size whose entries fit in the data is read, as exiftool reads one of 65,535 entries, and SubIFD offsets are decoded as exiftool decodes them, with the same rules as the Exif pointers below (in BigTIFF also LONG8, SLONG8 and IFD8, but not UNDEFINED); the walk reads at most 4,096 IFDs, 64 SubIFD levels deep, and stops once it has read more entries than tables that do not overlap could hold. A classic IFD is read when 0, 2 or 4 bytes of its next-IFD field are present and is not read when 1 or 3 are (exiftool 13.55 drops that directory). When that directory is IFD0 the file is not opened, and the error is "IFD0's next-IFD field has 1 of its 4 bytes, so IFD0 is not read and the image has no size" (or 3 of its 4 bytes). A wholly missing next field is still read, with no next IFD. A JPEG whose frame height is 0 takes it from the DNL segment after the first scan (ITU-T T.81 §B.2.5). PNG text keywords (Title, Author, Description, Copyright, Creation Time, Comment) are written before the pixel data, the GIF comment after the header, and the JPEG COM marker before the scan; exiftool's PNG `Artist` keyword is read as the artist when there is no `Author`. `Render` copies every other byte, including the pixels and anything after the PNG IEND, the GIF trailer, or the JPEG EOI; a no-op save is byte-identical. A path save (`SaveToFile(path)` and `SaveToFileAsync`) copies those pixels in 64 KB pieces and writes the same bytes as `Render`. When a field changes, its copies elsewhere in the file change too: the XMP property (`dc:title`, `dc:creator`, `dc:description`, `dc:rights`, `exif:UserComment`) is replaced in place, keeping its start and end tags, or removed for null, in PNG `XML:com.adobe.xmp` and ImageMagick's `Raw profile type xmp`, JPEG APP1 XMP, and the GIF XMP extension; the Exif copies (IFD0 `ImageDescription`, `Artist`, `Copyright`, the Windows XP title, author and comment tags, and `UserComment`) are removed from PNG `eXIf`, ImageMagick's raw EXIF, and JPEG APP1 Exif, from every table exiftool reads with its Exif tags (measured with exiftool 13.55): IFD0 and the IFDs chained after it (IFD1, IFD2, ...), and every Exif IFD (0x8769), SubIFD (0x014A) and interoperability IFD (0xA005) any of them points at, however deep (exiftool shows a copy from any of them; ImageIO and TagLib# read a subset), each table walked once. A pointer is followed as exiftool decodes it: a BYTE, SHORT, LONG, SBYTE, SSHORT, SLONG or IFD value, or UNDEFINED with count 1; an Exif IFD pointer only with count 1, a GPS or interoperability pointer by its first value, SubIFDs by every value; a negative value, or values that do not all lie in the data, name nothing; two pointer arrays at one offset are each read by their own type. IFD0's Exif IFD and GPS pointers are also followed as TagLib# reads them, their 4-byte field taken as a LONG whatever their type and count (measured), so the copy TagLib# shows from such a table is removed too, and its GPS table is protected. A GPS table is read with its GPS tags only: nothing in it is edited and no pointer in it is followed. A table is walked when its entries fit in the data. A pointer whose table's entries do not fit is skipped, as readers skip it. A field edit runs only when that structure is plain, and nothing is written otherwise. It is not plain when a strip, tile or thumbnail offset or length (TIFF 6.0 tags 0x0111/0x0117, 0x0144/0x0145 and 0x0201/0x0202) is typed other than SHORT or LONG; when one of those arrays is named more than once (two tables, both sides of one pair, or the same tag twice in one table); when a complete pair names more values than half the bytes; when a classic next-IFD field has only one, two or three of its four bytes (a wholly absent next field stays editable; exiftool itself still reads a table that has two); when removing an entry would change whether exiftool reads that table's first entry, including a change no tag shows; or when a removed value shares a protected byte, or compacting a table would rewrite any protected range other than that table. Two protected ranges may share a byte. Clear does not use this gate. An edit with nothing to remove still saves. A save is also refused when the tables hold more entries than the data could without overlapping and the block's bytes could hold an entry with one of the field's tags, of any type; edits with nothing to remove save. The `Artist` and ImageMagick `exif:*` text keywords are dropped. A packet no XMP reader reads because it is not well-formed, and does not name a changed field, an ImageMagick raw profile that is not hex, and PNG text that is not zlib data or whose iTXt header is cut short, which no reader decodes, are kept as they are; compressed text past the shared inflation budget is refused, since it cannot be checked. For a JPEG or GIF only the comment is stored, so only the comment's copies change. An XMP packet followed by NULs or padding (as ImageIO writes it) is edited and the tail kept, and GIF XMP written as data sub-blocks (ImageIO) is edited as well as the raw form with its magic trailer. A save that cannot update a copy (XMP that is not well-formed or has a DTD and names a changed field's property, a value XML cannot hold, an Exif block that is not classic TIFF and whose bytes could hold an entry with one of the field's tags, in either byte order, a JPEG XMP packet that would outgrow its segment, extended XMP, or a GIF XMP block in neither the raw form with its magic trailer nor data sub-blocks, that holds a UserComment) is refused with its own reason, as is a container that cannot be spliced, or a multi-picture JPEG whose MPF index cannot be corrected or (for Clear) followed; the file is left unchanged. A length-changing edit moves bytes after the edited segment, as exiftool does; a maker-note pointer to data after the image (for example Sony's preview tag 0x2001) is not rewritten (#163). When a maker note is not fully located, a removed value outside the Exif tables keeps its bytes. Inflated PNG text is capped at 1 MiB for the whole file, on read and on save. `Clear` removes all tag metadata and keeps only what a decoder or colour management needs, or the file's structure: PNG critical chunks and tRNS, gAMA, cHRM, sRGB, iCCP, cICP, mDCV, cLLI, sBIT, bKGD, hIST, pHYs, sPLT, the APNG chunks, oFFs, pCAL, sCAL and sTER; JPEG APP0 JFIF/JFXX, APP2 ICC_PROFILE, MPF and the ISO 21496-1 gain map, APP14 Adobe, the XMP an HDR decoder needs to find and apply a gain map (Ultra HDR `hdrgm` and `Container`/`Item` directory, Apple `apdi` and `HDRGainMap` version and headroom, and the motion-photo `Camera:MotionPhoto`, `MotionPhotoVersion` and `MotionPhotoPresentationTimestampUs` so a motion photo stays one; Clear writes a new packet from those properties alone, each checked against the value the format defines (a version, a Boolean, a Real or three, an integer, a timestamp that may be -1, an item semantic of `Primary`, `GainMap` or `MotionPhoto`, a MIME type of `image/jpeg`, `image/heic`, `image/avif`, `video/mp4` or `video/quicktime`, a length or padding), so no other property, attribute, nested structure or text survives; an item value outside those lists is dropped and the item keeps its place and length, a directory item may be written as `rdf:li` > `rdf:Description`, and a directory with an entry that holds no item is dropped whole; the first occurrence of a property wins, and the gain map's `Item:Length` follows its new length while later items such as a motion-photo video keep theirs. An Apple gain map of version 65536 (iPhone 12-14) has no headroom in its XMP: ImageIO and libultrahdr take it from the primary image's Apple maker note, tags 33 and 48. For such a file Clear writes a new Exif in the primary holding only those two maker-note values, copied as stored, and nothing else of the Exif: no IFD0, GPS or other Exif tag and no other maker-note tag. The values kept are the ones ImageIO applies, measured with every level duplicated and broken (where libultrahdr reads a file differently, Clear follows ImageIO): the first Exif segment, whose TIFF magic must be 42; at each level (IFD0's Exif IFD pointers, each Exif IFD's MakerNote entries, the maker note's 0x0021 and 0x0030 entries) an occurrence ImageIO cannot use is skipped and a later usable one overrides an earlier one, two Exif IFDs merging value by value; a maker-note value is usable when it is SRATIONAL with every value inside the maker note, at any offset; the headroom is kept only when both winning entries have count 1 (otherwise ImageIO renders no HDR image), and a winning MakerNote that is not Apple's keeps nothing. ImageIO then renders exactly what it rendered before, HDR or SDR; without the values it renders the photo SDR and libultrahdr refuses it. The new Exif is a minimal carrier for the two decode parameters, not a conformant Exif: it deliberately omits the tags Exif marks mandatory (ExifVersion, ComponentsConfiguration, ColorSpace, the pixel dimensions, YCbCrPositioning, the resolution tags), consistent with Clear removing all other Exif, so `exiftool -validate` warns about them; ImageIO, libultrahdr, ffmpeg, exiftool and TagLib# all read it), and the APP11 JPEG XT decoding boxes (`ftyp`, `TONE`, `RTRF`, `LTRF`, `LCHK`, `SPEC`, `RESI`); GIF graphic control and plain text extensions, looping and ICC application extensions. Everything else goes, including PNG text, `eXIf`, `tIME` and `caBX`, JPEG Exif (but for the Apple headroom above), the rest of XMP and extended XMP, IPTC, maker segments and every other APP11 box (JUMBF/C2PA, `xml `, `uuid`, `json`, `Exif`, unknown), and GIF XMP and ImageMagick's IPTC. In a multi-picture JPEG (MPF), Clear cleans every image the MPF index lists with the same rules; the index's offsets and sizes are rewritten after Clear and after an edit. An MP index outside its APP2 segment, or listing an image before the first image's end (its EOI), outside the file or overlapping another, is not followed: Clear is refused, and so is an edit that would move the later images. Apple's PNG `iDOT` is dropped when a chunk between it and the first IDAT changes. A field the format does not store reads back as null. EXIF, IPTC, and XMP values are not read yet, and SVG metadata is not read or written yet. +- Still images: `MediaFile.Read` and `StillImageFile.Read`/`ReadFromFile`/`ReadFromFileAsync` open JPEG, PNG, GIF, BMP, PCX, Netpbm (PBM, PGM, PPM, PNM), TIFF, DNG, and SVG and report width and height. A TIFF or DNG reports the size exiftool's ImageSize gives (measured case by case): the width and height of the first IFD whose NewSubfileType is 0, the full-resolution image, in the order exiftool reads them (IFD0, its SubIFDs depth first with their next IFDs, then IFD0's next IFD), or else IFD0's; unlike exiftool, a width and a height come from one IFD, and a size of 0, a negative one or one past 2^31 - 1 is none. DNG is TIFF with the DNG version tag in IFD0. A table of any size whose entries fit in the data is read, as exiftool reads one of 65,535 entries, and SubIFD offsets are decoded as exiftool decodes them, with the same rules as the Exif pointers below (in BigTIFF also LONG8, SLONG8 and IFD8, but not UNDEFINED); the walk reads at most 4,096 IFDs, 64 SubIFD levels deep, and stops once it has read more entries than tables that do not overlap could hold. A classic IFD is read when 0, 2 or 4 bytes of its next-IFD field are present and is not read when 1 or 3 are (exiftool 13.55 drops that directory). When that directory is IFD0 the file is not opened, and the error is "IFD0's next-IFD field has 1 of its 4 bytes, so IFD0 is not read and the image has no size" (or 3 of its 4 bytes). A wholly missing next field is still read, with no next IFD. A JPEG whose frame height is 0 takes it from the DNL segment after the first scan (ITU-T T.81 §B.2.5). PNG text keywords (Title, Author, Description, Copyright, Creation Time, Comment) are written before the pixel data, the GIF comment after the header, and the JPEG COM marker before the scan; exiftool's PNG `Artist` keyword is read as the artist when there is no `Author`. `Render` copies every other byte, including the pixels and anything after the PNG IEND, the GIF trailer, or the JPEG EOI; a no-op save is byte-identical. A path save (`SaveToFile(path)` and `SaveToFileAsync`) copies those pixels in 64 KB pieces and writes the same bytes as `Render`. When a field changes, its copies elsewhere in the file change too: the XMP property (`dc:title`, `dc:creator`, `dc:description`, `dc:rights`, `exif:UserComment`) is replaced in place, keeping its start and end tags, or removed for null, in PNG `XML:com.adobe.xmp` and ImageMagick's `Raw profile type xmp`, JPEG APP1 XMP, and the GIF XMP extension; the Exif copies (IFD0 `ImageDescription`, `Artist`, `Copyright`, the Windows XP title, author and comment tags, and `UserComment`) are removed from PNG `eXIf`, ImageMagick's raw EXIF, and JPEG APP1 Exif, from every table exiftool reads with its Exif tags (measured with exiftool 13.55): IFD0 and the IFDs chained after it (IFD1, IFD2, ...), and every Exif IFD (0x8769), SubIFD (0x014A) and interoperability IFD (0xA005) any of them points at, however deep (exiftool shows a copy from any of them; ImageIO and TagLib# read a subset), each table walked once. A pointer is followed as exiftool decodes it: a BYTE, SHORT, LONG, SBYTE, SSHORT, SLONG or IFD value, or UNDEFINED with count 1; an Exif IFD pointer only with count 1, a GPS or interoperability pointer by its first value, SubIFDs by every value; a negative value, or values that do not all lie in the data, name nothing; two pointer arrays at one offset are each read by their own type. IFD0's Exif IFD and GPS pointers are also followed as TagLib# reads them, their 4-byte field taken as a LONG whatever their type and count (measured), so the copy TagLib# shows from such a table is removed too, and its GPS table is protected. A GPS table is read with its GPS tags only: nothing in it is edited and no pointer in it is followed. A table is walked when its entries fit in the data. A pointer whose table's entries do not fit is skipped, as readers skip it. A field edit runs only when that structure is plain, and nothing is written otherwise. It is not plain when a strip, tile or thumbnail offset or length (TIFF 6.0 tags 0x0111/0x0117, 0x0144/0x0145 and 0x0201/0x0202) is typed other than SHORT or LONG; when one of those arrays is named more than once (two tables, both sides of one pair, or the same tag twice in one table); when a complete pair names more values than half the bytes; when a classic next-IFD field has only one, two or three of its four bytes (a wholly absent next field stays editable; exiftool itself still reads a table that has two); when removing an entry would change whether exiftool reads that table's first entry, including a change no tag shows; or when a removed value shares a protected byte, or compacting a table would rewrite any protected range other than that table. Two protected ranges may share a byte. Clear does not use this gate. An edit with nothing to remove still saves. A save is also refused when the tables hold more entries than the data could without overlapping and the block's bytes could hold an entry with one of the field's tags, of any type; edits with nothing to remove save. The `Artist` and ImageMagick `exif:*` text keywords are dropped. A packet no XMP reader reads because it is not well-formed, and does not name a changed field, an ImageMagick raw profile that is not hex, and PNG text that is not zlib data or whose iTXt header is cut short, which no reader decodes, are kept as they are; compressed text past the shared inflation budget is refused, since it cannot be checked. A JPEG stores the comment and the title, and a GIF the comment; only their copies change. An XMP packet followed by NULs or padding (as ImageIO writes it) is edited and the tail kept, and GIF XMP written as data sub-blocks (ImageIO) is edited as well as the raw form with its magic trailer. A save that cannot update a copy (XMP that is not well-formed or has a DTD and names a changed field's property, a value XML cannot hold, an Exif block that is not classic TIFF and whose bytes could hold an entry with one of the field's tags, in either byte order, a JPEG XMP packet that would outgrow its segment, extended XMP, or a GIF XMP block in neither the raw form with its magic trailer nor data sub-blocks, that holds a UserComment) is refused with its own reason, as is a container that cannot be spliced, or a multi-picture JPEG whose MPF index cannot be corrected or (for Clear) followed; the file is left unchanged. A length-changing edit moves bytes after the edited segment, as exiftool does; a maker-note pointer to data after the image (for example Sony's preview tag 0x2001) is not rewritten (#163). When a maker note is not fully located, a removed value outside the Exif tables keeps its bytes. Inflated PNG text is capped at 1 MiB for the whole file, on read and on save. `Clear` removes all tag metadata and keeps only what a decoder or colour management needs, or the file's structure: PNG critical chunks and tRNS, gAMA, cHRM, sRGB, iCCP, cICP, mDCV, cLLI, sBIT, bKGD, hIST, pHYs, sPLT, the APNG chunks, oFFs, pCAL, sCAL and sTER; JPEG APP0 JFIF/JFXX, APP2 ICC_PROFILE, MPF and the ISO 21496-1 gain map, APP14 Adobe, the XMP an HDR decoder needs to find and apply a gain map (Ultra HDR `hdrgm` and `Container`/`Item` directory, Apple `apdi` and `HDRGainMap` version and headroom, and the motion-photo `Camera:MotionPhoto`, `MotionPhotoVersion` and `MotionPhotoPresentationTimestampUs` so a motion photo stays one; Clear writes a new packet from those properties alone, each checked against the value the format defines (a version, a Boolean, a Real or three, an integer, a timestamp that may be -1, an item semantic of `Primary`, `GainMap` or `MotionPhoto`, a MIME type of `image/jpeg`, `image/heic`, `image/avif`, `video/mp4` or `video/quicktime`, a length or padding), so no other property, attribute, nested structure or text survives; an item value outside those lists is dropped and the item keeps its place and length, a directory item may be written as `rdf:li` > `rdf:Description`, and a directory with an entry that holds no item is dropped whole; the first occurrence of a property wins, and the gain map's `Item:Length` follows its new length while later items such as a motion-photo video keep theirs. An Apple gain map of version 65536 (iPhone 12-14) has no headroom in its XMP: ImageIO and libultrahdr take it from the primary image's Apple maker note, tags 33 and 48. For such a file Clear writes a new Exif in the primary holding only those two maker-note values, copied as stored, and nothing else of the Exif: no IFD0, GPS or other Exif tag and no other maker-note tag. The values kept are the ones ImageIO applies, measured with every level duplicated and broken (where libultrahdr reads a file differently, Clear follows ImageIO): the first Exif segment, whose TIFF magic must be 42; at each level (IFD0's Exif IFD pointers, each Exif IFD's MakerNote entries, the maker note's 0x0021 and 0x0030 entries) an occurrence ImageIO cannot use is skipped and a later usable one overrides an earlier one, two Exif IFDs merging value by value; a maker-note value is usable when it is SRATIONAL with every value inside the maker note, at any offset; the headroom is kept only when both winning entries have count 1 (otherwise ImageIO renders no HDR image), and a winning MakerNote that is not Apple's keeps nothing. ImageIO then renders exactly what it rendered before, HDR or SDR; without the values it renders the photo SDR and libultrahdr refuses it. The new Exif is a minimal carrier for the two decode parameters, not a conformant Exif: it deliberately omits the tags Exif marks mandatory (ExifVersion, ComponentsConfiguration, ColorSpace, the pixel dimensions, YCbCrPositioning, the resolution tags), consistent with Clear removing all other Exif, so `exiftool -validate` warns about them; ImageIO, libultrahdr, ffmpeg, exiftool and TagLib# all read it), and the APP11 JPEG XT decoding boxes (`ftyp`, `TONE`, `RTRF`, `LTRF`, `LCHK`, `SPEC`, `RESI`); GIF graphic control and plain text extensions, looping and ICC application extensions. Everything else goes, including PNG text, `eXIf`, `tIME` and `caBX`, JPEG Exif (but for the Apple headroom above), the rest of XMP and extended XMP, IPTC, maker segments and every other APP11 box (JUMBF/C2PA, `xml `, `uuid`, `json`, `Exif`, unknown), and GIF XMP and ImageMagick's IPTC. In a multi-picture JPEG (MPF), Clear cleans every image the MPF index lists with the same rules; the index's offsets and sizes are rewritten after Clear and after an edit. An MP index outside its APP2 segment, or listing an image before the first image's end (its EOI), outside the file or overlapping another, is not followed: Clear is refused, and so is an edit that would move the later images. Apple's PNG `iDOT` is dropped when a chunk between it and the first IDAT changes. A field the format does not store reads back as null. EXIF, IPTC, and XMP values are not read yet, and SVG metadata is not read or written yet. #### Raw AAC (ADTS/ADIF) Support - `AacFile` reads and writes raw AAC files (`.aac`): ADTS (ISO/IEC 13818-7 §6.2, MPEG-2 and MPEG-4) and ADIF (§6.1) @@ -81,6 +91,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Changed +- A JPEG title or comment edit refuses extended XMP only where a changed field's property name follows a prefix or opens an element; a bare `UserComment` inside base64 data no longer refuses a comment edit +- Matroska `Title`, on a file with no track or segment title, reads ffmpeg's untargeted `TITLE` before an explicit target-50 album `TITLE`; the album `TITLE` it reads is the default-language one (#188) +- `Id3v2Tag.Render` writes a tag whose `Version` is 2 (read as ID3v2.2, or created with `Id3v2Version.V22`) as ID3v2.3 (#187). `Version` still reports 2 on that object; the saved file reads back as 3 - An Exif field edit (Comment, Description, Copyright and the other stored fields) runs only when the Exif structure is plain. Otherwise it is refused, with the reason, and nothing is written. Clear is unchanged. A removed value that shares a protected byte, or a compaction that would rewrite any protected range other than the table itself, is refused. A strip, tile or thumbnail offset or length that is not SHORT or LONG, an array of those that does not lie wholly in the data, an array of those named more than once, a pair tag given twice in one table, a complete pair that names more values than half the bytes, a classic next-IFD field with one, two or three of its four bytes, or a first entry whose format would change whether exiftool reads the table, each refuse on their own. A wholly absent next field stays editable. A first-entry change that shows nothing new is still refused. - A path save copies still-image pixels in a rented 64 KB buffer and writes the same bytes as `Render`. `SaveToFile(path)` and `SaveToFileAsync` do this for JPEG, PNG, GIF, BMP, PCX, Netpbm, TIFF, DNG, and SVG. `Render` still copies every other byte. - A path save copies the audio in a rented 64 KB buffer and writes the same bytes as `Render` (#20). `SaveToFile(path)` and `SaveToFileAsync` do this for Ogg Vorbis, Opus, and Ogg FLAC, MP3, native FLAC, ASF/WMA, raw AAC, MPEG program streams, Audible, Monkey's Audio, WavPack, Musepack, DSF (when the samples were left on disk), MP4 including a chapter edit, WAV, AIFF, AVI, Matroska, and DFF. `SaveToFile(path, span)`, `Render`, and `ReadFromFile` still build one buffer. The source is closed when the destination is never created. A render failure is returned before an already-cancelled token. @@ -103,6 +116,22 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed +- A save no longer drops the ID3v2 frames this library does not read, such as `PCNT`, `MCDI`, `RVAD`, `ETCO`, `USER`, `COMR` and experimental frames (#207). Each is written back as it was stored, flags and any compressed, encrypted or unsynchronised body included, when the tag is saved in the version it was read in; a frame from an ID3v2.2 tag is written under its ID3v2.3 ID, except `LNK`, whose body differs. A frame of an ID this library reads that it cannot parse (a 1-byte `APIC`, a short `COMM` or `USLT`, a `POPM`, `UFID` or `PRIV` with no terminator, a truncated `CHAP` or `CTOC`, a `TALB` with an invalid encoding byte, a frame of size 0) is kept the same way, until a property sets or clears that ID, or a call removes every frame of it, as `Pictures = []` does; a rejected `COMM` or `USLT` goes with any write of `Comment` or `Lyrics`, and a rejected `TXXX` with a write or removal of the custom field its description names. A rejected ID3v2.2 `PIC` is not written as an `APIC`. Such frames make `IsEmpty` false, and `Clear` removes them +- A Matroska file with bytes that are not an element inside its Segment, such as the 0x0A filler a live recording puts after an unknown Segment size (the Matroska test suite's `test4.mkv`), read no tracks from a path or a seekable stream, while `ReadFromData` and a non-seekable stream read its audio and video (#208). The path and stream read now skip such bytes as the read from memory does, one window at a time. A save refused a file with such bytes anywhere after the Segment's first element ("Matroska segment cannot be bounded"); every save now keeps them where they are, as the reads skip them, and a save with no edit writes the file back unchanged +- MP3 audio in an MP4 `mp4a` sample entry (esds object type 0x6B or 0x69) is reported as `Mp4AudioCodec.Mp3` and codec "MP3", with its bit rate; it was reported as AAC (#206). The esds is found after a QuickTime sound description's version 1 or 2 fields too. Those object types hold MPEG audio of any layer, so the codec is named from the first frame's header, as MP3 files name it: Layer II in MP4 (`mp2.mp4`) is "MPEG-1 Layer II", where it read "MP3" and MediaInfo says Layer 2. QuickTime's `.mp3` sound entry (`mp3.mov`) had no codec; it is `Mp4AudioCodec.Mp3` and "MP3". Apple ProRes video (`apco`, `apcs`, `apcn`, `apch`, `ap4h`, `ap4x`) is named "ProRes" and H.263 (`s263`, `h263`) "H.263", where the fourcc was echoed +- A WAV file whose RIFF INFO text was written as UTF-8, as ffmpeg writes it, read as mojibake (`æ°æ é¢` for `新标题`) where ffprobe reads it correctly (#216). WAV INFO is now read as AVI reads a list with no CSET: a field of valid UTF-8 is UTF-8, and any other is Windows-1252, which fills the bytes 0x80 to 0x9F that Latin-1 leaves as controls. A field the caller does not change keeps its bytes on save, and a changed value is written by the same rule (#209). An AVI INFO list with no CSET that holds such a Windows-1252 field, next to a change that needs more than ASCII, is written the same way, field by field with no CSET, where the save was refused +- A WAV file whose RIFF INFO tag holds text Latin-1 cannot hold (a character beyond U+00FF) is no longer saved with `?` in its place, reporting success (#209). WAV INFO declares no character set; a changed value is now written by the rule the list is read with (#216), Windows-1252 when its bytes read back as the value and UTF-8 otherwise, so any text without a NUL is stored and reads back unchanged, and the save never fails for its text. A value Latin-1 cannot hold used to be written as `?`; ffprobe reads such a UTF-8 value; exiftool reads WAV INFO as Windows-1252 unless given `-charset RIFF=UTF8`, and MediaInfo as Latin-1, as they read ffmpeg's own UTF-8. `RiffInfoTag.SetCustomField` takes any text, where it refused text outside Latin-1. ID3v1, which is Latin-1 by its format, no longer writes `?` either: in MP3, AAC and MPEG-PS a value with a character beyond U+00FF that no other tag of the file holds, such as a title set on a file whose only tag is ID3v1, fails the save and names the field, where it was written as `?`; store it in the file's `Id3v2Tag`. A value written through `Tag` to a file that also has ID3v2 saves as before, with its Latin-1 copy in ID3v1. A value longer than an ID3v1 field (30 bytes) is still cut to fit, as the format holds no more +- Setting the Matroska `DiscNumber` on a file that does not already keep its disc as `PART_NUMBER` at target 50 writes ffmpeg's `DISC` ("n", or "n/m" with `TotalDiscs`), in the untargeted tag or a tag at target 50, which ffprobe, exiftool and MediaInfo show as the disc (#205). It used to write `PART_NUMBER` at target 50, which ffprobe shows as a second track number and MediaInfo as the track; a file that already keeps its disc that way is still updated there. The track total follows the same rule: `TotalTracks` on a file that does not already keep it as `TOTAL_PARTS` is written after the track number, ffmpeg's `PART_NUMBER` "n/m", which ffprobe shows as `track=n/m` and MediaInfo as the track position; ffprobe shows `TOTAL_PARTS` only as a raw tag, and writing back the track and total of an ffmpeg file turned its "5/12" into `5` and a `TOTAL_PARTS` of 12. Writing back the `DiscNumber`, `TotalTracks` or `TotalDiscs` read now changes nothing, where it rewrote a `DISCNUMBER`, `TRACKTOTAL` or `TOTALDISCS` that ffmpeg copied from FLAC +- Setting the Matroska `Title` also changes the segment title (`Info/Title`), which exiftool and MediaInfo show; it used to keep the old one, so exiftool showed the old title and MediaInfo `OldTitle / NewTitle` (#210). Info keeps its size, so nothing after it moves: the new title goes in Info when it fits there, and otherwise Info/Title is removed and the `TITLE` tag is the title every reader shows. `Title = null` and `Clear` remove the segment title too +- An empty string clears a field in every format, as null does; every text getter reads null for a field with no text. `Title = ""` used to store an empty `TITLE=` Vorbis comment in FLAC, Ogg Vorbis, Opus and Ogg FLAC, on a tagged file and through a tagless view; Vorbis `Movement` and `OriginalReleaseDate` left an empty `MOVEMENTNAME=` or `ORIGINALDATE=`; ID3v2 `PodcastFeedUrl` stored an empty `WFED` frame; ASF `Title`, `Artist`, `Album`, `Comment`, `Genre` and `Copyright` read `""` for a missing or cleared field; and in Matroska a clear left the `TITLE`, `ARTIST` or `COMPOSER` that ffmpeg writes in its untargeted tag. Matroska `Composer` and `AlbumArtist` read null and ignored every set; they now read and write the first name of `Composers` and `AlbumArtists` (#211). `Tag.IsEmpty` is false for a tag that holds a picture (FLAC PICTURE blocks, Vorbis `METADATA_BLOCK_PICTURE`, MP4 `covr`, APE cover items); it looked only at the standard text fields, so a FLAC holding only pictures read as empty (#211) +- An XMP packet whose JPEG signature has a space before the NUL is updated as a copy, and the title is written to a standard packet, which ImageIO and Exiv2 read +- An MP4 `esds` whose ES_Descriptor sets the stream-dependence, URL or OCR flag is read; the AAC bitrate of such a file was 0 +- Setting the Matroska album no longer changes the title (#188). A file with no `TITLE` at target 50, such as one ffmpeg wrote, gets an `ALBUM` tag at target 50, which ffprobe, MediaInfo and ExifTool report as the album. It used to get a `TITLE` in ffmpeg's untargeted tag, which ffprobe and MediaInfo showed as the file title (ffprobe in place of the segment title) and this library read back as the title. A file with a `TITLE` at target 50 has it updated; when the track has no title of its own, the title it showed is first kept as `TITLE` at target 30, after the album's tag. On a file ffmpeg wrote, setting the album artists writes `ALBUM_ARTIST` instead of an untargeted `ARTIST` that every reader showed as the artist, and clearing them keeps the artist +- ID3v2.2 (#187): saving a file whose tag was read as ID3v2.2 wrote four-character frames under a v2.2 header, which no reader could parse, so a save with no edits lost every field. The tag is now written as ID3v2.3 in MP3, AAC, MPEG-PS, WAV, AIFF, DSF, DFF and AVI; MPEG-PS and AVI keep the original v2.2 bytes when the tag did not change. A v2.2 frame missing from the ID table (`TDA`, `TIM`, `TRD`, `TXT`, `TRC`, `TLE`, `POP`, `GEO`, `SLT`, `WAF`, Apple's `TCP`, `TST`, `TSA`, `TSP`, `TS2` and `TSC`, and others) ended the read, so every later frame was lost; every frame of the v2.2 list is now mapped, and a frame with no ID3v2.3 name (`CRM`, experimental IDs) is stepped over. A `PIC` frame's three-character image format was read as the start of a MIME type, so its picture came back wrong; `JPG` and `PNG` now read as `image/jpeg` and `image/png`. A frame this library does not read (such as `MCI` and `CNT`) is written back under its ID3v2.3 name (#207) +- An MP4 video sample entry was parsed as an audio one, so a 320-pixel-wide video reported a 320 Hz sample rate +- A single ID3v2 name that contains a slash, such as `AC/DC`, was split into two values +- Matroska `Album` reads the untargeted `ALBUM` tag that ffmpeg writes when there is no `TITLE` at target 50 (it was null). Setting the album updates that `ALBUM`, and a target-50 `TITLE` beside it, instead of adding a `TITLE` +- APE and MP4: a picture whose role is `Other`, or any role without its own key, came back as a front cover after a save - `SaveToFile (path, span)` and `SaveToFileAsync (path, memory)` of DSF, DFF, FLAC, Ogg Vorbis, Opus, Ogg FLAC, MP3, AAC, Monkey's Audio, Musepack, WavPack, AVI, Audible, ASF and MPEG-PS files now fail and write nothing when the bytes passed in are not a file the object describes (#178). These saves take the payload from those bytes. Most of them used to report success and write whatever part of the payload the bytes held: an empty span wrote an empty ASF file, a DFF file with no sound, and an MP3, AAC, Monkey's Audio, Musepack or WavPack file of its tags alone. An object describes the file it was read from. Ogg Vorbis, Opus, Ogg FLAC, Monkey's Audio, Musepack, WavPack, AVI, ASF, DSF and DFF also describe each file they save, so a save from the bytes of an earlier save works as before; a DSF file that had no ID3 tag and was saved with one is the exception. Audible describes the file it saved over its source in place of the one it read. MP3, FLAC, AAC and MPEG-PS keep the offsets of the file they read, so a save from the bytes of an earlier save now fails: MP3, FLAC and AAC used to write a damaged file there (an MP3 lost audio), and MPEG-PS refused it with its own message, which is now this one. The check compares lengths, so another file of the same length passes. A DSF or DFF file read from memory holds its bytes and saves them, whatever bytes are passed. `Render (span)` is unchanged. MP4 and Matroska are unchanged too: their save parses the bytes it is given as a file of its own, and rejects bytes it cannot rewrite. - `DsfFile.Render` and `DffFile.Render` work after a path read (#176). The read leaves the sound on disk, and `Render` used to throw: `ArgumentNullException` from inside the DSF render, `InvalidOperationException` ("no original data available") from the DFF one. `Render` now reads the source file, as a path save does, and returns the same bytes the save writes. After a stream read, which keeps no source, or when the source can no longer be read, `Render` throws `InvalidOperationException` and says why. The render holds the source once, beside its result. A DSF save from a span that ends before the sound the read found now returns a failure result and writes nothing, instead of throwing `ArgumentException` from `Array.Copy`. - `MediaFile.ReadFromData` and `OggOpusFile.Read` no longer throw `OverflowException` on a malformed Opus file (#175). The read of bytes in memory took the granule position from any end-of-stream page in the file. A stream or path read takes it from the header pages and the last page. All entry points now take it from the header and last pages, for Opus and Ogg Vorbis, so they report the same duration. A sample count whose duration does not fit a `TimeSpan` now reports `TimeSpan.MaxValue`, as MP4 and DSDIFF already did, instead of throwing. That covers `AudioProperties.FromOpus`, `FromVorbis` and `FromFlac`, Ogg FLAC, Monkey's Audio, Musepack and DSF. diff --git a/README.md b/README.md index 9a80433e..2fa15f19 100644 --- a/README.md +++ b/README.md @@ -24,12 +24,12 @@ See the [Migration Guide](docs/MIGRATION-FROM-TAGLIB.md) for detailed comparison - **Performance-First**: Zero-allocation parsing with `Span` and `ArrayPool` - **Multi-Target**: Supports .NET Standard 2.0/2.1, .NET 8.0, and .NET 10.0 - **Format Support**: - - Audio: MP3 (ID3v1/ID3v2), FLAC, Ogg Vorbis, Ogg Opus, Ogg FLAC, WAV (RIFF INFO/ID3v2), AIFF (ID3v2), MP4/M4A (AAC/ALAC), raw AAC (ADTS/ADIF, ID3v2/APEv2/ID3v1), ASF/WMA, DSF (DSD), DFF (DSDIFF), WavPack, Monkey's Audio (.ape), Musepack - - Matroska/WebM (`.mkv`, `.mka`, `.mks`, `.mk3d`, `.webm`): tags (including `SORT_WITH` sort names for title, artist, album, album artist, and composer), chapters (editions and nested chapter atoms), duration, audio and video properties, tracks, and pictures. Tag values, chapters, pictures, and each track's enabled flag can be saved. A disabled track is not picked as the main audio or video track. Pictures are image attachments: a new front cover is written as `cover.jpg` or `cover.png` (another image type keeps its own extension, such as `cover.gif`), and fonts and other attachments are kept. WebM has no attachments, so a save that would add a picture to a WebM file fails. - - 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. + - Audio: MP3 (ID3v1, ID3v1.1, ID3v2.2 read and saved as ID3v2.3, ID3v2.3, ID3v2.4), FLAC, Ogg Vorbis, Ogg Opus, Ogg FLAC, WAV (RIFF INFO/ID3v2), AIFF (ID3v2), MP4/M4A (AAC/ALAC, including a video track's coded width and height, codec, and rotation), raw AAC (ADTS/ADIF, ID3v2/APEv2/ID3v1), ASF/WMA, DSF (DSD), DFF (DSDIFF), WavPack, Monkey's Audio (.ape), Musepack. A tagless MP3, raw AAC, DSF, DFF, WAV, AIFF, FLAC, WavPack, Monkey's Audio, Musepack, or MP4 file still has a tag view (`IMediaFile.Tag`): reading it does not write a tag, the first assignment creates the format's tag (ID3v2 in MP3, AAC, DSF, DFF, WAV and AIFF; a Vorbis comment in FLAC; APEv2; an MP4 `ilst`), and an assignment that leaves that tag empty removes it again, so a save then writes no empty tag + - Matroska/WebM (`.mkv`, `.mka`, `.mks`, `.mk3d`, `.webm`): tags (including `SORT_WITH` sort names for title, artist, album, album artist, and composer), chapters (editions and nested chapter atoms), duration, audio and video properties, tracks, and pictures. The album is read from `TITLE` at target type 50, else from the `ALBUM` tag ffmpeg writes. Setting the album never changes the title this library reads, and never makes ffprobe or MediaInfo show the album as the title. A file with a `TITLE` at target 50 has it updated, with any `ALBUM` beside it; when the track has no title of its own, the title it showed is first kept as `TITLE` at target 30. Any other file gets an `ALBUM` tag at target 50, which ffprobe, MediaInfo and ExifTool report as the album, and no `TITLE`. On a file ffmpeg wrote, album artists that would otherwise replace the track's artist are written as `ALBUM_ARTIST`. Tag values, chapters, pictures, and each track's enabled flag can be saved. A disabled track is not picked as the main audio or video track. Pictures are image attachments: a new front cover is written as `cover.jpg` or `cover.png` (another image type keeps its own extension, such as `cover.gif`), and fonts and other attachments are kept. WebM has no attachments, so a save that would add a picture to a WebM file fails. + - 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. A tagless stream still has a tag view: reading it does not write a tag, the first assignment creates an ID3v2 tag, and an assignment that leaves that tag empty removes it again. - 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. + - 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 and title can be edited. A JPEG title is stored in XMP `dc:title`, in a new XMP segment when the file has none, and is read from there, or from IFD0 `XPTitle` (0x9C9B) when the XMP has none. A set or a clear also removes every `XPTitle`, through the same plain-structure Exif edit as any other copy, so ExifTool, Exiv2, macOS ImageIO and TagLib# show the new title (measured), and Windows reads `dc:title` when no `XPTitle` is there (System.Title photo metadata policy). A set writes one `x-default` title and drops the other languages. A title whose XMP would not fit in one 64 KB segment is refused. IPTC `ObjectName` and Exif `ImageDescription` are not changed: after a clear, ImageIO shows an IPTC `ObjectName` as the title, and Windows falls back to `UserComment` or `ImageDescription`. A PNG edit also updates the XMP and Exif copies of the field. GPS, IPTC, and other Exif values are not read. TIFF, DNG, BMP, PCX, Netpbm, and SVG have dimensions and no text tag. ## Format Support Matrix @@ -75,7 +75,7 @@ See the [Migration Guide](docs/MIGRATION-FROM-TAGLIB.md) for detailed comparison | Ogg FLAC | Vorbis Comment | — | Native only | | WAV | RIFF INFO | ID3v2, bext (BWF) | ID3v2 preferred | | AIFF | ID3 chunk | ANNO, COMT, NAME, AUTH, (c) (read) | ID3 preferred; edits write ID3 | -| MP4/M4A | iTunes atoms (ilst) | — | Native only | +| MP4/M4A | iTunes atoms (ilst) | — | Native only. A `vide` track is video (ISO/IEC 14496-12); its sample entry is not read as audio | | ASF/WMA | ASF Content Description | Extended Content Description | Native only | | DSF | ID3v2 | — | Native only | | DFF | ID3v2 | — | Native only | @@ -193,13 +193,15 @@ This is a clean-room rewrite of media tagging functionality, designed from speci - [x] TagReadResult for error handling ### Phase 2: ID3 Support ✅ -- [x] ID3v1/v1.1 reading and writing (id3.org specification) -- [x] ID3v2.3/2.4 reading and writing (id3.org specification) - - [x] Text frames (TIT2, TPE1, TALB, TYER, TDRC, TCON, TRCK, TPE2, TPOS, TCOM, TBPM, TENC, TSSE, TIT1, TIT3, TPE4, TKEY, TMOO, TMED, TLAN) - - [x] Involved people frames (TIPL, TMCL, IPLS) for musician credits - - [x] Picture frames (APIC) with multiple picture types - - [x] Syncsafe integer handling, multiple text encodings - - [x] Extended header support +- [x] ID3v1 and ID3v1.1 reading and writing (id3.org). ID3v1.1 is the track number in the last two comment bytes when byte 28 is 0 +- [x] ID3v2.2 reading (id3.org). Three-character frame IDs are mapped onto their ID3v2.3 names (`TT2` to `TIT2`, `TYE` to `TYER`, `PIC` to `APIC` with its image format turned into a MIME type). A save writes the tag as ID3v2.3 with every frame that was read. A frame with no ID3v2.3 name (`CRM`, experimental IDs) and `LNK`, whose body differs in v2.3, are skipped; a frame this library does not read (such as `MCI` and `CNT`) is written back under its ID3v2.3 name. In every version, a frame this library does not read, or cannot parse, is written back as it was stored, flags included, when the tag is saved in the version it was read in. `Version` reports 2 until the saved file is read again +- [x] ID3v2.3 and ID3v2.4 reading and writing (id3.org). A new tag is v2.4 unless `Id3v2Version.V23` is passed. v2.3 frame sizes are big-endian and the year is `TYER`; v2.4 sizes are syncsafe, text may be UTF-8, and the year is `TDRC`. A header whose major version is not 2, 3, or 4 is rejected +- [x] Text lists split on NUL only (ID3v2.4 frames §4.2), in every version. A slash is part of the value, so `AC/DC` stays one performer. ID3v2.3's TPE1 text says `/` separates artists; that rule is not applied. `"(17)"` is still the ID3v1 genre Rock. Track and disc numbers still use `n/m` +- [x] Text frames (TIT2, TPE1, TALB, TYER, TDRC, TCON, TRCK, TPE2, TPOS, TCOM, TBPM, TENC, TSSE, TIT1, TIT3, TPE4, TKEY, TMOO, TMED, TLAN) +- [x] Involved people frames (TIPL, TMCL, IPLS) for musician credits +- [x] Picture frames (APIC) with multiple picture types +- [x] Syncsafe integer handling, multiple text encodings +- [x] Extended header support ### Phase 3: Xiph Formats ✅ - [x] Vorbis Comments (xiph.org specification) @@ -267,8 +269,9 @@ This is a clean-room rewrite of media tagging functionality, designed from speci - [x] ISO 14496-12 box parsing (ftyp, moov, mdat, etc.) - [x] iTunes-style metadata atoms (ilst with ©nam, ©ART, etc.) - [x] AAC audio properties via esds parsing +- [x] Video track width, height, and codec from a visual sample entry (ISO/IEC 14496-12), including when the handler is not `vide`. Width and height are the coded size, as ffprobe and mediainfo report it: the track matrix is not applied but returned as `VideoProperties.Rotation` (clockwise degrees; 0 for a matrix that mirrors or skews), and the pixel aspect ratio is not applied. An `mp4v` entry's codec is named from its `esds` object type (MPEG-4, MPEG-1 and MPEG-2 video, JPEG, PNG). A track another track names as chapters (`tref`/`chap`), such as Apple's chapter images, is not the video. That entry is not parsed as audio - [x] ALAC audio properties via alac magic cookie -- [x] Album art (covr atom) with JPEG/PNG detection +- [x] Album art (`covr`) with JPEG/PNG detection. The data type is the image format. QuickTime has no field for a picture role, so a role other than front cover is kept by a private convention: the data atom's locale holds the role one higher than the ID3 picture type in its top byte, a country byte no real locale uses. `Other` round-trips, and a locale of zero (or any real one) reads as front cover. AVFoundation, QuickLook, ffprobe, ExifTool and MediaInfo still show the image as a normal cover - [x] MusicBrainz IDs and ReplayGain via freeform atoms - [x] Atomic file writing with mdat relocation - [x] Chapters: Nero `chpl` and QuickTime chapter text track (`tref`/`chap`), read and write diff --git a/ROADMAP.md b/ROADMAP.md index 6eaa393a..ad7b933b 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -45,7 +45,7 @@ Based on the specification in `/Users/sshaw/code/roon-8/Docs/TagLibSharp2/` and | Feature | Status | |---------|--------| | Header parsing | ✅ | -| v2.2 support (3-char frames) | ✅ | +| v2.2 support (3-char frames) | ✅ | Read and mapped to ID3v2.3 IDs. A save writes the tag as ID3v2.3 | | v2.3 support | ✅ | | v2.4 support | ✅ | | Extended header parsing | ✅ | diff --git a/docs/IMPLEMENTATION-GUIDE.md b/docs/IMPLEMENTATION-GUIDE.md index f9e5148a..f3664b52 100644 --- a/docs/IMPLEMENTATION-GUIDE.md +++ b/docs/IMPLEMENTATION-GUIDE.md @@ -149,7 +149,6 @@ how it was broken before. remove them. Known gaps on main are follow-up bugs, not precedent. Do not copy them: - - Matroska `Clear()` and `Title = null` keep `Info/Title`, so the title still reads back. - Audible `Clear()` keeps `user_alias`, an account name. *Past example:* an MP4 `Clear()` kept the unmapped `apID` atom, so a "cleaned" file still carried the diff --git a/docs/MP4_COMPREHENSIVE_SPECIFICATION_ROADMAP.md b/docs/MP4_COMPREHENSIVE_SPECIFICATION_ROADMAP.md index 11086754..61ffad8b 100644 --- a/docs/MP4_COMPREHENSIVE_SPECIFICATION_ROADMAP.md +++ b/docs/MP4_COMPREHENSIVE_SPECIFICATION_ROADMAP.md @@ -1025,7 +1025,7 @@ Used for alphabetical sorting, ignoring articles like "The". **Structure:** - Can contain multiple `data` atoms (front cover, back cover, etc.) -- Each data atom has type indicator 13 (JPEG) or 14 (PNG) +- Each data atom has type indicator 13 (JPEG) or 14 (PNG). That code is the image format, not an ID3 picture role. A role other than front cover is stored in the top byte of a zero locale, one higher than the ID3 picture type, so this library can read it back. A locale of zero still reads as front cover. ExifTool still shows the image as cover art - No size limit specified, but typically ≤ 2048×2048 pixels **Example:** diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index 41e6e98d..5f6bd534 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -6,7 +6,7 @@ ## Executive Summary -TagLibSharp2 reads and writes tags for the audio and video formats below. JPEG, PNG, GIF, BMP, PCX, Netpbm, TIFF, DNG, and SVG open with width and height. PNG text keywords, the GIF comment, and the JPEG COM marker can be edited. A field edit also removes that field's Exif copies when the Exif structure is plain, and updates the matching XMP property; any other Exif structure is refused and nothing is written. Exif values are not read into the tag. IPTC is not read or written, and SVG metadata is not read or written yet. Remaining audio gaps are niche formats: Speex (obsolete), TrueAudio (niche), and tracker formats (demoscene). Matroska/WebM saves tag values, chapters, and picture attachments. A path save copies the audio in 64 KB pieces instead of loading the file. `Render` and a save from a span still build one buffer. +TagLibSharp2 reads and writes tags for the audio and video formats below. JPEG, PNG, GIF, BMP, PCX, Netpbm, TIFF, DNG, and SVG open with width and height. PNG text keywords, the GIF comment, and the JPEG COM marker can be edited. A JPEG title is stored in XMP `dc:title` and read from IFD0 `XPTitle` (0x9C9B) when the XMP has none. A field edit also removes that field's Exif copies, a JPEG title's `XPTitle` included, when the Exif structure is plain, and updates the matching XMP property. An edit with a copy to remove from any other Exif structure is refused and nothing is written. GPS, IPTC, and other Exif values are not read into the tag. SVG metadata is not read or written yet. Remaining audio gaps are niche formats: Speex (obsolete), TrueAudio (niche), and tracker formats (demoscene). Matroska/WebM saves tag values, chapters, and picture attachments. A path save copies the audio in 64 KB pieces instead of loading the file. `Render` and a save from a span still build one buffer. --- @@ -18,7 +18,7 @@ TagLibSharp2 reads and writes tags for the audio and video formats below. JPEG, |--------|----------|-------------|------|-------|----------|-------| | MP3 | P0 | ✅ | ✅ | ✅ | - | Production ready | | FLAC | P0 | ✅ | ✅ | ✅ | - | Production ready | -| MP4/M4A | P0 | ✅ | ✅ | ✅ | - | Production ready | +| MP4/M4A | P0 | ✅ | ✅ | ✅ | - | Production ready. A video track gives coded width, height, codec, and rotation; its sample entry is not read as audio | | WAV | P0 | ✅ | ✅ | ✅ | - | Production ready | | AIFF | P0 | ✅ | ✅ | ✅ | - | Production ready | | DSF | P0 | ✅ | ✅ | ✅ | - | Recently added | @@ -28,10 +28,10 @@ TagLibSharp2 reads and writes tags for the audio and video formats below. JPEG, | DFF | P1 | ✅ | ✅ | ✅ | - | Recently added | | WavPack | P1 | ✅ | ✅ | ✅ | - | Recently added | | Musepack | P1 | ✅ | ✅ | ✅ | - | SV7 and SV8 support | -| Matroska/WebM | P2 | ✅ | ✅ | ✅ | - | Tag values, chapters, picture attachments, and track enabled flags are saved. Other attachments are preserved, not rewritten | +| Matroska/WebM | P2 | ✅ | ✅ | ✅ | - | Tag values, chapters, picture attachments, and track enabled flags are saved. Album is `TITLE` at target 50, or the `ALBUM` tag ffmpeg writes. Setting it updates a target-50 `TITLE` and any `ALBUM` beside it, keeping the shown title at target 30 when the track has none; any other file gets `ALBUM` at target 50, so no reader shows the album as the title. Other attachments are preserved, not rewritten | | MPEG PS / video ES | P2 | ✅ | ✅ | ✅ | - | ID3v2 and ID3v1 around the stream; duration from PTS or GOP time codes | | AVI (incl. OpenDML) | P2 | ✅ | ✅ | ✅ | - | RIFF INFO and ID32 tags; movi and every index kept valid. A path save copies movi in 64 KB pieces | -| JPEG, PNG, GIF, BMP, PCX, Netpbm, TIFF, DNG, SVG | P2 | ✅ | Dimensions | PNG text, GIF comment, JPEG COM, plain Exif removal, matching XMP | - | A path save copies pixels in 64 KB pieces. Render still copies every other byte. A field edit removes Exif copies only when the structure is plain, and refuses otherwise. IPTC is not read or written. SVG metadata is not read or written yet | +| JPEG, PNG, GIF, BMP, PCX, Netpbm, TIFF, DNG, SVG | P2 | ✅ | Dimensions | PNG text, GIF comment, JPEG COM and title (XMP `dc:title`, read from `XPTitle` too), plain Exif removal, matching XMP | - | A path save copies pixels in 64 KB pieces. Render still copies every other byte. A JPEG title is written to XMP `dc:title` (a new XMP segment when there is none) and every `XPTitle` is removed; clearing removes both. IPTC `ObjectName` is not changed. A field edit removes Exif copies only when the structure is plain, and refuses otherwise. GPS and IPTC are not read. TIFF, DNG, BMP, PCX, Netpbm, and SVG have no text tag | | Ogg FLAC | P1 | ✅ | ✅ | ✅ | - | Recently added | | AAC (ADTS/ADIF) | P1 | ✅ | ✅ | ✅ | - | ID3v2, APEv2, ID3v1 tags | | Speex | P1 | ❌ | ❌ | ❌ | LOW | Uses Vorbis Comment | @@ -47,7 +47,9 @@ TagLibSharp2 reads and writes tags for the audio and video formats below. JPEG, | Tag Format | Required | Implemented | Notes | |------------|----------|-------------|-------| | ID3v1 | ✅ | ✅ | Complete | -| ID3v2 (v2.2/v2.3/v2.4) | ✅ | ✅ | Comprehensive frame support | +| ID3v2.2 | ✅ | Read; saved as ID3v2.3 | 3-character IDs mapped to their ID3v2.3 names. A save writes an ID3v2.3 tag with every frame that was read; a frame with no ID3v2.3 name is skipped | +| ID3v2.3 | ✅ | ✅ | Big-endian frame sizes, `TYER`. Text lists split on NUL only; the TPE1 "/" rule is not applied | +| ID3v2.4 | ✅ | ✅ | Default for a new tag. Syncsafe sizes, UTF-8, `TDRC`. Text lists split on NUL only (frames §4.2) | | Vorbis Comment | ✅ | ✅ | Full field mapping | | MP4/iTunes | ✅ | ✅ | Apple atom support | | APE Tag | ✅ | ✅ | v2 with binary items | @@ -95,7 +97,7 @@ src/TagLibSharp2/Asf/ | Duplicate ID3v2 tags | ✅ | `HasDuplicateTag` detection, auto-removed on save | | Apple proprietary v2.3 frames | ✅ | TSOA, TSOT, TSOP, WFED, MVNM, MVIN implemented | | MP4 duplicate atoms | ✅ | Multiple data atoms merged with "; " separator | -| ID3v2.4 genre separator | ✅ | Handles both null and "/" separators | +| ID3v2 text list separator | ✅ | NUL only, in v2.2, v2.3, and v2.4. A slash stays inside the value. `"(17)"` is still an ID3v1 genre | --- diff --git a/src/TagLibSharp2/Aac/AacFile.cs b/src/TagLibSharp2/Aac/AacFile.cs index cdd1c5dd..a1ef509a 100644 --- a/src/TagLibSharp2/Aac/AacFile.cs +++ b/src/TagLibSharp2/Aac/AacFile.cs @@ -56,6 +56,7 @@ internal void MarkPicturesSkipped () internal SourceLength Source { get; } = new (); bool _disposed; + TagCreation? _creation; IFileSystem? _sourceFileSystem; // The first byte after the leading ID3v2 tag's header, size, and footer: where the read placed the audio start, @@ -123,13 +124,13 @@ internal void MarkPicturesSkipped () /// /// - /// A over ID3v2, APEv2, and ID3v1 in that order, or null when the file - /// has none of them. Reads take the first tag with a value. Writes go to every tag present. + /// A over ID3v2, APEv2, and ID3v1 in that order. Reads take the first + /// tag with a value. Writes go to every tag present. Reading the view does not create a stored + /// tag. The first write on a tagless file creates an ID3v2 tag, and a write that leaves that tag + /// empty removes it again, so a save writes no empty tag. /// - public Tag? Tag => - Id3v2Tag is null && ApeTag is null && Id3v1Tag is null - ? null - : new CombinedTag (Id3v2Tag, ApeTag, Id3v1Tag); + public Tag? Tag => _disposed ? null : CombinedTag.Over (() => [Id3v2Tag, ApeTag, Id3v1Tag], + _creation ??= new TagCreation (() => new Id3v2Tag (), tag => Id3v2Tag = (Id3v2Tag?)tag)); /// IMediaProperties? IMediaFile.AudioProperties => Properties; @@ -382,6 +383,9 @@ static int StreamStart (ReadOnlySpan data) return total > int.MaxValue ? int.MaxValue : (int)total; } + // ID3v1 text is Latin-1: a value it cannot hold that no other tag holds fails the save (Id3v1Tag.Latin1Refusal). + string? Id3v1Refusal () => Id3v1Tag?.Latin1Refusal ("AAC", nameof (AacFile), Id3v2Tag, ApeTag); + /// /// Renders the file with the current tags. /// @@ -393,8 +397,12 @@ static int StreamStart (ReadOnlySpan data) /// trailing tags, the new APEv2 tag, any Lyrics3 block that sat in front of ID3v1, and the new ID3v1 tag. /// The APEv2 tag has a header and a footer unless it is the tag that was read and that tag had only a footer. /// + /// The ID3v1 tag holds text Latin-1 cannot hold that no other tag of the file holds. public BinaryData Render (ReadOnlySpan originalData) { + _creation?.Settle ([Id3v2Tag, ApeTag, Id3v1Tag]); + if (Id3v1Refusal () is string refusal) + throw new InvalidOperationException (refusal); // The read's tail rule against the read's audio start, so a save keeps every frame the read counted. var audioStart = Math.Min (Id3v2Size, originalData.Length); var tail = AacTail.Locate (new AacTailSource (originalData), Math.Min (_audioStart, originalData.Length), readTags: false); @@ -430,8 +438,11 @@ public BinaryData Render (ReadOnlySpan originalData) /// A result indicating success or failure. public FileWriteResult SaveToFile (string path, ReadOnlySpan originalData, IFileSystem? fileSystem = null) { + _creation?.Settle ([Id3v2Tag, ApeTag, Id3v1Tag]); if (PictureSkip.Refuse (this) is { } denied) return denied; + if (Id3v1Refusal () is string refusal) + return FileWriteResult.Failure (refusal); if (Source.Refuse ("AAC", originalData.Length) is { } mismatch) return mismatch; @@ -459,8 +470,11 @@ public Task SaveToFileAsync ( IFileSystem? fileSystem = null, CancellationToken cancellationToken = default) { + _creation?.Settle ([Id3v2Tag, ApeTag, Id3v1Tag]); if (PictureSkip.Refuse (this) is { } denied) return Task.FromResult (denied); + if (Id3v1Refusal () is string refusal) + return Task.FromResult (FileWriteResult.Failure (refusal)); if (Source.Refuse ("AAC", originalData.Length) is { } mismatch) return Task.FromResult (mismatch); @@ -484,8 +498,11 @@ public Task SaveToFileAsync ( /// A result indicating success or failure. public FileWriteResult SaveToFile (string path, IFileSystem? fileSystem = null) { + _creation?.Settle ([Id3v2Tag, ApeTag, Id3v1Tag]); if (PictureSkip.Refuse (this) is { } denied) return denied; + if (Id3v1Refusal () is string refusal) + return FileWriteResult.Failure (refusal); if (string.IsNullOrEmpty (SourcePath)) return FileWriteResult.Failure ("No source path available. File was not read from disk."); @@ -499,8 +516,11 @@ public FileWriteResult SaveToFile (string path, IFileSystem? fileSystem = null) /// A result indicating success or failure. public FileWriteResult SaveToFile (IFileSystem? fileSystem = null) { + _creation?.Settle ([Id3v2Tag, ApeTag, Id3v1Tag]); if (PictureSkip.Refuse (this) is { } denied) return denied; + if (Id3v1Refusal () is string refusal) + return FileWriteResult.Failure (refusal); if (string.IsNullOrEmpty (SourcePath)) return FileWriteResult.Failure ("No source path available. File was not read from disk."); @@ -523,8 +543,11 @@ public Task SaveToFileAsync ( IFileSystem? fileSystem = null, CancellationToken cancellationToken = default) { + _creation?.Settle ([Id3v2Tag, ApeTag, Id3v1Tag]); if (PictureSkip.Refuse (this) is { } denied) return Task.FromResult (denied); + if (Id3v1Refusal () is string refusal) + return Task.FromResult (FileWriteResult.Failure (refusal)); if (string.IsNullOrEmpty (SourcePath)) return Task.FromResult (FileWriteResult.Failure ("No source path available. File was not read from disk.")); @@ -604,8 +627,11 @@ public Task SaveToFileAsync ( IFileSystem? fileSystem = null, CancellationToken cancellationToken = default) { + _creation?.Settle ([Id3v2Tag, ApeTag, Id3v1Tag]); if (PictureSkip.Refuse (this) is { } denied) return Task.FromResult (denied); + if (Id3v1Refusal () is string refusal) + return Task.FromResult (FileWriteResult.Failure (refusal)); if (string.IsNullOrEmpty (SourcePath)) return Task.FromResult (FileWriteResult.Failure ("No source path available. File was not read from disk.")); diff --git a/src/TagLibSharp2/Aiff/AiffFile.cs b/src/TagLibSharp2/Aiff/AiffFile.cs index 75662c80..72e6f8d4 100644 --- a/src/TagLibSharp2/Aiff/AiffFile.cs +++ b/src/TagLibSharp2/Aiff/AiffFile.cs @@ -116,14 +116,15 @@ public Id3v2Tag? Id3v2Tag { /// Every set writes the ID3 tag; see the class remarks. The view is cached. Clearing the last field does not make this null. /// Assign an through ; this property /// has no setter, so the combined view cannot be downcast and drop the ID3 chunk. + /// The view is always present, including on a file with no metadata, so + /// file.Tag.Title can create the ID3 chunk. Reading it does not. A save + /// writes that chunk only when it is not empty. /// public Tag? Tag { get { - if (_metadata is not null) - return _metadata; - if (_id3 is null && !HasNativeFields) + if (_disposed) return null; - return _metadata = new AiffTag (this); + return _metadata ??= new AiffTag (this); } } @@ -699,7 +700,16 @@ static bool HasText (string[]? value) return false; } - internal Id3v2Tag EnsureId3 () => Id3v2Tag ??= new Id3v2Tag (); + internal Id3v2Tag EnsureId3 () + { + Id3Creation.BeforeWrite (() => [Id3v2Tag]); + return Id3v2Tag!; + } + + /// The ID3 tag the view creates on a first write, and drops while it stays empty. + internal TagCreation Id3Creation => _id3Creation ??= new TagCreation (() => new Id3v2Tag (), tag => Id3v2Tag = (Id3v2Tag?)tag); + + TagCreation? _id3Creation; internal void ClearMappedFields () { diff --git a/src/TagLibSharp2/Aiff/AiffTag.cs b/src/TagLibSharp2/Aiff/AiffTag.cs index 58950e19..f7d087f4 100644 --- a/src/TagLibSharp2/Aiff/AiffTag.cs +++ b/src/TagLibSharp2/Aiff/AiffTag.cs @@ -36,25 +36,25 @@ public override TagTypes TagType { /// public override string? Title { get => _file.Title; - set => _file.Title = value; + set => Write (() => _file.Title = value); } /// public override string? Artist { get => _file.Artist; - set => _file.Artist = value; + set => Write (() => _file.Artist = value); } /// public override string? Album { get => Id3?.Album; - set => Ensure ().Album = value; + set => Write (() => Ensure ().Album = value); } /// public override string? Year { get => Id3?.Year; - set => Ensure ().Year = value; + set => Write (() => Ensure ().Year = value); } /// @@ -63,367 +63,367 @@ public override string? Year { /// public override string? Comment { get => _file.Comment; - set => _file.Comment = value; + set => Write (() => _file.Comment = value); } /// public override string? Genre { get => Id3?.Genre; - set => Ensure ().Genre = value; + set => Write (() => Ensure ().Genre = value); } /// public override uint? Track { get => Id3?.Track; - set => Ensure ().Track = value; + set => Write (() => Ensure ().Track = value); } /// public override string? OriginalReleaseDate { get => Id3?.OriginalReleaseDate; - set => Ensure ().OriginalReleaseDate = value; + set => Write (() => Ensure ().OriginalReleaseDate = value); } /// public override string? AlbumArtist { get => Id3?.AlbumArtist; - set => Ensure ().AlbumArtist = value; + set => Write (() => Ensure ().AlbumArtist = value); } /// public override string? Composer { get => Id3?.Composer; - set => Ensure ().Composer = value; + set => Write (() => Ensure ().Composer = value); } /// public override string? Conductor { get => Id3?.Conductor; - set => Ensure ().Conductor = value; + set => Write (() => Ensure ().Conductor = value); } /// public override string? Work { get => Id3?.Work; - set => Ensure ().Work = value; + set => Write (() => Ensure ().Work = value); } /// public override string? Movement { get => Id3?.Movement; - set => Ensure ().Movement = value; + set => Write (() => Ensure ().Movement = value); } /// public override string? Copyright { get => _file.Copyright; - set => _file.Copyright = value; + set => Write (() => _file.Copyright = value); } /// public override string? PodcastFeedUrl { get => Id3?.PodcastFeedUrl; - set => Ensure ().PodcastFeedUrl = value; + set => Write (() => Ensure ().PodcastFeedUrl = value); } /// public override string? DiscSubtitle { get => Id3?.DiscSubtitle; - set => Ensure ().DiscSubtitle = value; + set => Write (() => Ensure ().DiscSubtitle = value); } /// public override string? Lyrics { get => Id3?.Lyrics; - set => Ensure ().Lyrics = value; + set => Write (() => Ensure ().Lyrics = value); } /// public override string? Isrc { get => Id3?.Isrc; - set => Ensure ().Isrc = value; + set => Write (() => Ensure ().Isrc = value); } /// public override string? Publisher { get => Id3?.Publisher; - set => Ensure ().Publisher = value; + set => Write (() => Ensure ().Publisher = value); } /// public override string? EncodedBy { get => Id3?.EncodedBy; - set => Ensure ().EncodedBy = value; + set => Write (() => Ensure ().EncodedBy = value); } /// public override string? EncoderSettings { get => Id3?.EncoderSettings; - set => Ensure ().EncoderSettings = value; + set => Write (() => Ensure ().EncoderSettings = value); } /// public override string? Grouping { get => Id3?.Grouping; - set => Ensure ().Grouping = value; + set => Write (() => Ensure ().Grouping = value); } /// public override string? Subtitle { get => Id3?.Subtitle; - set => Ensure ().Subtitle = value; + set => Write (() => Ensure ().Subtitle = value); } /// public override string? Remixer { get => Id3?.Remixer; - set => Ensure ().Remixer = value; + set => Write (() => Ensure ().Remixer = value); } /// public override string? InitialKey { get => Id3?.InitialKey; - set => Ensure ().InitialKey = value; + set => Write (() => Ensure ().InitialKey = value); } /// public override string? Mood { get => Id3?.Mood; - set => Ensure ().Mood = value; + set => Write (() => Ensure ().Mood = value); } /// public override string? MediaType { get => Id3?.MediaType; - set => Ensure ().MediaType = value; + set => Write (() => Ensure ().MediaType = value); } /// public override string? Language { get => Id3?.Language; - set => Ensure ().Language = value; + set => Write (() => Ensure ().Language = value); } /// public override string? Barcode { get => Id3?.Barcode; - set => Ensure ().Barcode = value; + set => Write (() => Ensure ().Barcode = value); } /// public override string? CatalogNumber { get => Id3?.CatalogNumber; - set => Ensure ().CatalogNumber = value; + set => Write (() => Ensure ().CatalogNumber = value); } /// public override string? AlbumSort { get => Id3?.AlbumSort; - set => Ensure ().AlbumSort = value; + set => Write (() => Ensure ().AlbumSort = value); } /// public override string? ArtistSort { get => Id3?.ArtistSort; - set => Ensure ().ArtistSort = value; + set => Write (() => Ensure ().ArtistSort = value); } /// public override string? TitleSort { get => Id3?.TitleSort; - set => Ensure ().TitleSort = value; + set => Write (() => Ensure ().TitleSort = value); } /// public override string? AlbumArtistSort { get => Id3?.AlbumArtistSort; - set => Ensure ().AlbumArtistSort = value; + set => Write (() => Ensure ().AlbumArtistSort = value); } /// public override string? ReplayGainTrackGain { get => Id3?.ReplayGainTrackGain; - set => Ensure ().ReplayGainTrackGain = value; + set => Write (() => Ensure ().ReplayGainTrackGain = value); } /// public override string? ReplayGainTrackPeak { get => Id3?.ReplayGainTrackPeak; - set => Ensure ().ReplayGainTrackPeak = value; + set => Write (() => Ensure ().ReplayGainTrackPeak = value); } /// public override string? ReplayGainAlbumGain { get => Id3?.ReplayGainAlbumGain; - set => Ensure ().ReplayGainAlbumGain = value; + set => Write (() => Ensure ().ReplayGainAlbumGain = value); } /// public override string? ReplayGainAlbumPeak { get => Id3?.ReplayGainAlbumPeak; - set => Ensure ().ReplayGainAlbumPeak = value; + set => Write (() => Ensure ().ReplayGainAlbumPeak = value); } /// public override string? R128TrackGain { get => Id3?.R128TrackGain; - set => Ensure ().R128TrackGain = value; + set => Write (() => Ensure ().R128TrackGain = value); } /// public override string? R128AlbumGain { get => Id3?.R128AlbumGain; - set => Ensure ().R128AlbumGain = value; + set => Write (() => Ensure ().R128AlbumGain = value); } /// public override string? MusicBrainzTrackId { get => Id3?.MusicBrainzTrackId; - set => Ensure ().MusicBrainzTrackId = value; + set => Write (() => Ensure ().MusicBrainzTrackId = value); } /// public override string? MusicBrainzReleaseId { get => Id3?.MusicBrainzReleaseId; - set => Ensure ().MusicBrainzReleaseId = value; + set => Write (() => Ensure ().MusicBrainzReleaseId = value); } /// public override string? MusicBrainzArtistId { get => Id3?.MusicBrainzArtistId; - set => Ensure ().MusicBrainzArtistId = value; + set => Write (() => Ensure ().MusicBrainzArtistId = value); } /// public override string? MusicBrainzReleaseGroupId { get => Id3?.MusicBrainzReleaseGroupId; - set => Ensure ().MusicBrainzReleaseGroupId = value; + set => Write (() => Ensure ().MusicBrainzReleaseGroupId = value); } /// public override string? MusicBrainzAlbumArtistId { get => Id3?.MusicBrainzAlbumArtistId; - set => Ensure ().MusicBrainzAlbumArtistId = value; + set => Write (() => Ensure ().MusicBrainzAlbumArtistId = value); } /// public override string? MusicBrainzReleaseArtistId { get => Id3?.MusicBrainzReleaseArtistId; - set => Ensure ().MusicBrainzReleaseArtistId = value; + set => Write (() => Ensure ().MusicBrainzReleaseArtistId = value); } /// public override string? MusicBrainzRecordingId { get => Id3?.MusicBrainzRecordingId; - set => Ensure ().MusicBrainzRecordingId = value; + set => Write (() => Ensure ().MusicBrainzRecordingId = value); } /// public override string? MusicBrainzWorkId { get => Id3?.MusicBrainzWorkId; - set => Ensure ().MusicBrainzWorkId = value; + set => Write (() => Ensure ().MusicBrainzWorkId = value); } /// public override string? MusicBrainzDiscId { get => Id3?.MusicBrainzDiscId; - set => Ensure ().MusicBrainzDiscId = value; + set => Write (() => Ensure ().MusicBrainzDiscId = value); } /// public override string? MusicBrainzReleaseStatus { get => Id3?.MusicBrainzReleaseStatus; - set => Ensure ().MusicBrainzReleaseStatus = value; + set => Write (() => Ensure ().MusicBrainzReleaseStatus = value); } /// public override string? MusicBrainzReleaseType { get => Id3?.MusicBrainzReleaseType; - set => Ensure ().MusicBrainzReleaseType = value; + set => Write (() => Ensure ().MusicBrainzReleaseType = value); } /// public override string? MusicBrainzReleaseCountry { get => Id3?.MusicBrainzReleaseCountry; - set => Ensure ().MusicBrainzReleaseCountry = value; + set => Write (() => Ensure ().MusicBrainzReleaseCountry = value); } /// public override string? AcoustIdId { get => Id3?.AcoustIdId; - set => Ensure ().AcoustIdId = value; + set => Write (() => Ensure ().AcoustIdId = value); } /// public override string? AcoustIdFingerprint { get => Id3?.AcoustIdFingerprint; - set => Ensure ().AcoustIdFingerprint = value; + set => Write (() => Ensure ().AcoustIdFingerprint = value); } /// public override string? ComposerSort { get => Id3?.ComposerSort; - set => Ensure ().ComposerSort = value; + set => Write (() => Ensure ().ComposerSort = value); } /// public override string? DateTagged { get => Id3?.DateTagged; - set => Ensure ().DateTagged = value; + set => Write (() => Ensure ().DateTagged = value); } /// public override string? Description { get => Id3?.Description; - set => Ensure ().Description = value; + set => Write (() => Ensure ().Description = value); } /// public override string? AmazonId { get => Id3?.AmazonId; - set => Ensure ().AmazonId = value; + set => Write (() => Ensure ().AmazonId = value); } /// public override uint? DiscNumber { get => Id3?.DiscNumber; - set => Ensure ().DiscNumber = value; + set => Write (() => Ensure ().DiscNumber = value); } /// public override uint? BeatsPerMinute { get => Id3?.BeatsPerMinute; - set => Ensure ().BeatsPerMinute = value; + set => Write (() => Ensure ().BeatsPerMinute = value); } /// public override uint? MovementNumber { get => Id3?.MovementNumber; - set => Ensure ().MovementNumber = value; + set => Write (() => Ensure ().MovementNumber = value); } /// public override uint? MovementTotal { get => Id3?.MovementTotal; - set => Ensure ().MovementTotal = value; + set => Write (() => Ensure ().MovementTotal = value); } /// public override uint? TotalTracks { get => Id3?.TotalTracks; - set => Ensure ().TotalTracks = value; + set => Write (() => Ensure ().TotalTracks = value); } /// public override uint? TotalDiscs { get => Id3?.TotalDiscs; - set => Ensure ().TotalDiscs = value; + set => Write (() => Ensure ().TotalDiscs = value); } /// public override bool IsCompilation { get => Id3?.IsCompilation ?? false; - set => Ensure ().IsCompilation = value; + set => Write (() => Ensure ().IsCompilation = value); } /// @@ -435,55 +435,55 @@ public override string[] Performers { var artist = _file.Artist; return string.IsNullOrEmpty (artist) ? [] : [artist!]; } - set => _file.SetPerformers (value); + set => Write (() => _file.SetPerformers (value)); } /// public override string[] Genres { get => Id3?.Genres ?? []; - set => Ensure ().Genres = value; + set => Write (() => Ensure ().Genres = value); } /// public override string[] AlbumArtists { get => Id3?.AlbumArtists ?? []; - set => Ensure ().AlbumArtists = value; + set => Write (() => Ensure ().AlbumArtists = value); } /// public override string[] Composers { get => Id3?.Composers ?? []; - set => Ensure ().Composers = value; + set => Write (() => Ensure ().Composers = value); } /// public override string[]? PerformersSort { get => Id3?.PerformersSort; - set => Ensure ().PerformersSort = value; + set => Write (() => Ensure ().PerformersSort = value); } /// public override string[]? AlbumArtistsSort { get => Id3?.AlbumArtistsSort; - set => Ensure ().AlbumArtistsSort = value; + set => Write (() => Ensure ().AlbumArtistsSort = value); } /// public override string[]? ComposersSort { get => Id3?.ComposersSort; - set => Ensure ().ComposersSort = value; + set => Write (() => Ensure ().ComposersSort = value); } /// public override string[]? PerformersRole { get => Id3?.PerformersRole; - set => Ensure ().PerformersRole = value; + set => Write (() => Ensure ().PerformersRole = value); } /// public override IPicture[] Pictures { get => Id3?.Pictures ?? []; - set => Ensure ().Pictures = value; + set => Write (() => Ensure ().Pictures = value); } #pragma warning restore CA1819 @@ -497,7 +497,7 @@ public override BinaryData Render () => "AiffTag is a view over an AIFF file. Render the owning AiffFile instead."); /// - public override void Clear () => _file.ClearMappedFields (); + public override void Clear () => Write (_file.ClearMappedFields); /// /// Custom fields live in the file's ID3 tag, as TXXX frames; the native text chunks have fixed names. @@ -518,22 +518,18 @@ public override IReadOnlyList GetCustomField (string name) public override bool SetCustomField (string name, params string[] values) { CustomFieldValues.ThrowIfNull (name); - if (Id3 is { } existing) - return existing.SetCustomField (name, values); - - var created = new Id3v2Tag (); - if (!created.SetCustomField (name, values)) - return false; - if (!created.IsEmpty) - _file.Id3v2Tag = created; - return true; + var stored = false; + Write (() => stored = Ensure ().SetCustomField (name, values)); + return stored; } /// public override bool RemoveCustomField (string name) { CustomFieldValues.ThrowIfNull (name); - return Id3?.RemoveCustomField (name) ?? false; + var removed = false; + Write (() => removed = Id3?.RemoveCustomField (name) ?? false); + return removed; } Id3v2Tag? Id3 => _file.Id3v2Tag; @@ -553,4 +549,12 @@ internal override IEnumerable Leaves () } Id3v2Tag Ensure () => _file.EnsureId3 (); + + // A write that leaves the ID3 tag this view created empty removes it again (TagCreation), so the file stores no + // empty tag in memory either; a save already skips one. + void Write (Action write) + { + write (); + _file.Id3Creation.AfterWrite ([_file.Id3v2Tag]); + } } diff --git a/src/TagLibSharp2/Ape/ApePicture.cs b/src/TagLibSharp2/Ape/ApePicture.cs index 464bb108..781a7dc3 100644 --- a/src/TagLibSharp2/Ape/ApePicture.cs +++ b/src/TagLibSharp2/Ape/ApePicture.cs @@ -159,6 +159,8 @@ public static ApePicture FromPicture (IPicture picture) /// public static PictureType GetPictureTypeForKey (string key) { + if (key is null) + return PictureType.Other; if (string.Equals (key, FrontCoverKey, StringComparison.OrdinalIgnoreCase)) return PictureType.FrontCover; if (string.Equals (key, BackCoverKey, StringComparison.OrdinalIgnoreCase)) @@ -167,9 +169,33 @@ public static PictureType GetPictureTypeForKey (string key) return PictureType.Media; if (string.Equals (key, ArtistKey, StringComparison.OrdinalIgnoreCase)) return PictureType.Artist; + if (NamedCover (key) is PictureType named) + return named; return PictureType.Other; } + // "Cover Art (LeafletPage)" and the other ID3 picture-type names, in any case, with or without a space between + // the words ("Lead Artist"). The four keys above stay the names already stored in files. Only letters reach + // Enum.TryParse, which would also take "3" and "Other, BackCover". + static PictureType? NamedCover (string key) + { + const string Prefix = "Cover Art ("; + if (key.Length <= Prefix.Length + 1 || !key.StartsWith (Prefix, StringComparison.OrdinalIgnoreCase) || key[key.Length - 1] != ')') + return null; + var name = new System.Text.StringBuilder (key.Length); + for (var i = Prefix.Length; i < key.Length - 1; i++) { + var c = key[i]; + if (c == ' ' && name.Length > 0 && key[i - 1] != ' ' && i < key.Length - 2) + continue; + if (c is not ((>= 'A' and <= 'Z') or (>= 'a' and <= 'z'))) + return null; + name.Append (c); + } + + // A name of letters only parses only to a member of the enum. + return Enum.TryParse (name.ToString (), true, out PictureType type) ? type : null; + } + /// /// Gets the APE tag key for a picture type. /// @@ -179,8 +205,8 @@ public static string GetKeyForPictureType (PictureType type) PictureType.FrontCover => FrontCoverKey, PictureType.BackCover => BackCoverKey, PictureType.Media => MediaKey, - PictureType.Artist or PictureType.LeadArtist => ArtistKey, - _ => FrontCoverKey // Default to front cover + PictureType.Artist => ArtistKey, + _ => "Cover Art (" + type + ")" }; } diff --git a/src/TagLibSharp2/Ape/ApeTag.cs b/src/TagLibSharp2/Ape/ApeTag.cs index 7b693c7b..f0279641 100644 --- a/src/TagLibSharp2/Ape/ApeTag.cs +++ b/src/TagLibSharp2/Ape/ApeTag.cs @@ -172,6 +172,9 @@ private ApeTag (Dictionary items) /// public int ItemCount => _items.Count; + /// + internal override bool StoresNothing => _items.Count == 0; + /// public override string? Title { get => GetValue (Keys.Title); diff --git a/src/TagLibSharp2/Ape/MonkeysAudioFile.cs b/src/TagLibSharp2/Ape/MonkeysAudioFile.cs index 4bd0c7a6..53044338 100644 --- a/src/TagLibSharp2/Ape/MonkeysAudioFile.cs +++ b/src/TagLibSharp2/Ape/MonkeysAudioFile.cs @@ -159,7 +159,14 @@ private MonkeysAudioFile () { } public ApeTag? ApeTag { get; private set; } /// - public Tag? Tag => ApeTag; + /// + /// The APEv2 tag. A file with none has a view whose first write creates one, and a write that leaves that tag + /// empty removes it again, so a save writes no empty tag. Reading the view creates nothing. + /// + public Tag? Tag => _disposed ? null : CombinedTag.SingleOrView (ApeTag, () => ApeTag, + _creation ??= new TagCreation (() => new ApeTag (), tag => ApeTag = (ApeTag?)tag)); + + TagCreation? _creation; /// IMediaProperties? IMediaFile.AudioProperties => Properties; @@ -551,6 +558,7 @@ public void RemoveApeTag () /// public byte[] Render (ReadOnlySpan originalData) { + _creation?.Settle ([ApeTag]); byte[] tagData = ApeTag is null ? [] : ApeTag.Render ().ToArray (); var location = ApeTagLocation.Locate (originalData); return ApeTagLocation.Rewrite (originalData, location, tagData); @@ -607,6 +615,7 @@ public static async Task ReadFromFileAsync ( /// The result of the write operation. public FileWriteResult SaveToFile (string path, ReadOnlySpan originalData, IFileSystem? fileSystem = null) { + _creation?.Settle ([ApeTag]); if (PictureSkip.Refuse (this) is { } denied) return denied; @@ -627,6 +636,7 @@ public FileWriteResult SaveToFile (string path, ReadOnlySpan originalData, /// public FileWriteResult SaveToFile (string path, IFileSystem? fileSystem = null) { + _creation?.Settle ([ApeTag]); if (PictureSkip.Refuse (this) is { } denied) return denied; var fs = fileSystem ?? _sourceFileSystem; @@ -644,6 +654,7 @@ public FileWriteResult SaveToFile (string path, IFileSystem? fileSystem = null) /// public FileWriteResult SaveToFile (IFileSystem? fileSystem = null) { + _creation?.Settle ([ApeTag]); if (PictureSkip.Refuse (this) is { } denied) return denied; if (string.IsNullOrEmpty (SourcePath)) @@ -667,6 +678,7 @@ public async Task SaveToFileAsync ( IFileSystem? fileSystem = null, CancellationToken cancellationToken = default) { + _creation?.Settle ([ApeTag]); if (PictureSkip.Refuse (this) is { } denied) return denied; @@ -691,6 +703,7 @@ public Task SaveToFileAsync ( IFileSystem? fileSystem = null, CancellationToken cancellationToken = default) { + _creation?.Settle ([ApeTag]); if (PictureSkip.Refuse (this) is { } denied) return Task.FromResult (denied); var fs = fileSystem ?? _sourceFileSystem; @@ -710,6 +723,7 @@ public async Task SaveToFileAsync ( IFileSystem? fileSystem = null, CancellationToken cancellationToken = default) { + _creation?.Settle ([ApeTag]); if (PictureSkip.Refuse (this) is { } denied) return denied; if (string.IsNullOrEmpty (SourcePath)) diff --git a/src/TagLibSharp2/Asf/AsfTag.cs b/src/TagLibSharp2/Asf/AsfTag.cs index 17634f7f..9c189b34 100644 --- a/src/TagLibSharp2/Asf/AsfTag.cs +++ b/src/TagLibSharp2/Asf/AsfTag.cs @@ -68,7 +68,7 @@ public override string? Comment { /// Gets or sets the rating field from Content Description. /// public string Rating { - get => ContentDescriptionText ("Rating"); + get => ContentDescriptionText ("Rating") ?? ""; set => SetContentDescriptionValue ("Rating", value); } @@ -78,7 +78,7 @@ public string Rating { /// public override string? Album { - get => GetString ("WM/AlbumTitle") ?? ""; + get => GetString ("WM/AlbumTitle") is { Length: > 0 } album ? album : null; set => SetString ("WM/AlbumTitle", value); } @@ -90,7 +90,7 @@ public override string? Year { /// public override string? Genre { - get => GetString ("WM/Genre") ?? ""; + get => GetString ("WM/Genre") is { Length: > 0 } genre ? genre : null; set => SetString ("WM/Genre", value); } @@ -1026,10 +1026,12 @@ void SetContentDescriptionField (string name, string value) /// string value of that name in the Extended Content Description and then the Metadata or Metadata Library /// Object (). /// - string ContentDescriptionText (string name) + // An empty field reads as null, as an absent field does in every format (#211). + string? ContentDescriptionText (string name) { TryGetContentDescriptionField (name, out var value); - return string.IsNullOrEmpty (value) ? GetString (name) ?? value : value; + var text = string.IsNullOrEmpty (value) ? GetString (name) ?? value : value; + return string.IsNullOrEmpty (text) ? null : text; } string? FirstLibraryText (string name) diff --git a/src/TagLibSharp2/Core/CombinedTag.cs b/src/TagLibSharp2/Core/CombinedTag.cs index 0cbcdc34..a259bff6 100644 --- a/src/TagLibSharp2/Core/CombinedTag.cs +++ b/src/TagLibSharp2/Core/CombinedTag.cs @@ -35,6 +35,8 @@ namespace TagLibSharp2.Core; public class CombinedTag : Tag { readonly Tag?[] _tags; + readonly Func? _source; + readonly TagCreation? _creation; /// /// Initializes a new with the supplied tags in @@ -46,17 +48,51 @@ public CombinedTag (params Tag?[] tags) _tags = tags ?? []; } + /// + /// A view over the tags a file stores, which may not exist yet. is read on every get + /// and write. A write on a file that stores no tag creates one through , and a write + /// that leaves that tag empty drops it again. A get creates nothing. + /// + CombinedTag (Func source, TagCreation creation) + { + _tags = []; + _source = source; + _creation = creation; + } + + /// + /// The view a file returns over the tags reads: over those tags as they are when the + /// file has a tag no view created, else over whatever the file stores at each access, so a first write creates + /// the tag and a write that leaves it empty drops it (). + /// + internal static CombinedTag Over (Func stored, TagCreation creation) + { + var tags = stored (); + return Array.Exists (tags, tag => tag is not null) && !creation.Pending + ? new CombinedTag (tags) + : new CombinedTag (stored, creation); + } + + /// + /// The tag of a file that stores one tag: itself when the file has one no view created, + /// else a view over whose first write creates it (). + /// + internal static Tag SingleOrView (Tag? stored, Func read, TagCreation creation) => + stored is not null && !creation.Pending ? stored : new CombinedTag (() => [read ()], creation); + /// /// Gets the underlying tags in priority order. Null entries are preserved. /// - protected IReadOnlyList Tags => _tags; + protected IReadOnlyList Tags => Current; + + Tag?[] Current => _source?.Invoke () ?? _tags; /// Gets the member tags, for code inside the library that must reach each one. - internal IReadOnlyList Members => _tags; + internal IReadOnlyList Members => Current; T? FirstNonDefault (Func selector, Func isDefault) { - foreach (var tag in _tags) { + foreach (var tag in Current) { if (tag is null) continue; var value = selector (tag); @@ -78,7 +114,7 @@ public CombinedTag (params Tag?[] tags) // base returns nothing) does not hide a later tag that does. string[] FirstNonEmptyArray (Func selector) { - foreach (var tag in _tags) { + foreach (var tag in Current) { if (tag is null) continue; var value = selector (tag); @@ -90,7 +126,7 @@ string[] FirstNonEmptyArray (Func selector) string[]? FirstNonEmptyNullableArray (Func selector) { - foreach (var tag in _tags) { + foreach (var tag in Current) { if (tag is null) continue; var value = selector (tag); @@ -105,26 +141,31 @@ string[] FirstNonEmptyArray (Func selector) // ID3v2 TCMP of 0 is not replaced by a later tag. bool FirstBool (Func selector) { - foreach (var tag in _tags) { + foreach (var tag in Current) { if (tag is not null) return selector (tag); } return false; } + // A write through a view of a tagless file creates the stored tag first, and drops it again when the write + // leaves it storing nothing (TagCreation). void WriteToAll (Action setter) { - foreach (var tag in _tags) { + if (_source is not null) + _creation?.BeforeWrite (_source); + foreach (var tag in Current) { if (tag is not null) setter (tag); } + _creation?.AfterWrite (Current); } /// public override TagTypes TagType { get { var types = TagTypes.None; - foreach (var tag in _tags) { + foreach (var tag in Current) { if (tag is not null) types |= tag.TagType; } @@ -164,7 +205,7 @@ public override string? Year { internal override IEnumerable Leaves () { yield return this; - foreach (var inner in _tags) { + foreach (var inner in Current) { if (inner is null) continue; foreach (var leaf in inner.Leaves ()) @@ -608,7 +649,7 @@ public override IPicture[] Pictures { get { var merged = new List (); var seen = new HashSet<(PictureType, string, BinaryData)> (); - foreach (var tag in _tags) { + foreach (var tag in Current) { if (tag is null) continue; foreach (var p in tag.Pictures) { @@ -623,14 +664,19 @@ public override IPicture[] Pictures { #pragma warning restore CA1819 /// - /// True when any underlying tag supports custom fields. + /// + /// True when any underlying tag supports custom fields. A view over a file that stores no tag answers for the tag + /// its first write creates. + /// public override bool SupportsCustomFields { get { - foreach (var tag in _tags) { + var any = false; + foreach (var tag in Current) { if (tag is { SupportsCustomFields: true }) return true; + any |= tag is not null; } - return false; + return !any && _creation is { CreatesCustomFields: true }; } } @@ -639,7 +685,7 @@ public override bool SupportsCustomFields { public override IReadOnlyList GetCustomField (string name) { CustomFieldValues.ThrowIfNull (name); - foreach (var tag in _tags) { + foreach (var tag in Current) { if (tag is null) continue; var values = tag.GetCustomField (name); @@ -666,9 +712,11 @@ public override IReadOnlyList GetCustomField (string name) public override bool SetCustomField (string name, params string[] values) { CustomFieldValues.ThrowIfNull (name); + if (_source is not null) + _creation?.BeforeWrite (_source); var stored = false; List? refused = null; - foreach (var tag in _tags) { + foreach (var tag in Current) { if (tag is not { SupportsCustomFields: true }) continue; if (tag.SetCustomField (name, values)) @@ -681,6 +729,7 @@ public override bool SetCustomField (string name, params string[] values) foreach (var tag in refused) tag.RemoveCustomField (name); } + _creation?.AfterWrite (Current); return stored; } @@ -690,10 +739,11 @@ public override bool RemoveCustomField (string name) { CustomFieldValues.ThrowIfNull (name); var removed = false; - foreach (var tag in _tags) { + foreach (var tag in Current) { if (tag is not null) removed |= tag.RemoveCustomField (name); } + _creation?.AfterWrite (Current); return removed; } diff --git a/src/TagLibSharp2/Core/IMediaFile.cs b/src/TagLibSharp2/Core/IMediaFile.cs index c3f342d3..c89243a3 100644 --- a/src/TagLibSharp2/Core/IMediaFile.cs +++ b/src/TagLibSharp2/Core/IMediaFile.cs @@ -43,10 +43,15 @@ public interface IMediaFile : IDisposable /// /// The returned tag type depends on the file format. For example: /// - /// FLAC files return VorbisComment + /// FLAC files return a FlacTag over the Vorbis comment and the PICTURE blocks /// MP3 files return a combined tag (Id3v2Tag preferred, Id3v1Tag fallback) /// MP4 files return Mp4Tag /// + /// A file with no tag, of a format that can store text, returns an empty view ( is + /// ): reading it creates nothing, the first write creates the format's tag, and a write + /// that leaves that tag empty removes it again, and a save writes no empty tag the view created, however it was + /// emptied. A reference to that tag taken from the file (such as Id3v2Tag) goes dead when a view drops it: + /// read the property again, or write through the view. The tag is null for a still image that has no text store. /// Tag? Tag { get; } diff --git a/src/TagLibSharp2/Core/MediaFile.cs b/src/TagLibSharp2/Core/MediaFile.cs index d5c39919..23f516b6 100644 --- a/src/TagLibSharp2/Core/MediaFile.cs +++ b/src/TagLibSharp2/Core/MediaFile.cs @@ -547,7 +547,7 @@ static MediaFileResult FromMp3 (Mp3FileReadResult result, string? sourcePath = n return MediaFileResult.Failure (result.Error ?? "Failed to parse MP3 file"); if (sourcePath is { Length: > 0 }) result.File.RememberSource (sourcePath, fileSystem); - return MediaFileResult.Success (result.File, result.File.Tag, MediaFormat.Mp3); + return MediaFileResult.Success (result.File, MediaFormat.Mp3); } static MediaFileResult FromFlac (FlacFileReadResult result, string? sourcePath = null, IFileSystem? fileSystem = null) @@ -556,119 +556,119 @@ static MediaFileResult FromFlac (FlacFileReadResult result, string? sourcePath = return MediaFileResult.Failure (result.Error ?? "Failed to parse FLAC file"); if (sourcePath is { Length: > 0 }) result.File.RememberSource (sourcePath, fileSystem); - return MediaFileResult.Success (result.File, result.File.Tag, MediaFormat.Flac); + return MediaFileResult.Success (result.File, MediaFormat.Flac); } static MediaFileResult FromMp4 (Mp4FileReadResult result) { if (!result.IsSuccess || result.File is null) return MediaFileResult.Failure (result.Error ?? "Failed to parse MP4 file"); - return MediaFileResult.Success (result.File, result.File.Tag, MediaFormat.Mp4); + return MediaFileResult.Success (result.File, MediaFormat.Mp4); } static MediaFileResult FromMatroska (MatroskaFileReadResult result) { if (!result.IsSuccess || result.File is null) return MediaFileResult.Failure (result.Error ?? "Failed to parse Matroska file"); - return MediaFileResult.Success (result.File, result.File.Tag, MediaFormat.Matroska); + return MediaFileResult.Success (result.File, MediaFormat.Matroska); } static MediaFileResult FromOggVorbis (OggVorbisFileReadResult result) { if (!result.IsSuccess || result.File is null) return MediaFileResult.Failure (result.Error ?? "Failed to parse Ogg Vorbis file"); - return MediaFileResult.Success (result.File, result.File.VorbisComment, MediaFormat.OggVorbis); + return MediaFileResult.Success (result.File, MediaFormat.OggVorbis); } static MediaFileResult FromOpus (OggOpusFileReadResult result) { if (!result.IsSuccess || result.File is null) return MediaFileResult.Failure (result.Error ?? "Failed to parse Opus file"); - return MediaFileResult.Success (result.File, result.File.VorbisComment, MediaFormat.Opus); + return MediaFileResult.Success (result.File, MediaFormat.Opus); } static MediaFileResult FromOggFlac (OggFlacFileReadResult result) { if (!result.IsSuccess || result.File is null) return MediaFileResult.Failure (result.Error ?? "Failed to parse Ogg FLAC file"); - return MediaFileResult.Success (result.File, result.File.VorbisComment, MediaFormat.OggFlac); + return MediaFileResult.Success (result.File, MediaFormat.OggFlac); } static MediaFileResult FromAiff (AiffFileReadResult result) { if (!result.IsSuccess || result.File is null) return MediaFileResult.Failure (result.Error ?? "Failed to parse AIFF file"); - return MediaFileResult.Success (result.File, result.File.Tag, MediaFormat.Aiff); + return MediaFileResult.Success (result.File, MediaFormat.Aiff); } static MediaFileResult FromWavPack (WavPackFileReadResult result) { if (!result.IsSuccess || result.File is null) return MediaFileResult.Failure (result.Error ?? "Failed to parse WavPack file"); - return MediaFileResult.Success (result.File, result.File.ApeTag, MediaFormat.WavPack); + return MediaFileResult.Success (result.File, MediaFormat.WavPack); } static MediaFileResult FromMonkeys (MonkeysAudioFileReadResult result) { if (!result.IsSuccess || result.File is null) return MediaFileResult.Failure (result.Error ?? "Failed to parse Monkey's Audio file"); - return MediaFileResult.Success (result.File, result.File.ApeTag, MediaFormat.MonkeysAudio); + return MediaFileResult.Success (result.File, MediaFormat.MonkeysAudio); } static MediaFileResult FromMusepack (MusepackFileReadResult result) { if (!result.IsSuccess || result.File is null) return MediaFileResult.Failure (result.Error ?? "Failed to parse Musepack file"); - return MediaFileResult.Success (result.File, result.File.ApeTag, MediaFormat.Musepack); + return MediaFileResult.Success (result.File, MediaFormat.Musepack); } static MediaFileResult FromDsf (DsfFileReadResult result) { if (!result.IsSuccess || result.File is null) return MediaFileResult.Failure (result.Error ?? "Failed to parse DSF file"); - return MediaFileResult.Success (result.File, result.File.Id3v2Tag, MediaFormat.Dsf); + return MediaFileResult.Success (result.File, MediaFormat.Dsf); } static MediaFileResult FromDff (DffFileReadResult result) { if (!result.IsSuccess || result.File is null) return MediaFileResult.Failure (result.Error ?? "Failed to parse DFF file"); - return MediaFileResult.Success (result.File, result.File.Id3v2Tag, MediaFormat.Dff); + return MediaFileResult.Success (result.File, MediaFormat.Dff); } static MediaFileResult FromAsf (AsfFileReadResult result) { if (!result.IsSuccess || result.File is null) return MediaFileResult.Failure (result.Error ?? "Failed to parse ASF file"); - return MediaFileResult.Success (result.File, result.File.Tag, MediaFormat.Asf); + return MediaFileResult.Success (result.File, MediaFormat.Asf); } static MediaFileResult FromMpegPs (MpegPsFileReadResult result) { if (!result.IsSuccess || result.File is null) return MediaFileResult.Failure (result.Error ?? "Failed to parse MPEG program stream"); - return MediaFileResult.Success (result.File, result.File.Tag, MediaFormat.MpegPs); + return MediaFileResult.Success (result.File, MediaFormat.MpegPs); } static MediaFileResult FromAac (AacFileReadResult result) { if (!result.IsSuccess || result.File is null) return MediaFileResult.Failure (result.Error ?? "Failed to parse AAC file"); - return MediaFileResult.Success (result.File, result.File.Tag, MediaFormat.Aac); + return MediaFileResult.Success (result.File, MediaFormat.Aac); } static MediaFileResult FromAudible (AudibleFileReadResult result) { if (!result.IsSuccess || result.File is null) return MediaFileResult.Failure (result.Error ?? "Failed to parse Audible file"); - return MediaFileResult.Success (result.File, result.File.Tag, MediaFormat.Audible); + return MediaFileResult.Success (result.File, MediaFormat.Audible); } static MediaFileResult FromAvi (AviFileReadResult result) { if (!result.IsSuccess || result.File is null) return MediaFileResult.Failure (result.Error ?? "Failed to parse AVI file"); - return MediaFileResult.Success (result.File, result.File.UnifiedTag, MediaFormat.Avi); + return MediaFileResult.Success (result.File, MediaFormat.Avi); } static MediaFileResult FromWav (WavFileReadResult result) @@ -676,10 +676,7 @@ static MediaFileResult FromWav (WavFileReadResult result) if (!result.IsSuccess || result.File is null) return MediaFileResult.Failure (result.Error ?? "Failed to parse WAV file"); - Tag? tag = result.File.Id3v2Tag is not null - ? result.File.Id3v2Tag - : result.File.InfoTag; - return MediaFileResult.Success (result.File, tag, MediaFormat.Wav); + return MediaFileResult.Success (result.File, MediaFormat.Wav); } /// @@ -978,7 +975,7 @@ static MediaFileResult OpenFlac (ReadOnlyMemory data) if (!result.IsSuccess) return MediaFileResult.Failure (result.Error!); - return MediaFileResult.Success (result.File!, result.File!.Tag, MediaFormat.Flac); + return MediaFileResult.Success (result.File!, MediaFormat.Flac); } static MediaFileResult OpenOggVorbis (ReadOnlyMemory data) @@ -987,7 +984,7 @@ static MediaFileResult OpenOggVorbis (ReadOnlyMemory data) if (!result.IsSuccess) return MediaFileResult.Failure (result.Error!); - return MediaFileResult.Success (result.File!, result.File!.VorbisComment, MediaFormat.OggVorbis); + return MediaFileResult.Success (result.File!, MediaFormat.OggVorbis); } static MediaFileResult OpenOpus (ReadOnlyMemory data) @@ -996,7 +993,7 @@ static MediaFileResult OpenOpus (ReadOnlyMemory data) if (!result.IsSuccess) return MediaFileResult.Failure (result.Error!); - return MediaFileResult.Success (result.File!, result.File!.VorbisComment, MediaFormat.Opus); + return MediaFileResult.Success (result.File!, MediaFormat.Opus); } static MediaFileResult OpenMp3 (ReadOnlyMemory data) @@ -1005,7 +1002,7 @@ static MediaFileResult OpenMp3 (ReadOnlyMemory data) if (!result.IsSuccess) return MediaFileResult.Failure (result.Error!); - return MediaFileResult.Success (result.File!, result.File!.Tag, MediaFormat.Mp3); + return MediaFileResult.Success (result.File!, MediaFormat.Mp3); } static MediaFileResult OpenWav (ReadOnlyMemory data) @@ -1014,11 +1011,7 @@ static MediaFileResult OpenWav (ReadOnlyMemory data) if (!result.IsSuccess || result.File is null) return MediaFileResult.Failure (result.Error ?? "Failed to parse WAV file"); - // Prefer ID3v2 tag, fall back to RIFF INFO tag - Tag? tag = result.File.Id3v2Tag is not null - ? result.File.Id3v2Tag - : result.File.InfoTag; - return MediaFileResult.Success (result.File, tag, MediaFormat.Wav); + return MediaFileResult.Success (result.File, MediaFormat.Wav); } static MediaFileResult OpenAiff (ReadOnlyMemory data) @@ -1026,7 +1019,7 @@ static MediaFileResult OpenAiff (ReadOnlyMemory data) if (!AiffFile.TryRead (data.Span, out var file) || file is null) return MediaFileResult.Failure ("Failed to parse AIFF file"); - return MediaFileResult.Success (file, file.Tag, MediaFormat.Aiff); + return MediaFileResult.Success (file, MediaFormat.Aiff); } static MediaFileResult OpenMp4 (ReadOnlyMemory data) @@ -1035,7 +1028,7 @@ static MediaFileResult OpenMp4 (ReadOnlyMemory data) if (!result.IsSuccess) return MediaFileResult.Failure (result.Error!); - return MediaFileResult.Success (result.File!, result.File!.Tag, MediaFormat.Mp4); + return MediaFileResult.Success (result.File!, MediaFormat.Mp4); } static MediaFileResult OpenDsf (ReadOnlyMemory data) @@ -1044,7 +1037,7 @@ static MediaFileResult OpenDsf (ReadOnlyMemory data) if (!result.IsSuccess) return MediaFileResult.Failure (result.Error!); - return MediaFileResult.Success (result.File!, result.File!.Id3v2Tag, MediaFormat.Dsf); + return MediaFileResult.Success (result.File!, MediaFormat.Dsf); } static MediaFileResult OpenDff (ReadOnlyMemory data) @@ -1053,7 +1046,7 @@ static MediaFileResult OpenDff (ReadOnlyMemory data) if (!result.IsSuccess) return MediaFileResult.Failure (result.Error!); - return MediaFileResult.Success (result.File!, result.File!.Id3v2Tag, MediaFormat.Dff); + return MediaFileResult.Success (result.File!, MediaFormat.Dff); } static MediaFileResult OpenOggFlac (ReadOnlyMemory data) @@ -1062,7 +1055,7 @@ static MediaFileResult OpenOggFlac (ReadOnlyMemory data) if (!result.IsSuccess) return MediaFileResult.Failure (result.Error!); - return MediaFileResult.Success (result.File!, result.File!.VorbisComment, MediaFormat.OggFlac); + return MediaFileResult.Success (result.File!, MediaFormat.OggFlac); } static MediaFileResult OpenWavPack (ReadOnlyMemory data) @@ -1071,7 +1064,7 @@ static MediaFileResult OpenWavPack (ReadOnlyMemory data) if (!result.IsSuccess) return MediaFileResult.Failure (result.Error!); - return MediaFileResult.Success (result.File!, result.File!.ApeTag, MediaFormat.WavPack); + return MediaFileResult.Success (result.File!, MediaFormat.WavPack); } static MediaFileResult OpenMonkeysAudio (ReadOnlyMemory data) @@ -1080,14 +1073,14 @@ static MediaFileResult OpenMonkeysAudio (ReadOnlyMemory data) if (!result.IsSuccess) return MediaFileResult.Failure (result.Error!); - return MediaFileResult.Success (result.File!, result.File!.ApeTag, MediaFormat.MonkeysAudio); + return MediaFileResult.Success (result.File!, 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.Success (opened.File!, format) : MediaFileResult.Failure (opened.Error!); } @@ -1111,7 +1104,7 @@ static MediaFileResult OpenAsf (ReadOnlyMemory data) if (!result.IsSuccess) return MediaFileResult.Failure (result.Error!); - return MediaFileResult.Success (result.File!, result.File!.Tag, MediaFormat.Asf); + return MediaFileResult.Success (result.File!, MediaFormat.Asf); } static MediaFileResult OpenMusepack (ReadOnlyMemory data) @@ -1120,7 +1113,7 @@ static MediaFileResult OpenMusepack (ReadOnlyMemory data) if (!result.IsSuccess) return MediaFileResult.Failure (result.Error!); - return MediaFileResult.Success (result.File!, result.File!.ApeTag, MediaFormat.Musepack); + return MediaFileResult.Success (result.File!, MediaFormat.Musepack); } static MediaFileResult OpenMatroska (ReadOnlyMemory data) @@ -1129,7 +1122,7 @@ static MediaFileResult OpenMatroska (ReadOnlyMemory data) if (!result.IsSuccess) return MediaFileResult.Failure (result.Error!); - return MediaFileResult.Success (result.File!, result.File!.Tag, MediaFormat.Matroska); + return MediaFileResult.Success (result.File!, MediaFormat.Matroska); } } @@ -1151,38 +1144,40 @@ public sealed class MediaFileResult /// /// Gets the underlying file object (FlacFile, Mp3File, etc.). /// - public object? File { get; } + public object? File => _file; + + readonly IMediaFile? _file; /// - /// Gets the tag from the file (VorbisComment, Id3v2Tag, etc.). + /// Gets the tag of : its , read when this is read, so a tagless + /// file's view and the tag a write creates are the ones the file has. Null when the file failed to open. /// - public Tag? Tag { get; } + public Tag? Tag => _file?.Tag; /// /// Gets the detected media format. /// public MediaFormat Format { get; } - MediaFileResult (bool isSuccess, string? error, object? file, Tag? tag, MediaFormat format) + MediaFileResult (bool isSuccess, string? error, IMediaFile? file, MediaFormat format) { IsSuccess = isSuccess; Error = error; - File = file; - Tag = tag; + _file = file; Format = format; } /// /// Creates a successful result. /// - internal static MediaFileResult Success (object file, Tag? tag, MediaFormat format) => - new (true, null, file, tag, format); + internal static MediaFileResult Success (IMediaFile file, MediaFormat format) => + new (true, null, file, format); /// /// Creates a failed result. /// internal static MediaFileResult Failure (string error) => - new (false, error, null, null, MediaFormat.Unknown); + new (false, error, null, MediaFormat.Unknown); /// /// Gets the file as a specific type. diff --git a/src/TagLibSharp2/Core/PictureType.cs b/src/TagLibSharp2/Core/PictureType.cs index 3eef2e7c..cf84e339 100644 --- a/src/TagLibSharp2/Core/PictureType.cs +++ b/src/TagLibSharp2/Core/PictureType.cs @@ -120,3 +120,15 @@ public enum PictureType : byte /// PublisherLogo = 0x14 } + +/// Checks on values read from a file. +static class PictureTypes +{ + /// Whether is one of the ID3v2 picture types (ID3v2.4 frames §4.14). + public static bool IsDefined (PictureType type) => +#if NET5_0_OR_GREATER + Enum.IsDefined (type); +#else + Enum.IsDefined (typeof (PictureType), type); +#endif +} diff --git a/src/TagLibSharp2/Core/Tag.cs b/src/TagLibSharp2/Core/Tag.cs index 202aae56..5548636f 100644 --- a/src/TagLibSharp2/Core/Tag.cs +++ b/src/TagLibSharp2/Core/Tag.cs @@ -145,7 +145,7 @@ internal static bool IsWriteBack (uint? value, uint? current) => /// /// Format-specific limitations: /// - /// ID3v1: Truncated to 30 bytes. Latin-1 encoding only (Unicode characters are lost). + /// ID3v1: Truncated to 30 bytes. Latin-1 encoding only; a save fails on a character beyond U+00FF that no other tag of the file holds. /// ID3v2, Vorbis, MP4, ASF: Full Unicode support, no practical length limit. /// /// @@ -156,10 +156,10 @@ internal static bool IsWriteBack (uint? value, uint? current) => /// /// /// This returns the first performer. For multiple performers, use . - /// In ID3v2, APE, Vorbis Comments, and ASF, writing back the value read keeps the other names; any other value, and any value writes, replaces the list. + /// In ID3v2, APE, Vorbis Comments, ASF, and Matroska, writing back the value read keeps the other names; any other value, and any value writes, replaces the list. /// Format-specific limitations: /// - /// ID3v1: Truncated to 30 bytes. Latin-1 encoding only (Unicode characters are lost). + /// ID3v1: Truncated to 30 bytes. Latin-1 encoding only; a save fails on a character beyond U+00FF that no other tag of the file holds. /// ID3v2, Vorbis, MP4, ASF: Full Unicode support, no practical length limit. /// /// @@ -194,7 +194,7 @@ public virtual string[] Performers { /// /// Format-specific limitations: /// - /// ID3v1: Truncated to 30 bytes. Latin-1 encoding only (Unicode characters are lost). + /// ID3v1: Truncated to 30 bytes. Latin-1 encoding only; a save fails on a character beyond U+00FF that no other tag of the file holds. /// ID3v2, Vorbis, MP4, ASF: Full Unicode support, no practical length limit. /// /// @@ -242,7 +242,7 @@ public virtual string[] Performers { /// /// Format-specific limitations: /// - /// ID3v1: Truncated to 28 bytes (or 30 if no track number). Latin-1 encoding only. + /// ID3v1: Truncated to 28 bytes (or 30 if no track number). Latin-1 encoding only; a save fails on a character beyond U+00FF that no other tag of the file holds. /// ID3v2, Vorbis, MP4, ASF: Full Unicode support, no practical length limit. /// /// @@ -301,7 +301,7 @@ public virtual string[] Genres { /// /// /// This returns the first album artist. For multiple album artists, use . - /// In ID3v2, APE, Vorbis Comments, and ASF, writing back the value read keeps the other names; any other value, and any value writes, replaces the list. + /// In ID3v2, APE, Vorbis Comments, ASF, and Matroska, writing back the value read keeps the other names; any other value, and any value writes, replaces the list. /// Not all tag formats support this field. Default implementation returns null. /// public virtual string? AlbumArtist { get => null; set { } } @@ -341,7 +341,7 @@ public virtual string[] AlbumArtists { /// /// /// This returns the first composer. For multiple composers, use . - /// In ID3v2, APE, Vorbis Comments, and ASF, writing back the value read keeps the other names; any other value, and any value writes, replaces the list. + /// In ID3v2, APE, Vorbis Comments, ASF, and Matroska, writing back the value read keeps the other names; any other value, and any value writes, replaces the list. /// Not all tag formats support this field. Default implementation returns null. /// public virtual string? Composer { get => null; set { } } @@ -1135,7 +1135,7 @@ public virtual string? MusicBrainzReleaseArtistId { #pragma warning restore CA1819 /// - /// Gets a value indicating whether all standard fields are empty or null. + /// Gets a value indicating whether all standard fields are empty or null and the tag holds no picture. /// public virtual bool IsEmpty => string.IsNullOrEmpty (Title) && @@ -1144,7 +1144,14 @@ public virtual string? MusicBrainzReleaseArtistId { string.IsNullOrEmpty (Year) && string.IsNullOrEmpty (Comment) && string.IsNullOrEmpty (Genre) && - Track is null; + Track is null && + Pictures.Length == 0; + + /// + /// Whether the tag stores nothing at all: no field, mapped or custom, and no picture. A tag whose + /// looks only at the standard fields overrides this. + /// + internal virtual bool StoresNothing => IsEmpty; /// /// Gets a value indicating whether this tag can store a field under a name the caller chooses. diff --git a/src/TagLibSharp2/Core/TagCreation.cs b/src/TagLibSharp2/Core/TagCreation.cs new file mode 100644 index 00000000..4c65cee9 --- /dev/null +++ b/src/TagLibSharp2/Core/TagCreation.cs @@ -0,0 +1,70 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +namespace TagLibSharp2.Core; + +/// +/// The stored tag that the tag views of a tagless file create on their first write, shared by every view the file +/// returns. A write that leaves that tag empty drops it again, so writing null, clearing, writing back an empty value, +/// or setting a value and clearing it later stores no empty tag, and a save writes the file as it was read. A tag the +/// file was read with, or one the caller assigned, is never dropped. +/// +/// +/// A reference to the created tag taken from the file (such as file.Id3v2Tag) goes dead when a later write +/// through a view drops that tag: values set on it afterwards are not saved. Read the stored-tag property again, or +/// write through the view. +/// +/// Makes a new, empty tag of the format. +/// Stores a tag in the file, or removes the stored one when given null. +internal sealed class TagCreation (Func make, Action store) +{ + Tag? _created; + Tag? _blank; + + /// + /// Whether the tag this would create stores custom fields, so a view over a tagless file answers + /// for the tag its first write creates. + /// + public bool CreatesCustomFields => (_blank ??= make ()).SupportsCustomFields; + + /// Whether a view created the tag the file stores now. + public bool Pending => _created is not null; + + /// + /// Creates and stores the tag when the file stores none. reads the stored tags. + /// + public void BeforeWrite (Func read) + { + var stored = read (); + // A tag the caller removed or replaced since the last write is no longer the view's. + if (_created is not null && Array.IndexOf (stored, _created) < 0) + _created = null; + if (_created is not null || !Array.TrueForAll (stored, tag => tag is null)) + return; + _created = make (); + store (_created); + } + + /// + /// Called by a save before it writes: drops the created tag when the file still stores it and it stores nothing, + /// however it was emptied (through a view or through the stored-tag property), so no empty tag is written. + /// + public void Settle (Tag?[] stored) => AfterWrite (stored); + + /// Drops the created tag when the file still stores it and it holds nothing. + public void AfterWrite (Tag?[] stored) + { + if (_created is null) + return; + // The caller replaced the tag the view created: it is theirs now. + if (Array.IndexOf (stored, _created) < 0) { + _created = null; + return; + } + + if (!_created.StoresNothing) + return; + _created = null; + store (null); + } +} diff --git a/src/TagLibSharp2/Core/VideoProperties.cs b/src/TagLibSharp2/Core/VideoProperties.cs index 676cc7bf..92e05d36 100644 --- a/src/TagLibSharp2/Core/VideoProperties.cs +++ b/src/TagLibSharp2/Core/VideoProperties.cs @@ -32,6 +32,18 @@ public readonly record struct VideoProperties ( /// public bool IsValid => Width > 0 && Height > 0; + /// + /// Gets the clockwise rotation, in degrees from 0 to 359, that the file asks a player to apply when it shows + /// the picture. and are the size before this rotation. + /// + /// + /// MP4 and QuickTime: the angle of the track header matrix (ISO/IEC 14496-12 §8.3.2), 0 when the matrix mirrors + /// or skews the picture. Matroska: the negated ProjectionPoseRoll (RFC 9559 §15, §5.1.4.1.28.46), which + /// counts counter-clockwise, for a rectangular projection with no yaw or pitch. 0 for every other format, which + /// has no rotation field. + /// + public int Rotation { get; init; } + /// /// Gets an empty instance with no video properties. /// @@ -54,6 +66,8 @@ public override string ToString () parts.Add ($"{Bitrate}kbps"); if (FrameRate > 0) parts.Add ($"{FrameRate:F2}fps"); + if (Rotation != 0) + parts.Add ($"rotated {Rotation}°"); if (!string.IsNullOrEmpty (Codec)) parts.Add (Codec!); diff --git a/src/TagLibSharp2/Dff/DffFile.cs b/src/TagLibSharp2/Dff/DffFile.cs index 18160bfe..46500445 100644 --- a/src/TagLibSharp2/Dff/DffFile.cs +++ b/src/TagLibSharp2/Dff/DffFile.cs @@ -149,6 +149,7 @@ internal void MarkPicturesSkipped () private byte[]? _originalData; private bool _disposed; + TagCreation? _creation; private IFileSystem? _sourceFileSystem; private ulong _sampleCount; /// The files this object describes; a save from caller bytes must be one of them (#178). @@ -194,7 +195,19 @@ internal void MarkPicturesSkipped () public Id3v2Tag? Id3v2Tag { get; set; } /// - public Tag? Tag => Id3v2Tag; + /// + /// Reading the view does not create a stored tag. The first write creates an ID3v2 tag, and a + /// write that leaves that tag empty removes it again, so a save writes no empty tag. While it is + /// there, this is the view, not the itself. + /// + public Tag? Tag { + get { + if (_disposed) + return null; + return CombinedTag.SingleOrView (Id3v2Tag, () => Id3v2Tag, + _creation ??= new TagCreation (() => new Id3v2Tag (), tag => Id3v2Tag = (Id3v2Tag?)tag)); + } + } /// IMediaProperties? IMediaFile.AudioProperties => Properties; @@ -659,6 +672,7 @@ public Id3v2Tag EnsureId3v2Tag () /// public BinaryData Render () { + _creation?.Settle ([Id3v2Tag]); if (_disposed) throw new ObjectDisposedException (nameof (DffFile)); @@ -724,6 +738,7 @@ public BinaryData Render () /// A result indicating success or failure. public FileWriteResult SaveToFile (string path, ReadOnlySpan originalData, IFileSystem? fileSystem = null) { + _creation?.Settle ([Id3v2Tag]); if (_disposed) throw new ObjectDisposedException (nameof (DffFile)); if (PictureSkip.Refuse (this) is { } denied) @@ -755,6 +770,7 @@ public Task SaveToFileAsync ( IFileSystem? fileSystem = null, CancellationToken cancellationToken = default) { + _creation?.Settle ([Id3v2Tag]); if (_disposed) throw new ObjectDisposedException (nameof (DffFile)); if (PictureSkip.Refuse (this) is { } denied) @@ -784,6 +800,7 @@ public Task SaveToFileAsync ( /// A result indicating success or failure. public FileWriteResult SaveToFile (string path, IFileSystem? fileSystem = null) { + _creation?.Settle ([Id3v2Tag]); if (_disposed) throw new ObjectDisposedException (nameof (DffFile)); if (PictureSkip.Refuse (this) is { } denied) @@ -799,6 +816,7 @@ public FileWriteResult SaveToFile (string path, IFileSystem? fileSystem = null) /// A result indicating success or failure. public FileWriteResult SaveToFile (IFileSystem? fileSystem = null) { + _creation?.Settle ([Id3v2Tag]); if (_disposed) throw new ObjectDisposedException (nameof (DffFile)); if (PictureSkip.Refuse (this) is { } denied) @@ -819,6 +837,7 @@ public Task SaveToFileAsync ( IFileSystem? fileSystem = null, CancellationToken cancellationToken = default) { + _creation?.Settle ([Id3v2Tag]); if (_disposed) throw new ObjectDisposedException (nameof (DffFile)); if (PictureSkip.Refuse (this) is { } denied) @@ -837,6 +856,7 @@ public Task SaveToFileAsync ( IFileSystem? fileSystem = null, CancellationToken cancellationToken = default) { + _creation?.Settle ([Id3v2Tag]); if (_disposed) throw new ObjectDisposedException (nameof (DffFile)); if (PictureSkip.Refuse (this) is { } denied) diff --git a/src/TagLibSharp2/Dsf/DsfFile.cs b/src/TagLibSharp2/Dsf/DsfFile.cs index 083848e7..15beb27a 100644 --- a/src/TagLibSharp2/Dsf/DsfFile.cs +++ b/src/TagLibSharp2/Dsf/DsfFile.cs @@ -148,6 +148,7 @@ internal void MarkPicturesSkipped () private byte[]? _originalData; private bool _disposed; + TagCreation? _creation; private readonly DsfDsdChunk _dsdChunk; private readonly DsfFmtChunk _fmtChunk; private readonly DsfDataChunk _dataChunk; @@ -218,7 +219,19 @@ internal void MarkPicturesSkipped () public DsfAudioProperties? Properties { get; private set; } /// - public Tag? Tag => Id3v2Tag; + /// + /// Reading the view does not create a stored tag. The first write creates an ID3v2 tag, and a + /// write that leaves that tag empty removes it again, so a save writes no empty tag. While it is + /// there, this is the view, not the itself. + /// + public Tag? Tag { + get { + if (_disposed) + return null; + return CombinedTag.SingleOrView (Id3v2Tag, () => Id3v2Tag, + _creation ??= new TagCreation (() => new Id3v2Tag (), tag => Id3v2Tag = (Id3v2Tag?)tag)); + } + } /// IMediaProperties? IMediaFile.AudioProperties => Properties; @@ -530,6 +543,7 @@ public Id3v2Tag EnsureId3v2Tag () /// public BinaryData Render () { + _creation?.Settle ([Id3v2Tag]); if (_disposed) throw new ObjectDisposedException (nameof (DsfFile)); @@ -614,6 +628,7 @@ bool TryRenderFrom (ReadOnlySpan original, out BinaryData rendered, out st /// A result indicating success or failure. public FileWriteResult SaveToFile (string path, ReadOnlySpan originalData, IFileSystem? fileSystem = null) { + _creation?.Settle ([Id3v2Tag]); if (_disposed) throw new ObjectDisposedException (nameof (DsfFile)); if (PictureSkip.Refuse (this) is { } denied) @@ -666,6 +681,7 @@ public Task SaveToFileAsync ( IFileSystem? fileSystem = null, CancellationToken cancellationToken = default) { + _creation?.Settle ([Id3v2Tag]); if (_disposed) throw new ObjectDisposedException (nameof (DsfFile)); if (PictureSkip.Refuse (this) is { } denied) @@ -697,6 +713,7 @@ public Task SaveToFileAsync ( /// A result indicating success or failure. public FileWriteResult SaveToFile (string path, IFileSystem? fileSystem = null) { + _creation?.Settle ([Id3v2Tag]); if (_disposed) throw new ObjectDisposedException (nameof (DsfFile)); if (PictureSkip.Refuse (this) is { } denied) @@ -821,6 +838,7 @@ long MetadataEnd () /// A result indicating success or failure. public FileWriteResult SaveToFile (IFileSystem? fileSystem = null) { + _creation?.Settle ([Id3v2Tag]); if (_disposed) throw new ObjectDisposedException (nameof (DsfFile)); if (PictureSkip.Refuse (this) is { } denied) @@ -851,6 +869,7 @@ public Task SaveToFileAsync ( IFileSystem? fileSystem = null, CancellationToken cancellationToken = default) { + _creation?.Settle ([Id3v2Tag]); if (_disposed) throw new ObjectDisposedException (nameof (DsfFile)); if (PictureSkip.Refuse (this) is { } denied) @@ -875,6 +894,7 @@ public Task SaveToFileAsync ( IFileSystem? fileSystem = null, CancellationToken cancellationToken = default) { + _creation?.Settle ([Id3v2Tag]); if (_disposed) throw new ObjectDisposedException (nameof (DsfFile)); if (PictureSkip.Refuse (this) is { } denied) diff --git a/src/TagLibSharp2/Id3/Id3v1Tag.cs b/src/TagLibSharp2/Id3/Id3v1Tag.cs index d7fb561e..8335f6e1 100644 --- a/src/TagLibSharp2/Id3/Id3v1Tag.cs +++ b/src/TagLibSharp2/Id3/Id3v1Tag.cs @@ -9,6 +9,11 @@ namespace TagLibSharp2.Id3; /// Represents an ID3v1 or ID3v1.1 tag. /// ID3v1 is a fixed 128-byte structure stored at the end of an audio file. /// +/// +/// Title, Artist and Album hold 30 bytes, Comment 30 (28 with a track number) and Year 4. A longer value is cut to +/// its field on render, as the format holds no more. Text is Latin-1: a save of an MP3, AAC or MPEG-PS file fails, +/// and writes nothing, when a value has a character beyond U+00FF that no other tag of the file holds. +/// public sealed class Id3v1Tag : Tag { /// @@ -147,6 +152,45 @@ public static TagReadResult Read (ReadOnlySpan data) public static TagReadResult Read (byte[] data) => Read (data.AsSpan ()); + static readonly (string Name, Func Read)[] TextFields = [ + ("Title", static tag => tag.Title), + ("Artist", static tag => tag.Artist), + ("Album", static tag => tag.Album), + ("Year", static tag => tag.Year), + ("Comment", static tag => tag.Comment), + ]; + + /// + /// Why a save that writes this tag is refused, or null. ID3v1 text is Latin-1 (ISO 8859-1), so a character beyond + /// U+00FF would be written as '?', the #209 rule. A field whose text one of also holds is a + /// short copy and loses nothing: a write through a file's Tag reaches every tag. Text read from a file is Latin-1, + /// so only a value set can be refused. The 30-byte field size is the format's, and a longer value is cut to it. + /// + /// The format, as the message names it. + /// The file type whose Id3v2Tag the message points to. + /// The file's other tags. + internal string? Latin1Refusal (string format, string owner, params Tag?[] others) + { + foreach (var (name, read) in TextFields) { + var value = read (this); + if (value is null || !HasNonLatin1 (value) || others.Any (other => other is not null && read (other) == value)) + continue; + return $"Cannot save the {format} file: its ID3v1 tag stores Latin-1 text, and {name} ('{value}') has a character Latin-1 cannot hold. Store that text in {owner}.Id3v2Tag, or remove it from the ID3v1 tag."; + } + + return null; + } + + static bool HasNonLatin1 (string value) + { + foreach (var c in value) { + if (c > '\u00FF') + return true; + } + + return false; + } + /// public override BinaryData Render () { diff --git a/src/TagLibSharp2/Id3/Id3v2/Frames/PictureFrame.cs b/src/TagLibSharp2/Id3/Id3v2/Frames/PictureFrame.cs index 55f45939..2e3a08b6 100644 --- a/src/TagLibSharp2/Id3/Id3v2/Frames/PictureFrame.cs +++ b/src/TagLibSharp2/Id3/Id3v2/Frames/PictureFrame.cs @@ -184,8 +184,9 @@ public static PictureFrame FromFile (string path, PictureType pictureType = Pict /// /// Attempts to read an APIC frame from binary data. /// - /// The frame content data (excluding the 10-byte frame header). - /// The ID3v2 version (affects text encoding validation). + /// The frame content data (excluding the frame header). + /// The ID3v2 version (affects text encoding validation). For + /// the data is a PIC body, whose 3-character image format is read as a MIME type. /// /// A indicating success or failure. /// Check before accessing @@ -218,6 +219,9 @@ public static PictureFrameReadResult Read (ReadOnlySpan data, Id3v2Version var encoding = (TextEncodingType)encodingByte; + if (version == Id3v2Version.V22 && !StartsWithImageMimeType (data.Slice (offset))) + return ReadV22Body (data, encoding); + // MIME type (null-terminated ASCII) var mimeTypeEnd = FindNullTerminator (data.Slice (offset), 1); if (mimeTypeEnd < 0) @@ -240,30 +244,71 @@ public static PictureFrameReadResult Read (ReadOnlySpan data, Id3v2Version if (offset >= data.Length) return PictureFrameReadResult.Failure ("Frame ends after picture type"); - // Description (null-terminated in specified encoding) + var (description, pictureData) = ReadDescriptionAndData (data.Slice (offset), encoding); + var frame = new PictureFrame (mimeType, pictureType, description, pictureData, encoding); + + return PictureFrameReadResult.Success (frame, data.Length); + } + + /// + /// Reads the description, terminated in , and the picture data after it. With no + /// terminator the description is empty and every byte is picture data. + /// + static (string Description, BinaryData Data) ReadDescriptionAndData (ReadOnlySpan data, TextEncodingType encoding) + { var nullSize = GetNullTerminatorSize (encoding); - var descriptionEnd = FindNullTerminator (data.Slice (offset), nullSize); - - string description; - if (descriptionEnd < 0) { - // No null terminator - treat rest as empty description with all remaining data as image - description = string.Empty; - // Don't advance offset - all remaining data is picture data - } else { - description = DecodeString (data.Slice (offset, descriptionEnd), encoding); - offset += descriptionEnd + nullSize; // Skip description and null terminator - } + var descriptionEnd = FindNullTerminator (data, nullSize); + if (descriptionEnd < 0) + return (string.Empty, new BinaryData (data)); - // Picture data (remaining bytes) - var pictureData = offset < data.Length - ? new BinaryData (data.Slice (offset)) - : BinaryData.Empty; + var description = DecodeString (data.Slice (0, descriptionEnd), encoding); + var offset = descriptionEnd + nullSize; + return (description, offset < data.Length ? new BinaryData (data.Slice (offset)) : BinaryData.Empty); + } - var frame = new PictureFrame (mimeType, pictureType, description, pictureData, encoding); + /// + /// Reads an ID3v2.2 PIC body (https://id3.org/id3v2-00, §4.15): encoding, a 3-character image format, the picture + /// type, a terminated description and the picture data. The image format becomes the MIME type an ID3v2.3 APIC + /// frame holds (). + /// + static PictureFrameReadResult ReadV22Body (ReadOnlySpan data, TextEncodingType encoding) + { + const int TypeOffset = 1 + ImageFormatLength; + if (data.Length <= TypeOffset + 1) + return PictureFrameReadResult.Failure ("PIC frame data is too short"); + + var mimeType = MimeTypeOfImageFormat (data.Slice (1, ImageFormatLength)); + var pictureType = (PictureType)data[TypeOffset]; + var (description, pictureData) = ReadDescriptionAndData (data.Slice (TypeOffset + 1), encoding); + return PictureFrameReadResult.Success (new PictureFrame (mimeType, pictureType, description, pictureData, encoding), data.Length); + } - return PictureFrameReadResult.Success (frame, data.Length); + const int ImageFormatLength = 3; + + /// + /// The MIME type of an ID3v2.2 image format. §4.15 prefers "PNG" and "JPG"; "-->" marks a link in both versions + /// (ID3v2.3 §4.15); any other format is taken as the image subtype, since ID3v2.3 implies "image/". + /// + static string MimeTypeOfImageFormat (ReadOnlySpan format) + { + var name = Polyfills.Latin1.GetString (format); + if (name.Equals ("JPG", StringComparison.OrdinalIgnoreCase)) + return "image/jpeg"; + if (name == "-->") + return name; +#pragma warning disable CA1308 // MIME subtypes are lowercase by convention + return "image/" + name.ToLowerInvariant (); +#pragma warning restore CA1308 } + /// + /// True when a PIC body holds a NUL-terminated MIME type starting "image/" where §4.15 puts the image format: the + /// APIC layout, which some writers use in PIC. Read as §4.15 says, its picture data would start with the picture + /// type and the description. + /// + static bool StartsWithImageMimeType (ReadOnlySpan afterEncoding) => + afterEncoding.StartsWith ("image/"u8) && afterEncoding.IndexOf ((byte)0) >= 0; + /// /// Renders the frame content to binary data for writing to a file. /// diff --git a/src/TagLibSharp2/Id3/Id3v2/Id3v22FrameIds.cs b/src/TagLibSharp2/Id3/Id3v2/Id3v22FrameIds.cs new file mode 100644 index 00000000..1651e92a --- /dev/null +++ b/src/TagLibSharp2/Id3/Id3v2/Id3v22FrameIds.cs @@ -0,0 +1,109 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +namespace TagLibSharp2.Id3.Id3v2; + +/// +/// The ID3v2.3 frame ID of each ID3v2.2 frame. A tag read as v2.2 holds its frames under these IDs and is written as +/// v2.3, so every pair here is a v2.3 frame whose body has the v2.2 layout: the same fields, and text encodings +/// $00 (ISO-8859-1) and $01 (Unicode) only. PIC is the one exception; its 3-character image format is turned into a +/// MIME type when it is read (). +/// +/// +/// The pairs follow the frame lists of ID3v2.2 §4 (https://id3.org/id3v2-00) and ID3v2.3 §4 +/// (https://id3.org/id3v2.3.0). ID3v2.3 is the target because ID3v2.4 removed or reshaped several of them: TYE, TDA, +/// TIM and TRD (TDRC), TOR (TDOR), IPL (TIPL/TMCL), RVA (RVA2) and EQU (EQU2), and TSI is gone. +/// TCP, TS2, TSA, TSC, TSP and TST are not in ID3v2.2. They are the v2.2 IDs Apple uses for TCMP, TSO2, TSOA, +/// TSOC, TSOP and TSOT, and exiftool and mutagen read them that way. +/// CRM (encrypted meta frame, §4.20) has no v2.3 frame: v2.3 encrypts a frame with a header flag instead +/// (§3.3.1). It, experimental IDs and undeclared IDs have no entry. The frame walk steps over them by their size, +/// as §3 says a reader may ("a size descriptor that allows software to skip unknown frames"), so they are not +/// written back. +/// +internal static class Id3v22FrameIds +{ + static readonly Dictionary ToV23 = new (StringComparer.Ordinal) { + // §4.1 to §4.22, in that order. + { "UFI", "UFID" }, + { "TT1", "TIT1" }, + { "TT2", "TIT2" }, + { "TT3", "TIT3" }, + { "TP1", "TPE1" }, + { "TP2", "TPE2" }, + { "TP3", "TPE3" }, + { "TP4", "TPE4" }, + { "TCM", "TCOM" }, + { "TXT", "TEXT" }, + { "TLA", "TLAN" }, + { "TCO", "TCON" }, + { "TAL", "TALB" }, + { "TPA", "TPOS" }, + { "TRK", "TRCK" }, + { "TRC", "TSRC" }, + { "TYE", "TYER" }, + { "TDA", "TDAT" }, + { "TIM", "TIME" }, + { "TRD", "TRDA" }, + { "TMT", "TMED" }, + { "TFT", "TFLT" }, + { "TBP", "TBPM" }, + { "TCR", "TCOP" }, + { "TPB", "TPUB" }, + { "TEN", "TENC" }, + { "TSS", "TSSE" }, + { "TOF", "TOFN" }, + { "TLE", "TLEN" }, + { "TSI", "TSIZ" }, + { "TDY", "TDLY" }, + { "TKE", "TKEY" }, + { "TOT", "TOAL" }, + { "TOA", "TOPE" }, + { "TOL", "TOLY" }, + { "TOR", "TORY" }, + { "TXX", "TXXX" }, + { "WAF", "WOAF" }, + { "WAR", "WOAR" }, + { "WAS", "WOAS" }, + { "WCM", "WCOM" }, + { "WCP", "WCOP" }, + { "WPB", "WPUB" }, + { "WXX", "WXXX" }, + { "IPL", "IPLS" }, + { "MCI", "MCDI" }, + { "ETC", "ETCO" }, + { "MLL", "MLLT" }, + { "STC", "SYTC" }, + { "ULT", "USLT" }, + { "SLT", "SYLT" }, + { "COM", "COMM" }, + { "RVA", "RVAD" }, + { "EQU", "EQUA" }, + { "REV", "RVRB" }, + { "PIC", "APIC" }, + { "GEO", "GEOB" }, + { "CNT", "PCNT" }, + { "POP", "POPM" }, + { "BUF", "RBUF" }, + { "CRA", "AENC" }, + { "LNK", "LINK" }, + // Apple's IDs for frames ID3v2.2 does not have. + { "TCP", "TCMP" }, + { "TS2", "TSO2" }, + { "TSA", "TSOA" }, + { "TSC", "TSOC" }, + { "TSP", "TSOP" }, + { "TST", "TSOT" }, + }; + + /// Gets the v2.3 ID of a v2.2 frame, or false when it has none. + public static bool TryGetV23Id (string v22Id, out string v23Id) + { + if (ToV23.TryGetValue (v22Id, out var mapped)) { + v23Id = mapped; + return true; + } + + v23Id = ""; + return false; + } +} diff --git a/src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.FrameWalk.cs b/src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.FrameWalk.cs index 28a54b61..dac0c9d9 100644 --- a/src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.FrameWalk.cs +++ b/src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.FrameWalk.cs @@ -22,7 +22,13 @@ internal enum FrameStepKind Empty, /// A frame of bytes after its header. - Frame + Frame, + + /// + /// A v2.2 frame of bytes with no v2.3 ID (). It is + /// not read, and the next frame starts after it. + /// + Unmapped } internal readonly struct FrameStep @@ -36,7 +42,7 @@ public FrameStep (FrameStepKind kind, string id, int size) public FrameStepKind Kind { get; } - /// The frame ID; a v2.2 ID is mapped to its v2.3 equivalent. + /// The frame ID; a v2.2 ID is mapped to its v2.3 equivalent, or kept when it has none. public string Id { get; } public int Size { get; } @@ -76,8 +82,8 @@ internal static FrameStep NextFrame (ReadOnlySpan head, int remaining, byt int size; if (version == 2) { id = GetFrameIdV22 (head); - if (string.IsNullOrEmpty (id) || id[id.Length - 1] == '?') - return FrameStep.Stop; // Unknown v2.2 frame + if (string.IsNullOrEmpty (id)) + return FrameStep.Stop; size = GetFrameSizeV22 (head.Slice (3, 3)); } else { id = GetFrameId (head); @@ -103,6 +109,6 @@ internal static FrameStep NextFrame (ReadOnlySpan head, int remaining, byt return new FrameStep (FrameStepKind.Empty, id, 0); if (size < 0 || size > remaining - headerSize) return FrameStep.Stop; - return new FrameStep (FrameStepKind.Frame, id, size); + return new FrameStep (id.Length == 3 ? FrameStepKind.Unmapped : FrameStepKind.Frame, id, size); } } diff --git a/src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.cs b/src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.cs index b06cffc7..e6595c30 100644 --- a/src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.cs +++ b/src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.cs @@ -75,56 +75,6 @@ public sealed partial class Id3v2Tag : Tag const int FrameHeaderSizeV22 = 6; // v2.2: 3-byte ID + 3-byte size (no flags) const int DefaultPaddingSize = 1024; - /// - /// Maps ID3v2.2 3-character frame IDs to ID3v2.3/2.4 4-character equivalents. - /// - static readonly Dictionary V22FrameIdMap = new (StringComparer.Ordinal) { - // Text frames - { "TT2", "TIT2" }, // Title - { "TP1", "TPE1" }, // Artist - { "TP2", "TPE2" }, // Album artist - { "TP3", "TPE3" }, // Conductor - { "TP4", "TPE4" }, // Remixer - { "TAL", "TALB" }, // Album - { "TYE", "TYER" }, // Year (mapped to TYER, not TDRC for simplicity) - { "TRK", "TRCK" }, // Track - { "TPA", "TPOS" }, // Disc number - { "TCO", "TCON" }, // Genre - { "TCM", "TCOM" }, // Composer - { "TEN", "TENC" }, // Encoded by - { "TSS", "TSSE" }, // Encoder settings - { "TT1", "TIT1" }, // Grouping - { "TT3", "TIT3" }, // Subtitle - { "TKE", "TKEY" }, // Initial key - { "TBP", "TBPM" }, // BPM - { "TLA", "TLAN" }, // Language - { "TMT", "TMED" }, // Media type - { "TCR", "TCOP" }, // Copyright - { "TPB", "TPUB" }, // Publisher - { "TOR", "TORY" }, // Original release year - { "TOT", "TOAL" }, // Original album - { "TOA", "TOPE" }, // Original artist - { "TOL", "TOLY" }, // Original lyricist - { "TXX", "TXXX" }, // User text - // Picture frame - { "PIC", "APIC" }, // Attached picture - // Comment frame - { "COM", "COMM" }, // Comment - // Lyrics frame - { "ULT", "USLT" }, // Unsynchronized lyrics - // Unique file ID - { "UFI", "UFID" }, // Unique file identifier - // URL frames - { "WAR", "WOAR" }, // Official artist URL - { "WAS", "WOAS" }, // Official audio source URL - { "WCM", "WCOM" }, // Commercial URL - { "WCP", "WCOP" }, // Copyright URL - { "WPB", "WPUB" }, // Publisher URL - { "WXX", "WXXX" }, // User URL - // Involved people - { "IPL", "IPLS" }, // Involved people list - }; - readonly List _frames = new (16); readonly List _pictures = new (2); readonly List _comments = new (2); @@ -138,6 +88,9 @@ public sealed partial class Id3v2Tag : Tag readonly List _syncLyricsFrames = new (2); readonly List _generalObjectFrames = new (2); readonly List _privateFrames = new (4); + + // Frames no branch of the read handles, written back on save (#207). + readonly List _unreadFrames = []; readonly List _chapterFrames = new (8); readonly List _tableOfContentsFrames = new (2); @@ -146,8 +99,16 @@ public sealed partial class Id3v2Tag : Tag bool _performersRoleCacheValid; /// - /// Gets the ID3v2 version (2, 3, or 4). + /// Gets the ID3v2 version the tag was read as or created with (2, 3, or 4). /// + /// + /// A version 2 tag is written as ID3v2.3: this library writes 4-character frame IDs only, and holds each + /// ID3v2.2 frame under its v2.3 ID. still reports 2 after a save; reading the saved + /// file reports 3. A frame this library does not read, or cannot parse, is written back as it was stored, flags + /// included, when the tag is saved in the version it was read in, and a v2.2 one under its v2.3 ID (UnreadFrame). + /// A v2.2 frame with no v2.3 ID (CRM, experimental IDs) is not written back, nor is a v2.2 LNK or a + /// v2.2 PIC that cannot be parsed. + /// public int Version { get; } /// @@ -174,6 +135,7 @@ public override IPicture[] Pictures { get => [.. _pictures]; set { _pictures.Clear (); + DropUnread ("APIC"); if (value is not null) { foreach (var pic in value) { if (pic is PictureFrame frame) @@ -325,6 +287,7 @@ public byte? Rating { set { if (value is null) { _popularimeterFrames.Clear (); + DropUnread ("POPM"); return; } if (_popularimeterFrames.Count == 0) @@ -456,17 +419,18 @@ public void SetPopularimeter (string email, byte rating, ulong playCount = 0) public void SetUrl (string frameId, string? url) #pragma warning restore CA1054 { + DropUnread (frameId); for (var i = 0; i < _urlFrames.Count; i++) { if (_urlFrames[i].Id == frameId) { - if (url is null) + if (string.IsNullOrEmpty (url)) _urlFrames.RemoveAt (i); else - _urlFrames[i].Url = url; + _urlFrames[i].Url = url!; return; } } - if (url is not null) - _urlFrames.Add (new UrlFrame (frameId, url)); + if (!string.IsNullOrEmpty (url)) + _urlFrames.Add (new UrlFrame (frameId, url!)); } /// @@ -1217,6 +1181,7 @@ public void RemoveInvolvedPeopleFrames (string? frameId = null) _involvedPeopleFrames.Clear (); else _involvedPeopleFrames.RemoveAll (f => f.Id == frameId); + _unreadFrames.RemoveAll (f => frameId is null ? f.Id is "TIPL" or "TMCL" or "IPLS" : f.Id == frameId); InvalidatePerformersRoleCache (); } @@ -1250,6 +1215,138 @@ public Id3v2Tag (Id3v2Version version = Id3v2Version.V24) Version = version; } + /// + /// Reads a frame of an ID this library reads into its list, and returns whether it did: false for an ID no branch + /// reads, and for a frame its branch rejects (a 1-byte APIC, a POPM with no terminator, an empty TPE1, a TALB with + /// an invalid encoding byte). The caller keeps either as stored (). + /// + bool ReadFrame (string frameId, ReadOnlySpan content, Id3v2Version version) + { + // Handle text frames (T***) - exclude TXXX (user text) and TIPL/TMCL (involved people) + // Also handle Apple proprietary text frames: MVNM (movement name), MVIN (movement index/total) + if ((frameId[0] == 'T' && frameId != "TXXX" && frameId != "TIPL" && frameId != "TMCL") || + frameId == "MVNM" || frameId == "MVIN") { + var frameResult = TextFrame.Read (frameId, content, version); + if (frameResult.IsSuccess) + _frames.Add (frameResult.Frame!); + return frameResult.IsSuccess; + } + + // Handle picture frames (APIC) + if (frameId == "APIC") { + var pictureResult = PictureFrame.Read (content, version); + if (pictureResult.IsSuccess) + _pictures.Add (pictureResult.Frame!); + return pictureResult.IsSuccess; + } + + // Handle comment frames (COMM) + if (frameId == "COMM") { + var commentResult = CommentFrame.Read (content, version); + if (commentResult.IsSuccess) + _comments.Add (commentResult.Frame!); + return commentResult.IsSuccess; + } + + // Handle user-defined text frames (TXXX) + if (frameId == "TXXX") { + var userTextResult = UserTextFrame.Read (content, version); + if (userTextResult.IsSuccess) + _userTextFrames.Add (userTextResult.Frame!); + return userTextResult.IsSuccess; + } + + // Handle lyrics frames (USLT) + if (frameId == "USLT") { + var lyricsResult = LyricsFrame.Read (content, version); + if (lyricsResult.IsSuccess) + _lyricsFrames.Add (lyricsResult.Frame!); + return lyricsResult.IsSuccess; + } + + // Handle unique file identifier frames (UFID) + if (frameId == "UFID") { + var ufidResult = UniqueFileIdFrame.Read (content, version); + if (ufidResult.IsSuccess) + _uniqueFileIdFrames.Add (ufidResult.Frame!); + return ufidResult.IsSuccess; + } + + // Handle involved people frames (TIPL, TMCL, IPLS) + if (frameId is "TIPL" or "TMCL" or "IPLS") { + var involvedResult = InvolvedPeopleFrame.Read (frameId, content, version); + if (involvedResult.IsSuccess) + _involvedPeopleFrames.Add (involvedResult.Frame!); + return involvedResult.IsSuccess; + } + + // Handle popularimeter frames (POPM) + if (frameId == "POPM") { + var popmResult = PopularimeterFrame.Read (content, version); + if (popmResult.IsSuccess) + _popularimeterFrames.Add (popmResult.Frame!); + return popmResult.IsSuccess; + } + + // Handle user URL frames (WXXX) + if (frameId == "WXXX") { + var wxxxResult = UserUrlFrame.Read (content, version); + if (wxxxResult.IsSuccess) + _userUrlFrames.Add (wxxxResult.Frame!); + return wxxxResult.IsSuccess; + } + + // Handle standard URL frames (W*** except WXXX) + if (UrlFrame.IsUrlFrameId (frameId)) { + var urlResult = UrlFrame.Read (frameId, content, version); + if (urlResult.IsSuccess) + _urlFrames.Add (urlResult.Frame!); + return urlResult.IsSuccess; + } + + // Handle synchronized lyrics frames (SYLT) + if (frameId == "SYLT") { + var syltResult = SyncLyricsFrame.Read (content, version); + if (syltResult.IsSuccess) + _syncLyricsFrames.Add (syltResult.Frame!); + return syltResult.IsSuccess; + } + + // Handle general encapsulated object frames (GEOB) + if (frameId == "GEOB") { + var geobResult = GeneralObjectFrame.Read (content, version); + if (geobResult.IsSuccess) + _generalObjectFrames.Add (geobResult.Frame!); + return geobResult.IsSuccess; + } + + // Handle private frames (PRIV) + if (frameId == "PRIV") { + var privResult = PrivateFrame.Read (content, version); + if (privResult.IsSuccess) + _privateFrames.Add (privResult.Frame!); + return privResult.IsSuccess; + } + + // Handle chapter frames (CHAP) + if (frameId == "CHAP") { + var chapResult = ChapterFrame.Read (content, version); + if (chapResult.IsSuccess) + _chapterFrames.Add (chapResult.Frame!); + return chapResult.IsSuccess; + } + + // Handle table of contents frames (CTOC) + if (frameId == "CTOC") { + var ctocResult = TableOfContentsFrame.Read (content, version); + if (ctocResult.IsSuccess) + _tableOfContentsFrames.Add (ctocResult.Frame!); + return ctocResult.IsSuccess; + } + + return false; + } + /// /// Attempts to read an ID3v2 tag from the provided data. /// @@ -1307,10 +1404,13 @@ public static TagReadResult Read (ReadOnlySpan data) if (step.Kind == FrameStepKind.Stop) break; - if (step.Kind == FrameStepKind.Empty) { - // A size of 0 is illegal, but the next frame starts after this header. - frameData = frameData.Slice (frameHeaderSize); - remaining -= frameHeaderSize; + if (step.Kind != FrameStepKind.Frame) { + // A size of 0 is illegal, but the next frame starts after this header, and the frame is kept as + // stored, as a frame a branch rejects is. A v2.2 frame with no v2.3 ID is stepped over by its size. + if (step.Kind == FrameStepKind.Empty && step.Id.Length == 4) + tag._unreadFrames.Add (new UnreadFrame (step.Id, isV22 ? (byte)0 : frameData[8], isV22 ? (byte)0 : frameData[9], [], header.MajorVersion)); + frameData = frameData.Slice (frameHeaderSize + step.Size); + remaining -= frameHeaderSize + step.Size; continue; } @@ -1330,97 +1430,11 @@ public static TagReadResult Read (ReadOnlySpan data) frameContent = ProcessFrameFlags (frameContent, formatFlags, header.MajorVersion); } - // Handle text frames (T***) - exclude TXXX (user text) and TIPL/TMCL (involved people) - // Also handle Apple proprietary text frames: MVNM (movement name), MVIN (movement index/total) - if ((frameId[0] == 'T' && frameId != "TXXX" && frameId != "TIPL" && frameId != "TMCL") || - frameId == "MVNM" || frameId == "MVIN") { - var frameResult = TextFrame.Read (frameId, frameContent, (Id3v2Version)header.MajorVersion); - if (frameResult.IsSuccess) - tag._frames.Add (frameResult.Frame!); - } - // Handle picture frames (APIC) - else if (frameId == "APIC") { - var pictureResult = PictureFrame.Read (frameContent, (Id3v2Version)header.MajorVersion); - if (pictureResult.IsSuccess) - tag._pictures.Add (pictureResult.Frame!); - } - // Handle comment frames (COMM) - else if (frameId == "COMM") { - var commentResult = CommentFrame.Read (frameContent, (Id3v2Version)header.MajorVersion); - if (commentResult.IsSuccess) - tag._comments.Add (commentResult.Frame!); - } - // Handle user-defined text frames (TXXX) - else if (frameId == "TXXX") { - var userTextResult = UserTextFrame.Read (frameContent, (Id3v2Version)header.MajorVersion); - if (userTextResult.IsSuccess) - tag._userTextFrames.Add (userTextResult.Frame!); - } - // Handle lyrics frames (USLT) - else if (frameId == "USLT") { - var lyricsResult = LyricsFrame.Read (frameContent, (Id3v2Version)header.MajorVersion); - if (lyricsResult.IsSuccess) - tag._lyricsFrames.Add (lyricsResult.Frame!); - } - // Handle unique file identifier frames (UFID) - else if (frameId == "UFID") { - var ufidResult = UniqueFileIdFrame.Read (frameContent, (Id3v2Version)header.MajorVersion); - if (ufidResult.IsSuccess) - tag._uniqueFileIdFrames.Add (ufidResult.Frame!); - } - // Handle involved people frames (TIPL, TMCL, IPLS) - else if (frameId is "TIPL" or "TMCL" or "IPLS") { - var involvedResult = InvolvedPeopleFrame.Read (frameId, frameContent, (Id3v2Version)header.MajorVersion); - if (involvedResult.IsSuccess) - tag._involvedPeopleFrames.Add (involvedResult.Frame!); - } - // Handle popularimeter frames (POPM) - else if (frameId == "POPM") { - var popmResult = PopularimeterFrame.Read (frameContent, (Id3v2Version)header.MajorVersion); - if (popmResult.IsSuccess) - tag._popularimeterFrames.Add (popmResult.Frame!); - } - // Handle user URL frames (WXXX) - else if (frameId == "WXXX") { - var wxxxResult = UserUrlFrame.Read (frameContent, (Id3v2Version)header.MajorVersion); - if (wxxxResult.IsSuccess) - tag._userUrlFrames.Add (wxxxResult.Frame!); - } - // Handle standard URL frames (W*** except WXXX) - else if (UrlFrame.IsUrlFrameId (frameId)) { - var urlResult = UrlFrame.Read (frameId, frameContent, (Id3v2Version)header.MajorVersion); - if (urlResult.IsSuccess) - tag._urlFrames.Add (urlResult.Frame!); - } - // Handle synchronized lyrics frames (SYLT) - else if (frameId == "SYLT") { - var syltResult = SyncLyricsFrame.Read (frameContent, (Id3v2Version)header.MajorVersion); - if (syltResult.IsSuccess) - tag._syncLyricsFrames.Add (syltResult.Frame!); - } - // Handle general encapsulated object frames (GEOB) - else if (frameId == "GEOB") { - var geobResult = GeneralObjectFrame.Read (frameContent, (Id3v2Version)header.MajorVersion); - if (geobResult.IsSuccess) - tag._generalObjectFrames.Add (geobResult.Frame!); - } - // Handle private frames (PRIV) - else if (frameId == "PRIV") { - var privResult = PrivateFrame.Read (frameContent, (Id3v2Version)header.MajorVersion); - if (privResult.IsSuccess) - tag._privateFrames.Add (privResult.Frame!); - } - // Handle chapter frames (CHAP) - else if (frameId == "CHAP") { - var chapResult = ChapterFrame.Read (frameContent, (Id3v2Version)header.MajorVersion); - if (chapResult.IsSuccess) - tag._chapterFrames.Add (chapResult.Frame!); - } - // Handle table of contents frames (CTOC) - else if (frameId == "CTOC") { - var ctocResult = TableOfContentsFrame.Read (frameContent, (Id3v2Version)header.MajorVersion); - if (ctocResult.IsSuccess) - tag._tableOfContentsFrames.Add (ctocResult.Frame!); + // A frame no branch reads, or one its branch rejects, is kept as stored, flags and all, so a save writes it + // back. A rejected frame goes when the tag writes or removes every frame of its ID (DropUnread). + if (!tag.ReadFrame (frameId, frameContent, (Id3v2Version)header.MajorVersion)) { + tag._unreadFrames.Add (new UnreadFrame (frameId, isV22 ? (byte)0 : frameData[8], formatFlags, + frameData.Slice (frameHeaderSize, frameSize).ToArray (), header.MajorVersion)); } // Move to next frame @@ -1529,14 +1543,26 @@ static string FirstTextValue (string text) /// /// The frame ID (e.g., TPE1 for artists). /// - /// A list of values, split by null characters (each value as written, empty values skipped), or by - /// "/" when the text has no null character, in any version (each value trimmed, blank values skipped). - /// The first entry is the same as unless the text was split on "/"; when every - /// value is empty there is no entry and returns "". + /// A list of values, split on U+0000 (each value as written, empty values skipped). A slash is + /// not a separator, and a slash cannot be told from a name that contains one. ffprobe reports one + /// TPE1 AC/DC as a single artist. /// /// - /// ID3v2.4 uses null characters as value separators. ID3v2.3 has no official - /// separator, but "/" is commonly used. This method handles both. + /// The same rule is used for every text frame in ID3v2.2, v2.3 and v2.4, including tags + /// carried by MP3, WAV, AIFF, DSF, DFF, AAC and MPEG program streams: + /// + /// ID3v2.4 text frames hold several strings as a list separated by the encoding's + /// NUL (https://id3.org/id3v2.4.0-frames, §4.2). + /// ID3v2.3 §4.2 (https://id3.org/id3v2.3.0) and ID3v2.2 §4.2 + /// (https://id3.org/id3v2-00) define one string: "If the textstring is followed by a termination + /// ($00 (00)) all the following information should be ignored and not be displayed". This reader + /// reads what follows a NUL as further values instead, as it does for v2.4, so a list written in + /// the v2.4 style survives in an older tag. + /// ID3v2.3 says TPE1, TCOM, TEXT, TOLY and TOPE separate names with "/", as + /// ID3v2.2 does for TP1, TCM, TXT, TOA and TOL. This reader does not apply that. + /// + /// Vorbis, APE, ASF and Matroska store repeated names as separate fields or NUL-separated + /// text, not as a slash-split string. Track and disc numbers still use n/m. /// public IReadOnlyList GetTextFrameValues (string frameId) { @@ -1545,14 +1571,14 @@ public IReadOnlyList GetTextFrameValues (string frameId) if (string.IsNullOrEmpty (text)) return Array.Empty (); - // ID3v2.4 uses null as separator + // NUL is the only multi-value separator (ID3v2.4 §4.2), in every version. A value with no NUL is one value, + // so "AC/DC" stays one performer and "Rock/Pop" stays one genre. "(17)" is still resolved + // by the genre reader, which looks for parentheses rather than a slash. #if NETSTANDARD2_0 if (text!.IndexOf ('\0') >= 0) { #else if (text!.Contains ('\0', StringComparison.Ordinal)) { #endif - // ID3v2.4 §4.2: each NUL-separated string is a value as written. An empty one is skipped, - // as the single-value getter skips it; spaces are kept, as every other reader keeps them. var parts = text.Split ('\0'); var result = new List (parts.Length); for (var i = 0; i < parts.Length; i++) { @@ -1562,25 +1588,7 @@ public IReadOnlyList GetTextFrameValues (string frameId) return result; } - // ID3v2.3 commonly uses "/" as separator (not official but widely used) - // Only split if there are multiple values indicated by "/" -#if NETSTANDARD2_0 - if (text.IndexOf ('/') >= 0) { -#else - if (text.Contains ('/', StringComparison.Ordinal)) { -#endif - var parts = text.Split ('/'); - var result = new List (parts.Length); - for (var i = 0; i < parts.Length; i++) { - var trimmed = parts[i].Trim (); - if (!string.IsNullOrEmpty (trimmed)) - result.Add (trimmed); - } - return result; - } - - // Single value - return new List { text }; + return new List { text! }; } /// @@ -1759,12 +1767,46 @@ void SetTextFrame (string frameId, string? value) { // Remove existing frame _frames.RemoveAll (f => f.Id == frameId); + DropUnread (frameId); // Add new frame if value is not empty if (!string.IsNullOrEmpty (value)) _frames.Add (new TextFrame (frameId, value!, TextEncodingType.Utf8)); } + /// + /// Drops the frames of kept as stored, for a write or removal of every frame of that ID. + /// For an ID a branch reads, those are the frames it rejected (): a set leaves the one frame + /// written, and a clear leaves none, where the rejected frame would still show in another reader. + /// + void DropUnread (string frameId) => _unreadFrames.RemoveAll (f => f.Id == frameId); + + /// + /// Drops the TXXX frames kept as stored whose description is ignoring case, for a + /// write or removal of that field, and returns how many went. A rejected frame's description is the text after its + /// encoding byte (see ). An empty body or an unknown encoding names no field. (WXXX needs no such rule: its reader rejects only a body with nothing after + /// the encoding byte or an unknown encoding, which name no field either.) + /// + int DropUnreadDescribed (string frameId, string description) => + _unreadFrames.RemoveAll (f => f.Id == frameId && string.Equals (UnreadDescription (f), description, StringComparison.OrdinalIgnoreCase)); + + // The TXXX reader rejects a frame only when it is too short, has an unknown encoding, or has no terminator after + // its description, so a rejected frame with a known encoding is all description. + static string? UnreadDescription (UnreadFrame frame) + { + var body = frame.Body; + if (body.Length == 0) + return null; + var field = body.AsSpan (1).ToArray (); + return (TextEncodingType)body[0] switch { + TextEncodingType.Latin1 => Polyfills.Latin1.GetString (field), + TextEncodingType.Utf8 => System.Text.Encoding.UTF8.GetString (field), + TextEncodingType.Utf16BE => System.Text.Encoding.BigEndianUnicode.GetString (field), + TextEncodingType.Utf16WithBom => Utf16Text.Decode (field), + _ => null, + }; + } + /// /// Adds a picture frame to the tag. /// @@ -1826,6 +1868,7 @@ public void SetPicture (Core.PictureType pictureType, PictureFrame? picture) public void RemoveAllPictures () { _pictures.Clear (); + DropUnread ("APIC"); } /// @@ -1834,6 +1877,10 @@ public void RemoveAllPictures () /// /// Renders the tag to binary data with specified padding. /// + /// + /// The header and frames are ID3v2.4 for a version 4 tag and ID3v2.3 otherwise, including a tag read as + /// ID3v2.2 (see ). The tag is written with no unsynchronisation and no compression flag. + /// /// The amount of padding to include. /// If true and version is 2.4, includes a footer. /// The rendered tag data. @@ -1977,6 +2024,18 @@ public BinaryData Render (int paddingSize, bool withFooter = false) framesSize += frameHeader.Length + content.Length; } + // Frames this library does not read, as they were stored (UnreadFrame.FitsVersion). + for (var i = 0; i < _unreadFrames.Count; i++) { + var unread = _unreadFrames[i]; + if (!unread.FitsVersion (WrittenVersion)) + continue; + var frameHeader = RenderFrameHeader (unread.Id, unread.Body.Length, + unread.Version == WrittenVersion ? unread.Status : (byte)0, unread.Version == WrittenVersion ? unread.Format : (byte)0); + frameDataList.Add (frameHeader); + frameDataList.Add (new BinaryData (unread.Body)); + framesSize += frameHeader.Length + unread.Body.Length; + } + var totalSize = framesSize + paddingSize; // Footer is only valid for ID3v2.4 @@ -1985,7 +2044,7 @@ public BinaryData Render (int paddingSize, bool withFooter = false) // Render header with optional footer flag var flags = includeFooter ? Id3v2HeaderFlags.Footer : Id3v2HeaderFlags.None; var header = new Id3v2Header ( - (byte)Version, + WrittenVersion, 0, flags, (uint)totalSize); @@ -2008,7 +2067,14 @@ public BinaryData Render (int paddingSize, bool withFooter = false) return builder.ToBinaryData (); } - BinaryData RenderFrameHeader (string frameId, int contentSize) + /// + /// The major version writes: , except that a v2.2 tag is + /// written as v2.3. This library writes 4-character frame IDs only (ID3v2.3 §3.3), and every ID3v2.2 frame it + /// reads has a v2.3 frame with the same body, so a v2.2 header over those frames would be unreadable. + /// + byte WrittenVersion => Version == 2 ? (byte)3 : (byte)Version; + + BinaryData RenderFrameHeader (string frameId, int contentSize, byte status = 0, byte format = 0) { // Always render in v2.3/v2.4 format (10-byte headers) using var builder = new BinaryDataBuilder (FrameHeaderSizeV23); @@ -2023,8 +2089,9 @@ BinaryData RenderFrameHeader (string frameId, int contentSize) else builder.AddUInt32BE ((uint)contentSize); - // Flags (2 bytes, zeros) - builder.AddUInt16BE (0); + // Flags: status, then format (zero for every frame this library renders itself) + builder.Add (status); + builder.Add (format); return builder.ToBinaryData (); } @@ -2101,8 +2168,10 @@ static bool IsToolPrivateComment (string? description) => /// void SetComment (string? value) { - // Remove existing comments with empty description + // Remove existing comments with empty description, and a COMM frame that could not be read, whose + // description is unknown: the comment written, or cleared, is the one comment shown. _comments.RemoveAll (c => string.IsNullOrEmpty (c.Description)); + DropUnread ("COMM"); // Add new comment if value is not empty if (!string.IsNullOrEmpty (value)) @@ -2134,6 +2203,8 @@ public void RemoveComments (string? language = null, string? description = null) _comments.RemoveAll (c => (language is null || c.Language == language) && (description is null || c.Description == description)); + if (language is null && description is null) + DropUnread ("COMM"); } /// @@ -2180,6 +2251,7 @@ public void SetUserText (string description, string? value) // Remove existing frame with this description _userTextFrames.RemoveAll (f => string.Equals (f.Description, description, StringComparison.OrdinalIgnoreCase)); + DropUnreadDescribed ("TXXX", description); // Add new frame if value is not empty if (!string.IsNullOrEmpty (value)) @@ -2209,6 +2281,7 @@ public void RemoveUserTextFrames (string description) { _userTextFrames.RemoveAll (f => string.Equals (f.Description, description, StringComparison.OrdinalIgnoreCase)); + DropUnreadDescribed ("TXXX", description); } /// @@ -2257,6 +2330,7 @@ public override bool SetCustomField (string name, params string[] values) var at = _userTextFrames.FindIndex (f => string.Equals (f.Description, name, StringComparison.OrdinalIgnoreCase)); _userTextFrames.RemoveAll (f => string.Equals (f.Description, name, StringComparison.OrdinalIgnoreCase)); + DropUnreadDescribed ("TXXX", name); if (kept.Count == 0) return true; @@ -2274,7 +2348,8 @@ public override bool RemoveCustomField (string name) CustomFieldValues.ThrowIfNull (name); if (!CustomFieldValues.IsUsableName (name)) return false; - return _userTextFrames.RemoveAll (f => string.Equals (f.Description, name, StringComparison.OrdinalIgnoreCase)) > 0; + var dropped = DropUnreadDescribed ("TXXX", name); + return _userTextFrames.RemoveAll (f => string.Equals (f.Description, name, StringComparison.OrdinalIgnoreCase)) + dropped > 0; } System.Collections.IList[]? _frameLists; @@ -2286,7 +2361,7 @@ public override bool RemoveCustomField (string name) System.Collections.IList[] FrameLists => _frameLists ??= [ _frames, _pictures, _comments, _userTextFrames, _lyricsFrames, _uniqueFileIdFrames, _involvedPeopleFrames, _popularimeterFrames, _urlFrames, _userUrlFrames, _syncLyricsFrames, - _generalObjectFrames, _privateFrames, _chapterFrames, _tableOfContentsFrames, + _generalObjectFrames, _privateFrames, _chapterFrames, _tableOfContentsFrames, _unreadFrames, ]; /// @@ -2317,8 +2392,9 @@ public override bool RemoveCustomField (string name) /// void SetLyrics (string? value) { - // Remove existing lyrics with empty description + // Remove existing lyrics with empty description, and a USLT frame that could not be read. _lyricsFrames.RemoveAll (l => string.IsNullOrEmpty (l.Description)); + DropUnread ("USLT"); // Add new lyrics if value is not empty if (!string.IsNullOrEmpty (value)) @@ -2350,6 +2426,8 @@ public void RemoveLyrics (string? language = null, string? description = null) _lyricsFrames.RemoveAll (l => (language is null || l.Language == language) && (description is null || l.Description == description)); + if (language is null && description is null) + DropUnread ("USLT"); } /// @@ -2404,11 +2482,14 @@ public void AddUniqueFileId (UniqueFileIdFrame frame) /// The owner identifier to match (case-insensitive), or null to remove all. public void RemoveUniqueFileIds (string? owner = null) { - if (owner is null) + if (owner is null) { _uniqueFileIdFrames.Clear (); - else - _uniqueFileIdFrames.RemoveAll (f => - string.Equals (f.Owner, owner, StringComparison.OrdinalIgnoreCase)); + DropUnread ("UFID"); + return; + } + + _uniqueFileIdFrames.RemoveAll (f => + string.Equals (f.Owner, owner, StringComparison.OrdinalIgnoreCase)); } /// @@ -2450,12 +2531,15 @@ public void AddSyncLyrics (SyncLyricsFrame frame) /// The description to match (null matches any). public void RemoveSyncLyrics (string? language = null, string? description = null) { - if (language is null && description is null) + if (language is null && description is null) { _syncLyricsFrames.Clear (); - else - _syncLyricsFrames.RemoveAll (f => - (language is null || f.Language == language) && - (description is null || f.Description == description)); + DropUnread ("SYLT"); + return; + } + + _syncLyricsFrames.RemoveAll (f => + (language is null || f.Language == language) && + (description is null || f.Description == description)); } /// @@ -2494,11 +2578,14 @@ public void AddGeneralObject (GeneralObjectFrame frame) /// The description to match (case-insensitive), or null to remove all. public void RemoveGeneralObjects (string? description = null) { - if (description is null) + if (description is null) { _generalObjectFrames.Clear (); - else - _generalObjectFrames.RemoveAll (f => - string.Equals (f.Description, description, StringComparison.OrdinalIgnoreCase)); + DropUnread ("GEOB"); + return; + } + + _generalObjectFrames.RemoveAll (f => + string.Equals (f.Description, description, StringComparison.OrdinalIgnoreCase)); } /// @@ -2537,11 +2624,14 @@ public void AddPrivateFrame (PrivateFrame frame) /// The owner ID to match (case-insensitive), or null to remove all. public void RemovePrivateFrames (string? ownerId = null) { - if (ownerId is null) + if (ownerId is null) { _privateFrames.Clear (); - else - _privateFrames.RemoveAll (f => - string.Equals (f.OwnerId, ownerId, StringComparison.OrdinalIgnoreCase)); + DropUnread ("PRIV"); + return; + } + + _privateFrames.RemoveAll (f => + string.Equals (f.OwnerId, ownerId, StringComparison.OrdinalIgnoreCase)); } /// @@ -2579,10 +2669,13 @@ public void AddChapter (ChapterFrame frame) /// The element ID to match (case-sensitive), or null to remove all chapters. public void RemoveChapters (string? elementId = null) { - if (elementId is null) + if (elementId is null) { _chapterFrames.Clear (); - else - _chapterFrames.RemoveAll (f => f.ElementId == elementId); + DropUnread ("CHAP"); + return; + } + + _chapterFrames.RemoveAll (f => f.ElementId == elementId); } /// @@ -2638,10 +2731,13 @@ public void AddTableOfContents (TableOfContentsFrame frame) /// The element ID to match (case-sensitive), or null to remove all. public void RemoveTableOfContents (string? elementId = null) { - if (elementId is null) + if (elementId is null) { _tableOfContentsFrames.Clear (); - else - _tableOfContentsFrames.RemoveAll (f => f.ElementId == elementId); + DropUnread ("CTOC"); + return; + } + + _tableOfContentsFrames.RemoveAll (f => f.ElementId == elementId); } static string GetFrameId (ReadOnlySpan data) @@ -2726,8 +2822,8 @@ static string GetFrameIdV22 (ReadOnlySpan data) var v22Id = System.Text.Encoding.ASCII.GetString (data.Slice (0, 3)); - // Map to v2.3/2.4 equivalent if known, otherwise return with padding - return V22FrameIdMap.TryGetValue (v22Id, out var mapped) ? mapped : v22Id + "?"; + // The v2.3 ID, or the 3-character ID of a frame that has none. + return Id3v22FrameIds.TryGetV23Id (v22Id, out var mapped) ? mapped : v22Id; } /// diff --git a/src/TagLibSharp2/Id3/Id3v2/Id3v2Version.cs b/src/TagLibSharp2/Id3/Id3v2/Id3v2Version.cs index 7e14c655..e0d9ea9b 100644 --- a/src/TagLibSharp2/Id3/Id3v2/Id3v2Version.cs +++ b/src/TagLibSharp2/Id3/Id3v2/Id3v2Version.cs @@ -12,7 +12,7 @@ namespace TagLibSharp2.Id3.Id3v2; public enum Id3v2Version { /// - /// ID3v2.2 - Uses 3-character frame IDs. + /// ID3v2.2 - Uses 3-character frame IDs. Read only: a tag of this version is written as ID3v2.3. /// V22 = 2, diff --git a/src/TagLibSharp2/Id3/Id3v2/UnreadFrame.cs b/src/TagLibSharp2/Id3/Id3v2/UnreadFrame.cs new file mode 100644 index 00000000..7d9a5311 --- /dev/null +++ b/src/TagLibSharp2/Id3/Id3v2/UnreadFrame.cs @@ -0,0 +1,22 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +namespace TagLibSharp2.Id3.Id3v2; + +/// +/// A frame this library does not read, or one of an ID it reads that its branch rejected, kept as it was stored so +/// that a save writes it back (#207): its ID (the ID3v2.3 one for a v2.2 frame), its status and format flags (none in +/// v2.2), its body as stored (still compressed, encrypted or unsynchronised when its flags say so), and the major +/// version of the tag it was read from. +/// +internal sealed record UnreadFrame (string Id, byte Status, byte Format, byte[] Body, int Version) +{ + /// + /// Whether a tag written as can hold this frame: as stored when the versions + /// match; and from a v2.2 tag written as v2.3, under its v2.3 ID, whose body is the v2.2 one (id3v2-00 §4, + /// id3v2.3.0 §4) except LINK's, which names a 3-character frame in v2.2 and a 4-character one in v2.3, and a + /// rejected PIC's, whose 3-character image format is a MIME type in APIC. + /// + public bool FitsVersion (int writtenVersion) => + Version == writtenVersion || (Version == 2 && writtenVersion == 3 && Id is not ("LINK" or "APIC")); +} diff --git a/src/TagLibSharp2/Image/Exif/XpText.cs b/src/TagLibSharp2/Image/Exif/XpText.cs new file mode 100644 index 00000000..bcd82a14 --- /dev/null +++ b/src/TagLibSharp2/Image/Exif/XpText.cs @@ -0,0 +1,39 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Text; +using TagLibSharp2.Image.Tiff; + +namespace TagLibSharp2.Image.Exif; + +/// +/// Reads a Windows XP text tag (IFD0 0x9C9B-0x9C9F: XPTitle, XPComment, XPAuthor, XPKeywords, XPSubject): a BYTE +/// array of UTF-16LE text, ended by a two-byte NUL, in either TIFF byte order. Windows and exiftool 13.55 write it +/// that way, with no byte order mark (measured); a leading U+FEFF is not part of the text. +/// +static class XpText +{ + /// The text of IFD0's in a classic TIFF, or null when there is none. + public static string? Read (ReadOnlySpan tiff, int tag) + { + if (!TiffReader.TryClassic (tiff, out var reader, out var ifd0) || !reader.TryTable (ifd0, out var count)) + return null; + for (var n = 0; n < count; n++) { + var entry = reader.Entry (ifd0, n); + if (reader.Tag (entry) == tag) + return reader.TryValueBytes (entry, out var value) ? Decode (value) : null; + } + + return null; + } + + // The text ends at the first NUL code unit. + static string? Decode (ReadOnlySpan value) + { + var end = 0; + while (end + 1 < value.Length && (value[end] | value[end + 1]) != 0) + end += 2; + var text = Encoding.Unicode.GetString (value.Slice (0, end).ToArray ()).TrimStart ('\uFEFF'); + return text.Length == 0 ? null : text; + } +} diff --git a/src/TagLibSharp2/Image/ImagePlan.cs b/src/TagLibSharp2/Image/ImagePlan.cs index 34ea6dfc..df1971f4 100644 --- a/src/TagLibSharp2/Image/ImagePlan.cs +++ b/src/TagLibSharp2/Image/ImagePlan.cs @@ -166,6 +166,39 @@ public void Cut (long start, long count) Length -= count; } + /// Inserts new bytes at an output offset. Ranges on either side keep their original-file offsets. + /// Offset in the output, from 0 to . + /// The new bytes. Empty inserts nothing. The array is kept. + public void Insert (long start, byte[] bytes) + { + if (bytes.Length == 0) + return; + if (start < 0 || start > Length) + throw new ArgumentOutOfRangeException (nameof (start)); + + var next = new List (_pieces.Count + 2); + long at = 0; + var inserted = false; + foreach (var piece in _pieces) { + if (!inserted && start < at + piece.Length) { + AddSlice (next, piece, 0, start - at); + AddLiteral (next, bytes); + AddSlice (next, piece, start - at, piece.Length - (start - at)); + inserted = true; + } else { + AddExisting (next, piece); + } + + at += piece.Length; + } + + if (!inserted) + AddLiteral (next, bytes); + _pieces.Clear (); + _pieces.AddRange (next); + Length += bytes.Length; + } + /// Replaces an output span with of the same length. /// Offset in the output. /// Number of bytes replaced. diff --git a/src/TagLibSharp2/Image/ImageRewrite.cs b/src/TagLibSharp2/Image/ImageRewrite.cs index 8eac3d1b..82f6af29 100644 --- a/src/TagLibSharp2/Image/ImageRewrite.cs +++ b/src/TagLibSharp2/Image/ImageRewrite.cs @@ -19,7 +19,8 @@ static class ImageRewrite { var stores = format switch { MediaFormat.Png => ImageStores.Png, - MediaFormat.Gif or MediaFormat.Jpeg => ImageStores.CommentOnly, + MediaFormat.Gif => ImageStores.CommentOnly, + MediaFormat.Jpeg => ImageStores.Jpeg, _ => ImageStores.None }; if (stores == ImageStores.None) diff --git a/src/TagLibSharp2/Image/ImageTag.cs b/src/TagLibSharp2/Image/ImageTag.cs index 584fd36c..9c633257 100644 --- a/src/TagLibSharp2/Image/ImageTag.cs +++ b/src/TagLibSharp2/Image/ImageTag.cs @@ -16,13 +16,16 @@ enum ImageStores Year = 1 << 4, Comment = 1 << 5, Png = Title | Artist | Description | Copyright | Year | Comment, + Jpeg = Title | 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. +/// GIF keeps the comment. JPEG keeps the comment (COM) and a title, stored in XMP +/// dc:title and read from Exif XPTitle when the XMP has none; an edit removes +/// every XPTitle. A field the format does not store reads back as null, and +/// assigning it changes nothing. /// sealed class ImageTag : Tag { diff --git a/src/TagLibSharp2/Image/Jpeg/JpegRewriter.cs b/src/TagLibSharp2/Image/Jpeg/JpegRewriter.cs index 9d4cf774..3b907214 100644 --- a/src/TagLibSharp2/Image/Jpeg/JpegRewriter.cs +++ b/src/TagLibSharp2/Image/Jpeg/JpegRewriter.cs @@ -10,26 +10,80 @@ namespace TagLibSharp2.Image.Jpeg; /// -/// Reads a JPEG's COM segments and splices a new comment before the scan (ITU-T T.81 §B.2.4.5). Clear also drops -/// the metadata APPn segments of every image a multi-picture index lists, and rewrites the index. Every byte from -/// the scan on is copied as it is. +/// Reads a JPEG's COM segments and title, and splices a new comment before the scan (ITU-T T.81 §B.2.4.5). The +/// title lives in XMP dc:title (XMP Part 1 §8.2.2.4), in the first standard XMP APP1 (XMP Part 3 §1.1.3) or a +/// new one; an edit of either field also updates its copies in Exif and XMP. Clear also drops the metadata APPn +/// segments of every image a multi-picture index lists, and rewrites the index. Every byte from the scan on is +/// copied as it is. /// static class JpegRewriter { const int MaxSegment = 65535; internal const string SpliceError = "The JPEG marker list before the scan is truncated or malformed, so the comment cannot be spliced in."; + /// + /// Reads the primary image's text in one walk of its segments before the scan: the comment from every COM + /// segment, and the title from the first XMP APP1 (dc:title), else from IFD0 XPTitle of the first Exif + /// APP1. XMP wins, as exiftool's Title, exiv2, ImageIO and TagLib# show it; Windows shows XPTitle first (System.Title + /// photo metadata policy), and after a title edit there is none. A marker list that is cut short or broken has no comment; the title is read from the segments before + /// the break. + /// public static void Read (ReadOnlySpan data, ImageTag tag) { - if (TryComment (data, out var text)) - tag.ReadField (ImageStores.Comment, text); + if (!IsSoi (data)) + return; + var comment = new List (); + ReadOnlySpan exif = default; + var sawExif = false; + string? xmp = null; + string? spaced = null; + var whole = true; + var i = 2; + while (i < data.Length) { + if (!TryMarker (data, ref i, out var marker)) { + whole = false; + break; + } + + if (marker is 0x01 or (>= 0xD0 and <= 0xD8)) + continue; + if (marker == 0xD9) + break; + if (!TryLength (data, i, out var length)) { + whole = false; + break; + } + + if (marker == 0xDA) + break; + var payload = data.Slice (i + 2, length - 2); + if (marker == 0xFE) + comment.AddRange (payload.ToArray ()); + else if (marker == 0xE1 && !sawExif && payload.StartsWith ("Exif\0\0"u8)) { + exif = payload.Slice (6); + sawExif = true; + } else if (marker == 0xE1 && TryXmpSignature (payload, out var signature)) { + if (signature == StandardXmp && xmp is null) + xmp = Encoding.UTF8.GetString (payload.Slice (signature)); + else if (signature != StandardXmp && spaced is null) + spaced = Encoding.UTF8.GetString (payload.Slice (signature)); + } + i += length; + } + + if (whole && comment.Count > 0) + tag.ReadField (ImageStores.Comment, Encoding.UTF8.GetString (comment.ToArray ())); + // exiftool reads a packet whose signature has a space only when the file has no standard one. + var packet = xmp ?? spaced; + var title = MirrorFields.Of (ImageStores.Title); + tag.ReadField (ImageStores.Title, (packet is null ? null : XmpValues.Read (packet, title)) ?? XpText.Read (exif, title.Ifd0[0])); } /// The edited file as new pieces and ranges of . public static ImagePlan? Plan (ReadOnlySpan data, ImageTag tag, out string? error) { error = null; - if (!tag.Changed (ImageStores.Comment) && !tag.DropUnmapped) + if (!MirrorFields.AnyChanged (tag) && !tag.DropUnmapped) return null; byte[]? replacement = tag.Changed (ImageStores.Comment) ? tag.Field (ImageStores.Comment) is string comment ? EncodeComment (comment) : [] @@ -39,43 +93,6 @@ public static void Read (ReadOnlySpan data, ImageTag tag) static bool IsSoi (ReadOnlySpan data) => data.Length >= 2 && data[0] == 0xFF && data[1] == 0xD8; - static bool TryComment (ReadOnlySpan data, out string? text) - { - text = null; - if (!IsSoi (data)) - return false; - var collected = new List (); - var i = 2; - while (i < data.Length) { - if (data[i] != 0xFF) - return collected.Count > 0; - while (i < data.Length && data[i] == 0xFF) - i++; - if (i >= data.Length) - return false; - var marker = data[i++]; - if (marker is 0x01 or (>= 0xD0 and <= 0xD9)) { - if (marker == 0xD9) - break; - continue; - } - - if (i + 1 >= data.Length) - return false; - var length = Endian.U16 (data, i, le: false); - if (length < 2 || i + length > data.Length) - return false; - if (marker == 0xDA) - break; - if (marker == 0xFE) - collected.AddRange (data.Slice (i + 2, length - 2).ToArray ()); - i += length; - } - - text = collected.Count == 0 ? null : Encoding.UTF8.GetString (collected.ToArray ()); - return true; - } - static ImagePlan? TryRewrite (ReadOnlySpan data, ImageTag tag, byte[]? comment, out string? error) { error = null; @@ -99,8 +116,9 @@ static bool TryComment (ReadOnlySpan data, out string? text) // A version-65536 Apple gain map takes its headroom from the primary's maker note, so the later images are // read first to know whether the primary keeps those two values (AppleHeadroom). - var options = new ImageOptions (comment, dropMetadata, Mirrors: comment is not null && !dropMetadata, - ItemLengths: dropMetadata ? cleaned.ConvertAll (c => c.Plan.Length) : null, AppleHeadroom: cleaned.Exists (c => c.HeadroomInMakerNote)); + var options = new ImageOptions (comment, dropMetadata, Mirrors: MirrorFields.AnyChanged (tag) && !dropMetadata, + ItemLengths: dropMetadata ? cleaned.ConvertAll (c => c.Plan.Length) : null, AppleHeadroom: cleaned.Exists (c => c.HeadroomInMakerNote), + XmpStores: tag.Changed (ImageStores.Title) && tag.Title is not null ? ImageStores.Title : ImageStores.None); var primaryEnd = images.Count > 0 ? images[0].Start : data.Length; var primary = RewriteImage (data.Slice (0, primaryEnd), tag, options, 0, out error); if (primary is null) @@ -117,7 +135,7 @@ static bool TryCleanLaterImages (ReadOnlySpan data, List images, { error = null; cleaned = []; - var options = new ImageOptions ([], DropMetadata: true, Mirrors: false, ItemLengths: null, AppleHeadroom: false); + var options = new ImageOptions ([], DropMetadata: true, Mirrors: false, ItemLengths: null, AppleHeadroom: false, XmpStores: ImageStores.None); foreach (var image in images) { if (RewriteImage (data.Slice (image.Start, image.Size), tag, options, image.Start, out _) is not JpegImage clean) { error = $"Image {image.Entry + 1} of the JPEG MPF index cannot be parsed, so its metadata cannot be cleared."; @@ -185,9 +203,10 @@ static bool TryCleanLaterImages (ReadOnlySpan data, List images, } // How one image is rewritten: the comment to add (null keeps the COM segments), whether its metadata is - // dropped (Clear), whether the APP1 copies of a changed comment are updated, the gain-map item lengths to - // write, and whether its first Exif keeps the Apple maker-note headroom. - sealed record ImageOptions (byte[]? Comment, bool DropMetadata, bool Mirrors, IReadOnlyList? ItemLengths, bool AppleHeadroom); + // dropped (Clear), whether the APP1 copies of the changed fields are updated, the gain-map item lengths to + // write, whether its first Exif keeps the Apple maker-note headroom, and the changed fields XMP is the store of + // (the title), which its first XMP packet holds, or a new one when the image has none. + sealed record ImageOptions (byte[]? Comment, bool DropMetadata, bool Mirrors, IReadOnlyList? ItemLengths, bool AppleHeadroom, ImageStores XmpStores); sealed class JpegImage { @@ -287,6 +306,9 @@ sealed class ImageBuilder (ImageTag tag, ImageOptions options, int origin) int _mpfLength; bool _headroomInMakerNote; bool _firstExif = true; + bool _sawXmp; + bool _wroteXmp; + long _xmpAt = -1; int Written => checked((int)_plan.Length); @@ -297,8 +319,12 @@ public bool TryAdd (Segment segment, out string? error) error = null; var marker = segment.Marker; var payload = segment.Payload; - if (options.DropMetadata && marker == 0xE1 && TryClearApp1 (segment)) - return true; + // A new XMP segment goes after the JFIF APP0 and Exif APP1 segments a reader expects first (JFIF 1.02; + // CIPA DC-008 §4.7.2), where exiftool puts one (measured, 13.55). + if (_xmpAt < 0 && marker != 0xE0 && !(marker == 0xE1 && payload.StartsWith ("Exif\0\0"u8))) + _xmpAt = Written; + if (options.DropMetadata && marker == 0xE1 && TryClearApp1 (segment, out error)) + return error is null; if ((options.Comment is not null && marker == 0xFE) || (options.DropMetadata && marker is >= 0xE0 and <= 0xEF && !IsKeptOnClear (marker, payload))) return true; if (marker == 0xE2 && _inMpf < 0 && payload.StartsWith ("MPF\0"u8)) { @@ -307,8 +333,10 @@ public bool TryAdd (Segment segment, out string? error) _mpfLength = payload.Length - 4; } + if (marker == 0xE1 && TryXmpSignature (payload, out var signature) && signature == StandardXmp) + _wroteXmp = true; if (options.Mirrors && marker == 0xE1) { - if (!TryMirrorApp1 (payload, tag, out var edited, out error)) + if (!TryMirrorApp1 (payload, tag, NextXmpStores (payload), out var edited, out error)) return false; if (edited is not null) { AddEdited (segment, edited); @@ -320,17 +348,35 @@ public bool TryAdd (Segment segment, out string? error) return true; } - // Clear keeps only the gain-map XMP an HDR decoder needs (ImageGainMap), and of the first Exif (the one - // readers use) only the Apple maker-note headroom. True when the segment was handled (kept or dropped). - bool TryClearApp1 (Segment segment) + // The fields to add to this XMP packet: only the image's first standard packet holds them. ImageIO and exiv2 + // do not read a packet whose signature has a space (measured), so that one is only a copy. + ImageStores NextXmpStores (ReadOnlySpan payload) + { + if (!TryXmpSignature (payload, out var signature) || signature != StandardXmp || _sawXmp) + return ImageStores.None; + _sawXmp = true; + return options.XmpStores; + } + + // Clear keeps only the gain-map XMP an HDR decoder needs (ImageGainMap), with the fields XMP is the store of + // added, and of the first Exif (the one readers use) only the Apple maker-note headroom. True when the + // segment was handled (kept or dropped), or refused with an error. + bool TryClearApp1 (Segment segment, out string? error) { + error = null; var payload = segment.Payload; if (TryXmpSignature (payload, out var signature)) { var kept = ImageGainMap.KeepForClear (payload.Slice (signature), options.ItemLengths, out var makerNote); if (kept is null || 2 + signature + kept.Length > MaxSegment) return true; _headroomInMakerNote |= makerNote; - AddEdited (segment, SegmentBytes (0xE1, [.. payload.Slice (0, signature), .. kept])); + byte[] keptPayload = [.. payload.Slice (0, signature), .. kept]; + byte[]? edited = null; + var add = NextXmpStores (keptPayload); + if (add != ImageStores.None && !TryMirrorXmp (keptPayload, signature, tag, add, out edited, out error)) + return true; + _wroteXmp |= signature == StandardXmp; + AddEdited (segment, edited ?? SegmentBytes (0xE1, keptPayload)); return true; } @@ -351,11 +397,20 @@ void AddEdited (Segment segment, byte[] replacement) public JpegImage? Finish (ReadOnlySpan data, int rest, out string? error) { + error = null; + var xmpAt = _xmpAt < 0 ? Written : _xmpAt; if (options.Comment is { Length: > 0 }) _plan.Add (options.Comment); + if (options.XmpStores != ImageStores.None && !_wroteXmp) { + if (!TryNewXmp (tag, options.XmpStores, out var xmp, out error)) + return null; + _plan.Insert (xmpAt, xmp); + if (_outMpf >= xmpAt) + _outMpf += xmp.Length; + } + var outRest = Written; _plan.Copy (origin + (long)rest, data.Length - rest); - error = null; return Built (outRest, rest); } @@ -371,17 +426,21 @@ void AddEdited (Segment segment, byte[] replacement) } // "http://ns.adobe.com/xap/1.0/" then NUL (XMP Part 3 §1.1.3), or with a space before the NUL as some writers - // do; exiftool and ImageIO read that packet too. + // do; exiftool reads that packet when the file has no standard one (warning "Non-standard header"), and ImageIO + // and exiv2 do not read it (measured, exiftool 13.55, exiv2 0.28.9, macOS ImageIO). + const int StandardXmp = 29; + static bool TryXmpSignature (ReadOnlySpan payload, out int length) { length = payload.StartsWith ("http://ns.adobe.com/xap/1.0/\0"u8) ? 29 : payload.StartsWith ("http://ns.adobe.com/xap/1.0/ \0"u8) ? 30 : 0; return length > 0; } - // A Comment edit also changes the copies of the comment in APP1: Exif UserComment and XPComment, and XMP - // exif:UserComment. Extended XMP is spread over several segments and keyed by a digest of its content; when - // it may hold the comment, the save is refused rather than leave a stale copy. - static bool TryMirrorApp1 (ReadOnlySpan payload, ImageTag tag, out byte[]? edited, out string? error) + // An edit also changes the changed fields' copies in APP1: in Exif, through the field edit (ExifEditor); in XMP, + // where the property is replaced, removed, or added when the packet is the field's store (XmpMirror). Extended + // XMP is spread over several segments and keyed by a digest of its content; when it may hold a changed field, + // the save is refused rather than leave a stale copy. + static bool TryMirrorApp1 (ReadOnlySpan payload, ImageTag tag, ImageStores add, out byte[]? edited, out string? error) { edited = null; error = null; @@ -390,33 +449,67 @@ static bool TryMirrorApp1 (ReadOnlySpan payload, ImageTag tag, out byte[]? return carrier.TryEdit (payload, tag, out edited, out error); } if (TryXmpSignature (payload, out var signature)) - return TryMirrorXmp (payload, signature, tag, out edited, out error); - if (payload.StartsWith ("http://ns.adobe.com/xmp/extension/\0"u8) && payload.IndexOf ("UserComment"u8) >= 0) { - error = "The JPEG extended XMP holds a UserComment, a copy of Comment that cannot be updated here."; + return TryMirrorXmp (payload, signature, tag, add, out edited, out error); + if (payload.StartsWith ("http://ns.adobe.com/xmp/extension/\0"u8) && ExtendedCopy (payload, tag) is MirrorFields.MirrorField field) { + error = $"The JPEG extended XMP holds a {field.XmpName}, a copy of {field.Name} that cannot be updated here."; return false; } return true; } - static bool TryMirrorXmp (ReadOnlySpan payload, int signature, ImageTag tag, out byte[]? edited, out string? error) + // A changed field whose property name, after a prefix or as an element, is in the extended XMP's bytes. + static MirrorFields.MirrorField? ExtendedCopy (ReadOnlySpan payload, ImageTag tag) + { + foreach (var field in MirrorFields.All) { + if (!tag.Changed (field.Store)) + continue; + var name = Encoding.ASCII.GetBytes (field.XmpName); + if (payload.IndexOf ([(byte)':', .. name]) >= 0 || payload.IndexOf ([(byte)'<', .. name]) >= 0) + return field; + } + + return null; + } + + static bool TryMirrorXmp (ReadOnlySpan payload, int signature, ImageTag tag, ImageStores add, out byte[]? edited, out string? error) { edited = null; var packet = Encoding.UTF8.GetString (payload.Slice (signature)); - if (!XmpMirror.TryUpdate (packet, tag, "JPEG XMP packet", out var updated, out error)) + if (!XmpMirror.TryUpdate (packet, tag, "JPEG XMP packet", out var updated, out error, add)) return false; if (ReferenceEquals (updated, packet)) return true; - var bytes = Encoding.UTF8.GetBytes (updated); - if (2 + signature + bytes.Length > MaxSegment) { - error = "The JPEG XMP packet would no longer fit in one APP1 segment after the comment edit."; + return TryXmpSegment (payload.Slice (0, signature), updated, "The JPEG XMP packet would no longer fit in one APP1 segment after the edit.", out edited, out error); + } + + // The packet an image with no XMP gets: one empty top-level description, which the fields are added to. + const string NewPacket = ""; + + static bool TryNewXmp (ImageTag tag, ImageStores add, out byte[] segment, out string? error) + { + segment = []; + if (!XmpMirror.TryUpdate (NewPacket, tag, "new JPEG XMP packet", out var packet, out error, add)) + return false; + if (!TryXmpSegment ("http://ns.adobe.com/xap/1.0/\0"u8, packet, "A new JPEG XMP packet with the edited fields would not fit in one APP1 segment.", out var built, out error)) + return false; + segment = built!; + return true; + } + + // An APP1 segment of the signature and the packet, or an error when it is past the 16-bit segment length + // (T.81 §B.1.1.4: the length counts itself, so at most 65,533 bytes of payload). + static bool TryXmpSegment (ReadOnlySpan signature, string packet, string tooLong, out byte[]? segment, out string? error) + { + segment = null; + error = null; + var bytes = Encoding.UTF8.GetBytes (packet); + if (2 + signature.Length + bytes.Length > MaxSegment) { + error = tooLong; return false; } - var body = new byte[signature + bytes.Length]; - payload.Slice (0, signature).CopyTo (body); - bytes.CopyTo (body, signature); - edited = SegmentBytes (0xE1, body); + segment = SegmentBytes (0xE1, [.. signature, .. bytes]); return true; } diff --git a/src/TagLibSharp2/Image/MirrorFields.cs b/src/TagLibSharp2/Image/MirrorFields.cs index 33f799dd..9c5d5a2c 100644 --- a/src/TagLibSharp2/Image/MirrorFields.cs +++ b/src/TagLibSharp2/Image/MirrorFields.cs @@ -29,6 +29,8 @@ static class MirrorFields new (ImageStores.Comment, "Comment", ExifNamespace, "UserComment", ordered: false, ifd0: [0x9C9C], exifIfd: [0x9286], text: ["exif:UserComment"]), ]; + internal static MirrorField Of (ImageStores store) => Array.Find (All, field => field.Store == store)!; + internal static bool AnyChanged (ImageTag tag) { foreach (var field in All) { @@ -46,6 +48,9 @@ internal sealed class MirrorField (ImageStores store, string name, string xmpNam public string Name { get; } = name; public string XmpNamespace { get; } = xmpNamespace; public string XmpName { get; } = xmpName; + + /// The prefix a property added to a packet is written with: dc or exif, as XMP Part 1 §8 names them. + public string XmpPrefix => XmpNamespace == DcNamespace ? "dc" : "exif"; public bool Ordered { get; } = ordered; public int[] Ifd0 { get; } = ifd0; public int[] ExifIfd { get; } = exifIfd; diff --git a/src/TagLibSharp2/Image/Tiff/TiffReader.cs b/src/TagLibSharp2/Image/Tiff/TiffReader.cs index 9370afe0..51e53fb3 100644 --- a/src/TagLibSharp2/Image/Tiff/TiffReader.cs +++ b/src/TagLibSharp2/Image/Tiff/TiffReader.cs @@ -214,6 +214,24 @@ public long Next (long table, long count) return (offset, offset + bytes); } + /// + /// The value bytes of a classic entry: in the entry when they fit in 4 bytes, else at its offset. False when the + /// type is not one of TIFF 6.0 §2 types 1-12 or IFD (13), or the value runs past the data. + /// + public bool TryValueBytes (long entry, out ReadOnlySpan value) + { + value = default; + var size = TypeSize (Type (entry)); + if (size == 0) + return false; + var bytes = Count (entry) * size; + var at = bytes <= 4 ? entry + 8 : Value (entry); + if (at < 0 || at > Length || bytes > Length - at) + return false; + value = Data.Slice ((int)at, (int)bytes); + return true; + } + /// /// A SHORT (3) or LONG (4) array that lies wholly in the data (TIFF 6.0 §2). An inline value is the entry's own /// value field. Any other type, a count of zero, or an array that runs past the data is not located. diff --git a/src/TagLibSharp2/Image/Xmp/XmlText.cs b/src/TagLibSharp2/Image/Xmp/XmlText.cs index 4ace2d12..d4724c55 100644 --- a/src/TagLibSharp2/Image/Xmp/XmlText.cs +++ b/src/TagLibSharp2/Image/Xmp/XmlText.cs @@ -82,6 +82,31 @@ public static bool TryAttributeEnd (string text, int from, out int end) public static bool IsXmlSpace (char c) => c is ' ' or '\t' or '\r' or '\n'; + /// + /// Where the XML of a packet is: after a UTF-8 byte order mark, which is not part of the XML, and before the NULs + /// or white space some writers put after the trailer (XMP Part 1 §7.3: the trailer processing instruction ends + /// the packet; ImageIO ends JPEG XMP with a NUL). + /// + public static (int Start, int End) PacketXml (string packet) + { + var start = packet.Length > 0 && packet[0] == '\uFEFF' ? 1 : 0; + var end = packet.Length; + var last = packet.LastIndexOf ('>'); + if (last >= start && last < end - 1 && IsPacketTail (packet, last + 1)) + end = last + 1; + return (start, end); + } + + 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; + } + public static bool IsWellFormed (string packet) { var settings = new XmlReaderSettings { DtdProcessing = DtdProcessing.Prohibit, XmlResolver = null }; diff --git a/src/TagLibSharp2/Image/Xmp/XmpMirror.cs b/src/TagLibSharp2/Image/Xmp/XmpMirror.cs index f28a9820..1385410f 100644 --- a/src/TagLibSharp2/Image/Xmp/XmpMirror.cs +++ b/src/TagLibSharp2/Image/Xmp/XmpMirror.cs @@ -7,8 +7,11 @@ namespace TagLibSharp2.Image.Xmp; /// /// Replaces each changed field's property in an XMP packet, or removes it when the field is null. A property the -/// packet does not hold is not added. The property's own start and end tags (and so any namespace they declare) are -/// kept; only its content changes. Every other character of the packet is kept, in one forward pass. +/// packet does not hold is added only for the fields the caller names (the fields the packet is the store of), to +/// its first top-level rdf:Description. The property's own start and end tags (and so any namespace they +/// declare) are kept; only its content changes. A language alternative is written as one x-default item +/// (XMP Part 1 §7.9): the other languages are dropped, so that no reader shows an old title in its own language +/// after a set. Every other character of the packet is kept, in one forward pass. /// static class XmpMirror { @@ -21,45 +24,47 @@ static class XmpMirror /// 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. + /// The changed fields to add when the packet does not hold them. /// False, with an error, when the packet is not well-formed XML or a value cannot be written as XML. - internal static bool TryUpdate (string packet, ImageTag tag, string carrier, out string updated, out string? error) + internal static bool TryUpdate (string packet, ImageTag tag, string carrier, out string updated, out string? error, ImageStores add = ImageStores.None) { - // A UTF-8 byte order mark before the packet is not part of the XML. - if (packet.Length > 0 && packet[0] == '') - return TryUpdateAfterBom (packet, tag, carrier, out updated, out error); - - // XMP Part 1 §7.3: the packet ends with the trailer processing instruction. Some writers follow it with - // NULs (ImageIO ends JPEG XMP with one) or padding; those bytes are not XML and are copied back as they are. - var last = packet.LastIndexOf ('>'); - if (last >= 0 && last < packet.Length - 1 && IsPacketTail (packet, last + 1)) - return TryUpdateBeforeTail (packet, last + 1, tag, carrier, out updated, out error); - return TrySplice (packet, tag, carrier, out updated, out error); - } + var (start, end) = XmlText.PacketXml (packet); + if (start == 0 && end == packet.Length) + return TrySplice (packet, tag, carrier, add, out updated, out error); - static bool TryUpdateAfterBom (string packet, ImageTag tag, string carrier, out string updated, out string? error) - { + // The byte order mark and the tail are not XML; they are copied back as they are. updated = packet; - if (!TryUpdate (packet.Substring (1), tag, carrier, out var body, out error)) + var xml = packet.Substring (start, end - start); + if (!TrySplice (xml, tag, carrier, add, out var edited, out error)) return false; - updated = body.Length == packet.Length - 1 && string.CompareOrdinal (body, 0, packet, 1, body.Length) == 0 ? packet : "" + body; + if (!string.Equals (edited, xml, StringComparison.Ordinal)) + updated = Join (packet, start, edited, end); return true; } - static bool TryUpdateBeforeTail (string packet, int tail, ImageTag tag, string carrier, out string updated, out string? error) - { - updated = packet; - if (!TryUpdate (packet.Substring (0, tail), tag, carrier, out var head, out error)) - return false; - updated = head.Length == tail && string.CompareOrdinal (head, 0, packet, 0, head.Length) == 0 ? packet : Join (head, packet, tail); - return true; - } + // The packet with its XML between start and end replaced. + static string Join (string packet, int start, string xml, int end) => +#if NETSTANDARD2_0 || NETSTANDARD2_1 + packet.Substring (0, start) + xml + packet.Substring (end); +#else + string.Concat (packet.AsSpan (0, start), xml.AsSpan (), packet.AsSpan (end)); +#endif - static bool TrySplice (string packet, ImageTag tag, string carrier, out string updated, out string? error) + static bool TrySplice (string packet, ImageTag tag, string carrier, ImageStores add, out string updated, out string? error) { updated = packet; var edits = new List (); - if (!XmpProperties.TryFind (packet, tag, carrier, edits, out error)) + var adding = Adding (tag, add); + var target = adding.Count > 0 ? new XmpTarget () : null; + if (!XmpProperties.TryFind (packet, tag, carrier, edits, target, out error)) return false; + adding.RemoveAll (field => edits.Exists (edit => edit.Field == field)); + if (adding.Count > 0) { + if (!TryInsert (packet, tag, carrier, adding, target!, out var insert, out error)) + return false; + edits.Add (insert); + } + if (edits.Count == 0) return true; @@ -69,6 +74,13 @@ static bool TrySplice (string packet, ImageTag tag, string carrier, out string u var written = new HashSet (); var at = 0; foreach (var edit in edits) { + if (edit.Inserted is string inserted) { + Append (builder, packet, at, edit.Start); + Write (builder, inserted); + at = edit.End; + continue; + } + var value = tag.Field (edit.Field.Store); var keep = value is not null && written.Add (edit.Field.Store); if (keep && !XmlText.IsXmlText (value!)) { @@ -89,6 +101,55 @@ static bool TrySplice (string packet, ImageTag tag, string carrier, out string u return true; } + // The changed fields with a value that the caller asks to add. + static List Adding (ImageTag tag, ImageStores add) => + [.. MirrorFields.All.Where (field => (add & field.Store) != 0 && tag.Changed (field.Store) && tag.Field (field.Store) is not null)]; + + // The added properties, as one edit: in the first top-level description, or in a new description at the end of + // rdf:RDF when the packet has none. + static bool TryInsert (string packet, ImageTag tag, string carrier, List fields, XmpTarget target, out XmpEdit insert, out string? error) + { + insert = null!; + error = null; + var spot = target.Description.Located ? target.Description : target.Rdf; + if (!spot.Located) { + var why = XmlText.IsWellFormed (packet) ? "has no rdf:RDF" : "is not well-formed XML"; + error = $"The {carrier} {why}, so {fields[0].Name} cannot be added to it."; + return false; + } + + var text = new StringBuilder (spot.Close.Length > 0 ? ">" : ""); + // A new description names the RDF namespace by a prefix, since rdf:about is an attribute (XML Namespaces 1.0 + // §6.2: the default namespace does not apply to attributes). + var rdfPrefix = spot == target.Description ? spot.RdfPrefix : spot.RdfPrefix is { Length: > 0 } ? spot.RdfPrefix : "rdf"; + var newDescription = spot == target.Rdf ? $"{rdfPrefix}:Description" : null; + if (newDescription is not null) { + var declare = spot.RdfPrefix is { Length: > 0 } ? "" : $" xmlns:rdf=\"{XmpProperties.RdfNamespace}\""; + text.Append ('<').Append (newDescription).Append (declare).Append (' ').Append (rdfPrefix).Append (":about=\"\">"); + } + + foreach (var field in fields) { + var value = tag.Field (field.Store)!; + if (!XmlText.IsXmlText (value)) { + error = $"The new {field.Name} has a character XML cannot store, so it cannot be added to the {carrier}."; + return false; + } + + // A prefix in scope names the namespace. Otherwise the element declares its own (XML Namespaces 1.0 §5.1), + // which also hides an outer binding of the same prefix to another namespace. + var inScope = spot.Prefixes[field.XmpNamespace] is { Length: > 0 } found ? found : null; + var name = (inScope ?? field.XmpPrefix) + ":" + field.XmpName; + var declare = inScope is null ? $" xmlns:{field.XmpPrefix}=\"{field.XmpNamespace}\"" : ""; + text.Append ('<').Append (name).Append (declare).Append ('>').Append (PropertyContent (field, rdfPrefix, value)).Append ("'); + } + + if (newDescription is not null) + text.Append ("'); + text.Append (spot.Close); + insert = new XmpEdit (fields[0], "", Attribute: false) { Start = spot.Start, End = spot.End, Inserted = text.ToString () }; + return true; + } + // Removed: an attribute takes the white space before it with it. static int Remove (StringBuilder builder, string packet, int at, XmpEdit edit) { @@ -113,7 +174,7 @@ static int Replace (StringBuilder builder, string packet, int at, XmpEdit edit, Append (builder, packet, tagAt, edit.StartTagEnd); Write (builder, edit.Empty ? ">" : ""); - Write (builder, PropertyContent (edit, value)); + Write (builder, PropertyContent (edit.Field, edit.RdfPrefix, value)); if (edit.Empty) Write (builder, $""); else @@ -121,23 +182,6 @@ static int Replace (StringBuilder builder, string packet, int at, XmpEdit edit, return edit.End; } - static string Join (string head, string packet, int tail) => -#if NETSTANDARD2_0 || NETSTANDARD2_1 - head + packet.Substring (tail); -#else - string.Concat (head.AsSpan (), packet.AsSpan (tail)); -#endif - - static bool IsPacketTail (string packet, int from) - { - for (var i = from; i < packet.Length; i++) { - if (packet[i] != '\0' && !XmlText.IsXmlSpace (packet[i])) - return false; - } - - return true; - } - static void Append (StringBuilder builder, string text, int from, int to) { if (to <= from) @@ -152,14 +196,14 @@ static void Write (StringBuilder builder, string text) SpliceWrites += text.Length; } - static string PropertyContent (XmpEdit edit, string value) + static string PropertyContent (MirrorFields.MirrorField field, string? rdfPrefix, string value) { var item = XmlText.EscapeXml (value, attribute: false); // The RDF namespace may have no prefix in scope at the property (a declaration on it can hide one); // then the container declares it as its default namespace. - var rdf = edit.RdfPrefix is null ? "" : edit.RdfPrefix.Length == 0 ? "" : edit.RdfPrefix + ":"; - var declare = edit.RdfPrefix is null ? $" xmlns=\"{XmpProperties.RdfNamespace}\"" : ""; - return edit.Field.Ordered + var rdf = rdfPrefix is null ? "" : rdfPrefix.Length == 0 ? "" : rdfPrefix + ":"; + var declare = rdfPrefix is null ? $" xmlns=\"{XmpProperties.RdfNamespace}\"" : ""; + return field.Ordered ? $"<{rdf}Seq{declare}><{rdf}li>{item}" : $"<{rdf}Alt{declare}><{rdf}li xml:lang=\"x-default\">{item}"; } diff --git a/src/TagLibSharp2/Image/Xmp/XmpProperties.cs b/src/TagLibSharp2/Image/Xmp/XmpProperties.cs index 5d690521..78e24b12 100644 --- a/src/TagLibSharp2/Image/Xmp/XmpProperties.cs +++ b/src/TagLibSharp2/Image/Xmp/XmpProperties.cs @@ -17,24 +17,28 @@ static class XmpProperties // rdf attributes on a property element that say its content is something else; they go with a new value. static readonly string[] ContradictingRdfAttributes = ["resource", "parseType", "datatype", "nodeID"]; - public static bool TryFind (string packet, ImageTag tag, string carrier, List edits, out string? error) + /// How a packet is read: a DTD is refused (no entity is expanded) and nothing outside the packet is resolved. + public static XmlReaderSettings ReaderSettings () => new () { + DtdProcessing = DtdProcessing.Prohibit, + XmlResolver = null, + IgnoreComments = true, + IgnoreProcessingInstructions = false, + CloseInput = true + }; + + /// Finds the changed fields' properties, and where a property is added when is set. + public static bool TryFind (string packet, ImageTag tag, string carrier, List edits, XmpTarget? target, out string? error) { error = null; var lines = XmlText.LineStarts (packet); - var settings = new XmlReaderSettings { - DtdProcessing = DtdProcessing.Prohibit, - XmlResolver = null, - IgnoreComments = true, - IgnoreProcessingInstructions = false, - CloseInput = true - }; try { - using var reader = XmlReader.Create (new StringReader (packet), settings); - return TryScan (packet, lines, reader, tag, carrier, edits, out error); + using var reader = XmlReader.Create (new StringReader (packet), ReaderSettings ()); + return TryScan (packet, lines, reader, tag, carrier, edits, target, out error); } catch (XmlException ex) { // A packet that is not well-formed is read by no XMP reader (exiftool: "Empty XMP"); it can hold a copy only // where its text names a changed field's property, and is refused only then. edits.Clear (); + target?.Forget (); if (!NamesAnyField (packet, tag)) return true; error = $"The {carrier} is not well-formed XML ({ex.Message}), so its copy of a changed field cannot be updated."; @@ -52,23 +56,55 @@ static bool NamesAnyField (string packet, ImageTag tag) return false; } - static bool TryScan (string packet, int[] lines, XmlReader reader, ImageTag tag, string carrier, List edits, out string? error) + static bool TryScan (string packet, int[] lines, XmlReader reader, ImageTag tag, string carrier, List edits, XmpTarget? target, out string? error) { error = null; var info = (IXmlLineInfo)reader; var descriptionDepth = -1; + var rdfDepth = -1; while (reader.Read ()) { if (reader.NodeType == XmlNodeType.EndElement && reader.Depth == descriptionDepth) { + if (target is { Description.Located: false } && !target.Description.TryEnd (packet, XmlText.Offset (lines, info.LineNumber, info.LinePosition) - 2)) { + error = $"The {carrier} could not be updated: the end of its rdf:Description could not be located in the packet text."; + return false; + } + descriptionDepth = -1; continue; } + if (reader.NodeType == XmlNodeType.EndElement && reader.Depth == rdfDepth) { + if (!target!.Rdf.TryEnd (packet, XmlText.Offset (lines, info.LineNumber, info.LinePosition) - 2)) { + error = $"The {carrier} could not be updated: the end of its rdf:RDF could not be located in the packet text."; + return false; + } + + rdfDepth = -1; + continue; + } + if (reader.NodeType != XmlNodeType.Element) continue; + if (target is { Rdf.Opened: false } && reader.LocalName == "RDF" && reader.NamespaceURI == RdfNamespace) { + if (!target.Rdf.TryOpen (packet, lines, reader, info)) { + error = $"The {carrier} could not be updated: its rdf:RDF could not be located in the packet text."; + return false; + } + + if (!reader.IsEmptyElement) + rdfDepth = reader.Depth; + 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 (target is { Description.Opened: false } && !target.Description.TryOpen (packet, lines, reader, info)) { + error = $"The {carrier} could not be updated: its rdf:Description could not be located in the packet text."; + return false; + } + if (!reader.IsEmptyElement) descriptionDepth = reader.Depth; } @@ -216,4 +252,74 @@ sealed record XmpEdit (MirrorField Field, string Name, bool Attribute) public bool Empty { get; init; } public string? RdfPrefix { get; init; } public List<(int Start, int End)> Cuts { get; init; } = []; + + /// Text written in place of Start..End: properties added to the packet. + public string? Inserted { get; init; } +} + +/// +/// Where properties are added to a packet: inside its first top-level rdf:Description, or, when it has none, +/// in a new description at the end of its rdf:RDF (XMP Part 1 §7.4: the properties of the resource are +/// in one or more descriptions there). +/// +sealed class XmpTarget +{ + public XmpSpot Description { get; } = new (); + public XmpSpot Rdf { get; } = new (); + + // A packet found not to be well-formed after an element was located has nowhere to add a property. + public void Forget () + { + Description.Forget (); + Rdf.Forget (); + } +} + +/// +/// The place in an element where content is added: before its end tag, or, when it is an empty element, in place of +/// its "/>", followed by a new end tag. The prefixes in scope there name the field namespaces and RDF. +/// +sealed class XmpSpot +{ + public bool Opened { get; private set; } + public bool Located => Start >= 0; + public int Start { get; private set; } = -1; + public int End { get; private set; } = -1; + + /// The end tag written after the added content: empty unless the element was an empty element. + public string Close { get; private set; } = ""; + + public string? RdfPrefix { get; private set; } + public Dictionary Prefixes { get; } = []; + + // The reader is on the element's start tag. + public bool TryOpen (string packet, int[] lines, XmlReader reader, IXmlLineInfo info) + { + Opened = true; + var resolver = (IXmlNamespaceResolver)reader; + RdfPrefix = resolver.LookupPrefix (XmpProperties.RdfNamespace); + foreach (var field in MirrorFields.All) + Prefixes[field.XmpNamespace] = resolver.LookupPrefix (field.XmpNamespace); + if (!reader.IsEmptyElement) + return true; + var name = reader.Name; + var nameAt = XmlText.Offset (lines, info.LineNumber, info.LinePosition); + if (!XmlText.At (packet, nameAt, name) || !XmlText.TryTagEnd (packet, nameAt + name.Length, out var startTagEnd) || packet[startTagEnd - 2] != '/') + return false; + Start = startTagEnd - 2; + End = startTagEnd; + Close = $""; + return true; + } + + public void Forget () => Start = End = -1; + + // At the element's end tag: its " +/// Reads one field's value from the text of an XMP packet with an XML reader, so every entity and character +/// reference is decoded (XML 1.0 §4.1, §4.6). The property is the first one, as an attribute or a child element, of +/// a top-level rdf:Description (XMP Part 1 §7.4, §7.5). A language alternative gives its +/// x-default item, else its first item (XMP Part 1 §7.9); a simple property gives its text. +/// +static class XmpValues +{ + /// The value, or null when the packet holds none or is not well-formed XML. + public static string? Read (string packet, MirrorField field) + { + var (start, end) = XmlText.PacketXml (packet); + try { + using var reader = XmlReader.Create (new StringReader (packet.Substring (start, end - start)), XmpProperties.ReaderSettings ()); + var value = Scan (reader, field); + // The rest of the packet is read too: a packet that is not well-formed holds no value for exiv2, which + // drops it, or for exiftool, which reports a format error and shows no XMP title (measured, 13.55). + while (reader.Read ()) { + } + + return value; + } catch (XmlException) { + return null; + } + } + + static string? Scan (XmlReader reader, MirrorField field) + { + 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 != XmpProperties.RdfNamespace) + continue; + if (reader.GetAttribute (field.XmpName, field.XmpNamespace) is string attribute) + return attribute; + if (!reader.IsEmptyElement) + descriptionDepth = reader.Depth; + continue; + } + + if (reader.Depth == descriptionDepth + 1 && reader.LocalName == field.XmpName && reader.NamespaceURI == field.XmpNamespace) + return reader.IsEmptyElement ? null : Property (reader); + } + + return null; + } + + // The reader is on the property's start tag. Its x-default item, else its first item, else its own text. + static string? Property (XmlReader reader) + { + var depth = reader.Depth; + var text = new StringBuilder (); + string? first = null; + while (reader.Read () && reader.Depth > depth) { + if (reader.NodeType is XmlNodeType.Text or XmlNodeType.CDATA && reader.Depth == depth + 1) { + text.Append (reader.Value); + continue; + } + + if (reader.NodeType != XmlNodeType.Element || reader.Depth != depth + 2 || reader.LocalName != "li" || reader.NamespaceURI != XmpProperties.RdfNamespace) + continue; + var lang = reader.XmlLang; + var item = reader.IsEmptyElement ? "" : Item (reader); + if (lang == "x-default") + return item; + first ??= item; + } + + return first ?? (text.Length > 0 ? text.ToString () : null); + } + + // The text of an item, read to its end tag. + static string Item (XmlReader reader) + { + var depth = reader.Depth; + var text = new StringBuilder (); + while (reader.Read () && reader.Depth > depth) { + if (reader.NodeType is XmlNodeType.Text or XmlNodeType.CDATA or XmlNodeType.Whitespace or XmlNodeType.SignificantWhitespace) + text.Append (reader.Value); + } + + return text.ToString (); + } +} diff --git a/src/TagLibSharp2/Matroska/EbmlWriter.cs b/src/TagLibSharp2/Matroska/EbmlWriter.cs index f92d80c2..d351cfa6 100644 --- a/src/TagLibSharp2/Matroska/EbmlWriter.cs +++ b/src/TagLibSharp2/Matroska/EbmlWriter.cs @@ -63,6 +63,24 @@ internal static byte[] Size (int value) return bytes; } + /// + /// as a size of exactly bytes (RFC 8794 §6.1 allows a longer + /// encoding than the shortest), or null when it does not fit there without being the unknown size. + /// + internal static byte[]? Size (int value, int width) + { + if (width is < 1 or > 8 || (ulong)value > (1UL << (7 * width)) - 2) + return null; + var raw = (1UL << (7 * width)) | (uint)value; + var bytes = new byte[width]; + for (var i = width - 1; i >= 0; i--) { + bytes[i] = (byte)raw; + raw >>= 8; + } + + return bytes; + } + static int WidthOf (ulong value) { if (value <= 0xFF) diff --git a/src/TagLibSharp2/Matroska/MatroskaFile.cs b/src/TagLibSharp2/Matroska/MatroskaFile.cs index 02571ff9..5153d75e 100644 --- a/src/TagLibSharp2/Matroska/MatroskaFile.cs +++ b/src/TagLibSharp2/Matroska/MatroskaFile.cs @@ -94,6 +94,7 @@ internal void MarkPicturesSkipped () _audioCodec = layout.AudioCodec; _width = layout.Width; _height = layout.Height; + _rotation = layout.Rotation; _frameRate = layout.FrameRate; _videoCodec = layout.VideoCodec; Tracks = layout.Tracks is null ? [] : layout.Tracks.ToArray (); @@ -106,6 +107,7 @@ internal void MarkPicturesSkipped () readonly string? _audioCodec; readonly int _width; readonly int _height; + readonly int _rotation; readonly double _frameRate; readonly string? _videoCodec; @@ -150,7 +152,7 @@ internal void MarkPicturesSkipped () VideoProperties? IMediaFile.VideoProperties => (MediaTypes & MediaTypes.Video) != 0 - ? new VideoProperties (Duration ?? TimeSpan.Zero, _width, _height, 0, _frameRate, _videoCodec ?? "Matroska") + ? new VideoProperties (Duration ?? TimeSpan.Zero, _width, _height, 0, _frameRate, _videoCodec ?? "Matroska") { Rotation = _rotation } : null; ImageProperties? IMediaFile.ImageProperties => null; @@ -324,8 +326,13 @@ static void CollectChildren (Stream stream, long start, long end, MemoryStream k { var pos = start; while (pos + 2 <= end) { - if (!TryPeek (stream, pos, out var id, out var headerLength, out var dataLength)) - break; + // Bytes that are not an element that fits the Segment are skipped, as the read from memory skips them + // (a live recording puts 0x0A filler after the unknown Segment size). + if (!TryPeek (stream, pos, out var id, out var headerLength, out var dataLength) + || (dataLength >= 0 && pos + headerLength + dataLength > end)) { + pos = NextElement (stream, pos + 1, end); + continue; + } if (id == MatroskaIds.Cluster) { // Known clusters are seeked past. An unknown-size cluster ends at the next // segment child, matching the byte reader, and its payload is not copied. @@ -364,6 +371,31 @@ static void CollectChildren (Stream stream, long start, long end, MemoryStream k } } + /// + /// The first offset at or after where an element starts that ends by + /// , or : the offsets the read from memory steps over one by one. The + /// scan reads 4 offsets (and the 12 bytes a header can take) first and doubles each time up to 64 KB, so a resync + /// reads about as far as it scans: a run of filler costs one pass, and a junk byte before the next element a few + /// bytes, not a window. + /// + static long NextElement (Stream stream, long start, long end) + { + const int MaxScan = 64 * 1024; + const int Header = 12; + var scan = 4; + for (var pos = start; pos + 2 <= end; pos += scan, scan = Math.Min (scan * 2, MaxScan)) { + stream.Position = pos; + var window = StreamBytes.ReadAtMost (stream, (int)Math.Min (scan + Header, end - pos)); + for (var i = 0; i < Math.Min (scan, window.Length - 1); i++) { + if (EbmlReader.TryPeekHeader (window.AsSpan (i), out _, out var headerLength, out var dataLength) + && (dataLength < 0 || pos + i + headerLength + dataLength <= end)) + return pos + i; + } + } + + return end; + } + static bool TryPeek (Stream stream, long pos, out ulong id, out int headerLength, out long dataLength) { id = 0; @@ -764,6 +796,7 @@ static void ReadTrackEntry (ReadOnlySpan entry, ref TrackLayout layout) var bits = 0; var width = 0; var height = 0; + var rotation = 0; double frameRate = 0; var offset = 0; while (offset < entry.Length) { @@ -795,7 +828,7 @@ static void ReadTrackEntry (ReadOnlySpan entry, ref TrackLayout layout) sawAudio = true; ReadAudio (payload, ref rate, ref outputRate, ref sawOutputRate, ref channels, ref bits); } else if (element.Id == MatroskaIds.Video) - ReadVideoSize (payload, ref width, ref height); + ReadVideo (payload, ref width, ref height, ref rotation); offset = element.End; } @@ -835,6 +868,7 @@ static void ReadTrackEntry (ReadOnlySpan entry, ref TrackLayout layout) layout.VideoRank = rank; layout.Width = width; layout.Height = height; + layout.Rotation = rotation; layout.FrameRate = frameRate; layout.VideoCodec = codec; } @@ -865,7 +899,7 @@ static void ReadAudio (ReadOnlySpan body, ref int rate, ref int outputRate channels = 1; } - static void ReadVideoSize (ReadOnlySpan body, ref int width, ref int height) + static void ReadVideo (ReadOnlySpan body, ref int width, ref int height, ref int rotation) { var offset = 0; while (offset < body.Length) { @@ -876,10 +910,48 @@ static void ReadVideoSize (ReadOnlySpan body, ref int width, ref int heigh width = (int)EbmlReader.ReadUInt (payload); else if (element.Id == MatroskaIds.PixelHeight) height = (int)EbmlReader.ReadUInt (payload); + else if (element.Id == MatroskaIds.Projection) + rotation = ReadRotation (payload); offset = element.End; } } + /// + /// The clockwise rotation a Projection asks for, in degrees from 0 to 359. RFC 9559 §15: ProjectionPoseRoll + /// (§5.1.4.1.28.46) rotates the image for presentation, counter-clockwise, in -180 to 180. Only a rectangular + /// projection (ProjectionType 0, §5.1.4.1.28.42) with no yaw or pitch (§5.1.4.1.28.44, .45; a yaw of 180 flips the + /// image) is a flat rotation; anything else, or a roll out of range, is 0. Every element has a default of 0. + /// + static int ReadRotation (ReadOnlySpan body) + { + ulong type = 0; + double yaw = 0, pitch = 0, roll = 0; + var offset = 0; + while (offset < body.Length) { + if (!EbmlReader.TryRead (body, offset, body.Length, out var element) || element.UnknownSize) + break; + var payload = body.Slice (element.DataOffset, (int)element.DataLength); + if (element.Id == MatroskaIds.ProjectionType) + type = payload.Length > 0 ? EbmlReader.ReadUInt (payload) : 0; + else if (element.Id == MatroskaIds.ProjectionPoseYaw) + yaw = ReadFloatOrZero (payload); + else if (element.Id == MatroskaIds.ProjectionPosePitch) + pitch = ReadFloatOrZero (payload); + else if (element.Id == MatroskaIds.ProjectionPoseRoll) + roll = ReadFloatOrZero (payload); + offset = element.End; + } + + if (type != 0 || yaw != 0 || pitch != 0 || !(roll is >= -180 and <= 180)) + return 0; + var degrees = (int)Math.Round (-roll); + return (degrees + 360) % 360; + } + + // RFC 8794 §7.2: an empty element is its default, 0 here. + static double ReadFloatOrZero (ReadOnlySpan payload) => + EbmlReader.TryReadFloat (payload, out var value) ? value : 0; + static string CodecLabel (string? codecId, string? codecName, ReadOnlySpan codecPrivate) { if (codecName is { Length: > 0 } name && name != codecId) @@ -985,6 +1057,7 @@ struct TrackLayout public int AudioRank; public int Width; public int Height; + public int Rotation; public double FrameRate; public string? VideoCodec; public bool HasVideo; diff --git a/src/TagLibSharp2/Matroska/MatroskaIds.cs b/src/TagLibSharp2/Matroska/MatroskaIds.cs index c118bc2a..300571ba 100644 --- a/src/TagLibSharp2/Matroska/MatroskaIds.cs +++ b/src/TagLibSharp2/Matroska/MatroskaIds.cs @@ -39,6 +39,11 @@ static class MatroskaIds public const ulong Video = 0xE0; public const ulong PixelWidth = 0xB0; public const ulong PixelHeight = 0xBA; + public const ulong Projection = 0x7670; + public const ulong ProjectionType = 0x7671; + public const ulong ProjectionPoseYaw = 0x7673; + public const ulong ProjectionPosePitch = 0x7674; + public const ulong ProjectionPoseRoll = 0x7675; public const ulong AttachedFile = 0x61A7; public const ulong FileDescription = 0x467E; public const ulong FileName = 0x466E; diff --git a/src/TagLibSharp2/Matroska/MatroskaRewrite.Info.cs b/src/TagLibSharp2/Matroska/MatroskaRewrite.Info.cs new file mode 100644 index 00000000..d6f5f095 --- /dev/null +++ b/src/TagLibSharp2/Matroska/MatroskaRewrite.Info.cs @@ -0,0 +1,70 @@ +// 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.Matroska; + +static partial class MatroskaRewrite +{ + /// + /// The first Info element with its Title (RFC 9559 §5.1.2.9) set to , at exactly the + /// length it has, so that nothing after it moves. Its Void children are dropped and one Void (RFC 8794 §11.3.1) + /// pads the payload back to its length. A title that does not fit, or that leaves one byte a Void cannot fill, is + /// left out, as is a null one: the TITLE tag then gives the title (exiftool and MediaInfo show it when Info has no + /// Title). Null when there is no Info of known size to rewrite, or it has no room even without the title. + /// + static byte[]? RenderInfo (ReadOnlySpan data, Layout layout, string? title) + { + var index = layout.Pieces.FindIndex (piece => piece.Id == MatroskaIds.Info && !piece.UnknownSize); + if (index < 0) + return null; + var piece = layout.Pieces[index]; + if (!EbmlReader.TryRead (data, piece.Offset, piece.Offset + piece.Length, out var info) || info.UnknownSize || info.End != piece.Offset + piece.Length) + return null; + + using var kept = new BinaryDataBuilder ((int)info.DataLength); + var offset = info.DataOffset; + while (offset < info.End) { + if (!EbmlReader.TryRead (data, offset, info.End, out var child) || child.UnknownSize) + return null; + if (child.Id is not (MatroskaIds.SegmentTitle or MatroskaIds.Void)) + kept.Add (data.Slice (offset, child.End - offset)); + offset = child.End; + } + + var room = (int)info.DataLength; + var withTitle = title is null ? null : EbmlWriter.String (MatroskaIds.SegmentTitle, title).ToArray (); + if (withTitle is not null && Void (room - kept.Length - withTitle.Length) is null) + withTitle = null; + var padding = Void (room - kept.Length - (withTitle?.Length ?? 0)); + if (padding is null) + return null; + + using var element = new BinaryDataBuilder (piece.Length); + element.Add (data.Slice (piece.Offset, info.DataOffset - piece.Offset)); + element.Add (kept.ToBinaryData ().Span); + if (withTitle is not null) + element.Add (withTitle); + element.Add (padding); + return element.ToArray (); + } + + // A Void element of exactly `length` bytes (0 for none), or null when no Void has that length (1 byte, or a + // negative length). + static byte[]? Void (int length) + { + if (length == 0) + return []; + for (var width = 1; width <= 8 && length >= 1 + width; width++) { + if (EbmlWriter.Size (length - 1 - width, width) is not byte[] size) + continue; + var bytes = new byte[length]; + bytes[0] = (byte)MatroskaIds.Void; + size.CopyTo (bytes, 1); + return bytes; + } + + return null; + } +} diff --git a/src/TagLibSharp2/Matroska/MatroskaRewrite.Stream.cs b/src/TagLibSharp2/Matroska/MatroskaRewrite.Stream.cs index 87d2992d..b9b25591 100644 --- a/src/TagLibSharp2/Matroska/MatroskaRewrite.Stream.cs +++ b/src/TagLibSharp2/Matroska/MatroskaRewrite.Stream.cs @@ -56,6 +56,9 @@ internal static bool TryPlanStream ( var tags = (attachmentsChanged ? tag.RenderWithout (removed) : tag.Render ()).ToArray (); if (!tag.IsAsRead (tags) && !TryStageStream (ref doc, MatroskaIds.Tags, tags, false, out error)) return false; + if (tag.SegmentTitleChanged && RenderInfo (doc.Data, doc.Layout, tag.SegmentTitle) is byte[] info + && !TryStageStream (ref doc, MatroskaIds.Info, info, false, out error)) + return false; byte[]? size = null; if (doc.Changed) { @@ -606,12 +609,10 @@ static bool TryBuildDocument (Document source, Draft draft, out Document built, using var packed = new MemoryStream (); var pieces = new List (); var states = new List (); - var saw = false; foreach (var seg in draft.Segments) { if (seg.Cluster is { } cluster) { pieces.Add (new Piece (MatroskaIds.Cluster, -1, cluster.Length, cluster.UnknownSize)); states.Add (cluster); - saw = true; continue; } @@ -623,7 +624,7 @@ static bool TryBuildDocument (Document source, Draft draft, out Document built, } var before = pieces.Count; - if (!TryParseRun (bytes, baseOffset, ref saw, pieces, out error)) + if (!TryParseRun (bytes, baseOffset, pieces, out error)) return false; for (var n = before; n < pieces.Count; n++) states.Add (null); @@ -655,18 +656,14 @@ static bool TryBuildDocument (Document source, Draft draft, out Document built, return true; } - static bool TryParseRun (byte[] run, int packedBase, ref bool sawElement, List pieces, out string error) + static bool TryParseRun (byte[] run, int packedBase, List pieces, out string error) { error = ""; var offset = 0; var end = run.Length; while (offset < end) { + // Filler is a piece of its own wherever it is, as in TryPieces. if (!EbmlReader.TryRead (run, offset, end, out var element)) { - if (sawElement) { - error = "Matroska segment cannot be bounded"; - return false; - } - var gap = offset; while (offset < end && !EbmlReader.TryRead (run, offset, end, out _)) offset++; @@ -690,7 +687,6 @@ static bool TryParseRun (byte[] run, int packedBase, ref bool sawElement, List

(); var states = new List (); - var saw = false; var cursor = dataOffset; while (cursor < segmentEnd) { + // Filler is a piece of its own wherever it is, as in TryPieces. if (!reader.TryElement (cursor, segmentEnd, out var id, out var headerLength, out var dataLength, out var elementEnd)) { - if (saw) { - error = "Matroska segment cannot be bounded"; - return false; - } - var gap = cursor; while (cursor < segmentEnd && !reader.TryElement (cursor, segmentEnd, out _, out _, out _, out _)) cursor++; @@ -848,7 +839,6 @@ static bool TryParseStream (Reader reader, out Document? doc, out string error) } else if (!TryAddStreamPiece (reader, packed, pieces, states, id, cursor, pieceLength, unknown, out error)) return false; - saw = true; cursor = pieceEnd; } diff --git a/src/TagLibSharp2/Matroska/MatroskaRewrite.cs b/src/TagLibSharp2/Matroska/MatroskaRewrite.cs index e203de76..019e71d1 100644 --- a/src/TagLibSharp2/Matroska/MatroskaRewrite.cs +++ b/src/TagLibSharp2/Matroska/MatroskaRewrite.cs @@ -47,6 +47,9 @@ public static bool TryRewrite (ReadOnlySpan data, MatroskaTag tag, Matrosk var tags = (attachmentsChanged ? tag.RenderWithout (removed) : tag.Render ()).ToArray (); if (!tag.IsAsRead (tags) && !TryStage (data, ref staged, ref layout, MatroskaIds.Tags, tags, false, out error)) return false; + if (tag.SegmentTitleChanged && RenderInfo (staged ?? data, layout, tag.SegmentTitle) is byte[] info + && !TryStage (data, ref staged, ref layout, MatroskaIds.Info, info, false, out error)) + return false; rewritten = staged ?? data.ToArray (); return true; @@ -1538,14 +1541,10 @@ static bool TryPieces (ReadOnlySpan data, int start, int end, out List (); error = ""; var offset = start; - var sawElement = false; while (offset < end) { + // Bytes that are not an element that fits the Segment are kept as a piece of their own, wherever they are, + // as the reads step over them (#208): a live recording puts 0x0A filler after the Segment size. if (!EbmlReader.TryRead (data, offset, end, out var element)) { - if (sawElement) { - error = "Matroska segment cannot be bounded"; - return false; - } - var gap = offset; while (offset < end && !EbmlReader.TryRead (data, offset, end, out _)) offset++; @@ -1569,7 +1568,6 @@ static bool TryPieces (ReadOnlySpan data, int start, int end, out List reads, whichever Tag is first. ///

string[] TitlesRead () { @@ -66,11 +70,24 @@ string[] TitlesRead () return AllAt (TrackLevel, "TITLE"); if (!string.IsNullOrEmpty (_segmentTitle)) return [_segmentTitle!]; - return MostSpecificFileTitleBelowCollection () is ulong level ? AllAt (level, "TITLE") : []; + if (MostSpecificFileTitleBelowCollection () is not ulong level) + return []; + var untargeted = level == AlbumLevel ? UntargetedTitles () : []; + return untargeted.Length > 0 ? untargeted : AllAt (level, "TITLE"); } + string[] UntargetedTitles () => TextsOf (ValuesWhere (IsUntargeted, "TITLE")); + static string? FirstOf (string[] values) => values.Length > 0 ? values[0] : null; + /// + /// The list a one-name setter writes: the list read when is its first name, so + /// writing it back keeps the other names (a copy still replaces them), else the one name, else empty, which + /// the list setter clears or keeps by its own write-back rule. + /// + string[] FirstSet (string? value, string[] held) => + string.IsNullOrEmpty (value) ? [] : IsWriteBackAt (value, held, null, "") ? held : [value!]; + /// public override string? Artist { get => FirstOf (All ("ARTIST")); @@ -78,6 +95,8 @@ public override string? Artist { if (IsWriteBackAt (value, All ("ARTIST"), TrackLevel, "ARTIST")) return; SetValue (TrackLevel, "ARTIST", value, ["ARTIST_SORT"], ["ARTIST_SORT"], shadows: true); + if (string.IsNullOrEmpty (value)) + ClearUntargeted ("ARTIST", "ARTIST_SORT"); } } @@ -91,19 +110,67 @@ public override string[] Performers { if (IsListWriteBack (value, Performers, AnyTextAt (TrackLevel, "ARTIST"), clearsOneLevel: true)) return; SetValues (TrackLevel, "ARTIST", value, ["ARTIST_SORT"], ["ARTIST_SORT"], shadows: true); + if (!HasText (value)) + ClearUntargeted ("ARTIST", "ARTIST_SORT"); } } /// + /// + /// + /// The Matroska tagging spec stores the album as TITLE at TargetTypeValue 50 + /// (https://www.matroska.org/technical/tagging.html), and ffmpeg's -metadata album= writes a + /// simple tag named ALBUM in a Tag with an empty Targets, whose TargetTypeValue is 50 by + /// default (RFC 9559 section 5.1.8.1.1.1). The getter reads the explicit target-50 TITLE first, + /// then ALBUM, then a TITLE in a Tag with no TargetTypeValue. + /// + /// + /// Setting the album never changes , and never makes ffprobe or MediaInfo show the album + /// as the title. Both show the TITLE of the last Tag that has one as the file title, and ffprobe lets + /// one in a Tag with no TargetType string replace the segment title; both report ALBUM as the + /// album. So a file with an explicit target-50 TITLE has that updated, with any ALBUM beside + /// it, and any other file gets ALBUM at target 50, in the untargeted Tag ffmpeg writes or in a new + /// target-50 Tag, and no TITLE. A target-50 TITLE also titles the track while no narrower + /// TITLE exists ("A tag defined for a given TargetTypeValue also applies to all Targets with + /// numerically smaller TargetTypeValues"), so before it changes or goes, the title shown is kept at target + /// 30, and the Tags with a narrower TITLE are moved after the album's. A clear removes every album + /// source, ffmpeg's untargeted TITLE included, after keeping the title the same way. + /// + /// public override string? Album { - get => FirstOf (AllAt (AlbumLevel, "TITLE")); + get => FirstOf (AlbumValues ()); set { - if (IsWriteBackAt (value, AllAt (AlbumLevel, "TITLE"), AlbumLevel, "TITLE")) + var hasExplicit = ExplicitAlbumTitles ().Length > 0; + var hasFlat = FileLevelValues ("ALBUM").Length > 0; + // An ALBUM makes AlbumValues non-empty, so the name only matters with no album, where it is TITLE. + if (IsWriteBackAt (value, AlbumValues (), AlbumLevel, "TITLE")) + return; + if (string.IsNullOrEmpty (value)) { + KeepTrackTitle (); + SetValue (AlbumLevel, "TITLE", null, [], ["ALBUM_SORT"], shadows: false); + WriteFlatAlbum (null); return; - SetValue (AlbumLevel, "TITLE", value, [], ["ALBUM_SORT"], shadows: false); + } + + if (!hasExplicit) { + WriteFlatAlbum (value); + return; + } + + KeepTrackTitle (); + WriteExplicitAlbumTitle (value!); + KeepTrackTitleLast (); + if (hasFlat) + WriteFlatAlbum (value); } } + /// + public override string? AlbumArtist { + get => FirstOf (AlbumArtists); + set => AlbumArtists = FirstSet (value, AlbumArtists); + } + /// /// /// The album artist is ARTIST at the album level (TargetTypeValue 50), per @@ -111,6 +178,17 @@ public override string? Album { /// (the name ffmpeg writes) names its album artist there instead: it is read and written, and /// clearing it also removes its flat ALBUM_ARTIST_SORT, so the specification's album-level /// ARTIST shows through. + /// + /// Setting the album artists on an ffmpeg file does not change , or the artist ffprobe + /// and MediaInfo show (the ARTIST of the last Tag that has one). A target-50 ARTIST is also the + /// track's artist while no narrower ARTIST exists ("A tag defined for a given TargetTypeValue also + /// applies to all Targets with numerically smaller TargetTypeValues"). So on a file with ffmpeg's untargeted + /// Tag and no explicit target-50 ARTIST, where a write there would change the artist the track reads, + /// the album artists go in ALBUM_ARTIST at target 50 instead, which ffprobe, MediaInfo and ExifTool + /// report as the album artist, and a clear first keeps that ARTIST at 30 for the track. A file tagged + /// by the spec alone keeps the spec's model: its target-50 ARTIST is written or removed, and the track + /// inherits it. + /// /// public override string[] AlbumArtists { get { @@ -124,6 +202,16 @@ public override string[] AlbumArtists { if (IsListWriteBack (value, AlbumArtists, byName ? AnyText (AlbumArtistName) : AnyTextAt (AlbumLevel, "ARTIST"), clearsOneLevel: !byName)) return; if (!UsesAlbumArtistName) { + if (IsFfmpegTrackArtist (value)) { + if (HasText (value)) { + SetAtValues (AlbumLevel, AlbumArtistName, value); + return; + } + + // A clear takes the album artists, not the artist: the track keeps its ARTIST at 30. + SetValues (TrackLevel, "ARTIST", All ("ARTIST"), ["ARTIST_SORT"], ["ARTIST_SORT"], shadows: true); + } + // ALBUM_ARTIST_SORT at 50 is the album artist's whatever the track has, so only ARTIST_SORT can be the track's. SetValues (AlbumLevel, "ARTIST", value, ["ARTIST_SORT"], ["ARTIST_SORT", AlbumArtistSortName], shadows: true); return; @@ -187,7 +275,10 @@ public override uint? Track { /// public override uint? TotalTracks { get => TrackTotal (); - set => SetTrackTotal (value); + set { + if (!IsWriteBack (value, TrackTotal ())) + SetTrackTotal (value); + } } /// @@ -195,8 +286,18 @@ public override uint? DiscNumber { // PART_NUMBER is the disc only when TargetTypeValue is stored and equal to 50. get => ParseLeading (DiscPartNumber ()); set { + // Writing back the number read leaves a DISCNUMBER, which a set replaces with DISC. + if (IsWriteBack (value, DiscNumber)) + return; // Changing the number keeps TotalDiscs, including a total read from the old "2/3". var total = DiscTotal (); + if (!KeepsSpecDisc ()) { + WriteDisc (value, value is null ? null : total); + if (value is null && total is not null) + SetDiscTotal (total); + return; + } + RemoveDiscNames (); if (value is null) { RemoveWhere (IsExplicitAlbum, "PART_NUMBER"); @@ -214,7 +315,16 @@ public override uint? DiscNumber { /// public override uint? TotalDiscs { get => DiscTotal (); - set => SetDiscTotal (value); + set { + if (!IsWriteBack (value, DiscTotal ())) + SetDiscTotal (value); + } + } + + /// + public override string? Composer { + get => FirstOf (Composers); + set => Composers = FirstSet (value, Composers); } /// @@ -228,6 +338,8 @@ public override string[] Composers { if (!HasText (value) && ChosenLevel ("COMPOSER") is not null) RemoveVisible ("COMPOSER_SORT"); SetItemValues ("COMPOSER", value); + if (!HasText (value)) + ClearUntargeted ("COMPOSER", "COMPOSER_SORT"); } } @@ -551,6 +663,7 @@ public override void Clear () _blocks.Clear (); _pictures.Clear (); _picturesChanged = true; + SetSegmentTitleEdit (null); } bool _picturesChanged; @@ -721,7 +834,29 @@ internal BinaryData RenderWithout (HashSet? removedAttachments) static bool IsDropped (TagBlock block) => block.Tags.Count == 0 && !block.WasEmpty; - internal void SetSegmentTitle (string? title) => _segmentTitle = title; + internal void SetSegmentTitle (string? title) + { + _segmentTitle = title; + _hasSegmentTitle = title is not null; + } + + // Whether Info held a Title when read, and whether a title edit or Clear changed it since (#210). + bool _hasSegmentTitle; + + /// Whether a save must rewrite Info/Title to . + internal bool SegmentTitleChanged { get; private set; } + + /// The segment title a save writes; null removes it. + internal string? SegmentTitle => _segmentTitle; + + // RFC 9559 §5.1.2.9: Info/Title is the segment's title, which exiftool and MediaInfo show before the TITLE tag. + void SetSegmentTitleEdit (string? title) + { + if (!_hasSegmentTitle) + return; + _segmentTitle = string.IsNullOrEmpty (title) ? null : title; + SegmentTitleChanged = true; + } internal void AddBlock (TagBlock block) => _blocks.Add (block); @@ -768,33 +903,15 @@ bool HasFileLevelName (ulong level, string name) // A getter's value is the first of the list its setter's write-back check reads (All, AllAt). string? First (string name) => FirstOf (All (name)); - string[] All (string name) - { - var values = Values (name); - var count = 0; - for (var i = 0; i < values.Count; i++) { - if (values[i].Length > 0) - count++; - } - - if (count == 0) - return []; - - var result = new string[count]; - var at = 0; - for (var i = 0; i < values.Count; i++) { - if (values[i].Length > 0) - result[at++] = values[i]; - } - - return result; - } + string[] All (string name) => TextsOf (Values (name)); string? FirstAt (ulong level, string name) => FirstOf (AllAt (level, name)); - string[] AllAt (ulong level, string name) + string[] AllAt (ulong level, string name) => TextsOf (ValuesAt (level, name)); + + // The values that hold text, in order. + static string[] TextsOf (List values) { - var values = ValuesAt (level, name); var count = 0; for (var i = 0; i < values.Count; i++) { if (values[i].Length > 0) @@ -1191,21 +1308,24 @@ bool ReplaceNestedSortAt (ulong level, string name, string? value) return null; } - List ValuesAt (ulong level, string name) + List ValuesAt (ulong level, string name) => + ValuesWhere (block => block.IsFileLevel && block.Level == level, name); + + // The default-language values when any Tag that matches holds one, else every value. + List ValuesWhere (Func match, string name) { var preferDefault = false; foreach (var block in _blocks) { - if (!block.IsFileLevel || block.Level != level) - continue; - if (block.HasDefault (name)) + t_levelSteps++; + if (match (block) && block.HasDefault (name)) preferDefault = true; } var values = new List (); foreach (var block in _blocks) { - if (!block.IsFileLevel || block.Level != level) - continue; - block.Collect (name, preferDefault, values); + t_levelSteps++; + if (match (block)) + block.Collect (name, preferDefault, values); } return values; @@ -1458,11 +1578,24 @@ void SetTrackNumber (string text) void SetTrackTotal (uint? value) { + var keepsTotalParts = KeepsTotalParts (); // The level 30 fallback goes when it is what the getter shows, and on a clear, which would otherwise expose it. if (value is null || SpecTrackTotal () is null) RemoveWhere (IsTrackLevel, "TOTAL_PARTS"); RemoveFileLevel ("TRACKTOTAL"); RemoveFileLevel ("TOTALTRACKS"); + + // As for the disc (#205): ffprobe shows TOTAL_PARTS only as a raw tag, and shows ffmpeg's PART_NUMBER "n/m" as + // the track with its total, as MediaInfo does. A file that does not already keep its total as TOTAL_PARTS + // (the spec's at 50, ffmpeg's untargeted one, or TagLib's at 30) gets it after its track number; a total + // with no number to follow is TOTAL_PARTS. + if (value is not null && !keepsTotalParts && ParseLeading (TrackPartNumber ()) is uint number) { + RemoveWhere (IsAlbumTarget, "TOTAL_PARTS"); + StripEmbeddedTotal (IsTrackTarget, "PART_NUMBER"); + SetTrackNumber (number.ToString (CultureInfo.InvariantCulture) + "/" + value.Value.ToString (CultureInfo.InvariantCulture)); + return; + } + if (value is null) { RemoveWhere (IsAlbumTarget, "TOTAL_PARTS"); StripEmbeddedTotal (IsTrackTarget, "PART_NUMBER"); @@ -1475,6 +1608,8 @@ void SetTrackTotal (uint? value) StripEmbeddedTotal (IsTrackTarget, "PART_NUMBER"); } + bool KeepsTotalParts () => AlbumTotalBlock () is not null || FirstNumberWhere (IsTrackLevel, "TOTAL_PARTS") is not null; + // The album the file's disc belongs to first, then any stored 50, then a block that omits TargetTypeValue. TagBlock? AlbumTotalBlock () => FirstBlock (block => IsExplicitAlbum (block) && Text (block, "PART_NUMBER") is not null && HasNumber (block, "TOTAL_PARTS")) @@ -1498,6 +1633,12 @@ TagBlock TrackTotalHome () => void SetDiscTotal (uint? value) { + // A disc written as ffmpeg's DISC keeps its total there, as "n/m". + if (!KeepsSpecDisc () && ParseLeading (LowestLevelText ("DISCNUMBER", "DISC")) is uint number) { + WriteDisc (number, value); + return; + } + // 60 TOTAL_PARTS counts "the first lower TargetTypeValue that is specified in the file" // (tagging.html, Target Types Parts). Without a 40 or 50 tag that is the track, so a known disc // number moves to 50 PART_NUMBER first and the 60 total then counts discs. @@ -1520,6 +1661,31 @@ void SetDiscTotal (uint? value) StripEmbeddedTotal (block => block.IsFileLevel, "DISCNUMBER"); } + /// + /// Whether the file keeps its disc as the specification's PART_NUMBER at an explicit target of 50 + /// (tagging.html, Target Types Parts). Any other file gets ffmpeg's DISC: ffprobe shows every + /// PART_NUMBER as a track number, whatever its target, and ffprobe, exiftool and MediaInfo show + /// DISC as the disc (#205). + /// + bool KeepsSpecDisc () => FirstBlock (block => IsExplicitAlbum (block) && block.HasName ("PART_NUMBER")) is not null; + + /// + /// Writes ffmpeg's DISC, "n" or "n/m", in the untargeted Tag ffmpeg writes, else in a Tag at target 50, and + /// removes the other copies of the disc and of its total. Null removes the disc. + /// + void WriteDisc (uint? number, uint? total) + { + RemoveDiscNames (); + RemoveFileLevel ("DISCTOTAL"); + RemoveFileLevel ("TOTALDISCS"); + RemoveWhere (IsVolume, "TOTAL_PARTS"); + if (number is null) + return; + var home = FirstBlock (IsUntargeted) ?? FirstBlock (IsExplicitAlbum) ?? AddFileBlock (new TagBlock (AlbumLevel)); + var text = number.Value.ToString (CultureInfo.InvariantCulture); + ReplaceOrAdd (home, "DISC", total is null ? text : text + "/" + total.Value.ToString (CultureInfo.InvariantCulture)); + } + /// /// The explicit album target that stores the disc. An omitted TargetTypeValue is not this target. /// @@ -1543,6 +1709,100 @@ static bool IsTrackTarget (TagBlock block) => static bool IsExplicitAlbum (TagBlock block) => block.IsFileLevel && block.HasTargetTypeValue && block.Level == AlbumLevel; + // TITLE at an explicit target of 50. An untargeted TITLE is not this: ffmpeg's untargeted tag is + // the file title's neighbour, and a TITLE added there is what ffprobe reports as the title. + string[] ExplicitAlbumTitles () => TextsOf (ValuesWhere (IsExplicitAlbum, "TITLE")); + + string[] FileLevelValues (string name) => TextsOf (ValuesWhere (block => block.IsFileLevel, name)); + + // Spec album first, then ffmpeg's ALBUM name, then a TITLE that shares the untargeted tag. + string[] AlbumValues () + { + var specified = ExplicitAlbumTitles (); + if (specified.Length > 0) + return specified; + var flat = FileLevelValues ("ALBUM"); + return flat.Length > 0 ? flat : AllAt (AlbumLevel, "TITLE"); + } + + // Replace every ALBUM simple tag ffmpeg wrote, or add one at target 50. Do not add TITLE beside it. + void WriteFlatAlbum (string? value) + { + if (string.IsNullOrEmpty (value)) { + foreach (var block in _blocks) { + t_levelSteps++; + if (block.IsFileLevel) + block.Remove ("ALBUM"); + } + + return; + } + + var home = FirstBlock (candidate => candidate.IsFileLevel && candidate.HasName ("ALBUM")) + ?? FirstBlock (IsUntargeted) + ?? AddFileBlock (new TagBlock (AlbumLevel)); + ReplaceOrAdd (home, "ALBUM", value!); + foreach (var block in _blocks) { + t_levelSteps++; + if (!ReferenceEquals (block, home) && block.IsFileLevel) + block.Remove ("ALBUM"); + } + } + + // The album TITLE at an explicit target of 50. ffmpeg's untargeted TITLE is the file title: it stays. + void WriteExplicitAlbumTitle (string value) => + SetValuesWhere (IsExplicitAlbum, "TITLE", [value], () => FirstBlock (IsExplicitAlbum) ?? AddFileBlock (new TagBlock (AlbumLevel))); + + /// + /// Before a TITLE at 50 changes: while no narrower TITLE exists the track inherits it, so the + /// title the file shows (, the segment title included) is written at 30. A new 30 Tag + /// goes after the album's, where ffprobe and MediaInfo, which show the last Tag's TITLE, read it. + /// + void KeepTrackTitle () + { + if (!HasFileLevelName (AlbumLevel, "TITLE") || HasFileLevelNameBelow (AlbumLevel, "TITLE")) + return; + var shown = FirstOf (TitlesRead ()); + if (!string.IsNullOrEmpty (shown)) + SetValue (TrackLevel, "TITLE", shown, [], ["TITLE_SORT"], shadows: false); + } + + /// + /// ffprobe and MediaInfo show the TITLE of the last Tag that has one, so the Tags holding a narrower + /// TITLE move after the last explicit album Tag that has one. Tag order carries no meaning in the + /// spec; this only changes which TITLE those readers meet last. + /// + void KeepTrackTitleLast () + { + var lastAlbum = _blocks.FindLastIndex (IsAlbumTitleBlock); + var narrower = new List (); + for (var i = 0; i < lastAlbum; i++) { + t_levelSteps++; + var block = _blocks[i]; + if (block.IsFileLevel && block.Level < AlbumLevel && block.HasName ("TITLE")) + narrower.Add (block); + } + + var moving = new HashSet (narrower); + _blocks.RemoveAll (moving.Contains); + _blocks.InsertRange (_blocks.FindLastIndex (IsAlbumTitleBlock) + 1, narrower); + } + + static bool IsAlbumTitleBlock (TagBlock block) => IsExplicitAlbum (block) && block.HasName ("TITLE"); + + /// + /// An ARTIST at 50 is the track's artist while no narrower ARTIST exists. On a file with ffmpeg's untargeted Tag + /// and no explicit target-50 ARTIST, that ARTIST is the one ffmpeg wrote for the track, so a write of other album + /// artists there would change the artist every reader shows. + /// + bool IsFfmpegTrackArtist (string[]? values) => + FirstBlock (IsUntargeted) is not null + && FirstBlock (block => IsExplicitAlbum (block) && block.HasName ("ARTIST")) is null + && !HasFileLevelNameBelow (AlbumLevel, "ARTIST") && !SameValues (values, All ("ARTIST")); + + bool HasFileLevelNameBelow (ulong level, string name) => + FirstBlock (block => block.IsFileLevel && block.Level < level && block.HasName (name)) is not null; + // A missing TargetTypeValue is 50, so this is an explicit or an untargeted album block. static bool IsAlbumTarget (TagBlock block) => block.IsFileLevel && block.Level == AlbumLevel; @@ -1556,6 +1816,14 @@ static bool IsExplicitAlbum (TagBlock block) => static bool HasNumber (TagBlock block, string name) => ParseLeading (Text (block, name)) is not null; + // ffmpeg's untargeted tag holds the track's own values, so a clear of a track-level field removes them there too, + // with their flat sort; an explicit target keeps the specification's inheritance (#211). + void ClearUntargeted (string name, string sort) + { + RemoveWhere (IsUntargeted, name); + RemoveWhere (IsUntargeted, sort); + } + void RemoveWhere (Func match, string name) { foreach (var block in _blocks) { @@ -1821,11 +2089,18 @@ void SetAt (ulong level, string name, string? value) SetAtValues (level, name, new[] { value! }); } - void SetAtValues (ulong level, string name, string[]? values) + void SetAtValues (ulong level, string name, string[]? values) => + SetValuesWhere (block => block.IsFileLevel && block.Level == level, name, values, () => FileBlock (level)); + + /// + /// Replaces the values of in the Tags that match: the default-language ones when there are + /// any, in place, keeping the other languages. With none, the values go in . + /// + void SetValuesWhere (Func match, string name, string[]? values, Func home) { var matches = new List (); foreach (var block in _blocks) { - if (!block.IsFileLevel || block.Level != level) + if (!match (block)) continue; foreach (var tag in block.Tags) { if (tag.Name == name) @@ -1859,19 +2134,19 @@ void SetAtValues (ulong level, string name, string[]? values) } if (primary.Count == 0) { - var block = FileBlock (level); + var block = home (); foreach (var value in incoming) block.Tags.Add (new SimpleTag (name, value)); return; } - var home = BlockContaining (primary[0]); + var holder = BlockContaining (primary[0]); ReplaceTag (primary[0], CopyTag (primary[0], incoming[0])); if (primary.Count > 1) RemoveTags (primary.GetRange (1, primary.Count - 1)); for (var i = 1; i < incoming.Count; i++) { var source = i < primary.Count ? primary[i] : primary[0]; - home.Tags.Add (CopyTag (source, incoming[i])); + holder.Tags.Add (CopyTag (source, incoming[i])); } } diff --git a/src/TagLibSharp2/Mp4/EsdsParser.cs b/src/TagLibSharp2/Mp4/EsdsParser.cs index 7348979a..9fdda1a1 100644 --- a/src/TagLibSharp2/Mp4/EsdsParser.cs +++ b/src/TagLibSharp2/Mp4/EsdsParser.cs @@ -6,7 +6,7 @@ namespace TagLibSharp2.Mp4; /// -/// Parses the Elementary Stream Descriptor (esds) box for AAC audio. +/// Parses the Elementary Stream Descriptor (esds) box of an MPEG-4 audio or visual sample entry. /// /// /// @@ -64,8 +64,22 @@ internal static class EsdsParser if (offset + esDescriptorSize > data.Length) return null; - // Skip ES_ID (2 bytes) and flags (1 byte) + // ES_ID (2 bytes), then streamDependenceFlag, URL_Flag, OCRstreamFlag and streamPriority (1 byte). + // dependsOn_ES_ID (2 bytes), URLlength + URLstring and OCR_ES_Id (2 bytes) follow when their flag + // is set (ISO/IEC 14496-1 §7.2.6.5.1). + if (offset + 3 > data.Length) + return null; + var flags = data[offset + 2]; offset += 3; + if ((flags & 0x80) != 0) + offset += 2; + if ((flags & 0x40) != 0) { + if (offset >= data.Length) + return null; + offset += 1 + data[offset]; + } + if ((flags & 0x20) != 0) + offset += 2; // Find Decoder Config Descriptor if (offset >= data.Length || data[offset] != DecoderConfigDescrTag) @@ -221,7 +235,9 @@ internal struct EsdsConfig /// Gets the object type indication (codec type). ///
/// + /// Values are registered at https://mp4ra.org/registered-types/object-types. /// Common values: + /// - 0x20 = MPEG-4 Visual, 0x6A = MPEG-1 Video, 0x60 to 0x65 = MPEG-2 Video, 0x6C = JPEG, 0x6D = PNG /// - 0x40 = AAC-LC (Low Complexity) /// - 0x66 = AAC Main /// - 0x67 = AAC LC diff --git a/src/TagLibSharp2/Mp4/Mp4AudioCodec.cs b/src/TagLibSharp2/Mp4/Mp4AudioCodec.cs index aca904c1..eb5bc0c2 100644 --- a/src/TagLibSharp2/Mp4/Mp4AudioCodec.cs +++ b/src/TagLibSharp2/Mp4/Mp4AudioCodec.cs @@ -36,11 +36,12 @@ public enum Mp4AudioCodec Alac, /// - /// MP3 audio in MP4 container. + /// MPEG-1 or MPEG-2 audio (MP3 and its Layer I and II forms) in an MP4 or QuickTime container. /// /// - /// 4CC: "mp4a" with object type 0x6B (MPEG-1 Layer 3). - /// Less common in MP4 containers. + /// 4CC: "mp4a" with object type 0x6B (ISO/IEC 11172-3) or 0x69 (ISO/IEC 13818-3), or QuickTime's ".mp3". + /// The object types cover every layer; names the layer of the first + /// frame, "MP3" for Layer III and, for example, "MPEG-1 Layer II". /// Mp3, diff --git a/src/TagLibSharp2/Mp4/Mp4ChapterCodec.cs b/src/TagLibSharp2/Mp4/Mp4ChapterCodec.cs index dd627188..80fcf8bc 100644 --- a/src/TagLibSharp2/Mp4/Mp4ChapterCodec.cs +++ b/src/TagLibSharp2/Mp4/Mp4ChapterCodec.cs @@ -2302,7 +2302,8 @@ static uint ReadTimescale (ReadOnlySpan header) static bool IsAudioOrVideo (Mp4Box trak) => HandlerType (trak) is "soun" or "vide"; - static string HandlerType (Mp4Box trak) + /// The handler_type of the trak's mdia/hdlr (§8.4.3): the 4 bytes at payload offset 8, or empty. + internal static string HandlerType (Mp4Box trak) { var hdlr = Payload (trak.FindChild ("mdia")?.FindChild ("hdlr")); if (hdlr.Length < 12) diff --git a/src/TagLibSharp2/Mp4/Mp4File.cs b/src/TagLibSharp2/Mp4/Mp4File.cs index 0525f4fb..65110c3b 100644 --- a/src/TagLibSharp2/Mp4/Mp4File.cs +++ b/src/TagLibSharp2/Mp4/Mp4File.cs @@ -3,6 +3,7 @@ using System.Buffers.Binary; using TagLibSharp2.Core; +using TagLibSharp2.Mpeg; namespace TagLibSharp2.Mp4; @@ -84,6 +85,11 @@ internal void MarkPicturesSkipped () ///
public AudioProperties Properties { get; } + /// + /// Gets the video properties when the file has a video track. + /// + public VideoProperties? VideoProperties { get; private set; } + /// /// Gets the audio codec used in this file. /// @@ -103,19 +109,25 @@ internal void MarkPicturesSkipped () public TimeSpan Duration => Properties.Duration; /// - Tag? IMediaFile.Tag => Tag; + /// + /// . A file with no ilst has a view whose first write creates the tag, and a write that + /// leaves that tag empty removes it again, so a save writes no metadata. Reading the view creates nothing. + /// + Tag? IMediaFile.Tag => _disposed ? null : CombinedTag.SingleOrView (Tag, () => Tag, + _creation ??= new TagCreation (() => new Mp4Tag (), tag => Tag = (Mp4Tag?)tag)); - /// - IMediaProperties? IMediaFile.AudioProperties => Properties; + TagCreation? _creation; /// - VideoProperties? IMediaFile.VideoProperties => null; + IMediaProperties? IMediaFile.AudioProperties => Properties; /// ImageProperties? IMediaFile.ImageProperties => null; /// - MediaTypes IMediaFile.MediaTypes => Properties.IsValid ? MediaTypes.Audio : MediaTypes.None; + MediaTypes IMediaFile.MediaTypes => + (Properties.IsValid ? MediaTypes.Audio : MediaTypes.None) + | (VideoProperties is { IsValid: true } ? MediaTypes.Video : MediaTypes.None); /// public MediaFormat Format => MediaFormat.Mp4; @@ -907,15 +919,18 @@ static Mp4FileReadResult Read (ReadOnlySpan data, Stream? sampleSource, Li if (moov is null) return Mp4FileReadResult.Failure ("Invalid MP4 file: missing moov box"); - // Extract audio properties from moov/trak/mdia - var (properties, audioCodec) = ExtractAudioProperties (moov); + // Extract audio and video properties from moov/trak/mdia. A video sample entry is not audio. + var (properties, audioCodec, video, firstChunk) = ExtractTrackProperties (moov); + if (firstChunk is long chunk && MpegCodecName (ReadAt (data, sampleSource, chunk, MpegFrame.HeaderSize)) is string mpeg) + properties = properties with { Codec = mpeg }; // Extract metadata from moov/udta/meta/ilst or moov/meta/ilst var (tag, placement) = ExtractMetadata (moov); var file = new Mp4File (tag, properties, audioCodec) { FileType = fileType, - MetaPlacement = placement + MetaPlacement = placement, + VideoProperties = video }; file._chapters = sampleSource is null ? Mp4ChapterCodec.Read (moov, fragments, data, properties.Duration) @@ -969,7 +984,11 @@ static string ExtractFileType (Mp4Box ftypBox) return ftypBox.Data.Slice (0, 4).ToStringLatin1 ().TrimEnd (); } - static (AudioProperties, Mp4AudioCodec) ExtractAudioProperties (Mp4Box moov) + /// + /// The movie's audio and video properties and its audio codec, and for MPEG audio the file offset of the sound + /// track's first chunk, where the frame that names its layer starts (). + /// + static (AudioProperties Audio, Mp4AudioCodec Codec, VideoProperties? Video, long? FirstChunk) ExtractTrackProperties (Mp4Box moov) { // First try to get duration from mvhd (movie header) for overall duration uint movieTimescale = 0; @@ -992,14 +1011,38 @@ static string ExtractFileType (Mp4Box ftypBox) } } - // Navigate to moov/trak/mdia for track info - var trak = moov.FindChild ("trak"); - if (trak is null) - return (AudioProperties.Empty, Mp4AudioCodec.Unknown); + // ISO/IEC 14496-12 handler_type: "soun" is audio, "vide" is video. A visual sample + // entry stores width and height where an audio entry stores the sample rate, so a + // video track must not be parsed as audio. A track another track names in a tref/chap + // (§8.3.3) is chapter media, such as Apple's chapter images, not the movie's video. + var durationSeconds = movieTimescale > 0 ? (double)movieDuration / movieTimescale : 0; + var chapterMedia = new HashSet (Mp4ChapterCodec.FindChapterTracks (moov, textOnly: false).Select (track => track.Trak)); + Mp4Box? sound = null; + Mp4Box? picture = null; + foreach (var child in moov.Children) { + if (child.Type != "trak" || chapterMedia.Contains (child)) + continue; + var handler = Mp4ChapterCodec.HandlerType (child); + var fourcc = SampleFourCc (child); + // A visual sample entry is video even when the handler is missing or is not "vide". + if (picture is null && (handler == "vide" || IsVisualSample (fourcc))) + picture = child; + else if (sound is null && (handler == "soun" || IsAudioSample (fourcc))) + sound = child; + } + + var video = picture is null ? (VideoProperties?)null : ReadVideoTrack (picture, durationSeconds); + if (sound is null && picture is null) + sound = moov.FindChild ("trak"); + if (sound is null) { + var durationOnly = Mp4AudioPropertiesParser.FromSeconds (durationSeconds); + return (new AudioProperties (durationOnly, 0, 0, 0, 0, null), Mp4AudioCodec.Unknown, video, null); + } + var trak = sound; var mdia = trak.FindChild ("mdia"); if (mdia is null) - return (AudioProperties.Empty, Mp4AudioCodec.Unknown); + return (AudioProperties.Empty, Mp4AudioCodec.Unknown, video, null); // Parse mdhd for track-level timescale (used for sample rate if not found in stsd) uint trackTimescale = movieTimescale; @@ -1036,7 +1079,9 @@ static string ExtractFileType (Mp4Box ftypBox) var codecType = entryData.Slice (4, 4).ToStringLatin1 (); codec = codecType switch { // Audible .aax stores AAC in an "aavd" entry: the mp4a layout, esds included, with encrypted samples. - "mp4a" or "aavd" => Mp4AudioCodec.Aac, + "mp4a" or "aavd" => AudioObjectType (EsdsObjectType (entryData, AudioBoxesOffset (entryData))), + // QuickTime's MPEG audio sound description (QTFF, Sound sample descriptions), which ffmpeg writes in .mov. + ".mp3" => Mp4AudioCodec.Mp3, "alac" => Mp4AudioCodec.Alac, "fLaC" => Mp4AudioCodec.Flac, "Opus" => Mp4AudioCodec.Opus, @@ -1074,8 +1119,9 @@ static string ExtractFileType (Mp4Box ftypBox) // Parse codec-specific extensions for bitrate var sampleEntrySize = entryData.ToUInt32BE (0); - if (sampleEntrySize > 36 && entryData.Length > 36) { - bitrate = ExtractBitrateFromCodecBox (entryData.Slice (36), codec); + var boxes = AudioBoxesOffset (entryData); + if (sampleEntrySize > boxes && entryData.Length > boxes) { + bitrate = ExtractBitrateFromCodecBox (entryData.Slice (boxes), codec); } } } @@ -1084,12 +1130,11 @@ static string ExtractFileType (Mp4Box ftypBox) if (sampleRate == 0 && trackTimescale > 0) sampleRate = (int)trackTimescale; - // Calculate duration from movie header - var durationSeconds = movieTimescale > 0 ? (double)movieDuration / movieTimescale : 0; var audioDuration = Mp4AudioPropertiesParser.FromSeconds (durationSeconds); var codecName = codec switch { Mp4AudioCodec.Aac => "AAC", + Mp4AudioCodec.Mp3 => "MP3", Mp4AudioCodec.Alac => "ALAC", Mp4AudioCodec.Flac => "FLAC", Mp4AudioCodec.Opus => "Opus", @@ -1099,93 +1144,198 @@ static string ExtractFileType (Mp4Box ftypBox) }; var properties = new AudioProperties (audioDuration, bitrate, sampleRate, bitsPerSample, channels, codecName); - return (properties, codec); + return (properties, codec, video, codec == Mp4AudioCodec.Mp3 ? FirstChunkOffset (stbl) : null); } - /// - /// Extracts bitrate from codec-specific boxes (esds for AAC, alac for ALAC). - /// - static int ExtractBitrateFromCodecBox (BinaryData codecExtensions, Mp4AudioCodec codec) + // The first sample entry's type: stsd is a FullBox with a 4-byte entry_count, then entries + // that start with their size and type (ISO/IEC 14496-12 §8.5.2). + static string? SampleFourCc (Mp4Box trak) { - if (codecExtensions.Length < 8) - return 0; - - // Look for nested boxes within the sample entry extensions - var offset = 0; - while (offset + 8 <= codecExtensions.Length) { - var boxSize = codecExtensions.ToUInt32BE (offset); - if (boxSize < 8 || boxSize > codecExtensions.Length - offset) - break; + var stsd = trak.FindChild ("mdia")?.FindChild ("minf")?.FindChild ("stbl")?.FindChild ("stsd"); + if (stsd is null || stsd.Data.Length < 16) + return null; + return stsd.Data.Slice (12, 4).ToStringLatin1 (); + } - var boxType = codecExtensions.Slice (offset + 4, 4).ToStringLatin1 (); + static bool IsVisualSample (string? fourcc) => fourcc is "avc1" or "avc3" or "hvc1" or "hev1" or "mp4v" or "vp09" or "av01"; - if (boxType == "esds" && codec == Mp4AudioCodec.Aac) { - // esds box: version(1) + flags(3) + ES_Descriptor - // Parse ES_Descriptor to find DecoderConfigDescriptor with bitrate - return ParseEsdsBitrate (codecExtensions.Slice (offset + 8, (int)boxSize - 8)); - } + static bool IsAudioSample (string? fourcc) => fourcc is "mp4a" or "aavd" or ".mp3" or "alac" or "fLaC" or "Opus" or "ac-3" or "ec-3"; - offset += (int)boxSize; - } + // The file offset of a track's first chunk: the first stco or co64 entry (ISO/IEC 14496-12 §8.7.5). + static long? FirstChunkOffset (Mp4Box? stbl) + { + if (stbl?.FindChild ("co64") is { } co64) + return co64.Data.Length >= 16 && co64.Data.ToUInt32BE (4) > 0 ? (long?)Math.Min (co64.Data.ToUInt64BE (8), long.MaxValue) : null; + if (stbl?.FindChild ("stco") is { } stco) + return stco.Data.Length >= 12 && stco.Data.ToUInt32BE (4) > 0 ? stco.Data.ToUInt32BE (8) : null; + return null; + } - return 0; + // count bytes at a file offset: from data, the whole file, unless sampleSource is set, when data holds only the + // boxes before and after mdat. Null when the file is shorter. + static byte[]? ReadAt (ReadOnlySpan data, Stream? sampleSource, long offset, int count) + { + if (sampleSource is null) + return offset >= 0 && offset <= data.Length - count ? data.Slice ((int)offset, count).ToArray () : null; + if (offset < 0 || offset > sampleSource.Length - count) + return null; + sampleSource.Position = offset; + var bytes = StreamBytes.ReadAtMost (sampleSource, count); + return bytes.Length == count ? bytes : null; } /// - /// Parses bitrate from esds (Elementary Stream Descriptor) box. + /// The codec name of MPEG audio, from the layer in its first frame's header (ISO/IEC 11172-3 §2.4.2.3), as MP3, + /// AVI and MPEG-PS files name it (): object types 0x6B and 0x69 and + /// QuickTime's .mp3 hold MPEG audio of any layer, and MediaInfo names the layer the same way. Null when the chunk + /// does not start with a frame header, which leaves "MP3". /// - static int ParseEsdsBitrate (BinaryData esdsData) + static string? MpegCodecName (byte[]? header) => + header is not null && MpegFrame.TryParse (header, out var frame) && frame is not null + ? MpegAudioProperties.CodecName (frame.Version, frame.Layer) + : null; + + /// + /// The clockwise rotation in the tkhd matrix, in degrees from 0 to 359. The matrix is {a, b, u, c, d, v, x, y, w} + /// at payload offset 40 (version 0) or 52 (version 1), each term 16.16 except u, v and w (ISO/IEC 14496-12 + /// §8.3.2.3). A point (p, q) is shown at (a·p + c·q + x, b·p + d·q + y), with q growing downwards (§6.2.2), so a + /// clockwise turn by θ is a = d = cos θ and b = −c = sin θ, and θ = atan2 (b, a). Any other matrix mirrors or + /// skews the picture and has no rotation: 0. + /// + static int MatrixRotation (Mp4Box trak) { - if (esdsData.Length < 12) + var tkhd = trak.FindChild ("tkhd"); + if (tkhd is null || tkhd.Data.Length < 4) return 0; - - // Skip version(1) + flags(3) - var offset = 4; - - // ES_Descriptor starts with tag 0x03 - if (offset >= esdsData.Length || esdsData[offset] != 0x03) + var at = tkhd.Data[0] == 1 ? 52 : 40; + if (tkhd.Data.Length < at + 20) return 0; - offset++; - - // Skip size (variable length, typically 1 byte for small descriptors) - offset += GetDescriptorSizeLength (esdsData.Slice (offset)); - if (offset + 3 > esdsData.Length) + long a = (int)tkhd.Data.ToUInt32BE (at); + long b = (int)tkhd.Data.ToUInt32BE (at + 4); + long c = (int)tkhd.Data.ToUInt32BE (at + 12); + long d = (int)tkhd.Data.ToUInt32BE (at + 16); + if (a != d || b != -c) return 0; + var degrees = (int)Math.Round (Math.Atan2 (b, a) * 180 / Math.PI); + return (degrees + 360) % 360; + } + + // VisualSampleEntry: width and height are the 16-bit fields at offsets 32 and 34 of the sample + // entry (ISO/IEC 14496-12 §12.1.3), the coded size in pixels, as MPEG-PS, AVI and Matroska report + // theirs. The tkhd matrix is returned as the rotation, not applied, and the pixel aspect ratio is + // not applied. Those bytes are the audio sample rate when the entry is an AudioSampleEntry. + static VideoProperties ReadVideoTrack (Mp4Box trak, double durationSeconds) + { + var duration = Mp4AudioPropertiesParser.FromSeconds (durationSeconds); + var stsd = trak.FindChild ("mdia")?.FindChild ("minf")?.FindChild ("stbl")?.FindChild ("stsd"); + if (stsd is null || stsd.Data.Length < 8 + 36) + return new VideoProperties (duration, 0, 0, 0, 0, null); + var entry = stsd.Data.Slice (8); + if (entry.Length < 36) + return new VideoProperties (duration, 0, 0, 0, 0, null); + var fourcc = entry.Slice (4, 4).ToStringLatin1 (); + var width = entry.ToUInt16BE (32); + var height = entry.ToUInt16BE (34); + var codec = fourcc switch { + "avc1" or "avc3" => "H.264", + "hvc1" or "hev1" => "HEVC", + "mp4v" => VisualObjectType (EsdsObjectType (entry, VisualBoxesOffset)), + "jpeg" => "JPEG", + // Apple ProRes 422 (Proxy, LT, standard, HQ) and 4444 (XQ) (QTFF, Video sample description codecs). + "apco" or "apcs" or "apcn" or "apch" or "ap4h" or "ap4x" => "ProRes", + "s263" or "h263" => "H.263", + "vp09" => "VP9", + "av01" => "AV1", + _ => fourcc + }; + return new VideoProperties (duration, width, height, 0, 0, codec) { Rotation = MatrixRotation (trak) }; + } - // ES_ID (2 bytes) + flags (1 byte) - offset += 3; + // A VisualSampleEntry's boxes follow its 8-byte header, 8 bytes of SampleEntry and 70 bytes of VisualSampleEntry + // fields (ISO/IEC 14496-12 §12.1.3). + const int VisualBoxesOffset = 86; - // DecoderConfigDescriptor tag 0x04 - if (offset >= esdsData.Length || esdsData[offset] != 0x04) - return 0; - offset++; + /// + /// Where an AudioSampleEntry's boxes start: after its 8-byte header, 8 bytes of SampleEntry and 20 bytes of + /// AudioSampleEntry fields (ISO/IEC 14496-12 §12.2.3), and after the 16 or 36 more bytes a QuickTime sound + /// description of version 1 or 2 has, whose version is the first 2 of the reserved bytes (QTFF, Sound sample + /// descriptions). + /// + static int AudioBoxesOffset (BinaryData entry) => (entry.Length >= 18 ? entry.ToUInt16BE (16) : 0) switch { + 1 => 36 + 16, + 2 => 36 + 36, + _ => 36 + }; - // Skip size - offset += GetDescriptorSizeLength (esdsData.Slice (offset)); - if (offset + 13 > esdsData.Length) - return 0; + /// + /// The codec an mp4a objectTypeIndication names (https://mp4ra.org/registered-types/object-types): 0x6B and 0x69 + /// are MPEG audio (ISO/IEC 11172-3 and 13818-3), which ffprobe reads as mp3. AAC, what mp4a is for, is also the + /// answer when there is no esds or the value is another one. + /// + static Mp4AudioCodec AudioObjectType (byte? objectType) => + objectType is 0x6B or 0x69 ? Mp4AudioCodec.Mp3 : Mp4AudioCodec.Aac; - // objectTypeIndication (1) + streamType (1) + bufferSizeDB (3) + maxBitrate (4) + avgBitrate (4) - // Skip to avgBitrate at offset + 1 + 1 + 3 + 4 = 9 - var avgBitrate = esdsData.ToUInt32BE (offset + 9); + /// + /// The objectTypeIndication of the esds box among a sample entry's boxes, which start at , + /// or null. mp4v and mp4a carry an esds there (ISO/IEC 14496-14 §5.6). + /// + static byte? EsdsObjectType (BinaryData entry, int boxes) + { + var size = (int)Math.Min (entry.ToUInt32BE (0), (uint)entry.Length); + if (size <= boxes) + return null; + foreach (var box in Mp4BoxParser.ParseChildren (entry.Slice (boxes, size - boxes).Span)) { + if (box.Type == "esds" && box.Data.Length > 4) + return EsdsParser.Parse (box.Data.Span.Slice (4))?.ObjectTypeIndication; + } - // Convert from bits/second to kbits/second - return (int)(avgBitrate / 1000); + return null; } /// - /// Gets the length of a descriptor size field (1-4 bytes, expandable). + /// The codec an mp4v objectTypeIndication names (https://mp4ra.org/registered-types/object-types). MPEG-4 Visual + /// (0x20), what the mp4v entry is for, is also the answer when there is no esds or the value is not a video one. + /// + static string VisualObjectType (byte? objectType) => objectType switch { + 0x21 => "H.264", + 0x23 => "HEVC", + >= 0x60 and <= 0x65 => "MPEG-2 Video", + 0x6A => "MPEG-1 Video", + 0x6C => "JPEG", + 0x6D => "PNG", + 0x6E => "JPEG 2000", + _ => "MPEG-4" + }; + + /// + /// Extracts bitrate from codec-specific boxes (esds for AAC, alac for ALAC). /// - static int GetDescriptorSizeLength (BinaryData data) + static int ExtractBitrateFromCodecBox (BinaryData codecExtensions, Mp4AudioCodec codec) { - // Expandable size encoding: high bit = more bytes follow - var length = 0; - for (int i = 0; i < 4 && i < data.Length; i++) { - length++; - if ((data[i] & 0x80) == 0) + if (codecExtensions.Length < 8) + return 0; + + // Look for nested boxes within the sample entry extensions + var offset = 0; + while (offset + 8 <= codecExtensions.Length) { + var boxSize = codecExtensions.ToUInt32BE (offset); + if (boxSize < 8 || boxSize > codecExtensions.Length - offset) break; + + var boxType = codecExtensions.Slice (offset + 4, 4).ToStringLatin1 (); + + if (boxType == "esds" && codec is Mp4AudioCodec.Aac or Mp4AudioCodec.Mp3) { + // esds box: version(1) + flags(3) + ES_Descriptor, whose DecoderConfigDescriptor holds avgBitrate. + if (boxSize < 12) + return 0; + var esds = EsdsParser.Parse (codecExtensions.Slice (offset + 12, (int)boxSize - 12).Span); + return esds is { } config ? (int)(config.AvgBitrate / 1000) : 0; + } + + offset += (int)boxSize; } - return length; + + return 0; } static (Mp4Tag? Tag, Mp4MetaPlacement Placement) ExtractMetadata (Mp4Box moov) @@ -2379,6 +2529,7 @@ public bool Moves (uint chunk) // Null removes all metadata of every meta, the same as Clear on the tag read. Mp4Tag? TagToSave (Mp4Box originalMoov) { + _creation?.Settle ([Tag]); if (Tag is not null && ReferenceEquals (Tag, _readTag)) return Tag; @@ -2816,6 +2967,7 @@ static BinaryData WrapBox (string type, BinaryData body) /// A result indicating success or failure. public FileWriteResult SaveToFile (string path, ReadOnlySpan originalData, IFileSystem? fileSystem = null) { + _creation?.Settle ([Tag]); if (PictureSkip.Refuse (this) is { } denied) return denied; @@ -2841,6 +2993,7 @@ public Task SaveToFileAsync ( IFileSystem? fileSystem = null, CancellationToken cancellationToken = default) { + _creation?.Settle ([Tag]); if (PictureSkip.Refuse (this) is { } denied) return Task.FromResult (denied); @@ -2865,6 +3018,7 @@ public Task SaveToFileAsync ( /// A result indicating success or failure. public FileWriteResult SaveToFile (string path, IFileSystem? fileSystem = null) { + _creation?.Settle ([Tag]); if (PictureSkip.Refuse (this) is { } denied) return denied; if (string.IsNullOrEmpty (SourcePath)) @@ -2886,6 +3040,7 @@ public FileWriteResult SaveToFile (string path, IFileSystem? fileSystem = null) /// A result indicating success or failure. public FileWriteResult SaveToFile (IFileSystem? fileSystem = null) { + _creation?.Settle ([Tag]); if (PictureSkip.Refuse (this) is { } denied) return denied; if (string.IsNullOrEmpty (SourcePath)) @@ -2906,6 +3061,7 @@ public Task SaveToFileAsync ( IFileSystem? fileSystem = null, CancellationToken cancellationToken = default) { + _creation?.Settle ([Tag]); if (PictureSkip.Refuse (this) is { } denied) return Task.FromResult (denied); if (string.IsNullOrEmpty (SourcePath)) @@ -3229,6 +3385,7 @@ public Task SaveToFileAsync ( IFileSystem? fileSystem = null, CancellationToken cancellationToken = default) { + _creation?.Settle ([Tag]); if (PictureSkip.Refuse (this) is { } denied) return Task.FromResult (denied); if (string.IsNullOrEmpty (SourcePath)) diff --git a/src/TagLibSharp2/Mp4/Mp4Picture.cs b/src/TagLibSharp2/Mp4/Mp4Picture.cs index b754997b..7f20cb78 100644 --- a/src/TagLibSharp2/Mp4/Mp4Picture.cs +++ b/src/TagLibSharp2/Mp4/Mp4Picture.cs @@ -19,8 +19,21 @@ public sealed class Mp4Picture : IPicture /// /// - /// MP4 files don't distinguish between different picture types in the same way as ID3v2/FLAC. - /// All images in the covr atom are typically FrontCover. + /// + /// QuickTime's covr data type is the image format (13 JPEG, 14 PNG), not a picture role + /// (https://developer.apple.com/documentation/quicktime-file-format/well-known_types), and the format has + /// no field for a role. This library keeps a role other than front cover in the data atom's locale + /// indicator, a private convention. The locale is a 16-bit country (high half) and a 16-bit language + /// (low half); 0 means every locale (https://developer.apple.com/documentation/quicktime-file-format/locale_indicator). + /// A role is written as the top byte, one higher than the ID3 picture type (Other is 1, PublisherLogo 21), + /// with the other three bytes 0, so Other is distinct from the zero locale iTunes writes for a front cover. + /// + /// + /// That top byte is below every ISO 3166 letter, so the country it makes is not a real one, and no real + /// country or language reads as a role. A locale of zero, or any other locale, is read as front cover. + /// AVFoundation, QuickLook, ffprobe, ExifTool and MediaInfo show such a picture as an ordinary cover and + /// do not reorder it; a reader that matched the locale against the user's country would skip it. + /// /// public PictureType PictureType { get; } @@ -87,7 +100,21 @@ internal static Mp4Picture FromDataAtom (Mp4DataAtom dataAtom) _ => "image/unknown" }; - return new Mp4Picture (mimeType, PictureType.FrontCover, string.Empty, dataAtom.Data, dataAtom.TypeIndicator, dataAtom.Locale); + return new Mp4Picture (mimeType, RoleFromLocale (dataAtom.Locale), string.Empty, dataAtom.Data, dataAtom.TypeIndicator, dataAtom.Locale); + } + + // Locale 0 is the QuickTime "all locales" value and means front cover. A role we wrote occupies + // only the top byte (the first byte of the country) and is one higher than the picture type, so + // Other is 1 and not 0. Any other locale is left as front cover rather than guessed. + static PictureType RoleFromLocale (uint locale) + { + if (locale == 0 || (locale & 0x00FFFFFF) != 0) + return PictureType.FrontCover; + var stored = (int)(locale >> 24) - 1; + if (stored < 0) + return PictureType.FrontCover; + var role = (PictureType)stored; + return PictureTypes.IsDefined (role) ? role : PictureType.FrontCover; } /// @@ -102,9 +129,15 @@ internal static Mp4Picture FromDataAtom (Mp4DataAtom dataAtom) internal int RenderTypeIndicator => _parsedTypeIndicator ?? IdentifyType (PictureData.Span, MimeType); /// - /// Locale indicator written for this picture: the parsed one, or 0 (every locale) for a new picture. + /// Locale indicator written for this picture. A picture read from a file keeps the locale it had. + /// A new front cover uses 0. Any other new role is stored one higher than the picture type in + /// the top byte (see ), so a later read can tell Other from a front cover. + /// The image type stays in the data type indicator. /// - internal uint RenderLocale => _parsedLocale; + internal uint RenderLocale => + _parsedTypeIndicator is not null || PictureType == PictureType.FrontCover + ? _parsedLocale + : (uint)((byte)PictureType + 1) << 24; static int IdentifyType (ReadOnlySpan data, string mimeType) { diff --git a/src/TagLibSharp2/Mp4/Mp4Tag.cs b/src/TagLibSharp2/Mp4/Mp4Tag.cs index 5ee8bca6..60b77aa0 100644 --- a/src/TagLibSharp2/Mp4/Mp4Tag.cs +++ b/src/TagLibSharp2/Mp4/Mp4Tag.cs @@ -1001,6 +1001,10 @@ public override bool RemoveCustomField (string name) return held; } + /// + internal override bool StoresNothing => + _atoms.Count == 0 && _pictures.Count == 0 && _freeform.Count == 0 && _preservedAtoms.Count == 0 && _movieItems.Count == 0; + /// /// /// Removes all metadata the tag holds: every field, every item it was read from, and every item diff --git a/src/TagLibSharp2/Mpeg/Mp3File.cs b/src/TagLibSharp2/Mpeg/Mp3File.cs index 4dad3813..b9ebd988 100644 --- a/src/TagLibSharp2/Mpeg/Mp3File.cs +++ b/src/TagLibSharp2/Mpeg/Mp3File.cs @@ -45,6 +45,7 @@ internal void MarkPicturesSkipped () const int Id3v1Size = 128; bool _disposed; + TagCreation? _creation; /// /// Gets the source file path if the file was read from disk. @@ -117,13 +118,15 @@ internal void RememberSource (string path, IFileSystem? fileSystem) /// /// - /// Returns a composing the ID3v2 and ID3v1 tags when at - /// least one is present. ID3v2 takes priority; ID3v1 supplies fallback values for - /// fields not set in v2 (and receives mirrored writes so both tags stay in sync - /// on save). Returns null when neither tag is present. + /// A over the ID3v2 and ID3v1 tags. ID3v2 takes priority; ID3v1 + /// supplies fallback values and receives mirrored writes. Reading the view does not create a + /// stored tag. The first write on a tagless file creates an ID3v2 tag, and a write that leaves + /// that tag empty removes it again, so a save writes no empty tag. /// - public Tag? Tag => - (Id3v2Tag is null && Id3v1Tag is null) ? null : new CombinedTag (Id3v2Tag, Id3v1Tag); + // Every read gets a new view. Two views then share the stored tags, which is what a copy from one view onto the + // other relies on, and the tag creation, so a tag one view created is dropped when another view empties it. + public Tag? Tag => _disposed ? null : CombinedTag.Over (() => [Id3v2Tag, Id3v1Tag], + _creation ??= new TagCreation (() => new Id3v2Tag (), tag => Id3v2Tag = (Id3v2Tag?)tag)); /// IMediaProperties? IMediaFile.AudioProperties => Properties; @@ -753,6 +756,9 @@ Tag EnsureTag () return Tag!; } + // ID3v1 text is Latin-1: a value it cannot hold that no other tag holds fails the save (Id3v1Tag.Latin1Refusal). + string? Id3v1Refusal () => Id3v1Tag?.Latin1Refusal ("MP3", nameof (Mp3File), Id3v2Tag); + /// /// Renders the complete MP3 file with updated tags. /// @@ -760,8 +766,12 @@ Tag EnsureTag () /// The original file data. /// /// The rendered file data. + /// The ID3v1 tag holds text Latin-1 cannot hold that no other tag of the file holds. public BinaryData Render (ReadOnlySpan originalData) { + _creation?.Settle ([Id3v2Tag, Id3v1Tag]); + if (Id3v1Refusal () is string refusal) + throw new InvalidOperationException (refusal); // Calculate audio data bounds var audioStart = Id3v2Size; var audioEnd = HasId3v1Tag @@ -805,8 +815,11 @@ public BinaryData Render (ReadOnlySpan originalData) /// A result indicating success or failure. public FileWriteResult SaveToFile (string path, ReadOnlySpan originalData, IFileSystem? fileSystem = null) { + _creation?.Settle ([Id3v2Tag, Id3v1Tag]); if (PictureSkip.Refuse (this) is { } denied) return denied; + if (Id3v1Refusal () is string refusal) + return FileWriteResult.Failure (refusal); if (Source.Refuse ("MP3", originalData.Length) is { } mismatch) return mismatch; @@ -835,8 +848,11 @@ public Task SaveToFileAsync ( IFileSystem? fileSystem = null, CancellationToken cancellationToken = default) { + _creation?.Settle ([Id3v2Tag, Id3v1Tag]); if (PictureSkip.Refuse (this) is { } denied) return Task.FromResult (denied); + if (Id3v1Refusal () is string refusal) + return Task.FromResult (FileWriteResult.Failure (refusal)); if (Source.Refuse ("MP3", originalData.Length) is { } mismatch) return Task.FromResult (mismatch); @@ -867,8 +883,11 @@ public Task SaveToFileAsync ( IFileSystem? fileSystem = null, CancellationToken cancellationToken = default) { + _creation?.Settle ([Id3v2Tag, Id3v1Tag]); if (PictureSkip.Refuse (this) is { } denied) return Task.FromResult (denied); + if (Id3v1Refusal () is string refusal) + return Task.FromResult (FileWriteResult.Failure (refusal)); if (string.IsNullOrEmpty (SourcePath)) return Task.FromResult (FileWriteResult.Failure ("No source path available. File was not read from disk.")); @@ -890,8 +909,11 @@ public Task SaveToFileAsync ( IFileSystem? fileSystem = null, CancellationToken cancellationToken = default) { + _creation?.Settle ([Id3v2Tag, Id3v1Tag]); if (PictureSkip.Refuse (this) is { } denied) return Task.FromResult (denied); + if (Id3v1Refusal () is string refusal) + return Task.FromResult (FileWriteResult.Failure (refusal)); if (string.IsNullOrEmpty (SourcePath)) return Task.FromResult (FileWriteResult.Failure ("No source path available. File was not read from disk.")); @@ -910,8 +932,11 @@ public Task SaveToFileAsync ( /// A result indicating success or failure. public FileWriteResult SaveToFile (string path, IFileSystem? fileSystem = null) { + _creation?.Settle ([Id3v2Tag, Id3v1Tag]); if (PictureSkip.Refuse (this) is { } denied) return denied; + if (Id3v1Refusal () is string refusal) + return FileWriteResult.Failure (refusal); if (string.IsNullOrEmpty (SourcePath)) return FileWriteResult.Failure ("No source path available. File was not read from disk."); @@ -980,8 +1005,11 @@ long AudioByteCount (long fileLength) /// A result indicating success or failure. public FileWriteResult SaveToFile (IFileSystem? fileSystem = null) { + _creation?.Settle ([Id3v2Tag, Id3v1Tag]); if (PictureSkip.Refuse (this) is { } denied) return denied; + if (Id3v1Refusal () is string refusal) + return FileWriteResult.Failure (refusal); if (string.IsNullOrEmpty (SourcePath)) return FileWriteResult.Failure ("No source path available. File was not read from disk."); diff --git a/src/TagLibSharp2/Mpeg/MpegPsFile.cs b/src/TagLibSharp2/Mpeg/MpegPsFile.cs index e312f329..c8849f24 100644 --- a/src/TagLibSharp2/Mpeg/MpegPsFile.cs +++ b/src/TagLibSharp2/Mpeg/MpegPsFile.cs @@ -155,6 +155,7 @@ internal void MarkPicturesSkipped () IFileSystem? _sourceFileSystem; bool _disposed; + TagCreation? _creation; // Layout of the file that was read. Render checks the original bytes against it: // [prepended ID3v2][stream][APEv2?][appended ID3v2][APEv2?][ID3v1]. @@ -254,15 +255,19 @@ internal void MarkPicturesSkipped () /// /// Gets a view over the ID3v2 and ID3v1 tags: ID3v2 wins when it has a value, and a write /// goes to every tag in the view. An appended update tag is followed by the prepended tag it - /// updates. Null when the file has neither; call to add one. + /// updates. Reading the view does not create a stored tag. The first write on a tagless file + /// creates an ID3v2 tag, and a write that leaves that tag empty removes it again, so a save + /// writes no empty tag. /// - public Tag? Tag { - get { - if (Id3v2Tag is null && Id3v1Tag is null) - return null; - var earlier = EarlierTag; - return earlier is null ? new CombinedTag (Id3v2Tag, Id3v1Tag) : new CombinedTag (Id3v2Tag, earlier, Id3v1Tag); - } + public Tag? Tag => _disposed ? null : CombinedTag.Over (TagSources, + _creation ??= new TagCreation (() => new Id3v2Tag (), tag => Id3v2Tag = (Id3v2Tag?)tag)); + + Tag?[] TagSources () + { + var earlier = EarlierTag; + return earlier is null + ? new Tag?[] { Id3v2Tag, Id3v1Tag } + : new Tag?[] { Id3v2Tag, earlier, Id3v1Tag }; } /// @@ -741,6 +746,9 @@ static MpegPsFileReadResult WithSource (MpegPsFileReadResult result, string? sou return result; } + // ID3v1 text is Latin-1: a value it cannot hold that no other tag holds fails the save (Id3v1Tag.Latin1Refusal). + string? Id3v1Refusal () => Id3v1Tag?.Latin1Refusal ("MPEG-PS", nameof (MpegPsFile), Id3v2Tag, EarlierTag); + /// /// Renders the file with the current tags around the original stream bytes. /// @@ -748,8 +756,12 @@ static MpegPsFileReadResult WithSource (MpegPsFileReadResult result, string? sou /// The bytes of the file this instance was read from. /// /// The new file bytes, or empty when is not that file. + /// The ID3v1 tag holds text Latin-1 cannot hold that no other tag of the file holds. public BinaryData Render (ReadOnlySpan originalData) { + _creation?.Settle (TagSources ()); + if (Id3v1Refusal () is string refusal) + throw new InvalidOperationException (refusal); if (!SameFile (originalData.Length)) return BinaryData.Empty; if (MpegPsScanner.StreamStart (originalData.Slice (Id3v2Size, (int)Math.Min (64, _streamEnd - Id3v2Size))) < 0) @@ -902,8 +914,11 @@ ReadOnlySpan RenderId3v1 (ReadOnlySpan original) /// Whether the write succeeded. public FileWriteResult SaveToFile (string path, ReadOnlySpan originalData, IFileSystem? fileSystem = null) { + _creation?.Settle (TagSources ()); if (PictureSkip.Refuse (this) is { } denied) return denied; + if (Id3v1Refusal () is string refusal) + return FileWriteResult.Failure (refusal); if (Source.Refuse ("MPEG-PS", originalData.Length) is { } mismatch) return mismatch; @@ -923,8 +938,11 @@ public FileWriteResult SaveToFile (string path, ReadOnlySpan originalData, /// Whether the write succeeded. public FileWriteResult SaveToFile (string path, IFileSystem? fileSystem = null) { + _creation?.Settle (TagSources ()); if (PictureSkip.Refuse (this) is { } denied) return denied; + if (Id3v1Refusal () is string refusal) + return FileWriteResult.Failure (refusal); if (string.IsNullOrEmpty (SourcePath)) return FileWriteResult.Failure ("No source path available. File was not read from disk."); @@ -938,8 +956,11 @@ public FileWriteResult SaveToFile (string path, IFileSystem? fileSystem = null) /// Whether the write succeeded. public FileWriteResult SaveToFile (IFileSystem? fileSystem = null) { + _creation?.Settle (TagSources ()); if (PictureSkip.Refuse (this) is { } denied) return denied; + if (Id3v1Refusal () is string refusal) + return FileWriteResult.Failure (refusal); if (string.IsNullOrEmpty (SourcePath)) return FileWriteResult.Failure ("No source path available. File was not read from disk."); @@ -962,8 +983,11 @@ public Task SaveToFileAsync ( IFileSystem? fileSystem = null, CancellationToken cancellationToken = default) { + _creation?.Settle (TagSources ()); if (PictureSkip.Refuse (this) is { } denied) return Task.FromResult (denied); + if (Id3v1Refusal () is string refusal) + return Task.FromResult (FileWriteResult.Failure (refusal)); if (Source.Refuse ("MPEG-PS", originalData.Length) is { } mismatch) return Task.FromResult (mismatch); @@ -990,8 +1014,11 @@ public Task SaveToFileAsync ( IFileSystem? fileSystem = null, CancellationToken cancellationToken = default) { + _creation?.Settle (TagSources ()); if (PictureSkip.Refuse (this) is { } denied) return Task.FromResult (denied); + if (Id3v1Refusal () is string refusal) + return Task.FromResult (FileWriteResult.Failure (refusal)); if (string.IsNullOrEmpty (SourcePath)) return Task.FromResult (FileWriteResult.Failure ("No source path available. File was not read from disk.")); @@ -1089,8 +1116,11 @@ public Task SaveToFileAsync ( IFileSystem? fileSystem = null, CancellationToken cancellationToken = default) { + _creation?.Settle (TagSources ()); if (PictureSkip.Refuse (this) is { } denied) return Task.FromResult (denied); + if (Id3v1Refusal () is string refusal) + return Task.FromResult (FileWriteResult.Failure (refusal)); if (string.IsNullOrEmpty (SourcePath)) return Task.FromResult (FileWriteResult.Failure ("No source path available. File was not read from disk.")); diff --git a/src/TagLibSharp2/Musepack/MusepackFile.cs b/src/TagLibSharp2/Musepack/MusepackFile.cs index d662c0f9..0daaeda2 100644 --- a/src/TagLibSharp2/Musepack/MusepackFile.cs +++ b/src/TagLibSharp2/Musepack/MusepackFile.cs @@ -146,7 +146,14 @@ private MusepackFile () { } public ApeTag? ApeTag { get; private set; } /// - public Tag? Tag => ApeTag; + /// + /// The APEv2 tag. A file with none has a view whose first write creates one, and a write that leaves that tag + /// empty removes it again, so a save writes no empty tag. Reading the view creates nothing. + /// + public Tag? Tag => _disposed ? null : CombinedTag.SingleOrView (ApeTag, () => ApeTag, + _creation ??= new TagCreation (() => new ApeTag (), tag => ApeTag = (ApeTag?)tag)); + + TagCreation? _creation; /// IMediaProperties? IMediaFile.AudioProperties => Properties; @@ -597,6 +604,7 @@ public void RemoveApeTag () /// public byte[] Render (ReadOnlySpan originalData) { + _creation?.Settle ([ApeTag]); byte[] tagData = ApeTag is null ? [] : ApeTag.Render ().ToArray (); var location = ApeTagLocation.Locate (originalData); return ApeTagLocation.Rewrite (originalData, location, tagData); @@ -653,6 +661,7 @@ public static async Task ReadFromFileAsync ( /// The result of the write operation. public FileWriteResult SaveToFile (string path, ReadOnlySpan originalData, IFileSystem? fileSystem = null) { + _creation?.Settle ([ApeTag]); if (PictureSkip.Refuse (this) is { } denied) return denied; @@ -673,6 +682,7 @@ public FileWriteResult SaveToFile (string path, ReadOnlySpan originalData, /// public FileWriteResult SaveToFile (string path, IFileSystem? fileSystem = null) { + _creation?.Settle ([ApeTag]); if (PictureSkip.Refuse (this) is { } denied) return denied; var fs = fileSystem ?? _sourceFileSystem; @@ -690,6 +700,7 @@ public FileWriteResult SaveToFile (string path, IFileSystem? fileSystem = null) /// public FileWriteResult SaveToFile (IFileSystem? fileSystem = null) { + _creation?.Settle ([ApeTag]); if (PictureSkip.Refuse (this) is { } denied) return denied; if (string.IsNullOrEmpty (SourcePath)) @@ -713,6 +724,7 @@ public async Task SaveToFileAsync ( IFileSystem? fileSystem = null, CancellationToken cancellationToken = default) { + _creation?.Settle ([ApeTag]); if (PictureSkip.Refuse (this) is { } denied) return denied; @@ -737,6 +749,7 @@ public Task SaveToFileAsync ( IFileSystem? fileSystem = null, CancellationToken cancellationToken = default) { + _creation?.Settle ([ApeTag]); if (PictureSkip.Refuse (this) is { } denied) return Task.FromResult (denied); var fs = fileSystem ?? _sourceFileSystem; @@ -756,6 +769,7 @@ public async Task SaveToFileAsync ( IFileSystem? fileSystem = null, CancellationToken cancellationToken = default) { + _creation?.Settle ([ApeTag]); if (PictureSkip.Refuse (this) is { } denied) return denied; if (string.IsNullOrEmpty (SourcePath)) diff --git a/src/TagLibSharp2/README.md b/src/TagLibSharp2/README.md index 221f2ab7..bcf05439 100644 --- a/src/TagLibSharp2/README.md +++ b/src/TagLibSharp2/README.md @@ -16,7 +16,7 @@ A modern .NET library for reading and writing metadata in media files. | Format | Read | Write | Audio Properties | |--------|:----:|:-----:|:----------------:| -| MP3 (ID3v1/ID3v2) | ✅ | ✅ | ✅ | +| MP3 (ID3v1, ID3v1.1, ID3v2.2 read and saved as ID3v2.3, ID3v2.3, ID3v2.4) | ✅ | ✅ | ✅ | | FLAC | ✅ | ✅ | ✅ | | Ogg Vorbis | ✅ | ✅ | ✅ | | Ogg Opus | ✅ | ✅ | ✅ | @@ -35,7 +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 | — | +| JPEG, PNG, GIF, BMP, PCX, Netpbm, TIFF, DNG, SVG | Dimensions; PNG text; GIF comment; JPEG COM and title (XMP `dc:title`, read from `XPTitle` when XMP has none) | Those fields. TIFF, DNG, BMP, PCX, Netpbm, and SVG have no text tag | — | ¹ 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. @@ -75,7 +75,8 @@ var asyncResult = await Mp3File.ReadFromFileAsync("song.mp3"); - **Basic**: Title, Artist, Album, Year, Genre, Track, Comment - **Extended**: AlbumArtist, Composer, DiscNumber, BPM, Conductor, Copyright -- **Pictures**: Album art with multiple picture types (front, back, etc.) +- **ID3**: ID3v1 and ID3v1.1 read and write. ID3v2.2 is read (3-character IDs mapped to their ID3v2.3 names) and saved as ID3v2.3. ID3v2.3 and ID3v2.4 read and write; a new tag is v2.4. Text lists split on NUL only, so `AC/DC` is one performer +- **Pictures**: Album art with multiple picture types (front, back, and the rest). An MP4 `covr` role, including Other, is kept by a private convention in the top byte of the data atom's locale; other tools still show the image as a cover - **ReplayGain**: Track and album gain/peak values - **MusicBrainz**: Track ID, Release ID, Artist ID, and more - **Lyrics**: Multi-language synchronized and unsynchronized lyrics diff --git a/src/TagLibSharp2/Riff/InfoText.cs b/src/TagLibSharp2/Riff/InfoText.cs index e315a9f8..13f40c08 100644 --- a/src/TagLibSharp2/Riff/InfoText.cs +++ b/src/TagLibSharp2/Riff/InfoText.cs @@ -150,6 +150,24 @@ public static bool CanEncode (string value, InfoCharacterSet characterSet) return true; } + /// + /// The value and a NUL terminator as a list with no CSET is read ( with + /// ): Windows-1252 when every character has a byte there and those bytes read back + /// as the value, else UTF-8, which reads back as the value whenever it holds a non-ASCII character. A value Windows-1252 + /// holds can still read back as other text when its bytes are valid UTF-8 (é); that one is written as UTF-8. + /// So any value without a NUL that this reader can return is stored and read back unchanged. + /// + public static byte[] EncodeByReadRule (string value) + { + if (CanEncode (value, InfoCharacterSet.Windows1252)) { + var windows1252 = Encode (value, InfoCharacterSet.Windows1252); + if (Decode (windows1252, InfoCharacterSet.None, out _) == value) + return windows1252; + } + + return Encode (value, InfoCharacterSet.Utf8); + } + /// The value and a NUL terminator in . The value must pass . public static byte[] Encode (string value, InfoCharacterSet characterSet) { @@ -252,9 +270,8 @@ public static string GuessReason (ReadOnlySpan field, InfoCharacterSet cha return $"is in code page {codePage}, which this library does not decode"; } - return codePage < 0 - ? "is not UTF-8 and the file has no CSET, so its code page is only a guess" - : $"is not valid in the declared code page {codePage}"; + // A list with no CSET is never refused (RiffInfoTag.TryRenderAvi writes it by the read rule). + return $"is not valid in the declared code page {codePage}"; } /// The value with control characters (C0, DEL, C1) written as \uXXXX, for a message. diff --git a/src/TagLibSharp2/Riff/RiffInfoTag.cs b/src/TagLibSharp2/Riff/RiffInfoTag.cs index abea160b..21b125f1 100644 --- a/src/TagLibSharp2/Riff/RiffInfoTag.cs +++ b/src/TagLibSharp2/Riff/RiffInfoTag.cs @@ -32,10 +32,13 @@ public class RiffInfoTag : Tag readonly Dictionary _fields = new (StringComparer.OrdinalIgnoreCase); /// - /// The stored bytes of each field, kept by a tag in AVI text mode, and whether they are UTF-8 - /// (so they can share a UTF-8 list). An unchanged field is written back with exactly these bytes. + /// The stored bytes of each field read from a file, and how surely their text is known (whether they are UTF-8, + /// so they can share a UTF-8 list in AVI). An unchanged field is written back with exactly these bytes. /// - readonly Dictionary? _stored; + readonly Dictionary _stored = new (StringComparer.OrdinalIgnoreCase); + + /// True for a tag in AVI text mode; false for WAV, whose changed values are written by the read rule. + readonly bool _avi; /// The code page the file's CSET declared, for a tag in AVI text mode. readonly InfoCharacterSet _characterSet; @@ -44,7 +47,11 @@ public class RiffInfoTag : Tag readonly int _codePage; /// - /// Creates an empty tag whose text is Latin-1, as WAV INFO is read and written. + /// Creates an empty tag as WAV INFO is read and written. reads a field as AVI reads a + /// list with no CSET (): valid UTF-8, as ffmpeg writes it, is UTF-8, and anything else is + /// Windows-1252, as Windows writes it. A changed value is written by the same rule, Windows-1252 when its bytes read + /// back as the value and UTF-8 otherwise, so any text without a NUL reads back unchanged; a field read from a file + /// and not changed keeps its bytes. /// public RiffInfoTag () { @@ -63,14 +70,16 @@ public RiffInfoTag () /// under a CSET of code page 65001: ASCII and UTF-8 values keep their bytes, and a value decoded /// exactly in its declared code page () is written as UTF-8 of the /// same text. A value whose code page is a guess () cannot be - /// rewritten, so refuses instead. + /// rewritten. With no CSET, where each field is read on its own (UTF-8, else Windows-1252), the list then + /// keeps every unchanged value's bytes and writes the changed values by that rule, with no CSET, as WAV INFO + /// does; under a CSET refuses instead. /// /// internal RiffInfoTag (InfoCharacterSet characterSet, int codePage = -1) { _characterSet = characterSet; _codePage = codePage; - _stored = new (StringComparer.OrdinalIgnoreCase); + _avi = true; } /// @@ -260,7 +269,7 @@ public void SetField (string fourCC, string? value) { if (string.IsNullOrEmpty (value)) { _fields.Remove (fourCC); - _stored?.Remove (fourCC); + _stored.Remove (fourCC); } else { #pragma warning disable CS8601 // Possible null reference assignment - checked above _fields[fourCC] = value; @@ -289,23 +298,16 @@ public override IReadOnlyList GetCustomField (string name) /// /// /// Returns false for a name that is not four ASCII characters from 0x20 to 0x7E (a FOURCC, Microsoft - /// RIFF specification, "Chunks") and for more than one value. A WAV INFO list is Latin-1, one byte per - /// character, so text outside ISO-8859-1 is refused there. An AVI INFO list takes any text, as the mapped - /// fields do: the save encodes it in the file's declared code page when every changed value fits, and - /// otherwise makes the list UTF-8 under a CSET of code page 65001 (see ). + /// RIFF specification, "Chunks") and for more than one value. Any text is taken, as the mapped fields take it: a WAV + /// INFO list writes it in Windows-1252 or UTF-8 by the rule it is read with (see ), and an + /// AVI INFO list encodes it in the file's declared code page when every changed value fits, and otherwise makes the + /// list UTF-8 under a CSET of code page 65001 (see ). /// public override bool SetCustomField (string name, params string[] values) { CustomFieldValues.ThrowIfNull (name); if (!IsFourCC (name) || !CustomFieldValues.TryNormalize (values, out var kept) || kept.Count > 1) return false; - if (_stored is null && kept.Count == 1) { - foreach (var c in kept[0]) { - if (c > 0xFF) - return false; - } - } - SetField (name, kept.Count == 0 ? null : kept[0]); return true; } @@ -353,7 +355,7 @@ internal void FillMissingFrom (RiffInfoTag later) if (string.IsNullOrEmpty (value)) continue; SetField (id, value); - if (_stored is not null && later._stored is not null && later._stored.TryGetValue (id, out var stored)) + if (later._stored.TryGetValue (id, out var stored)) _stored[id] = stored; } } @@ -364,7 +366,7 @@ internal void FillMissingFrom (RiffInfoTag later) public override void Clear () { _fields.Clear (); - _stored?.Clear (); + _stored.Clear (); } /// @@ -376,7 +378,8 @@ public override void Clear () /// /// Parses a RIFF INFO tag. A selects AVI text mode (see - /// ); null reads every value as Latin-1, as WAV does. + /// ); null is WAV, whose values are read as AVI reads a list + /// with no CSET. /// internal static RiffInfoTag? Parse (BinaryData data, InfoCharacterSet? characterSet, int codePage = -1) { @@ -408,16 +411,12 @@ public override void Clear () // Read field value (null-terminated string, safe cast after overflow check). // AVI text mode copies the field once: that copy is decoded and kept as the stored bytes. - string value; - if (characterSet is { } set) { - var bytes = span.Slice (offset, (int)fieldSize).ToArray (); - value = InfoText.Decode (bytes, set, out var kind); - tag._stored!.Remove (fieldId); - if (value.Length > 0) - tag._stored[fieldId] = (value, bytes, kind); - } else { - value = data.Slice (offset, (int)fieldSize).ToStringLatin1NullTerminated (); - } + // The field is copied once: that copy is decoded and kept as the stored bytes. + var bytes = span.Slice (offset, (int)fieldSize).ToArray (); + var value = InfoText.Decode (bytes, characterSet ?? InfoCharacterSet.None, out var kind); + tag._stored.Remove (fieldId); + if (value.Length > 0) + tag._stored[fieldId] = (value, bytes, kind); tag._fields[fieldId] = value; @@ -455,20 +454,20 @@ internal bool SameFieldsAs (RiffInfoTag? other) } bool IsUnchanged (string id, string value, out (string Value, byte[] Bytes, InfoTextKind Kind) stored) => - _stored!.TryGetValue (id, out stored) && stored.Value == value; + _stored.TryGetValue (id, out stored) && stored.Value == value; /// /// Renders the list in AVI text mode, keeping the invariant on . /// is true when the list became UTF-8 and needs a CSET of code page /// 65001 in place of the file's own CSET. Returns false, with , when a changed - /// value does not fit the file's code page and an unchanged value's code page is a guess. + /// value does not fit the file's declared code page and an unchanged value's code page is a guess. /// internal bool TryRenderAvi (out BinaryData list, out bool declareUtf8, out string? error) { list = BinaryData.Empty; declareUtf8 = false; error = null; - if (_stored is null) + if (!_avi) throw new InvalidOperationException ("Not an AVI text mode tag."); var target = _characterSet; @@ -484,6 +483,15 @@ internal bool TryRenderAvi (out BinaryData list, out bool declareUtf8, out strin if (declareUtf8) { foreach (var kvp in _fields) { if (IsUnchanged (kvp.Key, kvp.Value, out var stored) && stored.Kind == InfoTextKind.Guess) { + // With no CSET each field is read on its own (UTF-8, else Windows-1252). The legacy bytes stay, and + // the changed values are written by that rule, with no CSET to misdeclare the legacy ones: every + // value this reader returns is stored and reads back the same. + if (_characterSet == InfoCharacterSet.None) { + declareUtf8 = false; + list = RenderFields (InfoCharacterSet.None, keepStored: true); + return true; + } + var reason = InfoText.GuessReason (stored.Bytes, _characterSet, _codePage); error = $"Cannot save the INFO list: a changed value needs UTF-8, and {kvp.Key} ('{InfoText.Escape (kvp.Value)}') " + $"{reason}, so it cannot be rewritten as UTF-8 without guessing its text. Set or remove that field too."; @@ -505,8 +513,8 @@ public override BinaryData Render () { if (_fields.Count == 0) return BinaryData.Empty; - if (_stored is null) - return RenderFields (InfoCharacterSet.Latin1, keepStored: false); + if (!_avi) + return RenderFields (InfoCharacterSet.None, keepStored: true); if (TryRenderAvi (out var list, out _, out _)) return list; return RenderFields (InfoCharacterSet.Utf8, keepStored: true); @@ -528,7 +536,7 @@ BinaryData RenderFields (InfoCharacterSet target, bool keepStored) var bytes = keepStored && IsUnchanged (kvp.Key, kvp.Value, out var stored) && !(stored.Kind == InfoTextKind.Exact && target == InfoCharacterSet.Utf8) ? stored.Bytes - : _stored is null ? BinaryData.FromStringLatin1NullTerminated (kvp.Value).ToArray () : InfoText.Encode (kvp.Value, target); + : _avi && target != InfoCharacterSet.None ? InfoText.Encode (kvp.Value, target) : InfoText.EncodeByReadRule (kvp.Value); encodedFields.Add ((kvp.Key, bytes)); fieldsSize += 8 + bytes.Length + (bytes.Length & 1); } diff --git a/src/TagLibSharp2/Riff/WavFile.cs b/src/TagLibSharp2/Riff/WavFile.cs index 6f07ef5b..0978f44f 100644 --- a/src/TagLibSharp2/Riff/WavFile.cs +++ b/src/TagLibSharp2/Riff/WavFile.cs @@ -139,7 +139,24 @@ internal void MarkPicturesSkipped () public string? SourcePath { get; private set; } /// - Tag? IMediaFile.Tag => (Tag?)Id3v2Tag ?? InfoTag; + /// + /// The ID3v2 tag when the file has one, else the RIFF INFO tag. A file with neither has a view whose first write + /// creates an ID3v2 tag (the id3 chunk), which holds several values per field where INFO holds one and + /// declares its text encoding where INFO has none; ffprobe, ExifTool and MediaInfo read it. A write that leaves that tag empty removes it + /// again. Reading the view creates nothing, so and stay null. + /// + Tag? IMediaFile.Tag { + get { + if (_disposed) + return null; + if (Id3v2Tag is null && InfoTag is not null) + return InfoTag; + return CombinedTag.SingleOrView (Id3v2Tag, () => Id3v2Tag, + _creation ??= new TagCreation (() => new Id3v2Tag (), tag => Id3v2Tag = (Id3v2Tag?)tag)); + } + } + + TagCreation? _creation; /// IMediaProperties? IMediaFile.AudioProperties => Properties; diff --git a/src/TagLibSharp2/WavPack/WavPackFile.cs b/src/TagLibSharp2/WavPack/WavPackFile.cs index 654c6310..22223bd6 100644 --- a/src/TagLibSharp2/WavPack/WavPackFile.cs +++ b/src/TagLibSharp2/WavPack/WavPackFile.cs @@ -165,7 +165,14 @@ private WavPackFile () { } public ApeTag? ApeTag { get; private set; } /// - public Tag? Tag => ApeTag; + /// + /// The APEv2 tag. A file with none has a view whose first write creates one, and a write that leaves that tag + /// empty removes it again, so a save writes no empty tag. Reading the view creates nothing. + /// + public Tag? Tag => _disposed ? null : CombinedTag.SingleOrView (ApeTag, () => ApeTag, + _creation ??= new TagCreation (() => new ApeTag (), tag => ApeTag = (ApeTag?)tag)); + + TagCreation? _creation; /// IMediaProperties? IMediaFile.AudioProperties => Properties; @@ -798,6 +805,7 @@ public void RemoveApeTag () /// public byte[] Render (ReadOnlySpan originalData) { + _creation?.Settle ([ApeTag]); byte[] tagData = ApeTag is null ? [] : ApeTag.Render ().ToArray (); var location = ApeTagLocation.Locate (originalData); return ApeTagLocation.Rewrite (originalData, location, tagData); @@ -854,6 +862,7 @@ public static async Task ReadFromFileAsync ( /// The result of the write operation. public FileWriteResult SaveToFile (string path, ReadOnlySpan originalData, IFileSystem? fileSystem = null) { + _creation?.Settle ([ApeTag]); if (PictureSkip.Refuse (this) is { } denied) return denied; @@ -874,6 +883,7 @@ public FileWriteResult SaveToFile (string path, ReadOnlySpan originalData, /// public FileWriteResult SaveToFile (string path, IFileSystem? fileSystem = null) { + _creation?.Settle ([ApeTag]); if (PictureSkip.Refuse (this) is { } denied) return denied; var fs = fileSystem ?? _sourceFileSystem; @@ -891,6 +901,7 @@ public FileWriteResult SaveToFile (string path, IFileSystem? fileSystem = null) /// public FileWriteResult SaveToFile (IFileSystem? fileSystem = null) { + _creation?.Settle ([ApeTag]); if (PictureSkip.Refuse (this) is { } denied) return denied; if (string.IsNullOrEmpty (SourcePath)) @@ -914,6 +925,7 @@ public async Task SaveToFileAsync ( IFileSystem? fileSystem = null, CancellationToken cancellationToken = default) { + _creation?.Settle ([ApeTag]); if (PictureSkip.Refuse (this) is { } denied) return denied; @@ -938,6 +950,7 @@ public Task SaveToFileAsync ( IFileSystem? fileSystem = null, CancellationToken cancellationToken = default) { + _creation?.Settle ([ApeTag]); if (PictureSkip.Refuse (this) is { } denied) return Task.FromResult (denied); var fs = fileSystem ?? _sourceFileSystem; @@ -957,6 +970,7 @@ public async Task SaveToFileAsync ( IFileSystem? fileSystem = null, CancellationToken cancellationToken = default) { + _creation?.Settle ([ApeTag]); if (PictureSkip.Refuse (this) is { } denied) return denied; if (string.IsNullOrEmpty (SourcePath)) diff --git a/src/TagLibSharp2/Xiph/FlacFile.cs b/src/TagLibSharp2/Xiph/FlacFile.cs index 10f5cfdc..68d2812c 100644 --- a/src/TagLibSharp2/Xiph/FlacFile.cs +++ b/src/TagLibSharp2/Xiph/FlacFile.cs @@ -304,19 +304,15 @@ public string? Comment { /// /// - /// Returns null when the file has neither a VorbisComment nor any PICTURE blocks, - /// matching the "tag is absent" semantics used by other - /// implementations. Once instantiated, the is cached so a - /// later setter call (e.g. file.Tag.Title = "..." after creating a - /// VorbisComment) sees the same view. + /// Always present. Setting a field creates the Vorbis comment; reading the view + /// does not, and a save writes that block only when it exists. The same view is + /// cached so a later setter sees it. /// public Tag? Tag { get { - if (_tag is not null) - return _tag; - if (VorbisComment is null && _pictures.Count == 0) + if (_disposed) return null; - return _tag = new FlacTag (this); + return _tag ??= new FlacTag (this); } } @@ -752,6 +748,7 @@ VorbisComment EnsureVorbisComment () /// A result indicating success or failure. public FileWriteResult SaveToFile (string path, ReadOnlySpan originalData, IFileSystem? fileSystem = null) { + _tag?.Settle (); if (PictureSkip.Refuse (this) is { } denied) return denied; @@ -782,6 +779,7 @@ public Task SaveToFileAsync ( IFileSystem? fileSystem = null, CancellationToken cancellationToken = default) { + _tag?.Settle (); if (PictureSkip.Refuse (this) is { } denied) return Task.FromResult (denied); @@ -814,6 +812,7 @@ public Task SaveToFileAsync ( IFileSystem? fileSystem = null, CancellationToken cancellationToken = default) { + _tag?.Settle (); if (PictureSkip.Refuse (this) is { } denied) return Task.FromResult (denied); if (string.IsNullOrEmpty (SourcePath)) @@ -837,6 +836,7 @@ public Task SaveToFileAsync ( IFileSystem? fileSystem = null, CancellationToken cancellationToken = default) { + _tag?.Settle (); if (PictureSkip.Refuse (this) is { } denied) return Task.FromResult (denied); if (string.IsNullOrEmpty (SourcePath)) @@ -857,6 +857,7 @@ public Task SaveToFileAsync ( /// A result indicating success or failure. public FileWriteResult SaveToFile (string path, IFileSystem? fileSystem = null) { + _tag?.Settle (); if (PictureSkip.Refuse (this) is { } denied) return denied; if (string.IsNullOrEmpty (SourcePath)) @@ -919,6 +920,7 @@ FileWriteResult SaveFromSource (string destinationPath, IFileSystem? fileSystem, /// A result indicating success or failure. public FileWriteResult SaveToFile (IFileSystem? fileSystem = null) { + _tag?.Settle (); if (PictureSkip.Refuse (this) is { } denied) return denied; if (string.IsNullOrEmpty (SourcePath)) @@ -936,6 +938,7 @@ public FileWriteResult SaveToFile (IFileSystem? fileSystem = null) /// The complete file data, or empty if rendering failed. public BinaryData Render (ReadOnlySpan originalData) { + _tag?.Settle (); // Validate that we have audio data to preserve if (originalData.Length < MetadataSize) return BinaryData.Empty; diff --git a/src/TagLibSharp2/Xiph/FlacTag.cs b/src/TagLibSharp2/Xiph/FlacTag.cs index 7ef09c8c..7924f332 100644 --- a/src/TagLibSharp2/Xiph/FlacTag.cs +++ b/src/TagLibSharp2/Xiph/FlacTag.cs @@ -25,91 +25,95 @@ namespace TagLibSharp2.Xiph; public sealed class FlacTag : Tag { readonly FlacFile _file; + readonly TagCreation _creation; internal FlacTag (FlacFile file) { _file = file; + _creation = new TagCreation (() => new VorbisComment ("TagLibSharp2"), tag => _file.VorbisComment = (VorbisComment?)tag); } /// - public override TagTypes TagType => TagTypes.Xiph | TagTypes.FlacMetadata; + /// None while the file has no VORBIS_COMMENT and no PICTURE block, as for every view of a tagless file. + public override TagTypes TagType => + _file.VorbisComment is null && _file.Pictures.Count == 0 ? TagTypes.None : TagTypes.Xiph | TagTypes.FlacMetadata; /// public override string? Title { get => _file.VorbisComment?.Title; - set => EnsureVorbisComment ().Title = value; + set => Write (c => c.Title = value); } /// public override string? Artist { get => _file.VorbisComment?.Artist; - set => EnsureVorbisComment ().Artist = value; + set => Write (c => c.Artist = value); } /// public override string? Album { get => _file.VorbisComment?.Album; - set => EnsureVorbisComment ().Album = value; + set => Write (c => c.Album = value); } /// public override string? Year { get => _file.VorbisComment?.Year; - set => EnsureVorbisComment ().Year = value; + set => Write (c => c.Year = value); } /// public override string? Comment { get => _file.VorbisComment?.Comment; - set => EnsureVorbisComment ().Comment = value; + set => Write (c => c.Comment = value); } /// public override string? Genre { get => _file.VorbisComment?.Genre; - set => EnsureVorbisComment ().Genre = value; + set => Write (c => c.Genre = value); } /// public override uint? Track { get => _file.VorbisComment?.Track; - set => EnsureVorbisComment ().Track = value; + set => Write (c => c.Track = value); } /// public override string? OriginalReleaseDate { get => _file.VorbisComment?.OriginalReleaseDate; - set => EnsureVorbisComment ().OriginalReleaseDate = value; + set => Write (c => c.OriginalReleaseDate = value); } /// public override string? AlbumArtist { get => _file.VorbisComment?.AlbumArtist; - set => EnsureVorbisComment ().AlbumArtist = value; + set => Write (c => c.AlbumArtist = value); } /// public override string? Composer { get => _file.VorbisComment?.Composer; - set => EnsureVorbisComment ().Composer = value; + set => Write (c => c.Composer = value); } /// public override string? Conductor { get => _file.VorbisComment?.Conductor; - set => EnsureVorbisComment ().Conductor = value; + set => Write (c => c.Conductor = value); } /// public override string? Work { get => _file.VorbisComment?.Work; - set => EnsureVorbisComment ().Work = value; + set => Write (c => c.Work = value); } /// public override string? Movement { get => _file.VorbisComment?.Movement; - set => EnsureVorbisComment ().Movement = value; + set => Write (c => c.Movement = value); } /// @@ -125,320 +129,320 @@ internal override IEnumerable Leaves () /// public override string? Copyright { get => _file.VorbisComment?.Copyright; - set => EnsureVorbisComment ().Copyright = value; + set => Write (c => c.Copyright = value); } /// public override string? PodcastFeedUrl { get => _file.VorbisComment?.PodcastFeedUrl; - set => EnsureVorbisComment ().PodcastFeedUrl = value; + set => Write (c => c.PodcastFeedUrl = value); } /// public override string? DiscSubtitle { get => _file.VorbisComment?.DiscSubtitle; - set => EnsureVorbisComment ().DiscSubtitle = value; + set => Write (c => c.DiscSubtitle = value); } /// public override string? Lyrics { get => _file.VorbisComment?.Lyrics; - set => EnsureVorbisComment ().Lyrics = value; + set => Write (c => c.Lyrics = value); } /// public override string? Isrc { get => _file.VorbisComment?.Isrc; - set => EnsureVorbisComment ().Isrc = value; + set => Write (c => c.Isrc = value); } /// public override string? Publisher { get => _file.VorbisComment?.Publisher; - set => EnsureVorbisComment ().Publisher = value; + set => Write (c => c.Publisher = value); } /// public override string? EncodedBy { get => _file.VorbisComment?.EncodedBy; - set => EnsureVorbisComment ().EncodedBy = value; + set => Write (c => c.EncodedBy = value); } /// public override string? EncoderSettings { get => _file.VorbisComment?.EncoderSettings; - set => EnsureVorbisComment ().EncoderSettings = value; + set => Write (c => c.EncoderSettings = value); } /// public override string? Grouping { get => _file.VorbisComment?.Grouping; - set => EnsureVorbisComment ().Grouping = value; + set => Write (c => c.Grouping = value); } /// public override string? Subtitle { get => _file.VorbisComment?.Subtitle; - set => EnsureVorbisComment ().Subtitle = value; + set => Write (c => c.Subtitle = value); } /// public override string? Remixer { get => _file.VorbisComment?.Remixer; - set => EnsureVorbisComment ().Remixer = value; + set => Write (c => c.Remixer = value); } /// public override string? InitialKey { get => _file.VorbisComment?.InitialKey; - set => EnsureVorbisComment ().InitialKey = value; + set => Write (c => c.InitialKey = value); } /// public override string? Mood { get => _file.VorbisComment?.Mood; - set => EnsureVorbisComment ().Mood = value; + set => Write (c => c.Mood = value); } /// public override string? MediaType { get => _file.VorbisComment?.MediaType; - set => EnsureVorbisComment ().MediaType = value; + set => Write (c => c.MediaType = value); } /// public override string? Language { get => _file.VorbisComment?.Language; - set => EnsureVorbisComment ().Language = value; + set => Write (c => c.Language = value); } /// public override string? Barcode { get => _file.VorbisComment?.Barcode; - set => EnsureVorbisComment ().Barcode = value; + set => Write (c => c.Barcode = value); } /// public override string? CatalogNumber { get => _file.VorbisComment?.CatalogNumber; - set => EnsureVorbisComment ().CatalogNumber = value; + set => Write (c => c.CatalogNumber = value); } /// public override string? AlbumSort { get => _file.VorbisComment?.AlbumSort; - set => EnsureVorbisComment ().AlbumSort = value; + set => Write (c => c.AlbumSort = value); } /// public override string? ArtistSort { get => _file.VorbisComment?.ArtistSort; - set => EnsureVorbisComment ().ArtistSort = value; + set => Write (c => c.ArtistSort = value); } /// public override string? TitleSort { get => _file.VorbisComment?.TitleSort; - set => EnsureVorbisComment ().TitleSort = value; + set => Write (c => c.TitleSort = value); } /// public override string? AlbumArtistSort { get => _file.VorbisComment?.AlbumArtistSort; - set => EnsureVorbisComment ().AlbumArtistSort = value; + set => Write (c => c.AlbumArtistSort = value); } /// public override string? ReplayGainTrackGain { get => _file.VorbisComment?.ReplayGainTrackGain; - set => EnsureVorbisComment ().ReplayGainTrackGain = value; + set => Write (c => c.ReplayGainTrackGain = value); } /// public override string? ReplayGainTrackPeak { get => _file.VorbisComment?.ReplayGainTrackPeak; - set => EnsureVorbisComment ().ReplayGainTrackPeak = value; + set => Write (c => c.ReplayGainTrackPeak = value); } /// public override string? ReplayGainAlbumGain { get => _file.VorbisComment?.ReplayGainAlbumGain; - set => EnsureVorbisComment ().ReplayGainAlbumGain = value; + set => Write (c => c.ReplayGainAlbumGain = value); } /// public override string? ReplayGainAlbumPeak { get => _file.VorbisComment?.ReplayGainAlbumPeak; - set => EnsureVorbisComment ().ReplayGainAlbumPeak = value; + set => Write (c => c.ReplayGainAlbumPeak = value); } /// public override string? R128TrackGain { get => _file.VorbisComment?.R128TrackGain; - set => EnsureVorbisComment ().R128TrackGain = value; + set => Write (c => c.R128TrackGain = value); } /// public override string? R128AlbumGain { get => _file.VorbisComment?.R128AlbumGain; - set => EnsureVorbisComment ().R128AlbumGain = value; + set => Write (c => c.R128AlbumGain = value); } /// public override string? MusicBrainzTrackId { get => _file.VorbisComment?.MusicBrainzTrackId; - set => EnsureVorbisComment ().MusicBrainzTrackId = value; + set => Write (c => c.MusicBrainzTrackId = value); } /// public override string? MusicBrainzReleaseId { get => _file.VorbisComment?.MusicBrainzReleaseId; - set => EnsureVorbisComment ().MusicBrainzReleaseId = value; + set => Write (c => c.MusicBrainzReleaseId = value); } /// public override string? MusicBrainzArtistId { get => _file.VorbisComment?.MusicBrainzArtistId; - set => EnsureVorbisComment ().MusicBrainzArtistId = value; + set => Write (c => c.MusicBrainzArtistId = value); } /// public override string? MusicBrainzReleaseGroupId { get => _file.VorbisComment?.MusicBrainzReleaseGroupId; - set => EnsureVorbisComment ().MusicBrainzReleaseGroupId = value; + set => Write (c => c.MusicBrainzReleaseGroupId = value); } /// public override string? MusicBrainzAlbumArtistId { get => _file.VorbisComment?.MusicBrainzAlbumArtistId; - set => EnsureVorbisComment ().MusicBrainzAlbumArtistId = value; + set => Write (c => c.MusicBrainzAlbumArtistId = value); } /// public override string? MusicBrainzReleaseArtistId { get => _file.VorbisComment?.MusicBrainzReleaseArtistId; - set => EnsureVorbisComment ().MusicBrainzReleaseArtistId = value; + set => Write (c => c.MusicBrainzReleaseArtistId = value); } /// public override string? MusicBrainzRecordingId { get => _file.VorbisComment?.MusicBrainzRecordingId; - set => EnsureVorbisComment ().MusicBrainzRecordingId = value; + set => Write (c => c.MusicBrainzRecordingId = value); } /// public override string? MusicBrainzWorkId { get => _file.VorbisComment?.MusicBrainzWorkId; - set => EnsureVorbisComment ().MusicBrainzWorkId = value; + set => Write (c => c.MusicBrainzWorkId = value); } /// public override string? MusicBrainzDiscId { get => _file.VorbisComment?.MusicBrainzDiscId; - set => EnsureVorbisComment ().MusicBrainzDiscId = value; + set => Write (c => c.MusicBrainzDiscId = value); } /// public override string? MusicBrainzReleaseStatus { get => _file.VorbisComment?.MusicBrainzReleaseStatus; - set => EnsureVorbisComment ().MusicBrainzReleaseStatus = value; + set => Write (c => c.MusicBrainzReleaseStatus = value); } /// public override string? MusicBrainzReleaseType { get => _file.VorbisComment?.MusicBrainzReleaseType; - set => EnsureVorbisComment ().MusicBrainzReleaseType = value; + set => Write (c => c.MusicBrainzReleaseType = value); } /// public override string? MusicBrainzReleaseCountry { get => _file.VorbisComment?.MusicBrainzReleaseCountry; - set => EnsureVorbisComment ().MusicBrainzReleaseCountry = value; + set => Write (c => c.MusicBrainzReleaseCountry = value); } /// public override string? AcoustIdId { get => _file.VorbisComment?.AcoustIdId; - set => EnsureVorbisComment ().AcoustIdId = value; + set => Write (c => c.AcoustIdId = value); } /// public override string? AcoustIdFingerprint { get => _file.VorbisComment?.AcoustIdFingerprint; - set => EnsureVorbisComment ().AcoustIdFingerprint = value; + set => Write (c => c.AcoustIdFingerprint = value); } /// public override string? ComposerSort { get => _file.VorbisComment?.ComposerSort; - set => EnsureVorbisComment ().ComposerSort = value; + set => Write (c => c.ComposerSort = value); } /// public override string? DateTagged { get => _file.VorbisComment?.DateTagged; - set => EnsureVorbisComment ().DateTagged = value; + set => Write (c => c.DateTagged = value); } /// public override string? Description { get => _file.VorbisComment?.Description; - set => EnsureVorbisComment ().Description = value; + set => Write (c => c.Description = value); } /// public override string? AmazonId { get => _file.VorbisComment?.AmazonId; - set => EnsureVorbisComment ().AmazonId = value; + set => Write (c => c.AmazonId = value); } /// public override uint? DiscNumber { get => _file.VorbisComment?.DiscNumber; - set => EnsureVorbisComment ().DiscNumber = value; + set => Write (c => c.DiscNumber = value); } /// public override uint? BeatsPerMinute { get => _file.VorbisComment?.BeatsPerMinute; - set => EnsureVorbisComment ().BeatsPerMinute = value; + set => Write (c => c.BeatsPerMinute = value); } /// public override uint? MovementNumber { get => _file.VorbisComment?.MovementNumber; - set => EnsureVorbisComment ().MovementNumber = value; + set => Write (c => c.MovementNumber = value); } /// public override uint? MovementTotal { get => _file.VorbisComment?.MovementTotal; - set => EnsureVorbisComment ().MovementTotal = value; + set => Write (c => c.MovementTotal = value); } /// public override uint? TotalTracks { get => _file.VorbisComment?.TotalTracks; - set => EnsureVorbisComment ().TotalTracks = value; + set => Write (c => c.TotalTracks = value); } /// public override uint? TotalDiscs { get => _file.VorbisComment?.TotalDiscs; - set => EnsureVorbisComment ().TotalDiscs = value; + set => Write (c => c.TotalDiscs = value); } /// public override bool IsCompilation { get => _file.VorbisComment?.IsCompilation ?? false; - set => EnsureVorbisComment ().IsCompilation = value; + set => Write (c => c.IsCompilation = value); } /// #pragma warning disable CA1819 // Properties should not return arrays - Tag API contract public override string[] Performers { get => _file.VorbisComment?.Performers ?? []; - set => EnsureVorbisComment ().Performers = value; + set => Write (c => c.Performers = value); } #pragma warning restore CA1819 @@ -446,7 +450,7 @@ public override string[] Performers { #pragma warning disable CA1819 // Properties should not return arrays - Tag API contract public override string[] Genres { get => _file.VorbisComment?.Genres ?? []; - set => EnsureVorbisComment ().Genres = value; + set => Write (c => c.Genres = value); } #pragma warning restore CA1819 @@ -454,7 +458,7 @@ public override string[] Genres { #pragma warning disable CA1819 // Properties should not return arrays - Tag API contract public override string[] AlbumArtists { get => _file.VorbisComment?.AlbumArtists ?? []; - set => EnsureVorbisComment ().AlbumArtists = value; + set => Write (c => c.AlbumArtists = value); } #pragma warning restore CA1819 @@ -462,7 +466,7 @@ public override string[] AlbumArtists { #pragma warning disable CA1819 // Properties should not return arrays - Tag API contract public override string[] Composers { get => _file.VorbisComment?.Composers ?? []; - set => EnsureVorbisComment ().Composers = value; + set => Write (c => c.Composers = value); } #pragma warning restore CA1819 @@ -470,7 +474,7 @@ public override string[] Composers { #pragma warning disable CA1819 // Properties should not return arrays - Tag API contract public override string[]? PerformersSort { get => _file.VorbisComment?.PerformersSort; - set => EnsureVorbisComment ().PerformersSort = value; + set => Write (c => c.PerformersSort = value); } #pragma warning restore CA1819 @@ -478,7 +482,7 @@ public override string[]? PerformersSort { #pragma warning disable CA1819 // Properties should not return arrays - Tag API contract public override string[]? AlbumArtistsSort { get => _file.VorbisComment?.AlbumArtistsSort; - set => EnsureVorbisComment ().AlbumArtistsSort = value; + set => Write (c => c.AlbumArtistsSort = value); } #pragma warning restore CA1819 @@ -486,7 +490,7 @@ public override string[]? AlbumArtistsSort { #pragma warning disable CA1819 // Properties should not return arrays - Tag API contract public override string[]? ComposersSort { get => _file.VorbisComment?.ComposersSort; - set => EnsureVorbisComment ().ComposersSort = value; + set => Write (c => c.ComposersSort = value); } #pragma warning restore CA1819 @@ -494,7 +498,7 @@ public override string[]? ComposersSort { #pragma warning disable CA1819 // Properties should not return arrays - Tag API contract public override string[]? PerformersRole { get => _file.VorbisComment?.PerformersRole; - set => EnsureVorbisComment ().PerformersRole = value; + set => Write (c => c.PerformersRole = value); } #pragma warning restore CA1819 @@ -502,8 +506,19 @@ public override string[]? PerformersRole { // (https://xiph.org/vorbis/doc/v-comment.html, https://wiki.xiph.org/VorbisComment). // PICTURE blocks stay on FlacFile; this view only special-cases Pictures. - VorbisComment EnsureVorbisComment () => - _file.VorbisComment ??= new VorbisComment ("TagLibSharp2"); + // A file with no VORBIS_COMMENT gets one on the first write, and loses it again when a write leaves it empty, so a + // save writes no empty block (TagCreation). + void Write (Action write) + { + _creation.BeforeWrite (Stored); + write (_file.VorbisComment!); + _creation.AfterWrite (Stored ()); + } + + Tag?[] Stored () => [_file.VorbisComment]; + + /// Before a save: drops the Vorbis comment this view created when it stores nothing (TagCreation.Settle). + internal void Settle () => _creation.Settle (Stored ()); /// public override bool SupportsCustomFields => true; @@ -518,28 +533,24 @@ public override IReadOnlyList GetCustomField (string name) /// /// - /// Writes the VORBIS_COMMENT block (RFC 9639 §8.6). The block is created only when the field is stored, - /// so a refused name does not add an empty block to the file. + /// Writes the VORBIS_COMMENT block (RFC 9639 §8.6). A block this view creates is removed again when the write + /// leaves it empty, so a refused name does not add an empty block to the file. /// public override bool SetCustomField (string name, params string[] values) { CustomFieldValues.ThrowIfNull (name); - if (_file.VorbisComment is { } existing) - return existing.SetCustomField (name, values); - - var created = new VorbisComment ("TagLibSharp2"); - if (!created.SetCustomField (name, values)) - return false; - if (created.Fields.Count > 0) - _file.VorbisComment = created; - return true; + var stored = false; + Write (c => stored = c.SetCustomField (name, values)); + return stored; } /// public override bool RemoveCustomField (string name) { CustomFieldValues.ThrowIfNull (name); - return _file.VorbisComment?.RemoveCustomField (name) ?? false; + var removed = _file.VorbisComment?.RemoveCustomField (name) ?? false; + _creation.AfterWrite (Stored ()); + return removed; } /// @@ -596,5 +607,6 @@ public override void Clear () { _file.VorbisComment?.Clear (); _file.RemoveAllPictures (); + _creation.AfterWrite (Stored ()); } } diff --git a/src/TagLibSharp2/Xiph/VorbisComment.cs b/src/TagLibSharp2/Xiph/VorbisComment.cs index 9f4dddda..4d3c57c3 100644 --- a/src/TagLibSharp2/Xiph/VorbisComment.cs +++ b/src/TagLibSharp2/Xiph/VorbisComment.cs @@ -53,6 +53,9 @@ public sealed class VorbisComment : Tag /// public IReadOnlyList Fields => _fields; + /// + internal override bool StoresNothing => _fields.Count == 0 && _pictures.Count == 0; + /// /// Gets the list of embedded pictures as FlacPicture objects. /// @@ -290,16 +293,15 @@ public override string? Movement { set { if (IsWriteBack (value, Movement)) return; - // A name in MOVEMENT is kept in step with a new name, and removed by a clear ("" leaves an - // empty MOVEMENTNAME, as "" does for any field) or by a numeric name, which MOVEMENT would - // turn into the movement number. + // A name in MOVEMENT is kept in step with a new name, and removed by a clear (null or "", which + // removes MOVEMENTNAME too) or by a numeric name, which MOVEMENT would turn into the movement number. if (LegacyMovementName is not null) { if (string.IsNullOrEmpty (value) || TryParseUInt (value, out _)) RemoveAll ("MOVEMENT"); else SetValue ("MOVEMENT", value); } - SetValue ("MOVEMENTNAME", value); + SetValue ("MOVEMENTNAME", string.IsNullOrEmpty (value) ? null : value); } } @@ -984,7 +986,7 @@ public void SetValue (string name, string? value) void SetValueProperty (string name, string? value, string? current) { if (!IsWriteBack (value, current)) - SetValue (name, value); + SetValue (name, string.IsNullOrEmpty (value) ? null : value); } /// @@ -1022,7 +1024,7 @@ void SetValueWithFallback (string name, string? value, string fallback, Func +/// The APE "Cover Art (...)" item key of every picture role reads back as that role, through the key and through a +/// tag saved and read again; a key that is not a role's name reads as . +/// +[TestClass] +[TestCategory ("Unit")] +[TestCategory ("Ape")] +public class ApePictureKeyTests +{ + public static IEnumerable Roles => + Enum.GetValues ().Select (type => new object[] { type }); + + [TestMethod] + [DynamicData (nameof (Roles))] + public void EveryRole_RoundTripsThroughItsKey_AndASavedTag (PictureType type) + { + var key = ApePicture.GetKeyForPictureType (type); + + Assert.AreEqual (type, ApePicture.GetPictureTypeForKey (key), key); + var tag = new ApeTag { Pictures = [new ApePicture ("image/jpeg", type, "cover.jpg", new BinaryData ([0xFF, 0xD8]))] }; + Assert.AreEqual (type, ApeTag.Parse (tag.RenderWithOptions ().Span).Tag!.Pictures[0].PictureType, key); + } + + [TestMethod] + [DataRow ("Cover Art (Front)", PictureType.FrontCover)] + [DataRow ("Cover Art (Artist)", PictureType.Artist)] + [DataRow ("Cover Art (LeadArtist)", PictureType.LeadArtist)] + [DataRow ("cover art (leadartist)", PictureType.LeadArtist)] + [DataRow ("Cover Art (Lead Artist)", PictureType.LeadArtist)] + [DataRow ("Cover Art (Leaflet Page)", PictureType.LeafletPage)] + [DataRow ("Cover Art (3)", PictureType.Other)] + [DataRow ("Cover Art (-1)", PictureType.Other)] + [DataRow ("Cover Art (Other, BackCover)", PictureType.Other)] + [DataRow ("Cover Art (BackCover|Media)", PictureType.Other)] + [DataRow ("Cover Art ( FrontCover)", PictureType.Other)] + [DataRow ("Cover Art (FrontCover )", PictureType.Other)] + [DataRow ("Cover Art (Lead Artist)", PictureType.Other)] + [DataRow ("Cover Art ()", PictureType.Other)] + [DataRow ("Cover Art (Unknown)", PictureType.Other)] + public void Key_ReadsAsTheRoleItNames (string key, PictureType expected) + { + Assert.AreEqual (expected, ApePicture.GetPictureTypeForKey (key)); + } +} diff --git a/tests/TagLibSharp2.Tests/Ape/ApePictureTests.cs b/tests/TagLibSharp2.Tests/Ape/ApePictureTests.cs index f05a2db9..7adef206 100644 --- a/tests/TagLibSharp2.Tests/Ape/ApePictureTests.cs +++ b/tests/TagLibSharp2.Tests/Ape/ApePictureTests.cs @@ -69,17 +69,18 @@ public void GetKey_ReturnsArtistKey_ForArtist () } [TestMethod] - public void GetKey_ReturnsArtistKey_ForLeadArtist () + public void GetKey_ReturnsLeadArtistKey_ForLeadArtist () { var picture = new ApePicture ("artist.jpg", PictureType.LeadArtist, new BinaryData ([0xFF, 0xD8])); - Assert.AreEqual ("Cover Art (Artist)", picture.GetKey ()); + Assert.AreEqual ("Cover Art (LeadArtist)", picture.GetKey ()); } [TestMethod] - public void GetKey_ReturnsFrontCoverKey_ForOther () + public void GetKey_ReturnsOtherKey_ForOther () { var picture = new ApePicture ("other.jpg", PictureType.Other, new BinaryData ([0xFF, 0xD8])); - Assert.AreEqual ("Cover Art (Front)", picture.GetKey ()); + Assert.AreEqual ("Cover Art (Other)", picture.GetKey ()); + Assert.AreEqual (PictureType.Other, ApePicture.GetPictureTypeForKey (picture.GetKey ())); } [TestMethod] diff --git a/tests/TagLibSharp2.Tests/Asf/AsfRecordLayoutTests.cs b/tests/TagLibSharp2.Tests/Asf/AsfRecordLayoutTests.cs index c5513b41..463495fe 100644 --- a/tests/TagLibSharp2.Tests/Asf/AsfRecordLayoutTests.cs +++ b/tests/TagLibSharp2.Tests/Asf/AsfRecordLayoutTests.cs @@ -256,12 +256,12 @@ public void IsCompilation_NullBoolRecord_IsNotTrue () [TestMethod] public void EmptyString_OverAnEmptyStringAndANumber_ClearsBoth () { - // mutagen's WM/AlbumTitle = [Unicode '', DWORD 5]: Album reads "", yet "" is not the value read, because - // another value of the attribute is not empty. So "" is a clear. + // mutagen's WM/AlbumTitle = [Unicode '', DWORD 5]: Album reads null, as an empty value is no value (#211), + // yet another value of the attribute is not empty. So "" is a clear. var original = File (AsfMetadataLibraryTests.Metadata (AsfMetadataLibraryTests.RawRecord ("WM/AlbumTitle", 3, Dword (5))), AsfDescriptor.CreateString ("WM/AlbumTitle", "")); var file = Read (original); - Assert.AreEqual ("", file.Tag.Album); + Assert.IsNull (file.Tag.Album); CollectionAssert.AreEqual (Five, file.Tag.GetCustomField ("WM/AlbumTitle").ToArray (), "the DWORD is the one value with text"); file.Tag.Album = ""; diff --git a/tests/TagLibSharp2.Tests/Asf/AsfTagTests.cs b/tests/TagLibSharp2.Tests/Asf/AsfTagTests.cs index 6acd4715..6173e77e 100644 --- a/tests/TagLibSharp2.Tests/Asf/AsfTagTests.cs +++ b/tests/TagLibSharp2.Tests/Asf/AsfTagTests.cs @@ -235,10 +235,11 @@ public void Clear_RemovesAllMetadata () tag.Clear (); - Assert.AreEqual ("", tag.Title); - Assert.AreEqual ("", tag.Artist); - Assert.AreEqual ("", tag.Album); - Assert.AreEqual ("", tag.Genre); + // A field with no text reads null, as in the other formats (#211). + Assert.IsNull (tag.Title); + Assert.IsNull (tag.Artist); + Assert.IsNull (tag.Album); + Assert.IsNull (tag.Genre); } // ═══════════════════════════════════════════════════════════════ @@ -250,12 +251,13 @@ public void NewTag_AllPropertiesEmpty () { var tag = new AsfTag (); - Assert.AreEqual ("", tag.Title); - Assert.AreEqual ("", tag.Artist); - Assert.AreEqual ("", tag.Album); - Assert.IsTrue (string.IsNullOrEmpty (tag.Year)); + // A field with no text reads null, as in the other formats (#211). + Assert.IsNull (tag.Title); + Assert.IsNull (tag.Artist); + Assert.IsNull (tag.Album); + Assert.IsNull (tag.Year); Assert.IsNull (tag.Track); - Assert.AreEqual ("", tag.Genre); + Assert.IsNull (tag.Genre); } [TestMethod] @@ -311,13 +313,13 @@ public void Copyright_Set_UpdatesContentDescription () } [TestMethod] - public void Copyright_SetNull_SetsEmpty () + public void Copyright_SetNull_Clears () { var tag = new AsfTag (); tag.Copyright = "Test"; tag.Copyright = null; - Assert.AreEqual ("", tag.Copyright); + Assert.IsNull (tag.Copyright); } [TestMethod] @@ -330,13 +332,13 @@ public void Comment_Set_UpdatesContentDescription () } [TestMethod] - public void Comment_SetNull_SetsEmpty () + public void Comment_SetNull_Clears () { var tag = new AsfTag (); tag.Comment = "Test"; tag.Comment = null; - Assert.AreEqual ("", tag.Comment); + Assert.IsNull (tag.Comment); } [TestMethod] diff --git a/tests/TagLibSharp2.Tests/Core/CustomFieldTests.cs b/tests/TagLibSharp2.Tests/Core/CustomFieldTests.cs index 0881417b..3e8cb8f5 100644 --- a/tests/TagLibSharp2.Tests/Core/CustomFieldTests.cs +++ b/tests/TagLibSharp2.Tests/Core/CustomFieldTests.cs @@ -693,13 +693,15 @@ public void RiffInfo_NameNotAFourCC_Refused (string name) } [TestMethod] - public void RiffInfo_OneValueOnlyAndLatin1Only () + public void RiffInfo_OneValueOnly_AnyText () { + // An INFO subchunk holds one value. WAV INFO writes any text by the rule it is read with (#209, #216). var tag = new RiffInfoTag (); Assert.IsFalse (tag.SetCustomField ("IXYZ", "a", "b")); - Assert.IsFalse (tag.SetCustomField ("IXYZ", "日")); Assert.IsTrue (tag.IsEmpty); + Assert.IsTrue (tag.SetCustomField ("IXYZ", "日")); + AssertValues (RiffInfoTag.Parse (tag.Render ().Slice (8))!.GetCustomField ("IXYZ"), "日"); Assert.IsTrue (tag.SetCustomField ("IXYZ", "ÿ")); } diff --git a/tests/TagLibSharp2.Tests/Core/EmptyTextAndPicturesTests.cs b/tests/TagLibSharp2.Tests/Core/EmptyTextAndPicturesTests.cs new file mode 100644 index 00000000..70b6a962 --- /dev/null +++ b/tests/TagLibSharp2.Tests/Core/EmptyTextAndPicturesTests.cs @@ -0,0 +1,129 @@ +// 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.Ape; +using TagLibSharp2.Asf; +using TagLibSharp2.Core; +using TagLibSharp2.Id3.Id3v2; +using TagLibSharp2.Mp4; +using TagLibSharp2.Tests.Kit; +using TagLibSharp2.Xiph; + +namespace TagLibSharp2.Tests.Core; + +/// +/// An empty string clears a text field, as null does, on every format, tagged or tagless (#211). A tag that holds a +/// picture is not empty (#211). +/// +[TestClass] +[TestCategory ("Unit")] +public class EmptyTextAndPicturesTests +{ + static readonly string[] Fields = ["Title", "Album", "Comment", "Genre"]; + + static readonly string[] FileKinds = ["tagless.flac", "tagless.m4a", "tagged.flac", "tagged.ogg", "tagged.opus", "tagged.oga", "tagged.m4a"]; + + public static IEnumerable Files => + FileKinds.SelectMany (file => Fields.Select (name => new object[] { file, name })); + + [TestMethod] + [DynamicData (nameof (Files))] + public void EmptyText_ClearsTheField (string file, string field) + { + var (bytes, extension) = Build (file); + var read = (IMediaFile)MediaFile.ReadFromData (bytes, "file" + extension).File!; + var property = typeof (Tag).GetProperty (field)!; + property.SetValue (read.Tag, "Before"); + + property.SetValue (read.Tag, ""); + var saved = SkipPicturesFixtures.Render (read, bytes)!; + + var reread = MediaFile.ReadFromData (saved, "saved" + extension); + Assert.IsNull (property.GetValue (reread.Tag), $"{file} {field}"); + } + + static (byte[] Bytes, string Extension) Build (string file) => file switch { + "tagged.m4a" => (TestBuilders.Mp4.CreateWithMetadata (title: "Title", artist: "Artist", album: "Album"), ".m4a"), + _ when file.StartsWith ("tagless.", StringComparison.Ordinal) => (TaglessFixtures.All[file["tagless.".Length..]].Build (), TaglessFixtures.All[file["tagless.".Length..]].Extension), + _ => (SpanSaveKit.Fixtures["." + file["tagged.".Length..]].Build (), "." + file["tagged.".Length..]) + }; + + static readonly BinaryData Jpeg = new ([0xFF, 0xD8, 0xFF, 0xD9]); + + public static IEnumerable TagsWithAPicture => [ + ["Vorbis", (Func)(() => new VorbisComment ("v") { Pictures = [new FlacPicture ("image/jpeg", PictureType.FrontCover, "", Jpeg, 0, 0, 0, 0)] })], + ["MP4", (Func)(() => new Mp4Tag { Pictures = [new Mp4Picture ("image/jpeg", PictureType.FrontCover, "", Jpeg)] })], + ["APE", (Func)(() => new ApeTag { Pictures = [new ApePicture ("image/jpeg", PictureType.FrontCover, "cover.jpg", Jpeg)] })], + ["ASF", (Func)(() => new AsfTag { Pictures = [new Mp4Picture ("image/jpeg", PictureType.FrontCover, "", Jpeg)] })], + ["ID3v2", (Func)(() => new Id3v2Tag { Pictures = [new Mp4Picture ("image/jpeg", PictureType.FrontCover, "", Jpeg)] })], + ["FLAC file", (Func)(() => FlacFile.Read (TestBuilders.Flac.CreateWithPicture ()).File!.Tag!)], + ]; + + [TestMethod] + [DynamicData (nameof (TagsWithAPicture))] + public void TagHoldingOnlyAPicture_IsNotEmpty (string name, Func make) + { + var tag = make (); + + Assert.HasCount (1, tag.Pictures, name); + Assert.IsFalse (tag.IsEmpty, name); + } + + // Every writable text property of Tag, on every format's tag: set, then "", reads back null (#211). + static readonly string[] TextProperties = typeof (Tag).GetProperties () + .Where (p => p.PropertyType == typeof (string) && p.CanWrite && p.GetIndexParameters ().Length == 0) + .Select (p => p.Name).ToArray (); + + public static IEnumerable FormatsAndTextProperties => + from fixture in TaglessFixtures.All.Keys + from property in TextProperties + select new object[] { fixture, property }; + + // On a file with no tag, a value set and then set to "" leaves nothing: the save is the save with no edit, and the + // field reads null (#211). + [TestMethod] + [DynamicData (nameof (FormatsAndTextProperties))] + public void EmptyText_ClearsEveryTextField_OnEveryFormat (string fixture, string property) + { + var tagless = TaglessFixtures.All[fixture]; + var original = tagless.Build (); + var untouched = SkipPicturesFixtures.Render ((IMediaFile)tagless.ReadOwn (original)!, original)!; + var file = (IMediaFile)tagless.ReadOwn (original)!; + var info = typeof (Tag).GetProperty (property)!; + + info.SetValue (file.Tag, "Before"); + info.SetValue (file.Tag, ""); + + Assert.IsNull (info.GetValue (file.Tag), $"{fixture} {property}"); + CollectionAssert.AreEqual (untouched, SkipPicturesFixtures.Render (file, original), $"{fixture} {property}"); + } + + // Matroska: "" and null clear a field held in ffmpeg's untargeted tag, not only one at the track level (#211). + [TestMethod] + [DataRow ("Title", "TITLE")] + [DataRow ("Artist", "ARTIST")] + [DataRow ("Comment", "COMMENT")] + [DataRow ("Genre", "GENRE")] + [DataRow ("Composer", "COMPOSER")] + [DataRow ("Copyright", "COPYRIGHT")] + [DataRow ("Conductor", "CONDUCTOR")] + [DataRow ("Publisher", "PUBLISHER")] + [DataRow ("Album", "ALBUM")] + [DataRow ("AlbumArtist", "ALBUM_ARTIST")] + public void EmptyText_ClearsAFieldInTheUntargetedTag (string property, string name) + { + foreach (var empty in new[] { "", null }) { + var file = TagLibSharp2.Matroska.MatroskaFile.Read (Nesting.Concat ( + Nesting.EbmlElement (0x1A45DFA3, Nesting.EbmlElement (TagLibSharp2.Matroska.MatroskaIds.DocType, "matroska"u8)), + Nesting.EbmlElement (TagLibSharp2.Matroska.MatroskaIds.Segment, Nesting.EbmlElement (TagLibSharp2.Matroska.MatroskaIds.Tags, + Nesting.EbmlElement (0x7373, Nesting.Concat (Nesting.EbmlElement (0x63C0, []), + Nesting.EbmlElement (0x67C8, Nesting.Concat (Nesting.EbmlElement (0x45A3, System.Text.Encoding.ASCII.GetBytes (name)), Nesting.EbmlElement (0x4487, "A"u8))))))))).File!; + var info = typeof (Tag).GetProperty (property)!; + Assert.AreEqual ("A", info.GetValue (file.Tag), "read"); + + info.SetValue (file.Tag, empty); + + Assert.IsNull (info.GetValue (file.Tag), $"{property} = {(empty is null ? "null" : "\"\"")}"); + } + } +} diff --git a/tests/TagLibSharp2.Tests/Core/MediaFileResultTagTests.cs b/tests/TagLibSharp2.Tests/Core/MediaFileResultTagTests.cs new file mode 100644 index 00000000..0a59a424 --- /dev/null +++ b/tests/TagLibSharp2.Tests/Core/MediaFileResultTagTests.cs @@ -0,0 +1,49 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using TagLibSharp2.Core; + +namespace TagLibSharp2.Tests.Core; + +/// +/// is the tag of the file the result holds, on every entry +/// point, for tagged and tagless files of every format: the same null or the same view, so a write through either +/// reaches the file. +/// +[TestClass] +[TestCategory ("Unit")] +public class MediaFileResultTagTests +{ + public static IEnumerable Cases => + from fixture in TaglessFixtures.All.Keys.Select (key => "tagless." + key).Concat (SpanSaveKit.Fixtures.Keys.Select (key => "tagged" + key)) + from entry in SkipPicturesFixtures.Entries + select new object[] { fixture, entry }; + + [TestMethod] + [DynamicData (nameof (Cases))] + public void ResultTag_IsTheFilesTag (string fixture, string entry) + { + var (bytes, extension) = Build (fixture); + var result = SkipPicturesFixtures.Read (bytes, "file" + extension, entry, skip: false); + Assert.IsTrue (result.IsSuccess, result.Error); + var file = (IMediaFile)result.File!; + + Assert.AreEqual (file.Tag is null, result.Tag is null, "one of the two is null"); + if (result.Tag is null) + return; + Assert.AreEqual (file.Tag!.GetType (), result.Tag.GetType ()); + result.Tag.Title = "Through the result"; + Assert.AreEqual ("Through the result", file.Tag!.Title); + } + + static (byte[] Bytes, string Extension) Build (string fixture) + { + if (fixture.StartsWith ("tagless.", StringComparison.Ordinal)) { + var tagless = TaglessFixtures.All[fixture.Substring ("tagless.".Length)]; + return (tagless.Build (), tagless.Extension); + } + + var key = fixture.Substring ("tagged".Length); + return (SpanSaveKit.Fixtures[key].Build (), SpanSaveKit.Extension (key)); + } +} diff --git a/tests/TagLibSharp2.Tests/Core/SkipPicturesFixtures.cs b/tests/TagLibSharp2.Tests/Core/SkipPicturesFixtures.cs index 921cec63..13ba3784 100644 --- a/tests/TagLibSharp2.Tests/Core/SkipPicturesFixtures.cs +++ b/tests/TagLibSharp2.Tests/Core/SkipPicturesFixtures.cs @@ -216,13 +216,16 @@ public static int FullReadPictures (string fixture) => return Concat (bytes.AsSpan (0, pages[2]).ToArray (), new byte[100], audio); } - /// Reads through one entry point. - public static MediaFileResult Read (byte[] bytes, string name, string entry, bool skip) + /// + /// Reads through one entry point. A path entry reads them from + /// when given, so the caller can save the file to that file system. + /// + public static MediaFileResult Read (byte[] bytes, string name, string entry, bool skip, MockFileSystem? files = null) { var options = new MediaReadOptions { SkipPictures = skip }; switch (entry) { case "path": { - var files = new MockFileSystem (); + files ??= new MockFileSystem (); files.AddFile ("/" + name, bytes); return skip ? MediaFile.Read ("/" + name, options, files) : MediaFile.Read ("/" + name, files); } @@ -235,7 +238,7 @@ public static MediaFileResult Read (byte[] bytes, string name, string entry, boo case "data": return skip ? MediaFile.ReadFromData (bytes, options, name) : MediaFile.ReadFromData (bytes, name); case "async-path": { - var files = new MockFileSystem (); + files ??= new MockFileSystem (); files.AddFile ("/" + name, bytes); return (skip ? MediaFile.ReadAsync ("/" + name, options, files) : MediaFile.ReadAsync ("/" + name, files)) .GetAwaiter ().GetResult (); diff --git a/tests/TagLibSharp2.Tests/Core/TagCreationTests.cs b/tests/TagLibSharp2.Tests/Core/TagCreationTests.cs new file mode 100644 index 00000000..d303eb4a --- /dev/null +++ b/tests/TagLibSharp2.Tests/Core/TagCreationTests.cs @@ -0,0 +1,88 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using TagLibSharp2.Id3.Id3v2; +using TagLibSharp2.Mpeg; + +namespace TagLibSharp2.Tests.Core; + +/// +/// The tag a tagless file's views create belongs to the views only while the file still stores it: a tag the caller +/// removed is created again by the next write, and one the caller assigned is never dropped. +/// +[TestClass] +[TestCategory ("Unit")] +public class TagCreationTests +{ + static Mp3File Tagless () => Mp3File.Read (TaglessFixtures.All["mp3"].Build ()).File!; + + [TestMethod] + public void TagTheCallerRemoved_IsCreatedAgainByTheNextWrite () + { + var file = Tagless (); + file.Tag!.Title = "First"; + file.Id3v2Tag = null; + + file.Tag!.Title = "Second"; + + Assert.AreEqual ("Second", file.Id3v2Tag!.Title); + } + + [TestMethod] + public void TagTheCallerAssigned_IsKeptWhenAViewEmptiesIt () + { + var file = Tagless (); + file.Tag!.Title = "Created"; + var assigned = new Id3v2Tag { Title = "Assigned" }; + file.Id3v2Tag = assigned; + + file.Tag!.Title = null; + + Assert.AreSame (assigned, file.Id3v2Tag); + } + + // The tag the view created, emptied after the caller replaced it, is no longer the file's: a write that does not + // create (a removal) must not drop the caller's tag in its place. + [TestMethod] + public void TagTheCallerAssigned_IsKeptWhenTheReplacedCreatedTagIsEmptied () + { + var file = Tagless (); + file.Tag!.Title = "Created"; + var created = file.Id3v2Tag!; + var assigned = new Id3v2Tag { Title = "Assigned" }; + file.Id3v2Tag = assigned; + created.Title = null; + + file.Tag!.RemoveCustomField ("MOOD"); + + Assert.AreSame (assigned, file.Id3v2Tag); + } + + [TestMethod] + public void CreatedTag_IsKeptWhileItStoresAValue_AndDroppedWhenAnotherViewEmptiesIt () + { + var file = Tagless (); + file.Tag!.Title = "Kept"; + file.Tag!.Album = "Album"; + Assert.AreEqual ("Kept", file.Id3v2Tag!.Title); + + file.Tag!.Title = null; + Assert.IsNotNull (file.Id3v2Tag, "the album is still stored"); + file.Tag!.Album = null; + + Assert.IsNull (file.Id3v2Tag); + } + + // A view whose created tag the caller swapped for a tag with no custom fields answers for the stored tag: a write + // now creates nothing. + [TestMethod] + public void ViewOverAStoredTagWithoutCustomFields_DoesNotClaimThem () + { + var file = Tagless (); + file.Tag!.Title = "Created"; + file.Id3v2Tag = null; + file.Id3v1Tag = new TagLibSharp2.Id3.Id3v1Tag { Title = "Old" }; + + Assert.IsFalse (file.Tag!.SupportsCustomFields); + } +} diff --git a/tests/TagLibSharp2.Tests/Core/TaglessFixtures.cs b/tests/TagLibSharp2.Tests/Core/TaglessFixtures.cs new file mode 100644 index 00000000..ba2b554c --- /dev/null +++ b/tests/TagLibSharp2.Tests/Core/TaglessFixtures.cs @@ -0,0 +1,94 @@ +// 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.Aac; +using TagLibSharp2.Aiff; +using TagLibSharp2.Ape; +using TagLibSharp2.Asf; +using TagLibSharp2.Audible; +using TagLibSharp2.Core; +using TagLibSharp2.Dff; +using TagLibSharp2.Dsf; +using TagLibSharp2.Matroska; +using TagLibSharp2.Mp4; +using TagLibSharp2.Mpeg; +using TagLibSharp2.Musepack; +using TagLibSharp2.Ogg; +using TagLibSharp2.Riff; +using TagLibSharp2.Tests.Aac; +using TagLibSharp2.Tests.Asf; +using TagLibSharp2.Tests.Audible; +using TagLibSharp2.Tests.Kit; +using TagLibSharp2.Tests.Riff; +using TagLibSharp2.WavPack; +using TagLibSharp2.Xiph; +using MpegPsTestBuilder = TagLibSharp2.Tests.Mpeg.MpegPsTestBuilder; + +namespace TagLibSharp2.Tests.Core; + +/// +/// One file with no tag value for every format that can store text, with the format's own read. Where the format's +/// files can have no tag at all, the file has none; where they always carry a tag structure (the Ogg comment header, +/// the ASF header, the Audible dictionary), that structure holds no field. The key names the format. +/// +internal static class TaglessFixtures +{ + public sealed record Fixture (string Extension, Func Build, Func ReadOwn); + + public static readonly Dictionary All = new () { + // More frames than the read's 32 KB audio probe, so a stream read takes the prefix and tail windows. + ["mp3"] = new (".mp3", () => AacTestBuilder.Mp3Frames (100), b => Mp3File.Read (b).File), + ["aac"] = new (".aac", () => AacTestBuilder.Adts (8), b => AacFile.Read (b).File), + ["mpg"] = new (".mpg", () => MpegPsTestBuilder.ProgramStream (new MpegPsTestBuilder.Options { VideoFrames = 1, AudioFrames = 0, AudioKind = MpegPsTestBuilder.Audio.None }), b => MpegPsFile.Read (b).File), + ["wav"] = new (".wav", () => TestBuilders.Wav.CreateMinimal (soundBytes: 4096), b => WavFile.Read (b).File), + ["aiff"] = new (".aif", () => WithFormSize (TestBuilders.Aiff.CreateMinimal (soundBytes: 4096)), b => AiffFile.TryRead (b, out var file) ? file : null), + ["flac"] = new (".flac", () => [.. TestBuilders.Flac.CreateMinimal (), .. SpanSaveKit.Sound (4096)], b => FlacFile.Read (b).File), + ["dsf"] = new (".dsf", () => TestBuilders.Dsf.CreateMinimal (), b => DsfFile.Read (b).File), + ["dff"] = new (".dff", () => TestBuilders.Dff.CreateMinimal (), b => DffFile.Read (b).File), + ["wv"] = new (".wv", () => TestBuilders.WavPack.CreateMinimal (), b => WavPackFile.Read (b).File), + ["ape"] = new (".ape", () => TestBuilders.MonkeysAudio.CreateMinimal (), b => MonkeysAudioFile.Read (b).File), + ["mpc"] = new (".mpc", () => TestBuilders.Musepack.CreateMinimal (), b => MusepackFile.Read (b).File), + ["m4a"] = new (".m4a", () => TestBuilders.Mp4.CreateWithoutIlst (), b => Mp4File.Read (b).File), + ["ogg"] = new (".ogg", () => TestBuilders.Ogg.CreateMinimalFile (title: "", artist: ""), b => OggVorbisFile.Read (b).File), + ["opus"] = new (".opus", () => TestBuilders.Opus.CreateMinimalFile (title: "", artist: ""), b => OggOpusFile.Read (b).File), + ["oga"] = new (".oga", () => TestBuilders.OggFlac.CreateMinimal (), b => OggFlacFile.Read (b).File), + ["wma"] = new (".wma", () => AsfTestBuilder.CreateMinimalWma (), b => AsfFile.Read (b).File), + ["avi"] = new (".avi", () => new AviTestBuilder ().Build (), b => AviFile.Read (b).File), + ["mkv"] = new (".mkv", Matroska, b => MatroskaFile.Read (b).File), + ["aa"] = new (".aa", () => AudibleTestBuilder.Create ([]), b => AudibleFile.Read (b).File), + }; + + // An EBML header and a Segment with an Info element and no Tags (RFC 9559 §5.1). + static byte[] Matroska () => Nesting.Concat ( + Nesting.EbmlElement (0x1A45DFA3, Nesting.EbmlElement (0x4282, "matroska"u8)), + Nesting.EbmlElement (MatroskaIds.Segment, Nesting.EbmlElement (MatroskaIds.Info, Nesting.EbmlElement (0x2AD7B1, [0x0F, 0x42, 0x40])))); + + /// + /// Asserts that stores no tag: its view is empty and of no tag type, and every stored-tag + /// property (each public property of a type but Tag itself) is null. + /// + public static void AssertStoresNoTag (IMediaFile file) + { + var tag = file.Tag!; + Assert.IsTrue (tag.IsEmpty, "the view is not empty"); + Assert.AreEqual (TagTypes.None, tag.TagType); + foreach (var property in StoredTagProperties (file)) + Assert.IsNull (property.GetValue (file), property.Name); + } + + /// + /// The public properties that hold a tag the file stores: each property of a subtype, which + /// includes Mp4File.Tag (an Mp4Tag), but not a property typed itself, the view. + /// + public static IEnumerable StoredTagProperties (IMediaFile file) => + file.GetType ().GetProperties ().Where (p => + p.PropertyType != typeof (Tag) && typeof (Tag).IsAssignableFrom (p.PropertyType) && p.GetIndexParameters ().Length == 0); + + // The shared AIFF builder's FORM size leaves out the SSND header, so a path read stops 16 bytes into the sound. + // The FORM size here counts every chunk (AIFF 1.3 §"FORM AIFF": ckSize is the size of the data portion). + static byte[] WithFormSize (byte[] aiff) + { + System.Buffers.Binary.BinaryPrimitives.WriteUInt32BigEndian (aiff.AsSpan (4), (uint)(aiff.Length - 8)); + return aiff; + } +} diff --git a/tests/TagLibSharp2.Tests/Core/TaglessViewTests.cs b/tests/TagLibSharp2.Tests/Core/TaglessViewTests.cs new file mode 100644 index 00000000..a2ef22b2 --- /dev/null +++ b/tests/TagLibSharp2.Tests/Core/TaglessViewTests.cs @@ -0,0 +1,218 @@ +// 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.Dff; +using TagLibSharp2.Dsf; + +namespace TagLibSharp2.Tests.Core; + +/// +/// The tag view of a tagless file, on every format whose files can be tagless and that can store text, every entry +/// point and every save. An edit that leaves nothing to store saves exactly what a save with no edit saves: the view +/// writes no empty tag. An edit that stores a value reads back with that value. +/// +[TestClass] +[TestCategory ("Unit")] +public class TaglessViewTests +{ + // Edits after which the file holds no value, whatever the format. + static readonly string[] NoValueEdits = ["none", "null", "clear", "write-back", "set-then-clear", "custom-then-remove", "custom-refused", "set-then-clear-all"]; + + // A tag the view created and the caller emptied through the stored-tag property, on the formats whose view + // creates one: the save writes nothing for it, though it is still stored in memory. + const string EmptiedDirectly = "set-then-empty-stored"; + + // Edits that store a value when the format takes it. + static readonly string[] ValueEdits = ["custom", "set-values"]; + + const string Title = "新标题 Ünï 😀"; + static readonly string[] Performers = ["Ä", "Б"]; + + // Formats that keep one artist, for a tagged file as well: the iTunes ©ART item, the AVI INFO IART chunk (ffprobe + // and ExifTool read INFO in AVI, not its ID3), and the Audible dictionary's author are one string each. + static readonly string[] FirstPerformer = ["Ä"]; + static readonly string[] OneArtist = ["m4a", "avi", "aa"]; + + // The MediaFile entry points, and the format's own read from bytes. + static readonly string[] Entries = [.. SkipPicturesFixtures.Entries, "own"]; + + // The formats whose files can have no tag at all; the rest always carry a tag structure. + static readonly string[] CanBeTagless = ["mp3", "aac", "mpg", "wav", "aiff", "flac", "dsf", "dff", "wv", "ape", "mpc", "m4a"]; + + public static IEnumerable Cases => + from fixture in TaglessFixtures.All.Keys + from entry in Entries + where Saves (fixture, entry) + from edit in NoValueEdits.Concat (ValueEdits).Concat (CanBeTagless.Contains (fixture) ? [EmptiedDirectly] : []) + from save in SaveMethods (entry) + select new object[] { fixture, entry, edit, save }; + + [TestMethod] + [DynamicData (nameof (Cases))] + public void TaglessView_SavesWhatTheEditStores (string fixture, string entry, string edit, string save) + { + var original = TaglessFixtures.All[fixture].Build (); + var untouched = SaveAfter (fixture, entry, "none", save, original, out _); + + var saved = SaveAfter (fixture, entry, edit, save, original, out var stored); + + if (!stored) { + CollectionAssert.AreEqual (untouched, saved); + return; + } + + var reread = MediaFile.ReadFromData (saved, "saved" + TaglessFixtures.All[fixture].Extension); + Assert.IsTrue (reread.IsSuccess, reread.Error); + AssertStored (fixture, edit, reread.Tag!); + } + + static void AssertStored (string fixture, string edit, Tag tag) + { + switch (edit) { + case "custom": + Assert.AreEqual ("Calm", string.Join ("|", tag.GetCustomField ("MOOD"))); + break; + case "set-values": + Assert.AreEqual (Title, tag.Title); + Assert.AreEqual (string.Join ("|", OneArtist.Contains (fixture) ? FirstPerformer : Performers), string.Join ("|", tag.Performers), fixture); + break; + default: + throw new ArgumentOutOfRangeException (nameof (edit), edit, "not an edit that stores a value"); + } + } + + + public static IEnumerable EmptyCases => + from fixture in CanBeTagless + from entry in Entries + from edit in NoValueEdits + select new object[] { fixture, entry, edit }; + + // The view of a file with no tag is empty and of no tag type, and an edit that leaves no value stores no tag, in + // memory as on disk: every stored-tag property stays null. + [TestMethod] + [DynamicData (nameof (EmptyCases))] + public void TaglessView_StaysEmptyAndOfNoTagType (string fixture, string entry, string edit) + { + var original = TaglessFixtures.All[fixture].Build (); + var file = Read (fixture, entry, original, new MockFileSystem ()); + + Edit (file, edit); + + TaglessFixtures.AssertStoresNoTag (file); + // Every one of these formats stores custom fields (ID3v2 TXXX, Vorbis, APEv2, MP4 freeform). + Assert.IsTrue (file.Tag!.SupportsCustomFields, "SupportsCustomFields"); + } + + // A WAV or AIFF file read from a stream or from bytes keeps no copy of its sound, and every save of it is refused, + // tagged or not. + static bool Saves (string fixture, string entry) => + !(fixture is "wav" or "aiff" && entry is "stream" or "noseek" or "data" or "async-stream"); + + // A path save reads the file it was read from, so it applies to a file read from a path. + static IEnumerable SaveMethods (string entry) => + entry is "path" or "async-path" ? ["render", "path", "async"] : ["render"]; + + static byte[] SaveAfter (string fixture, string entry, string edit, string save, byte[] original, out bool stored) + { + var files = new MockFileSystem (); + var file = Read (fixture, entry, original, files); + stored = Edit (file, edit); + return Save (file, original, save, files); + } + + static IMediaFile Read (string fixture, string entry, byte[] bytes, MockFileSystem files) + { + var tagless = TaglessFixtures.All[fixture]; + if (entry == "own") + return (IMediaFile)tagless.ReadOwn (bytes)!; + var result = SkipPicturesFixtures.Read (bytes, "file" + tagless.Extension, entry, skip: false, files); + Assert.IsTrue (result.IsSuccess, result.Error); + return (IMediaFile)result.File!; + } + + // Each edit reads file.Tag again for every statement, as a caller would. True when the edit stored a value. + static bool Edit (IMediaFile file, string edit) + { + switch (edit) { + case "custom": { + // The view says what the write does: a caller checks SupportsCustomFields first. + var supports = file.Tag!.SupportsCustomFields; + var stored = file.Tag.SetCustomField ("MOOD", "Calm"); + Assert.AreEqual (supports, stored, "SupportsCustomFields"); + return stored; + } + case "set-values": + file.Tag!.Title = Title; + file.Tag.Performers = Performers; + return true; + case "none": + break; + case "null": + file.Tag!.Title = null; + break; + case "clear": + file.Tag!.Clear (); + break; + case "write-back": + file.Tag!.Title = file.Tag.Title; + file.Tag.Performers = file.Tag.Performers; + file.Tag.Genres = file.Tag.Genres; + file.Tag.Pictures = file.Tag.Pictures; + break; + case "set-then-clear": + file.Tag!.Title = "Temporary"; + file.Tag.Performers = ["A", "B"]; + file.Tag.Title = null; + file.Tag.Performers = []; + break; + case "custom-then-remove": + file.Tag!.SetCustomField ("MOOD", "Calm"); + file.Tag.RemoveCustomField ("MOOD"); + break; + case "set-then-clear-all": + file.Tag!.Title = "Temporary"; + file.Tag.Clear (); + break; + case "set-then-empty-stored": + // Emptied through the stored-tag property (file.Id3v2Tag and the like), not through the view. + file.Tag!.Title = "Temporary"; + foreach (var stored in StoredTags (file)) + stored.Clear (); + break; + case "custom-refused": + // Every format refuses an empty name (CustomFieldValues.IsUsableName). + Assert.IsFalse (file.Tag!.SetCustomField ("", "Calm")); + break; + default: + throw new ArgumentOutOfRangeException (nameof (edit), edit, "unknown edit"); + } + + return false; + } + + static List StoredTags (IMediaFile file) => + TaglessFixtures.StoredTagProperties (file).Select (p => p.GetValue (file) as Tag).OfType ().ToList (); + + // DSF and DFF read from a path or a stream leave the sound where it is, so their render is a save from the bytes. + static byte[] Save (IMediaFile file, byte[] original, string save, MockFileSystem files) + { + var result = save switch { + "render" => file switch { + DsfFile dsf => dsf.SaveToFile ("/saved", original, files), + DffFile dff => dff.SaveToFile ("/saved", original, files), + _ => (FileWriteResult?)null + }, + "path" => (FileWriteResult)file.GetType ().GetMethod ("SaveToFile", [typeof (string), typeof (IFileSystem)])! + .Invoke (file, ["/saved", files])!, + "async" => ((Task)file.GetType ().GetMethod ("SaveToFileAsync", [typeof (string), typeof (IFileSystem), typeof (CancellationToken)])! + .Invoke (file, ["/saved", files, CancellationToken.None])!).GetAwaiter ().GetResult (), + _ => throw new ArgumentOutOfRangeException (nameof (save), save, "unknown save") + }; + if (result is null) + return SkipPicturesFixtures.Render (file, original)!; + Assert.IsTrue (result.Value.IsSuccess, result.Value.Error); + return files.ReadAllBytes ("/saved"); + } +} diff --git a/tests/TagLibSharp2.Tests/Core/TextListSeparatorTests.cs b/tests/TagLibSharp2.Tests/Core/TextListSeparatorTests.cs new file mode 100644 index 00000000..108ab561 --- /dev/null +++ b/tests/TagLibSharp2.Tests/Core/TextListSeparatorTests.cs @@ -0,0 +1,58 @@ +// 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.Id3.Id3v2; +using TagLibSharp2.Xiph; + +namespace TagLibSharp2.Tests.Core; + +/// +/// A text list splits on NUL only: a slash is part of a value in ID3v2 (ID3v2.4 structure §4) and in Vorbis comments, +/// which repeat the field. +/// +[TestClass] +[TestCategory ("Unit")] +public class TextListSeparatorTests +{ + [TestMethod] + public void Id3_SingleNameWithSlash_StaysOneValue () + { + // ID3v2.4 §4: NUL separates text values. A slash does not. + foreach (var version in new[] { Id3v2Version.V23, Id3v2Version.V24 }) { + var tag = new Id3v2Tag (version) { + Performers = ["AC/DC"], + AlbumArtist = "Au/Ra" + }; + tag.SetTextFrameValues ("TCON", ["Rock/Pop"]); + var round = Id3v2Tag.Read (tag.Render ().Span).Tag!; + + Assert.AreEqual ("AC/DC", string.Join ("|", round.Performers), version.ToString ()); + Assert.AreEqual ("AC/DC", round.Artist, version.ToString ()); + Assert.AreEqual ("Au/Ra", string.Join ("|", round.AlbumArtists), version.ToString ()); + Assert.AreEqual ("Rock/Pop", string.Join ("|", round.Genres), version.ToString ()); + } + } + + [TestMethod] + public void Id3_NulSeparatedNames_StaySeparate_AndNumericGenreResolves () + { + var tag = new Id3v2Tag { Performers = ["AC", "DC"] }; + var round = Id3v2Tag.Read (tag.Render ().Span).Tag!; + Assert.AreEqual ("AC|DC", string.Join ("|", round.Performers)); + + // ID3v2.3 TCON "(n)" is still an ID3v1 genre reference. That parse does not use "/". + var genres = new Id3v2Tag (Id3v2Version.V23); + genres.SetTextFrameValues ("TCON", ["(17)"]); + Assert.AreEqual ("Rock", genres.Genres[0]); + } + + [TestMethod] + public void Vorbis_SinglePerformerWithSlash_StaysOneField () + { + // Vorbis comments repeat the field. A slash is only the n/m form of a track number. + var comment = new VorbisComment ("test") { Performers = ["AC/DC"] }; + Assert.AreEqual ("AC/DC", string.Join ("|", comment.Performers)); + Assert.AreEqual ("AC/DC", comment.Artist); + } +} diff --git a/tests/TagLibSharp2.Tests/Core/VideoPropertiesTests.cs b/tests/TagLibSharp2.Tests/Core/VideoPropertiesTests.cs new file mode 100644 index 00000000..3904e3b1 --- /dev/null +++ b/tests/TagLibSharp2.Tests/Core/VideoPropertiesTests.cs @@ -0,0 +1,31 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using TagLibSharp2.Core; + +namespace TagLibSharp2.Tests.Core; + +[TestClass] +[TestCategory ("Unit")] +public class VideoPropertiesTests +{ + [TestMethod] + [DataRow (0, "320x240, 01:05, H.264")] + [DataRow (90, "320x240, 01:05, rotated 90°, H.264")] + [DataRow (315, "320x240, 01:05, rotated 315°, H.264")] + public void ToString_NamesTheRotation_WhenThereIsOne (int rotation, string expected) + { + var video = new VideoProperties (TimeSpan.FromSeconds (65), 320, 240, 0, 0, "H.264") { Rotation = rotation }; + + Assert.AreEqual (expected, video.ToString ()); + } + + [TestMethod] + public void Rotation_TakesPartInEquality () + { + var upright = new VideoProperties (TimeSpan.Zero, 320, 240, 0, 0); + + Assert.AreNotEqual (upright, upright with { Rotation = 90 }); + Assert.AreEqual (upright with { Rotation = 90 }, upright with { Rotation = 90 }); + } +} diff --git a/tests/TagLibSharp2.Tests/Id3/Id3v1TextTests.cs b/tests/TagLibSharp2.Tests/Id3/Id3v1TextTests.cs new file mode 100644 index 00000000..ec26e536 --- /dev/null +++ b/tests/TagLibSharp2.Tests/Id3/Id3v1TextTests.cs @@ -0,0 +1,149 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using TagLibSharp2.Aac; +using TagLibSharp2.Core; +using TagLibSharp2.Id3; +using TagLibSharp2.Id3.Id3v2; +using TagLibSharp2.Mpeg; +using TagLibSharp2.Tests.Aac; +using TagLibSharp2.Tests.Core; +using TagLibSharp2.Tests.Mpeg; +using static TagLibSharp2.Tests.Core.SpanSaveKit; + +namespace TagLibSharp2.Tests.Id3; + +/// +/// ID3v1 text is Latin-1. A value it cannot hold, that no other tag of the file holds, fails every save and writes +/// nothing, as a WAV INFO value does (#209); it is never written as '?'. A value an ID3v2 tag holds too is not lost, +/// so ID3v1 keeps its short Latin-1 copy and the save goes ahead. MP3, AAC and MPEG-PS carry ID3v1. +/// +[TestClass] +[TestCategory ("Unit")] +public sealed class Id3v1TextTests +{ + const string NotLatin1 = "新标题 Ünï"; + + static readonly string[] Formats = [".mp3", ".aac", ".mpg"]; + static readonly string[] Fields = ["Title", "Artist", "Album", "Comment", "Year"]; + static readonly string[] Saves = ["span", "span-async", "path", "path-async", "source", "source-async", "render"]; + + static byte[] Audio (string format) => format switch { + ".mp3" => AacTestBuilder.Mp3Frames (100), + ".aac" => AacTestBuilder.Adts (8), + _ => MpegPsTestBuilder.ProgramStream (new MpegPsTestBuilder.Options { VideoFrames = 1, AudioFrames = 0, AudioKind = MpegPsTestBuilder.Audio.None }), + }; + + static byte[] Id3v1Only (string format) => [.. Audio (format), .. TestBuilders.Id3v1.CreateTag (title: "Old")]; + + static Id3v2Tag? Id3v2Of (IMediaFile file) => file switch { + Mp3File f => f.Id3v2Tag, + AacFile f => f.Id3v2Tag, + MpegPsFile f => f.Id3v2Tag, + _ => throw new ArgumentException (file.GetType ().Name, nameof (file)), + }; + + static Id3v1Tag? Id3v1Of (IMediaFile file) => file switch { + Mp3File f => f.Id3v1Tag, + AacFile f => f.Id3v1Tag, + MpegPsFile f => f.Id3v1Tag, + _ => throw new ArgumentException (file.GetType ().Name, nameof (file)), + }; + + static Task Save (IMediaFile file, string save, string format, byte[] original, MockFileSystem files) => save switch { + "span" => SaveSpan (file, "/in" + format, original, true, files), + "span-async" => SaveSpan (file, "/in" + format, original, false, files), + "path" => SavePath (file, "/in" + format, true, files), + "path-async" => SavePath (file, "/in" + format, false, files), + "source" => SavePath (file, null, true, files), + _ => SavePath (file, null, false, files), + }; + + static byte[] Render (IMediaFile file, byte[] original) => (file switch { + Mp3File f => f.Render (original), + AacFile f => f.Render (original), + MpegPsFile f => f.Render (original), + _ => throw new ArgumentException (file.GetType ().Name, nameof (file)), + }).ToArray (); + + public static IEnumerable FormatsFieldsAndSaves => + from format in Formats from name in Fields from save in Saves select new object[] { format, name, save }; + + [TestMethod] + [DynamicData (nameof (FormatsFieldsAndSaves))] + public async Task TextID3v1CannotHold_OnAFileWithOnlyID3v1_FailsEverySave_AndWritesNothing (string format, string field, string save) + { + var original = Id3v1Only (format); + var files = new MockFileSystem (); + var file = Open (format, "path", original, files); + Assert.IsNull (Id3v2Of (file), "the fixture has only ID3v1"); + + typeof (Tag).GetProperty (field)!.SetValue (file.Tag, NotLatin1); + + if (save == "render") { + var thrown = Assert.ThrowsExactly (() => Render (file, original)); + StringAssert.Contains (thrown.Message, field); + StringAssert.Contains (thrown.Message, "Latin-1"); + return; + } + + var result = await Save (file, save, format, original, files); + + Assert.IsFalse (result.IsSuccess, "the save reported success"); + StringAssert.Contains (result.Error, field); + StringAssert.Contains (result.Error, "Latin-1"); + CollectionAssert.AreEqual (original, files.ReadAllBytes ("/in" + format), "the save wrote the file"); + } + + // Through the file's Tag a value reaches ID3v2 too, which holds it; ID3v1 keeps its Latin-1 copy, as before. + [TestMethod] + [DataRow (".mp3")] + [DataRow (".aac")] + [DataRow (".mpg")] + public void TextAnID3v2TagHoldsToo_Saves (string format) + { + byte[] original = [.. new Id3v2Tag { Title = "Old" }.Render ().Span, .. Id3v1Only (format)]; + var file = Open (format, "data", original, new MockFileSystem ()); + + file.Tag!.Title = NotLatin1; + + var saved = MediaFile.ReadFromData (Render (file, original), "a" + format); + Assert.AreEqual (NotLatin1, Id3v2Of ((IMediaFile)saved.File!)!.Title); + Assert.AreEqual ("??? Ünï", Id3v1Of ((IMediaFile)saved.File!)!.Title); + } + + // A value set on ID3v1 alone, that the ID3v2 tag beside it does not hold, would be lost. + [TestMethod] + [DataRow (".mp3")] + [DataRow (".aac")] + [DataRow (".mpg")] + public void TextOnlyID3v1Holds_BesideAnID3v2Tag_FailsTheSave (string format) + { + byte[] original = [.. new Id3v2Tag { Title = "Old" }.Render ().Span, .. Id3v1Only (format)]; + var files = new MockFileSystem (); + var file = Open (format, "path", original, files); + + Id3v1Of (file)!.Title = NotLatin1; + + var result = SavePath (file, null, true, files).GetAwaiter ().GetResult (); + Assert.IsFalse (result.IsSuccess); + StringAssert.Contains (result.Error, "Title"); + CollectionAssert.AreEqual (original, files.ReadAllBytes ("/in" + format)); + } + + // Latin-1 text saves, and a value longer than the field is cut to its 30 bytes: that limit is the format's. + [TestMethod] + [DataRow (".mp3")] + [DataRow (".aac")] + [DataRow (".mpg")] + public void Latin1Text_Saves_AndALongValueIsCutToTheField (string format) + { + var original = Id3v1Only (format); + var file = Open (format, "data", original, new MockFileSystem ()); + + file.Tag!.Title = "Ünÿ " + new string ('x', 40); + + var saved = MediaFile.ReadFromData (Render (file, original), "a" + format); + Assert.AreEqual (("Ünÿ " + new string ('x', 40))[..30], Id3v1Of ((IMediaFile)saved.File!)!.Title); + } +} diff --git a/tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v22CarrierBuilder.cs b/tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v22CarrierBuilder.cs new file mode 100644 index 00000000..fabc8fdb --- /dev/null +++ b/tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v22CarrierBuilder.cs @@ -0,0 +1,78 @@ +// 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.Id3.Id3v2; +using TagLibSharp2.Id3.Id3v2.Frames; +using TagLibSharp2.Tests.Aac; +using TagLibSharp2.Tests.Core; +using TagLibSharp2.Tests.Riff; + +using MpegPsTestBuilder = TagLibSharp2.Tests.Mpeg.MpegPsTestBuilder; + +namespace TagLibSharp2.Tests.Id3.Id3v2; + +/// +/// Files of every format that carries an ID3v2 tag, holding a given ID3v2.2 tag. Each format's own writer places a +/// v2.4 tag with a large private frame; the v2.2 tag, padded with zeros, is then written over that tag's bytes, so +/// every chunk size and offset the writer set still holds. +/// +internal static class Id3v22CarrierBuilder +{ + /// Each carrier format with the file extension it is read under. + public static readonly (string Format, string Extension)[] Formats = [ + ("mp3", ".mp3"), ("aac", ".aac"), ("mpg", ".mpg"), ("wav", ".wav"), + ("aiff", ".aif"), ("dsf", ".dsf"), ("dff", ".dff"), ("avi", ".avi") + ]; + + const int Slot = 4096; + + /// A file whose ID3v2 tag is . + public static byte[] Build (string format, byte[] v22Tag) + { + var file = WithPlaceholder (format); + var at = file.AsSpan ().IndexOf ("ID3\u0004\0"u8); + Assert.IsGreaterThanOrEqualTo (0, at, format + ": no placeholder tag"); + var length = Id3v2Header.Read (file.AsSpan (at)).Header.TotalSize; + Assert.IsLessThanOrEqualTo (length, (uint)v22Tag.Length, format + ": the v2.2 tag does not fit"); + + var slot = file.AsSpan (at, (int)length); + slot.Clear (); + v22Tag.CopyTo (slot); + var body = (uint)length - 10; + slot[6] = (byte)((body >> 21) & 0x7F); + slot[7] = (byte)((body >> 14) & 0x7F); + slot[8] = (byte)((body >> 7) & 0x7F); + slot[9] = (byte)(body & 0x7F); + return file; + } + + static byte[] WithPlaceholder (string format) + { + var tag = new Id3v2Tag (Id3v2Version.V24); + tag.AddPrivateFrame (new PrivateFrame ("placeholder", new BinaryData (new byte[Slot]))); + var rendered = tag.Render ().ToArray (); + return format switch { + "mp3" => [.. rendered, .. AacTestBuilder.Mp3Frames (2)], + "aac" => [.. rendered, .. AacTestBuilder.Adts (1)], + "mpg" => [.. rendered, .. MpegPsTestBuilder.ProgramStream (new MpegPsTestBuilder.Options { VideoFrames = 1, AudioFrames = 0, AudioKind = MpegPsTestBuilder.Audio.None })], + "avi" => new AviTestBuilder { ChunkBeforeJunk = ("id3 ", rendered) }.Build (), + "wav" => Carry (TestBuilders.Wav.CreateMinimal (), ".wav", tag), + "aiff" => Carry (TestBuilders.Aiff.CreateMinimal (), ".aif", tag), + "dsf" => Carry (TestBuilders.Dsf.CreateMinimal (), ".dsf", tag), + "dff" => Carry (TestBuilders.Dff.CreateMinimal (), ".dff", tag), + _ => throw new ArgumentOutOfRangeException (nameof (format), format, "not an ID3v2 carrier") + }; + } + + static byte[] Carry (byte[] seed, string extension, Id3v2Tag tag) + { + var read = MediaFile.ReadFromData (seed, "seed" + extension); + Assert.IsTrue (read.IsSuccess, extension + " " + read.Error); + read.File!.GetType ().GetProperty ("Id3v2Tag")!.SetValue (read.File, tag); + return SkipPicturesFixtures.Render (read.File, seed)!; + } + + /// The ID3v2 tag a read of a carrier holds, or null. + public static Id3v2Tag? Id3 (object file) => file.GetType ().GetProperty ("Id3v2Tag")!.GetValue (file) as Id3v2Tag; +} diff --git a/tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v22CarrierTests.cs b/tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v22CarrierTests.cs new file mode 100644 index 00000000..756c386b --- /dev/null +++ b/tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v22CarrierTests.cs @@ -0,0 +1,169 @@ +// 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.Id3.Id3v2; +using TagLibSharp2.Tests.Core; +using TagLibSharp2.Tests.Kit; + +using V22 = TagLibSharp2.Tests.TestBuilders.Id3v2; + +namespace TagLibSharp2.Tests.Id3.Id3v2; + +/// +/// An ID3v2.2 tag in every format that carries ID3v2, read through every entry point, then saved with no edit, with +/// one field edited, and after (issue #187). A save that writes the tag writes it as ID3v2.3 +/// with every field; one that does not keeps the original v2.2 bytes. +/// +[TestClass] +[TestCategory ("Unit")] +[TestCategory ("Id3")] +[TestCategory ("Id3v2")] +public class Id3v22CarrierTests +{ + static readonly byte[] Cover = [0xFF, 0xD8, 0xFF, 0xE0, 0x00, 0x10, 0x4A, 0x46, 0x49, 0x46, 0x00, 0x01, 0x3C, 0xC3, 0xFF, 0xD9]; + + // XYZ (experimental, no v2.3 ID) sits between frames, so a walk that stops there loses the rest. + static readonly byte[] Tag = V22.CreateTagV22 ( + V22.CreateTextFrameV22 ("TT2", "A/B"), + V22.CreateTextFrameV22 ("TP1", "C/D"), + V22.CreateTextFrameV22 ("TAL", "Album"), + V22.CreateFrameV22 ("XYZ", [1, 2, 3]), + V22.CreateTextFrameV22 ("TYE", "1999"), + V22.CreateTextFrameV22 ("TRK", "3/9"), + V22.CreateTextFrameV22 ("TCP", "1"), + V22.CreateFrameV22 ("COM", [0, .. "eng"u8.ToArray (), 0, .. "Comment"u8.ToArray ()]), + V22.CreatePictureFrameV22 ("JPG", 3, "Front", Cover)); + + const string AllFields = "A/B|C/D|Album|1999|3/9|True|Comment|image/jpeg FrontCover Front 16"; + const string Edited = "Edited|C/D|Album|1999|3/9|True|Comment|image/jpeg FrontCover Front 16"; + const string NoTag = "no ID3v2 fields"; + + static readonly string[] Edits = ["none", "title", "clear"]; + + // An AIFF read from a stream does not keep its sound, and every save of it is refused whatever its tags. + public static IEnumerable Cases => + from format in Id3v22CarrierBuilder.Formats + from entry in SkipPicturesFixtures.Entries.Append ("own") + where !(format.Format == "aiff" && entry is "stream" or "async-stream") + from edit in Edits + select new object[] { format.Format, format.Extension, entry, edit }; + + [TestMethod] + [DynamicData (nameof (Cases))] + public void Save_V22Tag_WritesAReadableTagWithEveryField (string format, string extension, string entry, string edit) + { + var original = Id3v22CarrierBuilder.Build (format, Tag); + var file = Read (original, format, extension, entry); + var id3 = Id3v22CarrierBuilder.Id3 (file)!; + Assert.AreEqual (AllFields, Fields (id3), "read"); + + if (edit == "title") + id3.Title = "Edited"; + else if (edit == "clear") + id3.Clear (); + var saved = Save (file, original); + + var reread = MediaFile.ReadFromData (saved, "saved" + extension); + Assert.IsTrue (reread.IsSuccess, reread.Error); + var expected = edit switch { "title" => Edited, "clear" => NoTag, _ => AllFields }; + Assert.AreEqual (expected, Fields (Id3v22CarrierBuilder.Id3 (reread.File!))); + AssertOnlyV23OrTheOriginal (saved, original); + } + + public static IEnumerable SkipCases => + from format in Id3v22CarrierBuilder.Formats + from entry in SkipPicturesFixtures.Entries + select new object[] { format.Format, format.Extension, entry }; + + // A SkipPictures read copies the tag without its pictures, walking the frames with the same rules. + [TestMethod] + [DynamicData (nameof (SkipCases))] + public void SkipPicturesRead_V22Tag_ReadsEveryFieldButThePicture (string format, string extension, string entry) + { + var original = Id3v22CarrierBuilder.Build (format, Tag); + + var read = SkipPicturesFixtures.Read (original, "file" + extension, entry, skip: true); + + Assert.IsTrue (read.IsSuccess, read.Error); + Assert.AreEqual ("A/B|C/D|Album|1999|3/9|True|Comment|", Fields (Id3v22CarrierBuilder.Id3 (read.File!))); + } + + // A cut or changed v2.2 tag is read and saved without an exception, through the span read, a stream read and a + // SkipPictures stream read. + [TestMethod] + public void HostileV22Tag_ReadsAndSavesWithoutThrowing () + { + var file = Id3v22CarrierBuilder.Build ("mp3", Tag); + var tagLength = (int)Id3v2Header.Read (file).Header.TotalSize; + static void ReadAndSave (byte[] data) + { + var span = TagLibSharp2.Mpeg.Mp3File.Read (data); + if (span.IsSuccess) + _ = span.File!.Render (data); + _ = MediaFile.Read (new MemoryStream (data, writable: false), "file.mp3"); + _ = MediaFile.Read (new MemoryStream (data, writable: false), new MediaReadOptions { SkipPictures = true }, "file.mp3"); + } + + Hostile.EveryTruncation (file.AsSpan (0, tagLength + 64).ToArray (), ReadAndSave); + Hostile.ByteFlips (file, ReadAndSave, start: 0, length: tagLength); + } + + // Every ID3v2 header in the saved file is v2.3, or the original v2.2 tag kept byte for byte. + static void AssertOnlyV23OrTheOriginal (byte[] saved, byte[] original) + { + var at = saved.AsSpan ().IndexOf ("ID3\u0002"u8); + if (at >= 0) { + var from = original.AsSpan ().IndexOf ("ID3\u0002"u8); + var stored = original.AsSpan (from, (int)Id3v2Header.Read (original.AsSpan (from)).Header.TotalSize); + Assert.IsTrue (saved.AsSpan (at).StartsWith (stored), "a v2.2 header over bytes that are not the original tag"); + } + Assert.AreEqual (-1, saved.AsSpan ().IndexOf ("ID3\u0004"u8), "a v2.4 tag"); + } + + // DSF and DFF read from a path or a stream leave the sound where it is, so they are saved to a file; the rest render. + static byte[] Save (object file, byte[] original) + { + var files = new MockFileSystem (); + FileWriteResult? result = file switch { + TagLibSharp2.Dsf.DsfFile dsf => dsf.SaveToFile ("/saved", original, files), + TagLibSharp2.Dff.DffFile dff => dff.SaveToFile ("/saved", original, files), + _ => null + }; + if (result is null) + return SkipPicturesFixtures.Render (file, original)!; + Assert.IsTrue (result.Value.IsSuccess, result.Value.Error); + return files.ReadAllBytes ("/saved"); + } + + static string Fields (Id3v2Tag? tag) + { + if (tag is null || tag.IsEmpty) + return NoTag; + var pictures = string.Join (",", tag.Pictures.Select (p => $"{p.MimeType} {p.PictureType} {p.Description} {p.PictureData.Length}")); + return $"{tag.Title}|{string.Join (";", tag.Performers)}|{tag.Album}|{tag.Year}|{tag.Track}/{tag.TotalTracks}|{tag.IsCompilation}|{tag.Comment}|{pictures}"; + } + + static object Read (byte[] bytes, string format, string extension, string entry) + { + if (entry != "own") { + var result = SkipPicturesFixtures.Read (bytes, "file" + extension, entry, skip: false); + Assert.IsTrue (result.IsSuccess, result.Error); + return result.File!; + } + + object? file = format switch { + "mp3" => TagLibSharp2.Mpeg.Mp3File.Read (bytes).File, + "aac" => TagLibSharp2.Aac.AacFile.Read (bytes).File, + "mpg" => TagLibSharp2.Mpeg.MpegPsFile.Read (bytes).File, + "wav" => TagLibSharp2.Riff.WavFile.Read (bytes).File, + "aiff" => TagLibSharp2.Aiff.AiffFile.Read (bytes).File, + "dsf" => TagLibSharp2.Dsf.DsfFile.Read (bytes).File, + "dff" => TagLibSharp2.Dff.DffFile.Read (bytes).File, + "avi" => TagLibSharp2.Riff.AviFile.Read (bytes).File, + _ => null + }; + Assert.IsNotNull (file, format); + return file; + } +} diff --git a/tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v22WriteTests.cs b/tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v22WriteTests.cs new file mode 100644 index 00000000..a295ff00 --- /dev/null +++ b/tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v22WriteTests.cs @@ -0,0 +1,261 @@ +// 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.Id3.Id3v2; +using TagLibSharp2.Tests.Kit; + +using V22 = TagLibSharp2.Tests.TestBuilders.Id3v2; + +namespace TagLibSharp2.Tests.Id3.Id3v2; + +/// +/// A tag read as ID3v2.2 is written as ID3v2.3 (issue #187): every v2.2 frame has a v2.3 frame with the same body, +/// except PIC, whose 3-character image format becomes a MIME type. +/// +[TestClass] +[TestCategory ("Unit")] +[TestCategory ("Id3")] +[TestCategory ("Id3v2")] +public class Id3v22WriteTests +{ + static readonly byte[] TitleAndArtist = V22.CreateTagV22 ( + V22.CreateTextFrameV22 ("TT2", "A/B"), + V22.CreateTextFrameV22 ("TP1", "C/D")); + + [TestMethod] + public void Render_TagReadAsV22_WritesV23HeaderAndFrames () + { + var tag = Id3v2Tag.Read (TitleAndArtist).Tag!; + + var rendered = tag.Render ().ToArray (); + + // "ID3", major 3, revision 0, no flags; then the first frame as a 10-byte v2.3 header. + CollectionAssert.AreEqual (new byte[] { 0x49, 0x44, 0x33, 3, 0, 0 }, rendered[..6]); + CollectionAssert.AreEqual ("TIT2\0\0\0\u0004\0\0"u8.ToArray (), rendered[10..20]); + var reread = Id3v2Tag.Read (rendered).Tag!; + Assert.AreEqual (3, reread.Version); + Assert.AreEqual ("A/B", reread.Title); + Assert.AreEqual ("C/D", string.Join ("|", reread.Performers)); + } + + // ID3v2.2 §3.1: bit 7 is unsynchronisation, which the read undoes; bit 6 is compression, for which no scheme was + // ever defined, and the frames are read as they are (Read_V22CompressionFlag_KeepsTitleByLeniency). v2.3 gives + // bit 6 another meaning (extended header), so neither bit is written. + [TestMethod] + [DataRow ((byte)0x80)] + [DataRow ((byte)0x40)] + public void Render_V22TagWithHeaderFlags_WritesNoFlags (byte flags) + { + var frame = V22.CreateTextFrameV22 ("TT2", "Title\u00FFTest"); + var frames = flags == 0x80 ? V22.ApplyUnsynchronization (frame) : frame; + byte[] data = [.. V22.CreateHeaderWithFlags (2, (uint)frames.Length, flags), .. frames]; + + var rendered = Id3v2Tag.Read (data).Tag!.Render ().ToArray (); + + CollectionAssert.AreEqual (new byte[] { 0x49, 0x44, 0x33, 3, 0, 0 }, rendered[..6]); + Assert.AreEqual ("Title\u00FFTest", Id3v2Tag.Read (rendered).Tag!.Title); + } + + // Id3v2Version.V22 asks for a v2.2 tag, which this library writes as v2.3 too; its setters take the v2.3 frames. + [TestMethod] + public void Render_TagCreatedAsV22_WritesV23 () + { + var tag = new Id3v2Tag (Id3v2Version.V22) { Title = "T", Year = "1999" }; + + var rendered = tag.Render ().ToArray (); + + Assert.AreEqual (2, tag.Version); + Assert.AreEqual (3, rendered[3]); + Assert.IsGreaterThanOrEqualTo (0, rendered.AsSpan ().IndexOf ("TYER"u8)); + var reread = Id3v2Tag.Read (rendered).Tag!; + Assert.AreEqual ("T", reread.Title); + Assert.AreEqual ("1999", reread.Year); + } + + // Each row: a v2.2 frame ID, the v2.3 frame ID with the same body, and a body as this library renders it. + // The pairs are from the frame lists of ID3v2.2 §4 (https://id3.org/id3v2-00) and ID3v2.3 §4 + // (https://id3.org/id3v2.3.0). TCP, TS2, TSA, TSC, TSP and TST are not in ID3v2.2; they are the v2.2 IDs + // exiftool and mutagen read as TCMP, TSO2, TSOA, TSOC, TSOP and TSOT. + const string Text = "0056616C7565"; + const string Url = "687474703A2F2F612E62"; + + [TestMethod] + [DataRow ("TAL", "TALB", Text)] + [DataRow ("TBP", "TBPM", Text)] + [DataRow ("TCM", "TCOM", Text)] + [DataRow ("TCO", "TCON", Text)] + [DataRow ("TCR", "TCOP", Text)] + [DataRow ("TDA", "TDAT", Text)] + [DataRow ("TDY", "TDLY", Text)] + [DataRow ("TEN", "TENC", Text)] + [DataRow ("TFT", "TFLT", Text)] + [DataRow ("TIM", "TIME", Text)] + [DataRow ("TKE", "TKEY", Text)] + [DataRow ("TLA", "TLAN", Text)] + [DataRow ("TLE", "TLEN", Text)] + [DataRow ("TMT", "TMED", Text)] + [DataRow ("TOA", "TOPE", Text)] + [DataRow ("TOF", "TOFN", Text)] + [DataRow ("TOL", "TOLY", Text)] + [DataRow ("TOR", "TORY", Text)] + [DataRow ("TOT", "TOAL", Text)] + [DataRow ("TP1", "TPE1", Text)] + [DataRow ("TP2", "TPE2", Text)] + [DataRow ("TP3", "TPE3", Text)] + [DataRow ("TP4", "TPE4", Text)] + [DataRow ("TPA", "TPOS", Text)] + [DataRow ("TPB", "TPUB", Text)] + [DataRow ("TRC", "TSRC", Text)] + [DataRow ("TRD", "TRDA", Text)] + [DataRow ("TRK", "TRCK", Text)] + [DataRow ("TSI", "TSIZ", Text)] + [DataRow ("TSS", "TSSE", Text)] + [DataRow ("TT1", "TIT1", Text)] + [DataRow ("TT2", "TIT2", Text)] + [DataRow ("TT3", "TIT3", Text)] + [DataRow ("TXT", "TEXT", Text)] + [DataRow ("TYE", "TYER", Text)] + [DataRow ("TCP", "TCMP", Text)] + [DataRow ("TS2", "TSO2", Text)] + [DataRow ("TSA", "TSOA", Text)] + [DataRow ("TSC", "TSOC", Text)] + [DataRow ("TSP", "TSOP", Text)] + [DataRow ("TST", "TSOT", Text)] + [DataRow ("TXX", "TXXX", "004B0056")] + [DataRow ("WAF", "WOAF", Url)] + [DataRow ("WAR", "WOAR", Url)] + [DataRow ("WAS", "WOAS", Url)] + [DataRow ("WCM", "WCOM", Url)] + [DataRow ("WCP", "WCOP", Url)] + [DataRow ("WPB", "WPUB", Url)] + [DataRow ("WXX", "WXXX", "004400" + Url)] + [DataRow ("COM", "COMM", "00656E670054657874")] + [DataRow ("ULT", "USLT", "00656E670054657874")] + [DataRow ("UFI", "UFID", "6F776E6572006964")] + [DataRow ("IPL", "IPLS", "0070726F647563657200426F6200")] + [DataRow ("POP", "POPM", "6140622E6300C407")] + [DataRow ("GEO", "GEOB", "006D696D650066006400010203")] + [DataRow ("SLT", "SYLT", "00656E6702016400730000000010")] + public void Render_V22Frame_KeepsItsBodyUnderItsV23Id (string v22Id, string v23Id, string bodyHex) + { + var body = Convert.FromHexString (bodyHex); + var tag = Id3v2Tag.Read (V22.CreateTagV22 (V22.CreateFrameV22 (v22Id, body), After)).Tag!; + + var rendered = tag.Render ().ToArray (); + + Assert.AreEqual (3, rendered[3]); + byte[] v23Frame = [.. System.Text.Encoding.ASCII.GetBytes (v23Id), 0, 0, 0, (byte)body.Length, 0, 0, .. body]; + Assert.IsGreaterThanOrEqualTo (0, rendered.AsSpan ().IndexOf (v23Frame), v22Id + " was not written as " + v23Id + " with its body"); + Assert.IsTrue (HasMarker (Id3v2Tag.Read (rendered).Tag!), "the frames after " + v22Id); + } + + // A frame the walk must step over by its size. MCI, ETC, MLL, STC, RVA, EQU, REV, CNT, BUF, CRA and LNK have + // v2.3 forms this library does not keep in any version; CRM has none (ID3v2.3 replaced it with frame + // encryption, §3.3.1); XYZ is experimental and TZZ an undeclared text frame, which have no v2.3 ID. + [TestMethod] + [DataRow ("MCI", "0102")] + [DataRow ("ETC", "0200000010")] + [DataRow ("MLL", "00010000010000011808")] + [DataRow ("STC", "0278")] + [DataRow ("RVA", "030800010001")] + [DataRow ("EQU", "10")] + [DataRow ("REV", "00010001010101010101")] + [DataRow ("CNT", "00000009")] + [DataRow ("BUF", "00100000")] + [DataRow ("CRA", "6F00000000")] + [DataRow ("LNK", "5454326100")] + [DataRow ("CRM", "6F00650001")] + [DataRow ("XYZ", "6578")] + [DataRow ("TZZ", "007A7A")] + public void Read_V22FrameThisLibraryDoesNotKeep_IsSteppedOver (string v22Id, string bodyHex) + { + var tag = Id3v2Tag.Read (V22.CreateTagV22 ( + V22.CreateTextFrameV22 ("TT2", "Before"), + V22.CreateFrameV22 (v22Id, Convert.FromHexString (bodyHex)), + After)).Tag!; + + var reread = Id3v2Tag.Read (tag.Render ().ToArray ()).Tag!; + + Assert.AreEqual ("Before", reread.Title); + Assert.IsTrue (HasMarker (reread)); + Assert.AreEqual ("TIT2", string.Join (",", reread.Frames.Select (f => f.Id))); + } + + // Stepping over a frame with no v2.3 ID costs the same for every frame, so the walk stays linear in the tag. + [TestMethod] + public void Read_ManyV22FramesWithNoV23Id_AllocatesLinearly () + { + static byte[] Build (int count) => + V22.CreateTagV22 ([.. Enumerable.Repeat (V22.CreateFrameV22 ("XYZ", [1]), count), After]); + + Assert.IsTrue (HasMarker (Id3v2Tag.Read (Build (4000)).Tag!)); + Bounds.AssertLinearAllocation (Build, data => Id3v2Tag.Read (data), 2000, runs: 3); + } + + // ID3v2.2 §4.15: PIC holds a 3-character image format, "PNG" or "JPG" preferably, or "-->" for a link. ID3v2.3 + // §4.15 APIC holds a MIME type, "-->" for a link, and "image/" is implied when the subtype is left out. + [TestMethod] + [DataRow ("JPG", "image/jpeg")] + [DataRow ("jpg", "image/jpeg")] + [DataRow ("PNG", "image/png")] + [DataRow ("GIF", "image/gif")] + [DataRow ("BMP", "image/bmp")] + [DataRow ("-->", "-->")] + public void Render_V22Picture_WritesItsImageFormatAsAMimeType (string imageFormat, string mimeType) + { + var tag = Id3v2Tag.Read (V22.CreateTagV22 (V22.CreatePictureFrameV22 (imageFormat, 3, "Front", Cover), After)).Tag!; + + var rendered = tag.Render ().ToArray (); + + byte[] apic = [.. "APIC"u8.ToArray (), 0, 0, 0, (byte)(1 + mimeType.Length + 1 + 1 + 6 + Cover.Length), 0, 0, + 0, .. System.Text.Encoding.ASCII.GetBytes (mimeType), 0, 3, .. "Front"u8.ToArray (), 0, .. Cover]; + Assert.IsGreaterThanOrEqualTo (0, rendered.AsSpan ().IndexOf (apic), imageFormat + " was not written as " + mimeType); + var picture = Id3v2Tag.Read (rendered).Tag!.Pictures.Single (); + Assert.AreEqual (mimeType, picture.MimeType); + Assert.AreEqual (TagLibSharp2.Core.PictureType.FrontCover, picture.PictureType); + Assert.AreEqual ("Front", picture.Description); + CollectionAssert.AreEqual (Cover, picture.PictureData.ToArray ()); + } + + // Some writers put the APIC layout (a NUL-terminated MIME type) in a PIC frame, as the sample + // generated-covers/pic-v22.mp3 does. Read by the letter of §4.15 its picture data would start with the + // picture type and the description, so the MIME type is kept, as this reader has always taken it. + [TestMethod] + public void Render_V22PictureHoldingAMimeType_KeepsIt () + { + byte[] body = [0, .. "image/jpeg"u8.ToArray (), 0, 3, .. "thumbnail"u8.ToArray (), 0, .. Cover]; + var tag = Id3v2Tag.Read (V22.CreateTagV22 (V22.CreateFrameV22 ("PIC", body), After)).Tag!; + + var picture = Id3v2Tag.Read (tag.Render ().ToArray ()).Tag!.Pictures.Single (); + + Assert.AreEqual ("image/jpeg", picture.MimeType); + Assert.AreEqual (TagLibSharp2.Core.PictureType.FrontCover, picture.PictureType); + Assert.AreEqual ("thumbnail", picture.Description); + CollectionAssert.AreEqual (Cover, picture.PictureData.ToArray ()); + } + + // §4.15: a PIC body ends its description with a terminator. Five bytes (encoding, format, type) have none and + // are not a picture; six bytes are a picture with an empty description and no data. "image/j" with no NUL is + // not a MIME type, so it is read as §4.15 lays it out: format "ima", type 103, the rest picture data. + [TestMethod] + [DataRow ("00 4A5047 03", "")] + [DataRow ("00 4A5047 03 00", "image/jpeg FrontCover 0")] + [DataRow ("00 696D61 67", "")] + [DataRow ("00 696D61 67 652F6A", "image/ima 103 3")] + public void Read_V22PictureCutShort (string bodyHex, string expected) + { + var tag = Id3v2Tag.Read (V22.CreateTagV22 (V22.CreateFrameV22 ("PIC", Convert.FromHexString (bodyHex.Replace (" ", ""))), After)).Tag!; + + var pictures = string.Join (",", tag.Pictures.Select (p => $"{p.MimeType} {p.PictureType} {p.Description} {p.PictureData.Length}")); + + Assert.AreEqual (expected, pictures); + Assert.IsTrue (HasMarker (tag)); + } + + static readonly byte[] Cover = [0xFF, 0xD8, 0xFF, 0xE0, 0x00, 0x10, 0x4A, 0x46, 0x49, 0x46, 0x00, 0x01, 0x3C, 0xC3, 0xFF, 0xD9]; + + // A COM frame after the frame under test: read back only if the walk went past that frame. + static readonly byte[] After = V22.CreateFrameV22 ("COM", [0, .. "eng"u8.ToArray (), .. "Marker"u8.ToArray (), 0, .. "After"u8.ToArray ()]); + + static bool HasMarker (Id3v2Tag tag) => tag.Comments.Any (c => c.Description == "Marker" && c.Text == "After"); +} diff --git a/tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v2TagExtendedMetadataTests.cs b/tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v2TagExtendedMetadataTests.cs index 89792ccd..6cc6c53c 100644 --- a/tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v2TagExtendedMetadataTests.cs +++ b/tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v2TagExtendedMetadataTests.cs @@ -666,15 +666,17 @@ public void Artists_NullSeparated_ReturnsMultipleElements () } [TestMethod] - public void Artists_SlashSeparated_ReturnsMultipleElements () + public void Artists_SlashIsNotASeparator () { + // ID3v2.4 §4 separates text values with NUL. "Daft Punk / The Weeknd" is one + // string, which is also what ffprobe reports for a single TPE1. var tag = new Id3v2Tag (Id3v2Version.V24) { Artist = "Daft Punk / The Weeknd" }; var artists = tag.Performers; - Assert.HasCount (2, artists); - Assert.AreEqual ("Daft Punk", artists[0]); - Assert.AreEqual ("The Weeknd", artists[1]); + Assert.HasCount (1, artists); + Assert.AreEqual ("Daft Punk / The Weeknd", artists[0]); + Assert.AreEqual ("Daft Punk / The Weeknd", tag.Artist); } [TestMethod] @@ -749,7 +751,7 @@ public void AlbumArtists_MultiValue_Works () } [TestMethod] - public void MultiValue_SlashSeparated_RoundTrip_PreservesValues () + public void MultiValue_SlashIsKeptInsideOneValue () { var original = new Id3v2Tag (Id3v2Version.V24) { Artist = "Artist One / Artist Two / Artist Three" }; @@ -758,10 +760,8 @@ public void MultiValue_SlashSeparated_RoundTrip_PreservesValues () Assert.IsTrue (result.IsSuccess); var artists = result.Tag!.Performers; - Assert.HasCount (3, artists); - Assert.AreEqual ("Artist One", artists[0]); - Assert.AreEqual ("Artist Two", artists[1]); - Assert.AreEqual ("Artist Three", artists[2]); + Assert.HasCount (1, artists); + Assert.AreEqual ("Artist One / Artist Two / Artist Three", artists[0]); } // =========================================== diff --git a/tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v2TrailingTerminatorTests.cs b/tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v2TrailingTerminatorTests.cs index c24ec065..d4769758 100644 --- a/tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v2TrailingTerminatorTests.cs +++ b/tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v2TrailingTerminatorTests.cs @@ -157,13 +157,13 @@ public void Performers_V23SlashSeparated_SingleGetterDoesNotSplit () var frame = TestBuilders.Id3v2.CreateTextFrame ("TPE1", "A/B", TestConstants.Id3v2.Version3); var tag = ReadTag (TestConstants.Id3v2.Version3, frame); + // ID3v2.4 §4 uses NUL, not "/". The single getter and the list agree on one name. Assert.AreEqual ("A/B", tag.GetTextFrame ("TPE1")); Assert.AreEqual ("A/B", tag.Artist); var values = tag.GetTextFrameValues ("TPE1"); - Assert.HasCount (2, values); - Assert.AreEqual ("A", values[0]); - Assert.AreEqual ("B", values[1]); - Assert.HasCount (2, tag.Performers); + Assert.HasCount (1, values); + Assert.AreEqual ("A/B", values[0]); + Assert.HasCount (1, tag.Performers); } [TestMethod] diff --git a/tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v2UnreadFrameTests.cs b/tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v2UnreadFrameTests.cs new file mode 100644 index 00000000..086ef581 --- /dev/null +++ b/tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v2UnreadFrameTests.cs @@ -0,0 +1,283 @@ +// 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.Id3.Id3v2; + +namespace TagLibSharp2.Tests.Id3.Id3v2; + +/// +/// A frame this library does not read is written back on save (#207): byte for byte, flags included, when the tag is +/// written in the version it was read in; under its ID3v2.3 ID when a v2.2 tag is saved as v2.3 (the bodies are the +/// same, id3v2-00 §4 and id3v2.3.0 §4). Clear removes them. +/// +[TestClass] +[TestCategory ("Unit")] +[TestCategory ("Id3v2")] +public class Id3v2UnreadFrameTests +{ + static byte[] Frame (string id, byte[] body, int version, byte status = 0, byte format = 0) + { + var size = version == 4 + ? new[] { (byte)((body.Length >> 21) & 0x7F), (byte)((body.Length >> 14) & 0x7F), (byte)((body.Length >> 7) & 0x7F), (byte)(body.Length & 0x7F) } + : new[] { (byte)(body.Length >> 24), (byte)(body.Length >> 16), (byte)(body.Length >> 8), (byte)body.Length }; + return [.. System.Text.Encoding.ASCII.GetBytes (id), .. size, status, format, .. body]; + } + + static byte[] FrameV22 (string id, byte[] body) => + [.. System.Text.Encoding.ASCII.GetBytes (id), (byte)(body.Length >> 16), (byte)(body.Length >> 8), (byte)body.Length, .. body]; + + static byte[] Tag (int version, params byte[][] frames) + { + var body = frames.SelectMany (f => f).ToArray (); + return [(byte)'I', (byte)'D', (byte)'3', (byte)version, 0, 0, (byte)((body.Length >> 21) & 0x7F), (byte)((body.Length >> 14) & 0x7F), (byte)((body.Length >> 7) & 0x7F), (byte)(body.Length & 0x7F), .. body]; + } + + static byte[] Title (int version) => Frame ("TIT2", [0, (byte)'T'], version); + + // The frames the review found dropped from built/v23many.mp3, with bodies of their own shape. + static readonly (string Id, byte[] Body)[] Unread = [ + ("PCNT", [0, 0, 0, 9]), + ("MCDI", [1, 2, 3, 4]), + ("RVAD", [3, 16, 0, 1]), + ("ETCO", [2, 3, 0, 0, 0, 1]), + ("USER", [0, (byte)'e', (byte)'n', (byte)'g', (byte)'T', (byte)'o', (byte)'U']), + ("COMR", [0, 0]), + ("XABC", [7, 8, 9]), + ]; + + // The ID3v2 frames of a rendered tag, each as its whole stored bytes, keyed by ID. + static Dictionary Frames (ReadOnlySpan tag) + { + var version = tag[3]; + var size = (tag[6] << 21) | (tag[7] << 14) | (tag[8] << 7) | tag[9]; + var frames = new Dictionary (); + var at = 10; + while (at + 10 <= 10 + size && tag[at] != 0) { + var length = version == 4 + ? (tag[at + 4] << 21) | (tag[at + 5] << 14) | (tag[at + 6] << 7) | tag[at + 7] + : (tag[at + 4] << 24) | (tag[at + 5] << 16) | (tag[at + 6] << 8) | tag[at + 7]; + frames[System.Text.Encoding.ASCII.GetString (tag.Slice (at, 4))] = tag.Slice (at, 10 + length).ToArray (); + at += 10 + length; + } + + return frames; + } + + [TestMethod] + [DataRow (3)] + [DataRow (4)] + public void NoEditSave_KeepsEveryUnreadFrameByteForByte (int version) + { + var frames = Unread.Select (f => Frame (f.Id, f.Body, version)).ToList (); + // A frame with flags keeps them and the bytes they add: a v2.4 data length indicator (id3v2.4.0-structure + // §4.1.2), a v2.3 compressed frame's decompressed size and its file alter preservation flag (id3v2.3.0 §3.3.1). + frames.Add (version == 4 + ? Frame ("XFLG", [0, 0, 0, 2, 5, 6], 4, format: 0x01) + : Frame ("XFLG", [0, 0, 0, 3, 1, 2, 3], 3, status: 0x40, format: 0x80)); + var tag = Id3v2Tag.Read (Tag (version, [Title (version), .. frames])).Tag!; + + var saved = Frames (tag.Render ().Span); + + foreach (var frame in frames) + CollectionAssert.AreEqual (frame, saved[System.Text.Encoding.ASCII.GetString (frame, 0, 4)]); + } + + [TestMethod] + public void V22Tag_IsSavedWithItsUnreadFramesUnderTheirV23Ids () + { + var tag = Id3v2Tag.Read (Tag (2, + FrameV22 ("TT2", [0, (byte)'T']), + FrameV22 ("CNT", [0, 0, 0, 9]), + FrameV22 ("MCI", [1, 2, 3]), + FrameV22 ("ETC", [2, 3, 0, 0, 0, 1]), + FrameV22 ("LNK", [(byte)'T', (byte)'T', (byte)'2', (byte)'u', 0]))).Tag!; + + var saved = Frames (tag.Render ().Span); + + CollectionAssert.AreEqual (Frame ("PCNT", [0, 0, 0, 9], 3), saved["PCNT"]); + CollectionAssert.AreEqual (Frame ("MCDI", [1, 2, 3], 3), saved["MCDI"]); + CollectionAssert.AreEqual (Frame ("ETCO", [2, 3, 0, 0, 0, 1], 3), saved["ETCO"]); + // A v2.2 LNK names a 3-character frame where a v2.3 LINK names a 4-character one: not the same body. + Assert.IsFalse (saved.ContainsKey ("LINK")); + } + + // Frames of IDs this library reads, each one its branch rejects: the frames of id3/bad23.mp3 in review 3. + static readonly (string Id, byte[] Body)[] Rejected = [ + ("APIC", [0]), + ("COMM", [0, (byte)'e', (byte)'n']), + ("USLT", [0, (byte)'e']), + ("SYLT", [0]), + ("GEOB", [0]), + ("POPM", [(byte)'a', (byte)'@', (byte)'b']), + ("UFID", [(byte)'h', (byte)'t', (byte)'t', (byte)'p']), + ("PRIV", [(byte)'o', (byte)'w', (byte)'n']), + ("CHAP", [(byte)'c', (byte)'h']), + ("CTOC", [(byte)'t', (byte)'o']), + ("TXXX", [0]), + ("WXXX", [0]), + ("TALB", [9, (byte)'A']), + ("TIPL", [9]), + // Size 0: illegal (id3v2.3.0 §3.3), and kept as stored too. + ("TPE1", []), + ]; + + // Every frame ID of a rendered tag, in order, one entry per frame. + static List Ids (ReadOnlySpan tag) + { + var version = tag[3]; + var size = (tag[6] << 21) | (tag[7] << 14) | (tag[8] << 7) | tag[9]; + var ids = new List (); + var at = 10; + while (at + 10 <= 10 + size && tag[at] != 0) { + var length = version == 4 + ? (tag[at + 4] << 21) | (tag[at + 5] << 14) | (tag[at + 6] << 7) | tag[at + 7] + : (tag[at + 4] << 24) | (tag[at + 5] << 16) | (tag[at + 6] << 8) | tag[at + 7]; + ids.Add (System.Text.Encoding.ASCII.GetString (tag.Slice (at, 4))); + at += 10 + length; + } + + return ids; + } + + // What a set of TPE1 and every removal leaves: TXXX and WXXX have no call that removes every frame of the ID. + static readonly string[] Kept = ["TIT2", "TPE1", "TXXX", "WXXX"]; + + static Id3v2Tag WithRejected (int version) => + Id3v2Tag.Read (Tag (version, [Title (version), .. Rejected.Select (f => Frame (f.Id, f.Body, version))])).Tag!; + + // A frame a branch reads and rejects is written back as stored, as a frame no branch reads is, on a save with no + // edit and on one that edits another field (review 3, N3). + [TestMethod] + [DataRow (3, false)] + [DataRow (4, false)] + [DataRow (3, true)] + [DataRow (4, true)] + public void Save_KeepsEveryRejectedFrameByteForByte (int version, bool editTitle) + { + var tag = WithRejected (version); + Assert.IsNull (tag.Artist, "the empty TPE1 is rejected"); + Assert.IsNull (tag.Album, "the TALB with encoding 9 is rejected"); + Assert.IsEmpty (tag.Pictures, "the 1-byte APIC is rejected"); + if (editTitle) + tag.Title = "New"; + + var saved = Frames (tag.Render ().Span); + + foreach (var (id, body) in Rejected) + CollectionAssert.AreEqual (Frame (id, body, version), saved[id], id); + } + + // Writing or removing every frame of an ID takes the rejected frame of that ID with it, so a set leaves one frame + // and a clear leaves none. Other rejected frames stay. + [TestMethod] + public void WritingOrRemovingEveryFrameOfAnId_ReplacesItsRejectedFrame () + { + var tag = WithRejected (4); + + tag.Artist = "Ada"; + tag.Album = null; + tag.Rating = null; + tag.RemoveInvolvedPeopleFrames (); + tag.Pictures = []; + tag.RemoveComments (); + tag.RemoveLyrics (); + tag.RemoveSyncLyrics (); + tag.RemoveGeneralObjects (); + tag.RemoveUniqueFileIds (); + tag.RemovePrivateFrames (); + tag.RemoveChapters (); + tag.RemoveTableOfContents (); + + var ids = Ids (tag.Render ().Span); + CollectionAssert.AreEquivalent (Kept, ids); + Assert.AreEqual ("Ada", Id3v2Tag.Read (tag.Render ().Span).Tag!.Artist); + } + + // Writing a field through Tag, to a value, null or "", replaces the rejected frame of the ID it is stored in, as for + // the single-instance IDs: the comment and the lyrics (review 4, N2). A rejected TXXX goes with the field that names + // its description, when the body still shows one. A rejected WXXX, and the 1-byte TXXX above, name none (the WXXX + // reader rejects only a body with nothing after its encoding byte, or an unknown encoding), so only Clear removes them. + [TestMethod] + [DataRow ("Comment", "COMM", null)] + [DataRow ("Comment", "COMM", "")] + [DataRow ("Comment", "COMM", "New")] + [DataRow ("Lyrics", "USLT", null)] + [DataRow ("Lyrics", "USLT", "")] + [DataRow ("Lyrics", "USLT", "New")] + public void WritingTheCommentOrLyrics_ReplacesItsRejectedFrame (string property, string id, string? value) + { + var tag = WithRejected (4); + + typeof (TagLibSharp2.Core.Tag).GetProperty (property)!.SetValue (tag, value); + + var ids = Ids (tag.Render ().Span); + Assert.AreEqual (string.IsNullOrEmpty (value) ? 0 : 1, ids.Count (i => i == id), string.Join (",", ids)); + Assert.HasCount (Rejected.Length + (string.IsNullOrEmpty (value) ? 0 : 1), ids, "TIT2 and every other rejected frame kept"); + } + + // A TXXX whose description is readable but whose body is rejected (no terminator, so no value). + static byte[] NamedRejected (string id, int version, int encoding = 0) => Frame (id, encoding switch { + 1 => [1, 0xFF, 0xFE, (byte)'M', 0, (byte)'o', 0, (byte)'o', 0, (byte)'d', 0], + 2 => [2, 0, (byte)'M', 0, (byte)'o', 0, (byte)'o', 0, (byte)'d'], + 3 => [3, (byte)'M', (byte)'o', (byte)'o', (byte)'d'], + _ => [0, (byte)'M', (byte)'o', (byte)'o', (byte)'d'], + }, version); + + [TestMethod] + [DataRow ("TXXX", "custom null", 1)] + [DataRow ("TXXX", "custom null", 2)] + [DataRow ("TXXX", "custom null", 3)] + [DataRow ("TXXX", "custom null")] + [DataRow ("TXXX", "custom remove")] + [DataRow ("TXXX", "custom set")] + [DataRow ("TXXX", "user text")] + [DataRow ("TXXX", "remove user text")] + public void WritingTheFieldARejectedTxxxNames_RemovesIt (string id, string edit, int encoding = 0) + { + var tag = Id3v2Tag.Read (Tag (4, Title (4), NamedRejected (id, 4, encoding))).Tag!; + Assert.IsEmpty (tag.UserTextFrames, "the TXXX is rejected"); + Assert.AreEqual (2, Ids (tag.Render ().Span).Count, "the frame is rejected and kept"); + var other = Id3v2Tag.Read (Tag (4, Title (4), NamedRejected (id, 4, encoding))).Tag!; + other.SetCustomField ("OTHER", "x"); + Assert.AreEqual (2, Ids (other.Render ().Span).Count (i => i == id), "a field of another description leaves it"); + + switch (edit) { + case "custom null": tag.SetCustomField ("MOOD"); break; + case "custom remove": tag.RemoveCustomField ("mood"); break; + case "custom set": tag.SetCustomField ("Mood", "Calm"); break; + case "remove user text": tag.RemoveUserTextFrames ("MOOD"); break; + default: tag.SetUserText ("MOOD", null); break; + } + + var ids = Ids (tag.Render ().Span); + Assert.AreEqual (edit == "custom set" ? 1 : 0, ids.Count (i => i == id), string.Join (",", ids)); + if (edit == "custom set") + Assert.AreEqual ("Calm", string.Join ("|", Id3v2Tag.Read (tag.Render ().Span).Tag!.GetCustomField ("Mood"))); + } + + // A v2.2 PIC body has a 3-character image format where an APIC body has a MIME type, so a rejected PIC is not + // written into the v2.3 tag a v2.2 tag is saved as. + [TestMethod] + public void RejectedV22Picture_IsNotWrittenAsAnApic () + { + var tag = Id3v2Tag.Read (Tag (2, FrameV22 ("TT2", [0, (byte)'T']), FrameV22 ("PIC", [0]), FrameV22 ("TAL", [9, (byte)'A']))).Tag!; + + var saved = Frames (tag.Render ().Span); + + Assert.IsFalse (saved.ContainsKey ("APIC")); + CollectionAssert.AreEqual (Frame ("TALB", [9, (byte)'A'], 3), saved["TALB"]); + } + + [TestMethod] + public void UnreadFrames_AreTagContent_AndClearRemovesThem () + { + var tag = Id3v2Tag.Read (Tag (3, Frame ("PCNT", [0, 0, 0, 9], 3))).Tag!; + Assert.IsFalse (tag.IsEmpty); + + tag.Clear (); + + Assert.IsTrue (tag.IsEmpty); + Assert.IsFalse (Frames (tag.Render ().Span).ContainsKey ("PCNT")); + } +} diff --git a/tests/TagLibSharp2.Tests/Image/ExifEditMatrixTests.cs b/tests/TagLibSharp2.Tests/Image/ExifEditMatrixTests.cs index 9af8801f..5f47c42e 100644 --- a/tests/TagLibSharp2.Tests/Image/ExifEditMatrixTests.cs +++ b/tests/TagLibSharp2.Tests/Image/ExifEditMatrixTests.cs @@ -240,11 +240,12 @@ public void Fail (string kind, string message) } } - // What each operation asks to remove. A JPEG stores only the comment, so its other setters change nothing. + // What each operation asks to remove. A JPEG stores only the comment and the title, so its other setters change + // nothing. static HashSet RemovedBy (string operation, string carrier) => operation switch { "Comment" or "Comment null" => [0x9286, 0x9C9C], "Artist" when carrier != "jpeg APP1" => [0x013B, 0x9C9D], - "Title" when carrier != "jpeg APP1" => [0x9C9B], + "Title" => [0x9C9B], "Description" when carrier != "jpeg APP1" => [0x010E], "Copyright" when carrier != "jpeg APP1" => [0x8298], _ => [], diff --git a/tests/TagLibSharp2.Tests/Image/ExifEditRefusalTests.cs b/tests/TagLibSharp2.Tests/Image/ExifEditRefusalTests.cs index 5901a766..dbe3178a 100644 --- a/tests/TagLibSharp2.Tests/Image/ExifEditRefusalTests.cs +++ b/tests/TagLibSharp2.Tests/Image/ExifEditRefusalTests.cs @@ -89,6 +89,9 @@ public void Edit_IfdsThatOverlap_WithNoCopyOfTheField_SaveUnchanged (int tag, bo [DataRow ("jpeg", "BigTIFF II", "Comment", false)] [DataRow ("jpeg", "unknown order", "Comment", false)] [DataRow ("png", "BigTIFF MM", "Title", true)] + [DataRow ("jpeg", "BigTIFF MM", "Title", false)] + [DataRow ("jpeg", "unknown order", "Title", true)] + [DataRow ("jpeg", "BigTIFF II", "Title", true)] [DataRow ("png", "BigTIFF II", "Artist", true)] [DataRow ("png", "unknown order", "Comment", true)] [DataRow ("jpeg", "BigTIFF MM", "Comment", true)] @@ -237,6 +240,7 @@ public void Edit_APointerIntoTheMiddleOfAnEditedTable_IsRefused (int tag, bool a [DataRow ("jpeg", "two Exif IFDs that overlap, with no copy", "Comment")] [DataRow ("png", "IFD1 starts inside the GPS table", "Comment")] [DataRow ("png", "IFD1 starts inside the GPS table", "Title")] + [DataRow ("jpeg", "IFD1 starts inside the GPS table", "Title")] [DataRow ("jpeg", "IFD1 starts inside the GPS table", "Comment")] [DataRow ("png", "an interoperability pointer into the GPS table's values", "Comment")] [DataRow ("jpeg", "an interoperability pointer into the GPS table's values", "Comment")] diff --git a/tests/TagLibSharp2.Tests/Image/ExifEditScalingTests.cs b/tests/TagLibSharp2.Tests/Image/ExifEditScalingTests.cs index 47c4c9a5..8423bfd5 100644 --- a/tests/TagLibSharp2.Tests/Image/ExifEditScalingTests.cs +++ b/tests/TagLibSharp2.Tests/Image/ExifEditScalingTests.cs @@ -369,17 +369,6 @@ static long SharedStripSteps (string carrier, string field, string shape, int n) static byte[] RunSharedStrip (string field, byte[] data, string name) { - // JPEG stores only the comment, so assigning Title never reaches the editor. Measure that walk on the TIFF. - if (field == "title" && name.EndsWith (".jpg", StringComparison.Ordinal)) { - var tiff = ExifOf (data); - var tag = new ImageTag (MediaFormat.Jpeg, (ImageStores)0x3F); - tag.ReadField (ImageStores.Title, "Old"); - tag.Title = "New"; - Assert.IsTrue (ExifEditor.TryRemove (tiff, 0, tag, "jpeg APP1", out var changed, out var error), error); - Assert.IsFalse (changed, "jpeg title: the TIFF holds no title"); - return data; - } - var file = Open (data, name); if (field == "comment") file.Tag!.Comment = "New"; diff --git a/tests/TagLibSharp2.Tests/Image/ImageDetectionTests.cs b/tests/TagLibSharp2.Tests/Image/ImageDetectionTests.cs index 4e7e5a85..ac6fb199 100644 --- a/tests/TagLibSharp2.Tests/Image/ImageDetectionTests.cs +++ b/tests/TagLibSharp2.Tests/Image/ImageDetectionTests.cs @@ -90,13 +90,16 @@ public static IEnumerable MarkupThatIsNotSvg () [DynamicData (nameof (MarkupThatIsNotSvg))] public void DetectFormat_OfMarkup_DoesNotDecodeIt (string name, byte[] data) { - _ = MediaFile.DetectFormat (data); - var format = MediaFile.DetectFormat (data); - Bounds.AssertAllocatesAtMost (Noise, () => format = MediaFile.DetectFormat (data), name); + // The least of several runs (Bounds.LeastAllocated). One run measured alone failed twice under a loaded full + // suite, though this path allocates 0 bytes, even with the shared pool emptied first; what disturbed those + // single measurements is not known. + var format = MediaFormat.Unknown; + var detected = Bounds.LeastAllocated (() => format = MediaFile.DetectFormat (data)); + Assert.IsTrue (detected <= Noise, $"{name}: DetectFormat allocated {detected} bytes; the bound is {Noise}"); Assert.AreNotEqual (MediaFormat.Svg, format, name); - _ = StillImageFile.IsValidFormat (data); - var image = StillImageFile.IsValidFormat (data); - Bounds.AssertAllocatesAtMost (Noise, () => image = StillImageFile.IsValidFormat (data), name); + var image = true; + var validated = Bounds.LeastAllocated (() => image = StillImageFile.IsValidFormat (data)); + Assert.IsTrue (validated <= Noise, $"{name}: IsValidFormat allocated {validated} bytes; the bound is {Noise}"); Assert.IsFalse (image, name); } diff --git a/tests/TagLibSharp2.Tests/Image/ImageHostileTests.cs b/tests/TagLibSharp2.Tests/Image/ImageHostileTests.cs index 91498596..289683f3 100644 --- a/tests/TagLibSharp2.Tests/Image/ImageHostileTests.cs +++ b/tests/TagLibSharp2.Tests/Image/ImageHostileTests.cs @@ -39,6 +39,10 @@ public static IEnumerable Samples () 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]; + // A title in XMP and in XPTitle, in each byte order: the read, the set (XPTitle removed, dc:title replaced) + // and Clear. + yield return ["jpeg-title", "a.jpg", Jpeg (JpegExif (CameraExif ("Xp")), JpegXmp (XmpPacket (Alt ("dc:title", "x"))), JpegSegment (0xFE, "c"u8.ToArray ()))]; + yield return ["jpeg-title-mm", "a.jpg", Jpeg (JpegExif (CameraExif ("Xp", bigEndian: true)), JpegSegment (0xFE, "c"u8.ToArray ()))]; 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 _)]; diff --git a/tests/TagLibSharp2.Tests/Image/ImagePlanTests.cs b/tests/TagLibSharp2.Tests/Image/ImagePlanTests.cs index dad40539..4c53bb40 100644 --- a/tests/TagLibSharp2.Tests/Image/ImagePlanTests.cs +++ b/tests/TagLibSharp2.Tests/Image/ImagePlanTests.cs @@ -33,6 +33,41 @@ public void ImagePlan_EmptyAppendsAndAZeroCopy_AddNothing () Assert.AreEqual (0, plan.SourceEnd); } + // Source bytes 0-19; the plan is source 0-3, the new bytes 90 91, then source 10-12. An insert at each offset: + // the start, inside a range, at a range's end, inside new bytes, at their end, and the end of the plan. + [TestMethod] + [DataRow (0, new byte[] { 7, 7, 0, 1, 2, 3, 90, 91, 10, 11, 12 })] + [DataRow (2, new byte[] { 0, 1, 7, 7, 2, 3, 90, 91, 10, 11, 12 })] + [DataRow (4, new byte[] { 0, 1, 2, 3, 7, 7, 90, 91, 10, 11, 12 })] + [DataRow (5, new byte[] { 0, 1, 2, 3, 90, 7, 7, 91, 10, 11, 12 })] + [DataRow (6, new byte[] { 0, 1, 2, 3, 90, 91, 7, 7, 10, 11, 12 })] + [DataRow (9, new byte[] { 0, 1, 2, 3, 90, 91, 10, 11, 12, 7, 7 })] + public void ImagePlan_Insert_PutsTheBytesAtTheOutputOffset (int at, byte[] expected) + { + var source = Enumerable.Range (0, 20).Select (n => (byte)n).ToArray (); + var plan = new ImagePlan (); + plan.Copy (0, 4); + plan.Add ([90, 91]); + plan.Copy (10, 3); + + plan.Insert (at, [7, 7]); + + Assert.AreEqual (11, plan.Length); + CollectionAssert.AreEqual (expected, plan.Materialize (source)); + Assert.AreEqual (13, plan.SourceEnd, "ranges keep their original offsets"); + } + + [TestMethod] + public void ImagePlan_InsertOutsideTheOutput_Throws_AndEmptyInsertsNothing () + { + var plan = new ImagePlan (); + plan.Copy (0, 4); + Assert.ThrowsExactly (() => plan.Insert (5, [1])); + Assert.ThrowsExactly (() => plan.Insert (-1, [1])); + plan.Insert (2, []); + Assert.AreEqual (4, plan.Length); + } + [TestMethod] public void ImagePlan_NegativeCopy_Throws () { diff --git a/tests/TagLibSharp2.Tests/Image/ImageTestBuilder.cs b/tests/TagLibSharp2.Tests/Image/ImageTestBuilder.cs index 3ad23a41..ee84bfd8 100644 --- a/tests/TagLibSharp2.Tests/Image/ImageTestBuilder.cs +++ b/tests/TagLibSharp2.Tests/Image/ImageTestBuilder.cs @@ -327,6 +327,60 @@ public static byte[] JpegXmp (string packet) => public static byte[] JpegExif (byte[] tiff) => JpegSegment (0xE1, Concat ("Exif\0\0"u8.ToArray (), tiff)); + /// The marker and payload of each segment before the scan (T.81 §B.1.1.4), in file order. + public static List<(byte Marker, byte[] Payload)> JpegSegments (byte[] jpeg) + { + var segments = new List<(byte, byte[])> (); + var i = 2; + while (i + 4 <= jpeg.Length && jpeg[i] == 0xFF && jpeg[i + 1] is not (0xDA or 0xD9)) { + var length = BinaryPrimitives.ReadUInt16BigEndian (jpeg.AsSpan (i + 2)); + segments.Add ((jpeg[i + 1], jpeg[(i + 4)..(i + 2 + length)])); + i += 2 + length; + } + + return segments; + } + + /// The packets of the standard XMP APP1 segments (XMP Part 3 §1.1.3), in file order. + public static List JpegXmpPackets (byte[] jpeg) => [ + .. JpegSegments (jpeg) + .Where (s => s.Marker == 0xE1 && s.Payload.AsSpan ().StartsWith ("http://ns.adobe.com/xap/1.0/\0"u8)) + .Select (s => Encoding.UTF8.GetString (s.Payload, 29, s.Payload.Length - 29)) + ]; + + /// The TIFF of each Exif APP1 segment, in file order. + public static List JpegExifBlocks (byte[] jpeg) => [ + .. JpegSegments (jpeg).Where (s => s.Marker == 0xE1 && s.Payload.AsSpan ().StartsWith ("Exif\0\0"u8)).Select (s => s.Payload[6..]) + ]; + + /// + /// A camera-shaped Exif TIFF in either byte order: IFD0 (Make, the Exif IFD and GPS pointers, and XPTitle when + /// is set), an Exif IFD with DateTimeOriginal and an interoperability pointer, an + /// interoperability IFD, a GPS IFD, and IFD1 with a 4-byte thumbnail. XPTitle is BYTE UTF-16LE with a + /// two-byte terminator and no byte order mark in both byte orders, as exiftool 13.55 writes it (measured). + /// + public static byte[] CameraExif (string? xpTitle, bool bigEndian = false) + { + const int Ifd0 = 8, ExifIfd = 62, Interop = 92, Gps = 110, Ifd1 = 128, Make = 158, Date = 164, Values = 184; + var title = xpTitle is null ? [] : Encoding.Unicode.GetBytes (xpTitle + "\0"); + var thumb = Values + title.Length; + var tiff = new TiffBuilder (thumb + 4, bigEndian).Header (Ifd0); + var ifd0 = new List<(int, int, long, long)> { (0x010F, 2, 6, Make), (0x8769, 4, 1, ExifIfd), (0x8825, 4, 1, Gps) }; + if (xpTitle is not null) + ifd0.Add ((0x9C9B, 1, title.Length, Values)); + // A table always takes 4 entries' room, so every later offset stays where the layout puts it. + while (ifd0.Count < 4) + ifd0.Add ((0x0131, 2, 4, bigEndian ? 0x78797A00 : 0x007A7978)); + ifd0.Sort ((a, b) => a.Item1.CompareTo (b.Item1)); + tiff.Table (Ifd0, [.. ifd0], next: Ifd1) + .Table (ExifIfd, [(0x9003, 2, 20, Date), (0xA005, 4, 1, Interop)]) + .Table (Interop, [(0x0001, 2, 4, bigEndian ? 0x52393800 : 0x00383952)]) + .Table (Gps, [(0x0001, 2, 2, bigEndian ? 0x4E000000 : 0x0000004E)]) + .Table (Ifd1, [(0x0201, 4, 1, thumb), (0x0202, 4, 1, 4)]) + .Bytes (Make, "Canon\0"u8).Bytes (Date, "2001:01:01 00:00:00\0"u8).Bytes (Values, title).Bytes (thumb, [0xFF, 0xD8, 0xFF, 0xD9]); + return tiff.ToArray (); + } + /// An Exif SRATIONAL (TIFF 6.0 type 10), big-endian. public static byte[] SRational (int numerator, int denominator) { diff --git a/tests/TagLibSharp2.Tests/Image/JpegTitleTests.cs b/tests/TagLibSharp2.Tests/Image/JpegTitleTests.cs new file mode 100644 index 00000000..c0a18fd4 --- /dev/null +++ b/tests/TagLibSharp2.Tests/Image/JpegTitleTests.cs @@ -0,0 +1,412 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Xml.Linq; +using TagLibSharp2.Core; +using TagLibSharp2.Image; +using TagLibSharp2.Tests.Core; +using TagLibSharp2.Tests.Kit; +using static TagLibSharp2.Tests.Image.ExifTestData; +using static TagLibSharp2.Tests.Image.ImageTestBuilder; + +namespace TagLibSharp2.Tests.Image; + +/// +/// The JPEG title: XMP dc:title (XMP Part 1 §8.2.2.4), or, when the XMP holds none, the Windows XPTitle tag +/// (IFD0 0x9C9B) of the first Exif segment. +/// +[TestClass] +[TestCategory ("Unit")] +public class JpegTitleTests +{ + static byte[] SpacedXmp (string packet) => + JpegSegment (0xE1, Concat ("http://ns.adobe.com/xap/1.0/ \0"u8.ToArray (), System.Text.Encoding.UTF8.GetBytes (packet))); + + static string Titles (string items) => XmpPacket ($" {items}\n"); + + // Expected values are what exiftool 13.55 reports as Title (XMP-dc) or XPTitle (IFD0) for the same bytes, except + // where a row says otherwise. + static IEnumerable<(string Shape, byte[] Jpeg, string? Title)> ReadRows () + { + // XMP Part 1 §7.9: x-default is the value a reader shows when it has no language of its own. + yield return ("x-default after another language", Jpeg (JpegXmp (Titles ("TitreDefault"))), "Default"); + // exiftool shows no plain Title here (only Title-fr-FR and Title-de); exiv2 lists both, the first first. + yield return ("no x-default: the first item", Jpeg (JpegXmp (Titles ("TitreTitel"))), "Titre"); + // exiftool -XMP-dc:Title="Tom's \"A\" & " writes character and entity references. + yield return ("entity and character references", Jpeg (JpegXmp (Titles ("Tom's "A" & <B> ☺"))), "Tom's \"A\" & ☺"); + yield return ("CDATA", Jpeg (JpegXmp (Titles (" & c]]>"))), "a & c"); + yield return ("attribute form", Jpeg (JpegXmp (XmpPacket ("", " dc:title='Attr & 'x''"))), "Attr & 'x'"); + yield return ("a title in a nested description is not the title", Jpeg (JpegXmp (XmpPacket (" nested\n"))), null); + // ImageIO ends the JPEG packet with a NUL after the trailer (XMP Part 1 §7.3: the trailer ends the packet). + yield return ("NUL after the trailer (ImageIO)", Jpeg (JpegSegment (0xE1, Concat ("http://ns.adobe.com/xap/1.0/\0"u8.ToArray (), System.Text.Encoding.UTF8.GetBytes (Titles ("Nul")), [0x0A, 0]))), "Nul"); + yield return ("byte order mark before the packet", Jpeg (JpegXmp ("\uFEFF" + Titles ("Bom"))), "Bom"); + // Some writers put a space before the NUL of the XMP signature. exiftool reads that packet (warning + // "Non-standard header"), and ignores it once a standard one is in the file; ImageIO and exiv2 never read it. + yield return ("XMP with a space in its signature", Jpeg (SpacedXmp (Titles ("Spaced"))), "Spaced"); + yield return ("standard XMP after a spaced one: the standard one", Jpeg (SpacedXmp (Titles ("Spaced")), JpegXmp (XmpPacket (" l\n")), JpegExif (CameraExif ("Xp"))), "Xp"); + yield return ("XPTitle, little-endian", Jpeg (JpegExif (CameraExif ("Old ünï 🎵"))), "Old ünï 🎵"); + yield return ("XPTitle, big-endian", Jpeg (JpegExif (CameraExif ("Old ünï 🎵", bigEndian: true))), "Old ünï 🎵"); + yield return ("XMP and XPTitle: XMP wins", Jpeg (JpegExif (CameraExif ("Xp")), JpegXmp (Titles ("Xmp"))), "Xmp"); + yield return ("XMP without a title: XPTitle", Jpeg (JpegExif (CameraExif ("Xp")), JpegXmp (XmpPacket (" l\n"))), "Xp"); + yield return ("XMP that is not well-formed: XPTitle", Jpeg (JpegExif (CameraExif ("Xp")), JpegXmp (Titles ("Xmp").Replace ("", "", StringComparison.Ordinal))), "Xp"); + // A DTD is refused, so no entity is expanded. exiv2 shows no title; exiftool shows the text "&e;". + yield return ("a DTD is not read", Jpeg (JpegXmp ("]>" + Titles ("&e;"))), null); + } + + public static IEnumerable Reads () => ReadRows ().Select (row => new object[] { row.Shape }); + + [TestMethod] + [DynamicData (nameof (Reads))] + public void Read_TakesTheXmpTitle_ThenXpTitle (string shape) + { + var row = ReadRows ().Single (r => r.Shape == shape); + Assert.AreEqual (row.Title, Open (row.Jpeg, "a.jpg").Tag!.Title, shape); + } + + // The entry points (data, stream, path) and the saves (path, async path, Render). + static readonly string[] Opens = ["data", "stream", "path"]; + + static StillImageFile OpenBy (string how, byte[] data, MockFileSystem fs) => how switch { + "stream" => (StillImageFile)MediaFile.Read (new MemoryStream (data, writable: false), "a.jpg").File!, + "path" => (StillImageFile)MediaFile.Read ("/in.jpg", fs).File!, + _ => Open (data, "a.jpg"), + }; + + // The edit through every entry point and save. Every one gives the same bytes, or the same refusal; the result is + // those bytes (the input when refused) and the refusal. + static (byte[] Output, string? Error) EditEveryWay (byte[] input, Action edit) + { + byte[]? output = null; + string? error = null; + foreach (var how in Opens) { + var fs = new MockFileSystem (); + fs.AddFile ("/in.jpg", input); + var file = OpenBy (how, input, fs); + edit (file.Tag!); + var sync = file.SaveToFile ("/out.jpg", fs); + var async = file.SaveToFileAsync ("/async.jpg", fs).GetAwaiter ().GetResult (); + var rendered = file.Render ().ToArray (); + Assert.AreEqual (sync.Error, async.Error, how); + if (!sync.IsSuccess) { + Assert.IsFalse (fs.FileExists ("/out.jpg") || fs.FileExists ("/async.jpg"), $"{how}: a refused save writes nothing"); + CollectionAssert.AreEqual (input, rendered, $"{how}: Render of a refused edit is the input"); + } else { + CollectionAssert.AreEqual (rendered, fs.ReadAllBytes ("/out.jpg"), $"{how}: path save"); + CollectionAssert.AreEqual (rendered, fs.ReadAllBytes ("/async.jpg"), $"{how}: async path save"); + } + + if (output is not null) { + CollectionAssert.AreEqual (output, rendered, $"{how}: same bytes as the first entry point"); + Assert.AreEqual (error, sync.Error, how); + } + + output = rendered; + error = sync.Error; + } + + return (output!, error); + } + + // The x-default value of each dc:title in a packet (XMP Part 1 §7.9). + static List DcTitles (string packet) => [ + .. XDocument.Parse (packet.TrimStart ('\uFEFF').TrimEnd ('\0', '\n')) + .Descendants (Dc + "title") + .Select (t => t.Element (Rdf + "Alt")?.Elements (Rdf + "li").SingleOrDefault (li => li.Attribute (XNamespace.Xml + "lang")?.Value == "x-default")?.Value) + ]; + + static readonly bool[] ByteOrders = [false, true]; + static readonly string[] SetAndClear = ["New ✓ <&>", "(null)"]; + + public static IEnumerable ExifEdits () => + from bigEndian in ByteOrders + from value in SetAndClear + select new object[] { bigEndian, value }; + + // A set or a clear removes XPTitle through the Exif field edit, which compacts IFD0 in place: every other table, + // entry, value, pointer and next offset a reader sees keeps its bytes (the Exif IFD, interoperability and GPS + // pointers, IFD1 and its thumbnail). The title then lives in XMP only, which Windows reads next + // (System.Title photo metadata policy, JPEG read paths 1-3), and no second Exif segment is added. + [TestMethod] + [DynamicData (nameof (ExifEdits))] + public void Edit_RemovesXpTitleThroughTheExifFieldEdit_AndWritesXmp (bool bigEndian, string value) + { + var title = value == "(null)" ? null : value; + var tiff = CameraExif ("Old", bigEndian); + var input = Jpeg (JpegExif (tiff), JpegSegment (0xFE, "c"u8.ToArray ())); + + var (output, error) = EditEveryWay (input, tag => tag.Title = title); + + Assert.IsNull (error); + Assert.AreEqual (title, Open (output, "a.jpg").Tag!.Title); + Assert.AreEqual ("c", Open (output, "a.jpg").Tag!.Comment); + var exif = JpegExifBlocks (output); + Assert.AreEqual (1, exif.Count, "one Exif segment"); + Assert.AreEqual (tiff.Length, exif[0].Length, "the Exif block keeps its size: nothing after IFD0's entries moves"); + AssertOnlyTheCopiesAreGone (tiff, exif[0], $"{bigEndian} {value}", 0x9C9B); + var packets = JpegXmpPackets (output); + Assert.AreEqual (title is null ? 0 : 1, packets.Count, "one XMP segment, only when there is a title to hold"); + if (title is not null) + Assert.AreSequenceEqual ([title], DcTitles (packets[0])); + } + + // Clearing the title and changing the comment in one save updates both fields' copies: the Exif ones go, and + // the XMP comment holds the new value. + [TestMethod] + public void ClearTitle_AndEditComment_InOneSave_RemovesEveryCopyOfBoth () + { + var tiff = ExifTiff ([(0x010F, "Canon"), (0x9C9B, "XP title"), (0x9C9C, "XP comment")], [(0x9286, "ASCII\0\0\0Old comment")]); + var packet = XmpPacket (Alt ("dc:title", "Old title") + Alt ("exif:UserComment", "Old comment") + " Keep\n"); + var input = Jpeg (JpegExif (tiff), JpegXmp (packet), JpegSegment (0xFE, "Old"u8.ToArray ())); + + var (output, error) = EditEveryWay (input, tag => { + tag.Title = null; + tag.Comment = "New"; + }); + + Assert.IsNull (error); + var reread = Open (output, "a.jpg").Tag!; + Assert.IsNull (reread.Title); + Assert.AreEqual ("New", reread.Comment); + AssertOnlyTheCopiesAreGone (tiff, JpegExifBlocks (output).Single (), "Exif", 0x9C9B, 0x9C9C, 0x9286); + var doc = XDocument.Parse (JpegXmpPackets (output).Single ()); + Assert.AreEqual (0, doc.Descendants (Dc + "title").Count (), "dc:title removed"); + Assert.AreEqual ("New", doc.Descendants (Exif + "UserComment").Single ().Value, "exif:UserComment holds the new comment"); + Assert.AreEqual ("Keep", doc.Descendants ().Single (e => e.Name.LocalName == "Label").Value); + } + + static readonly byte[] Jfif = JpegApp (0xE0, "JFIF\0", "\x01\x02\0\0\x01\0\x01\0\0"); + static readonly byte[] Icc = JpegApp (0xE2, "ICC_PROFILE\0", "\x01\x01profile"); + static readonly byte[] Photoshop = JpegApp (0xED, "Photoshop 3.0\0", "8BIM"); + + // A segment by its marker and the signature a reader knows it by. + static string Kind ((byte Marker, byte[] Payload) segment) => segment.Marker switch { + 0xE0 => "JFIF", + 0xE1 when segment.Payload.AsSpan ().StartsWith ("Exif\0\0"u8) => "Exif", + 0xE1 => "XMP", + 0xE2 => "ICC", + 0xED => "Photoshop", + 0xFE => "COM", + 0xDB => "DQT", + _ => $"0x{segment.Marker:X2}", + }; + + static IEnumerable<(string Shape, byte[] Jpeg, Action Edit, string Order)> PlacementRows () + { + Action set = tag => { + tag.Title = "新标题 ✓"; + tag.Comment = "新注释"; + }; + yield return ("no APPn", Jpeg (JpegSegment (0xFE, "c"u8.ToArray ())), set, "XMP COM"); + yield return ("JFIF", Jpeg (Jfif, JpegSegment (0xDB, [0, 1])), set, "JFIF XMP DQT COM"); + yield return ("JFIF, Exif, ICC", Jpeg (Jfif, JpegExif (CameraExif (null)), Icc), set, "JFIF Exif XMP ICC COM"); + yield return ("Exif, Photoshop", Jpeg (JpegExif (CameraExif ("Old")), Photoshop), set, "Exif XMP Photoshop COM"); + // ImageIO and exiv2 do not read a packet whose signature has a space, so the title goes to a new standard one + // (as exiftool 13.55 does), and the old packet's own title, if any, is replaced as a copy. + yield return ("XMP with a space in its signature", Jpeg (Jfif, SpacedXmp (XmpPacket (Alt ("dc:title", "Old")))), set, "JFIF XMP XMP COM"); + yield return ("XMP after the ICC profile", Jpeg (Jfif, Icc, JpegXmp (XmpPacket (""))), set, "JFIF ICC XMP COM"); + // Clear keeps an Ultra HDR primary's hdrgm properties in a new packet, which then also takes the title. + yield return ("Clear of an Ultra HDR primary, then a title", Jpeg (Jfif, GainMapTestData.JpegXmpBytes (GainMapTestData.UltraHdrGainMap), Icc), tag => { + tag.Clear (); + set (tag); + }, "JFIF XMP ICC COM"); + yield return ("Clear, then a title", Jpeg (Jfif, JpegExif (CameraExif ("Old")), JpegXmp (XmpPacket (Alt ("dc:title", "Old"))), Icc), tag => { + tag.Clear (); + set (tag); + }, "JFIF XMP ICC COM"); + } + + public static IEnumerable Placements () => PlacementRows ().Select (row => new object[] { row.Shape }); + + // A title on an image with no XMP gets one new packet after the JFIF and Exif segments (where exiftool 13.55 + // puts one when no APP13 is there; measured). An image with XMP keeps its one packet where it is. + [TestMethod] + [DynamicData (nameof (Placements))] + public void Edit_WritesOneXmpPacket_AfterTheJfifAndExifSegments (string shape) + { + var row = PlacementRows ().Single (r => r.Shape == shape); + + var (output, error) = EditEveryWay (row.Jpeg, row.Edit); + + Assert.IsNull (error, shape); + Assert.AreEqual (row.Order, string.Join (" ", JpegSegments (output).Where (s => s.Marker != 0xC0).Select (Kind)), shape); + Assert.AreSequenceEqual (["新标题 ✓"], DcTitles (JpegXmpPackets (output).Single ()), $"{shape}: one standard packet"); + foreach (var spaced in JpegSegments (output).Where (s => s.Payload.AsSpan ().StartsWith ("http://ns.adobe.com/xap/1.0/ \0"u8))) + Assert.AreSequenceEqual (["新标题 ✓"], DcTitles (System.Text.Encoding.UTF8.GetString (spaced.Payload[30..])), $"{shape}: the spaced packet's copy"); + if (shape.Contains ("Ultra HDR", StringComparison.Ordinal)) + Assert.AreEqual ("1.0", ParsePacket (JpegXmpPackets (output).Single ()).Descendants ().SelectMany (e => e.Attributes ()).Single (a => a.Name.LocalName == "Version").Value, "the gain-map version stays"); + var reread = Open (output, "a.jpg").Tag!; + Assert.AreEqual ("新标题 ✓", reread.Title, shape); + Assert.AreEqual ("新注释", reread.Comment, shape); + Assert.AreEqual (0, JpegExifBlocks (output).Sum (tiff => ExifReaderModel.AnyReader (tiff).CopiesOf (0x9C9B).Count), $"{shape}: no XPTitle is left"); + } + + const string RdfOpen = ""; + const string RdfClose = ""; + + // Packets with no dc:title. exiftool writes the namespace on the description that uses it, so a packet with + // only xmp:Rating declares no dc prefix; Adobe writes simple properties as attributes of an empty description. + static IEnumerable<(string Shape, string Packet)> AddRows () + { + yield return ("dc declared on the description", XmpPacket (" l\n")); + yield return ("dc not declared (exiftool, a rating only)", "\n" + RdfOpen + "\n \n 5\n \n" + RdfClose + "\n"); + yield return ("empty description with attributes (Adobe)", RdfOpen + "" + RdfClose); + yield return ("dc bound to another namespace", RdfOpen + "o" + RdfClose); + yield return ("dc declared on the root", "c" + RdfClose); + yield return ("rdf as the default namespace", ""); + yield return ("two descriptions", RdfOpen + "l" + RdfClose); + // exiftool's packet once every property is gone (taglib-sharp sample_panasonic.jpg): no description at all. + yield return ("no description: an empty rdf:RDF", "\n" + RdfOpen + "\n\n" + RdfClose + "\n"); + yield return ("no description: an empty rdf:RDF element", ""); + yield return ("no description: rdf as the default namespace", ""); + yield return ("byte order mark, CRLF and a NUL tail", "\uFEFF" + XmpPacket (" l\r\n").Replace ("\n", "\r\n", StringComparison.Ordinal) + "\n\0"); + } + + public static IEnumerable Adds () => AddRows ().Select (row => new object[] { row.Shape }); + + // The packet as XML, with every element that has no content written as an empty element. + static string Canonical (XDocument doc) + { + foreach (var element in doc.Descendants ().Where (e => !e.Nodes ().Any ())) + element.RemoveNodes (); + return doc.ToString (SaveOptions.DisableFormatting); + } + + static XDocument ParsePacket (string packet) => XDocument.Parse (packet.TrimStart ('\uFEFF').TrimEnd ('\0', '\n')); + + // A title added to a packet that has none goes into its first top-level description, with the dc namespace + // declared on it when no prefix for it is in scope (XML Namespaces 1.0 §5). Everything else in the packet stays. + [TestMethod] + [DynamicData (nameof (Adds))] + public void Edit_AddsTheTitleToAPacketWithout_AsWellFormedXmp (string shape) + { + var packet = AddRows ().Single (r => r.Shape == shape).Packet; + var input = Jpeg (JpegXmp (packet), JpegSegment (0xFE, "c"u8.ToArray ())); + + var (output, error) = EditEveryWay (input, tag => tag.Title = "New ✓ <&>"); + + Assert.IsNull (error, shape); + Assert.AreEqual ("New ✓ <&>", Open (output, "a.jpg").Tag!.Title, shape); + var updated = JpegXmpPackets (output).Single (); + Assert.AreEqual (packet.StartsWith ('\uFEFF'), updated.StartsWith ('\uFEFF'), $"{shape}: the byte order mark is kept"); + Assert.AreEqual (packet.EndsWith ('\0'), updated.EndsWith ('\0'), $"{shape}: the tail is kept"); + var doc = ParsePacket (updated); + var title = doc.Descendants (Dc + "title").Single (); + var description = doc.Descendants (Rdf + "Description").First (); + Assert.AreEqual (description, title.Parent, $"{shape}: in the first description"); + Assert.AreEqual ("New ✓ <&>", title.Element (Rdf + "Alt")!.Elements (Rdf + "li").Single (li => li.Attribute (XNamespace.Xml + "lang")?.Value == "x-default").Value, shape); + title.Remove (); + if (shape.StartsWith ("no description", StringComparison.Ordinal)) { + // The new description is about the image itself (rdf:about="") and is the last child of rdf:RDF. + Assert.AreEqual ("", description.Attribute (Rdf + "about")?.Value, shape); + Assert.AreEqual (Rdf + "RDF", description.Parent!.Name, shape); + Assert.IsNull (description.NextNode, shape); + description.Remove (); + } + + Assert.AreEqual (Canonical (ParsePacket (packet)), Canonical (doc), $"{shape}: everything else stays"); + } + + static IEnumerable<(string Shape, byte[] Jpeg, string Title, string Reason)> RefusalRows () + { + var bare = Jpeg (JpegSegment (0xFE, "c"u8.ToArray ())); + yield return ("XMP that is not well-formed", Jpeg (JpegXmp (XmpPacket ("").Replace ("", "", StringComparison.Ordinal))), "New", "The JPEG XMP packet is not well-formed XML, so Title cannot be added to it."); + yield return ("XMP with no rdf:RDF", Jpeg (JpegXmp ("")), "New", "The JPEG XMP packet has no rdf:RDF, so Title cannot be added to it."); + yield return ("a character XML cannot store", bare, "bad\u0001", "The new Title has a character XML cannot store, so it cannot be added to the new JPEG XMP packet."); + // T.81 §B.1.1.4: a segment's 16-bit length counts itself, so an APP1 holds at most 65,533 bytes. + yield return ("a title past one APP1 segment, new packet", bare, new string ('x', 65_500), "A new JPEG XMP packet with the edited fields would not fit in one APP1 segment."); + yield return ("a title past one APP1 segment, existing packet", Jpeg (JpegXmp (XmpPacket (Alt ("dc:title", "Old")))), new string ('é', 33_000), "The JPEG XMP packet would no longer fit in one APP1 segment after the edit."); + } + + public static IEnumerable Refusals () => RefusalRows ().Select (row => new object[] { row.Shape }); + + // A title the XMP cannot hold is refused with its own reason, and nothing is written. + [TestMethod] + [DynamicData (nameof (Refusals))] + public void Edit_ThatXmpCannotHold_IsRefused_AndWritesNothing (string shape) + { + var row = RefusalRows ().Single (r => r.Shape == shape); + + var (output, error) = EditEveryWay (row.Jpeg, tag => tag.Title = row.Title); + + Assert.AreEqual (row.Reason, error, shape); + CollectionAssert.AreEqual (row.Jpeg, output, shape); + } + + // The longest title that fits makes an APP1 segment of exactly 65,535 bytes; one more character is refused. + [TestMethod] + [DataRow (false)] + [DataRow (true)] + public void Edit_TitleAtTheSegmentLimit_FitsExactly (bool existingPacket) + { + var input = existingPacket ? Jpeg (JpegXmp (XmpPacket ("")), JpegSegment (0xFE, "c"u8.ToArray ())) : Jpeg (JpegSegment (0xFE, "c"u8.ToArray ())); + static int XmpSegmentLength (byte[] jpeg) => JpegSegments (jpeg).Single (s => s.Marker == 0xE1).Payload.Length + 2; + var oneChar = EditEveryWay (input, tag => tag.Title = "x").Output; + var longest = 1 + 65_535 - XmpSegmentLength (oneChar); + + var fits = EditEveryWay (input, tag => tag.Title = new string ('x', longest)); + var over = EditEveryWay (input, tag => tag.Title = new string ('x', longest + 1)); + + Assert.IsNull (fits.Error); + Assert.AreEqual (65_535, XmpSegmentLength (fits.Output)); + Assert.AreEqual (longest, Open (fits.Output, "a.jpg").Tag!.Title!.Length); + StringAssert.Contains (over.Error, "would"); + CollectionAssert.AreEqual (input, over.Output); + } + + // Inputs that grow with n: segments before the scan (COM, Exif and XMP APP1, only the first of each read), a + // title with n language items and no x-default (each is read), and n properties before the title. + static byte[] Grown (string shape, int n) => shape switch { + "segments" => Jpeg ([.. Enumerable.Range (0, n).SelectMany (i => new[] { JpegSegment (0xFE, "c"u8.ToArray ()), JpegExif (CameraExif ("Xp")), JpegXmp (XmpPacket ("")) })]), + "language items" => Jpeg (JpegXmp (Titles (string.Concat (Enumerable.Range (0, n).Select (i => $"Title {i}"))))), + _ => Jpeg (JpegXmp (XmpPacket (string.Concat (Enumerable.Range (0, n).Select (i => $" {i}\n")) + Alt ("dc:title", "Old")))), + }; + + // The read, a set and a clear allocate in proportion to the input. + [TestMethod] + [DoNotParallelize] + [DataRow ("segments", "read")] + [DataRow ("language items", "read")] + [DataRow ("properties", "read")] + [DataRow ("segments", "set")] + [DataRow ("language items", "set")] + [DataRow ("properties", "set")] + [DataRow ("properties", "clear")] + public void ReadAndEdit_AllocateLinearly (string shape, string operation) + { + const int n = 300; + Assert.AreEqual (shape == "language items" ? "Title 0" : shape == "segments" ? "Xp" : "Old", Open (Grown (shape, n), "a.jpg").Tag!.Title, shape); + Bounds.AssertLinearAllocation (size => Grown (shape, size), data => { + var file = Open (data, "a.jpg"); + if (operation == "read") + return; + file.Tag!.Title = operation == "set" ? "New" : null; + Assert.IsTrue (file.SaveToFile ("/a.jpg", new MockFileSystem ()).IsSuccess, $"{shape} {operation}"); + }, n, runs: 3); + } + + // XMP Part 3 §1.1.3 has one standard packet. When a file holds two, the title goes to the first, which readers + // read; the second is left as it is. + [TestMethod] + public void Edit_OfAFileWithTwoStandardPackets_AddsTheTitleToTheFirst () + { + var second = XmpPacket (" second\n"); + var input = Jpeg (JpegXmp (XmpPacket (" first\n")), JpegXmp (second)); + + var (output, error) = EditEveryWay (input, tag => tag.Title = "New"); + + Assert.IsNull (error); + var packets = JpegXmpPackets (output); + Assert.AreEqual (2, packets.Count); + Assert.AreSequenceEqual (["New"], DcTitles (packets[0])); + Assert.AreEqual (second, packets[1]); + } + + // Windows and exiftool write XPTitle with no byte order mark; one written with it (this library's earlier + // version did) reads without it, as exiftool 13.55 shows it. + [TestMethod] + public void Read_XpTitleWithAByteOrderMark_DropsTheMark () + { + var tiff = new TiffBuilder (8 + 18 + 12).Header (8).Table (8, [(0x9C9B, 1, 12, 26)]).Bytes (26, [0xFF, 0xFE, (byte)'B', 0, (byte)'o', 0, (byte)'m', 0, 0, 0, 0, 0]).ToArray (); + Assert.AreEqual ("Bom", Open (Jpeg (JpegExif (tiff)), "a.jpg").Tag!.Title); + } +} diff --git a/tests/TagLibSharp2.Tests/Image/MirrorCopyTests.cs b/tests/TagLibSharp2.Tests/Image/MirrorCopyTests.cs index 5017136b..2240fdaf 100644 --- a/tests/TagLibSharp2.Tests/Image/MirrorCopyTests.cs +++ b/tests/TagLibSharp2.Tests/Image/MirrorCopyTests.cs @@ -284,7 +284,7 @@ public static IEnumerable CommentCopies () } } - // A JPEG or GIF stores only the comment, and its Exif and XMP copies are changed with it (rule 4). + // A JPEG or GIF comment edit changes its Exif and XMP copies with it (rule 4). [TestMethod] [DynamicData (nameof (CommentCopies))] public void JpegAndGif_CommentEdit_ChangesTheExifAndXmpCopies (string format, string carrier, byte[] input, string? value) @@ -342,14 +342,88 @@ public void Jpeg_CommentEdit_ThatCannotUpdateACopy_IsRefusedWithItsOwnReason () } } + // Extended XMP (XMP Part 3 §1.1.3.1) is split over segments and keyed by a digest, so a copy in it cannot be updated: + // an edit of a field whose property it names (after a prefix, or as an element) is refused. Its digest and + // base64 data hold no ':' or '<', so a name that only appears there does not refuse. [TestMethod] - public void JpegAndGif_TitleIsNotStored_SoItsCopiesAreNotTouched () + [DataRow ("Title", "Old", "The JPEG extended XMP holds a title, a copy of Title that cannot be updated here.")] + [DataRow ("Title", "Old", "The JPEG extended XMP holds a title, a copy of Title that cannot be updated here.")] + [DataRow ("Title", "GDepth:Data='aGVsbG8titleZ29vZGJ5ZQ=='", null)] + [DataRow ("Comment", "", "The JPEG extended XMP holds a UserComment, a copy of Comment that cannot be updated here.")] + [DataRow ("Comment", "GDepth:Data='aGVsbG8UserCommentZ29v'", null)] + public void Jpeg_EditOfAFieldTheExtendedXmpHolds_IsRefused (string field, string body, string? reason) { - var jpeg = Jpeg (JpegXmp (CommentPacket), JpegSegment (0xFE, "Old"u8.ToArray ())); - var file = Open (jpeg, "a.jpg"); + var extended = JpegApp (0xE1, "http://ns.adobe.com/xmp/extension/\0", "0123456789ABCDEF0123456789ABCDEF\0\0\0\x10\0\0\0\0" + body); + var input = Jpeg (extended, JpegSegment (0xFE, "Old"u8.ToArray ())); + var file = Open (input, "a.jpg"); + typeof (Tag).GetProperty (field)!.SetValue (file.Tag, "New"); + + var fs = new MockFileSystem (); + var save = file.SaveToFile ("/a.jpg", fs); + + Assert.AreEqual (reason, save.Error); + if (reason is null) + Assert.IsTrue (file.Render ().ToArray ().AsSpan ().IndexOf (extended) >= 0, "the extended XMP keeps its bytes"); + else + Assert.IsFalse (fs.FileExists ("/a.jpg")); + } + + [TestMethod] + public void Gif_TitleIsNotStored_SoItsCopiesAreNotTouched () + { + // GIF89a has a comment extension and no title. Assigning Title changes nothing. + var gif = Gif (GifComment ("Old")); + var file = Open (gif, "a.gif"); file.Tag!.Title = "New"; Assert.IsNull (file.Tag.Title); - CollectionAssert.AreEqual (jpeg, file.Render ().ToArray ()); + CollectionAssert.AreEqual (gif, file.Render ().ToArray ()); + } + + static byte[] TitleExif () => ExifTiff ([(0x010F, "Canon"), (0x9C9B, "Old XP title"), (0x9C9C, "Keep XP comment")], []); + + public static IEnumerable TitleCopies () + { + foreach (var value in new[] { "New ✓ <&>", null }) { + yield return ["APP1 Exif", Jpeg (JpegExif (TitleExif ()), JpegSegment (0xFE, "Old"u8.ToArray ())), value!]; + yield return ["APP1 XMP", Jpeg (JpegXmp (CommentPacket), JpegSegment (0xFE, "Old"u8.ToArray ())), value!]; + yield return ["APP1 Exif and XMP", Jpeg (JpegExif (TitleExif ()), JpegXmp (CommentPacket), JpegSegment (0xFE, "Old"u8.ToArray ())), value!]; + yield return ["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!]; + } + } + + // A JPEG title lives in XMP dc:title (XMP Part 1 §8.2.2.4). An edit replaces it there (or removes it) and removes + // every XPTitle (IFD0 0x9C9B); the comment and its copies keep their values. + [TestMethod] + [DynamicData (nameof (TitleCopies))] + public void Jpeg_TitleEdit_ChangesTheXmpTitle_AndRemovesXpTitle (string carrier, byte[] input, string? value) + { + var file = Open (input, "a.jpg"); + file.Tag!.Title = value; + var save = file.SaveToFile ("/a.jpg", new MockFileSystem ()); + Assert.IsTrue (save.IsSuccess, save.Error); + var output = file.Render ().ToArray (); + var reread = Open (output, "a.jpg").Tag!; + Assert.AreEqual (value, reread.Title, carrier); + Assert.AreEqual ("Old", reread.Comment, carrier); + + if (carrier.Contains ("Exif", StringComparison.Ordinal)) + AssertOnlyTheCopiesAreGone (TitleExif (), ExifOf (output), carrier, 0x9C9B); + // A packet whose signature has a space is a copy; the title's store is a standard packet, new when needed. + var packets = JpegSegments (output).Where (s => s.Marker == 0xE1 && s.Payload.AsSpan ().StartsWith ("http://ns.adobe.com/xap/1.0/"u8)).ToList (); + var expected = carrier == "APP1 Exif" ? (value is null ? 0 : 1) : carrier.Contains ("space", StringComparison.Ordinal) && value is not null ? 2 : 1; + Assert.AreEqual (expected, packets.Count, $"{carrier}: XMP packets"); + foreach (var packet in packets) { + var text = Encoding.UTF8.GetString (packet.Payload); + var doc = XDocument.Parse (text[text.IndexOf ('<', StringComparison.Ordinal)..]); + var titles = doc.Descendants (Dc + "title").ToList (); + Assert.AreEqual (value is null ? 0 : 1, titles.Count, carrier); + if (value is not null) + Assert.AreEqual (value, titles[0].Element (Rdf + "Alt")!.Elements (Rdf + "li").Single ().Value, carrier); + if (doc.Descendants (Exif + "UserComment").Any ()) + Assert.AreEqual ("Old xmp comment", doc.Descendants (Exif + "UserComment").Single ().Element (Rdf + "Alt")!.Elements ().First ().Value, carrier); + } + + Assert.AreEqual (carrier == "APP1 Exif" ? 0 : 1, packets.Count (p => Encoding.UTF8.GetString (p.Payload).Contains ("Old xmp comment", StringComparison.Ordinal)), $"{carrier}: the comment copy stays"); } static byte[] JoinGifXmpSubBlocks (byte[] gif) diff --git a/tests/TagLibSharp2.Tests/Image/MultiPictureTests.cs b/tests/TagLibSharp2.Tests/Image/MultiPictureTests.cs index a3660ae5..7137d367 100644 --- a/tests/TagLibSharp2.Tests/Image/MultiPictureTests.cs +++ b/tests/TagLibSharp2.Tests/Image/MultiPictureTests.cs @@ -22,6 +22,12 @@ 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 ())]; + // The image has no XMP: the title's new packet goes before the MPF segment, so the index moves. + yield return ["title added in a new XMP before the MPF segment", new Action (t => t.Title = "New title")]; + yield return ["clear then a title: only the primary image gets XMP", new Action (t => { + t.Clear (); + t.Title = "New title"; + })]; } static byte[] SecondImage () => Jpeg ( diff --git a/tests/TagLibSharp2.Tests/Image/XmpMirrorTests.cs b/tests/TagLibSharp2.Tests/Image/XmpMirrorTests.cs index 0873a7c0..5bb57132 100644 --- a/tests/TagLibSharp2.Tests/Image/XmpMirrorTests.cs +++ b/tests/TagLibSharp2.Tests/Image/XmpMirrorTests.cs @@ -39,16 +39,28 @@ public static IEnumerable PacketShapes () yield return ["nested description is not a property", XmpPacket (" nested\n" + Alt ("dc:title", "Old")), "nested"]; } + static readonly string[] TitleFormats = ["png", "jpeg"]; + + // PNG mirrors its title into XMP; a JPEG stores its title there. + public static IEnumerable PacketShapesByFormat () => + from format in TitleFormats + from row in PacketShapes () + select new object[] { format, row[0], row[1], row[2] }; + + static string OnlyPacket (string format, byte[] file) => + format == "png" ? PngTexts (file, "XML:com.adobe.xmp").Single () : JpegXmpPackets (file).Single (); + [TestMethod] - [DynamicData (nameof (PacketShapes))] - public void Edit_UpdatesTheTitleInEveryPacketShape (string shape, string packet, string? kept) + [DynamicData (nameof (PacketShapesByFormat))] + public void Edit_UpdatesTheTitleInEveryPacketShape (string format, string shape, string packet, string? kept) { - var file = Open (Png (Xmp (packet)), "a.png"); + var name = format == "png" ? "a.png" : "a.jpg"; + var file = Open (format == "png" ? Png (Xmp (packet)) : Jpeg (JpegXmp (packet)), name); file.Tag!.Title = "New"; - var save = file.SaveToFile ("/a.png", new MockFileSystem ()); + var save = file.SaveToFile ("/" + name, new MockFileSystem ()); Assert.IsTrue (save.IsSuccess, $"{shape}: {save.Error}"); - var updated = PngTexts (file.Render ().ToArray (), "XML:com.adobe.xmp").Single (); + var updated = OnlyPacket (format, file.Render ().ToArray ()); 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 () @@ -66,7 +78,7 @@ public void Edit_UpdatesTheTitleInEveryPacketShape (string shape, string packet, StringAssert.Contains (updated, kept, shape); file.Tag.Title = null; - var cleared = PngTexts (file.Render ().ToArray (), "XML:com.adobe.xmp").Single (); + var cleared = OnlyPacket (format, file.Render ().ToArray ()); 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"))) @@ -140,7 +152,7 @@ public void Edit_ManyMirroredXmpCopies_AllocatesLinearly (string format) Assert.AreEqual (copies, CountPacketTitles (sizedFile.Render ().ToArray (), "New"), $"{format} N={n}"); } - // PNG stores a title, so dc:title is the mirrored copy. JPEG and GIF store a comment, so the copy is UserComment. + // PNG mirrors its title into dc:title. JPEG and GIF mirror their comment into UserComment. static void SetMirroredField (Tag tag, string format) { if (format == "png") diff --git a/tests/TagLibSharp2.Tests/Kit/CountingFileSystem.cs b/tests/TagLibSharp2.Tests/Kit/CountingFileSystem.cs new file mode 100644 index 00000000..0fe58569 --- /dev/null +++ b/tests/TagLibSharp2.Tests/Kit/CountingFileSystem.cs @@ -0,0 +1,41 @@ +// 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.Tests.Core; + +namespace TagLibSharp2.Tests.Kit; + +/// +/// A whose read streams count what they read, to pin how much a path read reads +/// ( over every stream it opened). +/// +public sealed class CountingFileSystem : IFileSystem +{ + readonly MockFileSystem _inner = new (); + readonly List _opened = []; + + public long BytesRead => _opened.Sum (stream => stream.BytesRead); + + public void AddFile (string path, byte[] data) => _inner.AddFile (path, data); + + public Stream OpenRead (string path) + { + var stream = new CountingStream (_inner.OpenRead (path)); + _opened.Add (stream); + return stream; + } + + public bool FileExists (string path) => _inner.FileExists (path); + public Stream OpenReadWrite (string path) => _inner.OpenReadWrite (path); + public Stream Create (string path) => _inner.Create (path); + public byte[] ReadAllBytes (string path) => _inner.ReadAllBytes (path); + public Task ReadAllBytesAsync (string path, CancellationToken cancellationToken = default) => _inner.ReadAllBytesAsync (path, cancellationToken); + public void WriteAllBytes (string path, ReadOnlySpan data) => _inner.WriteAllBytes (path, data); + public Task WriteAllBytesAsync (string path, ReadOnlyMemory data, CancellationToken cancellationToken = default) => _inner.WriteAllBytesAsync (path, data, cancellationToken); + public void Delete (string path) => _inner.Delete (path); + public void Move (string sourcePath, string destinationPath) => _inner.Move (sourcePath, destinationPath); + public string? GetDirectoryName (string path) => _inner.GetDirectoryName (path); + public string GetFileName (string path) => _inner.GetFileName (path); + public string CombinePath (string path1, string path2) => _inner.CombinePath (path1, path2); +} diff --git a/tests/TagLibSharp2.Tests/Kit/StreamResyncReadTests.cs b/tests/TagLibSharp2.Tests/Kit/StreamResyncReadTests.cs new file mode 100644 index 00000000..d8811839 --- /dev/null +++ b/tests/TagLibSharp2.Tests/Kit/StreamResyncReadTests.cs @@ -0,0 +1,58 @@ +// 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.Ogg; +using TagLibSharp2.Tests.Aac; + +using MpegPsTestBuilder = TagLibSharp2.Tests.Mpeg.MpegPsTestBuilder; + +namespace TagLibSharp2.Tests.Kit; + +/// +/// A stream read that resyncs (scans forward for the next frame, page, pack or element after bytes that are not one) +/// reads a bounded multiple of the file, however often a hostile file makes it resync: a junk byte before every unit, +/// or a run of near-miss start codes. The Matroska case is in MatroskaFillerTests. +/// +[TestClass] +[TestCategory ("Unit")] +public class StreamResyncReadTests +{ + // Each hostile body, built to about `size` bytes, with the extension it is read under. + static readonly Dictionary Build)> Bodies = new () { + // An ADTS frame, then one junk byte, repeated: every frame after the first is found by a resync. + ["aac junk between frames"] = (".aac", size => Repeat ([.. AacTestBuilder.Adts (1), 0x00], size)), + // MPEG audio frames with a junk byte after each. + ["mp3 junk between frames"] = (".mp3", size => Repeat ([.. AacTestBuilder.Mp3Frames (1), 0x00], size)), + // A program stream, then start codes with an ID that begins no pack. + ["mpeg-ps near-miss start codes"] = (".mpg", size => [.. MpegPsTestBuilder.ProgramStream (new MpegPsTestBuilder.Options { VideoFrames = 1, AudioFrames = 0, AudioKind = MpegPsTestBuilder.Audio.None }), .. Repeat ([0x00, 0x00, 0x01, 0x00], size)]), + // An Ogg Vorbis file, then a junk byte and an audio page, repeated. + ["ogg junk between pages"] = (".ogg", size => [.. TestBuilders.Ogg.CreateMinimalFile (), .. Repeat ([0x00, .. OggPageHelper.BuildOggPage ([new byte[4]], OggPageFlags.None, 1, 1, 9)], size)]), + }; + + static byte[] Repeat (byte[] unit, int size) => + Enumerable.Range (0, Math.Max (1, size / unit.Length)).SelectMany (_ => unit).ToArray (); + + static readonly int[] Sizes = [10_000, 100_000, 1_000_000]; + static readonly bool[] Skips = [false, true]; + + public static IEnumerable Cases => + from body in Bodies.Keys + from size in Sizes + from skip in Skips + select new object[] { body, size, skip }; + + [TestMethod] + [DynamicData (nameof (Cases))] + public void StreamRead_ReadsABoundedMultipleOfTheFile (string body, int size, bool skipPictures) + { + var (extension, build) = Bodies[body]; + var file = build (size); + using var counting = new CountingStream (new MemoryStream (file, writable: false)); + + _ = MediaFile.Read (counting, new MediaReadOptions { SkipPictures = skipPictures }, "a" + extension); + + Console.WriteLine ($"{body} {file.Length}: {(double)counting.BytesRead / file.Length:F1}x"); + Assert.IsLessThanOrEqualTo (16L * file.Length, counting.BytesRead, $"{counting.BytesRead} bytes read for {file.Length}"); + } +} diff --git a/tests/TagLibSharp2.Tests/Matroska/MatroskaAlbumKeepsTitleTests.cs b/tests/TagLibSharp2.Tests/Matroska/MatroskaAlbumKeepsTitleTests.cs new file mode 100644 index 00000000..0433cb25 --- /dev/null +++ b/tests/TagLibSharp2.Tests/Matroska/MatroskaAlbumKeepsTitleTests.cs @@ -0,0 +1,631 @@ +// 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.Matroska; +using TagLibSharp2.Tests.Core; + +namespace TagLibSharp2.Tests.Matroska; + +/// +/// Setting the album never changes the title (issue #188). ffprobe and MediaInfo show the TITLE of the last Tag +/// that has one as the file title, and ffprobe lets a TITLE in a Tag with no TargetType string replace the +/// segment title; a TITLE at target 50 is also the track title when no narrower TITLE exists (tagging.html, +/// "A tag defined for a given TargetTypeValue also applies to all Targets with numerically smaller +/// TargetTypeValues"). So the expected TITLE and ALBUM lists below, in file order, are what those readers +/// see: measured with ffprobe 8 and MediaInfo 26.10 on the same layouts. +/// +public partial class MatroskaFileTests +{ + const string OldTitle = "OldTitle"; + const string OldAlbum = "OldAlbum"; + const string NewAlbum = "NewAlbum"; + const string NewTitle = "NewTitle"; + + static readonly Dictionary> AlbumLayouts = new () { + ["none"] = () => AlbumLayout (null, Untargeted ()), + ["segment title"] = () => AlbumLayout (OldTitle, Untargeted ()), + ["untargeted TITLE"] = () => AlbumLayout (null, Untargeted (Simple ("TITLE", OldTitle))), + ["segment title, untargeted TITLE"] = () => AlbumLayout (OldTitle, Untargeted (Simple ("TITLE", OldAlbum))), + ["untargeted ALBUM"] = () => AlbumLayout (null, Untargeted (Simple ("ALBUM", OldAlbum))), + ["segment title, untargeted ALBUM"] = () => AlbumLayout (OldTitle, Untargeted (Simple ("ALBUM", OldAlbum))), + ["target 50 TITLE"] = () => AlbumLayout (null, Untargeted (), Tag (50, Simple ("TITLE", OldAlbum))), + ["segment title, target 50 TITLE"] = () => AlbumLayout (OldTitle, Untargeted (), Tag (50, Simple ("TITLE", OldAlbum))), + ["target 50 TITLE, untargeted ALBUM"] = () => AlbumLayout (null, Untargeted (Simple ("ALBUM", OldAlbum)), Tag (50, Simple ("TITLE", OldAlbum))), + ["target 30 TITLE"] = () => AlbumLayout (null, Untargeted (), Tag (30, Simple ("TITLE", OldTitle))), + ["target 50 and 30 TITLE"] = () => AlbumLayout (null, Tag (50, Simple ("TITLE", OldAlbum)), Tag (30, Simple ("TITLE", OldTitle))), + ["target 70 TITLE"] = () => AlbumLayout (null, Untargeted (), Tag (70, Simple ("TITLE", "Coll"))), + ["segment title, no Tags"] = () => FileWith (SegmentInfo (OldTitle), Master (0x1F43B675, new byte[] { 1 })), + ["untargeted TITLE, target 50 TITLE"] = () => AlbumLayout (null, Untargeted (Simple ("TITLE", OldTitle)), Tag (50, Simple ("TITLE", OldAlbum))), + ["target 50 TITLE, untargeted TITLE"] = () => AlbumLayout (null, Tag (50, Simple ("TITLE", OldAlbum)), Untargeted (Simple ("TITLE", OldTitle))), + ["target 30 TITLE, then target 50 TITLE"] = () => AlbumLayout (null, Untargeted (), Tag (30, Simple ("TITLE", OldTitle)), Tag (50, Simple ("TITLE", OldAlbum))), + ["target 30 ARTIST, then target 50 TITLE"] = () => AlbumLayout (null, Untargeted (), Tag (30, Simple ("ARTIST", "Art")), Tag (50, Simple ("TITLE", OldAlbum))), + ["target 50 and 40 TITLE"] = () => AlbumLayout (null, Untargeted (), Tag (50, Simple ("TITLE", OldAlbum)), Tag (40, Simple ("TITLE", "Part"))), + ["untargeted TITLE, target 50 TITLE in two languages"] = () => AlbumLayout (null, Untargeted (Simple ("TITLE", OldTitle)), Tag (50, Simple ("TITLE", "AlbumFr", isDefault: false), Simple ("TITLE", OldAlbum))), + }; + + static readonly Dictionary> AlbumEdits = new () { + ["set album"] = t => t.Album = NewAlbum, + ["clear album"] = t => t.Album = null, + ["write back album"] = t => t.Album = t.Album, + ["set album, then title"] = t => { t.Album = NewAlbum; t.Title = NewTitle; }, + ["set title, then album"] = t => { t.Title = NewTitle; t.Album = NewAlbum; }, + ["set album, then clear it"] = t => { t.Album = NewAlbum; t.Album = null; }, + }; + + // (layout, edit) -> Title and Album this library reads back, and the TITLE and ALBUM texts of the Tags in file order. + static readonly Dictionary<(string, string), (string? Title, string? Album, string[] Titles, string[] Albums)> AlbumExpected = new () { + [("none", "set album")] = (null, NewAlbum, [], [NewAlbum]), + [("none", "clear album")] = (null, null, [], []), + [("none", "write back album")] = (null, null, [], []), + [("none", "set album, then title")] = (NewTitle, NewAlbum, [NewTitle], [NewAlbum]), + [("none", "set title, then album")] = (NewTitle, NewAlbum, [NewTitle], [NewAlbum]), + + [("segment title", "set album")] = (OldTitle, NewAlbum, [], [NewAlbum]), + [("segment title", "clear album")] = (OldTitle, null, [], []), + [("segment title", "write back album")] = (OldTitle, null, [], []), + [("segment title", "set album, then title")] = (NewTitle, NewAlbum, [NewTitle], [NewAlbum]), + [("segment title", "set title, then album")] = (NewTitle, NewAlbum, [NewTitle], [NewAlbum]), + + // The untargeted TITLE is ffmpeg's title. The album is read from it until an ALBUM exists; a clear moves the title to 30. + [("untargeted TITLE", "set album")] = (OldTitle, NewAlbum, [OldTitle], [NewAlbum]), + [("untargeted TITLE", "clear album")] = (OldTitle, null, [OldTitle], []), + [("untargeted TITLE", "write back album")] = (OldTitle, OldTitle, [OldTitle], []), + [("untargeted TITLE", "set album, then title")] = (NewTitle, NewAlbum, [OldTitle, NewTitle], [NewAlbum]), + [("untargeted TITLE", "set title, then album")] = (NewTitle, NewAlbum, [OldTitle, NewTitle], [NewAlbum]), + + [("segment title, untargeted TITLE", "set album")] = (OldTitle, NewAlbum, [OldAlbum], [NewAlbum]), + [("segment title, untargeted TITLE", "clear album")] = (OldTitle, null, [OldTitle], []), + [("segment title, untargeted TITLE", "write back album")] = (OldTitle, OldAlbum, [OldAlbum], []), + [("segment title, untargeted TITLE", "set album, then title")] = (NewTitle, NewAlbum, [OldAlbum, NewTitle], [NewAlbum]), + [("segment title, untargeted TITLE", "set title, then album")] = (NewTitle, NewAlbum, [OldAlbum, NewTitle], [NewAlbum]), + + [("untargeted ALBUM", "set album")] = (null, NewAlbum, [], [NewAlbum]), + [("untargeted ALBUM", "clear album")] = (null, null, [], []), + [("untargeted ALBUM", "write back album")] = (null, OldAlbum, [], [OldAlbum]), + [("untargeted ALBUM", "set album, then title")] = (NewTitle, NewAlbum, [NewTitle], [NewAlbum]), + [("untargeted ALBUM", "set title, then album")] = (NewTitle, NewAlbum, [NewTitle], [NewAlbum]), + + [("segment title, untargeted ALBUM", "set album")] = (OldTitle, NewAlbum, [], [NewAlbum]), + [("segment title, untargeted ALBUM", "clear album")] = (OldTitle, null, [], []), + [("segment title, untargeted ALBUM", "write back album")] = (OldTitle, OldAlbum, [], [OldAlbum]), + [("segment title, untargeted ALBUM", "set album, then title")] = (NewTitle, NewAlbum, [NewTitle], [NewAlbum]), + [("segment title, untargeted ALBUM", "set title, then album")] = (NewTitle, NewAlbum, [NewTitle], [NewAlbum]), + + // The track inherits the album TITLE, so it keeps that title at 30, after the album's Tag. + [("target 50 TITLE", "set album")] = (OldAlbum, NewAlbum, [NewAlbum, OldAlbum], []), + [("target 50 TITLE", "clear album")] = (OldAlbum, null, [OldAlbum], []), + [("target 50 TITLE", "write back album")] = (OldAlbum, OldAlbum, [OldAlbum], []), + [("target 50 TITLE", "set album, then title")] = (NewTitle, NewAlbum, [NewAlbum, NewTitle], []), + [("target 50 TITLE", "set title, then album")] = (NewTitle, NewAlbum, [NewAlbum, NewTitle], []), + + [("segment title, target 50 TITLE", "set album")] = (OldTitle, NewAlbum, [NewAlbum, OldTitle], []), + [("segment title, target 50 TITLE", "clear album")] = (OldTitle, null, [OldTitle], []), + [("segment title, target 50 TITLE", "write back album")] = (OldTitle, OldAlbum, [OldAlbum], []), + [("segment title, target 50 TITLE", "set album, then title")] = (NewTitle, NewAlbum, [NewAlbum, NewTitle], []), + [("segment title, target 50 TITLE", "set title, then album")] = (NewTitle, NewAlbum, [NewAlbum, NewTitle], []), + + [("target 50 TITLE, untargeted ALBUM", "set album")] = (OldAlbum, NewAlbum, [NewAlbum, OldAlbum], [NewAlbum]), + [("target 50 TITLE, untargeted ALBUM", "clear album")] = (OldAlbum, null, [OldAlbum], []), + [("target 50 TITLE, untargeted ALBUM", "write back album")] = (OldAlbum, OldAlbum, [OldAlbum], [OldAlbum]), + [("target 50 TITLE, untargeted ALBUM", "set album, then title")] = (NewTitle, NewAlbum, [NewAlbum, NewTitle], [NewAlbum]), + [("target 50 TITLE, untargeted ALBUM", "set title, then album")] = (NewTitle, NewAlbum, [NewAlbum, NewTitle], [NewAlbum]), + + [("target 30 TITLE", "set album")] = (OldTitle, NewAlbum, [OldTitle], [NewAlbum]), + [("target 30 TITLE", "clear album")] = (OldTitle, null, [OldTitle], []), + [("target 30 TITLE", "write back album")] = (OldTitle, null, [OldTitle], []), + [("target 30 TITLE", "set album, then title")] = (NewTitle, NewAlbum, [NewTitle], [NewAlbum]), + [("target 30 TITLE", "set title, then album")] = (NewTitle, NewAlbum, [NewTitle], [NewAlbum]), + + [("target 50 and 30 TITLE", "set album")] = (OldTitle, NewAlbum, [NewAlbum, OldTitle], []), + [("target 50 and 30 TITLE", "clear album")] = (OldTitle, null, [OldTitle], []), + [("target 50 and 30 TITLE", "write back album")] = (OldTitle, OldAlbum, [OldAlbum, OldTitle], []), + [("target 50 and 30 TITLE", "set album, then title")] = (NewTitle, NewAlbum, [NewAlbum, NewTitle], []), + [("target 50 and 30 TITLE", "set title, then album")] = (NewTitle, NewAlbum, [NewAlbum, NewTitle], []), + + [("target 70 TITLE", "set album")] = (null, NewAlbum, ["Coll"], [NewAlbum]), + [("target 70 TITLE", "clear album")] = (null, null, ["Coll"], []), + [("target 70 TITLE", "write back album")] = (null, null, ["Coll"], []), + [("target 70 TITLE", "set album, then title")] = (NewTitle, NewAlbum, ["Coll", NewTitle], [NewAlbum]), + [("target 70 TITLE", "set title, then album")] = (NewTitle, NewAlbum, ["Coll", NewTitle], [NewAlbum]), + + [("segment title, no Tags", "set album")] = (OldTitle, NewAlbum, [], [NewAlbum]), + [("segment title, no Tags", "clear album")] = (OldTitle, null, [], []), + [("segment title, no Tags", "write back album")] = (OldTitle, null, [], []), + [("segment title, no Tags", "set album, then title")] = (NewTitle, NewAlbum, [NewTitle], [NewAlbum]), + [("segment title, no Tags", "set title, then album")] = (NewTitle, NewAlbum, [NewTitle], [NewAlbum]), + + // With an explicit album TITLE beside it, ffmpeg's untargeted TITLE is the title, whichever Tag comes first. + [("untargeted TITLE, target 50 TITLE", "set album")] = (OldTitle, NewAlbum, [OldTitle, NewAlbum, OldTitle], []), + [("untargeted TITLE, target 50 TITLE", "clear album")] = (OldTitle, null, [OldTitle], []), + [("untargeted TITLE, target 50 TITLE", "write back album")] = (OldTitle, OldAlbum, [OldTitle, OldAlbum], []), + [("untargeted TITLE, target 50 TITLE", "set album, then title")] = (NewTitle, NewAlbum, [OldTitle, NewAlbum, NewTitle], []), + [("untargeted TITLE, target 50 TITLE", "set title, then album")] = (NewTitle, NewAlbum, [OldTitle, NewAlbum, NewTitle], []), + + [("target 50 TITLE, untargeted TITLE", "set album")] = (OldTitle, NewAlbum, [NewAlbum, OldTitle, OldTitle], []), + [("target 50 TITLE, untargeted TITLE", "clear album")] = (OldTitle, null, [OldTitle], []), + [("target 50 TITLE, untargeted TITLE", "write back album")] = (OldTitle, OldAlbum, [OldAlbum, OldTitle], []), + [("target 50 TITLE, untargeted TITLE", "set album, then title")] = (NewTitle, NewAlbum, [NewAlbum, OldTitle, NewTitle], []), + [("target 50 TITLE, untargeted TITLE", "set title, then album")] = (NewTitle, NewAlbum, [NewAlbum, OldTitle, NewTitle], []), + + [("none", "set album, then clear it")] = (null, null, [], []), + [("segment title", "set album, then clear it")] = (OldTitle, null, [], []), + [("untargeted TITLE", "set album, then clear it")] = (OldTitle, null, [OldTitle], []), + [("segment title, untargeted TITLE", "set album, then clear it")] = (OldTitle, null, [OldTitle], []), + [("untargeted ALBUM", "set album, then clear it")] = (null, null, [], []), + [("segment title, untargeted ALBUM", "set album, then clear it")] = (OldTitle, null, [], []), + [("target 50 TITLE", "set album, then clear it")] = (OldAlbum, null, [OldAlbum], []), + [("segment title, target 50 TITLE", "set album, then clear it")] = (OldTitle, null, [OldTitle], []), + [("target 50 TITLE, untargeted ALBUM", "set album, then clear it")] = (OldAlbum, null, [OldAlbum], []), + [("target 30 TITLE", "set album, then clear it")] = (OldTitle, null, [OldTitle], []), + [("target 50 and 30 TITLE", "set album, then clear it")] = (OldTitle, null, [OldTitle], []), + [("target 70 TITLE", "set album, then clear it")] = (null, null, ["Coll"], []), + [("segment title, no Tags", "set album, then clear it")] = (OldTitle, null, [], []), + [("untargeted TITLE, target 50 TITLE", "set album, then clear it")] = (OldTitle, null, [OldTitle], []), + [("target 50 TITLE, untargeted TITLE", "set album, then clear it")] = (OldTitle, null, [OldTitle], []), + + // The track's Tag moves after the album's, so the last Tag with a TITLE is the track's. + [("target 30 TITLE, then target 50 TITLE", "set album")] = (OldTitle, NewAlbum, [NewAlbum, OldTitle], []), + [("target 30 TITLE, then target 50 TITLE", "clear album")] = (OldTitle, null, [OldTitle], []), + [("target 30 TITLE, then target 50 TITLE", "write back album")] = (OldTitle, OldAlbum, [OldTitle, OldAlbum], []), + [("target 30 TITLE, then target 50 TITLE", "set album, then title")] = (NewTitle, NewAlbum, [NewAlbum, NewTitle], []), + [("target 30 TITLE, then target 50 TITLE", "set title, then album")] = (NewTitle, NewAlbum, [NewAlbum, NewTitle], []), + [("target 30 TITLE, then target 50 TITLE", "set album, then clear it")] = (OldTitle, null, [OldTitle], []), + + [("target 30 ARTIST, then target 50 TITLE", "set album")] = (OldAlbum, NewAlbum, [NewAlbum, OldAlbum], []), + [("target 30 ARTIST, then target 50 TITLE", "clear album")] = (OldAlbum, null, [OldAlbum], []), + [("target 30 ARTIST, then target 50 TITLE", "write back album")] = (OldAlbum, OldAlbum, [OldAlbum], []), + [("target 30 ARTIST, then target 50 TITLE", "set album, then title")] = (NewTitle, NewAlbum, [NewAlbum, NewTitle], []), + [("target 30 ARTIST, then target 50 TITLE", "set title, then album")] = (NewTitle, NewAlbum, [NewAlbum, NewTitle], []), + [("target 30 ARTIST, then target 50 TITLE", "set album, then clear it")] = (OldAlbum, null, [OldAlbum], []), + + // A part TITLE is narrower than the album's: the track reads it, so nothing is kept at 30. + [("target 50 and 40 TITLE", "set album")] = ("Part", NewAlbum, [NewAlbum, "Part"], []), + [("target 50 and 40 TITLE", "clear album")] = ("Part", null, ["Part"], []), + [("target 50 and 40 TITLE", "write back album")] = ("Part", OldAlbum, [OldAlbum, "Part"], []), + [("target 50 and 40 TITLE", "set album, then title")] = (NewTitle, NewAlbum, [NewAlbum, "Part", NewTitle], []), + [("target 50 and 40 TITLE", "set title, then album")] = (NewTitle, NewAlbum, [NewAlbum, "Part", NewTitle], []), + [("target 50 and 40 TITLE", "set album, then clear it")] = ("Part", null, ["Part"], []), + + // The default-language album TITLE is the album; a set keeps the other language, a clear removes both. + [("untargeted TITLE, target 50 TITLE in two languages", "set album")] = (OldTitle, NewAlbum, [OldTitle, "AlbumFr", NewAlbum, OldTitle], []), + [("untargeted TITLE, target 50 TITLE in two languages", "clear album")] = (OldTitle, null, [OldTitle], []), + [("untargeted TITLE, target 50 TITLE in two languages", "write back album")] = (OldTitle, OldAlbum, [OldTitle, "AlbumFr", OldAlbum], []), + [("untargeted TITLE, target 50 TITLE in two languages", "set album, then title")] = (NewTitle, NewAlbum, [OldTitle, "AlbumFr", NewAlbum, NewTitle], []), + [("untargeted TITLE, target 50 TITLE in two languages", "set title, then album")] = (NewTitle, NewAlbum, [OldTitle, "AlbumFr", NewAlbum, NewTitle], []), + [("untargeted TITLE, target 50 TITLE in two languages", "set album, then clear it")] = (OldTitle, null, [OldTitle], []), + }; + + static readonly string[] MatroskaEntryPoints = ["MatroskaFile.Read", "ReadFromData", "stream", "path", "async path"]; + + public static IEnumerable AlbumEditCases () + { + foreach (var layout in AlbumLayouts.Keys) { + foreach (var edit in AlbumEdits.Keys) { + foreach (var entry in MatroskaEntryPoints) + yield return [layout, edit, entry]; + } + } + } + + [TestMethod] + [DynamicData (nameof (AlbumEditCases))] + public async Task AlbumEdit_NeverChangesTheTitleReadersShow (string layout, string edit, string entry) + { + var original = AlbumLayouts[layout] (); + var expected = AlbumExpected[(layout, edit)]; + + var saved = await EditAndSave (original, entry, AlbumEdits[edit]); + + var again = MatroskaFile.Read (saved); + Assert.IsTrue (again.IsSuccess, again.Error); + var context = $"{layout} / {edit} / {entry}"; + Assert.AreEqual (expected.Title, again.File!.Tag.Title, context + ": Title"); + Assert.AreEqual (expected.Album, again.File.Tag.Album, context + ": Album"); + CollectionAssert.AreEqual (expected.Titles, FileLevelTexts (saved, "TITLE"), context + ": TITLE in file order"); + CollectionAssert.AreEqual (expected.Albums, FileLevelTexts (saved, "ALBUM"), context + ": ALBUM in file order"); + } + + // ffmpeg keeps ALBUM in its untargeted Tag; the album goes there, and a file without that Tag gets one Tag at 50. + [TestMethod] + [DataRow ("none", "ENCODER,ALBUM")] + [DataRow ("segment title, no Tags", "50:ALBUM")] + [DataRow ("target 30 TITLE", "ENCODER,ALBUM|30:TITLE")] + public void Album_GoesInTheUntargetedTag_OrANewTargetFiftyTag (string layout, string expected) + { + var original = AlbumLayouts[layout] (); + var file = MatroskaFile.Read (original).File!; + + file.Tag.Album = NewAlbum; + + Assert.AreEqual (expected, TagShapes (file.Render (original).ToArray ()), layout); + } + + // Each Tag as "level:NAMES" (no level for an empty Targets), in file order. + static string TagShapes (byte[] file) + { + Assert.IsTrue (TrySegmentBody (file, out var body, out _)); + var shapes = new List (); + foreach (var tags in Children (body, MatroskaIds.Tags)) { + foreach (var tag in Children (tags, MatroskaIds.Tag)) { + var levels = Children (Children (tag, MatroskaIds.Targets)[0], MatroskaIds.TargetTypeValue); + var names = new List (); + foreach (var simple in Children (tag, MatroskaIds.SimpleTag)) + names.Add (Encoding.UTF8.GetString (Children (simple, MatroskaIds.TagName)[0])); + shapes.Add ((levels.Count == 1 ? levels[0][^1] + ":" : "") + string.Join (",", names)); + } + } + + return string.Join ("|", shapes); + } + + // The album artist twin: ffprobe and MediaInfo show the ARTIST of the last Tag that has one, and a target-50 + // ARTIST is the track's artist while no narrower ARTIST exists. On a file with ffmpeg's untargeted Tag the album + // artists go in ALBUM_ARTIST, ffmpeg's name (ffprobe ALBUM_ARTIST, MediaInfo ALBUM_ARTIST, exiftool AlbumArtist). + // A file tagged by the spec alone keeps the spec's model, where the track inherits the album's ARTIST. + static readonly Dictionary> AlbumArtistLayouts = new () { + ["none"] = () => AlbumLayout (null, Untargeted ()), + ["untargeted ARTIST"] = () => AlbumLayout (null, Untargeted (Simple ("ARTIST", "Art"))), + ["untargeted ARTIST and ALBUM_ARTIST"] = () => AlbumLayout (null, Untargeted (Simple ("ARTIST", "Art"), Simple ("ALBUM_ARTIST", "AArt"))), + ["target 50 ARTIST"] = () => AlbumLayout (null, Tag (50, Simple ("ARTIST", "AArt")), Tag (30, Simple ("TITLE", "Song"))), + ["target 50 and 30 ARTIST"] = () => AlbumLayout (null, Tag (50, Simple ("ARTIST", "AArt")), Tag (30, Simple ("ARTIST", "Art"))), + ["target 30 ARTIST"] = () => AlbumLayout (null, Untargeted (), Tag (30, Simple ("ARTIST", "Art"))), + ["untargeted Tag, target 50 ARTIST"] = () => AlbumLayout (null, Untargeted (), Tag (50, Simple ("ARTIST", "AArt"))), + ["untargeted Tag, target 70 ARTIST"] = () => AlbumLayout (null, Untargeted (), Tag (70, Simple ("ARTIST", "Coll")), Tag (30, Simple ("TITLE", "Song"))), + ["target 70 ARTIST"] = () => AlbumLayout (null, Tag (70, Simple ("ARTIST", "Coll")), Tag (30, Simple ("TITLE", "Song"))), + }; + + static readonly Dictionary> AlbumArtistEdits = new () { + ["set"] = t => t.AlbumArtists = ["NewAA"], + ["clear"] = t => t.AlbumArtists = [], + ["write back"] = t => t.AlbumArtists = t.AlbumArtists, + ["set, then artist"] = t => { t.AlbumArtists = ["NewAA"]; t.Artist = "NewArt"; }, + ["artist, then set"] = t => { t.Artist = "NewArt"; t.AlbumArtists = ["NewAA"]; }, + ["set, then clear"] = t => { t.AlbumArtists = ["NewAA"]; t.AlbumArtists = []; }, + ["set to the artist"] = t => t.AlbumArtists = t.Artist is null ? [] : [t.Artist], + }; + + // (layout, edit) -> Artist, AlbumArtists joined, and the ARTIST and ALBUM_ARTIST texts of the Tags in file order. + // Clearing ALBUM_ARTIST lets the album-level ARTIST show through, as AlbumArtists documents. + static readonly Dictionary<(string, string), (string? Artist, string AlbumArtists, string[] Artists, string[] AlbumArtistNames)> AlbumArtistExpected = new () { + [("none", "set")] = (null, "NewAA", [], ["NewAA"]), + [("none", "clear")] = (null, "", [], []), + [("none", "write back")] = (null, "", [], []), + [("none", "set, then artist")] = ("NewArt", "NewAA", ["NewArt"], ["NewAA"]), + [("none", "artist, then set")] = ("NewArt", "NewAA", ["NewAA", "NewArt"], []), + [("none", "set, then clear")] = (null, "", [], []), + + [("untargeted ARTIST", "set")] = ("Art", "NewAA", ["Art"], ["NewAA"]), + [("untargeted ARTIST", "clear")] = ("Art", "", ["Art"], []), + [("untargeted ARTIST", "write back")] = ("Art", "Art", ["Art"], []), + [("untargeted ARTIST", "set, then artist")] = ("NewArt", "NewAA", ["Art", "NewArt"], ["NewAA"]), + [("untargeted ARTIST", "artist, then set")] = ("NewArt", "NewAA", ["NewAA", "NewArt"], []), + [("untargeted ARTIST", "set, then clear")] = ("Art", "Art", ["Art"], []), + + [("untargeted ARTIST and ALBUM_ARTIST", "set")] = ("Art", "NewAA", ["Art"], ["NewAA"]), + [("untargeted ARTIST and ALBUM_ARTIST", "clear")] = ("Art", "Art", ["Art"], []), + [("untargeted ARTIST and ALBUM_ARTIST", "write back")] = ("Art", "AArt", ["Art"], ["AArt"]), + [("untargeted ARTIST and ALBUM_ARTIST", "set, then artist")] = ("NewArt", "NewAA", ["Art", "NewArt"], ["NewAA"]), + [("untargeted ARTIST and ALBUM_ARTIST", "artist, then set")] = ("NewArt", "NewAA", ["Art", "NewArt"], ["NewAA"]), + [("untargeted ARTIST and ALBUM_ARTIST", "set, then clear")] = ("Art", "Art", ["Art"], []), + + // Tagged by the spec alone: the track inherits the target-50 ARTIST, so the artist follows the album artist. + [("target 50 ARTIST", "set")] = ("NewAA", "NewAA", ["NewAA"], []), + [("target 50 ARTIST", "clear")] = (null, "", [], []), + [("target 50 ARTIST", "write back")] = ("AArt", "AArt", ["AArt"], []), + [("target 50 ARTIST", "set, then artist")] = ("NewArt", "NewAA", ["NewAA", "NewArt"], []), + [("target 50 ARTIST", "artist, then set")] = ("NewArt", "NewAA", ["NewAA", "NewArt"], []), + [("target 50 ARTIST", "set, then clear")] = (null, "", [], []), + + [("target 50 and 30 ARTIST", "set")] = ("Art", "NewAA", ["NewAA", "Art"], []), + [("target 50 and 30 ARTIST", "clear")] = ("Art", "", ["Art"], []), + [("target 50 and 30 ARTIST", "write back")] = ("Art", "AArt", ["AArt", "Art"], []), + [("target 50 and 30 ARTIST", "set, then artist")] = ("NewArt", "NewAA", ["NewAA", "NewArt"], []), + [("target 50 and 30 ARTIST", "artist, then set")] = ("NewArt", "NewAA", ["NewAA", "NewArt"], []), + [("target 50 and 30 ARTIST", "set, then clear")] = ("Art", "", ["Art"], []), + + [("target 30 ARTIST", "set")] = ("Art", "NewAA", ["NewAA", "Art"], []), + [("target 30 ARTIST", "clear")] = ("Art", "", ["Art"], []), + [("target 30 ARTIST", "write back")] = ("Art", "", ["Art"], []), + [("target 30 ARTIST", "set, then artist")] = ("NewArt", "NewAA", ["NewAA", "NewArt"], []), + [("target 30 ARTIST", "artist, then set")] = ("NewArt", "NewAA", ["NewAA", "NewArt"], []), + [("target 30 ARTIST", "set, then clear")] = ("Art", "", ["Art"], []), + + // An explicit target-50 ARTIST is the spec's album artist, beside ffmpeg's Tag too. + [("untargeted Tag, target 50 ARTIST", "set")] = ("NewAA", "NewAA", ["NewAA"], []), + [("untargeted Tag, target 50 ARTIST", "clear")] = (null, "", [], []), + [("untargeted Tag, target 50 ARTIST", "write back")] = ("AArt", "AArt", ["AArt"], []), + [("untargeted Tag, target 50 ARTIST", "set, then artist")] = ("NewArt", "NewAA", ["NewAA", "NewArt"], []), + [("untargeted Tag, target 50 ARTIST", "artist, then set")] = ("NewArt", "NewAA", ["NewAA", "NewArt"], []), + [("untargeted Tag, target 50 ARTIST", "set, then clear")] = (null, "", [], []), + + // The track inherits the collection's ARTIST; an album artist equal to it is a repeat, anything else ALBUM_ARTIST. + [("untargeted Tag, target 70 ARTIST", "set")] = ("Coll", "NewAA", ["Coll"], ["NewAA"]), + [("untargeted Tag, target 70 ARTIST", "clear")] = ("Coll", "", ["Coll"], []), + [("untargeted Tag, target 70 ARTIST", "write back")] = ("Coll", "", ["Coll"], []), + [("untargeted Tag, target 70 ARTIST", "set, then artist")] = ("NewArt", "NewAA", ["Coll", "NewArt"], ["NewAA"]), + [("untargeted Tag, target 70 ARTIST", "artist, then set")] = ("NewArt", "NewAA", ["NewAA", "Coll", "NewArt"], []), + [("untargeted Tag, target 70 ARTIST", "set, then clear")] = ("Coll", "", ["Coll"], []), + [("untargeted Tag, target 70 ARTIST", "set to the artist")] = ("Coll", "Coll", ["Coll", "Coll"], []), + + // Tagged by the spec alone: a new target-50 Tag goes before the track's, and the track inherits its ARTIST. + [("target 70 ARTIST", "set")] = ("NewAA", "NewAA", ["Coll", "NewAA"], []), + [("target 70 ARTIST", "clear")] = ("Coll", "", ["Coll"], []), + [("target 70 ARTIST", "write back")] = ("Coll", "", ["Coll"], []), + [("target 70 ARTIST", "set, then artist")] = ("NewArt", "NewAA", ["Coll", "NewAA", "NewArt"], []), + [("target 70 ARTIST", "artist, then set")] = ("NewArt", "NewAA", ["Coll", "NewAA", "NewArt"], []), + [("target 70 ARTIST", "set, then clear")] = ("Coll", "", ["Coll"], []), + [("target 70 ARTIST", "set to the artist")] = ("Coll", "Coll", ["Coll", "Coll"], []), + + [("none", "set to the artist")] = (null, "", [], []), + [("untargeted ARTIST", "set to the artist")] = ("Art", "Art", ["Art"], []), + [("untargeted ARTIST and ALBUM_ARTIST", "set to the artist")] = ("Art", "Art", ["Art"], ["Art"]), + [("target 50 ARTIST", "set to the artist")] = ("AArt", "AArt", ["AArt"], []), + [("target 50 and 30 ARTIST", "set to the artist")] = ("Art", "Art", ["Art", "Art"], []), + [("target 30 ARTIST", "set to the artist")] = ("Art", "Art", ["Art", "Art"], []), + [("untargeted Tag, target 50 ARTIST", "set to the artist")] = ("AArt", "AArt", ["AArt"], []), + }; + + public static IEnumerable AlbumArtistEditCases () + { + foreach (var layout in AlbumArtistLayouts.Keys) { + foreach (var edit in AlbumArtistEdits.Keys) { + foreach (var entry in MatroskaEntryPoints) + yield return [layout, edit, entry]; + } + } + } + + [TestMethod] + [DynamicData (nameof (AlbumArtistEditCases))] + public async Task AlbumArtistEdit_OnAnFfmpegFile_KeepsTheArtistReadersShow (string layout, string edit, string entry) + { + var original = AlbumArtistLayouts[layout] (); + var expected = AlbumArtistExpected[(layout, edit)]; + + var saved = await EditAndSave (original, entry, AlbumArtistEdits[edit]); + + var again = MatroskaFile.Read (saved); + Assert.IsTrue (again.IsSuccess, again.Error); + var context = $"{layout} / {edit} / {entry}"; + Assert.AreEqual (expected.Artist, again.File!.Tag.Artist, context + ": Artist"); + Assert.AreEqual (expected.AlbumArtists, string.Join ("|", again.File.Tag.AlbumArtists), context + ": AlbumArtists"); + CollectionAssert.AreEqual (expected.Artists, FileLevelTexts (saved, "ARTIST"), context + ": ARTIST in file order"); + CollectionAssert.AreEqual (expected.AlbumArtistNames, FileLevelTexts (saved, "ALBUM_ARTIST"), context + ": ALBUM_ARTIST in file order"); + } + + // Each album edit visits every Tag a bounded number of times, at N and 4N Tags of the worst shape: track + // TITLEs that move after the album's Tag, ffmpeg Tags each holding a TITLE and an ALBUM, and one album TITLE. + [TestMethod] + public void AlbumEdits_AreLinearInTheTags () + { + static byte[] Build (int count) + { + var blocks = new List (); + for (var i = 0; i < count; i++) { + blocks.Add (Tag (30, Simple ("TITLE", $"t{i}"))); + blocks.Add (Untargeted (Simple ("TITLE", $"u{i}"), Simple ("ALBUM", $"a{i}"))); + } + + blocks.Add (Tag (50, Simple ("TITLE", OldAlbum))); + return Matroska (WideElement (0x18538067, WideElement (0x1254C367, Concat ([.. blocks])))); + } + + foreach (var (name, op) in new (string, Action)[] { + ("Album get", t => _ = t.Album), + ("Title get", t => _ = t.Title), + ("Album set", t => t.Album = NewAlbum), + ("Album clear", t => t.Album = null), + ("Album write back", t => t.Album = t.Album), + }) { + long Steps (int count) + { + var tag = MatroskaFile.Read (Build (count)).File!.Tag; + MatroskaTag.LevelSteps = 0; + op (tag); + return MatroskaTag.LevelSteps; + } + + var one = Steps (500); + var four = Steps (2000); + Assert.IsTrue (one >= 1000, $"{name}: visited only {one} Tags of 1001; the counter is not counting"); + Assert.IsTrue (four <= 5 * one, $"{name}: {one} visits at 1001 Tags, {four} at 4001; not linear"); + } + } + + // #205: ffprobe shows every PART_NUMBER as a track number, whatever its target. A file that does not already keep + // its disc as the specification's PART_NUMBER at target 50 gets ffmpeg's DISC ("n" or "n/m"), which ffprobe, + // exiftool and MediaInfo show as the disc; a file that does keeps that layout. + static readonly Dictionary> DiscLayouts = new () { + ["no Tags"] = () => AlbumLayout (null), + ["untargeted Tag"] = () => AlbumLayout (null, Untargeted ()), + ["untargeted DISC with a total"] = () => AlbumLayout (null, Untargeted (Simple ("DISC", "1/4"))), + ["target 50 PART_NUMBER"] = () => AlbumLayout (null, Tag (50, Simple ("PART_NUMBER", "1")), Tag (30, Simple ("TITLE", "Song"))), + }; + + static readonly Dictionary> DiscEdits = new () { + ["disc"] = tag => tag.DiscNumber = 2, + ["disc and total"] = tag => { tag.DiscNumber = 2; tag.TotalDiscs = 3; }, + ["disc and track"] = tag => { tag.DiscNumber = 2; tag.Track = 5; }, + ["clear disc"] = tag => tag.DiscNumber = null, + }; + + // layout, edit, entry, then the DISC texts, the PART_NUMBER texts, DiscNumber, TotalDiscs and Track read back. + public static IEnumerable DiscCases () + { + string? N (uint? value) => value?.ToString (System.Globalization.CultureInfo.InvariantCulture); + var expected = new Dictionary<(string, string), (string Disc, string Part, uint? Number, uint? Total, uint? Track)> { + [("no Tags", "disc")] = ("2", "", 2, null, null), + [("no Tags", "disc and total")] = ("2/3", "", 2, 3, null), + [("no Tags", "disc and track")] = ("2", "5", 2, null, 5), + [("no Tags", "clear disc")] = ("", "", null, null, null), + [("untargeted Tag", "disc")] = ("2", "", 2, null, null), + [("untargeted Tag", "disc and total")] = ("2/3", "", 2, 3, null), + [("untargeted Tag", "disc and track")] = ("2", "5", 2, null, 5), + [("untargeted Tag", "clear disc")] = ("", "", null, null, null), + [("untargeted DISC with a total", "disc")] = ("2/4", "", 2, 4, null), + [("untargeted DISC with a total", "disc and total")] = ("2/3", "", 2, 3, null), + [("untargeted DISC with a total", "disc and track")] = ("2/4", "5", 2, 4, 5), + [("untargeted DISC with a total", "clear disc")] = ("", "", null, 4, null), + [("target 50 PART_NUMBER", "disc")] = ("", "2", 2, null, null), + [("target 50 PART_NUMBER", "disc and total")] = ("", "2", 2, 3, null), + [("target 50 PART_NUMBER", "disc and track")] = ("", "2|5", 2, null, 5), + [("target 50 PART_NUMBER", "clear disc")] = ("", "", null, null, null), + }; + foreach (var ((layout, edit), e) in expected) + foreach (var entry in new[] { "MatroskaFile.Read", "path" }) + yield return [layout, edit, entry, e.Disc, e.Part, N (e.Number), N (e.Total), N (e.Track)]; + } + + [TestMethod] + [DynamicData (nameof (DiscCases))] + public async Task DiscEdit_NeverShowsAsASecondTrack (string layout, string edit, string entry, string disc, string part, string? number, string? total, string? track) + { + var saved = await EditAndSave (DiscLayouts[layout] (), entry, DiscEdits[edit]); + + Assert.AreEqual (disc, string.Join ("|", FileLevelTexts (saved, "DISC")), "DISC"); + Assert.AreEqual (part, string.Join ("|", FileLevelTexts (saved, "PART_NUMBER")), "PART_NUMBER"); + var tag = MatroskaFile.Read (saved).File!.Tag; + Assert.AreEqual (number, tag.DiscNumber?.ToString (System.Globalization.CultureInfo.InvariantCulture), "DiscNumber"); + Assert.AreEqual (total, tag.TotalDiscs?.ToString (System.Globalization.CultureInfo.InvariantCulture), "TotalDiscs"); + Assert.AreEqual (track, tag.Track?.ToString (System.Globalization.CultureInfo.InvariantCulture), "Track"); + } + + // The track total, as for the disc (#205): ffprobe shows TOTAL_PARTS only as a raw tag, and shows ffmpeg's + // PART_NUMBER "n/m" as the track with its total, as MediaInfo does. A file that does not already keep its total as + // TOTAL_PARTS gets the total after its track number; one that does keeps that layout. A total with no track number + // to follow has only TOTAL_PARTS. + static readonly Dictionary> TrackLayouts = new () { + ["no Tags"] = () => AlbumLayout (null), + ["ffmpeg n/m"] = () => AlbumLayout (null, Untargeted (Simple ("PART_NUMBER", "5/12"))), + ["untargeted number"] = () => AlbumLayout (null, Untargeted (Simple ("PART_NUMBER", "5"))), + ["track at 30"] = () => AlbumLayout (null, Tag (30, Simple ("PART_NUMBER", "5"))), + ["total at 50"] = () => AlbumLayout (null, Tag (50, Simple ("TOTAL_PARTS", "12")), Tag (30, Simple ("PART_NUMBER", "5"))), + ["untargeted total"] = () => AlbumLayout (null, Untargeted (Simple ("PART_NUMBER", "5"), Simple ("TOTAL_PARTS", "12"))), + // A TOTAL_PARTS with no number is no total; the new one replaces it. + ["empty total at 50"] = () => AlbumLayout (null, Tag (50, Simple ("TOTAL_PARTS", "")), Tag (30, Simple ("PART_NUMBER", "5"))), + }; + + static readonly Dictionary> TrackEdits = new () { + ["total"] = tag => tag.TotalTracks = 13, + ["track"] = tag => tag.Track = 6, + ["track and total"] = tag => { tag.Track = 5; tag.TotalTracks = 12; }, + ["clear total"] = tag => tag.TotalTracks = null, + }; + + // layout, edit, entry, then the PART_NUMBER texts, the TOTAL_PARTS texts, Track and TotalTracks read back. + public static IEnumerable TrackTotalCases () + { + string? N (uint? value) => value?.ToString (System.Globalization.CultureInfo.InvariantCulture); + var expected = new Dictionary<(string, string), (string Part, string Total, uint? Track, uint? Count)> { + [("no Tags", "total")] = ("", "13", null, 13), + [("no Tags", "track and total")] = ("5/12", "", 5, 12), + [("no Tags", "clear total")] = ("", "", null, null), + [("ffmpeg n/m", "total")] = ("5/13", "", 5, 13), + [("ffmpeg n/m", "track")] = ("6/12", "", 6, 12), + [("ffmpeg n/m", "track and total")] = ("5/12", "", 5, 12), + [("ffmpeg n/m", "clear total")] = ("5", "", 5, null), + [("untargeted number", "total")] = ("5/13", "", 5, 13), + [("untargeted number", "track")] = ("6", "", 6, null), + [("untargeted number", "clear total")] = ("5", "", 5, null), + [("track at 30", "total")] = ("5/13", "", 5, 13), + [("track at 30", "track and total")] = ("5/12", "", 5, 12), + [("track at 30", "clear total")] = ("5", "", 5, null), + [("total at 50", "total")] = ("5", "13", 5, 13), + [("total at 50", "track")] = ("6", "12", 6, 12), + [("total at 50", "track and total")] = ("5", "12", 5, 12), + [("total at 50", "clear total")] = ("5", "", 5, null), + [("untargeted total", "total")] = ("5", "13", 5, 13), + [("untargeted total", "track")] = ("6", "12", 6, 12), + [("untargeted total", "clear total")] = ("5", "", 5, null), + [("empty total at 50", "total")] = ("5/13", "", 5, 13), + }; + foreach (var ((layout, edit), e) in expected) + foreach (var entry in new[] { "MatroskaFile.Read", "path" }) + yield return [layout, edit, entry, e.Part, e.Total, N (e.Track), N (e.Count)]; + } + + [TestMethod] + [DynamicData (nameof (TrackTotalCases))] + public async Task TrackTotal_IsWrittenWhereFfprobeShowsIt (string layout, string edit, string entry, string part, string total, string? track, string? count) + { + var saved = await EditAndSave (TrackLayouts[layout] (), entry, TrackEdits[edit]); + + Assert.AreEqual (part, string.Join ("|", FileLevelTexts (saved, "PART_NUMBER")), "PART_NUMBER"); + var totals = FileLevelTexts (saved, "TOTAL_PARTS"); + Assert.AreEqual (total, string.Join ("|", totals), "TOTAL_PARTS"); + if (total.Length == 0) + Assert.IsEmpty (totals, "an empty TOTAL_PARTS is left"); + var tag = MatroskaFile.Read (saved).File!.Tag; + Assert.AreEqual (track, tag.Track?.ToString (System.Globalization.CultureInfo.InvariantCulture), "Track"); + Assert.AreEqual (count, tag.TotalTracks?.ToString (System.Globalization.CultureInfo.InvariantCulture), "TotalTracks"); + } + + static async Task EditAndSave (byte[] original, string entry, Action edit) + { + var fs = new MockFileSystem (); + fs.AddFile ("/in.mka", original); + var opened = entry switch { + "MatroskaFile.Read" => MatroskaFile.Read (original).File, + "ReadFromData" => (MatroskaFile?)MediaFile.ReadFromData (original, "in.mka").File, + "stream" => (MatroskaFile?)MediaFile.Read (new MemoryStream (original), "in.mka").File, + "path" => (MatroskaFile?)MediaFile.Read ("/in.mka", fs).File, + "async path" => (MatroskaFile?)(await MediaFile.ReadAsync ("/in.mka", fs)).File, + _ => throw new ArgumentException (entry), + }; + Assert.IsNotNull (opened, entry); + edit (opened.Tag); + var result = entry switch { + "path" => opened.SaveToFile ("/in.mka", fs), + "async path" => await opened.SaveToFileAsync ("/in.mka", fs), + _ => opened.SaveToFile ("/in.mka", original, fs), + }; + Assert.IsTrue (result.IsSuccess, result.Error); + return fs.ReadAllBytes ("/in.mka"); + } + + static byte[] AlbumLayout (string? segmentTitle, params byte[][] tags) + { + var info = segmentTitle is null ? [] : SegmentInfo (segmentTitle); + return FileWith (info, Tags (tags), Master (0x1F43B675, new byte[] { 1 })); + } + + static byte[] SegmentInfo (string title) => Master (MatroskaIds.Info, Element (MatroskaIds.SegmentTitle, Encoding.UTF8.GetBytes (title))); + + // ffmpeg's untargeted Tag: an empty Targets and the muxer name. + static byte[] Untargeted (params byte[][] simpleTags) => + Master (0x7373, Concat (Master (0x63C0, Array.Empty ()), Simple ("ENCODER", "Lavf"), Concat (simpleTags))); + + /// The text of every top-level SimpleTag named , Tag by Tag in file order. + static string[] FileLevelTexts (byte[] file, string name) + { + Assert.IsTrue (TrySegmentBody (file, out var body, out _)); + var texts = new List (); + foreach (var tags in Children (body, MatroskaIds.Tags)) { + foreach (var tag in Children (tags, MatroskaIds.Tag)) { + foreach (var simple in Children (tag, MatroskaIds.SimpleTag)) { + var tagName = Children (simple, MatroskaIds.TagName); + var text = Children (simple, MatroskaIds.TagString); + if (tagName.Count == 1 && Encoding.UTF8.GetString (tagName[0]) == name && text.Count == 1) + texts.Add (Encoding.UTF8.GetString (text[0])); + } + } + } + + return [.. texts]; + } + + static List Children (byte[] body, ulong id) + { + var found = new List (); + var offset = 0; + while (offset < body.Length && EbmlReader.TryRead (body, offset, body.Length, out var element) && !element.UnknownSize) { + if (element.Id == id) + found.Add (body.AsSpan (element.DataOffset, (int)element.DataLength).ToArray ()); + offset = element.End; + } + + return found; + } +} diff --git a/tests/TagLibSharp2.Tests/Matroska/MatroskaFileTests.cs b/tests/TagLibSharp2.Tests/Matroska/MatroskaFileTests.cs index f8fc4dd1..92f10fa7 100644 --- a/tests/TagLibSharp2.Tests/Matroska/MatroskaFileTests.cs +++ b/tests/TagLibSharp2.Tests/Matroska/MatroskaFileTests.cs @@ -193,7 +193,7 @@ public void Read_ExplicitAlbumPartNumber_BeatsADiscName () } [TestMethod] - public void Save_DiscNumberAndTotalDiscs_RoundTripAtAlbumAndVolumeLevels () + public void Save_DiscNumberAndTotalDiscs_RoundTripAsTheDisc () { var original = FileWith ( Tags (Tag (30, Simple ("TITLE", "Song"), Simple ("PART_NUMBER", "4"))), @@ -218,8 +218,11 @@ public void Save_DiscNumberAndTotalDiscs_RoundTripAtAlbumAndVolumeLevels () Assert.AreEqual (3u, again.TotalDiscs); Assert.IsNull (again.TotalTracks); Assert.AreEqual (4u, again.Track); - Assert.IsTrue (FileTargetHas (bytes, 50, "PART_NUMBER")); - Assert.IsTrue (FileTargetHas (bytes, 60, "TOTAL_PARTS")); + // A file that does not keep its disc as PART_NUMBER at 50 gets ffmpeg's DISC "n/m" (#205): ffprobe shows + // every PART_NUMBER as a track number. + Assert.IsTrue (FileTargetHas (bytes, 50, "DISC")); + Assert.IsFalse (FileTargetHas (bytes, 50, "PART_NUMBER")); + Assert.IsFalse (FileTargetHas (bytes, 60, "TOTAL_PARTS")); Assert.IsFalse (FileTargetHas (bytes, 50, "TOTAL_PARTS")); Assert.IsTrue (FileTargetHas (bytes, 30, "PART_NUMBER")); Assert.IsTrue (bytes.AsSpan ().IndexOf ("DISC_NUMBER"u8) < 0); @@ -251,7 +254,8 @@ public void DiscNumber_Set_DoesNotMoveGenreOrYearToVolumeLevel () Assert.AreEqual (2u, again.DiscNumber); Assert.AreEqual (4u, again.TotalDiscs); Assert.AreEqual (3u, again.Track); - Assert.IsTrue (FileTargetHas (bytes, 60, "TOTAL_PARTS")); + Assert.IsTrue (FileTargetHas (bytes, 50, "DISC")); + Assert.IsFalse (FileTargetHas (bytes, 60, "TOTAL_PARTS")); Assert.IsTrue (FileTargetHas (bytes, 50, "GENRE")); Assert.IsTrue (FileTargetHas (bytes, 50, "DATE_RELEASED")); Assert.IsFalse (FileTargetHas (bytes, 60, "GENRE")); @@ -726,9 +730,10 @@ public void Save_NewTargets_GoBeforeNarrowerOnes () var again = SaveAndReread (parsed, original, out var bytes); AssertNumbers (again, 4, 12, 2, 3, "saved"); - CollectionAssert.AreEqual (new ulong[] { 60, 50, 30 }, TargetLevelsInOrder (bytes)); + CollectionAssert.AreEqual (new ulong[] { 50, 30 }, TargetLevelsInOrder (bytes)); + Assert.IsTrue (FileTargetHas (bytes, 50, "DISC")); - // ffmpeg's single untargeted tag holds the track, so the new album and set tags go before it. + // ffmpeg's single untargeted tag holds the track; the disc goes there as DISC (#205), so no tag is added. var ffmpeg = FileWith ( Tags (Master (0x7373, Concat (Master (0x63C0, Array.Empty ()), Simple ("PART_NUMBER", "4/12")))), Master (0x1F43B675, new byte[] { 1 })); @@ -737,8 +742,69 @@ public void Save_NewTargets_GoBeforeNarrowerOnes () fromFfmpeg.Tag.TotalDiscs = 3; var ffAgain = SaveAndReread (fromFfmpeg, ffmpeg, out var ffBytes); AssertNumbers (ffAgain, 4, 12, 2, 3, "ffmpeg saved"); - CollectionAssert.AreEqual (new ulong[] { 60, 50 }, TargetLevelsInOrder (ffBytes)); - Assert.IsTrue (ffBytes.AsSpan ().IndexOf (Element (0x68CA, new byte[] { 50 })) < ffBytes.AsSpan ().IndexOf ("4/12"u8)); + CollectionAssert.AreEqual (Array.Empty (), TargetLevelsInOrder (ffBytes)); + Assert.IsTrue (ffBytes.AsSpan ().IndexOf ("2/3"u8) > 0, "DISC 2/3"); + } + + [TestMethod] + public void Album_FfmpegUntargetedName_ReadsAndWritesWithoutAddingTitle () + { + // ffmpeg -metadata album= writes a simple tag named ALBUM and no target. + // ffprobe reports that name as ALBUM. A TITLE added to the same tag is what + // ffprobe then reports as the file title (https://www.matroska.org/technical/tagging.html + // stores the album as TITLE at target 50; this name is the ffmpeg form). + var original = FileWith ( + Tags (Master (0x7373, Concat (Master (0x63C0, Array.Empty ()), Simple ("ALBUM", "OldAlbum")))), + Master (0x1F43B675, new byte[] { 1 })); + var parsed = MatroskaFile.Read (original).File!; + Assert.AreEqual ("OldAlbum", parsed.Tag.Album); + + parsed.Tag.Album = "NewAlbum"; + + var again = SaveAndReread (parsed, original, out var bytes); + Assert.AreEqual ("NewAlbum", again.Album); + Assert.IsTrue (HasTagName (bytes, "ALBUM")); + Assert.IsFalse (HasTagName (bytes, "TITLE")); + } + + [TestMethod] + public void Album_ExplicitTitleAndFlatAlbum_UpdatesBoth () + { + // A file can carry the spec TITLE at target 50 and ffmpeg's ALBUM together. + // Changing the album has to change both, and the track title stays. + var original = FileWith ( + Tags ( + Tag (50, Simple ("TITLE", "SpecAlbum")), + Master (0x7373, Concat (Master (0x63C0, Array.Empty ()), Simple ("ALBUM", "FlatAlbum"), Simple ("TITLE", "KeepTitle")))), + Master (0x1F43B675, new byte[] { 1 })); + var parsed = MatroskaFile.Read (original).File!; + + parsed.Tag.Album = "NewAlbum"; + + var again = SaveAndReread (parsed, original, out var bytes); + Assert.AreEqual ("NewAlbum", again.Album); + Assert.IsTrue (bytes.AsSpan ().IndexOf ("FlatAlbum"u8) < 0); + Assert.IsTrue (bytes.AsSpan ().IndexOf ("SpecAlbum"u8) < 0); + Assert.IsTrue (bytes.AsSpan ().IndexOf ("KeepTitle"u8) >= 0); + Assert.IsTrue (bytes.AsSpan ().IndexOf ("NewAlbum"u8) >= 0); + } + + [TestMethod] + public void Album_OnAFileWhoseTitleIsTheOnlyTitle_KeepsThatTitle () + { + // Writing the album as TITLE at target 50 must not become the only TITLE ffprobe will show. + var original = FileWith ( + Tags (Master (0x7373, Concat (Master (0x63C0, Array.Empty ()), Simple ("TITLE", "KeepTitle")))), + Master (0x1F43B675, new byte[] { 1 })); + var parsed = MatroskaFile.Read (original).File!; + Assert.AreEqual ("KeepTitle", parsed.Tag.Title); + + parsed.Tag.Album = "NewAlbum"; + + var again = SaveAndReread (parsed, original, out var bytes); + Assert.AreEqual ("NewAlbum", again.Album); + Assert.AreEqual ("KeepTitle", again.Title); + Assert.IsTrue (HasTagName (bytes, "ALBUM") || bytes.AsSpan ().IndexOf ("NewAlbum"u8) >= 0); } [TestMethod] @@ -759,13 +825,14 @@ public void NewFields_AfterDiscNumber_GoToFfmpegsUntargetedTag () Assert.AreEqual (2u, again.DiscNumber); Assert.AreEqual ("Comp", again.Composers.Single ()); Assert.AreEqual ("Note", again.Comment); - Assert.IsTrue (FileTargetHas (bytes, 50, "PART_NUMBER")); + Assert.IsFalse (FileTargetHas (bytes, 50, "PART_NUMBER")); + Assert.IsTrue (HasTagName (bytes, "DISC")); Assert.IsFalse (FileTargetHas (bytes, 50, "COMPOSER"), "COMPOSER went into the disc-only tag"); Assert.IsFalse (FileTargetHas (bytes, 50, "COMMENT"), "COMMENT went into the disc-only tag"); } [TestMethod] - public void TotalDiscs_Set_OnATrackOnlyFile_MovesAKnownDiscTo50 () + public void TotalDiscs_Set_OnATrackOnlyFile_KeepsTheDiscWithItsTotal () { // 60 TOTAL_PARTS counts the first lower level in the file. With only a 30 tag that would be tracks. var original = FileWith ( @@ -776,10 +843,10 @@ public void TotalDiscs_Set_OnATrackOnlyFile_MovesAKnownDiscTo50 () var again = SaveAndReread (parsed, original, out var bytes); AssertNumbers (again, 4, null, 2, 3, "set"); - Assert.IsTrue (FileTargetHas (bytes, 50, "PART_NUMBER")); - Assert.IsTrue (FileTargetHas (bytes, 60, "TOTAL_PARTS")); - Assert.IsFalse (HasTagName (bytes, "DISC")); - CollectionAssert.AreEqual (new ulong[] { 60, 50, 30 }, TargetLevelsInOrder (bytes)); + Assert.IsFalse (FileTargetHas (bytes, 50, "PART_NUMBER")); + Assert.IsFalse (FileTargetHas (bytes, 60, "TOTAL_PARTS")); + Assert.IsTrue (FileTargetHas (bytes, 50, "DISC")); + CollectionAssert.AreEqual (new ulong[] { 50, 30 }, TargetLevelsInOrder (bytes)); } [TestMethod] @@ -1093,9 +1160,10 @@ public void TotalTracks_Set_LeavesOneTrackTotal () } [TestMethod] - public void TotalTracks_Set_StripsTheSlashTotal () + public void TotalTracks_Set_ReplacesTheSlashTotal () { - // The getter prefers TOTAL_PARTS, but other readers still see the "/12". + // A file that keeps its total after the track number, as ffmpeg writes it, keeps that form (#205): the old + // "/12" goes, and no TOTAL_PARTS is added beside the new one. var original = FileWith (Tags (Tag (30, Simple ("PART_NUMBER", "4/12"))), Master (0x1F43B675, new byte[] { 1 })); var parsed = MatroskaFile.Read (original).File!; parsed.Tag.TotalTracks = 20; @@ -1104,7 +1172,8 @@ public void TotalTracks_Set_StripsTheSlashTotal () Assert.AreEqual (4u, again.Track); Assert.AreEqual (20u, again.TotalTracks); Assert.IsFalse (HasTagString (bytes, "4/12")); - Assert.IsTrue (HasTagString (bytes, "4")); + Assert.IsTrue (HasTagString (bytes, "4/20")); + Assert.IsFalse (HasTagName (bytes, "TOTAL_PARTS")); } static void AssertNumbers (MatroskaTag tag, uint? track, uint? totalTracks, uint? disc, uint? totalDiscs, string context) @@ -1464,6 +1533,53 @@ public void Read_Tracks_ReportAudioAndVideoProperties () Assert.AreEqual ("VP8", videoProps.Codec); } + /// + /// RFC 9559 §15: ProjectionPoseRoll asks for a counter-clockwise turn at presentation, so the clockwise rotation is + /// its negative. ffmpeg writes -display_rotation 90 as roll 90 and ffprobe reads it back as rotation 90 (counter- + /// clockwise); the same picture from MP4 is exiftool's and mediainfo's Rotation 270. Yaw, pitch or a projection + /// other than rectangular (0) is not a flat rotation (§5.1.4.1.28.42 to .46), so those report 0. + /// + [TestMethod] + [DataRow (0u, 0.0, 0.0, 90.0, 270)] + [DataRow (0u, 0.0, 0.0, -90.0, 90)] + [DataRow (0u, 0.0, 0.0, 180.0, 180)] + [DataRow (0u, 0.0, 0.0, -180.0, 180)] + [DataRow (0u, 0.0, 0.0, 45.0, 315)] + [DataRow (0u, 0.0, 0.0, 0.0, 0)] + [DataRow (0u, 180.0, 0.0, 90.0, 0)] + [DataRow (0u, 0.0, 30.0, 90.0, 0)] + [DataRow (1u, 0.0, 0.0, 90.0, 0)] + [DataRow (0u, 0.0, 0.0, 270.0, 0)] + public void Read_ProjectionPoseRoll_IsTheClockwiseRotation (uint projectionType, double yaw, double pitch, double roll, int rotation) + { + var projection = Master (0x7670, + Element (0x7671, [(byte)projectionType]), + Element (0x7673, Float64 (yaw)), + Element (0x7674, Float64 (pitch)), + Element (0x7675, Float64 (roll))); + var video = Master (0xAE, Concat ( + Element (0x83, new byte[] { 1 }), + Element (0x86, "V_MPEG4/ISO/AVC"u8), + Master (0xE0, Concat (Element (0xB0, new byte[] { 0x01, 0x40 }), Element (0xBA, new byte[] { 0xF0 }), projection)))); + var file = FileWith (Master (0x1654AE6B, video)); + + IMediaFile media = MatroskaFile.Read (file).File!; + + Assert.AreEqual (new VideoProperties (TimeSpan.Zero, 320, 240, 0, 0, "H.264") { Rotation = rotation }, media.VideoProperties); + } + + [TestMethod] + public void Read_VideoWithoutProjection_HasNoRotation () + { + var video = Master (0xAE, Concat ( + Element (0x83, new byte[] { 1 }), + Master (0xE0, Concat (Element (0xB0, new byte[] { 0x01, 0x40 }), Element (0xBA, new byte[] { 0xF0 }))))); + + IMediaFile media = MatroskaFile.Read (FileWith (Master (0x1654AE6B, video))).File!; + + Assert.AreEqual (0, media.VideoProperties!.Value.Rotation); + } + [TestMethod] public void Read_DefaultTrack_WinsOverAnEarlierDisabledTrack () { @@ -2585,6 +2701,13 @@ static byte[] Id (ulong id) return bytes; } + static byte[] Float64 (double value) + { + var bytes = new byte[8]; + System.Buffers.Binary.BinaryPrimitives.WriteInt64BigEndian (bytes, BitConverter.DoubleToInt64Bits (value)); + return bytes; + } + static byte[] Float32 (float value) { var bytes = new byte[4]; diff --git a/tests/TagLibSharp2.Tests/Matroska/MatroskaFillerTests.cs b/tests/TagLibSharp2.Tests/Matroska/MatroskaFillerTests.cs new file mode 100644 index 00000000..9e4866e1 --- /dev/null +++ b/tests/TagLibSharp2.Tests/Matroska/MatroskaFillerTests.cs @@ -0,0 +1,225 @@ +// 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.Matroska; +using TagLibSharp2.Tests.Core; +using TagLibSharp2.Tests.Kit; + +namespace TagLibSharp2.Tests.Matroska; + +/// +/// Bytes that are not an element inside a Segment (a live recording puts 0x0A filler after the unknown Segment size, +/// as the Matroska test suite's test4.mkv does) are skipped on every entry point, so a path or stream read reports the +/// tracks a read from memory reports (#208). +/// +[TestClass] +[TestCategory ("Unit")] +[TestCategory ("Matroska")] +public class MatroskaFillerTests +{ + static byte[] Float (double value) + { + var bytes = BitConverter.GetBytes (value); + if (BitConverter.IsLittleEndian) + Array.Reverse (bytes); + return bytes; + } + + static byte[] Tracks () => Nesting.EbmlElement (MatroskaIds.Tracks, Nesting.Concat ( + Nesting.EbmlElement (0xAE, Nesting.Concat ( + Nesting.EbmlElement (0xD7, [1]), Nesting.EbmlElement (0x83, [1]), Nesting.EbmlElement (0x86, "V_THEORA"u8), + Nesting.EbmlElement (0xE0, Nesting.Concat (Nesting.EbmlElement (0xB0, [0x05, 0x00]), Nesting.EbmlElement (0xBA, [0x02, 0xD0]))))), + Nesting.EbmlElement (0xAE, Nesting.Concat ( + Nesting.EbmlElement (0xD7, [2]), Nesting.EbmlElement (0x83, [2]), Nesting.EbmlElement (0x86, "A_VORBIS"u8), + Nesting.EbmlElement (0xE1, Nesting.Concat (Nesting.EbmlElement (0xB5, Float (44100)), Nesting.EbmlElement (0x9F, [2]))))))); + + // An unknown-size Segment, `filler` bytes of `pattern` (0x0A by default), then Info, Tracks and a Cluster. + static byte[] File (int filler, byte[]? pattern = null) => Nesting.Concat ( + Nesting.EbmlElement (0x1A45DFA3, Nesting.EbmlElement (MatroskaIds.DocType, "matroska"u8)), + [0x18, 0x53, 0x80, 0x67, 0xFF], + Enumerable.Range (0, filler).Select (i => (pattern ?? [0x0A])[i % (pattern ?? [0x0A]).Length]).ToArray (), + Nesting.EbmlElement (MatroskaIds.Info, Nesting.EbmlElement (MatroskaIds.TimestampScale, [0x0F, 0x42, 0x40])), + Tracks (), + Nesting.EbmlElement (MatroskaIds.Cluster, Nesting.EbmlElement (0xE7, [0x00]))); + + static readonly int[] Fillers = [0, 134, 70_000]; + + public static IEnumerable Cases => + from filler in Fillers + from entry in SkipPicturesFixtures.Entries + select new object[] { filler, entry }; + + [TestMethod] + [DynamicData (nameof (Cases))] + public void FillerInTheSegment_IsSkippedOnEveryEntryPoint (int filler, string entry) + { + var read = SkipPicturesFixtures.Read (File (filler), "a.mkv", entry, skip: false); + + Assert.IsTrue (read.IsSuccess, read.Error); + var file = (IMediaFile)read.File!; + Assert.AreEqual (MediaTypes.Audio | MediaTypes.Video, file.MediaTypes); + Assert.AreEqual ("Vorbis", file.AudioProperties!.Codec); + Assert.AreEqual ("Theora 1280x720", $"{file.VideoProperties!.Value.Codec} {file.VideoProperties.Value.Width}x{file.VideoProperties.Value.Height}"); + } + + // Filler after the first element: where review 3 put it in at.mka (after the first element, before the Cluster, + // after the last Cluster, and both), as 0x0A and as 0x00, in a known-size and an unknown-size Segment. + static byte[] Placed (string place, byte fill, bool knownSize) + { + var filler = Enumerable.Repeat (fill, 40).ToArray (); + var info = Nesting.EbmlElement (MatroskaIds.Info, Nesting.EbmlElement (MatroskaIds.TimestampScale, [0x0F, 0x42, 0x40])); + var cluster = Nesting.EbmlElement (MatroskaIds.Cluster, Nesting.EbmlElement (0xE7, [0x00])); + var body = place switch { + "after the first element" => Nesting.Concat (info, filler, Tracks (), cluster), + "before the Cluster" => Nesting.Concat (info, Tracks (), filler, cluster), + "after the last Cluster" => Nesting.Concat (info, Tracks (), cluster, filler), + _ => Nesting.Concat (info, filler, Tracks (), cluster, filler), + }; + return Nesting.Concat ( + Nesting.EbmlElement (0x1A45DFA3, Nesting.EbmlElement (MatroskaIds.DocType, "matroska"u8)), + knownSize ? Nesting.EbmlElement (MatroskaIds.Segment, body) : Nesting.Concat ([0x18, 0x53, 0x80, 0x67, 0xFF], body)); + } + + static readonly string[] Placements = ["after the first element", "before the Cluster", "after the last Cluster", "both"]; + static readonly string[] SaveEntries = ["data", "path"]; + static readonly byte[] Fills = [0x0A, 0x00]; + static readonly bool[] KnownSizes = [true, false]; + + public static IEnumerable PlacedCases => + from place in Placements + from fill in Fills + from known in KnownSizes + from entry in SaveEntries + select new object[] { place, fill, known, entry }; + + // The save walks the Segment with the read's rule, so filler anywhere is kept as it is, where the save used to be + // refused once an element had been seen: a save with no edit writes the file back, and a title edit reads back + // with the tracks and every filler byte (review 3, #208). + [TestMethod] + [DynamicData (nameof (PlacedCases))] + public async Task FillerAfterAnElement_IsKeptBySaves (string place, byte fill, bool knownSize, string entry) + { + var original = Placed (place, fill, knownSize); + foreach (var title in new[] { null, "New title" }) { + var files = new MockFileSystem (); + files.AddFile ("/a.mkv", original); + var file = (MatroskaFile)SkipPicturesFixtures.Read (original, "a.mkv", entry, skip: false, files).File!; + if (title is not null) + file.Tag.Title = title; + + var saved = entry == "path" ? await file.SaveToFileAsync ("/a.mkv", files) : file.SaveToFile ("/a.mkv", original, files); + + Assert.IsTrue (saved.IsSuccess, saved.Error); + var bytes = files.ReadAllBytes ("/a.mkv"); + if (title is null) { + CollectionAssert.AreEqual (original, bytes, "a save with no edit changed the file"); + continue; + } + + var again = MatroskaFile.Read (bytes).File!; + Assert.AreEqual (title, again.Tag.Title); + Assert.AreEqual ("Vorbis", ((IMediaFile)again).AudioProperties!.Codec); + Assert.AreEqual (place == "both" ? 2 : 1, Runs (original, fill), "filler runs in the file"); + Assert.AreEqual (Runs (original, fill), Runs (bytes, fill), "filler runs kept"); + } + } + + // Runs of at least 40 fill bytes: each filler run, with any fill byte an element ends with beside it. + static int Runs (byte[] bytes, byte fill) + { + var runs = 0; + var length = 0; + foreach (var b in bytes) { + length = b == fill ? length + 1 : 0; + if (length == 40) + runs++; + } + + return runs; + } + + // The save's walk peeks at most 12 bytes at each filler offset and copies each piece once, so a hostile Segment of + // alternating junk and Voids after its first element saves in reads that grow with the file. + [TestMethod] + [DataRow (10_000)] + [DataRow (100_000)] + public void AlternatingJunkAndElements_SaveLinearly (int size) + { + var info = Nesting.EbmlElement (MatroskaIds.Info, Nesting.EbmlElement (MatroskaIds.TimestampScale, [0x0F, 0x42, 0x40])); + var file = Nesting.Concat ( + Nesting.EbmlElement (0x1A45DFA3, Nesting.EbmlElement (MatroskaIds.DocType, "matroska"u8)), + [0x18, 0x53, 0x80, 0x67, 0xFF], info, Enumerable.Range (0, size).Select (i => JunkThenVoid[i % 3]).ToArray ()); + var files = new CountingFileSystem (); + files.AddFile ("/a.mkv", file); + var read = MatroskaFile.ReadFromFile ("/a.mkv", files).File!; + read.Tag.Title = "T"; + var before = files.BytesRead; + + var saved = read.SaveToFile ("/a.mkv", files); + + Assert.IsTrue (saved.IsSuccess, saved.Error); + Assert.IsLessThanOrEqualTo (20L * file.Length, files.BytesRead - before, $"{files.BytesRead - before} bytes read to save a {file.Length}-byte file"); + } + + // The skip reads the filler a window at a time: the bytes a stream read reads grow with the filler, not faster. + // 81 01 02 repeated: every third offset is an element header whose 8-byte size runs past the Segment, so the skip + // passes it over without reading the window again. + static readonly byte[] OversizeHeaders = [0x81, 0x01, 0x02]; + + [TestMethod] + [DataRow (false)] + [DataRow (true)] + public void FillerSkip_ReadsLinearly (bool oversizeHeaders) + { + var pattern = oversizeHeaders ? OversizeHeaders : null; + long BytesRead (int filler) + { + using var counting = new CountingStream (new MemoryStream (File (filler, pattern), writable: false)); + Assert.IsTrue (MediaFile.Read (counting, "a.mkv").IsSuccess); + return counting.BytesRead; + } + + var one = BytesRead (100_000); + var four = BytesRead (400_000); + + Assert.IsLessThan (5 * one, four, $"{one} bytes read for 100,000 filler bytes, {four} for 400,000"); + // About one pass over the file: a 12-byte peek at every offset would read twelve times the filler. + Assert.IsLessThan (2L * File (400_000, pattern).Length, four); + } + + // One junk byte, then a 2-byte Void (0xEC, size 0), over and over: every junk byte starts a resync whose element is + // one byte on. Each resync must read about as far as it scans, not a fixed window, or a hostile file of n bytes + // makes a read of n / 3 windows. + static readonly byte[] JunkThenVoid = [0x0A, 0xEC, 0x80]; + + static readonly int[] AlternatingSizes = [10_000, 100_000, 1_000_000]; + static readonly string[] AlternatingEntries = ["path", "stream", "skip-pictures stream"]; + + public static IEnumerable AlternatingCases => + from size in AlternatingSizes + from entry in AlternatingEntries + select new object[] { size, entry }; + + [TestMethod] + [DynamicData (nameof (AlternatingCases))] + public void AlternatingJunkAndElements_ReadLinearly (int size, string entry) + { + var file = File (size, JunkThenVoid); + long bytesRead; + if (entry == "path") { + var files = new CountingFileSystem (); + files.AddFile ("/a.mkv", file); + Assert.IsTrue (MediaFile.Read ("/a.mkv", files).IsSuccess); + bytesRead = files.BytesRead; + } else { + using var counting = new CountingStream (new MemoryStream (file, writable: false)); + var options = new MediaReadOptions { SkipPictures = entry == "skip-pictures stream" }; + Assert.IsTrue (MediaFile.Read (counting, options, "a.mkv").IsSuccess); + bytesRead = counting.BytesRead; + } + + // Every 3 bytes: a 12-byte peek at the junk byte, a short resync read, a 12-byte peek at the Void and its copy. + Assert.IsLessThanOrEqualTo (16L * file.Length, bytesRead, $"{bytesRead} bytes read for a {file.Length}-byte file"); + } +} diff --git a/tests/TagLibSharp2.Tests/Matroska/MatroskaSaveTests.cs b/tests/TagLibSharp2.Tests/Matroska/MatroskaSaveTests.cs index 733c8bf0..9622ed2a 100644 --- a/tests/TagLibSharp2.Tests/Matroska/MatroskaSaveTests.cs +++ b/tests/TagLibSharp2.Tests/Matroska/MatroskaSaveTests.cs @@ -223,7 +223,8 @@ public void Save_InsertsTagsWhenTheFileHasNone () var tag = MatroskaFile.Read (bytes).File!.Tag; Assert.AreEqual ("Added", tag.Title); Assert.AreEqual ("Someone", tag.Artist); - Assert.IsTrue (bytes.AsSpan ().IndexOf ("Segment Title"u8) >= 0); + // The segment title follows the title edit (#210), so no reader shows the old one. + Assert.AreEqual (-1, bytes.AsSpan ().IndexOf ("Segment Title"u8)); } [TestMethod] @@ -1252,17 +1253,17 @@ public void Save_LeadingPaddingInsideTheSegment_IsKept () } [TestMethod] - public void Save_GarbageAfterARealElement_DoesNotWrite () + public void Save_ByteThatIsNotAnElementAfterARealElement_IsKept () { + // Bytes that are not an element are filler wherever they are in the Segment, as the reads skip them (#208); + // the save used to be refused once an element had been seen. var info = Master (0x1549A966, Element (0x7BA9, "T"u8)); var original = Matroska (Master (0x18538067, Concat (info, new byte[] { 0x01 }))); - var parsed = MatroskaFile.Read (FileWith (Master (0x1F43B675, new byte[] { 1 }))).File!; + var parsed = MatroskaFile.Read (original).File!; var fs = new MockFileSystem (); - fs.AddFile ("/bad.mkv", new byte[] { 1 }); var saved = parsed.SaveToFile ("/bad.mkv", original, fs); - Assert.IsFalse (saved.IsSuccess); - Assert.IsTrue (saved.Error!.Contains ("cannot be bounded", StringComparison.Ordinal)); - Assert.AreEqual (1, fs.ReadAllBytes ("/bad.mkv").Length); + Assert.IsTrue (saved.IsSuccess, saved.Error); + CollectionAssert.AreEqual (original, fs.ReadAllBytes ("/bad.mkv")); } static void AssertFailure (MatroskaFile file, MockFileSystem fs, string path, byte[] original, string error) diff --git a/tests/TagLibSharp2.Tests/Matroska/MatroskaSegmentTitleTests.cs b/tests/TagLibSharp2.Tests/Matroska/MatroskaSegmentTitleTests.cs new file mode 100644 index 00000000..6ac82ff3 --- /dev/null +++ b/tests/TagLibSharp2.Tests/Matroska/MatroskaSegmentTitleTests.cs @@ -0,0 +1,112 @@ +// 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.Matroska; +using TagLibSharp2.Tests.Core; +using TagLibSharp2.Tests.Kit; + +namespace TagLibSharp2.Tests.Matroska; + +/// +/// Setting the title also changes the segment title (Info/Title, RFC 9559 §5.1.2.9), which exiftool and MediaInfo +/// show (#210). Info keeps its size, so nothing after it moves: the new title is written in Info when it fits, and +/// otherwise Info/Title is removed and the TITLE tag is the title every reader shows. Null and Clear remove it. +/// +[TestClass] +[TestCategory ("Unit")] +[TestCategory ("Matroska")] +public class MatroskaSegmentTitleTests +{ + const ulong MuxingApp = 0x4D80; + const ulong WritingApp = 0x5741; + + // EBML header, then a Segment with Info (scale, title, apps, and a 20-byte Void when asked), and one Cluster. + static byte[] File (bool voidInInfo = false) => Nesting.Concat ( + Nesting.EbmlElement (0x1A45DFA3, Nesting.EbmlElement (MatroskaIds.DocType, "matroska"u8)), + Nesting.EbmlElement (MatroskaIds.Segment, Nesting.Concat ( + Nesting.EbmlElement (MatroskaIds.Info, Nesting.Concat ( + Nesting.EbmlElement (MatroskaIds.TimestampScale, [0x0F, 0x42, 0x40]), + Nesting.EbmlElement (MatroskaIds.SegmentTitle, "OldTitle"u8), + Nesting.EbmlElement (MuxingApp, "mux"u8), + Nesting.EbmlElement (WritingApp, "app"u8), + voidInInfo ? Nesting.EbmlElement (MatroskaIds.Void, new byte[18]) : [])), + Nesting.EbmlElement (MatroskaIds.Cluster, Nesting.EbmlElement (0xE7, [0x00]))))); + + static readonly string[] Edits = ["short", "same", "long", "null", "clear"]; + static readonly string[] Saves = ["render", "path"]; + static readonly byte[] InfoId = [0x15, 0x49, 0xA9, 0x66]; + + public static IEnumerable Cases => + from edit in Edits + from save in Saves + select new object[] { edit, save }; + + [TestMethod] + [DynamicData (nameof (Cases))] + public void TitleEdit_ChangesTheSegmentTitle_AndMovesNothing (string edit, string save) + { + var original = File (); + var files = new MockFileSystem (); + files.AddFile ("/a.mka", original); + var file = MatroskaFile.ReadFromFile ("/a.mka", files).File!; + var expected = edit switch { "short" => "New", "same" => "NewTitle", "long" => new string ('x', 40), _ => null }; + if (edit == "clear") + file.Tag!.Clear (); + else + file.Tag!.Title = expected; + + var saved = save == "render" ? SkipPicturesFixtures.Render (file, original)! : SaveByPath (file, files); + + Assert.AreEqual (expected, MatroskaFile.Read (saved).File!.Tag!.Title, "library title"); + // The segment title is the new title when it fits in Info, and gone otherwise; never the old one. + var segmentTitle = SegmentTitle (saved); + Assert.AreNotEqual ("OldTitle", segmentTitle); + Assert.AreEqual (edit is "short" or "same" ? expected : null, segmentTitle); + Assert.AreEqual (InfoRange (original), InfoRange (saved), "Info moved or changed size"); + } + + // A Void inside Info is room: a title longer than the old one goes in Info when the Void makes it fit. + [TestMethod] + public void LongerTitle_UsesTheVoidInInfo () + { + var original = File (voidInInfo: true); + var file = MatroskaFile.Read (original).File!; + + file.Tag.Title = "OldTitle and fifteen"; + var saved = SkipPicturesFixtures.Render (file, original)!; + + Assert.AreEqual ("OldTitle and fifteen", SegmentTitle (saved)); + Assert.AreEqual (InfoRange (original), InfoRange (saved)); + } + + static byte[] SaveByPath (MatroskaFile file, MockFileSystem files) + { + var result = file.SaveToFile ("/b.mka", files); + Assert.IsTrue (result.IsSuccess, result.Error); + return files.ReadAllBytes ("/b.mka"); + } + + // The first Info's offset and length. + static (int, int) InfoRange (byte[] data) + { + var at = data.AsSpan ().IndexOf (InfoId); + Assert.IsGreaterThanOrEqualTo (0, at); + Assert.IsTrue (EbmlReader.TryRead (data, at, data.Length, out var info)); + return (at, info.End - at); + } + + static string? SegmentTitle (byte[] data) + { + var (at, length) = InfoRange (data); + EbmlReader.TryRead (data, at, data.Length, out var info); + var offset = info.DataOffset; + while (offset < at + length && EbmlReader.TryRead (data, offset, at + length, out var child)) { + if (child.Id == MatroskaIds.SegmentTitle) + return System.Text.Encoding.UTF8.GetString (data, child.DataOffset, (int)child.DataLength); + offset = child.End; + } + + return null; + } +} diff --git a/tests/TagLibSharp2.Tests/Matroska/MatroskaWriteBackTests.cs b/tests/TagLibSharp2.Tests/Matroska/MatroskaWriteBackTests.cs index b32a99e6..34069bae 100644 --- a/tests/TagLibSharp2.Tests/Matroska/MatroskaWriteBackTests.cs +++ b/tests/TagLibSharp2.Tests/Matroska/MatroskaWriteBackTests.cs @@ -20,6 +20,8 @@ static readonly (string Name, Func Read, Action Joined (t.Performers), t => t.Performers = t.Performers), ("AlbumArtists", t => Joined (t.AlbumArtists), t => t.AlbumArtists = t.AlbumArtists), ("Composers", t => Joined (t.Composers), t => t.Composers = t.Composers), + ("Composer", t => t.Composer, t => t.Composer = t.Composer), + ("AlbumArtist", t => t.AlbumArtist, t => t.AlbumArtist = t.AlbumArtist), ("Title", t => t.Title, t => t.Title = t.Title), ("Album", t => t.Album, t => t.Album = t.Album), ("Genre", t => t.Genre, t => t.Genre = t.Genre), @@ -27,6 +29,10 @@ static readonly (string Name, Func Read, Action t.Year, t => t.Year = t.Year), ("Comment", t => t.Comment, t => t.Comment = t.Comment), ("BeatsPerMinute", t => t.BeatsPerMinute?.ToString (System.Globalization.CultureInfo.InvariantCulture), t => t.BeatsPerMinute = t.BeatsPerMinute), + ("Track", t => t.Track?.ToString (System.Globalization.CultureInfo.InvariantCulture), t => t.Track = t.Track), + ("TotalTracks", t => t.TotalTracks?.ToString (System.Globalization.CultureInfo.InvariantCulture), t => t.TotalTracks = t.TotalTracks), + ("DiscNumber", t => t.DiscNumber?.ToString (System.Globalization.CultureInfo.InvariantCulture), t => t.DiscNumber = t.DiscNumber), + ("TotalDiscs", t => t.TotalDiscs?.ToString (System.Globalization.CultureInfo.InvariantCulture), t => t.TotalDiscs = t.TotalDiscs), ("Publisher", t => t.Publisher, t => t.Publisher = t.Publisher), ("ReplayGainTrackGain", t => t.ReplayGainTrackGain, t => t.ReplayGainTrackGain = t.ReplayGainTrackGain), ("ReplayGainTrackPeak", t => t.ReplayGainTrackPeak, t => t.ReplayGainTrackPeak = t.ReplayGainTrackPeak), @@ -34,6 +40,35 @@ static readonly (string Name, Func Read, Action values.Length == 0 ? null : string.Join ("|", values); + // The one-name Composer and AlbumArtist read the first name of their list and write through it, as + // Artist does: they read null and dropped every set before (#211 sweep). Writing the first name back keeps + // the other names; another name replaces the list; "" and null clear it. + [TestMethod] + [DataRow ("COMPOSER", 30)] + [DataRow ("ALBUM_ARTIST", 50)] + public void OneNameSetter_ReadsAndWritesTheFirstNameOfTheList (string name, int level) + { + Func one = name == "COMPOSER" ? t => t.Composer : t => t.AlbumArtist; + Action set = name == "COMPOSER" ? (t, v) => t.Composer = v : (t, v) => t.AlbumArtist = v; + Func all = name == "COMPOSER" ? t => t.Composers : t => t.AlbumArtists; + var data = FileWith (Tags (Tag ((ulong)level, Simple (name, "Ada"), Simple (name, "Bea")), Tag (30, Simple ("TITLE", "Song")))); + + var tag = MatroskaFile.Read (data).File!.Tag; + Assert.AreEqual ("Ada", one (tag)); + var before = tag.Render ().ToArray (); + set (tag, "Ada"); + CollectionAssert.AreEqual (before, tag.Render ().ToArray (), "write-back"); + set (tag, "Cy"); + Assert.AreEqual ("Cy", Joined (all (tag)), "set"); + + foreach (var empty in new[] { "", null }) { + tag = MatroskaFile.Read (data).File!.Tag; + set (tag, empty); + Assert.IsNull (one (tag), empty is null ? "null" : "\"\""); + Assert.IsEmpty (all (tag), empty is null ? "null" : "\"\""); + } + } + // A value read back unchanged is a no-op: the bytes stay. Null is a clear: it still reads null afterwards, // and may remove a value a broader level held behind it. [TestMethod] @@ -70,6 +105,17 @@ public void WritingBackTheValueRead_ChangesNoBytes () yield return ($"item {shape}", data); foreach (var (name, build) in SortShapes) yield return ($"sort {name}", build ()); + // The track and disc layouts: ffmpeg's untargeted "n/m" (mkv/ffdisc.mka in review 3), the spec's numbers at 30 + // and 50 with TOTAL_PARTS at 50 and 60, and ffmpeg's untargeted TOTAL_PARTS beside a plain number. + yield return ("numbers ffmpeg", FileWith (Tags (Master (0x7373, Concat (Master (0x63C0, Array.Empty ()), + Simple ("TITLE", "Song"), Simple ("PART_NUMBER", "5/12"), Simple ("DISC", "2/3")))))); + yield return ("numbers spec", FileWith (Tags (Tag (60, Simple ("TOTAL_PARTS", "3")), + Tag (50, Simple ("PART_NUMBER", "2"), Simple ("TOTAL_PARTS", "12")), Tag (30, Simple ("PART_NUMBER", "5"))))); + // The Vorbis names ffmpeg copies from FLAC: a write-back leaves them, though a set writes DISC and "n/m". + yield return ("numbers vorbis names", FileWith (Tags (Master (0x7373, Concat (Master (0x63C0, Array.Empty ()), + Simple ("PART_NUMBER", "5"), Simple ("TRACKTOTAL", "12"), Simple ("DISCNUMBER", "2"), Simple ("TOTALDISCS", "3")))))); + yield return ("numbers ffmpeg total", FileWith (Tags (Master (0x7373, Concat (Master (0x63C0, Array.Empty ()), + Simple ("PART_NUMBER", "5"), Simple ("TOTAL_PARTS", "12")))))); yield return ("genre at 70", FileWith (Tags (Tag (70, Simple ("GENRE", "Rock")), Tag (30, Simple ("TITLE", "Song"))))); yield return ("untargeted ffmpeg", FileWith (Tags (Master (0x7373, Concat (Master (0x63C0, Array.Empty ()), Simple ("TITLE", "Song"), Simple ("ARTIST", "Ada"), Simple ("ARTIST_SORT", "Ada sort"), Simple ("GENRE", "Rock")))))); diff --git a/tests/TagLibSharp2.Tests/Mp4/EsdsParserTests.cs b/tests/TagLibSharp2.Tests/Mp4/EsdsParserTests.cs new file mode 100644 index 00000000..64143556 --- /dev/null +++ b/tests/TagLibSharp2.Tests/Mp4/EsdsParserTests.cs @@ -0,0 +1,45 @@ +// 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.Mp4; + +namespace TagLibSharp2.Tests.Mp4; + +/// +/// ES_Descriptor (ISO/IEC 14496-1 §7.2.6.5): ES_ID, a flags byte, then the optional fields the flags name, then the +/// DecoderConfigDescriptor. A descriptor that ends inside those fields is not an esds the parser can read. +/// +[TestClass] +[TestCategory ("Unit")] +[TestCategory ("Mp4")] +public class EsdsParserTests +{ + [TestMethod] + [DataRow (new byte[] { 0x03, 0x00, 0x00, 0x00 })] + [DataRow (new byte[] { 0x03, 0x02, 0x00, 0x01 })] + [DataRow (new byte[] { 0x03, 0x03, 0x00, 0x01, 0x40 })] + [DataRow (new byte[] { 0x03, 0x05, 0x00, 0x01, 0xC0, 0x00, 0x07 })] + public void DescriptorEndingInsideTheEsFields_IsNotRead (byte[] esds) + { + Assert.IsNull (EsdsParser.Parse (esds)); + } + + [TestMethod] + [DataRow ((byte)0x00, (byte)0x40)] + [DataRow ((byte)0x80, (byte)0x6C)] + [DataRow ((byte)0x40, (byte)0x6C)] + [DataRow ((byte)0x20, (byte)0x6C)] + [DataRow ((byte)0xE0, (byte)0x6C)] + public void DecoderConfig_FollowsTheOptionalFields (byte flags, byte objectType) + { + var box = Mp4TrackTestBuilder.Esds (objectType, flags); + + // The box's payload after its 8-byte header and the FullBox version and flags. + var config = EsdsParser.Parse (box.AsSpan (12)); + + Assert.IsNotNull (config); + Assert.AreEqual (objectType, config.Value.ObjectTypeIndication); + Assert.AreEqual (65536u, config.Value.MaxBitrate); + Assert.AreEqual (65536u, config.Value.AvgBitrate); + } +} diff --git a/tests/TagLibSharp2.Tests/Mp4/Mp4CodecNameTests.cs b/tests/TagLibSharp2.Tests/Mp4/Mp4CodecNameTests.cs new file mode 100644 index 00000000..f7a5af34 --- /dev/null +++ b/tests/TagLibSharp2.Tests/Mp4/Mp4CodecNameTests.cs @@ -0,0 +1,103 @@ +// 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.Mp4; + +namespace TagLibSharp2.Tests.Mp4; + +/// +/// An mp4a sample entry's codec is its esds objectTypeIndication (https://mp4ra.org/registered-types/object-types): +/// 0x6B (ISO/IEC 11172-3) and 0x69 (ISO/IEC 13818-3) are MPEG audio, which ffprobe reports as mp3, and the AAC types +/// are AAC (#206). The esds follows the AudioSampleEntry fields, and 16 or 36 more bytes in a QuickTime sound +/// description of version 1 or 2 (QTFF, Sound sample descriptions). Video fourccs are named, not echoed. +/// +[TestClass] +[TestCategory ("Unit")] +[TestCategory ("Mp4")] +public class Mp4CodecNameTests +{ + [TestMethod] + [DataRow (0x40, (ushort)0, Mp4AudioCodec.Aac, "AAC")] + [DataRow (0x67, (ushort)0, Mp4AudioCodec.Aac, "AAC")] + [DataRow (0x6B, (ushort)0, Mp4AudioCodec.Mp3, "MP3")] + [DataRow (0x69, (ushort)0, Mp4AudioCodec.Mp3, "MP3")] + [DataRow (0x6B, (ushort)1, Mp4AudioCodec.Mp3, "MP3")] + [DataRow (0x6B, (ushort)2, Mp4AudioCodec.Mp3, "MP3")] + [DataRow (0x40, (ushort)2, Mp4AudioCodec.Aac, "AAC")] + public void Mp4aEntry_NamesTheCodecFromItsEsds (int objectType, ushort soundVersion, Mp4AudioCodec codec, string name) + { + var data = Mp4TrackTestBuilder.Movie (Mp4TrackTestBuilder.AudioTrak (1, esds: Mp4TrackTestBuilder.Esds ((byte)objectType), soundVersion: soundVersion)); + + var file = Mp4File.Read (data).File!; + + Assert.AreEqual (codec, file.AudioCodec); + Assert.AreEqual (name, file.Properties.Codec); + } + + // A movie whose audio track's one chunk is the frame header in the mdat after the moov. + static byte[] WithFirstFrame (string sampleType, byte? objectType, byte[] header, bool co64 = false) + { + byte[] Build (uint offset) => Mp4TrackTestBuilder.Movie (Mp4TrackTestBuilder.AudioTrak (1, + esds: objectType is byte type ? Mp4TrackTestBuilder.Esds (type) : null, sampleType: sampleType, chunkOffset: offset, co64: co64)); + var moovEnd = Build (0).Length; + return [.. Build ((uint)moovEnd + 8), .. Mp4TestBuilder.CreateBox ("mdat", [.. header, .. new byte[64]])]; + } + + // Object types 0x6B and 0x69 are MPEG audio of any layer (ISO/IEC 11172-3, 13818-3); the layer is in the first + // frame's header (ISO/IEC 11172-3 §2.4.2.3), and MediaInfo names it from there: mp2.mp4 is Layer II, not MP3. + // QuickTime's .mp3 sound entry (mp3.mov) is MPEG audio too. A first frame that is not a frame header leaves "MP3". + [TestMethod] + [DataRow ("mp4a", 0x6B, new byte[] { 0xFF, 0xFD, 0x90, 0x00 }, "MPEG-1 Layer II")] + [DataRow ("mp4a", 0x6B, new byte[] { 0xFF, 0xFF, 0x90, 0x00 }, "MPEG-1 Layer I")] + [DataRow ("mp4a", 0x69, new byte[] { 0xFF, 0xF5, 0x80, 0x00 }, "MPEG-2 Layer II")] + [DataRow ("mp4a", 0x6B, new byte[] { 0xFF, 0xFB, 0x90, 0x00 }, "MP3")] + [DataRow ("mp4a", 0x6B, new byte[] { 0, 0, 0, 0 }, "MP3")] + [DataRow (".mp3", null, new byte[] { 0xFF, 0xFB, 0x90, 0x00 }, "MP3")] + [DataRow (".mp3", null, new byte[] { 0, 0, 0, 0 }, "MP3")] + public void MpegAudio_IsNamedByTheLayerOfItsFirstFrame (string sampleType, int? objectType, byte[] header, string name) + { + foreach (var co64 in new[] { false, true }) + AssertNamed (WithFirstFrame (sampleType, (byte?)objectType, header, co64), name, co64 ? "co64 " : "stco "); + } + + static void AssertNamed (byte[] data, string name, string context) + { + + foreach (var (entry, file) in new[] { + ("span", Mp4File.Read (data).File!), + ("stream", (Mp4File)TagLibSharp2.Core.MediaFile.Read (new MemoryStream (data), "a.mp4").File!), + ("skip", (Mp4File)TagLibSharp2.Core.MediaFile.Read (new MemoryStream (data), new TagLibSharp2.Core.MediaReadOptions { SkipPictures = true }, "a.mp4").File!), + }) { + Assert.AreEqual (Mp4AudioCodec.Mp3, file.AudioCodec, context + entry); + Assert.AreEqual (name, file.Properties.Codec, context + entry); + } + } + + // Beside a video track, a sound track whose handler is not "soun" is found by its sample entry, .mp3 among them. + [TestMethod] + [DataRow ("mp4a", "AAC")] + [DataRow (".mp3", "MP3")] + public void AudioEntry_WithNoSoundHandler_IsTheAudioTrack (string sampleType, string name) + { + var data = Mp4TrackTestBuilder.Movie (Mp4TrackTestBuilder.VideoTrak (1, "avc1", 320, 240), + Mp4TrackTestBuilder.AudioTrak (2, sampleType: sampleType, handler: "none")); + + Assert.AreEqual (name, Mp4File.Read (data).File!.Properties.Codec); + } + + [TestMethod] + [DataRow ("ap4h", "ProRes")] + [DataRow ("apch", "ProRes")] + [DataRow ("apcn", "ProRes")] + [DataRow ("apcs", "ProRes")] + [DataRow ("apco", "ProRes")] + [DataRow ("ap4x", "ProRes")] + [DataRow ("s263", "H.263")] + [DataRow ("h263", "H.263")] + public void VideoFourcc_IsNamed (string fourcc, string name) + { + var data = Mp4TrackTestBuilder.Movie (Mp4TrackTestBuilder.VideoTrak (1, fourcc, 320, 240)); + + Assert.AreEqual (name, Mp4File.Read (data).File!.VideoProperties!.Value.Codec); + } +} diff --git a/tests/TagLibSharp2.Tests/Mp4/Mp4PictureRoleTests.cs b/tests/TagLibSharp2.Tests/Mp4/Mp4PictureRoleTests.cs new file mode 100644 index 00000000..7a0a7b76 --- /dev/null +++ b/tests/TagLibSharp2.Tests/Mp4/Mp4PictureRoleTests.cs @@ -0,0 +1,72 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using TagLibSharp2.Core; +using TagLibSharp2.Mp4; + +namespace TagLibSharp2.Tests.Mp4; + +/// +/// A covr picture keeps a role other than front cover across a save. +/// +[TestClass] +[TestCategory ("Unit")] +[TestCategory ("Mp4")] +public class Mp4PictureRoleTests +{ + [TestMethod] + public void BackCover_RoundTrips () + { + // covr's data type is the image format. The role rides in the locale's top byte. + var data = TestBuilders.Mp4.CreateMinimalM4a (Mp4CodecType.Aac); + var file = Mp4File.Read (data).File!; + var jpeg = new BinaryData (new byte[] { 0xFF, 0xD8, 0xFF, 0xD9 }); + file.AddPicture (new Mp4Picture ("image/jpeg", PictureType.BackCover, "", jpeg)); + + var again = Mp4File.Read (file.Render (data).Span).File!; + + Assert.AreEqual (1, again.Pictures.Length); + Assert.AreEqual (PictureType.BackCover, again.Pictures[0].PictureType); + } + + [TestMethod] + public void Other_RoundTrips () + { + // A zero locale is the iTunes front cover. Other is a different role and has to survive a save. + var data = TestBuilders.Mp4.CreateMinimalM4a (Mp4CodecType.Aac); + var file = Mp4File.Read (data).File!; + file.AddPicture (new Mp4Picture ("image/jpeg", PictureType.Other, "", new BinaryData (new byte[] { 0xFF, 0xD8, 0xFF, 0xD9 }))); + + var again = Mp4File.Read (file.Render (data).Span).File!; + + Assert.AreEqual (PictureType.Other, again.Pictures[0].PictureType); + } + + /// + /// The locale indicator is a 16-bit country (high half) and a 16-bit language (low half); 0 is every locale, 1 to 255 + /// in either half is a list index, and anything else is an ISO 3166 country or a packed ISO 639-2/T language (QTFF + /// "Locale indicator"). Only a locale whose low 24 bits are 0 and whose top byte is 1 to 21 is a role this library + /// wrote; that byte is below every ISO 3166 letter, so no real locale reads as a role. + /// + [TestMethod] + [DataRow (0x00000000u, PictureType.FrontCover)] + [DataRow (0x01000000u, PictureType.Other)] + [DataRow (0x05000000u, PictureType.BackCover)] + [DataRow (0x15000000u, PictureType.PublisherLogo)] + [DataRow (0x16000000u, PictureType.FrontCover)] + [DataRow (0x05000001u, PictureType.FrontCover)] + [DataRow (0x00010000u, PictureType.FrontCover)] + [DataRow (0x000015C7u, PictureType.FrontCover)] + [DataRow (0x55530000u, PictureType.FrontCover)] + [DataRow (0x555315C7u, PictureType.FrontCover)] + public void Locale_ReadsAsTheRoleOnlyWhenThisLibraryWroteOne (uint locale, PictureType role) + { + byte[] jpeg = [0xFF, 0xD8, 0xFF, 0xD9]; + var data = TestBuilders.Mp4.CreateWithIlstAtoms (TestBuilders.Mp4.CreateIlstChild ("covr", 13, jpeg, locale)); + + var picture = Mp4File.Read (data).File!.Pictures.Single (); + + Assert.AreEqual (role, picture.PictureType); + Assert.AreEqual ("image/jpeg", picture.MimeType); + } +} diff --git a/tests/TagLibSharp2.Tests/Mp4/Mp4TestBuilder.cs b/tests/TagLibSharp2.Tests/Mp4/Mp4TestBuilder.cs index 4c23b5bf..67954636 100644 --- a/tests/TagLibSharp2.Tests/Mp4/Mp4TestBuilder.cs +++ b/tests/TagLibSharp2.Tests/Mp4/Mp4TestBuilder.cs @@ -102,12 +102,9 @@ public static byte[] CreateMoovBox (params byte[][] children) /// Complete mvhd box bytes. public static byte[] CreateMvhdBox (uint duration, uint timescale, byte version = 0) { + // CreateFullBox writes the version and flags. var content = new BinaryDataBuilder (); - // Version and flags - content.Add (version); - content.AddUInt24BE (0); // flags - if (version == 0) { // Version 0: 32-bit values content.AddUInt32BE (0); // creation_time diff --git a/tests/TagLibSharp2.Tests/Mp4/Mp4TrackTestBuilder.cs b/tests/TagLibSharp2.Tests/Mp4/Mp4TrackTestBuilder.cs new file mode 100644 index 00000000..cf557692 --- /dev/null +++ b/tests/TagLibSharp2.Tests/Mp4/Mp4TrackTestBuilder.cs @@ -0,0 +1,176 @@ +// 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; + +namespace TagLibSharp2.Tests.Mp4; + +/// +/// Builds movies from audio and video tracks: tkhd (both versions, any matrix), hdlr, and one sample entry +/// (ISO/IEC 14496-12 §8.3.2, §8.4.3, §12.1.3 VisualSampleEntry, §12.2.3 AudioSampleEntry). +/// +internal static class Mp4TrackTestBuilder +{ + internal const uint MovieTimescale = 1000; + internal const uint MovieDuration = 2000; + + /// The tkhd matrix's a, b, c and d terms in 16.16 (§8.3.2.3). x, y, u and v are 0; w is 1.0 in 2.30. + internal readonly record struct Matrix (int A, int B, int C, int D) + { + public static Matrix Identity => new (0x10000, 0, 0, 0x10000); + } + + /// ftyp and a moov holding mvhd and the tracks, in the order given. + internal static byte[] Movie (params byte[][] traks) => + [ + .. Mp4TestBuilder.CreateFtypBox ("isom", 512, "isom", "mp41"), + .. Mp4TestBuilder.CreateMoovBox ([Mp4TestBuilder.CreateMvhdBox (MovieDuration, MovieTimescale), .. traks]), + ]; + + /// A track whose only sample entry is a VisualSampleEntry of . + internal static byte[] VideoTrak ( + uint trackId, + string sampleType, + ushort width, + ushort height, + string handler = "vide", + Matrix? matrix = null, + byte tkhdVersion = 0, + byte[]? sampleChildren = null, + byte[]? tref = null, + int? tkhdLength = null) => + Trak (Tkhd (trackId, tkhdVersion, matrix ?? Matrix.Identity, width, height, tkhdLength), tref, handler, MovieTimescale, + VisualSampleEntry (sampleType, width, height, sampleChildren ?? [])); + + /// An AAC sound track: mp4a with , by default an esds of object type 0x40. + /// 1 or 2 writes a QuickTime sound description of that version, whose 16 or 36 + /// extra bytes come before the esds. + /// names another entry, such as QuickTime's .mp3, whose children are + /// when given. adds an stco with one chunk at that file offset. + internal static byte[] AudioTrak (uint trackId, uint sampleRate = 44100, ushort channels = 2, byte[]? tref = null, byte[]? esds = null, + ushort soundVersion = 0, string sampleType = "mp4a", uint? chunkOffset = null, string handler = "soun", bool co64 = false) => + Trak (Tkhd (trackId, 0, Matrix.Identity, 0, 0), tref, handler, sampleRate, + AudioSampleEntry (sampleType, sampleRate, channels, esds ?? (sampleType == "mp4a" ? Esds (0x40) : []), soundVersion), + chunkOffset is not uint at ? [] : co64 + ? Mp4TestBuilder.CreateFullBox ("co64", 0, 0, [0, 0, 0, 1, 0, 0, 0, 0, (byte)(at >> 24), (byte)(at >> 16), (byte)(at >> 8), (byte)at]) + : Mp4TestBuilder.CreateFullBox ("stco", 0, 0, [0, 0, 0, 1, (byte)(at >> 24), (byte)(at >> 16), (byte)(at >> 8), (byte)at])); + + /// A tref box with one chap reference naming (§8.3.3). + internal static byte[] ChapterReference (params uint[] trackIds) + { + using var ids = new BinaryDataBuilder (); + foreach (var id in trackIds) + ids.AddUInt32BE (id); + return Mp4TestBuilder.CreateBox ("tref", Mp4TestBuilder.CreateBox ("chap", ids.ToArray ())); + } + + /// + /// An esds box: ES_Descriptor (tag 3) holding a DecoderConfigDescriptor (tag 4) with + /// (ISO/IEC 14496-1 §7.2.6.5, §7.2.6.6; ISO/IEC 14496-14 §5.6). + /// + /// The object type, such as 0x20 (MPEG-4 Visual) or 0x6C (JPEG). + /// The ES_Descriptor flags byte: 0x80 streamDependenceFlag, 0x40 URL_Flag, 0x20 OCRstreamFlag. + internal static byte[] Esds (byte objectTypeIndication, byte esFlags = 0) + { + byte[] decoderConfig = [0x04, 13, objectTypeIndication, 0x11, 0, 0, 0, 0, 0x01, 0, 0, 0, 0x01, 0, 0]; + using var optional = new BinaryDataBuilder (); + if ((esFlags & 0x80) != 0) + optional.AddUInt16BE (7); + if ((esFlags & 0x40) != 0) { + optional.Add ((byte)3); + optional.Add ("u:x"u8.ToArray ()); + } + if ((esFlags & 0x20) != 0) + optional.AddUInt16BE (9); + + byte[] body = [0, 1, esFlags, .. optional.ToArray (), .. decoderConfig]; + return Mp4TestBuilder.CreateFullBox ("esds", 0, 0, [0x03, (byte)body.Length, .. body]); + } + + static byte[] Trak (byte[] tkhd, byte[]? tref, string handler, uint mediaTimescale, byte[] sampleEntry, byte[]? stblTail = null) + { + var stsd = Mp4TestBuilder.CreateFullBox ("stsd", 0, 0, [0, 0, 0, 1, .. sampleEntry]); + var minf = Mp4TestBuilder.CreateBox ("minf", Mp4TestBuilder.CreateBox ("stbl", [.. stsd, .. stblTail ?? []])); + var mdia = Mp4TestBuilder.CreateBox ("mdia", [.. Mdhd (mediaTimescale), .. Hdlr (handler), .. minf]); + return Mp4TestBuilder.CreateBox ("trak", [.. tkhd, .. tref ?? [], .. mdia]); + } + + /// + /// tkhd: the matrix is at payload offset 40 in version 0 and 52 in version 1, then width and height in 16.16. + /// cuts the payload (version and flags included) to that many bytes. + /// + static byte[] Tkhd (uint trackId, byte version, Matrix matrix, ushort width, ushort height, int? length = null) + { + using var body = new BinaryDataBuilder (); + var timeSize = version == 1 ? 8 : 4; + body.AddZeros (timeSize * 2); + body.AddUInt32BE (trackId); + body.AddZeros (4); + body.AddZeros (timeSize - 4); + body.AddUInt32BE (MovieDuration); + body.AddZeros (16); + body.AddInt32BE (matrix.A); + body.AddInt32BE (matrix.B); + body.AddZeros (4); + body.AddInt32BE (matrix.C); + body.AddInt32BE (matrix.D); + body.AddZeros (12); + body.AddInt32BE (0x40000000); + body.AddUInt32BE ((uint)width << 16); + body.AddUInt32BE ((uint)height << 16); + var full = Mp4TestBuilder.CreateFullBox ("tkhd", version, 3, body.ToArray ()); + return length is int cut ? Mp4TestBuilder.CreateBox ("tkhd", full[8..(8 + cut)]) : full; + } + + static byte[] Mdhd (uint timescale) + { + using var body = new BinaryDataBuilder (); + body.AddZeros (8); + body.AddUInt32BE (timescale); + body.AddUInt32BE (timescale * 2); + body.AddUInt16BE (0x55C4); + body.AddZeros (2); + return Mp4TestBuilder.CreateFullBox ("mdhd", 0, 0, body.ToArray ()); + } + + static byte[] Hdlr (string handler) => + Mp4TestBuilder.CreateFullBox ("hdlr", 0, 0, [0, 0, 0, 0, .. Encoding.ASCII.GetBytes (handler), .. new byte[12], 0]); + + /// VisualSampleEntry: 8 bytes of SampleEntry, then 70 bytes with width and height at 24 and 26, then boxes. + static byte[] VisualSampleEntry (string type, ushort width, ushort height, byte[] children) + { + using var body = new BinaryDataBuilder (); + body.AddZeros (6); + body.AddUInt16BE (1); + body.AddZeros (16); + body.AddUInt16BE (width); + body.AddUInt16BE (height); + body.AddUInt32BE (0x00480000); + body.AddUInt32BE (0x00480000); + body.AddZeros (4); + body.AddUInt16BE (1); + body.AddZeros (32); + body.AddUInt16BE (0x0018); + body.AddUInt16BE (0xFFFF); + body.Add (children); + return Mp4TestBuilder.CreateBox (type, body.ToArray ()); + } + + /// AudioSampleEntry: 8 bytes of SampleEntry, then channelcount, samplesize and samplerate (16.16), then boxes. + static byte[] AudioSampleEntry (string type, uint sampleRate, ushort channels, byte[] children, ushort soundVersion = 0) + { + using var body = new BinaryDataBuilder (); + body.AddZeros (6); + body.AddUInt16BE (1); + body.AddUInt16BE (soundVersion); + body.AddZeros (6); + body.AddUInt16BE (channels); + body.AddUInt16BE (16); + body.AddZeros (4); + body.AddUInt32BE (sampleRate << 16); + body.AddZeros (soundVersion switch { 1 => 16, 2 => 36, _ => 0 }); + body.Add (children); + return Mp4TestBuilder.CreateBox (type, body.ToArray ()); + } +} diff --git a/tests/TagLibSharp2.Tests/Mp4/Mp4VideoTrackTests.cs b/tests/TagLibSharp2.Tests/Mp4/Mp4VideoTrackTests.cs new file mode 100644 index 00000000..65fa635a --- /dev/null +++ b/tests/TagLibSharp2.Tests/Mp4/Mp4VideoTrackTests.cs @@ -0,0 +1,268 @@ +// 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.Mp4; +using TagLibSharp2.Tests.Core; +using TagLibSharp2.Tests.Kit; +using static TagLibSharp2.Tests.Mp4.Mp4TrackTestBuilder; + +namespace TagLibSharp2.Tests.Mp4; + +/// +/// Which track the video properties come from, and what they say. +/// +[TestClass] +[TestCategory ("Unit")] +[TestCategory ("Mp4")] +public class Mp4VideoTrackTests +{ + const int Half = 46340; // 0.70709228515625 in 16.16, as ffmpeg writes cos 45° + + /// + /// tkhd matrices and the clockwise rotation exiftool, mediainfo and AVFoundation's preferredTransform report + /// for them (measured on ffmpeg files made with -display_rotation 90, -90, 180, 45 and -45). A mirror is not a + /// rotation, so it reports 0 (the three tools say 180); so do a skew and an all-zero matrix. + /// + static readonly (string Name, Matrix Matrix, int Rotation)[] Rotations = [ + ("identity", Matrix.Identity, 0), + ("90", new Matrix (0, 0x10000, -0x10000, 0), 90), + ("180", new Matrix (-0x10000, 0, 0, -0x10000), 180), + ("270", new Matrix (0, -0x10000, 0x10000, 0), 270), + ("45", new Matrix (Half, Half, -Half, Half), 45), + ("315", new Matrix (Half, -Half, Half, Half), 315), + ("mirror", new Matrix (-0x10000, 0, 0, 0x10000), 0), + ("skew", new Matrix (0x10000, 0x10000, 0, 0x10000), 0), + ("zero", new Matrix (0, 0, 0, 0), 0), + ]; + + static readonly byte[] TkhdVersions = [0, 1]; + + // "meta" stands for any handler other than "vide": the sample entry still decides. + static readonly string[] VisualHandlers = ["vide", "meta"]; + + public static IEnumerable RotationCases () => + from rotation in Rotations + from version in TkhdVersions + from handler in VisualHandlers + select new object[] { rotation.Name, version, handler }; + + [TestMethod] + [DynamicData (nameof (RotationCases))] + public void VisualTrack_ReportsCodedSize_AndMatrixRotation (string rotation, byte tkhdVersion, string handler) + { + // ISO/IEC 14496-12 §12.1.3: width and height in the VisualSampleEntry are the coded size; §8.3.2.3: the tkhd + // matrix is applied at presentation. ffprobe, mediainfo, exiftool and AVFoundation all report 320x240 for + // every one of these files. A visual sample entry is video even when the handler is not "vide". + var row = Rotations.Single (r => r.Name == rotation); + var data = Movie (VideoTrak (1, "avc1", 320, 240, handler: handler, matrix: row.Matrix, tkhdVersion: tkhdVersion)); + + var file = Mp4File.Read (data).File!; + var video = file.VideoProperties!.Value; + + Assert.AreEqual (new VideoProperties (TimeSpan.FromSeconds (2), 320, 240, 0, 0, "H.264") { Rotation = row.Rotation }, video); + Assert.AreEqual (video, ((IMediaFile)file).VideoProperties); + Assert.AreEqual (MediaTypes.Video, ((IMediaFile)file).MediaTypes); + Assert.AreEqual (0, file.Properties.SampleRate); + } + + /// + /// Track layouts, with the media types, video and audio sample rate every reader reports for them. A track another + /// track names in a tref/chap (ISO/IEC 14496-12 §8.3.3; QTFF "Track reference types", chap) is chapter media, as + /// Apple's chapter-image track in bgo_701689.m4a is: ffprobe marks it attached_pic and timed_thumbnails, and + /// mediainfo lists it among the audio track's menus. It is neither the video nor the audio. + /// + static readonly (string Name, byte[][] Traks, MediaTypes Types, string? Video, int SampleRate)[] Layouts = [ + ("audio only", [AudioTrak (1)], MediaTypes.Audio, null, 44100), + ("video only", [VideoTrak (1, "avc1", 320, 240)], MediaTypes.Video, "320x240 H.264", 0), + ("video then audio", [VideoTrak (1, "avc1", 320, 240), AudioTrak (2)], MediaTypes.Audio | MediaTypes.Video, "320x240 H.264", 44100), + ("audio then video", [AudioTrak (1), VideoTrak (2, "avc1", 320, 240)], MediaTypes.Audio | MediaTypes.Video, "320x240 H.264", 44100), + ("audio with chapter images", [AudioTrak (1, tref: ChapterReference (2)), VideoTrak (2, "jpeg", 2048, 1536)], MediaTypes.Audio, null, 44100), + ("chapter images before the video", [ + VideoTrak (3, "jpeg", 2048, 1536), + VideoTrak (1, "avc1", 320, 240, tref: ChapterReference (3)), + AudioTrak (2, tref: ChapterReference (3))], MediaTypes.Audio | MediaTypes.Video, "320x240 H.264", 44100), + ("chapter images with a visual sample and no vide handler", [AudioTrak (1, tref: ChapterReference (2)), VideoTrak (2, "avc1", 640, 480, handler: "meta")], MediaTypes.Audio, null, 44100), + ]; + + public static IEnumerable LayoutCases () => Layouts.Select (layout => new object[] { layout.Name }); + + [TestMethod] + [DynamicData (nameof (LayoutCases))] + public void TrackLayout_PicksThePresentationTracks (string layout) + { + var row = Layouts.Single (l => l.Name == layout); + + IMediaFile file = Mp4File.Read (Movie (row.Traks)).File!; + + Assert.AreEqual (row.Types, file.MediaTypes); + Assert.AreEqual (row.Video, file.VideoProperties is { } video ? $"{video.Width}x{video.Height} {video.Codec}" : null); + Assert.AreEqual (row.SampleRate, file.AudioProperties!.SampleRate); + } + + /// + /// An mp4v sample entry names its codec in the esds DecoderConfigDescriptor's objectTypeIndication (ISO/IEC 14496-14 + /// §5.6; MP4RA object types). ffmpeg writes MPEG-1, MPEG-2, JPEG and PNG video this way; ffprobe reads them as + /// mpeg1video, mpeg2video, mjpeg and png, and mediainfo as MPEG Video, MPEG Video, JPEG and PNG. The names follow + /// the ones this library gives MPEG-PS video. + /// + [TestMethod] + [DataRow (0x20, (byte)0, "MPEG-4")] + [DataRow (0x21, (byte)0, "H.264")] + [DataRow (0x23, (byte)0, "HEVC")] + [DataRow (0x5F, (byte)0, "MPEG-4")] + [DataRow (0x60, (byte)0, "MPEG-2 Video")] + [DataRow (0x61, (byte)0, "MPEG-2 Video")] + [DataRow (0x65, (byte)0, "MPEG-2 Video")] + [DataRow (0x66, (byte)0, "MPEG-4")] + [DataRow (0x6A, (byte)0, "MPEG-1 Video")] + [DataRow (0x6C, (byte)0, "JPEG")] + [DataRow (0x6D, (byte)0, "PNG")] + [DataRow (0x6E, (byte)0, "JPEG 2000")] + [DataRow (0x6C, (byte)0x80, "JPEG")] + [DataRow (0x6C, (byte)0x40, "JPEG")] + [DataRow (0x6C, (byte)0x20, "JPEG")] + [DataRow (0x6C, (byte)0xE0, "JPEG")] + public void Mp4vSample_NamesTheCodecFromItsEsds (int objectTypeIndication, byte esFlags, string codec) + { + var data = Movie (VideoTrak (1, "mp4v", 320, 240, sampleChildren: Esds ((byte)objectTypeIndication, esFlags))); + + var video = Mp4File.Read (data).File!.VideoProperties!.Value; + + Assert.AreEqual (new VideoProperties (TimeSpan.FromSeconds (2), 320, 240, 0, 0, codec), video); + } + + [TestMethod] + [DataRow ("mp4v", "MPEG-4")] + [DataRow ("jpeg", "JPEG")] + [DataRow ("avc1", "H.264")] + [DataRow ("hvc1", "HEVC")] + [DataRow ("vp09", "VP9")] + [DataRow ("av01", "AV1")] + [DataRow ("ap4h", "ProRes")] + public void SampleWithoutEsds_NamesTheCodecFromItsType (string sampleType, string codec) + { + // QTFF "Video sample description": jpeg is Photo-JPEG, which AVFoundation and mediainfo report as JPEG. + var data = Movie (VideoTrak (1, sampleType, 320, 240)); + + Assert.AreEqual (codec, Mp4File.Read (data).File!.VideoProperties!.Value.Codec); + } + + /// + /// A movie that uses every rule at once: chapter images listed first and named by both presentation tracks, an + /// MPEG-1 video in an mp4v entry with a tkhd version 1 matrix (rotated 270 clockwise), then the sound track. + /// + static byte[] Everything () => Movie ( + VideoTrak (3, "jpeg", 2048, 1536), + VideoTrak (1, "mp4v", 320, 240, matrix: new Matrix (0, -0x10000, 0x10000, 0), tkhdVersion: 1, sampleChildren: Esds (0x6A), tref: ChapterReference (3)), + AudioTrak (2, 48000, 2, tref: ChapterReference (3))); + + static readonly VideoProperties EverythingVideo = new (TimeSpan.FromSeconds (2), 320, 240, 0, 0, "MPEG-1 Video") { Rotation = 270 }; + + static readonly string[] EntryPointNames = ["span", "data", "stream", "stream without pictures", "path", "path async", "stream async"]; + + public static IEnumerable EntryPoints () => EntryPointNames.Select (name => new object[] { name }); + + [TestMethod] + [DynamicData (nameof (EntryPoints))] + public async Task EveryEntryPoint_ReportsTheSameTracks (string entry) + { + var data = Everything (); + var fs = new MockFileSystem (); + fs.AddFile ("/a.mp4", data); + + IMediaFile? file = entry switch { + "span" => Mp4File.Read (data).File, + "data" => (IMediaFile?)MediaFile.ReadFromData (data).File, + "stream" => (IMediaFile?)MediaFile.Read (new MemoryStream (data)).File, + "stream without pictures" => (IMediaFile?)MediaFile.Read (new MemoryStream (data), new MediaReadOptions { SkipPictures = true }).File, + "path" => (IMediaFile?)MediaFile.Read ("/a.mp4", fs).File, + "path async" => (IMediaFile?)(await MediaFile.ReadAsync ("/a.mp4", fs)).File, + _ => (IMediaFile?)(await MediaFile.ReadAsync (new MemoryStream (data))).File, + }; + + Assert.IsNotNull (file); + Assert.AreEqual (EverythingVideo, file.VideoProperties); + Assert.AreEqual (MediaTypes.Audio | MediaTypes.Video, file.MediaTypes); + Assert.AreEqual (48000, file.AudioProperties!.SampleRate); + Assert.AreEqual (2, file.AudioProperties.Channels); + } + + [TestMethod] + public void HostileTracks_NeverThrow_OnSpanOrStream () + { + var data = Everything (); + static void Touch (object? read) + { + if (read is IMediaFile file) + _ = (file.VideoProperties, file.MediaTypes, file.AudioProperties); + } + + static void Read (byte[] input) + { + Touch (Mp4File.Read (input).File); + Touch (MediaFile.Read (new MemoryStream (input)).File); + } + + Assert.IsTrue (Hostile.EveryTruncation (data, Read) > data.Length); + Assert.IsTrue (Hostile.ByteFlips (data, Read) > data.Length); + } + + [TestMethod] + public void ChapterReferences_CostLinearWork () + { + // n chapter-image tracks, each named by the sound track's chap: the presentation-track choice walks each + // reference once. + static byte[] Build (int n) => Movie ([ + AudioTrak (1, tref: ChapterReference ([.. Enumerable.Range (2, n).Select (id => (uint)id)])), + .. Enumerable.Range (2, n).Select (id => VideoTrak ((uint)id, "jpeg", 64, 64)), + ]); + + Bounds.AssertLinearAllocation (Build, data => Assert.IsNull (Mp4File.Read (data).File!.VideoProperties), 256); + } + + /// + /// The avgBitrate of an mp4a's esds is the bitrate (ISO/IEC 14496-1 §7.2.6.6). An esds box too short to hold even + /// its FullBox header, or one whose descriptor is cut, gives no bitrate and does not stop the read. + /// + [TestMethod] + [DataRow ("whole", 65)] + [DataRow ("empty box", 0)] + [DataRow ("header only", 0)] + [DataRow ("cut descriptor", 0)] + public void AudioEsds_GivesTheBitrate_OrNoneWhenItIsShort (string shape, int bitrate) + { + var esds = shape switch { + "whole" => Esds (0x40), + "empty box" => Mp4TestBuilder.CreateBox ("esds", []), + "header only" => Mp4TestBuilder.CreateBox ("esds", [0, 0, 0]), + _ => Mp4TestBuilder.CreateFullBox ("esds", 0, 0, [0x03, 0x19, 0x00, 0x01, 0x00, 0x04, 0x0D, 0x40]), + }; + + var audio = Mp4File.Read (Movie (AudioTrak (1, esds: esds))).File!.Properties; + + Assert.AreEqual (bitrate, audio.Bitrate); + Assert.AreEqual (44100, audio.SampleRate); + Assert.AreEqual (2, audio.Channels); + } + + /// + /// The matrix's a, b, c and d end 20 bytes after its start: payload offset 60 in a version 0 tkhd, 72 in version 1. + /// A tkhd cut before that has no rotation; the size still comes from the sample entry. + /// + [TestMethod] + [DataRow ((byte)0, 0, 0)] + [DataRow ((byte)0, 3, 0)] + [DataRow ((byte)0, 59, 0)] + [DataRow ((byte)0, 60, 90)] + [DataRow ((byte)1, 71, 0)] + [DataRow ((byte)1, 72, 90)] + public void ShortTkhd_HasNoRotation (byte version, int length, int rotation) + { + var data = Movie (VideoTrak (1, "avc1", 320, 240, matrix: new Matrix (0, 0x10000, -0x10000, 0), tkhdVersion: version, tkhdLength: length)); + + var video = Mp4File.Read (data).File!.VideoProperties!.Value; + + Assert.AreEqual (new VideoProperties (TimeSpan.FromSeconds (2), 320, 240, 0, 0, "H.264") { Rotation = rotation }, video); + } +} diff --git a/tests/TagLibSharp2.Tests/Mpeg/Mp3FileTests.cs b/tests/TagLibSharp2.Tests/Mpeg/Mp3FileTests.cs index cba7e877..aff3b1dc 100644 --- a/tests/TagLibSharp2.Tests/Mpeg/Mp3FileTests.cs +++ b/tests/TagLibSharp2.Tests/Mpeg/Mp3FileTests.cs @@ -177,13 +177,11 @@ public void Tag_BothIdTags_PrefersId3v2ButFallsBackToId3v1 () } /// - /// An MP3 file with no ID3v2 and no ID3v1 must expose Tag == null, - /// matching the "tag is absent" convention used by other - /// implementations in this repo. A Mp3File that - /// always materialized a facade would lie about the absence of metadata. + /// An MP3 file with no ID3v2 and no ID3v1 still has a tag view, so a caller can set a title. + /// Reading that view must not create a stored tag. /// [TestMethod] - public void Tag_NoTagsPresent_ReturnsNull () + public void Tag_NoTagsPresent_IsAnEmptyView () { var audioOnly = new byte[256]; @@ -192,7 +190,7 @@ public void Tag_NoTagsPresent_ReturnsNull () Assert.IsTrue (result.IsSuccess); Assert.IsNull (result.File!.Id3v2Tag); Assert.IsNull (result.File.Id3v1Tag); - Assert.IsNull (result.File.Tag); + Assert.IsTrue (result.File.Tag!.IsEmpty); } /// diff --git a/tests/TagLibSharp2.Tests/Mpeg/MpegPsAppendedTagTests.cs b/tests/TagLibSharp2.Tests/Mpeg/MpegPsAppendedTagTests.cs index 6e7a7bd3..e0e4697a 100644 --- a/tests/TagLibSharp2.Tests/Mpeg/MpegPsAppendedTagTests.cs +++ b/tests/TagLibSharp2.Tests/Mpeg/MpegPsAppendedTagTests.cs @@ -96,7 +96,8 @@ public void Read_FooterWithoutAMatchingHeader_IsStreamData (int offset, byte val var file = MpegPsFile.Read (data).File!; - Assert.IsNull (file.Tag); + TaglessFixtures.AssertStoresNoTag (file); + Assert.IsNull (file.Id3v2Tag); var rendered = file.Render (data).ToArray (); CollectionAssert.AreEqual (data, rendered); } @@ -110,7 +111,7 @@ public void Read_V23TagWithAFooter_IsStreamData () tag[^7] = 3; var data = Concat (ProgramStream (), tag); - Assert.IsNull (MpegPsFile.Read (data).File!.Tag); + TaglessFixtures.AssertStoresNoTag (MpegPsFile.Read (data).File!); } [TestMethod] @@ -128,8 +129,8 @@ public void Read_ApeSizeLongerThanTheFile_FindsNoAppendedTag () var streamed = MediaFile.Read (new MemoryStream (data), "clip.mpg"); Assert.IsTrue (result.IsSuccess, result.Error); - Assert.IsNull (result.File!.Tag); - Assert.IsNull (streamed.Tag); + TaglessFixtures.AssertStoresNoTag (result.File!); + TaglessFixtures.AssertStoresNoTag ((IMediaFile)streamed.File!); } [TestMethod] @@ -145,7 +146,7 @@ public void Read_ApeHeaderAtTheEnd_IsNotAnApeFooter () header[23] = 0x20; var data = Concat (ProgramStream (), Appended ("Hidden"), header); - Assert.IsNull (MpegPsFile.Read (data).File!.Tag); + TaglessFixtures.AssertStoresNoTag (MpegPsFile.Read (data).File!); } [TestMethod] @@ -157,7 +158,7 @@ public void Read_FooterWithoutTheFooterFlag_IsStreamData () tag[^5] = 0x00; var data = Concat (ProgramStream (), tag); - Assert.IsNull (MpegPsFile.Read (data).File!.Tag); + TaglessFixtures.AssertStoresNoTag (MpegPsFile.Read (data).File!); } [TestMethod] @@ -206,7 +207,7 @@ public void Read_FooterClaimingMoreThanTheFile_IsStreamData () var result = MpegPsFile.Read (data); Assert.IsTrue (result.IsSuccess, result.Error); - Assert.IsNull (result.File!.Tag); + TaglessFixtures.AssertStoresNoTag (result.File!); } [TestMethod] diff --git a/tests/TagLibSharp2.Tests/Mpeg/MpegPsFileTests.cs b/tests/TagLibSharp2.Tests/Mpeg/MpegPsFileTests.cs index 46290ab8..14259661 100644 --- a/tests/TagLibSharp2.Tests/Mpeg/MpegPsFileTests.cs +++ b/tests/TagLibSharp2.Tests/Mpeg/MpegPsFileTests.cs @@ -48,7 +48,7 @@ public void Read_Mpeg1ProgramStream_ReadsVideoAudioAndDuration () Assert.AreEqual (192, audio.Bitrate); Assert.AreEqual ("MPEG-1 Layer II", audio.Codec); Assert.AreEqual (TimeSpan.FromSeconds (2), audio.Duration); - Assert.IsNull (file.Tag); + TaglessFixtures.AssertStoresNoTag (file); } [TestMethod] @@ -678,7 +678,8 @@ public void Tag_IsACombinedViewThatWritesBothTags () public void EnsureId3v2Tag_CreatesOnce () { var file = MpegPsFile.Read (ProgramStream ()).File!; - Assert.IsNull (file.Tag); + TaglessFixtures.AssertStoresNoTag (file); + Assert.IsNull (file.Id3v2Tag); var tag = file.EnsureId3v2Tag (); diff --git a/tests/TagLibSharp2.Tests/Mpeg/MpegPsGuardTests.cs b/tests/TagLibSharp2.Tests/Mpeg/MpegPsGuardTests.cs index 9143fbbc..87d3956e 100644 --- a/tests/TagLibSharp2.Tests/Mpeg/MpegPsGuardTests.cs +++ b/tests/TagLibSharp2.Tests/Mpeg/MpegPsGuardTests.cs @@ -4,6 +4,7 @@ using TagLibSharp2.Core; using TagLibSharp2.Id3.Id3v2; using TagLibSharp2.Mpeg; +using TagLibSharp2.Tests.Core; using static TagLibSharp2.Tests.Mpeg.MpegPsAppendedTagTests; using static TagLibSharp2.Tests.Mpeg.MpegPsFileTests; using static TagLibSharp2.Tests.Mpeg.MpegPsTestBuilder; @@ -255,7 +256,7 @@ public void Read_FooterWithRevisionFF_IsStreamData () tag[^6] = 0xFF; var data = Concat (ProgramStream (), tag); - Assert.IsNull (MpegPsFile.Read (data).File!.Tag); + TaglessFixtures.AssertStoresNoTag (MpegPsFile.Read (data).File!); } [TestMethod] diff --git a/tests/TagLibSharp2.Tests/Mpeg/MpegPsTrailerTests.cs b/tests/TagLibSharp2.Tests/Mpeg/MpegPsTrailerTests.cs index 6177c48a..6fcb0d91 100644 --- a/tests/TagLibSharp2.Tests/Mpeg/MpegPsTrailerTests.cs +++ b/tests/TagLibSharp2.Tests/Mpeg/MpegPsTrailerTests.cs @@ -4,6 +4,7 @@ using TagLibSharp2.Core; using TagLibSharp2.Id3.Id3v2; using TagLibSharp2.Mpeg; +using TagLibSharp2.Tests.Core; using static TagLibSharp2.Tests.Mpeg.MpegPsAppendedTagTests; using static TagLibSharp2.Tests.Mpeg.MpegPsFileTests; using static TagLibSharp2.Tests.Mpeg.MpegPsTestBuilder; @@ -61,7 +62,8 @@ public void Read_ApeTagEndingTheFileWithoutAnAppendedTag_IsNotId3v1 () var file = MpegPsFile.Read (data).File!; - Assert.IsNull (file.Tag); + TaglessFixtures.AssertStoresNoTag (file); + Assert.IsNull (file.Id3v2Tag); file.EnsureId3v2Tag ().Title = "Front"; var rendered = file.Render (data).ToArray (); CollectionAssert.AreEqual (Concat (stream, ape), rendered.AsSpan (rendered.Length - stream.Length - ape.Length).ToArray ()); diff --git a/tests/TagLibSharp2.Tests/PublicApi/Snapshots/TagLibSharp2.PublicApi.verified.txt b/tests/TagLibSharp2.Tests/PublicApi/Snapshots/TagLibSharp2.PublicApi.verified.txt index 8afff90b..cb3f554a 100644 --- a/tests/TagLibSharp2.Tests/PublicApi/Snapshots/TagLibSharp2.PublicApi.verified.txt +++ b/tests/TagLibSharp2.Tests/PublicApi/Snapshots/TagLibSharp2.PublicApi.verified.txt @@ -1541,6 +1541,7 @@ namespace TagLibSharp2.Core public double FrameRate { get; init; } public int Height { get; init; } public bool IsValid { get; } + public int Rotation { get; init; } public int Width { get; init; } public static TagLibSharp2.Core.VideoProperties Empty { get; } public override string ToString() { } @@ -2581,6 +2582,7 @@ namespace TagLibSharp2.Matroska public sealed class MatroskaTag : TagLibSharp2.Core.Tag { public override string? Album { get; set; } + public override string? AlbumArtist { get; set; } public override string? AlbumArtistSort { get; set; } public override string[] AlbumArtists { get; set; } public override string? AlbumSort { get; set; } @@ -2590,6 +2592,7 @@ namespace TagLibSharp2.Matroska public override uint? BeatsPerMinute { get; set; } public override string? CatalogNumber { get; set; } public override string? Comment { get; set; } + public override string? Composer { get; set; } public override string? ComposerSort { get; set; } public override string[] Composers { get; set; } public override string? Conductor { get; set; } @@ -2797,6 +2800,7 @@ namespace TagLibSharp2.Mp4 public uint? TotalDiscs { get; set; } public uint? TotalTracks { get; set; } public uint? Track { get; set; } + public TagLibSharp2.Core.VideoProperties? VideoProperties { get; } public string? Work { get; set; } public string? Year { get; set; } public void AddPicture(TagLibSharp2.Core.IPicture picture) { } diff --git a/tests/TagLibSharp2.Tests/Riff/AviInfoTextTests.cs b/tests/TagLibSharp2.Tests/Riff/AviInfoTextTests.cs index 2b2252fe..70da0b85 100644 --- a/tests/TagLibSharp2.Tests/Riff/AviInfoTextTests.cs +++ b/tests/TagLibSharp2.Tests/Riff/AviInfoTextTests.cs @@ -28,7 +28,8 @@ public class AviInfoTextTests /// /// {CSET none, 0, 28591, 932, 1252, 65001} x {unchanged ASCII, UTF-8, legacy} x {changed ASCII, non-ASCII}. - /// Each cell either keeps the unchanged field's bytes and text, or refuses the save. + /// Each cell either keeps the unchanged field's bytes and text, or refuses the save. With no CSET a legacy value + /// next to a non-ASCII change keeps its bytes and the change is written by the read rule, with no CSET. /// [TestMethod] [DynamicData (nameof (Matrix))] @@ -48,8 +49,9 @@ public void Save_UnchangedField_KeepsItsBytesOrTheSaveRefuses (int codePage, str var result = file.SaveToFile ("/out.avi", original, fs); var nativeUtf8 = codePage == 65001; - var becameUtf8 = changedKind == "nonascii" && !nativeUtf8; var kind = Kind (codePage, unchanged); + var byReadRule = changedKind == "nonascii" && codePage < 0 && kind == "guess"; + var becameUtf8 = changedKind == "nonascii" && !nativeUtf8 && !byReadRule; var expectRefusal = becameUtf8 && kind == "guess"; var reencoded = becameUtf8 && kind == "exact"; var cell = $"CSET {codePage}, unchanged {unchangedKind}, changed {changedKind}"; @@ -114,8 +116,9 @@ public void Save_CustomFieldChange_KeepsUnchangedBytesOrTheSaveRefuses (int code var fs = new MockFileSystem (); var result = file.SaveToFile ("/out.avi", original, fs); - var becameUtf8 = changedKind == "nonascii" && codePage != 65001; var kind = Kind (codePage, unchanged); + var byReadRule = changedKind == "nonascii" && codePage < 0 && kind == "guess"; + var becameUtf8 = changedKind == "nonascii" && codePage != 65001 && !byReadRule; var cell = $"CSET {codePage}, unchanged {unchangedKind}, custom field {changedKind}"; if (becameUtf8 && kind == "guess") { Assert.IsFalse (result.IsSuccess, cell); @@ -142,6 +145,8 @@ public void Save_CustomFieldChange_KeepsUnchangedBytesOrTheSaveRefuses (int code Assert.AreEqual ((ushort)65001, CodePage (saved), cell); else if (codePage >= 0) Assert.AreEqual ((ushort)codePage, CodePage (saved), $"{cell}: the declared code page is kept"); + else + CollectionAssert.DoesNotContain (AviSaveTests.Names (saved), "CSET", cell); } [TestMethod] @@ -166,11 +171,12 @@ public void Save_CustomFieldThatFitsTheDeclaredCodePage_IsWrittenInIt (ushort co } [TestMethod] - public void WavInfo_CustomFieldOutsideLatin1_IsRefused () + public void WavInfo_CustomFieldOutsideLatin1_IsWrittenByTheReadRule () { - // A WAV INFO list is Latin-1 and has no CSET, so text it cannot hold is refused, not mangled. + // A WAV INFO list has no CSET: text Windows-1252 cannot hold is UTF-8, as the list is read (#209, #216). var tag = new RiffInfoTag (); - Assert.IsFalse (tag.SetCustomField ("IXYZ", ChangedNonAscii)); + Assert.IsTrue (tag.SetCustomField ("IXYZ", ChangedNonAscii)); + Assert.AreEqual (ChangedNonAscii, RiffInfoTag.Parse (tag.Render ().Slice (8))!.GetField ("IXYZ")); Assert.IsTrue (tag.SetCustomField ("IXYZ", "Café")); } @@ -288,7 +294,6 @@ public void Save_UndefinedByteInTheDeclaredCodePage_Refuses (int codePage, byte[ } [TestMethod] - [DataRow (-1, "is not UTF-8 and the file has no CSET, so its code page is only a guess")] [DataRow (932, "is in code page 932, which this library does not decode")] [DataRow (1251, "is in code page 1251, which this library does not decode")] public void Save_RefusalNamesItsReason (int codePage, string reason) @@ -398,23 +403,46 @@ public void Save_NonAsciiTextWithoutACset_IsUtf8UnderACset () } [TestMethod] - public void Save_LegacyTextNextToANonAsciiChange_Refuses () + public void Save_LegacyTextNextToANonAsciiChange_KeepsItsBytes_AndWritesTheChangeByTheReadRule () { - // VirtualDub on a Russian system writes cp1251 with no CSET; transcoding it would destroy it. + // VirtualDub on a Russian system writes cp1251 with no CSET; transcoding it would destroy it, and a CSET of 65001 + // would misdeclare it. A list with no CSET is read field by field (UTF-8, else Windows-1252), so the changed value + // is written by that rule and the legacy bytes stay as they are, with no CSET: everything this reader returned + // reads back the same (review 4, B1). The save used to be refused. var builder = new AviTestBuilder (); builder.InfoBytes.Add (("IART", Windows1251Alice)); var original = builder.Build (); var file = AviFile.Read (original).File!; + var artist = file.InfoTag.Artist; file.InfoTag.Title = ChangedNonAscii; - var saved = file.SaveToFile ("/x.avi", original, new MockFileSystem ()); + var saved = file.Render (original).ToArray (); - Assert.IsFalse (saved.IsSuccess); - StringAssert.Contains (saved.Error, "IART"); - Assert.AreEqual (0, file.Render (original).Length, "Render of the file refuses the same way."); + CollectionAssert.AreEqual (Windows1251Alice, AviTestBuilder.InfoField (saved, "IART")); + CollectionAssert.AreEqual (Encoding.UTF8.GetBytes (ChangedNonAscii + "\0"), AviTestBuilder.InfoField (saved, "INAM")); + CollectionAssert.DoesNotContain (AviSaveTests.Names (saved), "CSET"); + var again = AviFile.Read (saved).File!.InfoTag; + Assert.AreEqual (ChangedNonAscii, again.Title); + Assert.AreEqual (artist, again.Artist); + Assert.IsTrue (file.SaveToFile ("/x.avi", original, new MockFileSystem ()).IsSuccess); + } - file.InfoTag.Artist = "Alisa"; - Assert.IsTrue (file.SaveToFile ("/x.avi", original, new MockFileSystem ()).IsSuccess, "Setting the field too lets the save write UTF-8."); + [TestMethod] + public void Save_LegacyTextCopiedToAnotherField_ReadsBackTheSame () + { + // Text the reader returned from a Windows-1252 field with no CSET, written to another field: stored and read back. + var builder = new AviTestBuilder (); + builder.InfoBytes.Add (("INAM", Windows1252Halo)); + var original = builder.Build (); + var file = AviFile.Read (original).File!; + file.InfoTag.Comment = file.InfoTag.Title; + + var saved = file.Render (original).ToArray (); + + var again = AviFile.Read (saved).File!.InfoTag; + Assert.AreEqual ("Beyonc\u00E9 \u2013 Halo", again.Comment); + Assert.AreEqual (again.Title, again.Comment); + CollectionAssert.AreEqual (Windows1252Halo, AviTestBuilder.InfoField (saved, "INAM")); } [TestMethod] diff --git a/tests/TagLibSharp2.Tests/Riff/WavInfoTextTests.cs b/tests/TagLibSharp2.Tests/Riff/WavInfoTextTests.cs new file mode 100644 index 00000000..fa2cc107 --- /dev/null +++ b/tests/TagLibSharp2.Tests/Riff/WavInfoTextTests.cs @@ -0,0 +1,238 @@ +// 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.Riff; +using TagLibSharp2.Tests.Core; + +namespace TagLibSharp2.Tests.Riff; + +/// +/// WAV RIFF INFO has no declared character set. It is read as AVI reads a list with no CSET: a field of valid UTF-8 is +/// UTF-8, as ffmpeg writes it, and any other is Windows-1252, as Windows writes it (#216). A changed value is written by +/// the same rule, Windows-1252 when its bytes read back as the value and UTF-8 otherwise, so whatever the reader +/// returns the writer stores and reads back unchanged, and no text is written as '?' or refused (#209). A field the +/// caller did not change keeps its bytes. +/// +[TestClass] +[TestCategory ("Unit")] +public class WavInfoTextTests +{ + static byte[] InfoOnlyWav () + { + var wav = WavFile.Read (TestBuilders.Wav.CreateMinimal (soundBytes: 64)).File!; + wav.InfoTag = new RiffInfoTag { Title = "Old" }; + return wav.Render ().ToArray (); + } + + static readonly string[] Saves = ["path", "async", "async-source", "render"]; + + static byte[] Save (WavFile file, string save, MockFileSystem files) + { + if (save == "render") + return file.Render ().ToArray (); + var result = save switch { + "path" => file.SaveToFile ("/a.wav", files), + "async" => file.SaveToFileAsync ("/a.wav", files).GetAwaiter ().GetResult (), + _ => file.SaveToFileAsync (files).GetAwaiter ().GetResult (), + }; + Assert.IsTrue (result.IsSuccess, result.Error); + return files.ReadAllBytes ("/a.wav"); + } + + // A title Latin-1 cannot hold used to fail the save (#209); it is now UTF-8, which the reader, ffprobe and + // MediaInfo read back, on every save. + [TestMethod] + [DataRow ("path")] + [DataRow ("async")] + [DataRow ("async-source")] + [DataRow ("render")] + public void TitleLatin1CannotHold_IsWrittenAsUtf8_OnEverySave (string save) + { + var files = new MockFileSystem (); + files.AddFile ("/a.wav", InfoOnlyWav ()); + var file = WavFile.ReadFromFile ("/a.wav", files).File!; + + ((IMediaFile)file).Tag!.Title = "新标题 Ünï"; + + var saved = Save (file, save, files); + Assert.AreEqual ("新标题 Ünï", WavFile.Read (saved).File!.InfoTag!.Title); + byte[] field = [.. "INAM"u8, .. BitConverter.GetBytes ((uint)Utf8 ("新标题 Ünï").Length + 1), .. Utf8 ("新标题 Ünï"), 0]; + Assert.IsGreaterThanOrEqualTo (0, saved.AsSpan ().IndexOf (field)); + } + + [TestMethod] + public void Latin1Title_Saves () + { + var original = InfoOnlyWav (); + var file = WavFile.Read (original).File!; + + ((IMediaFile)file).Tag!.Title = "Ünï"; + + Assert.AreEqual ("Ünï", WavFile.Read (file.Render ().Span).File!.InfoTag!.Title); + } + + // A WAV built from raw INFO fields: each value's bytes and a NUL, padded to even. + static byte[] WavWithInfo (params (string Id, byte[] Value)[] fields) + { + using var list = new BinaryDataBuilder (); + list.AddStringLatin1 ("INFO"); + foreach (var (id, value) in fields) { + list.AddStringLatin1 (id); + list.AddUInt32LE ((uint)value.Length + 1); + list.Add (value); + list.Add (0); + if ((value.Length & 1) == 0) + list.Add (0); + } + + var body = list.ToArray (); + byte[] wav = [.. TestBuilders.Wav.CreateMinimal (soundBytes: 64), .. "LIST"u8, .. BitConverter.GetBytes ((uint)body.Length), .. body]; + BitConverter.GetBytes ((uint)(wav.Length - 8)).CopyTo (wav, 4); + return wav; + } + + static byte[] Utf8 (string text) => System.Text.Encoding.UTF8.GetBytes (text); + + static byte[] Latin1 (string text) => System.Text.Encoding.Latin1.GetBytes (text); + + // ffmpeg writes WAV INFO as UTF-8 (#216). The fields are read with AVI's rule for a list with no CSET: + // valid UTF-8 is UTF-8, anything else Windows-1252 (InfoText.Decode), so ffmpeg's text is not mojibake. + static byte[] FfmpegStyleInfo () => WavWithInfo ( + ("INAM", Utf8 ("新标题")), + ("IART", Utf8 ("Ünï")), + ("ICMT", Latin1 ("Ünï")), + ("IPRD", [0x93, (byte)'x', 0x94]), + ("IGNR", Utf8 ("Rock"))); + + public static IEnumerable ReadEntries => SkipPicturesFixtures.Entries.Select (entry => new object[] { entry }); + + [TestMethod] + [DynamicData (nameof (ReadEntries))] + public void Utf8Info_ReadsAsUtf8_AsAviInfoDoes (string entry) + { + var read = SkipPicturesFixtures.Read (FfmpegStyleInfo (), "a.wav", entry, skip: false); + + var tag = ((WavFile)read.File!).InfoTag!; + Assert.AreEqual ("新标题", tag.Title); + Assert.AreEqual ("Ünï", tag.Artist); + Assert.AreEqual ("Ünï", tag.Comment); + Assert.AreEqual ("\u201Cx\u201D", tag.Album); + Assert.AreEqual ("Rock", tag.Genre); + } + + // A field the caller did not change keeps its bytes, so a save writes ffmpeg's UTF-8 back as it was, whatever else + // changed; a changed value that Windows-1252 holds is written in it. + [TestMethod] + public void UnchangedUtf8Field_KeepsItsBytes_ThroughASave () + { + var original = FfmpegStyleInfo (); + var file = WavFile.Read (original).File!; + CollectionAssert.AreEqual (original, file.Render ().ToArray (), "a render with no edit"); + + file.InfoTag!.Genre = "Jazz"; + file.InfoTag.Comment = "Ünï Ö"; + var saved = file.Render ().ToArray (); + + var again = WavFile.Read (saved).File!.InfoTag!; + Assert.AreEqual ("新标题", again.Title); + Assert.AreEqual ("Ünï", again.Artist); + Assert.AreEqual ("\u201Cx\u201D", again.Album); + Assert.AreEqual ("Jazz", again.Genre); + Assert.AreEqual ("Ünï Ö", again.Comment); + byte[] title = [.. "INAM"u8, .. BitConverter.GetBytes ((uint)Utf8 ("新标题").Length + 1), .. Utf8 ("新标题"), 0]; + byte[] comment = [.. "ICMT"u8, 6, 0, 0, 0, .. Latin1 ("Ünï Ö"), 0]; + Assert.IsGreaterThanOrEqualTo (0, saved.AsSpan ().IndexOf (title), "INAM keeps its UTF-8 bytes"); + Assert.IsGreaterThanOrEqualTo (0, saved.AsSpan ().IndexOf (comment), "the changed ICMT is Windows-1252"); + } + + // A changed value whose Windows-1252 bytes would read back as other text (valid UTF-8, or a C1 control 1252 maps + // elsewhere) is written as UTF-8 instead; one that round-trips in Windows-1252 (a typographic apostrophe, 0x92, as + // Windows writes it) is written in it. + [TestMethod] + [DataRow ("\u00C3\u00A9", null)] + [DataRow ("a\u0093b", null)] + [DataRow ("Don\u2019t", new byte[] { 0x44, 0x6F, 0x6E, 0x92, 0x74 })] + [DataRow ("\u20AC\u2014\u2122\u2026", new byte[] { 0x80, 0x97, 0x99, 0x85 })] + public void ChangedValue_IsWrittenByTheReadRule (string title, byte[]? windows1252) + { + var file = WavFile.Read (FfmpegStyleInfo ()).File!; + + file.InfoTag!.Title = title; + + var saved = file.Render ().ToArray (); + Assert.AreEqual (title, WavFile.Read (saved).File!.InfoTag!.Title); + var bytes = windows1252 ?? Utf8 (title); + byte[] field = [.. "INAM"u8, .. BitConverter.GetBytes ((uint)bytes.Length + 1), .. bytes, 0]; + Assert.IsGreaterThanOrEqualTo (0, saved.AsSpan ().IndexOf (field)); + } + + // Review 4's cases: text the reader returned from one file or field, written to another, saved where main saved it + // and #209's refusal did not. + [TestMethod] + public void TextReadFromAnotherFileOrField_Saves_AndReadsBackTheSame () + { + var ffmpeg = WavFile.Read (FfmpegStyleInfo ()).File!; + var windows = WavFile.Read (WavWithInfo (("INAM", [(byte)'D', (byte)'o', (byte)'n', 0x92, (byte)'t', (byte)' ', (byte)'S', (byte)'t', (byte)'o', (byte)'p']))).File!; + Assert.AreEqual ("Don\u2019t Stop", windows.InfoTag!.Title); + + foreach (var source in new[] { ffmpeg, windows }) { + var target = WavFile.Read (InfoOnlyWav ()).File!; + ((IMediaFile)source).Tag!.CopyTo (((IMediaFile)target).Tag!); + var copied = WavFile.Read (target.Render ().Span).File!.InfoTag!; + Assert.AreEqual (source.InfoTag!.Title, copied.Title, "CopyTo"); + + var same = WavFile.Read (source.Render ().Span).File!; + same.InfoTag!.Comment = same.InfoTag.Title; + Assert.AreEqual (same.InfoTag.Title, WavFile.Read (same.Render ().Span).File!.InfoTag!.Comment, "Comment = Title"); + } + } + + // The invariant, as a property: any text without a NUL (an INFO value ends at its first NUL) written to a field + // reads back the same, from every read entry and every save, alone and beside fields of every kind. + static IEnumerable Texts () + { + yield return "Old"; + yield return "新标题"; + yield return "Ünï"; + yield return "\u00C3\u00A9t\u00C3\u00A9"; + yield return "Don\u2019t"; + yield return "\u0081\u008D\u008F\u0090\u009D"; + yield return "\u0080\u0085\u009F"; + yield return "\u20AC\u201A\u0192"; + yield return "\U0001F3B5 note"; + yield return "\u00FF\u00A0\u00AD"; + var random = new Random (186); + char[] pool = ['a', ' ', 'é', 'ÿ', '\u0080', '\u0092', '\u0093', '\u2019', '\u20AC', 'Ã', '©', '€', 'Ж', '新', '\u00C2', '\u00A0', '\u007F']; + for (var n = 0; n < 60; n++) + yield return new string (Enumerable.Range (0, 1 + random.Next (8)).Select (_ => pool[random.Next (pool.Length)]).ToArray ()); + } + + public static IEnumerable TextCases => Texts ().Select ((text, n) => new object[] { n, text }); + + [TestMethod] + [DynamicData (nameof (TextCases))] + public void WhatTheWriterStores_ReadsBackUnchanged (int n, string text) + { + foreach (var entry in SkipPicturesFixtures.Entries) { + foreach (var save in Saves) { + if (save != "render" && !entry.Contains ("path", StringComparison.Ordinal)) + continue; + var files = new MockFileSystem (); + var file = (WavFile)SkipPicturesFixtures.Read (FfmpegStyleInfo (), "a.wav", entry, skip: false, files).File!; + Assert.AreEqual ("Ünï\u201Cx\u201D", file.InfoTag!.Artist + file.InfoTag.Album, $"{entry} read"); + ((IMediaFile)file).Tag!.Title = text; + file.InfoTag!.SetField ("IXYZ", text); + // A stream or path read keeps the samples in the source, so only a path read saves, and Render needs a + // read that loaded them. + if (save == "render" && entry is "stream" or "async-stream" or "path" or "async-path") + continue; + var again = WavFile.Read (Save (file, save, files)).File!.InfoTag!; + Assert.AreEqual (text, again.Title, $"{n} {entry} {save}"); + Assert.AreEqual (text, again.GetField ("IXYZ"), $"{n} {entry} {save} custom"); + Assert.AreEqual ("Ünï", again.Artist, $"{n} {entry} {save} unchanged UTF-8 field"); + Assert.AreEqual ("\u201Cx\u201D", again.Album, $"{n} {entry} {save} unchanged Windows-1252 field"); + } + } + } +} diff --git a/tests/TagLibSharp2.Tests/TestBuilders.cs b/tests/TagLibSharp2.Tests/TestBuilders.cs index 03ac545c..89eb9387 100644 --- a/tests/TagLibSharp2.Tests/TestBuilders.cs +++ b/tests/TagLibSharp2.Tests/TestBuilders.cs @@ -283,6 +283,22 @@ public static byte[] CreateTagWithTextFrameV22 (string frameId, string text) return result; } + /// + /// Creates an ID3v2.2 tag (header version 2, no flags) holding in order. + /// + public static byte[] CreateTagV22 (params byte[][] frames) + { + var body = frames.SelectMany (f => f).ToArray (); + return [.. CreateHeader (TestConstants.Id3v2.Version2, (uint)body.Length), .. body]; + } + + /// + /// Creates an ID3v2.2 PIC frame as ID3v2.2 §4.15 lays it out: encoding 0, a 3-character image + /// format, the picture type, a NUL-terminated Latin-1 description and the picture data. + /// + public static byte[] CreatePictureFrameV22 (string imageFormat, byte pictureType, string description, byte[] data) => + CreateFrameV22 ("PIC", [0, .. Encoding.ASCII.GetBytes (imageFormat), pictureType, .. Encoding.Latin1.GetBytes (description), 0, .. data]); + /// /// Applies unsynchronization to data (inserts 0x00 after each 0xFF). /// diff --git a/tests/TagLibSharp2.Tests/WavPack/WavPackFileTests.cs b/tests/TagLibSharp2.Tests/WavPack/WavPackFileTests.cs index 5e3c8f93..81057830 100644 --- a/tests/TagLibSharp2.Tests/WavPack/WavPackFileTests.cs +++ b/tests/TagLibSharp2.Tests/WavPack/WavPackFileTests.cs @@ -1034,7 +1034,7 @@ static MediaFileResult FromWavPackStream (byte[] data, string name) if (!opened.IsSuccess || opened.File is null) return MediaFileResult.Failure (opened.Error ?? "WavPack stream read failed"); - return MediaFileResult.Success (opened.File, opened.File.Tag, MediaFormat.WavPack); + return MediaFileResult.Success (opened.File, MediaFormat.WavPack); } static MediaFileResult FromWavPackFile (byte[] data, string name) @@ -1045,7 +1045,7 @@ static MediaFileResult FromWavPackFile (byte[] data, string name) if (!opened.IsSuccess || opened.File is null) return MediaFileResult.Failure (opened.Error ?? "WavPack file read failed"); - return MediaFileResult.Success (opened.File, opened.File.Tag, MediaFormat.WavPack); + return MediaFileResult.Success (opened.File, MediaFormat.WavPack); } static byte[] WavWithFactChunk () diff --git a/tests/TagLibSharp2.Tests/Xiph/FlacTagTests.cs b/tests/TagLibSharp2.Tests/Xiph/FlacTagTests.cs index 290c1e6a..8b588f6b 100644 --- a/tests/TagLibSharp2.Tests/Xiph/FlacTagTests.cs +++ b/tests/TagLibSharp2.Tests/Xiph/FlacTagTests.cs @@ -87,8 +87,7 @@ public void Tag_Pictures_IncludesMetadataBlockPictureFromVorbisComment () [TestMethod] public void Tag_SetPictures_WritesToNativePictureBlocks () { - // Seed with a VorbisComment so Tag is non-null (the reader maps a - // file with no metadata to Tag == null -- see Tag_AbsentMetadata_ReturnsNull). + // The view is always present. Setting a field creates the Vorbis comment. var data = TestBuilders.Flac.CreateWithVorbisComment ("seed", "seed"); var file = FlacFile.Read (data).File!; @@ -259,18 +258,23 @@ public void Tag_TagType_AdvertisesXiphAndFlacMetadata () } /// - /// A FLAC file with no VorbisComment and no PICTURE blocks exposes - /// Tag == null, matching the "tag absent" convention used across - /// other implementations in this repo. + /// A FLAC file with no Vorbis comment still has a tag view. Reading it does + /// not create a comment block. Setting a field does. /// [TestMethod] - public void Tag_AbsentMetadata_ReturnsNull () + public void Tag_AbsentMetadata_ViewDoesNotCreateBlockUntilSet () { var file = FlacFile.Read (TestBuilders.Flac.CreateMinimal ()).File!; Assert.IsNull (file.VorbisComment); Assert.AreEqual (0, file.Pictures.Count); - Assert.IsNull (file.Tag); + Assert.IsNotNull (file.Tag); + Assert.IsTrue (file.Tag!.IsEmpty); + Assert.IsNull (file.VorbisComment); + + file.Tag.Title = "Hello"; + + Assert.AreEqual ("Hello", file.VorbisComment!.Title); } /// @@ -379,4 +383,14 @@ static byte[] BuildFlacWithEmbeddedPicture () return seedRead.File.Render (seed).ToArray (); } + + // Pictures alone are FLAC tag data (PICTURE blocks), so such a view is not the empty view of a tagless file. + [TestMethod] + public void PicturesWithoutVorbisComment_ReportTheFlacTagType () + { + var file = FlacFile.Read (TestBuilders.Flac.CreateWithPicture ()).File!; + Assert.IsNull (file.VorbisComment); + + Assert.AreEqual (TagTypes.Xiph | TagTypes.FlacMetadata, file.Tag!.TagType); + } } diff --git a/tests/TagLibSharp2.Tests/Xiph/VorbisCommentExtendedMetadataTests.cs b/tests/TagLibSharp2.Tests/Xiph/VorbisCommentExtendedMetadataTests.cs index d0c0c4d8..97ff0150 100644 --- a/tests/TagLibSharp2.Tests/Xiph/VorbisCommentExtendedMetadataTests.cs +++ b/tests/TagLibSharp2.Tests/Xiph/VorbisCommentExtendedMetadataTests.cs @@ -417,7 +417,9 @@ public void OriginalReleaseDate_SetEmpty_RemovesOriginalYear () comment.AddField ("ORIGINALYEAR", "1969"); comment.OriginalReleaseDate = ""; - Assert.AreEqual ("", comment.OriginalReleaseDate); + // "" clears, as null does (#211). + Assert.IsNull (comment.OriginalReleaseDate); + Assert.HasCount (0, comment.GetValues ("ORIGINALDATE")); Assert.HasCount (0, comment.GetValues ("ORIGINALYEAR")); } @@ -473,15 +475,16 @@ public void Movement_LegacyNameInMovement_IsReadAndKeptInStep () } [TestMethod] - public void Movement_SetEmpty_LeavesAnEmptyNameAndRemovesALegacyName () + public void Movement_SetEmpty_RemovesTheNameAndALegacyName () { var comment = new VorbisComment ("test"); comment.AddField ("MOVEMENTNAME", "Adagio"); comment.AddField ("MOVEMENT", "Adagio"); comment.Movement = ""; - Assert.AreEqual ("", comment.Movement); - AssertSingle (comment, "MOVEMENTNAME", ""); + // "" clears, as null does (#211). + Assert.IsNull (comment.Movement); + Assert.HasCount (0, comment.GetValues ("MOVEMENTNAME")); Assert.HasCount (0, comment.GetValues ("MOVEMENT")); } @@ -530,9 +533,9 @@ public void EmptyPrimary_UnchangedWriteBack_KeepsBothFields (string primary, str AssertSingle (reparsed.Tag!, primary, ""); AssertSingle (reparsed.Tag!, fallback, fallbackValue); - // An explicit empty value is not what the getter returned, so it is still a clear. + // An explicit empty value is not what the getter returned, so it is still a clear, of both names (#211). info.SetValue (comment, ""); - AssertSingle (comment, primary, ""); + Assert.HasCount (0, comment.GetValues (primary)); Assert.HasCount (0, comment.GetValues (fallback)); }