diff --git a/CHANGELOG.md b/CHANGELOG.md
index a62c0c54..21e3fbe0 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -21,6 +21,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
+- `AsfFile.FileProperties` (`AsfFileProperties?`) exposes the File Properties Object the header holds, or null when it has none (#250). `AsfFileProperties.IsBroadcast` (#249), which tells why a file still being written reads a duration of 0, could only be reached by parsing the file again; the file ID, size, creation date, packet counts, durations, flags and bit rate can now be read too. Every read entry point fills it, `SkipPictures` reads included. A header with more than one (the specification allows one) gives the last
+- `WavFile.SaveToFile ()` and `AiffFile.SaveToFile ()` save back to `SourcePath` through the file system the file was read with (or the one given), as every other format does, so `file.Tag.Title = x; file.SaveToFile ();` works on WAV and AIFF (#235). They refuse as `SaveToFileAsync ()` does: a file not read from a path, or read with `SkipPictures`. `WavFile.Tag` and `AviFile.Tag` are public; each was only the explicit `IMediaFile.Tag`, so `wav.Tag` and `avi.Tag` did not compile on a `WavFile` or `AviFile` variable. On a WAV file with both an ID3v2 tag and an INFO list, `Tag` is now a view over both, ID3v2 first, so a set or `Clear` reaches both and ffprobe, ExifTool and MediaInfo show no stale copy (it was the ID3v2 tag alone, and the INFO list kept the old values). `AviFile.Tag` is the INFO tag, combined with the ID3v2 tag when there is one, and is never null, after `Dispose` too; on an AVI with no ID3v2 tag a field INFO cannot hold, such as a MusicBrainz ID, is not stored. After a successful save over its source a WAV, AVI or AIFF file's view goes on without a tag the save emptied and did not write, as a fresh read of the saved file has none, so the next value set through `Tag` goes where that read's would; the emptied tag stays the file's, so a value set later through a reference to it is written; a kept ID3v2 tag becomes a new ID3v2.4 tag, as a view creates one, and the view's next write that needs an ID3v2 tag uses it. After a save to another path the object still describes its source
- `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
@@ -77,7 +79,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Tags: every `LIST INFO` in the first RIFF form (`InfoTag`) and an ID3v2 tag in an `ID32` chunk (`Id3v2Tag`). The unified `Tag` puts INFO first.
- Saving keeps the `movi` sample bytes. New tags reuse the tag and `JUNK` space between `hdrl` and `movi`, so nothing moves; when they do not fit, the data moves and the RIFF size, absolute `idx1` offsets, `indx` super index entries, and each standard index's base offset (or, when the base stays put, each entry whose data moved) are shifted. A save is refused, without writing, when an index cannot be verified first. A changed tag chunk cut off by the end of the file is turned into `JUNK`, so a removed value does not return. An unchanged save writes the original bytes.
- A file whose RIFF size is still the streaming placeholder 0xFFFFFFFF reports no duration: its frame counts were never filled in.
- - 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).
+ - 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, and untouched text whose code page is a guess because of a byte its declared code page leaves undefined (0x81, 0x8D, 0x8F, 0x90, 0x9D in 1252; 0x80-0x9F under code page 0) as the UTF-8 of the text read (#220). With no `CSET`, or a `CSET` of a code page not decoded here (for example Shift-JIS or cp1251), untouched text that is not UTF-8 keeps its bytes, the changes are written by the read rule, and such a `CSET` is dropped. 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. 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.
@@ -123,6 +125,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- An ID3v2 frame in ISO-8859-1 given text that ISO-8859-1 cannot hold is written in an encoding that holds it, UTF-16 with a BOM in an ID3v2.3 tag and UTF-8 in an ID3v2.4 tag, where each such character was written as `?` (#262). This reaches a frame read from a file in ISO-8859-1 whose `Text`, `Description`, `Value`, `FileName` or pairs are then changed, and a frame built or set to `TextEncodingType.Latin1` with such text: text frames, `TXXX`, `COMM`, `USLT`, `WXXX` descriptions, `GEOB`, `SYLT`, the involved-people lists and `APIC` descriptions. A frame's own `RenderContent ()` writes such text in UTF-8, as a v2.4 tag does
- A chapter or table-of-contents title in an ID3v2.3 tag whose TIT2 is 128 bytes or longer reads back (#261). The TIT2 that CHAP and CTOC embed was written with a syncsafe size, which only ID3v2.4 uses, and read with a big-endian one in v2.3, so the title was lost. The embedded frames now take the tag's own frame header when written, and are read with the same frame-header and frame-flag rules as the tag's top-level frames, so an embedded TIT2 that is grouped, compressed, unsynchronised or has a data length indicator reads too. A v2.3 file an earlier version wrote reads, since a v2.3 size that does not fit is read as syncsafe, as for a top-level frame
- A frame written into an ID3v2.3 tag, or a v2.2 tag (which is written as v2.3), uses a text encoding ID3v2.3 defines: ISO-8859-1 when its text fits, otherwise UTF-16 with a BOM (#255). New frames start as UTF-8, which only ID3v2.4 defines, and were written with that encoding byte whatever the tag's version. So a picture added to an MP3 whose tag is ID3v2.3, as the QuickStart's "add album art" sample does, saved, but this library's own read of the file found no picture, because the v2.3 APIC reader rejects encoding 3. The text frames, `TXXX`, `COMM`, `USLT`, `WXXX`, `GEOB`, `SYLT`, the involved-people lists and the title inside `CHAP` and `CTOC` had the same encoding byte, which the other readers accepted. The tag's version now chooses the encoding when the tag is written, for every frame and every save path, in MP3, WAV, AIFF, DSF, DFF, raw AAC, MPEG-PS and AVI. A frame read from a v2.3 tag in UTF-8 or UTF-16BE is written back in ISO-8859-1 or UTF-16 too; one in ISO-8859-1 or UTF-16 keeps that encoding and is written as before. `SetCustomField` on a v2.3 tag now writes ISO-8859-1 when the values fit, where it always wrote UTF-16. An ID3v2.4 tag still writes UTF-8. A frame object keeps the encoding it was given, and its own `RenderContent ()` still writes that one. A v2.3 picture in UTF-8 or UTF-16BE, such as one an earlier version of this library wrote, is now read, as the other v2.3 frames are, and the next save rewrites it in an encoding v2.3 defines. The `Id3v2Tag` class example now compiles: its picture, custom-field and comment snippets used a wrong argument order and members that do not exist
+- A save writes no APE tag that holds no item, in Monkey's Audio, WavPack, Musepack and raw AAC (#258). `Clear` on a tagged file wrote an empty 32-byte APE tag (with its header too, when it was read with one), so a fresh read of the saved file cleared again wrote that empty tag while the object that saved wrote none. Now `Clear` removes the tag, a file with no tag stays without one, and after such a save over its source the emptied tag the object keeps (a reference to it stays live) is no longer the tag read, so the next value set is written footer-only, as a fresh read's view writes it (raw AAC's view goes to its ID3v2 tag, as a fresh read's does); after a save to another path the object still describes its source and keeps the read layout
+- An ASF save writes the header's objects in the order they were read (#257). The Content Description and Extended Content Description Objects were moved to the end of the header, so a save with no edit changed both WMA files in the TagLib# test set (`sample.wma` from offset 4,330). They are now rewritten where they were, and a save with no edit of those files is byte for byte; one the file did not have goes after the others, as before, and a second copy of either (the specification allows one) is still dropped
+- An ASF save that changes the file's length keeps the File Properties Object's File Size, "the size, in bytes, of the entire file", true (#253). It was copied unchanged, so a 10,332-byte WMA given a long title read a File Size of 10,332 at 18,314 bytes. A save whose length differs from the file the object describes (the one it read, or the one it last saved over its source) now writes the length it writes, into the File Properties Object the read takes (the last, in a header holding more than the one the specification allows; any other stays as stored), on every save entry point, and after a save over the source `AsfFile.FileProperties` is the object the save wrote; a save to another path leaves the object describing its source. A save that keeps the length writes the object's File Size, so a save with no edit leaves the field as it was, even where another tagger left it stale (both WMA files in the TagLib# test set declare a size smaller than the file). A broadcast file's File Size, which the specification calls invalid, stays as it is
+- An MP4 ilst keeps its items in the order they were read, and a save after a save over the source writes what a fresh read of the saved file writes (#252). Standard atoms, freeform (`----`) fields, cover art and atoms the tag does not map share one order: a set field stays in its item's place and a new field goes after the others, in the order added. A save grouped them by kind and wrote the standard atoms in the order of a dictionary that reused a removed atom's slot, so a save with no edit reordered `sample.m4a`, `bgo_676934.m4a`, `bgo_701689.m4a`, `sample_replaygain.m4a` and `01 Horrible Theme.m4a` (it is now byte-identical). After a save over the source the object's tag takes the state a fresh read of the saved file has (its items, places, keys and key indexes, slots and metas), so the next save writes what that read's save writes in an iTunes `ilst`, a QuickTime `keys` meta, and a `moov/meta` beside `udta/meta` alike; the tag the object holds keeps its identity, whether the file read it, the caller assigned it or a view created it, and takes a new tag's state when the save wrote no `ilst`, so a reference to it stays live and a later edit through it is written. A save over the source is recognised as #179 recognises it, by what the file at `SourcePath` holds, under any spelling of the path or file system. A read where a second meta overrides n fields is linear in n again; it walked every field for each one. Before a save, or after a save to another path, a field cleared and set again still goes back where it was read
+- A WAV or AVI INFO list keeps its fields in the order they were read (#251). A field added after a removal took the removed field's place, so after a save over the source a save from the same object and a save from a fresh read of that file, given the same edit, wrote the fields in different orders. A changed value now stays in its field's place and a new field goes after the others, in the order added, as for APE items (#238)
+- An AVI INFO list with a declared `CSET` saves a change its code page cannot hold next to a value whose code page is a guess (#220). The save was refused, naming the guessed field: a `CSET` of 932, 1251 or another code page this library does not decode, or a byte the declared code page leaves undefined (0x81 in 1252; 0x80-0x9F under code page 0). Copying a title read from such a field into another field failed. Under a code page this library does not decode, the save now drops the `CSET` and keeps every unchanged field's bytes, writing the change by the no-`CSET` read rule: this library already reads such a list by that rule, so every value reads back as it read, and the Shift-JIS or cp1251 bytes stay for a reader that decodes them. Under 1252 or code page 0 the list becomes UTF-8 under a `CSET` of 65001, as it already did next to text decoded exactly, and the guessed value is written as the UTF-8 of the text the reader returned. Both hold on every save entry point. Without the `CSET`, ExifTool reads a UTF-8 change as Latin-1
+- An APE tag keeps its items in the order they were read (#238). A save sorted them by size, so a file that stores them in another order (`sample.ape`, `8bit.wv`, `sample.mpc`) changed on a save with no edit, and items of equal size were written in the order they were added, so after a removal a save from the object that saved before and a save from a fresh read of that save could order them differently. Now a save with no edit writes the items as they were; a changed value stays in its item's place, a value written under its key in place of its alias (`Album Artist` for `ALBUMARTIST`) takes the alias item's place, writing back the pictures or a custom field read moves nothing, and a new item goes after the others, in the order added. A key read twice keeps the first item's place and the last item's value, as before. This holds for Monkey's Audio, WavPack, Musepack and raw AAC. `sample_v8.mpc` declares 11 items and holds 8; its save with no edit now differs only in that count, which it writes as 8
+- An Ogg Vorbis, Opus or FLAC file whose Vorbis comment was removed (`OggVorbisFile.VorbisComment = null`, `OggOpusFile.VorbisComment = null`, `OggFlacFile.RemoveVorbisComment ()`) keeps a `Tag` (#236). It was null; it is now an empty view, as on a FLAC file: reading it creates nothing, its first write creates the comment (vendor `TagLibSharp2` in Vorbis and Opus, empty in Ogg FLAC, as `EnsureVorbisComment` creates it), and a write that leaves that comment empty removes it again, so the save writes what a save with no edit writes. A file that has its comment still returns that comment as its `Tag`. `Tag` is null after `Dispose`
+- `Picture.DetectMimeType` no longer types any RIFF data as WebP (#234). RIFF data is `image/webp` only when its form type at offset 8 is `WEBP` (RFC 9649 §2.4); WAV, AVI and other RIFF forms, and a RIFF header cut off before its form type, fall through to the file extension, or `application/octet-stream` without one. This reaches every picture typed from its bytes: `PictureFrame.FromBytes` and `FromFile`, `FlacPicture.FromBytes` and `FromFile`, `ApePicture`, the Audible cover, and a Matroska picture given no MIME type, whose save now fails with "is not an image/ media type" instead of writing WAV or AVI bytes as an `image/webp` attachment
- A Matroska save no longer grows quadratically with the pictures a file holds, and the Tags read is bounded (#247). Each picture now finds its own attachment by its content in an ordered index, the UIDs and names a save keeps are in ordered sets, and new pictures of one type are numbered in one pass, so no content a file holds, its attachments' data or UIDs included, can make a hash collide; setting the pictures back on a file with many image attachments took time quadratic in them. A read models at most 65,536 Tags and SimpleTags, as Chapters bounds its entries; the Tags past that are kept as their bytes and written back unread. A save that would write a Tag, a SimpleTag, a chapter or a chapter's value past what a read models (a new Tag or chapter in a file at the budget, or an edit that pushes the last one read, or only its title, language, times or flags, past it) now fails with a result saying so, and leaves the file and the object's edits as they were; it used to report success for a value no read could show. A chapter title edit at the budget counts too when the display was read without a language, as the save writes the default "eng". An edit that writes as many elements, such as a value replaced in place, is saved.
- A second save of a Matroska file from the same object writes a clear or an undone edit (#244). Read a file, set `Title`, save it over its source, then clear `Title` and save again: the file kept the title. A save left the `Tags` element as it was when the tags matched the ones the object first read, but after a save over the source the file holds the saved tags. The same held for every tag field, and for a chapter edit undone, or a chapter or edition added and then removed. A save now compares with the `Tags` and `Chapters` elements in the bytes it rewrites, on all six save entry points. A chapter read without a `ChapterUID`, or with 0, now reads `Uid` 0 and is written as it was (a read gave it a random UID, so no two reads of the file were the same); a save that writes the chapter changed gives it a new random UID, as RFC 9559 requires one that is not 0, and the chapter keeps it once a save over the source has written it. Setting `MatroskaChapter.Uid` to 0 now means the same, no UID yet, where it threw. After a save over its source the object holds the tags and chapters it wrote, as a read of the saved file would, so a later save writes what a fresh object would; a save that fails or goes elsewhere leaves it as it was. A UID the library draws for a new chapter, edition or picture attachment is now always 8 bytes wide, so the size of a save no longer depends on the draw. A save finds the empty Tags it keeps by their content in an ordered set, in O(log n) comparisons each whatever the Tags hold, with no hash a file could make collide.
- A Matroska file whose only title is a `TITLE` in a Tag with an empty Targets, such as the Matroska test suite's test1.mkv, no longer reads that title as its `Album` too (#221). A Tag with no `TargetTypeValue` is target 50 by default, but ffprobe, exiftool and MediaInfo show its `TITLE` as the title and no album, so `Album` now reads an explicit target-50 `TITLE`, then ffmpeg's `ALBUM`, and nothing else; clearing the album leaves that `TITLE`, and `AlbumSort` no longer reads the sort nested in it, which `TitleSort` now reads. Setting `Title` on such a file replaced nothing: it added a `TITLE` at target 30 and kept the old one, which exiftool, showing the first, still showed (and `Album` still read), with a segment title too, and when a save left out an Info/Title too long to rewrite in place. The new title now replaces the untargeted `TITLE` in place, in the language `Title` reads (a `TITLE` in another language stays), and the segment title with it; where a narrower `TITLE` or an explicit album `TITLE` could be the one a reader shows, the title is also written at target 30, with its languages and sort, so ffprobe, exiftool and MediaInfo show only the new title. An album edit keeps the title's sort.
diff --git a/src/TagLibSharp2/Aac/AacFile.cs b/src/TagLibSharp2/Aac/AacFile.cs
index 6d9ccb5e..072e6a2b 100644
--- a/src/TagLibSharp2/Aac/AacFile.cs
+++ b/src/TagLibSharp2/Aac/AacFile.cs
@@ -89,7 +89,24 @@ internal void MarkPicturesSkipped ()
///
/// Gets or sets the APEv2 tag after the stream. Set to null to remove it on save.
///
- public ApeTag? ApeTag { get; set; }
+ public ApeTag? ApeTag {
+ get => _apeTag;
+ set {
+ _apeTag = value;
+ _apeGone = false;
+ }
+ }
+
+ ApeTag? _apeTag;
+
+ // The APE tag the view shows: an emptied tag a save over the source did not write is held for a caller who holds it
+ // (review 2 B1) and written again once it holds a value, but the file holds no APE tag, so the view goes on as a fresh
+ // read of that file does, its first write creating an ID3v2 tag.
+ ApeTag? ViewApe => _apeGone && _apeTag is { StoresNothing: true } ? null : _apeTag;
+
+ // Whether the source holds no APE tag for the tag held: set by a save over the source that wrote none, cleared by one
+ // that wrote it, and by an assignment. A save elsewhere does not change it (contract suite round 3, R1).
+ bool _apeGone;
///
/// Gets or sets the ID3v1 tag in the last 128 bytes. Set to null to remove it on save.
@@ -134,7 +151,7 @@ internal void MarkPicturesSkipped ()
/// 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 => _disposed ? null : CombinedTag.Over (() => [Id3v2Tag, ApeTag, Id3v1Tag],
+ public Tag? Tag => _disposed ? null : CombinedTag.Over (() => [Id3v2Tag, ViewApe, Id3v1Tag],
_creation ??= new TagCreation (() => new Id3v2Tag (), tag => Id3v2Tag = (Id3v2Tag?)tag));
///
@@ -448,12 +465,14 @@ Written Plan (AacTailSource source)
// Lyrics3 belongs in front of ID3v1 and goes when that tag goes.
var keepsLyrics = Id3v1Tag is not null && tail.LyricsStart >= audioEnd && tail.Id3v1Start > tail.LyricsStart;
- var apeHeader = ApeTag is not null && ApeTag.HeaderForSave (ApeTag, _readApeTag, _readApeHeader, defaultHeader: true);
+ // An APE tag that holds nothing is not written (#258).
+ var ape = ApeTag is { StoresNothing: false } ? ApeTag : null;
+ var apeHeader = ape is not null && ApeTag.HeaderForSave (ape, _readApeTag, _readApeHeader, defaultHeader: true);
return new Written (
Id3v2Tag?.Render () ?? BinaryData.Empty,
audioStart,
audioEnd - audioStart,
- ApeTag?.RenderWithOptions (apeHeader) ?? BinaryData.Empty,
+ ape?.RenderWithOptions (apeHeader) ?? BinaryData.Empty,
apeHeader,
keepsLyrics ? tail.LyricsStart : 0,
keepsLyrics ? tail.Id3v1Start - tail.LyricsStart : 0,
@@ -475,7 +494,11 @@ FileWriteResult Adopt (FileWriteResult result, Written written, IFileSystem? fil
_audioStart = written.Id3v2.Length;
Id3v2Size = written.Id3v2.Length;
- _readApeTag = ApeTag;
+ // No empty APE tag was written (#258), so the file holds none: the tag the object holds, kept for a caller who
+ // holds it (review 2 B1), is then not a tag the file read, and a value set next is written with the layout of a
+ // tag this file did not read, as a fresh read's view writes it. A save elsewhere does not get here (round 3, R1).
+ _apeGone = _apeTag is { StoresNothing: true };
+ _readApeTag = _apeGone ? null : _apeTag;
_readApeHeader = written.ApeHeader;
Source.Rewrote (length);
return result;
diff --git a/src/TagLibSharp2/Aiff/AiffFile.cs b/src/TagLibSharp2/Aiff/AiffFile.cs
index 6ac72bbc..51b4eeb9 100644
--- a/src/TagLibSharp2/Aiff/AiffFile.cs
+++ b/src/TagLibSharp2/Aiff/AiffFile.cs
@@ -104,9 +104,21 @@ internal void MarkPicturesSkipped ()
///
public Id3v2Tag? Id3v2Tag {
get => _id3;
- set => _id3 = value;
+ set {
+ _id3 = value;
+ _id3Gone = false;
+ }
}
+ // The ID3 tag the view shows: an emptied tag a save over the source did not write is held for a caller who holds it
+ // (review 2 B1) and written again once it holds a value, but the file holds no ID3 chunk, so the view goes on as a
+ // fresh read of that file does, its first write creating a tag.
+ internal Id3v2Tag? ViewId3 => _id3Gone && _id3 is { IsEmpty: true } ? null : _id3;
+
+ // Whether the source holds no ID3 chunk for the tag held: set by a save over the source that wrote none, cleared by
+ // one that wrote it, and by an assignment. A save elsewhere leaves it as it was (contract suite round 3).
+ bool _id3Gone;
+
///
/// Gets the combined metadata view.
///
@@ -724,12 +736,38 @@ static bool HasText (string[]? value)
internal Id3v2Tag EnsureId3 ()
{
- Id3Creation.BeforeWrite (() => [Id3v2Tag]);
+ Id3Creation.BeforeWrite (() => [ViewId3]);
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);
+ internal TagCreation Id3Creation => _id3Creation ??= new TagCreation (() => TakeGoneId3 () ?? new Id3v2Tag (), StoreCreatedId3);
+
+ // The ID3 tag a view write creates on a file that holds none: the hidden tag the object kept, when there is one, so a
+ // caller who holds it still holds the file's tag (review 3 B1). A save over the source already made it a new tag
+ // (ResetToNew), so it is what a fresh read's view creates.
+ Id3v2Tag? TakeGoneId3 ()
+ {
+ if (!_id3Gone || _id3 is not { IsEmpty: true } kept)
+ return null;
+ kept.ResetToNew ();
+ return kept;
+ }
+
+ // A view write that leaves the tag it created empty removes it (TagCreation); the hidden tag the object kept is hidden
+ // again instead, as the file still holds no ID3 chunk.
+ void StoreCreatedId3 (Tag? tag)
+ {
+ if (tag is null && _id3 is { IsEmpty: true } && _id3Reused) {
+ _id3Gone = true;
+ return;
+ }
+
+ _id3Reused = tag is not null && ReferenceEquals (tag, _id3) && _id3Gone;
+ Id3v2Tag = (Id3v2Tag?)tag;
+ }
+
+ bool _id3Reused;
TagCreation? _id3Creation;
@@ -983,14 +1021,34 @@ public FileWriteResult SaveToFile (string path, IFileSystem? fileSystem = null)
if (SaveRefusal () is { } refused)
return refused;
if (_skipped.Count == 0)
- return SaveLoaded (path, fileSystem);
+ return SettleEmptyId3 (SaveLoaded (path, fileSystem), path, fileSystem);
- return SaveFromSource (path, fileSystem, default);
+ return SettleEmptyId3 (SaveFromSource (path, fileSystem, default), path, fileSystem);
} catch (Id3v2TagTooLargeException tooLarge) {
return FileWriteResult.Failure (tooLarge.Message);
}
}
+ // A save writes no empty ID3 chunk. After a successful one over the source the file holds none, and the view goes on
+ // as a fresh read's (ViewId3); the tag itself stays attached. After a save elsewhere the object still describes its
+ // source, which holds the chunk (#235, review 1; contract suite round 3).
+ FileWriteResult SettleEmptyId3 (FileWriteResult result, string path, IFileSystem? fileSystem)
+ {
+ if (result.IsSuccess && (_id3 is { IsEmpty: true } || _id3Gone)
+ && SavedOverSource.HoldsFile (SourcePath, _sourceFileSystem, path, fileSystem ?? _sourceFileSystem)) {
+ _id3Gone = _id3 is { IsEmpty: true };
+ // The tag kept is now the one a view creates on that file, so its next value is written as a fresh read's
+ // would be (review 3 B1).
+ if (_id3Gone)
+ _id3!.ResetToNew ();
+ }
+
+ return result;
+ }
+
+ async Task SettleEmptyId3 (Task save, string path, IFileSystem? fileSystem) =>
+ SettleEmptyId3 (await save.ConfigureAwait (false), path, fileSystem);
+
FileWriteResult SaveLoaded (string path, IFileSystem? fileSystem)
{
var fs = fileSystem ?? _sourceFileSystem;
@@ -1092,10 +1150,10 @@ public Task SaveToFileAsync (
if (SaveRefusal () is { } refused)
return Task.FromResult (refused);
if (_skipped.Count == 0)
- return SaveLoadedAsync (path, fileSystem, cancellationToken);
+ return SettleEmptyId3 (SaveLoadedAsync (path, fileSystem, cancellationToken), path, fileSystem);
// "Was not loaded" and a short source are decided before the token, matching the sync save.
- return Task.FromResult (SaveFromSource (path, fileSystem, cancellationToken));
+ return Task.FromResult (SettleEmptyId3 (SaveFromSource (path, fileSystem, cancellationToken), path, fileSystem));
} catch (Id3v2TagTooLargeException tooLarge) {
return Task.FromResult (FileWriteResult.Failure (tooLarge.Message));
}
@@ -1321,6 +1379,33 @@ void WritePlanned (Stream output, Stream source, List chunks, long ch
}
}
+ ///
+ /// Saves the AIFF file back to its source path.
+ ///
+ ///
+ /// This convenience method saves the file back to the path it was read from, through the file system it was read
+ /// with unless is given, as does.
+ /// Requires that the file was read using or
+ /// .
+ ///
+ /// Optional file system abstraction.
+ /// The write result.
+ public FileWriteResult SaveToFile (IFileSystem? fileSystem = null)
+ {
+ // A tag a save renders that is too large for its size field fails the save, never throws (#275).
+ try {
+ if (PictureSkip.Refuse (this, Id3v2Tag) is { } denied)
+ return denied;
+ if (string.IsNullOrEmpty (SourcePath))
+ return FileWriteResult.Failure ("No source path available. File was not read from disk.");
+
+ var fs = fileSystem ?? _sourceFileSystem;
+ return SaveToFile (SourcePath!, fs);
+ } catch (Id3v2TagTooLargeException tooLarge) {
+ return FileWriteResult.Failure (tooLarge.Message);
+ }
+ }
+
///
/// Saves the AIFF file back to its source path asynchronously.
///
diff --git a/src/TagLibSharp2/Aiff/AiffTag.cs b/src/TagLibSharp2/Aiff/AiffTag.cs
index f7d087f4..466593b0 100644
--- a/src/TagLibSharp2/Aiff/AiffTag.cs
+++ b/src/TagLibSharp2/Aiff/AiffTag.cs
@@ -532,7 +532,7 @@ public override bool RemoveCustomField (string name)
return removed;
}
- Id3v2Tag? Id3 => _file.Id3v2Tag;
+ Id3v2Tag? Id3 => _file.ViewId3;
///
///
diff --git a/src/TagLibSharp2/Ape/ApeTag.cs b/src/TagLibSharp2/Ape/ApeTag.cs
index 03d621a0..de488ad1 100644
--- a/src/TagLibSharp2/Ape/ApeTag.cs
+++ b/src/TagLibSharp2/Ape/ApeTag.cs
@@ -81,7 +81,8 @@ public override bool Equals (object? obj) =>
///
public sealed class ApeTag : Tag
{
- private readonly Dictionary _items;
+ // The items in the order a save writes them: as read, a replaced item in its place, a new one last (#238).
+ private readonly OrderedMap _items;
// Whether the tag was read with a header; null for a tag created here. The header is optional at the end of a
// file (APEv2: "must have at least a footer"), so a save writes the tag back the way it was read.
@@ -157,13 +158,13 @@ private static class Keys
///
public ApeTag ()
{
- _items = new Dictionary (StringComparer.OrdinalIgnoreCase);
+ _items = new OrderedMap (StringComparer.OrdinalIgnoreCase);
}
///
/// Creates an APE tag with the specified items, read with or without a header.
///
- private ApeTag (Dictionary items, bool readWithHeader)
+ private ApeTag (OrderedMap items, bool readWithHeader)
{
_items = items;
_readWithHeader = readWithHeader;
@@ -835,13 +836,7 @@ internal static bool IsPictureItem (string key, ApeItemType type) =>
/// Removes every item would return, and nothing else.
internal void RemovePictureItems ()
{
- var keys = new List ();
- foreach (var kvp in _items) {
- if (IsPictureItem (kvp.Value))
- keys.Add (kvp.Key);
- }
-
- foreach (var key in keys)
+ foreach (var key in _items.KeysWhere (static (_, item) => IsPictureItem (item)))
_items.Remove (key);
}
@@ -859,34 +854,32 @@ public override IPicture[] Pictures {
pictures.Add (ApePicture.FromBinaryData (Keys.CoverArtBack, back.BinaryValue!));
// Check for other cover art keys
- foreach (var kvp in _items) {
- if (IsPictureItem (kvp.Value) &&
- !string.Equals (kvp.Key, Keys.CoverArtFront, StringComparison.OrdinalIgnoreCase) &&
- !string.Equals (kvp.Key, Keys.CoverArtBack, StringComparison.OrdinalIgnoreCase)) {
- pictures.Add (ApePicture.FromBinaryData (kvp.Key, kvp.Value.BinaryValue!));
+ foreach (var (key, item) in _items.InOrder ()) {
+ if (IsPictureItem (item) &&
+ !string.Equals (key, Keys.CoverArtFront, StringComparison.OrdinalIgnoreCase) &&
+ !string.Equals (key, Keys.CoverArtBack, StringComparison.OrdinalIgnoreCase)) {
+ pictures.Add (ApePicture.FromBinaryData (key, item.BinaryValue!));
}
}
return [.. pictures];
}
set {
- // Remove existing cover art
- var keysToRemove = _items.Keys
- .Where (k => k.StartsWith ("Cover Art", StringComparison.OrdinalIgnoreCase))
- .ToList ();
- foreach (var key in keysToRemove)
- _items.Remove (key);
-
- // Add new pictures
- if (value is null || value.Length == 0)
- return;
-
- foreach (var pic in value) {
+ // Every "Cover Art" item goes, text and locator items too, but a picture whose key was there takes that
+ // item's place, so writing back the pictures read moves nothing (#238).
+ var pictures = new List<(string Key, ApeTagItem Item)> ();
+ var kept = new HashSet (StringComparer.OrdinalIgnoreCase);
+ foreach (var pic in value ?? []) {
var apePic = ApePicture.FromPicture (pic);
var key = apePic.GetKey ();
- var data = apePic.PictureData.ToArray ();
- SetBinaryItem (key, apePic.Filename, data);
+ pictures.Add ((key, ApeTagItem.CreateBinary (key, apePic.Filename, apePic.PictureData.ToArray ())));
+ kept.Add (key);
}
+
+ foreach (var key in _items.KeysWhere ((key, _) => key.StartsWith ("Cover Art", StringComparison.OrdinalIgnoreCase) && !kept.Contains (key)))
+ _items.Remove (key);
+ foreach (var (key, item) in pictures)
+ _items.Set (key, item);
}
}
#pragma warning restore CA1819
@@ -904,7 +897,7 @@ public override IPicture[] Pictures {
///
public void SetValue (string key, string value)
{
- _items[key] = ApeTagItem.CreateText (key, value);
+ _items.Set (key, ApeTagItem.CreateText (key, value));
}
///
@@ -977,24 +970,13 @@ string[] GetTextList (string key)
///
void SetTextList (string key, string[]? values, string? alias = null)
{
- if (alias is not null)
- _items.Remove (alias);
-
- if (values is null || values.Length == 0) {
- _items.Remove (key);
- return;
- }
-
- var kept = new List (values.Length);
- for (var i = 0; i < values.Length; i++) {
- if (!string.IsNullOrEmpty (values[i]))
- kept.Add (values[i]);
+ var kept = new List (values?.Length ?? 0);
+ foreach (var value in values ?? []) {
+ if (!string.IsNullOrEmpty (value))
+ kept.Add (value);
}
- if (kept.Count == 0)
- _items.Remove (key);
- else
- SetValue (key, string.Join ("\0", kept));
+ SetOrRemove (key, kept.Count == 0 ? null : string.Join ("\0", kept), alias);
}
///
@@ -1010,7 +992,7 @@ void SetTextList (string key, string[]? values, string? alias = null)
///
public void SetBinaryItem (string key, string filename, byte[] data)
{
- _items[key] = ApeTagItem.CreateBinary (key, filename, data);
+ _items.Set (key, ApeTagItem.CreateBinary (key, filename, data));
}
///
@@ -1067,9 +1049,11 @@ public override bool SetCustomField (string name, params string[] values)
if (!IsCustomFieldKey (name) || !CustomFieldValues.TryNormalize (values, out var kept))
return false;
- _items.Remove (name);
+ // The item takes the place of the one it replaces, whatever the case of its key.
if (kept.Count > 0)
- _items[name] = ApeTagItem.CreateText (name, string.Join ("\0", kept));
+ _items.Set (name, ApeTagItem.CreateText (name, string.Join ("\0", kept)));
+ else
+ _items.Remove (name);
return true;
}
@@ -1087,13 +1071,19 @@ static bool IsCustomFieldKey (string name) =>
ApeTagItem.IsValidKey (name) &&
!name.StartsWith ("Cover Art", StringComparison.OrdinalIgnoreCase);
- private void SetOrRemove (string key, string? value, string? alias = null)
+ ///
+ /// Stores as the text item , or removes that item when it is null or
+ /// empty. is removed either way; a value stored when only the alias item was there takes
+ /// its place.
+ ///
+ void SetOrRemove (string key, string? value, string? alias = null)
{
- if (alias is not null)
- _items.Remove (alias);
-
if (string.IsNullOrEmpty (value)) {
+ if (alias is not null)
+ _items.Remove (alias);
_items.Remove (key);
+ } else if (alias is not null) {
+ _items.Set (key, ApeTagItem.CreateText (key, value!), alias);
} else {
SetValue (key, value!);
}
@@ -1147,9 +1137,7 @@ internal static ApeTagParseResult Parse (ReadOnlySpan data, int floor)
// Do not size the dictionary from ItemCount. A count that fits the 11-byte minimum
// can still allocate more than a megabyte; 0xFF payloads fail in the item parser either way.
- var items = new Dictionary (
- (int)Math.Min (footer.ItemCount, 256u),
- StringComparer.OrdinalIgnoreCase);
+ var items = new OrderedMap (StringComparer.OrdinalIgnoreCase, (int)Math.Min (footer.ItemCount, 256u));
var itemsData = data.Slice (itemsStart, itemsSize);
var offset = 0;
@@ -1162,7 +1150,8 @@ internal static ApeTagParseResult Parse (ReadOnlySpan data, int floor)
return ApeTagParseResult.Failure (itemResult.Error!);
}
- items[itemResult.Item!.Key] = itemResult.Item;
+ // A key read again (APEv2 allows one) keeps the first item's place and takes the last item's value.
+ items.Set (itemResult.Item!.Key, itemResult.Item);
offset += itemResult.BytesConsumed;
itemsParsed++;
}
@@ -1212,13 +1201,13 @@ internal static bool MoreItems (long offset, long length, int parsed, uint count
public override BinaryData Render () => RenderWithOptions (_readWithHeader ?? false);
///
- /// The bytes a save writes for , or none when it is null, in a file whose read produced
+ /// The bytes a save writes for , or none when it is null or holds no item (#258), in a file whose read produced
/// . That tag keeps the layout it was read with, so a save with no edit reproduces it.
/// Any other tag, one created here or one parsed from other bytes and assigned, gets
/// : the carrier's layout for a tag it did not read.
///
internal static BinaryData RenderForSave (ApeTag? tag, ApeTag? readTag, bool defaultHeader) =>
- tag?.RenderWithOptions (HeaderForSave (tag, readTag, null, defaultHeader)) ?? BinaryData.Empty;
+ tag is null || tag.StoresNothing ? BinaryData.Empty : tag.RenderWithOptions (HeaderForSave (tag, readTag, null, defaultHeader));
///
/// Whether a save writes with a header (see ).
@@ -1234,10 +1223,10 @@ internal static bool HeaderForSave (ApeTag tag, ApeTag? readTag, bool? readHeade
///
public BinaryData RenderWithOptions (bool includeHeader = false)
{
- // Render items (optionally sorted by size per spec recommendation)
- var renderedItems = _items.Values
- .Select (item => item.Render ())
- .OrderBy (data => data.Length)
+ // The items in the order they were read, new ones last (#238). APEv2 only recommends sorting by size, and a
+ // sort would change a file that stores them in another order on a save with no edit.
+ var renderedItems = _items.InOrder ()
+ .Select (entry => entry.Value.Render ())
.ToList ();
var itemsSize = renderedItems.Sum (data => data.Length);
diff --git a/src/TagLibSharp2/Ape/MonkeysAudioFile.cs b/src/TagLibSharp2/Ape/MonkeysAudioFile.cs
index e5cf7487..b9432f8c 100644
--- a/src/TagLibSharp2/Ape/MonkeysAudioFile.cs
+++ b/src/TagLibSharp2/Ape/MonkeysAudioFile.cs
@@ -539,6 +539,20 @@ private void ParseApeTag (ReadOnlySpan data, int tagFloor)
byte[] ApeTagBytes () => ApeTag.RenderForSave (ApeTag, _readApeTag, defaultHeader: false).ToArray ();
+ // A save writes no APE tag that holds nothing (#258). After a successful one over the source the file holds no tag,
+ // so the tag the object holds, kept for a caller who holds it (review 2 B1), is no longer the tag read: a value set
+ // next is written with the layout of a tag this file did not read (footer only), as a fresh read's view writes it.
+ // After a save elsewhere the object still describes its source, whose tag it emptied, and keeps the read layout
+ // (contract suite round 3, R1).
+ FileWriteResult Saved (FileWriteResult result, string path, IFileSystem? fileSystem)
+ {
+ if (result.IsSuccess && ApeTag is { StoresNothing: true } && _readApeTag is not null
+ && SavedOverSource.HoldsFile (SourcePath, _sourceFileSystem ?? fileSystem, path, fileSystem))
+ _readApeTag = null;
+
+ return Source.Saved (result);
+ }
+
///
/// Ensures an APE tag exists, creating one if necessary.
///
@@ -627,7 +641,7 @@ public FileWriteResult SaveToFile (string path, ReadOnlySpan originalData,
var fs = fileSystem ?? _sourceFileSystem ?? DefaultFileSystem.Instance;
var rendered = Render (originalData);
- return Source.Saved (AtomicFileWriter.Write (path, rendered, fs));
+ return Saved (AtomicFileWriter.Write (path, rendered, fs), path, fs);
}
///
@@ -649,7 +663,7 @@ public FileWriteResult SaveToFile (string path, IFileSystem? fileSystem = null)
return FileWriteResult.Failure ("No source path available. File was not read from disk.");
var tag = ApeTagBytes ();
- return Source.Saved (ApeTagLocation.WriteFromSource (SourcePath, path, fs, tag));
+ return Saved (ApeTagLocation.WriteFromSource (SourcePath, path, fs, tag), path, fs);
}
///
@@ -690,7 +704,7 @@ public async Task SaveToFileAsync (
var fs = fileSystem ?? _sourceFileSystem ?? DefaultFileSystem.Instance;
var rendered = Render (originalData.Span);
- return Source.Saved (await AtomicFileWriter.WriteAsync (path, rendered, fs, cancellationToken).ConfigureAwait (false));
+ return Saved (await AtomicFileWriter.WriteAsync (path, rendered, fs, cancellationToken).ConfigureAwait (false), path, fs);
}
///
@@ -716,7 +730,7 @@ public Task SaveToFileAsync (
return Task.FromResult (FileWriteResult.Failure ("No source path available. File was not read from disk."));
var tag = ApeTagBytes ();
- return Task.FromResult (Source.Saved (ApeTagLocation.WriteFromSource (SourcePath, path, fs, tag, cancellationToken)));
+ return Task.FromResult (Saved (ApeTagLocation.WriteFromSource (SourcePath, path, fs, tag, cancellationToken), path, fs));
}
///
diff --git a/src/TagLibSharp2/Asf/AsfFile.cs b/src/TagLibSharp2/Asf/AsfFile.cs
index 3765a44e..81ebdf93 100644
--- a/src/TagLibSharp2/Asf/AsfFile.cs
+++ b/src/TagLibSharp2/Asf/AsfFile.cs
@@ -42,6 +42,23 @@ internal void MarkPicturesSkipped ()
///
public AudioProperties Properties { get; }
+ ///
+ /// Gets the File Properties Object the header holds, or null when it has none (ASF Specification 01.20.03, File
+ /// Properties Object).
+ ///
+ ///
+ /// takes its duration from this object, so
+ /// tells why a file still being written reads a duration of 0. A header with more than one (the specification allows
+ /// one) gives the last. A save copies the object and writes the length it wrote as its File Size when the length
+ /// changed (#253). After a successful save over the source this is the object that save wrote, as a fresh read of
+ /// the file shows it; after a save to another path it is still the source's, as the object still describes the source.
+ ///
+ public AsfFileProperties? FileProperties { get; private set; }
+
+ // The length of the file the object describes: -1 until a save over the source, when it is the length that save
+ // wrote (#253); until then it is the length the read saw. A save elsewhere leaves the source described.
+ long _describedLength = -1;
+
///
/// Gets the source file path if the file was read from disk.
///
@@ -67,10 +84,11 @@ internal void MarkPicturesSkipped ()
///
public MediaFormat Format => MediaFormat.Asf;
- AsfFile (AsfTag tag, AudioProperties audioProperties)
+ AsfFile (AsfTag tag, AudioProperties audioProperties, AsfFileProperties? fileProperties)
{
Tag = tag;
Properties = audioProperties;
+ FileProperties = fileProperties;
}
// ═══════════════════════════════════════════════════════════════
@@ -194,7 +212,7 @@ static AsfFileReadResult Parse (ReadOnlySpan data)
// Create audio properties
var audioProps = CreateAudioProperties (fileProps, streamProps);
- var file = new AsfFile (tag, audioProps);
+ var file = new AsfFile (tag, audioProps, fileProps);
file._originalData = data.ToArray ();
return AsfFileReadResult.Success (file);
}
@@ -508,8 +526,16 @@ static AudioProperties CreateAudioProperties (AsfFileProperties? fileProps, AsfS
/// The original file data to preserve audio content from.
///
/// The rendered file bytes, or empty when the header's objects do not fill it whole (#200).
- public byte[] Render (ReadOnlySpan originalData)
+ public byte[] Render (ReadOnlySpan originalData) => Render (originalData, out _);
+
+ byte[] Render (ReadOnlySpan originalData, out ulong? fileSize) => Render (originalData, out fileSize, out _);
+
+ // headerLength is the length of the rebuilt header at the front of the bytes returned: 0 when the header did not parse.
+ byte[] Render (ReadOnlySpan originalData, out ulong? fileSize, out int headerLength)
{
+ fileSize = null;
+ headerLength = 0;
+
// Parse original header to find structure
var headerInfo = ParseHeaderStructure (originalData);
if (!headerInfo.IsValid)
@@ -517,7 +543,8 @@ public byte[] Render (ReadOnlySpan originalData)
if (headerInfo.IsRefused)
return [];
- var newHeader = RenderRebuiltHeader (headerInfo);
+ var newHeader = RenderRebuiltHeader (headerInfo, originalData.Length, out fileSize);
+ headerLength = newHeader.Length;
// Combine header with data object and remainder
using var ms = new MemoryStream ();
@@ -527,17 +554,44 @@ public byte[] Render (ReadOnlySpan originalData)
return ms.ToArray ();
}
- // Same child objects Render writes. The bytes after HeaderEndOffset stay in the source file.
- byte[] RenderRebuiltHeader (HeaderParseInfo headerInfo)
+ // Same child objects Render writes. The bytes after HeaderEndOffset stay in the source file, which is
+ // sourceLength bytes long. fileSize is the File Size written, or null when the header has no File Properties Object.
+ byte[] RenderRebuiltHeader (HeaderParseInfo headerInfo, long sourceLength, out ulong? fileSize)
{
var childObjects = new List ();
- // Copy preserved objects (File Properties, Stream Properties, etc.). The Header Extension Object is
- // rebuilt only when a write changed its Metadata or Metadata Library records.
+ // Every object goes back in the order it was read (#257); the specification sets no order. The Content
+ // Description and Extended Content Description Objects are rendered from the tag where the first of each was,
+ // and a later copy of either (the specification allows one) is dropped. The Header Extension Object is rebuilt
+ // only when a write changed its Metadata or Metadata Library records.
+ var contentDesc = Tag.ContentDescription;
+ var hasDescription = !string.IsNullOrEmpty (contentDesc.Title) ||
+ !string.IsNullOrEmpty (contentDesc.Author) ||
+ !string.IsNullOrEmpty (contentDesc.Copyright) ||
+ !string.IsNullOrEmpty (contentDesc.Description) ||
+ !string.IsNullOrEmpty (contentDesc.Rating);
+ var extendedDesc = Tag.ExtendedContentDescription;
+ var hasExtended = extendedDesc.Descriptors.Count > 0;
var wroteExtension = false;
- foreach (var obj in headerInfo.PreservedObjects) {
- var isExtension = AsfGuid.Parse (obj).Value == AsfGuids.HeaderExtensionObject;
- if (isExtension && Tag.HeaderExtensionChanged && !wroteExtension) {
+ var placedDescription = false;
+ var placedExtended = false;
+ foreach (var obj in headerInfo.Objects) {
+ var guid = AsfGuid.Parse (obj).Value;
+ if (guid == AsfGuids.ContentDescriptionObject) {
+ if (!placedDescription && hasDescription)
+ childObjects.Add (RenderContentDescriptionObject (contentDesc));
+ placedDescription = true;
+ continue;
+ }
+
+ if (guid == AsfGuids.ExtendedContentDescriptionObject) {
+ if (!placedExtended && hasExtended)
+ childObjects.Add (RenderExtendedContentDescriptionObject (extendedDesc));
+ placedExtended = true;
+ continue;
+ }
+
+ if (guid == AsfGuids.HeaderExtensionObject && Tag.HeaderExtensionChanged && !wroteExtension) {
childObjects.Add (RenderHeaderExtension (obj, Tag));
wroteExtension = true;
continue;
@@ -547,22 +601,58 @@ byte[] RenderRebuiltHeader (HeaderParseInfo headerInfo)
if (!wroteExtension && Tag.HeaderExtensionChanged && Tag.LibraryRecords is { Count: > 0 })
childObjects.Add (RenderHeaderExtension (null, Tag));
- // Add Content Description if tag has content
- var contentDesc = Tag.ContentDescription;
- if (!string.IsNullOrEmpty (contentDesc.Title) ||
- !string.IsNullOrEmpty (contentDesc.Author) ||
- !string.IsNullOrEmpty (contentDesc.Copyright) ||
- !string.IsNullOrEmpty (contentDesc.Description) ||
- !string.IsNullOrEmpty (contentDesc.Rating)) {
+ // A description object the file did not have goes after the others.
+ if (!placedDescription && hasDescription)
childObjects.Add (RenderContentDescriptionObject (contentDesc));
+ if (!placedExtended && hasExtended)
+ childObjects.Add (RenderExtendedContentDescriptionObject (extendedDesc));
+
+ var header = RenderHeaderObject ([.. childObjects]);
+ var writtenLength = sourceLength - headerInfo.HeaderEndOffset + header.Length;
+ fileSize = FileProperties is { } properties
+ ? AsfFileProperties.SavedFileSize (properties.FileSize, properties.Flags,
+ _describedLength >= 0 ? _describedLength : Source.First ?? sourceLength, writtenLength)
+ : null;
+ if (fileSize is { } size)
+ PatchFileSize (header, size);
+ return header;
+ }
+
+ // Writes fileSize into the File Properties Object the read takes (#253): the last of the rebuilt header that holds a
+ // whole one. The value comes from the object, not from the source bytes, so a save writes the same File Size whichever
+ // file the payload is copied from (the one read, or one saved since). The specification allows one File Properties
+ // Object; any other one a header holds stays as stored, so a save with no edit is byte for byte (review 2). The rest
+ // of the header holds no length or offset that moves: the Header Object's size and count are written fresh, and
+ // nothing records where the Data Object starts.
+ static void PatchFileSize (byte[] header, ulong fileSize)
+ {
+ var offset = 30;
+ var last = -1;
+ while (MoreObjects (offset, header.Length)) {
+ var size = (int)BinaryPrimitives.ReadUInt64LittleEndian (header.AsSpan (offset + 16));
+ if (AsfGuid.Parse (header.AsSpan (offset)).Value == AsfGuids.FilePropertiesObject && size >= 24 + AsfFileProperties.MinContentSize)
+ last = offset;
+
+ offset += size;
}
- // Add Extended Content Description if tag has extended content
- var extendedDesc = Tag.ExtendedContentDescription;
- if (extendedDesc.Descriptors.Count > 0)
- childObjects.Add (RenderExtendedContentDescriptionObject (extendedDesc));
+ if (last >= 0)
+ BinaryPrimitives.WriteUInt64LittleEndian (header.AsSpan (last + 24 + AsfFileProperties.FileSizeOffset, 8), fileSize);
+ }
- return RenderHeaderObject ([.. childObjects]);
+ // After a successful save over the source the object describes the file it wrote: its length, and the File Properties
+ // that save wrote. A save elsewhere leaves the source described, as a fresh read of it given the same edits describes
+ // it (contract suite round 3, R3); a failed save changes neither. Either way the payload of a later span save may come
+ // from any file the object saved (SourceLength).
+ FileWriteResult Wrote (FileWriteResult result, ulong? fileSize, long writtenLength, ReadOnlyMemory header, IFileSystem? fileSystem)
+ {
+ if (result.IsSuccess && SavedOverSource.Holds (SourcePath, _sourceFileSystem ?? fileSystem, writtenLength, new WrittenBytes (0, header))) {
+ _describedLength = writtenLength;
+ if (fileSize is { } size && FileProperties is { } properties)
+ FileProperties = properties.WithFileSize (size);
+ }
+
+ return Source.Saved (result);
}
static byte[] RenderHeaderObject (byte[][] childObjects)
@@ -631,7 +721,8 @@ readonly struct HeaderParseInfo
{
public bool IsValid { get; }
public int HeaderEndOffset { get; }
- public List PreservedObjects { get; }
+ /// Every object of the header, in the order read.
+ public List Objects { get; }
/// The header parsed, but its objects do not fill it whole: a save would drop bytes, and fails.
public bool IsRefused { get; }
@@ -640,7 +731,7 @@ public HeaderParseInfo (bool isValid, int headerEndOffset, List preserve
{
IsValid = isValid;
HeaderEndOffset = headerEndOffset;
- PreservedObjects = preservedObjects;
+ Objects = preservedObjects;
IsRefused = isRefused;
}
@@ -680,8 +771,6 @@ static HeaderParseInfo ParseHeaderStructure (ReadOnlySpan data)
if (!guidResult.IsSuccess)
return HeaderParseInfo.Refused ();
- var objectGuid = guidResult.Value;
-
var objectSize = BinaryPrimitives.ReadUInt64LittleEndian (data[(offset + 16)..]);
if (objectSize < 24 || objectSize > int.MaxValue)
return HeaderParseInfo.Refused ();
@@ -690,12 +779,8 @@ static HeaderParseInfo ParseHeaderStructure (ReadOnlySpan data)
if (offset + objSize > headerEnd)
return HeaderParseInfo.Refused ();
- // Preserve all objects except Content Description and Extended Content Description
- // (those will be re-rendered from the Tag)
- if (objectGuid != AsfGuids.ContentDescriptionObject &&
- objectGuid != AsfGuids.ExtendedContentDescriptionObject) {
- preservedObjects.Add (data.Slice (offset, objSize).ToArray ());
- }
+ // Every object is kept in order; the description objects are rendered from the tag in their place.
+ preservedObjects.Add (data.Slice (offset, objSize).ToArray ());
offset += objSize;
}
@@ -726,10 +811,10 @@ public FileWriteResult SaveToFile (string path, ReadOnlySpan originalData,
return mismatch;
var fs = fileSystem ?? _sourceFileSystem ?? DefaultFileSystem.Instance;
- var rendered = Render (originalData);
+ var rendered = Render (originalData, out var fileSize, out var headerLength);
if (rendered.Length == 0)
return FileWriteResult.Failure (HeaderNotWhole);
- return Source.Saved (AtomicFileWriter.Write (path, rendered, fs));
+ return Wrote (AtomicFileWriter.Write (path, rendered, fs), fileSize, rendered.Length, rendered.AsMemory (0, headerLength), fs);
}
///
@@ -752,7 +837,7 @@ public FileWriteResult SaveToFile (string path, IFileSystem? fileSystem = null)
if (SourcePath is not { Length: > 0 })
return FileWriteResult.Failure ("No source path available. Use SaveToFile(path) instead.");
- return Source.Saved (SaveFromSource (path, fs));
+ return SaveFromSource (path, fs);
}
// Same bytes as Render: rebuilt header, then every byte after the declared header size.
@@ -773,6 +858,7 @@ FileWriteResult SaveFromSource (string destinationPath, IFileSystem? fileSystem,
var opened = source!;
var fileLength = opened.Length;
byte[]? headerBytes = null;
+ ulong? fileSize = null;
long copyStart = 0;
var copyWhole = true;
if (fileLength >= 30) {
@@ -788,7 +874,7 @@ FileWriteResult SaveFromSource (string destinationPath, IFileSystem? fileSystem,
if (info.IsRefused)
return FileWriteResult.Failure (HeaderNotWhole);
if (info.IsValid) {
- headerBytes = RenderRebuiltHeader (info);
+ headerBytes = RenderRebuiltHeader (info, fileLength, out fileSize);
copyStart = info.HeaderEndOffset;
copyWhole = false;
}
@@ -809,7 +895,7 @@ FileWriteResult SaveFromSource (string destinationPath, IFileSystem? fileSystem,
StreamCopy.Copy (opened.Stream, output, tail, copyBuffer);
});
source = null;
- return written;
+ return Wrote (written, fileSize, (headerBytes?.Length ?? 0) + tail, headerBytes ?? ReadOnlyMemory.Empty, fileSystem);
} finally {
source?.Dispose ();
if (chunk is not null)
@@ -872,10 +958,10 @@ public async Task SaveToFileAsync (
return mismatch;
var fs = fileSystem ?? _sourceFileSystem ?? DefaultFileSystem.Instance;
- var rendered = Render (originalData.Span);
+ var rendered = Render (originalData.Span, out var fileSize, out var headerLength);
if (rendered.Length == 0)
return FileWriteResult.Failure (HeaderNotWhole);
- return Source.Saved (await AtomicFileWriter.WriteAsync (path, rendered, fs, cancellationToken).ConfigureAwait (false));
+ return Wrote (await AtomicFileWriter.WriteAsync (path, rendered, fs, cancellationToken).ConfigureAwait (false), fileSize, rendered.Length, rendered.AsMemory (0, headerLength), fs);
}
///
@@ -904,7 +990,7 @@ public Task SaveToFileAsync (
if (SourcePath is not { Length: > 0 })
return Task.FromResult (FileWriteResult.Failure ("No source path available. Use SaveToFileAsync(path) instead."));
- return Task.FromResult (Source.Saved (SaveFromSource (path, fs, cancellationToken)));
+ return Task.FromResult (SaveFromSource (path, fs, cancellationToken));
}
///
diff --git a/src/TagLibSharp2/Asf/AsfFileProperties.cs b/src/TagLibSharp2/Asf/AsfFileProperties.cs
index 39cc5d04..80f09eab 100644
--- a/src/TagLibSharp2/Asf/AsfFileProperties.cs
+++ b/src/TagLibSharp2/Asf/AsfFileProperties.cs
@@ -129,6 +129,29 @@ public TimeSpan Duration {
MaxBitrate = maxBitrate;
}
+ /// The offset of File Size in the object's content, after the File ID.
+ internal const int FileSizeOffset = 16;
+
+ /// The offset of Flags in the object's content.
+ internal const int FlagsOffset = 64;
+
+ /// This object with as its File Size, as a save that rewrote the field leaves it.
+ internal AsfFileProperties WithFileSize (ulong fileSize) =>
+ new (FileId, fileSize, CreationDateFiletime, DataPacketsCount, PlayDurationNs, SendDurationNs, PrerollMs, Flags,
+ MinPacketSize, MaxPacketSize, MaxBitrate);
+
+ ///
+ /// The File Size a save writes, given the one the object holds () and its
+ /// , when the file the object describes is bytes and the
+ /// save writes (#253). File Size is "the size, in bytes, of the entire file" (ASF
+ /// Specification 01.20.03, File Properties Object), so a save that changes the length writes the length it writes. A
+ /// save that keeps the length keeps the object's value, so a save with no edit leaves the field as it was, even where
+ /// another tagger left it wrong. Null while the Broadcast Flag is set: the specification calls the field invalid
+ /// then, and the save leaves the bytes as they are.
+ ///
+ internal static ulong? SavedFileSize (ulong stored, uint flags, long describedLength, long writtenLength) =>
+ (flags & 0x01) != 0 ? null : writtenLength == describedLength ? stored : (ulong)writtenLength;
+
///
/// Parses a File Properties Object from binary data.
///
diff --git a/src/TagLibSharp2/Core/OrderedMap.cs b/src/TagLibSharp2/Core/OrderedMap.cs
new file mode 100644
index 00000000..54d2c38e
--- /dev/null
+++ b/src/TagLibSharp2/Core/OrderedMap.cs
@@ -0,0 +1,126 @@
+// Copyright (c) 2025-2026 Stephen Shaw and contributors
+// Licensed under the MIT License. See LICENSE file in the project root for full license information.
+
+using System.Diagnostics.CodeAnalysis;
+
+namespace TagLibSharp2.Core;
+
+///
+/// Values by key in the order a save writes them: the order they were read in, a replaced value in the place of the
+/// value it replaces, and a new value after the others, in the order added. A tag whose format sets no order (APEv2
+/// items, #238) keeps the order it was read in, so a save from the object that saved before writes what a fresh read
+/// of that save writes, and a save with no edit writes the values as they were.
+///
+///
+/// A lookup, a replacement and a removal take a dictionary operation; sorts by place, so any
+/// number of edits and one render take O(n log n) in the values a file holds. The order comes from a counter, not from
+/// the keys, so no choice of keys changes it. The dictionary underneath hashes the keys as any string dictionary does.
+///
+/// How keys compare.
+/// The number of values to allocate room for.
+///
+/// Where new places come from. Maps that share one write their values in one order between them (an MP4 ilst's
+/// atoms and freeform fields, #252); a map given none has its own.
+///
+internal sealed class OrderedMap (IEqualityComparer comparer, int capacity = 0, Places? places = null)
+{
+ readonly Dictionary _entries = new (capacity, comparer);
+
+ // Places only grow, so a new value always goes after every value there is.
+ readonly Places _places = places ?? new Places ();
+
+ public int Count => _entries.Count;
+
+ public bool ContainsKey (string key) => _entries.ContainsKey (key);
+
+ public bool TryGetValue (string key, [MaybeNullWhen (false)] out TValue value)
+ {
+ if (_entries.TryGetValue (key, out var entry)) {
+ value = entry.Value;
+ return true;
+ }
+
+ value = default;
+ return false;
+ }
+
+ /// The value under and its place, when there is one.
+ public bool TryGetValue (string key, [MaybeNullWhen (false)] out TValue value, out long place)
+ {
+ if (_entries.TryGetValue (key, out var entry)) {
+ (value, place) = entry;
+ return true;
+ }
+
+ value = default;
+ place = -1;
+ return false;
+ }
+
+ /// Stores under : in the place of the value it replaces, else last.
+ public void Set (string key, TValue value) =>
+ _entries[key] = (value, _entries.TryGetValue (key, out var entry) ? entry.Place : _places.Next ());
+
+ ///
+ /// Removes and stores under : in the place of
+ /// the value it replaces, else in the alias's place, else last. A field read from its alias and written back under
+ /// its key keeps its place.
+ ///
+ public void Set (string key, TValue value, string alias)
+ {
+ if (!_entries.ContainsKey (key) && _entries.TryGetValue (alias, out var aliased)) {
+ _entries.Remove (alias);
+ _entries[key] = (value, aliased.Place);
+ return;
+ }
+
+ _entries.Remove (alias);
+ Set (key, value);
+ }
+
+ public bool Remove (string key) => _entries.Remove (key);
+
+ public void Clear () => _entries.Clear ();
+
+ /// The keys of the values selects, in place order.
+ public List KeysWhere (Func match)
+ {
+ var keys = new List ();
+ foreach (var (key, value) in InOrder ()) {
+ if (match (key, value))
+ keys.Add (key);
+ }
+
+ return keys;
+ }
+
+ /// Every value with the key it is stored under, in the order a save writes them.
+ public List<(string Key, TValue Value)> InOrder ()
+ {
+ var entries = Placed ();
+ var ordered = new List<(string, TValue)> (entries.Count);
+ foreach (var (key, value, _) in entries)
+ ordered.Add ((key, value));
+ return ordered;
+ }
+
+ /// Every value with its key and its place, in place order, to merge with another map's values.
+ public List<(string Key, TValue Value, long Place)> Placed ()
+ {
+ var entries = new List<(string Key, TValue Value, long Place)> (_entries.Count);
+ foreach (var pair in _entries)
+ entries.Add ((pair.Key, pair.Value.Value, pair.Value.Place));
+
+ // Places are unique, so the sort needs no tie-break and is the same however the dictionary enumerates.
+ entries.Sort (static (a, b) => a.Place.CompareTo (b.Place));
+ return entries;
+ }
+}
+
+/// The places gives new values; shared, they order several maps as one.
+internal sealed class Places
+{
+ long _next;
+
+ public long Next () => _next++;
+}
diff --git a/src/TagLibSharp2/Core/Picture.cs b/src/TagLibSharp2/Core/Picture.cs
index 16b24a3f..a7f22562 100644
--- a/src/TagLibSharp2/Core/Picture.cs
+++ b/src/TagLibSharp2/Core/Picture.cs
@@ -41,6 +41,10 @@ public abstract class Picture : IPicture
///
/// Detects the MIME type from image data by examining magic bytes.
///
+ ///
+ /// RIFF data is WebP only when its form type is WEBP; WAV, AVI or any other RIFF form falls through to the
+ /// extension of .
+ ///
/// The image data.
/// Optional file path to use extension as fallback.
/// The detected MIME type, or "application/octet-stream" if unknown.
@@ -61,8 +65,11 @@ public static string DetectMimeType (ReadOnlySpan data, string? filePath =
if (data.Length >= 2 && data[0] == 0x42 && data[1] == 0x4D)
return "image/bmp";
- if (data.Length >= 4 && data[0] == 0x52 && data[1] == 0x49 && data[2] == 0x46 && data[3] == 0x46)
- return "image/webp"; // RIFF header (WebP)
+ // "RIFF", the file size, then the form type "WEBP" (RFC 9649 §2.4). A RIFF of another form, such as WAVE or AVI,
+ // is not a WebP image.
+ if (data.Length >= 12 && data[0] == 0x52 && data[1] == 0x49 && data[2] == 0x46 && data[3] == 0x46 &&
+ data[8] == 0x57 && data[9] == 0x45 && data[10] == 0x42 && data[11] == 0x50)
+ return "image/webp";
// Fall back to file extension if provided
if (!string.IsNullOrEmpty (filePath)) {
diff --git a/src/TagLibSharp2/Core/SavedOverSource.cs b/src/TagLibSharp2/Core/SavedOverSource.cs
index f51e0fe5..80e96539 100644
--- a/src/TagLibSharp2/Core/SavedOverSource.cs
+++ b/src/TagLibSharp2/Core/SavedOverSource.cs
@@ -53,6 +53,81 @@ public static bool Holds (string? sourcePath, IFileSystem? fileSystem, long leng
}
}
+ ///
+ /// Whether the file at now holds exactly what the save wrote to :
+ /// as long, byte for byte. That is true after a save over the source under any spelling of its path, and false after
+ /// a save elsewhere, which leaves the source as it was, unless the source already held those bytes, when a fresh read
+ /// of either file is the same. A carrier asks it before it drops a tag a save emptied and did not write: after a save
+ /// elsewhere the object still describes its source, which holds that tag (contract suite round 3). A source or a
+ /// written file that cannot be read answers false. Both files are read in chunks, and only when the save could have
+ /// gone to an alias of the source: a save to the same full path on the same file system wrote over the source, and
+ /// answers true without a read (review 3). Another process that rewrites the source between the save and the compare
+ /// gets whatever answer its bytes give; a wrong false only keeps the object's earlier bookkeeping, as a save elsewhere
+ /// does.
+ ///
+ public static bool HoldsFile (string? sourcePath, IFileSystem? sourceFileSystem, string path, IFileSystem? fileSystem)
+ {
+ if (sourcePath is null)
+ return false;
+ if (SamePath (sourcePath, sourceFileSystem, path, fileSystem))
+ return true;
+
+ byte[]? left = null;
+ byte[]? right = null;
+ try {
+ using var source = (sourceFileSystem ?? DefaultFileSystem.Instance).OpenRead (sourcePath);
+ using var written = (fileSystem ?? DefaultFileSystem.Instance).OpenRead (path);
+ if (source.Length != written.Length)
+ return false;
+
+ left = StreamCopy.Rent ();
+ right = StreamCopy.Rent ();
+ var remaining = source.Length;
+ while (remaining > 0) {
+ var count = (int)Math.Min (left.Length, remaining);
+ if (!ReadAll (source, left, count) || !ReadAll (written, right, count)
+ || !left.AsSpan (0, count).SequenceEqual (right.AsSpan (0, count)))
+ return false;
+ remaining -= count;
+ }
+
+ return true;
+ } catch (Exception ex) when (IsReadBackFailure (ex)) {
+ return false;
+ } finally {
+ if (left is not null)
+ StreamCopy.Return (left);
+ if (right is not null)
+ StreamCopy.Return (right);
+ }
+ }
+
+ // The same full path, compared ordinally, on the same file system instance. A path that differs only by case, a link
+ // or another spelling the full path does not settle falls through to the compare.
+ static bool SamePath (string sourcePath, IFileSystem? sourceFileSystem, string path, IFileSystem? fileSystem)
+ {
+ if (!ReferenceEquals (sourceFileSystem ?? DefaultFileSystem.Instance, fileSystem ?? DefaultFileSystem.Instance))
+ return false;
+ try {
+ return string.Equals (Path.GetFullPath (sourcePath), Path.GetFullPath (path), StringComparison.Ordinal);
+ } catch (Exception ex) when (ex is ArgumentException or NotSupportedException or PathTooLongException or System.Security.SecurityException) {
+ return false;
+ }
+ }
+
+ static bool ReadAll (Stream stream, byte[] buffer, int count)
+ {
+ var done = 0;
+ while (done < count) {
+ var read = stream.Read (buffer, done, count - done);
+ if (read <= 0)
+ return false;
+ done += read;
+ }
+
+ return true;
+ }
+
///
/// The failures a read-back after a save can meet. The save has committed by then, so none of them turns its
/// success into a failure; the object keeps the offsets it had.
diff --git a/src/TagLibSharp2/Core/SourceLength.cs b/src/TagLibSharp2/Core/SourceLength.cs
index 0038bf82..3b04730a 100644
--- a/src/TagLibSharp2/Core/SourceLength.cs
+++ b/src/TagLibSharp2/Core/SourceLength.cs
@@ -61,6 +61,12 @@ public FileWriteResult Saved (FileWriteResult result)
public async Task Saved (Task save) =>
Saved (await save.ConfigureAwait (false));
+ ///
+ /// The length of the file the read saw, or of the file the object last saved over its source ();
+ /// null before a read recorded one.
+ ///
+ public long? First => _lengths.Count > 0 ? _lengths[0] : null;
+
/// Whether is the length of a file the object describes.
public bool Describes (long length) => _lengths.Contains (length);
diff --git a/src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.cs b/src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.cs
index a542dd8c..309b70eb 100644
--- a/src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.cs
+++ b/src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.cs
@@ -107,9 +107,21 @@ public sealed partial class Id3v2Tag : Tag
/// 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.
+ /// v2.2 PIC that cannot be parsed. A WAV, AIFF or AVI file that keeps this tag after a save over its source
+ /// wrote it empty makes it a new tag, as a view creates one: version 4 from then on.
///
- public int Version { get; }
+ public int Version { get; private set; }
+
+ ///
+ /// Makes this tag the one a view creates for a file that holds no ID3v2 tag (new Id3v2Tag ()): no frame, and
+ /// ID3v2.4. A file whose save over its source wrote no ID3v2 tag, as this one was empty, keeps this instance for a
+ /// caller who holds it (review 2 B1, review 3 B1), so its next value is written as a fresh read's view would write it.
+ ///
+ internal void ResetToNew ()
+ {
+ Clear ();
+ Version = (int)Id3v2Version.V24;
+ }
///
public override TagTypes TagType => TagTypes.Id3v2;
diff --git a/src/TagLibSharp2/Mp4/Mp4File.cs b/src/TagLibSharp2/Mp4/Mp4File.cs
index fb6536b0..1250552b 100644
--- a/src/TagLibSharp2/Mp4/Mp4File.cs
+++ b/src/TagLibSharp2/Mp4/Mp4File.cs
@@ -78,7 +78,7 @@ internal void MarkPicturesSkipped ()
// The tag as read. A different tag assigned to Tag replaces the mapped fields on save, in
// every meta, and the items the tag does not map stay; null removes all metadata, as Clear.
- readonly Mp4Tag? _readTag;
+ Mp4Tag? _readTag;
///
/// Gets the audio properties (duration, bitrate, sample rate, etc.).
@@ -101,7 +101,7 @@ internal void MarkPicturesSkipped ()
public string FileType { get; private set; } = string.Empty;
// Where the tag was read from. A save writes it back there.
- Mp4MetaPlacement MetaPlacement { get; init; }
+ Mp4MetaPlacement MetaPlacement { get; set; }
///
/// Gets the audio duration from audio properties.
@@ -2981,7 +2981,7 @@ public FileWriteResult SaveToFile (string path, ReadOnlySpan originalData,
return FileWriteResult.Failure (error ?? "Failed to render MP4 file");
fileSystem ??= _sourceFileSystem;
- return AtomicFileWriter.Write (path, rendered.Span, fileSystem);
+ return Adopt (AtomicFileWriter.Write (path, rendered.Span, fileSystem), fileSystem, rendered);
}
///
@@ -3007,7 +3007,64 @@ public Task SaveToFileAsync (
return Task.FromResult (FileWriteResult.Failure (error ?? "Failed to render MP4 file"));
fileSystem ??= _sourceFileSystem;
- return AtomicFileWriter.WriteAsync (path, rendered.Memory, fileSystem, cancellationToken);
+ return AdoptAsync (AtomicFileWriter.WriteAsync (path, rendered.Memory, fileSystem, cancellationToken), fileSystem, rendered);
+ }
+
+ // A save of the whole file in memory: its moov is found where the render put it.
+ FileWriteResult Adopt (FileWriteResult result, IFileSystem? fileSystem, BinaryData written)
+ {
+ if (!result.IsSuccess || FindTopLevel (written.Span, "moov") is not { } moov)
+ return result;
+ return Adopt (result, fileSystem, written.Length, moov.Offset, written.Memory.Slice ((int)moov.Offset, (int)moov.Length));
+ }
+
+ async Task AdoptAsync (Task save, IFileSystem? fileSystem, BinaryData written) =>
+ Adopt (await save.ConfigureAwait (false), fileSystem, written);
+
+ ///
+ /// After a save over the source the object goes on as a fresh read of the saved file does (#252): its tag takes the
+ /// state of the tag read back from the moov the save wrote, and the tag's placement with it, so a later save writes
+ /// what that read's save writes. Whether the save went over the source is decided as the other formats decide it
+ /// (#179, ): the file at holds the bytes written, however the
+ /// path was spelled and through whichever file system. A save elsewhere leaves the source as it was, and the object
+ /// still describes it. The tag the object holds keeps its identity, whether the file read it, the caller assigned it
+ /// or a view created it, so a reference to it stays live and a later edit through it is written (review 2 B1): it
+ /// takes the state of the tag read back, or of a new tag when the save wrote no ilst, as a fresh read's view
+ /// creates one.
+ ///
+ FileWriteResult Adopt (FileWriteResult result, IFileSystem? fileSystem, long length, long moovOffset, ReadOnlyMemory moov)
+ {
+ if (!result.IsSuccess || !SavedOverSource.Holds (SourcePath, fileSystem, length, new WrittenBytes (moovOffset, moov)))
+ return result;
+
+ var parsed = Mp4Box.Parse (moov.Span);
+ if (!parsed.IsSuccess || parsed.Box is null)
+ return result;
+
+ var (readBack, placement) = ExtractMetadata (parsed.Box);
+ MetaPlacement = placement;
+ _creation = null;
+ if (Tag is not null)
+ Tag.AdoptStateOf (readBack ?? new Mp4Tag ());
+ else
+ Tag = readBack;
+ _readTag = Tag;
+ return result;
+ }
+
+ // The offset and length of the first top-level box of type type in a whole file, or null.
+ static (long Offset, long Length)? FindTopLevel (ReadOnlySpan file, string type)
+ {
+ long offset = 0;
+ while (offset + Mp4Box.HeaderSize <= file.Length) {
+ if (!TryMeasure (file[(int)offset..], out var found, out var size, out _) || size <= 0 || size > file.Length - offset)
+ return null;
+ if (found == type)
+ return (offset, size);
+ offset += size;
+ }
+
+ return null;
}
///
@@ -3190,26 +3247,35 @@ FileWriteResult SaveFromSource (string destinationPath, IFileSystem? fileSystem,
if (cancellationToken.IsCancellationRequested)
return FileWriteResult.Failure ("Failed to re-read source file: Operation was cancelled");
+ long length = 0;
+ long moovAt = 0;
var written = PathSave.Replace (destinationPath, opened, output => {
for (var i = 0; i < boxes.Count; i++) {
if (i == droppedIndex)
continue;
if (i == moovIndex) {
+ moovAt = length;
StreamCopy.Write (output, moovBytes, copyBuffer);
+ length += moovBytes.Length;
if (chapterBytes.Length > 0)
StreamCopy.Write (output, chapterBytes, copyBuffer);
+ length += chapterBytes.Length;
} else if (patched[i] is { } block) {
StreamCopy.Write (output, block, copyBuffer);
+ length += block.Length;
} else {
CopyFileRange (stream, output, boxes[i].Start, boxes[i].Length, copyBuffer);
+ length += boxes[i].Length;
}
}
- if (tailStart >= 0)
+ if (tailStart >= 0) {
CopyFileRange (stream, output, tailStart, fileLength - tailStart, copyBuffer);
+ length += fileLength - tailStart;
+ }
});
source = null;
- return written;
+ return Adopt (written, fileSystem, length, moovAt, moovBytes);
} finally {
source?.Dispose ();
if (chunk is not null)
diff --git a/src/TagLibSharp2/Mp4/Mp4Tag.cs b/src/TagLibSharp2/Mp4/Mp4Tag.cs
index 60b77aa0..238b7d49 100644
--- a/src/TagLibSharp2/Mp4/Mp4Tag.cs
+++ b/src/TagLibSharp2/Mp4/Mp4Tag.cs
@@ -49,48 +49,63 @@ public enum Mp4ContentRating
///
public sealed class Mp4Tag : Tag
{
- readonly Dictionary> _atoms = new ();
- readonly List _pictures = new ();
+ // The tag's state. None of it is readonly: after a save over the source the file takes the state a fresh read of the
+ // saved file has (AdoptStateOf), so a later save writes what that read's save writes (#252).
- // mean and name stay separate so a colon in either field is not a delimiter.
- // The list keeps render order; the index finds a field without scanning, so a file
- // with many freeform atoms reads in linear time.
- readonly LinkedList _freeform = new ();
- readonly Dictionary<(string Mean, string Name), LinkedListNode> _freeformByKey = new ();
+ // Every ilst item the tag writes takes a place from one counter, in the order it was read, so a save writes the
+ // items in that order: a set field stays in its item's place, a new one goes after the others (#252). The standard
+ // atoms, the freeform fields, the cover art and the kept atoms share it.
+ Places _places = new ();
+ OrderedMap> _atoms;
+ List _pictures = new ();
+ long _picturesPlace = -1;
+
+ // Keyed by FreeformId, so a colon in the mean or the name is not a delimiter. The map finds a field without
+ // scanning, so a file with many freeform atoms reads in linear time.
+ OrderedMap _freeform;
// ilst children that are not rebuilt from parsed fields, such as "orch".
// Indexed by 4-byte type so one edit does not scan every child.
- readonly List _preservedAtoms = new ();
- readonly Dictionary> _preservedByType = new ();
+ List _preservedAtoms = new ();
+ Dictionary> _preservedByType = new ();
// Preserved freeform boxes that carry a mean and a name, so a set drops its twin directly.
- readonly Dictionary<(string Mean, string Name), List> _preservedFreeformByKey = new ();
+ Dictionary<(string Mean, string Name), List> _preservedFreeformByKey = new ();
// Set when the ilst belongs to a QuickTime meta whose handler is "mdta". Items are then typed
// by key index, so a field remembers the key it was read from and a new field gets a key.
Mp4QuickTimeKeys? _keys;
bool _cleared;
- readonly Dictionary _keyIndexByField = new (StringComparer.Ordinal);
+ Dictionary _keyIndexByField = new (StringComparer.Ordinal);
// Items a field was read from when they are kept byte for byte: every item of an "mdta" meta
// that names a field (keyed, iTunes-typed, or with a value the reader rejects), and the items
// of a second meta (moov/meta beside udta/meta). While a field's value comes from them, an
// unedited save writes them back as they were; setting the field drops all of them.
- readonly Dictionary> _sources = new (StringComparer.Ordinal);
- readonly HashSet _valueFromSources = new (StringComparer.Ordinal);
- readonly Dictionary _valueRank = new (StringComparer.Ordinal);
- readonly Dictionary _slotByField = new (StringComparer.Ordinal);
+ Dictionary> _sources = new (StringComparer.Ordinal);
+ HashSet _valueFromSources = new (StringComparer.Ordinal);
+ Dictionary _valueRank = new (StringComparer.Ordinal);
+ Dictionary _slotByField = new (StringComparer.Ordinal);
// Items of a second meta (moov/meta beside udta/meta), in file order. Null marks one a set
// dropped. A field whose value came from it is written back there when set: QTFF gives
// metadata precedence over user data that declares the same information.
- readonly List _movieItems = new ();
- readonly HashSet _movieFields = new (StringComparer.Ordinal);
- readonly Dictionary _movieSlotByField = new (StringComparer.Ordinal);
- readonly Dictionary _movieKeyIndexByField = new (StringComparer.Ordinal);
+ List _movieItems = new ();
+ HashSet _movieFields = new (StringComparer.Ordinal);
+ Dictionary _movieSlotByField = new (StringComparer.Ordinal);
+ Dictionary _movieKeyIndexByField = new (StringComparer.Ordinal);
Mp4QuickTimeKeys? _movieKeys;
bool _hasMovieMeta;
+ ///
+ /// Creates an empty tag.
+ ///
+ public Mp4Tag ()
+ {
+ _atoms = new OrderedMap> (StringComparer.Ordinal, 0, _places);
+ _freeform = new OrderedMap (StringComparer.Ordinal, 0, _places);
+ }
+
///
public override TagTypes TagType => TagTypes.Apple;
@@ -759,10 +774,16 @@ public override IPicture[] Pictures {
_pictures.Add (new Mp4Picture (pic.MimeType, pic.PictureType, pic.Description, pic.PictureData));
}
}
+
+ PicturesChanged ();
}
}
#pragma warning restore CA1819
+ // The cover art keeps its place while the tag has pictures; pictures set on a tag with none go last.
+ void PicturesChanged () =>
+ _picturesPlace = _pictures.Count == 0 ? -1 : _picturesPlace >= 0 ? _picturesPlace : _places.Next ();
+
string? GetGnreName ()
{
var code = GetInteger (Mp4AtomMapping.GenreId3);
@@ -913,22 +934,17 @@ internal void SetFreeform (string mean, string name, string? value)
internal void SetFreeformAtoms (string mean, string name, List dataAtoms)
{
- var key = (mean, name);
- if (_freeformByKey.TryGetValue (key, out var existing)) {
- _freeform.Remove (existing);
- _freeformByKey.Remove (key);
- }
-
DropPreservedFreeform (mean, name);
DropFreeformTwins (mean, name);
+ var id = FreeformId (mean, name);
if (dataAtoms is null || dataAtoms.Count == 0)
- return;
-
- _freeformByKey.Add (key, _freeform.AddLast (new FreeformField (mean, name, dataAtoms)));
+ _freeform.Remove (id);
+ else
+ _freeform.Set (id, new FreeformField (mean, name, dataAtoms));
}
FreeformField? FindFreeform (string mean, string name) =>
- _freeformByKey.TryGetValue ((mean, name), out var node) ? node.Value : null;
+ _freeform.TryGetValue (FreeformId (mean, name), out var field) ? field : null;
void RemoveAtom (string atomId)
{
@@ -936,6 +952,36 @@ void RemoveAtom (string atomId)
DropPreserved (atomId);
}
+ ///
+ /// Takes the state of , a tag read from the file a save just wrote over the source, so this
+ /// object goes on as a fresh read of that file does (#252): the same items in the same places, the same keys and key
+ /// indexes, the same sources and slots, and the same metas. Every field of the tag is state, and every one is taken.
+ ///
+ internal void AdoptStateOf (Mp4Tag other)
+ {
+ _places = other._places;
+ _atoms = other._atoms;
+ _pictures = other._pictures;
+ _picturesPlace = other._picturesPlace;
+ _freeform = other._freeform;
+ _preservedAtoms = other._preservedAtoms;
+ _preservedByType = other._preservedByType;
+ _preservedFreeformByKey = other._preservedFreeformByKey;
+ _keys = other._keys;
+ _cleared = other._cleared;
+ _keyIndexByField = other._keyIndexByField;
+ _sources = other._sources;
+ _valueFromSources = other._valueFromSources;
+ _valueRank = other._valueRank;
+ _slotByField = other._slotByField;
+ _movieItems = other._movieItems;
+ _movieFields = other._movieFields;
+ _movieSlotByField = other._movieSlotByField;
+ _movieKeyIndexByField = other._movieKeyIndexByField;
+ _movieKeys = other._movieKeys;
+ _hasMovieMeta = other._hasMovieMeta;
+ }
+
///
public override bool SupportsCustomFields => true;
@@ -1019,8 +1065,8 @@ public override void Clear ()
_cleared = true;
_atoms.Clear ();
_pictures.Clear ();
+ _picturesPlace = -1;
_freeform.Clear ();
- _freeformByKey.Clear ();
_preservedAtoms.Clear ();
_preservedByType.Clear ();
_preservedFreeformByKey.Clear ();
@@ -1050,8 +1096,8 @@ internal void ClearMappedFields ()
_atoms.Clear ();
_pictures.Clear ();
+ _picturesPlace = -1;
_freeform.Clear ();
- _freeformByKey.Clear ();
for (var i = 0; i < _preservedAtoms.Count; i++) {
if (_preservedAtoms[i] is { } kept && IsMappedType (kept.Box.Span))
_preservedAtoms[i] = null;
@@ -1126,20 +1172,31 @@ public override BinaryData Render ()
if (_keys is not null)
return RenderKeyed (_keys);
- using var builder = new BinaryDataBuilder ();
-
- // A field whose value still comes from kept items is not written here. A field set after it
- // was read from a second meta is written both there and here, so every reader shows it.
+ // Every item in its place (#252). A field whose value still comes from kept items is not written here. A field
+ // set after it was read from a second meta is written both there and here, so every reader shows it.
+ var items = new List<(long Place, BinaryData Box)> ();
foreach (var field in ValuedFields ()) {
if (!_valueFromSources.Contains (field.Id))
- builder.Add (field.Itunes ());
+ items.Add ((field.Place, field.Itunes ()));
}
foreach (var preserved in _preservedAtoms) {
if (preserved is not null)
- builder.Add (preserved.Box);
+ items.Add ((preserved.Place, preserved.Box));
}
+ // A kept item that holds a field's earlier value shares that field's place; the field is not written then.
+ var order = new int[items.Count];
+ for (var i = 0; i < order.Length; i++)
+ order[i] = i;
+ Array.Sort (order, (x, y) => {
+ var byPlace = items[x].Place.CompareTo (items[y].Place);
+ return byPlace != 0 ? byPlace : x.CompareTo (y);
+ });
+
+ using var builder = new BinaryDataBuilder ();
+ foreach (var i in order)
+ builder.Add (items[i].Box);
return builder.ToBinaryData ();
}
@@ -1201,7 +1258,7 @@ internal void AddSourceAtom (string atomId, List? value, BinaryData
if (!AddSource (atomId, box, keyIndex, movie) || value is null || value.Count == 0 || !TakesValue (atomId, _atoms.ContainsKey (atomId), rank))
return;
- _atoms[atomId] = value;
+ _atoms.Set (atomId, value);
TookValue (atomId, rank, movie);
}
@@ -1211,12 +1268,7 @@ internal void AddSourceFreeform (string mean, string name, List? va
if (!AddSource (id, box, keyIndex, movie) || value is null || value.Count == 0 || !TakesValue (id, FindFreeform (mean, name) is not null, rank))
return;
- if (_freeformByKey.TryGetValue ((mean, name), out var existing)) {
- _freeform.Remove (existing);
- _freeformByKey.Remove ((mean, name));
- }
-
- _freeformByKey.Add ((mean, name), _freeform.AddLast (new FreeformField (mean, name, value)));
+ _freeform.Set (id, new FreeformField (mean, name, value));
TookValue (id, rank, movie);
}
@@ -1228,6 +1280,7 @@ internal void AddSourcePictures (Mp4Picture[]? value, BinaryData box, uint keyIn
_pictures.Clear ();
_pictures.AddRange (value);
+ PicturesChanged ();
TookValue (id, rank, movie);
}
@@ -1292,21 +1345,20 @@ void TookValue (string fieldId, Mp4SourceRank rank, bool movie)
void KeepCurrentValue (string fieldId)
{
- foreach (var field in ValuedFields ()) {
- if (field.Id != fieldId)
- continue;
-
- var index = PreserveIlstAtom (field.Itunes (), field.Field.Mean, field.Field.Name);
- if (!_slotByField.ContainsKey (fieldId))
- _slotByField[fieldId] = index;
- if (!_sources.TryGetValue (fieldId, out var list)) {
- list = new List<(bool, int)> ();
- _sources[fieldId] = list;
- }
-
- list.Add ((false, index));
+ // Found by its id: a read where a second meta overrides n fields stays linear in n (#252).
+ if (FindValuedField (fieldId) is not { } field)
return;
+
+ // The kept value stays where the field was.
+ var index = PreserveIlstAtom (field.Itunes (), field.Field.Mean, field.Field.Name, field.Place);
+ if (!_slotByField.ContainsKey (fieldId))
+ _slotByField[fieldId] = index;
+ if (!_sources.TryGetValue (fieldId, out var list)) {
+ list = new List<(bool, int)> ();
+ _sources[fieldId] = list;
}
+
+ list.Add ((false, index));
}
// A set or a removal replaces every item the field was read from.
@@ -1333,28 +1385,48 @@ void DropSources (string fieldId)
internal BinaryData RenderMovieIlst () =>
RenderOrdered (_movieItems, _movieKeys, _movieSlotByField, _movieKeyIndexByField, movie: true);
- // Every field that has a value, with its iTunes form and its keyed form.
- IEnumerable<(string Id, Mp4KeyedField Field, List Atoms, Func Itunes)> ValuedFields ()
+ // Every field that has a value, with its place, its iTunes form and its keyed form, in place order (#252).
+ List ValuedFields ()
{
- foreach (var kvp in _atoms) {
- var (atomId, atoms) = (kvp.Key, kvp.Value);
- yield return (atomId, Mp4KeyedField.Atom (atomId), atoms, () => Rendered (b => RenderStandardAtom (b, atomId, atoms)));
- }
+ var fields = new List (_atoms.Count + _freeform.Count + 1);
+ foreach (var (atomId, atoms, place) in _atoms.Placed ())
+ fields.Add (AtomField (atomId, atoms, place));
+ foreach (var (id, f, place) in _freeform.Placed ())
+ fields.Add (FreeformValuedField (id, f, place));
+ if (PicturesField () is { } pictures)
+ fields.Add (pictures);
+ fields.Sort (static (a, b) => a.Place.CompareTo (b.Place));
+ return fields;
+ }
+
+ // The field with the id fieldId, or null when it has no value: a lookup, not a walk.
+ ValuedField? FindValuedField (string fieldId)
+ {
+ if (fieldId == Mp4AtomMapping.CoverArt)
+ return PicturesField ();
+ if (_freeform.TryGetValue (fieldId, out var f, out var place))
+ return FreeformValuedField (fieldId, f, place);
+ return _atoms.TryGetValue (fieldId, out var atoms, out place) ? AtomField (fieldId, atoms, place) : null;
+ }
- foreach (var field in _freeform) {
- var f = field;
- yield return (FreeformId (f.Mean, f.Name), Mp4KeyedField.Freeform (f.Mean, f.Name), f.Atoms,
- () => Rendered (b => RenderFreeformAtom (b, f.Mean, f.Name, f.Atoms)));
- }
+ static ValuedField AtomField (string atomId, List atoms, long place) =>
+ new (atomId, Mp4KeyedField.Atom (atomId), atoms, place, () => Rendered (b => RenderStandardAtom (b, atomId, atoms)));
- if (_pictures.Count > 0) {
- var covers = new List (_pictures.Count);
- foreach (var picture in _pictures)
- covers.Add (new Mp4DataAtom (picture.RenderTypeIndicator, picture.PictureData, picture.RenderLocale));
- yield return (Mp4AtomMapping.CoverArt, Mp4KeyedField.Artwork (), covers, () => Rendered (RenderPictures));
- }
+ static ValuedField FreeformValuedField (string id, FreeformField f, long place) =>
+ new (id, Mp4KeyedField.Freeform (f.Mean, f.Name), f.Atoms, place, () => Rendered (b => RenderFreeformAtom (b, f.Mean, f.Name, f.Atoms)));
+
+ ValuedField? PicturesField ()
+ {
+ if (_pictures.Count == 0)
+ return null;
+ var covers = new List (_pictures.Count);
+ foreach (var picture in _pictures)
+ covers.Add (new Mp4DataAtom (picture.RenderTypeIndicator, picture.PictureData, picture.RenderLocale));
+ return new ValuedField (Mp4AtomMapping.CoverArt, Mp4KeyedField.Artwork (), covers, _picturesPlace, () => Rendered (RenderPictures));
}
+ readonly record struct ValuedField (string Id, Mp4KeyedField Field, List Atoms, long Place, Func Itunes);
+
static BinaryData Rendered (Action render)
{
using var builder = new BinaryDataBuilder ();
@@ -1577,17 +1649,17 @@ internal void SetAtoms (string atomId, List dataAtoms)
}
DropPreserved (atomId);
- _atoms[atomId] = dataAtoms;
+ _atoms.Set (atomId, dataAtoms);
}
- internal int PreserveIlstAtom (BinaryData box, string? mean = null, string? name = null)
+ internal int PreserveIlstAtom (BinaryData box, string? mean = null, string? name = null, long? place = null)
{
if (box.IsEmpty)
return -1;
var typeKey = TypeKey (box.Span);
var index = _preservedAtoms.Count;
- _preservedAtoms.Add (new PreservedBox (box));
+ _preservedAtoms.Add (new PreservedBox (box, place ?? _places.Next ()));
if (!_preservedByType.TryGetValue (typeKey, out var indexes)) {
indexes = new List ();
_preservedByType.Add (typeKey, indexes);
@@ -1674,13 +1746,17 @@ public FreeformField (string mean, string name, List atoms)
public List Atoms { get; }
}
+ // A kept ilst item and its place among the items a save writes (#252).
sealed class PreservedBox
{
- public PreservedBox (BinaryData box)
+ public PreservedBox (BinaryData box, long place)
{
Box = box;
+ Place = place;
}
public BinaryData Box { get; }
+
+ public long Place { get; }
}
}
diff --git a/src/TagLibSharp2/Musepack/MusepackFile.cs b/src/TagLibSharp2/Musepack/MusepackFile.cs
index 296bc5ce..2b505675 100644
--- a/src/TagLibSharp2/Musepack/MusepackFile.cs
+++ b/src/TagLibSharp2/Musepack/MusepackFile.cs
@@ -585,6 +585,20 @@ private void ParseApeTag (ReadOnlySpan data, int tagFloor)
byte[] ApeTagBytes () => ApeTag.RenderForSave (ApeTag, _readApeTag, defaultHeader: false).ToArray ();
+ // A save writes no APE tag that holds nothing (#258). After a successful one over the source the file holds no tag,
+ // so the tag the object holds, kept for a caller who holds it (review 2 B1), is no longer the tag read: a value set
+ // next is written with the layout of a tag this file did not read (footer only), as a fresh read's view writes it.
+ // After a save elsewhere the object still describes its source, whose tag it emptied, and keeps the read layout
+ // (contract suite round 3, R1).
+ FileWriteResult Saved (FileWriteResult result, string path, IFileSystem? fileSystem)
+ {
+ if (result.IsSuccess && ApeTag is { StoresNothing: true } && _readApeTag is not null
+ && SavedOverSource.HoldsFile (SourcePath, _sourceFileSystem ?? fileSystem, path, fileSystem))
+ _readApeTag = null;
+
+ return Source.Saved (result);
+ }
+
///
/// Ensures an APE tag exists, creating one if necessary.
///
@@ -673,7 +687,7 @@ public FileWriteResult SaveToFile (string path, ReadOnlySpan originalData,
var fs = fileSystem ?? _sourceFileSystem ?? DefaultFileSystem.Instance;
var rendered = Render (originalData);
- return Source.Saved (AtomicFileWriter.Write (path, rendered, fs));
+ return Saved (AtomicFileWriter.Write (path, rendered, fs), path, fs);
}
///
@@ -695,7 +709,7 @@ public FileWriteResult SaveToFile (string path, IFileSystem? fileSystem = null)
return FileWriteResult.Failure ("No source path available. File was not read from disk.");
var tag = ApeTagBytes ();
- return Source.Saved (ApeTagLocation.WriteFromSource (SourcePath, path, fs, tag));
+ return Saved (ApeTagLocation.WriteFromSource (SourcePath, path, fs, tag), path, fs);
}
///
@@ -736,7 +750,7 @@ public async Task SaveToFileAsync (
var fs = fileSystem ?? _sourceFileSystem ?? DefaultFileSystem.Instance;
var rendered = Render (originalData.Span);
- return Source.Saved (await AtomicFileWriter.WriteAsync (path, rendered, fs, cancellationToken).ConfigureAwait (false));
+ return Saved (await AtomicFileWriter.WriteAsync (path, rendered, fs, cancellationToken).ConfigureAwait (false), path, fs);
}
///
@@ -762,7 +776,7 @@ public Task SaveToFileAsync (
return Task.FromResult (FileWriteResult.Failure ("No source path available. File was not read from disk."));
var tag = ApeTagBytes ();
- return Task.FromResult (Source.Saved (ApeTagLocation.WriteFromSource (SourcePath, path, fs, tag, cancellationToken)));
+ return Task.FromResult (Saved (ApeTagLocation.WriteFromSource (SourcePath, path, fs, tag, cancellationToken), path, fs));
}
///
diff --git a/src/TagLibSharp2/Ogg/OggFlacFile.cs b/src/TagLibSharp2/Ogg/OggFlacFile.cs
index 6017b346..fb317986 100644
--- a/src/TagLibSharp2/Ogg/OggFlacFile.cs
+++ b/src/TagLibSharp2/Ogg/OggFlacFile.cs
@@ -190,7 +190,17 @@ internal List MetadataBlockPayloads (byte type)
public string? SourcePath => _sourcePath;
///
- public Tag? Tag => VorbisComment;
+ ///
+ /// The Vorbis comment. A file without one (it was removed) has a view whose first write creates one, and a write
+ /// that leaves that comment empty removes it again, as on a FLAC file. Reading the view creates nothing. Null after
+ /// Dispose.
+ ///
+ public Tag? Tag => _disposed ? null : CombinedTag.SingleOrView (VorbisComment, () => VorbisComment,
+ _creation ??= new TagCreation (NewComment, tag => VorbisComment = (VorbisComment?)tag));
+
+ TagCreation? _creation;
+
+ static VorbisComment NewComment () => new ();
///
IMediaProperties? IMediaFile.AudioProperties => Properties;
@@ -484,7 +494,7 @@ private static ExtractPacketResult ExtractFirstPacket (ReadOnlySpan data)
///
public VorbisComment EnsureVorbisComment ()
{
- VorbisComment ??= new VorbisComment ();
+ VorbisComment ??= NewComment ();
return VorbisComment;
}
@@ -505,6 +515,9 @@ public void RemoveVorbisComment ()
///
public byte[] Render (ReadOnlySpan originalData)
{
+ // A comment the tag view created and that holds nothing is not written (TagCreation).
+ _creation?.Settle ([VorbisComment]);
+
// Do not splice metadata in front of a continuation we failed to reassemble.
var headerInfo = ExtractHeaderInfo (originalData);
if (!headerInfo.IsSuccess)
diff --git a/src/TagLibSharp2/Ogg/OggOpusFile.cs b/src/TagLibSharp2/Ogg/OggOpusFile.cs
index 5e66a059..79961017 100644
--- a/src/TagLibSharp2/Ogg/OggOpusFile.cs
+++ b/src/TagLibSharp2/Ogg/OggOpusFile.cs
@@ -172,7 +172,17 @@ public string? Comment {
}
///
- public Tag? Tag => VorbisComment;
+ ///
+ /// The Vorbis comment. A file without one (it was removed) has a view whose first write creates one, and a write
+ /// that leaves that comment empty removes it again, as on a FLAC file. Reading the view creates nothing. Null after
+ /// Dispose.
+ ///
+ public Tag? Tag => _disposed ? null : CombinedTag.SingleOrView (VorbisComment, () => VorbisComment,
+ _creation ??= new TagCreation (NewComment, tag => VorbisComment = (VorbisComment?)tag));
+
+ TagCreation? _creation;
+
+ static VorbisComment NewComment () => new ("TagLibSharp2");
///
IMediaProperties? IMediaFile.AudioProperties => Properties;
@@ -565,7 +575,7 @@ static bool IsOpusTags (ReadOnlySpan data) =>
VorbisComment EnsureVorbisComment ()
{
- VorbisComment ??= new VorbisComment ("TagLibSharp2");
+ VorbisComment ??= NewComment ();
return VorbisComment;
}
diff --git a/src/TagLibSharp2/Ogg/OggVorbisFile.cs b/src/TagLibSharp2/Ogg/OggVorbisFile.cs
index b0453c8e..fba20595 100644
--- a/src/TagLibSharp2/Ogg/OggVorbisFile.cs
+++ b/src/TagLibSharp2/Ogg/OggVorbisFile.cs
@@ -128,7 +128,17 @@ public string? Comment {
}
///
- public Tag? Tag => VorbisComment;
+ ///
+ /// The Vorbis comment. A file without one (it was removed) has a view whose first write creates one, and a write
+ /// that leaves that comment empty removes it again, as on a FLAC file. Reading the view creates nothing. Null after
+ /// Dispose.
+ ///
+ public Tag? Tag => _disposed ? null : CombinedTag.SingleOrView (VorbisComment, () => VorbisComment,
+ _creation ??= new TagCreation (NewComment, tag => VorbisComment = (VorbisComment?)tag));
+
+ TagCreation? _creation;
+
+ static VorbisComment NewComment () => new ("TagLibSharp2");
///
IMediaProperties? IMediaFile.AudioProperties => Properties;
@@ -449,7 +459,7 @@ static bool IsVorbisCommentHeader (ReadOnlySpan data)
VorbisComment EnsureVorbisComment ()
{
- VorbisComment ??= new VorbisComment ("TagLibSharp2");
+ VorbisComment ??= NewComment ();
return VorbisComment;
}
diff --git a/src/TagLibSharp2/Riff/AviFile.cs b/src/TagLibSharp2/Riff/AviFile.cs
index dd960395..a2a7b83f 100644
--- a/src/TagLibSharp2/Riff/AviFile.cs
+++ b/src/TagLibSharp2/Riff/AviFile.cs
@@ -91,14 +91,18 @@ internal void MarkPicturesSkipped ()
///
/// On save, a value that was not changed 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 all fit it; with no CSET,
- /// or one this library does not encode, only ASCII fits. Otherwise the list becomes UTF-8 with a CSET
- /// of code page 65001 in front of it: unchanged UTF-8 and ASCII values keep their bytes, and unchanged
- /// text in a declared code page this library decodes exactly (1252, 28591, 0) is written as UTF-8 of
- /// the same text; the new CSET keeps the old one's country, language and dialect codes. The save is
- /// refused, with an error naming the field and the reason, rather than changing an unchanged value's
- /// text when its code page is a guess (no CSET and not UTF-8), is not decoded here (932 or 1251, say),
- /// or the value holds a byte its declared code page leaves undefined (0x81, 0x8D, 0x8F, 0x90 or 0x9D
- /// in 1252; 0x80-0x9F under code page 0). mediainfo ignores CSET.
+ /// or one this library does not encode, only ASCII fits. When one does not fit (#220):
+ /// with no CSET and an unchanged value that is not UTF-8, or with a CSET of a code page this library does not decode
+ /// (932 or 1251, say), every unchanged value keeps its bytes and the changes are written by the read rule
+ /// (Windows-1252 when that reads back as the value, else UTF-8), and such a CSET is dropped: this library already
+ /// reads that list by the no-CSET rule, so every value reads back as it read, and a reader that decodes the code page
+ /// itself still has the original bytes. Otherwise (no CSET and only ASCII or UTF-8, or a code page this library
+ /// decodes: 1252, 28591, 0) the list becomes UTF-8 with a CSET of code page 65001 in front of it:
+ /// unchanged UTF-8 and ASCII values keep their bytes, and every other unchanged value is written as the UTF-8 of the
+ /// text this reader returned for it (the same text when decoded exactly; the text read when a byte the code page
+ /// leaves undefined, 0x81, 0x8D, 0x8F, 0x90 or 0x9D in 1252 or 0x80-0x9F under code page 0, made it a guess). The
+ /// new CSET keeps the old one's country, language and dialect codes. A changed value is never refused. mediainfo
+ /// ignores CSET.
///
///
public RiffInfoTag InfoTag { get; }
@@ -111,7 +115,24 @@ internal void MarkPicturesSkipped ()
/// null removes the chunk the tag was read from. A chunk this reader could not parse is kept
/// while this property stays null.
///
- public Id3v2Tag? Id3v2Tag { get; set; }
+ public Id3v2Tag? Id3v2Tag {
+ get => _id3v2Tag;
+ set {
+ _id3v2Tag = value;
+ _id3Gone = false;
+ }
+ }
+
+ Id3v2Tag? _id3v2Tag;
+
+ // The ID3v2 tag the view shows: an emptied tag a save over the source did not write is held for a caller who holds
+ // it (review 2 B1) and written again once it holds a value, but the file holds no such chunk, so the view goes on as
+ // a fresh read of that file does, over the INFO list alone (review 1 N7).
+ Id3v2Tag? ViewId3 => _id3Gone && _id3v2Tag is { IsEmpty: true } ? null : _id3v2Tag;
+
+ // Whether the source holds no chunk for the tag held: set by a save over the source that wrote none, cleared by one
+ // that wrote it, and by an assignment. A save elsewhere leaves it as it was (contract suite round 3).
+ bool _id3Gone;
/// Gets the duration of the file.
///
@@ -138,11 +159,20 @@ internal void MarkPicturesSkipped ()
/// Gets .
public MediaFormat Format => MediaFormat.Avi;
- ///
- /// The INFO tag, combined with the ID3v2 tag when there is one. The INFO tag comes first.
- Tag? IMediaFile.Tag => UnifiedTag;
+ /// Gets the file's tag view.
+ ///
+ /// The INFO tag, combined with the ID3v2 tag when there is one; the INFO tag comes first, and a set or
+ /// writes both. INFO holds only its own fields (title, artist, album, comment, genre, year,
+ /// track, copyright and custom INFO fields): on a file with no ID3v2 tag a field it cannot hold, such as a
+ /// MusicBrainz ID, is not stored; assign first to keep one. A save writes no empty ID3v2 tag,
+ /// and after a successful save over the source that emptied it this view is the INFO tag alone, as a fresh read of
+ /// the file finds no ID3v2 tag; keeps it, as a new ID3v2.4 tag, so a value set later through it is written. A save
+ /// to another path changes neither. Never null, after too, as AsfFile.Tag and MatroskaFile.Tag.
+ ///
+ public Tag Tag => ViewId3 is { } id3 ? new CombinedTag (InfoTag, id3) : InfoTag;
- internal Tag UnifiedTag => Id3v2Tag is null ? InfoTag : new CombinedTag (InfoTag, Id3v2Tag);
+ ///
+ Tag? IMediaFile.Tag => Tag;
IMediaProperties? IMediaFile.AudioProperties => AudioProperties;
@@ -475,7 +505,7 @@ public FileWriteResult SaveToFile (string path, ReadOnlySpan originalData,
if (!AviRewrite.TryRewrite (originalData, InfoTag, Id3v2Tag, out var rewritten, out var error))
return FileWriteResult.Failure (error);
- return Source.Saved (AtomicFileWriter.Write (path, rewritten, fileSystem ?? _sourceFileSystem));
+ return Saved (AtomicFileWriter.Write (path, rewritten, fileSystem ?? _sourceFileSystem), path, fileSystem);
} catch (Id3v2TagTooLargeException tooLarge) {
return FileWriteResult.Failure (tooLarge.Message);
}
@@ -495,7 +525,7 @@ public FileWriteResult SaveToFile (string path, IFileSystem? fileSystem = null)
if (string.IsNullOrEmpty (SourcePath))
return FileWriteResult.Failure ("No source path available. File was not read from disk.");
- return Source.Saved (SaveStreaming (path, fileSystem ?? _sourceFileSystem, CancellationToken.None));
+ return Saved (SaveStreaming (path, fileSystem ?? _sourceFileSystem, CancellationToken.None), path, fileSystem);
} catch (Id3v2TagTooLargeException tooLarge) {
return FileWriteResult.Failure (tooLarge.Message);
}
@@ -543,7 +573,7 @@ public Task SaveToFileAsync (
if (!AviRewrite.TryRewrite (originalData.Span, InfoTag, Id3v2Tag, out var rewritten, out var error))
return Task.FromResult (FileWriteResult.Failure (error));
- return Source.Saved (AtomicFileWriter.WriteAsync (path, rewritten, fileSystem ?? _sourceFileSystem, cancellationToken));
+ return Saved (AtomicFileWriter.WriteAsync (path, rewritten, fileSystem ?? _sourceFileSystem, cancellationToken), path, fileSystem);
} catch (Id3v2TagTooLargeException tooLarge) {
return Task.FromResult (FileWriteResult.Failure (tooLarge.Message));
}
@@ -567,7 +597,7 @@ public Task SaveToFileAsync (
if (string.IsNullOrEmpty (SourcePath))
return Task.FromResult (FileWriteResult.Failure ("No source path available. File was not read from disk."));
- return Task.FromResult (Source.Saved (SaveStreaming (path, fileSystem ?? _sourceFileSystem, cancellationToken)));
+ return Task.FromResult (Saved (SaveStreaming (path, fileSystem ?? _sourceFileSystem, cancellationToken), path, fileSystem));
} catch (Id3v2TagTooLargeException tooLarge) {
return Task.FromResult (FileWriteResult.Failure (tooLarge.Message));
}
@@ -631,6 +661,26 @@ public Task SaveToFileAsync (
}
}
+ // A successful save describes the file it wrote (SourceLength). It writes no empty ID3v2 tag, so after one over the
+ // source the file holds none, and the view goes on as a fresh read's (ViewId3); the tag itself stays attached. After a
+ // save elsewhere the object still describes its source, which holds the tag (contract suite round 3).
+ FileWriteResult Saved (FileWriteResult result, string path, IFileSystem? fileSystem)
+ {
+ if (result.IsSuccess && (_id3v2Tag is { IsEmpty: true } || _id3Gone)
+ && SavedOverSource.HoldsFile (SourcePath, _sourceFileSystem, path, fileSystem ?? _sourceFileSystem)) {
+ _id3Gone = _id3v2Tag is { IsEmpty: true };
+ // The tag kept is now a new one, as a tag assigned to the saved file would be, so its next value is written as
+ // that one's (review 3 B1).
+ if (_id3Gone)
+ _id3v2Tag!.ResetToNew ();
+ }
+
+ return Source.Saved (result);
+ }
+
+ async Task Saved (Task save, string path, IFileSystem? fileSystem) =>
+ Saved (await save.ConfigureAwait (false), path, fileSystem);
+
/// Releases the tags held by this instance.
public void Dispose ()
{
diff --git a/src/TagLibSharp2/Riff/AviRewrite.cs b/src/TagLibSharp2/Riff/AviRewrite.cs
index 1acd5f71..bd78d9e5 100644
--- a/src/TagLibSharp2/Riff/AviRewrite.cs
+++ b/src/TagLibSharp2/Riff/AviRewrite.cs
@@ -94,18 +94,21 @@ public static bool TryRewrite (
var list = BinaryData.Empty;
byte[]? characterSet = null;
+ var dropCharacterSet = false;
if (infoChanged && !info.IsEmpty) {
- if (!info.TryRenderAvi (out list, out var declareUtf8, out var refused)) {
- error = refused!;
- return false;
- }
+ list = info.RenderAvi (out var cset);
// The CSET goes right before the list; exiftool honours only a CSET it meets first.
- characterSet = declareUtf8 ? AviChunks.Utf8CharacterSetChunk (original) : AviChunks.FirstCharacterSetChunk (original);
+ characterSet = cset switch {
+ InfoCsetWrite.Utf8 => AviChunks.Utf8CharacterSetChunk (original),
+ InfoCsetWrite.Drop => null,
+ _ => AviChunks.FirstCharacterSetChunk (original),
+ };
+ dropCharacterSet = cset == InfoCsetWrite.Drop;
}
var blob = Blob (list, characterSet, id3, id3Changed, id3Present ? AviChunks.Name (id3Chunk.Id) : "ID32");
- var plan = Plan (original, movi, hasHeaders ? hdrl.Offset : -1, new Changes (infoChanged, characterSet is not null, id3Changed), blob.Length);
+ var plan = Plan (original, movi, hasHeaders ? hdrl.Offset : -1, new Changes (infoChanged, characterSet is not null || dropCharacterSet, id3Changed), blob.Length);
if (blob.Length == 0 || plan.Target is not null) {
output = owned ?? original.ToArray ();
if (plan.Target is { } target) {
@@ -216,7 +219,8 @@ static bool IsChangedTag (AviTopChunk chunk, Changes changes) =>
///
/// What the save rewrites. A CSET is rewritten only when a new list is written with one in front:
- /// the file's own CSET again, or a 65001 CSET for a list that became UTF-8. A cleared list leaves it.
+ /// the file's own CSET again, or a 65001 CSET for a list that became UTF-8. It is removed when the list drops a CSET
+ /// of a code page this library does not decode (#220). A cleared list leaves it.
///
readonly struct Changes (bool info, bool characterSet, bool id3)
{
@@ -690,19 +694,20 @@ internal static bool TryPlanStream (
var list = BinaryData.Empty;
byte[]? characterSet = null;
+ var dropCharacterSet = false;
if (infoChanged && !info.IsEmpty) {
- if (!info.TryRenderAvi (out list, out var declareUtf8, out var refused)) {
- error = refused!;
- return false;
- }
+ list = info.RenderAvi (out var cset);
- characterSet = declareUtf8
- ? Utf8CharacterSet (FirstChunk (source, ref walk, static item => item.IsCharacterSet, length, chunk))
- : ReadWholeChunk (source, ref walk, static item => item.IsCharacterSet, chunk);
+ characterSet = cset switch {
+ InfoCsetWrite.Utf8 => Utf8CharacterSet (FirstChunk (source, ref walk, static item => item.IsCharacterSet, length, chunk)),
+ InfoCsetWrite.Drop => null,
+ _ => ReadWholeChunk (source, ref walk, static item => item.IsCharacterSet, chunk),
+ };
+ dropCharacterSet = cset == InfoCsetWrite.Drop;
}
var blob = Blob (list, characterSet, id3, id3Changed, id3Present ? AviChunks.Name (id3Chunk.Id) : "ID32");
- var save = Plan (ref walk, movi.Value.Offset, hdrl is { } headers ? headers.Offset : -1, new Changes (infoChanged, characterSet is not null, id3Changed), blob.Length);
+ var save = Plan (ref walk, movi.Value.Offset, hdrl is { } headers ? headers.Offset : -1, new Changes (infoChanged, characterSet is not null || dropCharacterSet, id3Changed), blob.Length);
if (blob.Length == 0 || save.Target is not null) {
plan = new StreamPlan {
InPlace = true,
diff --git a/src/TagLibSharp2/Riff/InfoText.cs b/src/TagLibSharp2/Riff/InfoText.cs
index 13f40c08..a889376b 100644
--- a/src/TagLibSharp2/Riff/InfoText.cs
+++ b/src/TagLibSharp2/Riff/InfoText.cs
@@ -30,6 +30,22 @@ internal enum InfoCharacterSet
Other
}
+/// What an AVI save does with the file's CSET chunk when it writes a new INFO list.
+internal enum InfoCsetWrite
+{
+ /// The file's CSET goes in front of the list again (or there is none).
+ Keep,
+
+ /// A CSET of code page 65001 goes in front of the list, which became UTF-8.
+ Utf8,
+
+ ///
+ /// The file's CSET goes: it names a code page this library does not decode, and the list keeps every unchanged
+ /// value's bytes and writes the changes by the no-CSET read rule (#220).
+ ///
+ Drop
+}
+
/// How surely a stored INFO value's text is known.
internal enum InfoTextKind
{
@@ -241,50 +257,4 @@ static int Windows1252Byte (char c)
var index = Array.IndexOf (Windows1252High, c);
return index < 0 || IsUnassigned1252 ((byte)(0x80 + index)) ? -1 : 0x80 + index;
}
-
- ///
- /// Why an unchanged value of kind cannot be rewritten as UTF-8,
- /// for the refusal message. is the CSET's wCodePage, or -1 for none.
- ///
- public static string GuessReason (ReadOnlySpan field, InfoCharacterSet characterSet, int codePage)
- {
- var end = field.IndexOf ((byte)0);
- if (end >= 0)
- field = field.Slice (0, end);
- switch (characterSet) {
- case InfoCharacterSet.Latin1Default:
- foreach (var b in field) {
- if (IsC1 (b))
- return $"holds byte 0x{b:X2}, which the CSET's code page 0 (ISO 8859/1 without columns 8 and 9) leaves undefined";
- }
-
- break;
- case InfoCharacterSet.Windows1252:
- foreach (var b in field) {
- if (IsUnassigned1252 (b))
- return $"holds byte 0x{b:X2}, which code page 1252 leaves undefined";
- }
-
- break;
- case InfoCharacterSet.Other:
- return $"is in code page {codePage}, which this library does not decode";
- }
-
- // 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.
- public static string Escape (string value)
- {
- var builder = new System.Text.StringBuilder (value.Length);
- foreach (var c in value) {
- if (c < '\u0020' || c is >= '\u007F' and <= '\u009F')
- builder.Append ("\\u").Append (((int)c).ToString ("X4", System.Globalization.CultureInfo.InvariantCulture));
- else
- builder.Append (c);
- }
-
- return builder.ToString ();
- }
}
diff --git a/src/TagLibSharp2/Riff/RiffInfoTag.cs b/src/TagLibSharp2/Riff/RiffInfoTag.cs
index 21b125f1..b974c182 100644
--- a/src/TagLibSharp2/Riff/RiffInfoTag.cs
+++ b/src/TagLibSharp2/Riff/RiffInfoTag.cs
@@ -29,7 +29,8 @@ namespace TagLibSharp2.Riff;
///
public class RiffInfoTag : Tag
{
- readonly Dictionary _fields = new (StringComparer.OrdinalIgnoreCase);
+ // The fields in the order a save writes them: as read, a changed value in its field's place, a new field last.
+ readonly OrderedMap _fields = new (StringComparer.OrdinalIgnoreCase);
///
/// The stored bytes of each field read from a file, and how surely their text is known (whether they are UTF-8,
@@ -63,16 +64,18 @@ public RiffInfoTag ()
///
/// Values are decoded as describes.
///
- /// Invariant on save: a value the caller did not change keeps its meaning under the file's CSET.
- /// Changed values are encoded in the file's declared code page when they all fit it (with no CSET,
+ /// Invariant on save: every value reads back as this reader returned it, and any value it can return can be
+ /// saved (#220). Changed values are encoded in the file's declared code page when they all fit it (with no CSET,
/// or one this library does not encode, only ASCII fits); unchanged values then keep their exact
- /// bytes and the CSET is kept as it is. When a changed value does not fit, the list becomes UTF-8
- /// 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. 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.
+ /// bytes and the CSET is kept as it is. When a changed value does not fit:
+ /// with no CSET and an unchanged value that is not UTF-8, or a CSET of a code page this library does not decode
+ /// (932, 1251, ...), where each field is read on its own (UTF-8, else Windows-1252), the list keeps every unchanged
+ /// value's bytes and writes the changed values by that rule, as WAV INFO does, and such a CSET is dropped; otherwise
+ /// (no CSET and only ASCII or UTF-8, or a code page this library decodes: 1252, 28591, 0) the list becomes UTF-8
+ /// under a CSET of code page 65001: ASCII and UTF-8 values keep their bytes, and every other
+ /// value is written as the UTF-8 of the text this reader returned for it, the same text when it was decoded exactly
+ /// (), the text read when a byte the code page leaves undefined made it a guess
+ /// ().
///
///
internal RiffInfoTag (InfoCharacterSet characterSet, int codePage = -1)
@@ -271,9 +274,7 @@ public void SetField (string fourCC, string? value)
_fields.Remove (fourCC);
_stored.Remove (fourCC);
} else {
-#pragma warning disable CS8601 // Possible null reference assignment - checked above
- _fields[fourCC] = value;
-#pragma warning restore CS8601
+ _fields.Set (fourCC, value!);
}
}
@@ -333,7 +334,7 @@ static bool IsFourCC (string name)
///
/// Gets all field identifiers present in this tag.
///
- public IEnumerable FieldIds => _fields.Keys;
+ public IEnumerable FieldIds => _fields.InOrder ().Select (entry => entry.Key);
///
/// Gets whether this tag has any fields.
@@ -418,7 +419,8 @@ public override void Clear ()
if (value.Length > 0)
tag._stored[fieldId] = (value, bytes, kind);
- tag._fields[fieldId] = value;
+ // A field read again keeps the first one's place and takes the last one's value.
+ tag._fields.Set (fieldId, value);
// Field size does not include the pad. Advance in long; a size near int.MaxValue must not throw.
var next = (long)offset + fieldSize + (fieldSize & 1);
@@ -442,11 +444,10 @@ internal bool SameFieldsAs (RiffInfoTag? other)
if (other._fields.Count != _fields.Count)
return false;
- using var mine = _fields.GetEnumerator ();
- using var theirs = other._fields.GetEnumerator ();
- while (mine.MoveNext () && theirs.MoveNext ()) {
- if (!string.Equals (mine.Current.Key, theirs.Current.Key, StringComparison.OrdinalIgnoreCase)
- || mine.Current.Value != theirs.Current.Value)
+ var mine = _fields.InOrder ();
+ var theirs = other._fields.InOrder ();
+ for (var i = 0; i < mine.Count; i++) {
+ if (!string.Equals (mine[i].Key, theirs[i].Key, StringComparison.OrdinalIgnoreCase) || mine[i].Value != theirs[i].Value)
return false;
}
@@ -458,66 +459,53 @@ bool IsUnchanged (string id, string value, out (string Value, byte[] Bytes, Info
///
/// 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 declared code page and an unchanged value's code page is a guess.
+ /// says what the save does with the file's CSET chunk.
///
- internal bool TryRenderAvi (out BinaryData list, out bool declareUtf8, out string? error)
+ internal BinaryData RenderAvi (out InfoCsetWrite cset)
{
- list = BinaryData.Empty;
- declareUtf8 = false;
- error = null;
+ cset = InfoCsetWrite.Keep;
if (!_avi)
throw new InvalidOperationException ("Not an AVI text mode tag.");
- var target = _characterSet;
- foreach (var kvp in _fields) {
- if (!IsUnchanged (kvp.Key, kvp.Value, out _) && !InfoText.CanEncode (kvp.Value, _characterSet)) {
- // Only a file not already in UTF-8 gets here: UTF-8 encodes every value.
- target = InfoCharacterSet.Utf8;
- declareUtf8 = true;
- break;
- }
+ var needsUtf8 = false;
+ var hasGuess = false;
+ foreach (var (id, value) in _fields.InOrder ()) {
+ if (!IsUnchanged (id, value, out var stored))
+ needsUtf8 |= !InfoText.CanEncode (value, _characterSet);
+ else
+ hasGuess |= stored.Kind == InfoTextKind.Guess;
}
- 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.";
- return false;
- }
- }
+ // Only a file not already in UTF-8 needs it: UTF-8 encodes every value.
+ if (!needsUtf8)
+ return RenderFields (_characterSet, keepStored: true);
+
+ // 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 && hasGuess)
+ return RenderFields (InfoCharacterSet.None, keepStored: true);
+
+ // A code page this library does not decode (932, 1251, ...) is read by that same rule already, so dropping its
+ // CSET changes nothing this library reads, and every unchanged value keeps its bytes (#220): a reader that
+ // decodes the code page itself still has the original bytes, where a rewrite would leave the UTF-8 of their
+ // misreading.
+ if (_characterSet == InfoCharacterSet.Other) {
+ cset = InfoCsetWrite.Drop;
+ return RenderFields (InfoCharacterSet.None, keepStored: true);
}
- list = RenderFields (target, keepStored: true);
- return true;
+ cset = InfoCsetWrite.Utf8;
+ return RenderFields (InfoCharacterSet.Utf8, keepStored: true);
}
///
- ///
- /// In AVI text mode this is the list writes. When that save would be
- /// refused, unchanged values keep their bytes and changed values are UTF-8; no CSET describes that list.
- ///
+ /// In AVI text mode this is the list writes.
public override BinaryData Render ()
{
if (_fields.Count == 0)
return BinaryData.Empty;
- if (!_avi)
- return RenderFields (InfoCharacterSet.None, keepStored: true);
- if (TryRenderAvi (out var list, out _, out _))
- return list;
- return RenderFields (InfoCharacterSet.Utf8, keepStored: true);
+ return _avi ? RenderAvi (out _) : RenderFields (InfoCharacterSet.None, keepStored: true);
}
BinaryData RenderFields (InfoCharacterSet target, bool keepStored)
@@ -527,17 +515,17 @@ BinaryData RenderFields (InfoCharacterSet target, bool keepStored)
var encodedFields = new List<(string Id, byte[] Bytes)> (_fields.Count);
var fieldsSize = 4; // "INFO" type
- foreach (var kvp in _fields) {
- if (string.IsNullOrEmpty (kvp.Key) || kvp.Key.Length != 4)
+ foreach (var (id, value) in _fields.InOrder ()) {
+ if (string.IsNullOrEmpty (id) || id.Length != 4)
continue;
- // An unchanged value keeps its bytes, except an exactly decoded legacy value in a list that
- // became UTF-8: that one is written as UTF-8 of the same text.
- var bytes = keepStored && IsUnchanged (kvp.Key, kvp.Value, out var stored)
- && !(stored.Kind == InfoTextKind.Exact && target == InfoCharacterSet.Utf8)
+ // An unchanged value keeps its bytes, except a legacy value (decoded exactly, or a guess) in a list that
+ // became UTF-8: that one is written as the UTF-8 of the text read (#220).
+ var bytes = keepStored && IsUnchanged (id, value, out var stored)
+ && !(stored.Kind is InfoTextKind.Exact or InfoTextKind.Guess && target == InfoCharacterSet.Utf8 && _characterSet != InfoCharacterSet.Utf8)
? stored.Bytes
- : _avi && target != InfoCharacterSet.None ? InfoText.Encode (kvp.Value, target) : InfoText.EncodeByReadRule (kvp.Value);
- encodedFields.Add ((kvp.Key, bytes));
+ : _avi && target != InfoCharacterSet.None ? InfoText.Encode (value, target) : InfoText.EncodeByReadRule (value);
+ encodedFields.Add ((id, bytes));
fieldsSize += 8 + bytes.Length + (bytes.Length & 1);
}
diff --git a/src/TagLibSharp2/Riff/WavFile.cs b/src/TagLibSharp2/Riff/WavFile.cs
index 5e74ef96..38fa814c 100644
--- a/src/TagLibSharp2/Riff/WavFile.cs
+++ b/src/TagLibSharp2/Riff/WavFile.cs
@@ -80,7 +80,15 @@ internal void MarkPicturesSkipped ()
/// Every LIST INFO is merged into this tag. The first list wins, and save writes exactly one INFO list.
/// Save writes that merged list at the end, not in its original position.
///
- public RiffInfoTag? InfoTag { get; set; }
+ public RiffInfoTag? InfoTag {
+ get => _infoTag;
+ set {
+ _infoTag = value;
+ _infoGone = false;
+ }
+ }
+
+ RiffInfoTag? _infoTag;
///
/// Gets or sets the ID3v2 tag.
@@ -93,7 +101,15 @@ internal void MarkPicturesSkipped ()
/// stays null. Assigning an , including new Id3v2Tag(),
/// replaces that unparsed chunk.
///
- public Id3v2Tag? Id3v2Tag { get; set; }
+ public Id3v2Tag? Id3v2Tag {
+ get => _id3v2Tag;
+ set {
+ _id3v2Tag = value;
+ _id3Gone = false;
+ }
+ }
+
+ Id3v2Tag? _id3v2Tag;
///
/// Gets or sets the BWF bext tag (Broadcast Wave Extension).
@@ -140,22 +156,99 @@ internal void MarkPicturesSkipped ()
///
///
- /// 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.
+ ///
+ /// A file with both an ID3v2 tag and a RIFF INFO list has a view over both, ID3v2 first: a get returns the ID3v2
+ /// value, else the INFO one, and a set or writes both, so ffprobe, ExifTool and MediaInfo,
+ /// which read both, show no stale copy (INFO holds one value per field and only its own fields; a field it cannot
+ /// hold is written to ID3v2 alone). A file with only one of them has that 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. A save writes no empty tag. After a
+ /// successful save over its source this view goes on without a tag the save emptied, as a fresh read of the saved
+ /// file holds none; and keep it, so a value set later through them is
+ /// written. The kept ID3v2 tag becomes a new ID3v2.4 tag, as a view creates one, and a view write that needs an
+ /// ID3v2 tag uses it. A save to another path changes neither.
+ ///
+ /// Null after .
///
- Tag? IMediaFile.Tag {
+ public Tag? 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));
+ var id3 = ViewId3;
+ var info = ViewInfo;
+ if (id3 is not null && info is not null)
+ return new CombinedTag (id3, info);
+ if (id3 is null && info is not null)
+ return info;
+ return CombinedTag.SingleOrView (id3, () => ViewId3,
+ _creation ??= new TagCreation (() => TakeGoneId3 () ?? new Id3v2Tag (), StoreCreatedId3));
+ }
+ }
+
+ // The tags a view shows: an emptied tag a save over the source did not write is held for a caller who holds it
+ // (review 2 B1) and written again once it holds a value, but the file holds no such tag, so the view goes on as a
+ // fresh read of that file does: without it, its first write creating an ID3v2 tag (review 1 N7).
+ Id3v2Tag? ViewId3 => _id3Gone && _id3v2Tag is { IsEmpty: true } ? null : _id3v2Tag;
+
+ RiffInfoTag? ViewInfo => _infoGone && _infoTag is { IsEmpty: true } ? null : _infoTag;
+
+ // Whether the source holds no tag of the instance held: set by a save over the source that wrote none, as the tag was
+ // empty; cleared by one that wrote it, and by an assignment. A save elsewhere leaves the source, and these, as they
+ // were (contract suite round 3, R2).
+ bool _id3Gone;
+ bool _infoGone;
+
+ // The ID3v2 tag a view write creates on a file that holds none: the hidden tag the object kept, when there is one, so
+ // a caller who holds it still holds the file's tag (review 3 B1). A save over the source already made it a new tag
+ // (ResetToNew), so it is what a fresh read's view creates.
+ Id3v2Tag? TakeGoneId3 ()
+ {
+ if (!_id3Gone || _id3v2Tag is not { IsEmpty: true } kept)
+ return null;
+ kept.ResetToNew ();
+ return kept;
+ }
+
+ // A view write that leaves the tag it created empty removes it (TagCreation); the hidden tag the object kept is hidden
+ // again instead, as the file still holds none.
+ void StoreCreatedId3 (Tag? tag)
+ {
+ if (tag is null && _id3v2Tag is { IsEmpty: true } && _id3Reused) {
+ _id3Gone = true;
+ return;
+ }
+
+ _id3Reused = tag is not null && ReferenceEquals (tag, _id3v2Tag) && _id3Gone;
+ Id3v2Tag = (Id3v2Tag?)tag;
+ }
+
+ bool _id3Reused;
+
+ FileWriteResult SettleEmptyTags (FileWriteResult result, string path, IFileSystem? fileSystem)
+ {
+ if (!result.IsSuccess
+ || (_id3v2Tag is not { IsEmpty: true } && _infoTag is not { IsEmpty: true } && !_id3Gone && !_infoGone)
+ || !SavedOverSource.HoldsFile (SourcePath, _sourceFileSystem, path, fileSystem ?? _sourceFileSystem))
+ return result;
+
+ _id3Gone = _id3v2Tag is { IsEmpty: true };
+ _infoGone = _infoTag is { IsEmpty: true };
+ // The empty tag replaced any id3 chunk the read could not parse; the file written holds none. The tag kept is now
+ // the one a view creates on that file, so its next value is written as a fresh read's would be (review 3 B1).
+ if (_id3Gone) {
+ _keepUnparsedId3 = false;
+ _id3v2Tag!.ResetToNew ();
}
+ return result;
}
+ async Task SettleEmptyTags (Task save, string path, IFileSystem? fileSystem) =>
+ SettleEmptyTags (await save.ConfigureAwait (false), path, fileSystem);
+
TagCreation? _creation;
///
@@ -706,9 +799,9 @@ public FileWriteResult SaveToFile (string path, IFileSystem? fileSystem = null)
return failure;
if (_skippedChunks.Count == 0)
- return SaveLoaded (path, fileSystem);
+ return SettleEmptyTags (SaveLoaded (path, fileSystem), path, fileSystem);
- return SaveFromSource (path, fileSystem, default);
+ return SettleEmptyTags (SaveFromSource (path, fileSystem, default), path, fileSystem);
} catch (Id3v2TagTooLargeException tooLarge) {
return FileWriteResult.Failure (tooLarge.Message);
}
@@ -736,10 +829,10 @@ public Task SaveToFileAsync (
return Task.FromResult (failure);
if (_skippedChunks.Count == 0)
- return SaveLoadedAsync (path, fileSystem, cancellationToken);
+ return SettleEmptyTags (SaveLoadedAsync (path, fileSystem, cancellationToken), path, fileSystem);
// Length and "was not loaded" are decided before the token, matching the sync save.
- return Task.FromResult (SaveFromSource (path, fileSystem, cancellationToken));
+ return Task.FromResult (SettleEmptyTags (SaveFromSource (path, fileSystem, cancellationToken), path, fileSystem));
} catch (Id3v2TagTooLargeException tooLarge) {
return Task.FromResult (FileWriteResult.Failure (tooLarge.Message));
}
@@ -1112,6 +1205,33 @@ public WavSavePiece (string fourCC, byte[]? inline, int skippedIndex, long size)
public long Size { get; }
}
+ ///
+ /// Saves the WAV file back to its source path.
+ ///
+ ///
+ /// This convenience method saves the file back to the path it was read from, through the file system it was read
+ /// with unless is given, as does.
+ /// Requires that the file was read using or
+ /// .
+ ///
+ /// Optional file system abstraction.
+ /// The write result.
+ public FileWriteResult SaveToFile (IFileSystem? fileSystem = null)
+ {
+ // A tag a save renders that is too large for its size field fails the save, never throws (#275).
+ try {
+ if (PictureSkip.Refuse (this, Id3v2Tag) is { } denied)
+ return denied;
+ if (string.IsNullOrEmpty (SourcePath))
+ return FileWriteResult.Failure ("No source path available. File was not read from disk.");
+
+ var fs = fileSystem ?? _sourceFileSystem;
+ return SaveToFile (SourcePath!, fs);
+ } catch (Id3v2TagTooLargeException tooLarge) {
+ return FileWriteResult.Failure (tooLarge.Message);
+ }
+ }
+
///
/// Saves the WAV file back to its source path asynchronously.
///
diff --git a/src/TagLibSharp2/WavPack/WavPackFile.cs b/src/TagLibSharp2/WavPack/WavPackFile.cs
index f6138a0c..abdc251e 100644
--- a/src/TagLibSharp2/WavPack/WavPackFile.cs
+++ b/src/TagLibSharp2/WavPack/WavPackFile.cs
@@ -800,6 +800,20 @@ private static int ParseMultiChannelCount (ReadOnlySpan data)
byte[] ApeTagBytes () => ApeTag.RenderForSave (ApeTag, _readApeTag, defaultHeader: false).ToArray ();
+ // A save writes no APE tag that holds nothing (#258). After a successful one over the source the file holds no tag,
+ // so the tag the object holds, kept for a caller who holds it (review 2 B1), is no longer the tag read: a value set
+ // next is written with the layout of a tag this file did not read (footer only), as a fresh read's view writes it.
+ // After a save elsewhere the object still describes its source, whose tag it emptied, and keeps the read layout
+ // (contract suite round 3, R1).
+ FileWriteResult Saved (FileWriteResult result, string path, IFileSystem? fileSystem)
+ {
+ if (result.IsSuccess && ApeTag is { StoresNothing: true } && _readApeTag is not null
+ && SavedOverSource.HoldsFile (SourcePath, _sourceFileSystem ?? fileSystem, path, fileSystem))
+ _readApeTag = null;
+
+ return Source.Saved (result);
+ }
+
///
/// Ensures an APE tag exists, creating one if necessary.
///
@@ -888,7 +902,7 @@ public FileWriteResult SaveToFile (string path, ReadOnlySpan originalData,
var fs = fileSystem ?? _sourceFileSystem ?? DefaultFileSystem.Instance;
var rendered = Render (originalData);
- return Source.Saved (AtomicFileWriter.Write (path, rendered, fs));
+ return Saved (AtomicFileWriter.Write (path, rendered, fs), path, fs);
}
///
@@ -910,7 +924,7 @@ public FileWriteResult SaveToFile (string path, IFileSystem? fileSystem = null)
return FileWriteResult.Failure ("No source path available. File was not read from disk.");
var tag = ApeTagBytes ();
- return Source.Saved (ApeTagLocation.WriteFromSource (SourcePath, path, fs, tag));
+ return Saved (ApeTagLocation.WriteFromSource (SourcePath, path, fs, tag), path, fs);
}
///
@@ -951,7 +965,7 @@ public async Task SaveToFileAsync (
var fs = fileSystem ?? _sourceFileSystem ?? DefaultFileSystem.Instance;
var rendered = Render (originalData.Span);
- return Source.Saved (await AtomicFileWriter.WriteAsync (path, rendered, fs, cancellationToken).ConfigureAwait (false));
+ return Saved (await AtomicFileWriter.WriteAsync (path, rendered, fs, cancellationToken).ConfigureAwait (false), path, fs);
}
///
@@ -977,7 +991,7 @@ public Task SaveToFileAsync (
return Task.FromResult (FileWriteResult.Failure ("No source path available. File was not read from disk."));
var tag = ApeTagBytes ();
- return Task.FromResult (Source.Saved (ApeTagLocation.WriteFromSource (SourcePath, path, fs, tag, cancellationToken)));
+ return Task.FromResult (Saved (ApeTagLocation.WriteFromSource (SourcePath, path, fs, tag, cancellationToken), path, fs));
}
///
diff --git a/tests/TagLibSharp2.Tests/Ape/ApeEmptyTagTests.cs b/tests/TagLibSharp2.Tests/Ape/ApeEmptyTagTests.cs
new file mode 100644
index 00000000..47ae0927
--- /dev/null
+++ b/tests/TagLibSharp2.Tests/Ape/ApeEmptyTagTests.cs
@@ -0,0 +1,100 @@
+// 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.Ape;
+
+///
+/// A save writes no APE tag that holds no item (#258): Clear on a file with no tag writes no tag, Clear on a tagged file
+/// removes the tag, and an emptied tag is gone from the object after the save, as from a fresh read of the saved file.
+/// Every APE carrier: Monkey's Audio, WavPack, Musepack and raw AAC.
+///
+[TestClass]
+[TestCategory ("Unit")]
+[TestCategory ("Ape")]
+public class ApeEmptyTagTests
+{
+ static readonly string[] Carriers = [".ape", ".wv", ".mpc", ".aac"];
+ static readonly string[] Starts = ["tagless", "footer", "header"];
+ static readonly string[] Seconds = ["noop", "title", "clear"];
+
+ public static IEnumerable