diff --git a/CHANGELOG.md b/CHANGELOG.md index 938c3575..72726dec 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -116,6 +116,34 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed +- 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. +- An Ogg Opus, Vorbis or FLAC file whose last pages have a granule position of −1 now reads with its duration (#185). RFC 3533 §6: "A special value of -1 (in two's complement) indicates that no packets finish on this page"; the −1 is that page's, not the stream's. The duration came from the header pages' granule, 0. It now comes from the last page whose granule is not −1 that starts within the last 130,614 bytes (two maximum pages), the same on every entry point, with the Opus pre-skip still applied; past that bound the duration is unknown, so a tail of junk or of −1 pages never makes a read scan the whole file. ffprobe and mutagen step back the same way (2.0 s and 0.998 s for the crafted Opus and Vorbis files). A stream or path read of Opus or Vorbis no longer appends the file's last page to the header pages it parses: in a damaged file whose comment packet is cut at the end of its header pages, that page ran into the packet and the read failed ("Invalid field 1 length") where `ReadFromData` read the file; every entry point now reads it as `ReadFromData` does. +- A save of an Ogg Opus, Vorbis or FLAC file writes the bytes after its last whole page as they were (#215): a last page the end of the file cuts short, as a truncated download leaves, and bytes that are no page. A save dropped them, so a truncated file lost its last page and its duration (2.0 s read 1.0 s after a save). When a page cut short follows, the last whole page is not marked as the end of the stream, as in the source. A readable page after such bytes still fails the save (#199). +- A save of an Ogg Opus, Vorbis or FLAC file carries every audio page across, or fails with "Failed to render Ogg Opus file" (or Vorbis, or FLAC) and writes nothing (#199). An Opus file whose tags page was broken read its duration, and a save with no edit reported success and wrote the two header pages without the audio; an Ogg FLAC file did the same, and an Ogg Vorbis file refused. One rule now decides for all three on every save entry point: the save fails when its page walk stops at bytes that are no page and a readable page follows them, or when the page the duration comes from lies among the header pages (a header page whose declared body runs over the audio pages). A header packet cut off at the end of the file, which Vorbis refused, is now refused by Opus and Ogg FLAC too: the header walk tells when it reaches the end of the file inside a page or with a packet open before its header packets are done, and the save fails. An Opus file of OpusHead and a tags packet cut at the end saved as OpusHead and a rebuilt tags page, dropping the cut bytes. +- An Ogg Opus or Vorbis file with the end-of-stream flag on a header page now reads the same duration on every entry point (#190). RFC 3533 §6 sets the flag on "the last page of a logical bitstream"; the scan that reads the granule preferred a page with the flag, and on a header page that made the duration the header's 0 on a full read, while a `SkipPictures` read, which rebuilds the header pages without the flag, read the audio page's granule (2.0 s for the crafted file, as ffprobe reads it). The flag no longer picks the granule. +- An ASF file whose Header Object count is short of the objects it holds now reads them all, and a save carries each of them across byte for byte (#200). The walk stopped at the count, so the read did not see the objects after it and a save dropped them (a file with a count of 1 saved 19,384 of its 19,744 bytes). The header's objects are now the ones that fill its declared size, whatever the count says, on every entry point; a read of the bytes no longer walks past the header's end. A save of a header whose objects do not fill it whole (its size cuts the last object short, or leaves bytes that are no object) fails with "Cannot save an ASF file whose header objects do not fill its header." and writes nothing, where it dropped those bytes or wrote them twice. +- An Ogg Opus, Vorbis or FLAC file whose last page has no segments now reads with its duration, and a save keeps that page (#189). RFC 3533 §6 lets a page hold no packets; an end-of-stream page that only carries the final granule is 27 bytes. The scan that reads the granule stopped one byte before a page of exactly that length at the end of the file, and the duration was 0 on every entry point (ffprobe reads 2.0 s for the crafted Opus, Vorbis and FLAC files); a save's page copy stopped at the same byte and dropped the page. In an Ogg FLAC file the header read also took such a page for a header page when it came right after the headers, so a save of a file with no audio page dropped it; a page with no packets after every header packet the first packet declares is now the stream's. A first packet that declares the count unknown (0) cannot tell, and such a page stays with the headers. +- The ASF header walk now reads an object of only its 24-byte header that ends the header data (#189). The walk (`AsfFile.MoreObjects`, which the read and the `SkipPictures` copy share, and which the render's own walk now uses) stopped one byte short of it, the 24-byte twin of the 27-byte Ogg page above. +- An Ogg FLAC file made by ffmpeg now reads with its duration (#184). ffmpeg writes STREAMINFO total samples = 0, which RFC 9639 §8.2 defines as unknown, and the file read with a duration of 0 and with its sample rate, channels and bits per sample all 0. The duration now comes from the last granule position when STREAMINFO has no total, as for Ogg Vorbis and Opus, on every entry point; the other properties are STREAMINFO's even when the duration is unknown. ffprobe, MediaInfo and mutagen read 2.0 s for a 2-second ffmpeg file. +- An ASF file whose preroll is so long that it wraps 64 bits in 100 ns units no longer reads with a duration (#193). The duration is the Play Duration (100 ns units) less the Preroll (ms); the preroll was scaled to 100 ns in unchecked 64-bit arithmetic, so a preroll of 1,844,674,407,370,956 ms became 8,384 ticks, and a file whose preroll is past its 51.42 s play duration read 51.42 s, not 0. A preroll at or past the play duration is now compared in ms first, and the duration is 0. +- A bit rate too large for an `int` now reads 0 (#198). A bit rate worked out from a file's size over its duration, or from a sample rate, bits and channels, was a real number cast to `int`: it read 2,147,483,647 where the cast saturates (.NET 9 and later) and wrapped before (a 6 MB Opus file whose duration is one sample read 2,147,483,647 kbps). `AudioProperties.FromFlac`, `FromOpus`, `FromDsf` and `FromDff`, Ogg FLAC, Opus, WavPack, Monkey's Audio, Musepack, AAC and MPEG audio now take #194's rule. Matroska's sampling frequency, channels and bit depth past an `int` read 0 too, and a stored value too large is no longer taken for an absent one. A Matroska `SamplingFrequency` (a float) is now rounded to the nearest hertz, as the other real-valued rates are: a stored 22,050.7 Hz reads 22,051, where it read 22,050. +- An AIFF or WAV file saved over its source, edited and saved again from the same object now writes what a fresh read of the file on disk writes (#212). A save copies the sound from the source at the offset the read found it; when a chunk ahead of the sound changed size on the first save (an edited AIFF NAME, a WAV LIST INFO before the data, each of which the edit writes after the sound), the sound moved, and the second save copied other bytes in its place (AIFF, reporting success) or failed (WAV). After a save over the source the file takes the offsets the save wrote the sound at, once a read of the source back confirms the source is the file it wrote. A save elsewhere keeps the offsets of the read. MP4, Matroska, AVI, ASF, Audible, DSF and DSDIFF were checked the same way and needed nothing; MP3, FLAC, AAC and MPEG-PS take their offsets after such a save since #179. +- A WAV save to a path copies a chunk of any size from the source, as an AIFF save copies its sound (#197), where it failed with "Cannot save a WAV file whose sample data does not fit in memory." for a chunk past 2 GB (#203). A WAV file of more than 2 GB, such as one whose data chunk holds 2 GB of samples or ends with the 0xFFFFFFFF size a streamed writer leaves, now saves from a path read, to a new path or over the source, sync and async, and the samples are streamed in 64 KB pieces, never held in memory. A save whose RIFF would pass its 32-bit size fails with "Cannot save a WAV file larger than its 32-bit RIFF size." and writes nothing. A save from memory still needs the samples to fit in memory. +- An AIFF save no longer throws, and refuses a file it cannot write whole (#196). A save of a new `AiffFile ()`, which has read nothing, threw `InvalidOperationException` ("Cannot render invalid AIFF file"); it now fails with "Cannot save an invalid AIFF file." A file with no valid `COMM` chunk, such as one whose FORM size of 0 ends the form before its chunks, saved "successfully" as its 12-byte FORM header; it now fails with "Cannot save an AIFF file that has no valid COMM chunk." A save from memory of chunks past 2 GB fails with "Cannot save an AIFF file larger than supported memory." where it threw. Each writes nothing. No save throws on malformed input. +- A sample rate past `int.MaxValue` no longer reads as a negative sample rate, and a WAV byte rate past it no longer gives a negative or zero bit rate (#194). WAV, DSF, DSDIFF, Monkey's Audio and ASF store the sample rate as an unsigned 32-bit field, MP4 as a 32-bit timescale, ALAC in its magic cookie, and AIFF as an 80-bit real; the readers cast it to `int`, so 2^31 Hz read as −2,147,483,648 (AIFF's real saturated at 2,147,483,647). It now reads as no sample rate (0), as WavPack's reader already ruled, and the WAV bit rate is the byte rate times 8 in 64 bits. DSF's 32-bit channel count, bits per sample and block size follow the same rule, and a DSF or DSDIFF bit rate (sample rate times channels) past an `int` is 0 where it used to wrap. A WAV file without a sample rate, which `Render` refuses with `InvalidOperationException`, now fails a save with a result and writes nothing; `SaveToFile` and `SaveToFileAsync` used to throw. +- An AIFF file now reads the same from memory as from a stream when its FORM size is smaller than the file or a chunk's size runs past its bytes (#197). A read of bytes in memory ignored the FORM size and dropped a chunk that ran past the data or past `int.MaxValue`: a FORM size of 0, 4 or 12 read 2.0 s from memory and no audio properties from a stream (ffprobe rejects such a file). Both reads now keep every chunk by the rule WAV uses (#192): its bytes present, up to its size and never past the FORM's end. `AiffChunk.TryParse` keeps a chunk whose size runs past the data, with its size and the bytes present, where it returned false. A save writes such a chunk with the size of the bytes it holds, as a WAV save does, and sizes the file by those bytes: a few hundred bytes that declared a chunk of 256 MB made a save allocate 512 MB, and a chunk header that kept the declared size swallowed the ID3 chunk written after it. A file with an SSND size of 0xFFFFFFFF, the placeholder a streamed writer leaves, or a COMM size that runs into the next chunk now saves from a path read, where `SaveToFile` and `SaveToFileAsync` threw `InvalidOperationException` ("Cannot render an AIFF file larger than supported memory."). A save copies an SSND of any size from the source: one of more than 2 GB, such as the sound of a 2.28 GB file, was left in the file without being recorded, so a save wrote it as an empty chunk and reported success, and a save over the source destroyed the file (main threw instead). A save whose FORM would pass its 32-bit size fails with "Cannot save an AIFF file larger than its 32-bit FORM size." and writes nothing. Bytes after the FORM are written after it by a save as they were, as a WAV save writes the bytes after its RIFF form (#192): a FORM size short of the sound lost the sound past it. An ID3v2.2, v2.3 or v2.4 chunk right after the FORM (`ID3 `, or `id3 `) is read as the file's tag when the FORM has none, on every entry point, as exiftool reads it, so a save writes the tag in the FORM and no stale copy stays after it; more such chunks are superseded and kept by the rule a WAV file's are (#192). taglib-samples' sample.aif, whose ID3 chunk follows the FORM's declared end, lost it on a save with no edit (177,704 bytes to 176,454); its ID3v2.2 tag is now read on every entry point and written in the FORM as ID3v2.3 (#187), with its title, artist, album and other fields. +- A WAV file whose data chunk has a size past `int.MaxValue`, such as the 0xFFFFFFFF ffmpeg writes to a pipe, now reads the same from memory as from a stream (#192). `MediaFile.ReadFromData`, `WavFile.Read` and `WavFile.ReadFromFile` stopped at the chunk and lost it, so the duration was 0 and a save was refused for having no data chunk; a stream or path read kept the samples present and read their duration (2.12 s for the crafted file, as ffprobe reads it). Both reads now keep every chunk by one rule: its bytes present, up to its size and never past the end of the RIFF form, so bytes after the form are not samples and a `LIST` or `fmt ` chunk whose size is past `int.MaxValue` is read from the bytes present on every entry point (a stream read used to keep it empty, so a `LIST INFO` title was lost; ffprobe reads it). A save from any read writes the samples with the size of the bytes present. Bytes after the RIFF form are written after the form by a save as they were: a save dropped them (bytes that are no chunk, or the samples past a RIFF size short of them). An `id3 ` chunk (or `ID3 `) with an ID3v2.2, v2.3 or v2.4 tag that a tagger appended right after the form, which exiftool and ffprobe read, is read as the file's tag when the form has none, on every entry point, so a save writes the tag in the form and no stale copy stays after it for another reader to show. More such chunks right after it, or right after a form that has its own tag, are superseded: a save that writes the tag other than as it was read (an edit, or removing it) drops them, so ffprobe shows no old title beside the new one, and a save that leaves the tag as read writes them as they were. Every other byte after the form is written as it was: a tag chunk cut short or declaring more than the file holds (ffprobe still shows its title beside a new one), one not right after the form or a tag, and one whose ID3v2 header is followed by no field, which a save dropped. +- A WavPack file whose first block declares a size too small to hold the 32-byte block header now reads with unknown properties on every entry point (#201). The size counts the block after its first 8 bytes, and the header takes 24 of them; a stream or path read took the 8 bytes a smaller size named, and the bytes after them (the APE tag) for the block header, and read 2 days 20 hours at 6,000 Hz, or failed when no tag followed, while a read of the bytes read the header as a block. Such a size is no block: its header fields are not read, and a save keeps the audio. +- A WavPack file whose header gives a total sample count of 0xFFFFFFFF now reads as having no count and an unknown duration (#191). The WavPack file format says of the version 4 block header's total_samples that it "is only valid if block_index == 0 and a value of -1 indicates unknown length". We read it as a count, a fake 27 hours at 44.1 kHz, and `TotalSamples` was 4,294,967,295; ffprobe reports N/A. `TotalSamples` is now 0 and the file reads as one whose header gives 0. The version 3 header inside RIFF/WAVE, which that document does not describe, reads 0xFFFFFFFF the same way for a reason of its own: the reader already takes a data size with bit 31 set as an unknown length in versions 1 and 2, and it reads the version 3 count by that rule rather than as 27 hours. +- The MP4 duration that means unknown, and an ASF file's Play Duration while the Broadcast Flag is set, now read as unknown (#183). ISO 14496-12 §8.2.2.3 and §8.4.2.3: "If the duration cannot be determined then duration is set to all 1s" in `mvhd` and `mdhd`; we read 2^32 − 1 (version 0) as a real duration, 49.7 days at a timescale of 1000, and 2^64 − 1 (version 1) as one too. The ASF Specification says the File Properties Object's Play Duration "is invalid if the Broadcast Flag bit in the Flags field is set to 1"; we read it regardless. ffprobe reports the MP4 marker as N/A and ignores the ASF header duration. The movie duration MP4 chapters take as their end follows the same rule. New: `AsfFileProperties.IsBroadcast`. +- A DSDIFF file whose `DSD ` chunk is 2^61 bytes or more no longer reads with a wrapped duration (#182). The sample count was the chunk size times 8 over the channels in unchecked 64-bit arithmetic: a chunk of 2^61 + 16 bytes read as 22.6 µs. It is now worked out without wrapping (`DffFile.SampleCount` is 2^63 + 64 there), and the duration, 3.3e12 s, is unknown as in #181. A count of samples past 64 bits is 0. +- A duration that a `TimeSpan` cannot hold now reads as unknown in every format (#181): `TimeSpan.Zero` on the `Duration` properties that are not nullable, and null on the nullable ones (`MatroskaFile.Duration`). MP4, DSDIFF, DSF, Opus, Ogg Vorbis, Monkey's Audio and Musepack reported `TimeSpan.MaxValue`, to which adding anything throws, and an ASF Play Duration of 2^63 ticks or more (100-ns units) read as a negative duration. No format spec sets a maximum, and ffprobe reports such a duration as N/A. Every reader but Audible's now takes its duration through one rule (Audible's sizes are 32-bit, so its duration fits a `TimeSpan` at any bit rate); AVI's bound moves from half of `TimeSpan.MaxValue` to `TimeSpan.MaxValue`. +- A FLAC save no longer drops bytes a metadata block holds (#204). A save writes the first STREAMINFO, SEEKTABLE, APPLICATION and the reserved block types (7 to 126) as they are, the comment, pictures and cue sheet from what it parsed of them, and fresh padding, then copies every byte after the last block it read. A block whose bytes that does not write back was lost: a VORBIS_COMMENT length grown from 35 to 255 took in the first 220 bytes of the audio, past its last comment, and a save dropped them. Such a save now fails with "Cannot save a FLAC file with a metadata block whose bytes the save would not write back." and writes nothing, from the bytes and from a path, and `Render` returns no bytes: a comment, picture or cue sheet with bytes past its contents or that does not parse, a second STREAMINFO, comment or cue sheet, or padding that holds a byte that is not zero and does not end where a block header, a frame or the end of the file begins, since its length grew into the block or the audio after it. Nothing else is refused: stray bytes in padding are replaced by fresh padding, and a file whose last block runs past its end, whose blocks are not flagged last, or whose audio does not start with a frame saves with every byte, and a block that runs past the end of the file keeps its header, which a save dropped. A block of a reserved type is now written back as it is, where a save dropped it. +- An ID3v2.4 tag whose footer flag is set with no footer after it no longer takes the 10 bytes after its body (#202). The reader counted the footer from the flag alone, so those bytes were not the audio's, and a save dropped them: an MP3, AAC or MPEG-PS file lost the first 10 bytes of its audio. ID3v2.4 §3.4 makes the footer a copy of the header whose identifier is "3DI"; a footer now counts only when that "3DI" is there, on every reader that finds where a tag ends: the tag read, the copy a `SkipPictures` read makes, AAC's audio start and detection, and MPEG-PS's tag length. A tag with a real footer reads as before. +- A path save after a save over the source now writes what a fresh read of the file on disk, given the same edit, writes (#179). Each save reads the file the save before it left on disk. MP3, FLAC, AAC and untagged DSF files applied the offsets of the first read to it and reported success: an MP3 lost audio and its duration changed, a FLAC file kept old metadata in front of its audio, an AAC file got a wrong stream extent and, from the third save on, no duration, and an untagged DSF file that was given a tag kept that tag as sound. PNG, JPEG and GIF files planned the edit against the bytes they read and copied from the file on disk: the second save wrote an unreadable JPEG, a GIF without its comment and a PNG whose chunks no longer reach IEND. MPEG-PS refused the second save in place. MP3, FLAC, AAC, MPEG-PS, PNG, JPEG and GIF files now take the layout of the file a save wrote over their source, by path or by span and under any spelling of the path; the source is read back after the save to tell. A span save from the bytes of that file works, and one from the bytes they read now fails with a message that names the file they last saved over their source (Audible's message, which said it was the file read, now says so too). A DSF file keeps its sound where the read found it, so it describes every file it saves; a path save from a source that ends before that sound fails with the message `Render` gives. A path save of an MP3, FLAC or AAC file whose source is no longer of a length the object describes now fails and writes nothing. A known limit, filed as #195: an MP3 or AAC file with two tags of one kind stacked (two ID3v2 tags in front, or two ID3v1 tags at the end). A read takes the outer tag and leaves the inner one in the audio, as before; a save that drops the outer tag uncovers the inner one, which a fresh read of the saved file takes as its tag and this object does not, so a later save of the object keeps the inner tag in front of the tag it writes. No audio is lost. +- `Mp3File.Id3v1Tag = null` followed by a save now removes the ID3v1 tag; its 128 bytes used to stay at the end of the file as audio, and a read of the saved file still found the tag. Giving a file without an ID3v1 tag one no longer drops the last 128 bytes of its audio. The audio ends at the ID3v1 tag of the file, not at the one the object holds. - A save of a Monkey's Audio, WavPack or Musepack file no longer drops the APEv2 tag's 32-byte header and clears the footer's "has header" flag (#217). The tag read from the file is written back the way it was read: with a header when it had one, footer-only when it had none, so a save with no edit keeps the tag's layout and the file's size. Any other tag, a new one or one parsed elsewhere and assigned, gets the format's layout, as before: footer-only in these formats, a header in raw AAC. `ApeTag.Render ()` writes a parsed tag with the header it was read with, and a new one without; `RenderWithOptions` is unchanged. Items are still written in order of size, as before. - An APEv2 footer that claims a header (bit 31) with no `APETAGEX` in front of its items reads the same from a path or stream as from bytes (#240). The stream tag read of Monkey's Audio, WavPack and Musepack and the MPEG-PS trailer search took the claim at its word: a small Musepack file read no tag from a path, a small Monkey's Audio file read a bitrate of 0, and an MPEG-PS file did not find an ID3v2 tag appended before such an APE tag. Every reader now counts a header only when those bytes are there, as the bytes read already did. - A path save of a Monkey's Audio, WavPack or Musepack file whose APEv2 tag is followed by Lyrics3 v2 and ID3v1 no longer keeps the old tag in front of the new one (#241). When the first read from the end held LYRICSBEGIN but only part of the APE footer in front of it, the save did not read further, kept the old tag as audio and grew the file by its size. It now reads the footer, and writes what `Render` writes. @@ -136,9 +164,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - A single ID3v2 name that contains a slash, such as `AC/DC`, was split into two values - Matroska `Album` reads the untargeted `ALBUM` tag that ffmpeg writes when there is no `TITLE` at target 50 (it was null). Setting the album updates that `ALBUM`, and a target-50 `TITLE` beside it, instead of adding a `TITLE` - APE and MP4: a picture whose role is `Other`, or any role without its own key, came back as a front cover after a save -- `SaveToFile (path, span)` and `SaveToFileAsync (path, memory)` of DSF, DFF, FLAC, Ogg Vorbis, Opus, Ogg FLAC, MP3, AAC, Monkey's Audio, Musepack, WavPack, AVI, Audible, ASF and MPEG-PS files now fail and write nothing when the bytes passed in are not a file the object describes (#178). These saves take the payload from those bytes. Most of them used to report success and write whatever part of the payload the bytes held: an empty span wrote an empty ASF file, a DFF file with no sound, and an MP3, AAC, Monkey's Audio, Musepack or WavPack file of its tags alone. An object describes the file it was read from. Ogg Vorbis, Opus, Ogg FLAC, Monkey's Audio, Musepack, WavPack, AVI, ASF, DSF and DFF also describe each file they save, so a save from the bytes of an earlier save works as before; a DSF file that had no ID3 tag and was saved with one is the exception. Audible describes the file it saved over its source in place of the one it read. MP3, FLAC, AAC and MPEG-PS keep the offsets of the file they read, so a save from the bytes of an earlier save now fails: MP3, FLAC and AAC used to write a damaged file there (an MP3 lost audio), and MPEG-PS refused it with its own message, which is now this one. The check compares lengths, so another file of the same length passes. A DSF or DFF file read from memory holds its bytes and saves them, whatever bytes are passed. `Render (span)` is unchanged. MP4 and Matroska are unchanged too: their save parses the bytes it is given as a file of its own, and rejects bytes it cannot rewrite. +- `SaveToFile (path, span)` and `SaveToFileAsync (path, memory)` of DSF, DFF, FLAC, Ogg Vorbis, Opus, Ogg FLAC, MP3, AAC, Monkey's Audio, Musepack, WavPack, AVI, Audible, ASF and MPEG-PS files now fail and write nothing when the bytes passed in are not a file the object describes (#178). These saves take the payload from those bytes. Most of them used to report success and write whatever part of the payload the bytes held: an empty span wrote an empty ASF file, a DFF file with no sound, and an MP3, AAC, Monkey's Audio, Musepack or WavPack file of its tags alone. An object describes the file it was read from. Ogg Vorbis, Opus, Ogg FLAC, Monkey's Audio, Musepack, WavPack, AVI, ASF, DSF and DFF also describe each file they save, so a save from the bytes of an earlier save works as before. MP3, FLAC, AAC, MPEG-PS and Audible describe one file: the one they read, or the one they last saved over their source (#179). A save from the bytes of a file they saved elsewhere now fails: MP3, FLAC and AAC used to write a damaged file there (an MP3 lost audio), and MPEG-PS refused it with its own message, which is now this one. The check compares lengths, so another file of the same length passes. A DSF or DFF file read from memory holds its bytes and saves them, whatever bytes are passed. `Render (span)` is unchanged. MP4 and Matroska are unchanged too: their save parses the bytes it is given as a file of its own, and rejects bytes it cannot rewrite. - `DsfFile.Render` and `DffFile.Render` work after a path read (#176). The read leaves the sound on disk, and `Render` used to throw: `ArgumentNullException` from inside the DSF render, `InvalidOperationException` ("no original data available") from the DFF one. `Render` now reads the source file, as a path save does, and returns the same bytes the save writes. After a stream read, which keeps no source, or when the source can no longer be read, `Render` throws `InvalidOperationException` and says why. The render holds the source once, beside its result. A DSF save from a span that ends before the sound the read found now returns a failure result and writes nothing, instead of throwing `ArgumentException` from `Array.Copy`. -- `MediaFile.ReadFromData` and `OggOpusFile.Read` no longer throw `OverflowException` on a malformed Opus file (#175). The read of bytes in memory took the granule position from any end-of-stream page in the file. A stream or path read takes it from the header pages and the last page. All entry points now take it from the header and last pages, for Opus and Ogg Vorbis, so they report the same duration. A sample count whose duration does not fit a `TimeSpan` now reports `TimeSpan.MaxValue`, as MP4 and DSDIFF already did, instead of throwing. That covers `AudioProperties.FromOpus`, `FromVorbis` and `FromFlac`, Ogg FLAC, Monkey's Audio, Musepack and DSF. +- `MediaFile.ReadFromData` and `OggOpusFile.Read` no longer throw `OverflowException` on a malformed Opus file (#175). The read of bytes in memory took the granule position from any end-of-stream page in the file. A stream or path read takes it from the header pages and the last page. All entry points now take it from the header and last pages, for Opus and Ogg Vorbis, so they report the same duration. A sample count whose duration does not fit a `TimeSpan` no longer throws; it reads as unknown (#181). That covers `AudioProperties.FromOpus`, `FromVorbis` and `FromFlac`, Ogg FLAC, Monkey's Audio, Musepack and DSF. - An MP4 file with container boxes nested thousands deep no longer ends the process with a stack overflow, or runs out of memory first (#174). The box parser, the chunk-offset walk of a save and its track-layout walk still recurse into each container, but now stop at 32 levels; a container nested deeper is kept as its bytes and saved as it was read. A parsed box no longer copies its payload: it is a view of the bytes the top box was copied into, copied only when `Mp4Box.Data` is read. - `MediaFile.Read` of a DSDIFF (`.dff`) path or stream no longer hangs on a chunk whose 64-bit size does not fit the file (#177). A size of 2^64 − 12 or 2^64 − 13 used to wrap the chunk end back onto the chunk, and a `DSD ` or `DST ` chunk of that size also grew memory on every pass. The size is now compared with the bytes left before it is added, so such a chunk ends the walk at the end of the file. The stream read now also keeps each `DSD `/`DST ` chunk in its place, so it reads what `ReadFromData` and `DffFile.Read` read when a chunk after the sound runs past the file or a second sound chunk is present. - A path save that is cancelled while it writes the temp file no longer leaves that temp file beside the destination; the save fails with "Operation was cancelled" and the destination is left as it was. diff --git a/src/TagLibSharp2/Aac/AacFile.cs b/src/TagLibSharp2/Aac/AacFile.cs index d8c4736d..9c567298 100644 --- a/src/TagLibSharp2/Aac/AacFile.cs +++ b/src/TagLibSharp2/Aac/AacFile.cs @@ -68,6 +68,10 @@ internal void MarkPicturesSkipped () // as ffmpeg writes it; some readers (mediainfo) find the tag only through the header. ApeTag? _readApeTag; + // The layout the file holds for _readApeTag after a save over the source wrote it; null after a read, where the + // tag's own read layout is the file's. + bool? _readApeHeader; + AacFile () { } @@ -93,7 +97,8 @@ internal void MarkPicturesSkipped () public Id3v1Tag? Id3v1Tag { get; set; } /// - /// Gets the size in bytes of the ID3v2 tag that was read (0 if none). + /// Gets the size in bytes of the ID3v2 tag of the file the object describes (0 if none): the one it read or, after + /// a save over its source, the one that save wrote. /// public int Id3v2Size { get; private set; } @@ -220,7 +225,8 @@ static AacFileReadResult ReadSeekable (Stream stream, ReadOnlyMemory bytes var prefix = StreamBytes.ReadAtMost (stream, Id3v2Header.HeaderSize); var header = Id3v2Header.Read (prefix); if (header.IsSuccess) { - audioStart = Math.Min ((long)header.Header.TotalSize, length); + // The audio starts after the tag, and after its footer only when one is there (#202). + audioStart = Math.Min ((long)header.Header.TotalSizeIn (stream, 0), length); stream.Position = 0; var tag = options.SkipPictures ? Id3v2Tag.ReadWithoutPictures (stream, audioStart) @@ -251,6 +257,7 @@ void TakeTags (AacTail tail) { ApeTag = tail.ApeTag; _readApeTag = tail.ApeTag; + _readApeHeader = null; Id3v1Tag = tail.Id3v1Tag; } @@ -363,8 +370,8 @@ public static bool IsValidFormat (ReadOnlySpan data) internal static bool IsValidFormat (Stream stream) { stream.Position = 0; - var prefix = StreamBytes.ReadAtMost (stream, Id3v2Header.HeaderSize); - var start = StreamStart (prefix); + var header = Id3v2Header.Read (StreamBytes.ReadAtMost (stream, Id3v2Header.HeaderSize)); + var start = header.IsSuccess ? (int)Math.Min (header.Header.TotalSizeIn (stream, 0), int.MaxValue) : 0; return AacStream.FindStart (stream, start, SearchBytes (start), -1, out _) >= 0; } @@ -372,13 +379,13 @@ internal static bool IsValidFormat (Stream stream) // AacFile.Read allows. Without a tag only offset 0 counts; the .aac extension covers the rest. static int SearchBytes (int start) => start > 0 ? AacStream.FirstFrameSearchBytes : 1; - // The byte after a leading ID3v2 tag (header, body, and v2.4 footer), or 0 without one. + // The byte after a leading ID3v2 tag (header, body, and a v2.4 footer that is there), or 0 without one. static int StreamStart (ReadOnlySpan data) { var header = Id3v2Header.Read (data); if (!header.IsSuccess) return 0; - var total = header.Header.TotalSize; + var total = header.Header.TotalSizeIn (data); return total > int.MaxValue ? int.MaxValue : (int)total; } @@ -402,37 +409,88 @@ public BinaryData Render (ReadOnlySpan originalData) _creation?.Settle ([Id3v2Tag, ApeTag, Id3v1Tag]); if (Id3v1Refusal () is string refusal) throw new InvalidOperationException (refusal); - // The read's tail rule against the read's audio start, so a save keeps every frame the read counted. - var audioStart = Math.Min (Id3v2Size, originalData.Length); - var tail = AacTail.Locate (new AacTailSource (originalData), Math.Min (_audioStart, originalData.Length), readTags: false); - var audioEnd = Math.Max (tail.AudioEnd, audioStart); + return Assemble (originalData, Plan (new AacTailSource (originalData))); + } - var id3v2 = Id3v2Tag?.Render () ?? BinaryData.Empty; - var ape = ApeTag.RenderForSave (ApeTag, _readApeTag, defaultHeader: true); - var id3v1 = Id3v1Tag?.Render () ?? BinaryData.Empty; + static BinaryData Assemble (ReadOnlySpan originalData, Written written) + { + using var builder = new BinaryDataBuilder ((int)written.Length); + builder.Add (written.Id3v2); + builder.Add (originalData.Slice ((int)written.AudioStart, (int)written.AudioLength)); + builder.Add (written.Ape); + builder.Add (originalData.Slice ((int)written.LyricsStart, (int)written.LyricsLength)); + builder.Add (written.Id3v1); + return builder.ToBinaryData (); + } + + // The file a save writes: the current tags, the audio and any Lyrics3 block in front of ID3v1, both copied from the + // file at the offsets the object describes. + readonly record struct Written ( + BinaryData Id3v2, + long AudioStart, + long AudioLength, + BinaryData Ape, + bool ApeHeader, + long LyricsStart, + long LyricsLength, + BinaryData Id3v1) + { + public long Length => Id3v2.Length + AudioLength + Ape.Length + LyricsLength + Id3v1.Length; + } + + // The read's tail rule against the read's audio start, so a save keeps every frame the read counted. + Written Plan (AacTailSource source) + { + var fileLength = source.Length; + var audioStart = Math.Min ((long)Id3v2Size, fileLength); + var tail = AacTail.Locate (source, Math.Min (_audioStart, fileLength), readTags: false); + var audioEnd = Math.Max (tail.AudioEnd, audioStart); // Lyrics3 belongs in front of ID3v1 and goes when that tag goes. - var lyrics = Id3v1Tag is not null && tail.LyricsStart >= audioEnd && tail.Id3v1Start > tail.LyricsStart - ? originalData[(int)tail.LyricsStart..(int)tail.Id3v1Start] - : []; - - var audio = originalData[audioStart..(int)audioEnd]; - using var builder = new BinaryDataBuilder (id3v2.Length + audio.Length + ape.Length + lyrics.Length + id3v1.Length); - builder.Add (id3v2); - builder.Add (audio); - builder.Add (ape); - builder.Add (lyrics); - builder.Add (id3v1); - return builder.ToBinaryData (); + 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); + return new Written ( + Id3v2Tag?.Render () ?? BinaryData.Empty, + audioStart, + audioEnd - audioStart, + ApeTag?.RenderWithOptions (apeHeader) ?? BinaryData.Empty, + apeHeader, + keepsLyrics ? tail.LyricsStart : 0, + keepsLyrics ? tail.Id3v1Start - tail.LyricsStart : 0, + Id3v1Tag?.Render () ?? BinaryData.Empty); + } + + // A save that rewrote the source leaves the object describing the file it wrote (#179), as a read of it would: the + // audio starts after the ID3v2 tag written (at the start when none was), the tail is found from there, and the + // APEv2 tag written is the tag read, with the layout it was written with: the file's, not the one it was parsed with. + FileWriteResult Adopt (FileWriteResult result, Written written, IFileSystem? fileSystem) + { + var length = written.Length; + if (!result.IsSuccess + || !SavedOverSource.Holds (SourcePath, fileSystem, length, + new WrittenBytes (0, written.Id3v2.Memory), + new WrittenBytes (written.Id3v2.Length + written.AudioLength, written.Ape.Memory), + new WrittenBytes (length - written.Id3v1.Length, written.Id3v1.Memory))) + return result; + + _audioStart = written.Id3v2.Length; + Id3v2Size = written.Id3v2.Length; + _readApeTag = ApeTag; + _readApeHeader = written.ApeHeader; + Source.Rewrote (length); + return result; } + async Task Adopt (Task save, Written written, IFileSystem? fileSystem) => + Adopt (await save.ConfigureAwait (false), written, fileSystem); + /// /// Saves the file to the specified path using atomic write. /// /// The target file path. - /// The bytes of the file this object was read from; the payload is taken from them at the - /// offsets the read found. Bytes of any other length, a file it has saved since among them, fail with a result, and - /// nothing is written. + /// The bytes of the file this object was read from or, after a save over its source, of the + /// file that save wrote; the payload is taken from them at the offsets of that file. Bytes of any other length, a + /// file it saved elsewhere among them, fail with a result, and nothing is written. /// Optional file system abstraction for testing. /// A result indicating success or failure. public FileWriteResult SaveToFile (string path, ReadOnlySpan originalData, IFileSystem? fileSystem = null) @@ -446,20 +504,22 @@ public FileWriteResult SaveToFile (string path, ReadOnlySpan originalData, if (Source.Refuse ("AAC", originalData.Length) is { } mismatch) return mismatch; - var rendered = Render (originalData); + var written = Plan (new AacTailSource (originalData)); + var rendered = Assemble (originalData, written); if (rendered.IsEmpty) return FileWriteResult.Failure ("Failed to render AAC file"); - return AtomicFileWriter.Write (path, rendered.Span, fileSystem ?? _sourceFileSystem); + fileSystem ??= _sourceFileSystem; + return Adopt (AtomicFileWriter.Write (path, rendered.Span, fileSystem), written, fileSystem); } /// /// Asynchronously saves the file to the specified path using atomic write. /// /// The target file path. - /// The bytes of the file this object was read from; the payload is taken from them at the - /// offsets the read found. Bytes of any other length, a file it has saved since among them, fail with a result, and - /// nothing is written. + /// The bytes of the file this object was read from or, after a save over its source, of the + /// file that save wrote; the payload is taken from them at the offsets of that file. Bytes of any other length, a + /// file it saved elsewhere among them, fail with a result, and nothing is written. /// Optional file system abstraction for testing. /// A token to cancel the operation. /// A task containing a result indicating success or failure. @@ -478,11 +538,13 @@ public Task SaveToFileAsync ( if (Source.Refuse ("AAC", originalData.Length) is { } mismatch) return Task.FromResult (mismatch); - var rendered = Render (originalData.Span); + var written = Plan (new AacTailSource (originalData.Span)); + var rendered = Assemble (originalData.Span, written); if (rendered.IsEmpty) return Task.FromResult (FileWriteResult.Failure ("Failed to render AAC file")); - return AtomicFileWriter.WriteAsync (path, rendered.Memory, fileSystem ?? _sourceFileSystem, cancellationToken); + fileSystem ??= _sourceFileSystem; + return Adopt (AtomicFileWriter.WriteAsync (path, rendered.Memory, fileSystem, cancellationToken), written, fileSystem); } /// @@ -561,27 +623,12 @@ FileWriteResult SaveFromSource (string destinationPath, IFileSystem? fileSystem, try { if (!PathSave.TryOpen (SourcePath!, fileSystem, out source, out var error)) return error; + if (Source.Refuse ("AAC", source!.Length, "the source file") is { } changed) + return changed; var opened = source!; - var fileLength = opened.Length; - var audioStart = Math.Min ((long)Id3v2Size, fileLength); - var tail = AacTail.Locate ( - new AacTailSource (opened.Stream, fileLength), - Math.Min (_audioStart, fileLength), - readTags: false); - var audioEnd = Math.Max (tail.AudioEnd, audioStart); - var id3v2 = Id3v2Tag?.Render () ?? BinaryData.Empty; - var ape = ApeTag.RenderForSave (ApeTag, _readApeTag, defaultHeader: true); - var id3v1 = Id3v1Tag?.Render () ?? BinaryData.Empty; - long lyricsStart = 0; - long lyricsLength = 0; - if (Id3v1Tag is not null && tail.LyricsStart >= audioEnd && tail.Id3v1Start > tail.LyricsStart) { - lyricsStart = tail.LyricsStart; - lyricsLength = tail.Id3v1Start - tail.LyricsStart; - } - - var audioLength = audioEnd - audioStart; - if (id3v2.IsEmpty && audioLength <= 0 && ape.IsEmpty && lyricsLength <= 0 && id3v1.IsEmpty) + var written = Plan (new AacTailSource (opened.Stream, opened.Length)); + if (written.Length == 0) return FileWriteResult.Failure ("Failed to render AAC file"); if (cancellationToken.IsCancellationRequested) @@ -590,15 +637,15 @@ FileWriteResult SaveFromSource (string destinationPath, IFileSystem? fileSystem, chunk = StreamCopy.Rent (); var copyBuffer = chunk; var stream = opened.Stream; - var written = PathSave.Replace (destinationPath, opened, output => { - StreamCopy.Write (output, id3v2.Span, copyBuffer); - CopyRange (stream, output, audioStart, audioLength, copyBuffer); - StreamCopy.Write (output, ape.Span, copyBuffer); - CopyRange (stream, output, lyricsStart, lyricsLength, copyBuffer); - StreamCopy.Write (output, id3v1.Span, copyBuffer); + var saved = PathSave.Replace (destinationPath, opened, output => { + StreamCopy.Write (output, written.Id3v2.Span, copyBuffer); + CopyRange (stream, output, written.AudioStart, written.AudioLength, copyBuffer); + StreamCopy.Write (output, written.Ape.Span, copyBuffer); + CopyRange (stream, output, written.LyricsStart, written.LyricsLength, copyBuffer); + StreamCopy.Write (output, written.Id3v1.Span, copyBuffer); }); source = null; - return written; + return Adopt (saved, written, fileSystem); } finally { source?.Dispose (); if (chunk is not null) @@ -648,6 +695,7 @@ public void Dispose () Id3v2Tag = null; ApeTag = null; _readApeTag = null; + _readApeHeader = null; Id3v1Tag = null; SourcePath = null; _sourceFileSystem = null; diff --git a/src/TagLibSharp2/Aac/AacStream.cs b/src/TagLibSharp2/Aac/AacStream.cs index e7c2d556..1d412415 100644 --- a/src/TagLibSharp2/Aac/AacStream.cs +++ b/src/TagLibSharp2/Aac/AacStream.cs @@ -342,7 +342,7 @@ static bool TryReadAdif (Stream stream, long start, long end, out AacAudioProper var payload = end - start - header.Size; var duration = header.Bitrate > 0 && payload > 0 - ? TimeSpan.FromTicks ((long)Math.Round ((double)payload * 8 * TimeSpan.TicksPerSecond / header.Bitrate)) + ? Durations.FromTicks ((double)payload * 8 * TimeSpan.TicksPerSecond / header.Bitrate) : TimeSpan.Zero; var program = header.Program; properties = new AacAudioProperties ( @@ -391,9 +391,9 @@ static bool TryWalkAdts (ScanReader reader, long first, long end, out AacAudioPr var sampleRate = stream0.SampleRate; var samples = (double)blocks * AdtsHeader.SamplesPerBlock; - var duration = TimeSpan.FromTicks ((long)Math.Round (samples * TimeSpan.TicksPerSecond / sampleRate)); + var duration = Durations.FromTicks (samples * TimeSpan.TicksPerSecond / sampleRate); var bitrate = duration > TimeSpan.Zero - ? (int)(bytes * 8 / duration.TotalSeconds / 1000) + ? Rates.Kbps (bytes * 8 / duration.TotalSeconds) : 0; properties = new AacAudioProperties ( duration, diff --git a/src/TagLibSharp2/Aiff/AiffAudioProperties.cs b/src/TagLibSharp2/Aiff/AiffAudioProperties.cs index 5c765194..90d888f6 100644 --- a/src/TagLibSharp2/Aiff/AiffAudioProperties.cs +++ b/src/TagLibSharp2/Aiff/AiffAudioProperties.cs @@ -116,7 +116,7 @@ public class AiffAudioProperties : IMediaProperties // Calculate duration if (sampleRate > 0 && sampleFrames > 0) - Duration = TimeSpan.FromSeconds ((double)sampleFrames / sampleRate); + Duration = Durations.FromSeconds ((double)sampleFrames / sampleRate); else Duration = TimeSpan.Zero; @@ -155,7 +155,7 @@ public static bool TryParse (BinaryData commData, out AiffAudioProperties? prope // Parse sample rate from 80-bit extended float var sampleRateDouble = ExtendedFloat.ToDouble (commData.Slice (8, 10)); - int sampleRate = (int)Math.Round (sampleRateDouble); + var sampleRate = Rates.SampleRate (sampleRateDouble); // Parse AIFC compression fields if present string? compressionType = null; diff --git a/src/TagLibSharp2/Aiff/AiffChunk.cs b/src/TagLibSharp2/Aiff/AiffChunk.cs index a5fcb4bc..69d92e23 100644 --- a/src/TagLibSharp2/Aiff/AiffChunk.cs +++ b/src/TagLibSharp2/Aiff/AiffChunk.cs @@ -48,6 +48,13 @@ public class AiffChunk /// public long TotalSize => HeaderSize + (long)Size + (Size % 2 == 1 ? 1 : 0); + /// + /// The bytes writes: the header, the bytes present and a pad to an even length. A chunk read + /// with a size past its bytes (a cut-off file, or a placeholder size) is written with the size of its bytes (#197), + /// as a WAV chunk is. + /// + internal long RenderedSize => HeaderSize + (long)Data.Length + (Data.Length & 1); + AiffChunk (string fourCC, uint size, BinaryData data) { FourCC = fourCC; @@ -79,14 +86,14 @@ public AiffChunk (string fourCC, BinaryData data) /// The complete chunk including header and padding. public BinaryData Render () { - var needsPadding = Size % 2 == 1; - using var builder = new BinaryDataBuilder (HeaderSize + (int)Size + (needsPadding ? 1 : 0)); + var needsPadding = (Data.Length & 1) == 1; + using var builder = new BinaryDataBuilder ((int)RenderedSize); // Write FourCC builder.AddStringLatin1 (FourCC); - // Write size (big-endian) - builder.AddUInt32BE (Size); + // Write the size of the bytes present (big-endian) + builder.AddUInt32BE ((uint)Data.Length); // Write data builder.Add (Data); @@ -105,7 +112,15 @@ public BinaryData Render () /// The offset where the chunk starts. /// The parsed chunk, or null if parsing failed. /// True if parsing succeeded; otherwise, false. - public static bool TryParse (BinaryData data, int offset, out AiffChunk? chunk) + public static bool TryParse (BinaryData data, int offset, out AiffChunk? chunk) => + TryParse (data, offset, data.Length, out chunk); + + /// + /// within a FORM that ends at : the + /// chunk holds , the rule the stream walk applies too (#197). A chunk whose + /// size runs past them keeps that size and the bytes present. + /// + internal static bool TryParse (BinaryData data, int offset, int end, out AiffChunk? chunk) { chunk = null; @@ -125,18 +140,8 @@ public static bool TryParse (BinaryData data, int offset, out AiffChunk? chunk) (span[offset + 6] << 8) | span[offset + 7]); - // Overflow protection: reject chunks claiming > int.MaxValue size - if (size > int.MaxValue) - return false; - - // Verify we have enough data - if (data.Length < offset + HeaderSize + size) - return false; - - // Extract chunk data (safe cast after overflow check) - var chunkData = data.Slice (offset + HeaderSize, (int)size); - - chunk = new AiffChunk (fourCC, size, chunkData); + var present = (int)ChunkExtent.PresentBytes (size, offset + HeaderSize, Math.Min (end, data.Length)); + chunk = new AiffChunk (fourCC, size, present > 0 ? data.Slice (offset + HeaderSize, present) : BinaryData.Empty); return true; } } diff --git a/src/TagLibSharp2/Aiff/AiffFile.cs b/src/TagLibSharp2/Aiff/AiffFile.cs index 72e6f8d4..3472d54a 100644 --- a/src/TagLibSharp2/Aiff/AiffFile.cs +++ b/src/TagLibSharp2/Aiff/AiffFile.cs @@ -215,6 +215,9 @@ public string? Copyright { readonly List _chunks = []; readonly List _skipped = []; + + // The bytes after the FORM ends: not its chunks, but the file's, and a save writes them after the FORM (#197). + FormTrail? _trail; readonly List _markers = []; readonly List _annotations = []; readonly List _markerComments = []; @@ -412,9 +415,7 @@ internal static AiffFileReadResult Read (Stream stream, string? sourcePath, IFil } file.IsValid = true; - var limit = file.FileSize == 0xFFFFFFFF - ? stream.Length - : Math.Min (stream.Length, 8L + file.FileSize); + var limit = ChunkExtent.FormEnd (file.FileSize, stream.Length); while (stream.Position + 8 <= limit) { var chunkHeader = StreamBytes.ReadAtMost (stream, 8); @@ -424,13 +425,14 @@ internal static AiffFileReadResult Read (Stream stream, string? sourcePath, IFil var id = FourCC (chunkHeader, 0); var size = ReadUInt32BE (chunkHeader, 4); var dataPos = stream.Position; - var available = limit - dataPos; - if (available < 0) - available = 0; - var present = available < size ? (uint)available : size; + var present = (uint)ChunkExtent.PresentBytes (size, dataPos, limit); var pad = (size & 1) == 1 && present == size ? 1 : 0; - if (id == "SSND" || size > int.MaxValue) { - if (present > 0 && present <= int.MaxValue) + // Sound is reloaded on save. Other chunks are copied, but only the bytes present, as the span walk keeps + // them (#197); only bytes present past int.MaxValue, which no copy holds, stay in the file like sound. + // Every byte left in the file is recorded, whatever its size: a save copies it from the source, and a + // chunk with bytes left unrecorded would be written empty (review 4's big.aif lost its sound). + if (id == "SSND" || present > int.MaxValue) { + if (present > 0) file._skipped.Add (new SkippedChunk (file._chunks.Count, dataPos, present)); file._chunks.Add (AiffChunk.WithDeclaredSize (id, size, BinaryData.Empty)); var skip = (long)present + pad; @@ -446,7 +448,9 @@ internal static AiffFileReadResult Read (Stream stream, string? sourcePath, IFil byte[] data; if (options.SkipPictures && (id is "ID3 " or "ID3")) { var bodyEnd = stream.Position + present; - data = Id3v2Tag.CopyWithoutPictures (stream, bodyEnd).Bytes; + var stripped = Id3v2Tag.CopyWithoutPictures (stream, bodyEnd); + data = stripped.Bytes; + file._tagPicturesDropped |= stripped.DroppedPictures; if (stream.Position < bodyEnd) PictureSkip.Discard (stream, bodyEnd - stream.Position); } else { @@ -464,6 +468,15 @@ internal static AiffFileReadResult Read (Stream stream, string? sourcePath, IFil break; } + var trailStart = limit; + if (!file.HasId3Chunk && TrailingTagChunk.TryRead (stream, limit, stream.Length, bigEndian: true, Id3ChunkIds, options.SkipPictures, out var tag)) { + file.AddChunk (new AiffChunk ("ID3 ", new BinaryData (tag.Body))); + file._tagPicturesDropped |= tag.DroppedPictures; + trailStart += tag.Taken; + } + + var superseded = file.HasId3Chunk ? TrailingTagChunk.Superseded (stream, trailStart, stream.Length, bigEndian: true, Id3ChunkIds) : 0; + file._trail = FormTrail.InSource (trailStart, stream.Length, superseded); file.FinishNative (); file.SourcePath = sourcePath; file._sourceFileSystem = fileSystem; @@ -555,23 +568,28 @@ bool Parse (BinaryData data) IsValid = true; - // Parse chunks. TotalSize is a long so a size near int.MaxValue does not walk backward. + // Parse chunks up to the FORM's end, each with its bytes present (#197), as the stream walk does. TotalSize is a + // long so a size near int.MaxValue does not walk backward. + var limit = ChunkExtent.FormEnd (FileSize, data.Length); long offset = HeaderSize; - while (offset < data.Length) { - if (offset > int.MaxValue || !AiffChunk.TryParse (data, (int)offset, out var chunk)) + while (offset + AiffChunk.HeaderSize <= limit) { + if (!AiffChunk.TryParse (data, (int)offset, (int)limit, out var chunk)) break; + // A chunk cut at the FORM's end declares more than it holds, so the next offset is past the end. _chunks.Add (chunk!); - var next = offset + chunk!.TotalSize; - if (next <= offset) - break; - - offset = next; + ProcessChunk (chunk!); + offset += chunk!.TotalSize; + } - // Process specific chunk types - ProcessChunk (chunk); + var trailStart = limit; + if (!HasId3Chunk && TrailingTagChunk.TryRead (data.Span.Slice ((int)limit), bigEndian: true, Id3ChunkIds, out var tag)) { + AddChunk (new AiffChunk ("ID3 ", new BinaryData (tag.Body))); + trailStart += tag.Taken; } + var superseded = HasId3Chunk ? TrailingTagChunk.Superseded (data.Span.Slice ((int)trailStart), bigEndian: true, Id3ChunkIds) : 0; + _trail = FormTrail.Of (data.Memory, trailStart, superseded); FinishNative (); return true; } @@ -812,16 +830,18 @@ public BinaryData Render () output.Add (new AiffChunk ("ID3 ", id3Data)); } - // TotalSize is a long file length, not a wrapped int. + // RenderedSize is a long file length, not a wrapped int, and the bytes each chunk holds, never a declared size. long chunksSize = 0; foreach (var chunk in output) - chunksSize += chunk.TotalSize; + chunksSize += chunk.RenderedSize; - if (chunksSize > int.MaxValue - HeaderSize) + var trail = _trail?.For (TagRewritten); + var trailLength = trail?.Length ?? 0; + if (chunksSize + trailLength > int.MaxValue - HeaderSize) throw new InvalidOperationException ("Cannot render an AIFF file larger than supported memory."); var contentSize = 4 + chunksSize; - var totalSize = (int)(HeaderSize + chunksSize); + var totalSize = (int)(HeaderSize + chunksSize + trailLength); using var builder = new BinaryDataBuilder (totalSize); builder.AddStringLatin1 ("FORM"); @@ -829,12 +849,52 @@ public BinaryData Render () builder.AddStringLatin1 (FormType); foreach (var chunk in output) builder.Add (chunk.Render ()); + if (trail is not null) + builder.Add (trail.Bytes); return builder.ToBinaryData (); } static bool IsId3Chunk (string fourCC) => fourCC is "ID3 " or "ID3"; + // The identifiers of an ID3 chunk, which a tag chunk after the FORM may have in either case (TrailingTagChunk). + static readonly string[] Id3ChunkIds = ["ID3 ", "ID3"]; + + // Whether a SkipPictures read left a picture out of the tag (TagRewritten). + bool _tagPicturesDropped; + + /// + /// Whether a save writes the ID3 chunk other than as the read found it, so the tag chunks after the FORM that it + /// supersedes are dropped (, #197): the tag it writes, rendered, against the + /// tag the ID3 chunks read (the last that reads, as takes it), rendered, or a tag written + /// or removed where there was none or one. A SkipPictures read that left a picture out of the tag writes what a full + /// read cleared of its pictures writes, which is not the tag read. + /// + bool TagRewritten () + { + if (_tagPicturesDropped) + return true; + + Id3v2Tag? readTag = null; + foreach (var chunk in _chunks) { + if (IsId3Chunk (chunk.FourCC) && Id3v2Tag.Read (chunk.Data.Span) is { IsSuccess: true } result) + readTag = result.Tag; + } + + byte[]? read = readTag is { IsEmpty: false } ? readTag.Render ().ToArray () : null; + byte[]? written = Id3v2Tag is { IsEmpty: false } tag ? tag.Render ().ToArray () : null; + return read is null ? written is not null : written is null || !read.AsSpan ().SequenceEqual (written); + } + + bool HasId3Chunk => _chunks.Exists (chunk => IsId3Chunk (chunk.FourCC)); + + // A tag chunk after the FORM's end is read as one of its chunks (#197), so a save writes the tag in the FORM. + void AddChunk (AiffChunk chunk) + { + _chunks.Add (chunk); + ProcessChunk (chunk); + } + bool OmitNativeChunk (string fourCC) { if (fourCC is "ANNO" or "COMT") @@ -899,7 +959,9 @@ public FileWriteResult SaveToFile (string path, IFileSystem? fileSystem = null) { if (PictureSkip.Refuse (this) is { } denied) return denied; - if (!IsValid || _skipped.Count == 0) + if (SaveRefusal () is { } refused) + return refused; + if (_skipped.Count == 0) return SaveLoaded (path, fileSystem); return SaveFromSource (path, fileSystem, default); @@ -911,14 +973,38 @@ FileWriteResult SaveLoaded (string path, IFileSystem? fileSystem) if (!TryLoadSkipped (fs, out var skipped)) return FileWriteResult.Failure (skipped!); + if (InMemoryTooLarge () is { } tooLarge) + return tooLarge; var data = Render (); return AtomicFileWriter.Write (path, data.Span, fs); } + // Render throws for an invalid file; a save returns a failure and writes nothing (#196). A file with no valid COMM + // chunk, which every AIFF file needs (AIFF 1.3, "Common Chunk"), is refused too: such a file reads as one when its + // FORM ends before COMM (review 4's aif-form-0.aif), and its save wrote the FORM header alone. + FileWriteResult? SaveRefusal () + { + if (!IsValid) + return FileWriteResult.Failure ("Cannot save an invalid AIFF file."); + if (Properties is null) + return FileWriteResult.Failure ("Cannot save an AIFF file that has no valid COMM chunk."); + return null; + } + + FileWriteResult? InMemoryTooLarge () + { + long chunksSize = 0; + foreach (var chunk in PlanChunks ()) + chunksSize += chunk.RenderedSize; + return chunksSize > int.MaxValue - HeaderSize + ? FileWriteResult.Failure ("Cannot save an AIFF file larger than supported memory.") + : null; + } + bool TryLoadSkipped (IFileSystem? fileSystem, out string? error) { error = null; - if (_skipped.Count == 0) + if (_skipped.Count == 0 && _trail is null or { Held: true }) return true; foreach (var chunk in _skipped) { @@ -929,19 +1015,27 @@ bool TryLoadSkipped (IFileSystem? fileSystem, out string? error) } if (SourcePath is not { Length: > 0 } path) { - error = "Cannot save an AIFF file whose sound data was not loaded."; + error = _skipped.Count > 0 + ? "Cannot save an AIFF file whose sound data was not loaded." + : "Cannot save an AIFF file whose bytes after its FORM were not loaded."; return false; } var fs = fileSystem ?? _sourceFileSystem ?? DefaultFileSystem.Instance; using var stream = fs.OpenRead (path); + var length = stream.Length; foreach (var chunk in _skipped) { - if (stream.Length < chunk.Offset + chunk.PresentBytes) { + if (length < chunk.Offset + chunk.PresentBytes) { error = "Cannot save an AIFF file whose sound data is no longer in the source file."; return false; } } + if (_trail is { } trail && !trail.TryLoad (stream, length)) { + error = TrailMissing; + return false; + } + foreach (var chunk in _skipped) { stream.Position = chunk.Offset; var samples = StreamBytes.ReadAtMost (stream, (int)chunk.PresentBytes); @@ -953,6 +1047,8 @@ bool TryLoadSkipped (IFileSystem? fileSystem, out string? error) return true; } + const string TrailMissing = "Cannot save an AIFF file whose bytes after its FORM are no longer in the source file."; + /// /// Saves the AIFF file to the specified path asynchronously. /// @@ -967,7 +1063,9 @@ public Task SaveToFileAsync ( { if (PictureSkip.Refuse (this) is { } denied) return Task.FromResult (denied); - if (!IsValid || _skipped.Count == 0) + if (SaveRefusal () is { } refused) + return Task.FromResult (refused); + if (_skipped.Count == 0) return SaveLoadedAsync (path, fileSystem, cancellationToken); // "Was not loaded" and a short source are decided before the token, matching the sync save. @@ -980,6 +1078,8 @@ Task SaveLoadedAsync (string path, IFileSystem? fileSystem, Can if (!TryLoadSkipped (fs, out var skipped)) return Task.FromResult (FileWriteResult.Failure (skipped!)); + if (InMemoryTooLarge () is { } tooLarge) + return Task.FromResult (tooLarge); var data = Render (); return AtomicFileWriter.WriteAsync (path, data.Memory, fs, cancellationToken); } @@ -990,11 +1090,7 @@ Task SaveLoadedAsync (string path, IFileSystem? fileSystem, Can /// FileWriteResult SaveFromSource (string path, IFileSystem? fileSystem, CancellationToken cancellationToken) { - foreach (var chunk in _skipped) { - if (chunk.PresentBytes > int.MaxValue) - return FileWriteResult.Failure ("Cannot save an AIFF file whose sound data does not fit in memory."); - } - + // A chunk of any size is copied from the source in pieces; only the FORM's 32-bit size bounds the file. if (SourcePath is not { Length: > 0 } sourcePath) return FileWriteResult.Failure ("Cannot save an AIFF file whose sound data was not loaded."); @@ -1010,26 +1106,45 @@ FileWriteResult SaveFromSource (string path, IFileSystem? fileSystem, Cancellati if (!SoundStillPresent (open)) return FileWriteResult.Failure ("Cannot save an AIFF file whose sound data is no longer in the source file."); + // Each chunk is written with the bytes it holds: its own, or the sound present in the source (#197). The + // FORM size is 32 bits; a streamed save needs no more memory than one chunk. var output = PlanChunks (); long chunksSize = 0; foreach (var chunk in output) - chunksSize += chunk.TotalSize; + chunksSize += FindSkipped (chunk) is var skipped and >= 0 + ? AiffChunk.HeaderSize + (long)_skipped[skipped].PresentBytes + (_skipped[skipped].PresentBytes & 1) + : chunk.RenderedSize; - if (chunksSize > int.MaxValue - HeaderSize) - throw new InvalidOperationException ("Cannot render an AIFF file larger than supported memory."); + if (4 + chunksSize > uint.MaxValue) + return FileWriteResult.Failure ("Cannot save an AIFF file larger than its 32-bit FORM size."); if (cancellationToken.IsCancellationRequested) return FileWriteResult.Failure ("Operation was cancelled"); var rented = StreamCopy.Rent (); buffer = rented; + var layout = new ChunkLayout (); + var trail = _trail?.For (TagRewritten); var result = AtomicFileWriter.WriteStream (path, fs, outputStream => { try { - WritePlanned (outputStream, open.Stream, output, chunksSize, rented); + WritePlanned (outputStream, open.Stream, output, chunksSize, rented, layout); + trail?.Write (outputStream, open.Stream, open.Length, rented); + layout.Trail (trail?.Length ?? 0); } finally { open.Dispose (); } }); + // A save over the source moved the sound when a chunk ahead of it changed size: the next save copies it + // from where this one wrote it. + if (result.IsSuccess && layout.Holds (SourcePath, readFs)) { + foreach (var (index, offset) in layout.Copied) + _skipped[index] = new SkippedChunk (_skipped[index].Index, offset, _skipped[index].PresentBytes); + + // The superseded tag chunks this save dropped are no longer in the source, so the next save copies the + // bytes that were after them. + _trail = trail; + } + return result; } finally { if (buffer is not null) @@ -1128,10 +1243,11 @@ int FindSkipped (AiffChunk chunk) } /// - /// The size field is the declared ckSize. An odd declared size gets a 0 pad that is not copied from the source. - /// A short payload is not padded out to that declared size. + /// Each chunk is written with the size of the bytes it holds, and an odd size gets a 0 pad that is not copied from + /// the source (#197): a chunk read with a size past its bytes is written as the bytes present, as + /// writes it. /// - void WritePlanned (Stream output, Stream source, List chunks, long chunksSize, byte[] scratch) + void WritePlanned (Stream output, Stream source, List chunks, long chunksSize, byte[] scratch, ChunkLayout layout) { var header = new byte[HeaderSize]; header[0] = (byte)'F'; @@ -1144,27 +1260,31 @@ void WritePlanned (Stream output, Stream source, List chunks, long ch header[10] = (byte)FormType[2]; header[11] = (byte)FormType[3]; output.Write (header, 0, header.Length); + layout.Written (header); - var chunkHeader = new byte[AiffChunk.HeaderSize]; foreach (var chunk in chunks) { var skippedIndex = FindSkipped (chunk); if (skippedIndex < 0) { - StreamCopy.Write (output, chunk.Render ().Span, scratch); + var rendered = chunk.Render (); + StreamCopy.Write (output, rendered.Span, scratch); + layout.Written (rendered.Memory); continue; } + var chunkHeader = new byte[AiffChunk.HeaderSize]; var fourCC = chunk.FourCC; chunkHeader[0] = (byte)fourCC[0]; chunkHeader[1] = (byte)fourCC[1]; chunkHeader[2] = (byte)fourCC[2]; chunkHeader[3] = (byte)fourCC[3]; - BinaryPrimitives.WriteUInt32BigEndian (chunkHeader.AsSpan (4), chunk.Size); + var skipped = _skipped[skippedIndex]; + BinaryPrimitives.WriteUInt32BigEndian (chunkHeader.AsSpan (4), skipped.PresentBytes); output.Write (chunkHeader, 0, chunkHeader.Length); + layout.Copy (skippedIndex, chunkHeader, AiffChunk.HeaderSize + (long)skipped.PresentBytes + (skipped.PresentBytes & 1)); - var skipped = _skipped[skippedIndex]; source.Position = skipped.Offset; StreamCopy.Copy (source, output, skipped.PresentBytes, scratch); - if ((chunk.Size & 1) == 0) + if ((skipped.PresentBytes & 1) == 0) continue; scratch[0] = 0; diff --git a/src/TagLibSharp2/Ape/ApeTag.cs b/src/TagLibSharp2/Ape/ApeTag.cs index 53367501..03d621a0 100644 --- a/src/TagLibSharp2/Ape/ApeTag.cs +++ b/src/TagLibSharp2/Ape/ApeTag.cs @@ -1217,13 +1217,17 @@ internal static bool MoreItems (long offset, long length, int parsed, uint count /// 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) - { - if (tag is null) - return BinaryData.Empty; - var header = ReferenceEquals (tag, readTag) ? tag._readWithHeader ?? defaultHeader : defaultHeader; - return tag.RenderWithOptions (header); - } + internal static BinaryData RenderForSave (ApeTag? tag, ApeTag? readTag, bool defaultHeader) => + tag?.RenderWithOptions (HeaderForSave (tag, readTag, null, defaultHeader)) ?? BinaryData.Empty; + + /// + /// Whether a save writes with a header (see ). + /// , when given, is the layout the file holds for : a + /// carrier that saved over its source takes the tag it wrote as the tag read, with the layout it wrote, as a read + /// of that file would (#179), whatever layout the tag was parsed with. + /// + internal static bool HeaderForSave (ApeTag tag, ApeTag? readTag, bool? readHeader, bool defaultHeader) => + ReferenceEquals (tag, readTag) ? readHeader ?? tag._readWithHeader ?? defaultHeader : defaultHeader; /// /// Renders the tag to binary data with optional header. diff --git a/src/TagLibSharp2/Ape/MonkeysAudioFile.cs b/src/TagLibSharp2/Ape/MonkeysAudioFile.cs index 7598cb3d..e5cf7487 100644 --- a/src/TagLibSharp2/Ape/MonkeysAudioFile.cs +++ b/src/TagLibSharp2/Ape/MonkeysAudioFile.cs @@ -14,13 +14,16 @@ namespace TagLibSharp2.Ape; /// /// Represents the result of parsing a Monkey's Audio file. /// -public readonly struct MonkeysAudioFileReadResult : IEquatable +public readonly struct MonkeysAudioFileReadResult : IEquatable, ISourceRecorder { /// /// Gets the parsed Monkey's Audio file, or null if parsing failed. /// public MonkeysAudioFile? File { get; } + /// + SourceLength? ISourceRecorder.Source => File?.Source; + /// /// Gets the error message if parsing failed, or null if successful. /// @@ -193,14 +196,7 @@ private MonkeysAudioFile () { } /// A result indicating success with the parsed file, or failure with an error message. [SuppressMessage ("Reliability", "CA2000:Dispose objects before losing scope", Justification = "Factory method transfers ownership to caller")] public static MonkeysAudioFileReadResult Read (ReadOnlySpan data) => - Recorded (Parse (data), data.Length); - - // The file a read made, recording the length of the file it read. - static MonkeysAudioFileReadResult Recorded (MonkeysAudioFileReadResult result, long length) - { - result.File?.Source.Record (length); - return result; - } + SourceLength.Recorded (Parse (data), data.Length); // The parse of Read without the length it records: a stream reader parses part of the stream and records the // stream's length. @@ -296,7 +292,7 @@ internal static MonkeysAudioFileReadResult Read (Stream stream, string? sourcePa if (tagAt < header.Length) return Mark (Finish (Read (ReadWhole (stream)), sourcePath, fileSystem, keepPayload: sourcePath is null), options); - return Mark (Finish (Recorded (Parse (Join (header, tag), header.Length), stream.Length), sourcePath, fileSystem, keepPayload: false, fileLength: stream.Length), options); + return Mark (Finish (SourceLength.Recorded (Parse (Join (header, tag), header.Length), stream.Length), sourcePath, fileSystem, keepPayload: false, fileLength: stream.Length), options); } static MonkeysAudioFileReadResult Mark (MonkeysAudioFileReadResult parsed, MediaReadOptions options) @@ -432,7 +428,7 @@ private static ParseResult ParseNewFormat (ReadOnlySpan data, MonkeysAudio file.Channels = BinaryPrimitives.ReadUInt16LittleEndian (data.Slice (headerStart + 18, 2)); // [4] sample rate - file.SampleRate = (int)BinaryPrimitives.ReadUInt32LittleEndian (data.Slice (headerStart + 20, 4)); + file.SampleRate = Rates.SampleRate (BinaryPrimitives.ReadUInt32LittleEndian (data.Slice (headerStart + 20, 4))); return ParseResult.Success (); } @@ -458,7 +454,7 @@ private static ParseResult ParseOldFormat (ReadOnlySpan data, MonkeysAudio offset += 2; // [6-9] sample rate - file.SampleRate = (int)BinaryPrimitives.ReadUInt32LittleEndian (data.Slice (offset, 4)); + file.SampleRate = Rates.SampleRate (BinaryPrimitives.ReadUInt32LittleEndian (data.Slice (offset, 4))); offset += 4; // [10-13] header bytes (skip) @@ -517,7 +513,7 @@ private void CalculateProperties () var bitrate = 0; var length = _fileLength > 0 ? _fileLength : _originalData.Length; if (length > 0 && durationSeconds > 0) - bitrate = (int)(length * 8 / durationSeconds / 1000); + bitrate = Rates.Kbps (length * 8 / durationSeconds); // AudioProperties: duration, bitrate, sampleRate, bitsPerSample, channels, codec Properties = new AudioProperties ( diff --git a/src/TagLibSharp2/Asf/AsfFile.cs b/src/TagLibSharp2/Asf/AsfFile.cs index 7e8f0b1d..3765a44e 100644 --- a/src/TagLibSharp2/Asf/AsfFile.cs +++ b/src/TagLibSharp2/Asf/AsfFile.cs @@ -109,14 +109,7 @@ public string? Album { /// Reads an ASF file from binary data. /// public static AsfFileReadResult Read (ReadOnlySpan data) => - Recorded (Parse (data), data.Length); - - // The file a read made, recording the length of the file it read. - static AsfFileReadResult Recorded (AsfFileReadResult result, long length) - { - result.File?.Source.Record (length); - return result; - } + SourceLength.Recorded (Parse (data), data.Length); // The parse of Read without the length it records: a stream reader parses part of the stream and records the // stream's length. @@ -145,8 +138,7 @@ static AsfFileReadResult Parse (ReadOnlySpan data) if (headerSize > (ulong)data.Length) return AsfFileReadResult.Failure ("Invalid ASF file: header size exceeds available data"); - // Read child object count - var childCount = BinaryPrimitives.ReadUInt32LittleEndian (data[offset..]); + // Skip the child object count: the objects that fill the header size are its objects (#200) offset += 4; // Skip reserved bytes (2) @@ -161,8 +153,10 @@ static AsfFileReadResult Parse (ReadOnlySpan data) List? library = null; var extensionUnreadable = false; - for (uint i = 0; MoreObjects (i, childCount, offset, data.Length); i++) { - var contentSize = ObjectContentSize (data.Slice (offset, 24), data.Length - offset - 24, out var objectGuid); + // The header's objects are those that fill its size, whatever the count says (#200). + var headerEnd = (int)headerSize; + while (MoreObjects (offset, headerEnd)) { + var contentSize = ObjectContentSize (data.Slice (offset, 24), headerEnd - offset - 24, out var objectGuid); if (contentSize < 0) break; // Stop parsing but don't fail completely offset += 24; @@ -208,9 +202,14 @@ static AsfFileReadResult Parse (ReadOnlySpan data) // The header-object walk of Read (ASF spec rev. 01.20.03 §3.1, §3.2), shared with the picture skip so both // stop at the same object. - /// Whether another header child is read: the declared count is not reached and a 24-byte header fits. - internal static bool MoreObjects (uint index, uint count, long offset, long length) => - index < count && offset < length - 24; + /// + /// Whether another header child is read: a 24-byte header fits before the end of the header, which an object of + /// only a header ending it does (the 27-byte Ogg page twin of #189). The declared count is not trusted (#200): + /// the header's objects are the ones that fill its declared size, so a count short of them reads them all, and a + /// save carries them all. + /// + internal static bool MoreObjects (long offset, long length) => + offset <= length - 24; /// /// The content size of the object whose GUID and size are , or -1 when the walk stops: @@ -366,7 +365,7 @@ internal static AsfFileReadResult Read (Stream stream, string? sourcePath, IFile // picture is parsed, so that read is used as it is. using var stripped = AsfPictureSkip.ReadHeader (stream); var skipped = stripped is not null - ? Finish (Recorded (Parse (stripped.GetBuffer ().AsSpan (0, (int)stripped.Length)), stream.Length), sourcePath, fileSystem, dropPayload: stream.Position < stream.Length) + ? Finish (Parse (stripped.GetBuffer ().AsSpan (0, (int)stripped.Length)), sourcePath, fileSystem, dropPayload: stream.Position < stream.Length) : ReadHeaderBytes (stream, sourcePath, fileSystem); if (skipped.IsSuccess && skipped.File is not null) skipped.File.MarkPicturesSkipped (); @@ -392,7 +391,7 @@ static AsfFileReadResult ReadHeaderBytes (Stream stream, string? sourcePath, IFi head.CopyTo (header, 0); rest.CopyTo (header, head.Length); var coversFile = headerSize >= (ulong)stream.Length; - return Finish (Recorded (Parse (header), stream.Length), sourcePath, fileSystem, dropPayload: !coversFile); + return Finish (SourceLength.Recorded (Parse (header), stream.Length), sourcePath, fileSystem, dropPayload: !coversFile); } static AsfFileReadResult Finish (AsfFileReadResult result, string? sourcePath, IFileSystem? fileSystem, bool dropPayload) @@ -489,8 +488,8 @@ public static async Task ReadFromFileAsync ( static AudioProperties CreateAudioProperties (AsfFileProperties? fileProps, AsfStreamProperties? streamProps) { var duration = fileProps?.Duration ?? TimeSpan.Zero; - var bitrate = (int)((fileProps?.MaxBitrate ?? 0) / 1000); - var sampleRate = (int)(streamProps?.SampleRate ?? 0); + var bitrate = Rates.Kbps ((long)(fileProps?.MaxBitrate ?? 0)); + var sampleRate = Rates.SampleRate (streamProps?.SampleRate ?? 0); var channels = streamProps?.Channels ?? 0; var bitsPerSample = streamProps?.BitsPerSample ?? 0; var codec = streamProps?.CodecName; @@ -508,13 +507,15 @@ static AudioProperties CreateAudioProperties (AsfFileProperties? fileProps, AsfS /// /// The original file data to preserve audio content from. /// - /// The rendered file bytes. + /// The rendered file bytes, or empty when the header's objects do not fill it whole (#200). public byte[] Render (ReadOnlySpan originalData) { // Parse original header to find structure var headerInfo = ParseHeaderStructure (originalData); if (!headerInfo.IsValid) return originalData.ToArray (); // Can't parse, return unchanged + if (headerInfo.IsRefused) + return []; var newHeader = RenderRebuiltHeader (headerInfo); @@ -632,16 +633,24 @@ readonly struct HeaderParseInfo public int HeaderEndOffset { get; } public List PreservedObjects { get; } - public HeaderParseInfo (bool isValid, int headerEndOffset, List preservedObjects) + /// The header parsed, but its objects do not fill it whole: a save would drop bytes, and fails. + public bool IsRefused { get; } + + public HeaderParseInfo (bool isValid, int headerEndOffset, List preservedObjects, bool isRefused = false) { IsValid = isValid; HeaderEndOffset = headerEndOffset; PreservedObjects = preservedObjects; + IsRefused = isRefused; } public static HeaderParseInfo Invalid () => new (false, 0, []); + + public static HeaderParseInfo Refused () => new (true, 0, [], isRefused: true); } + const string HeaderNotWhole = "Cannot save an ASF file whose header objects do not fill its header."; + static HeaderParseInfo ParseHeaderStructure (ReadOnlySpan data) { var preservedObjects = new List (); @@ -659,29 +668,27 @@ static HeaderParseInfo ParseHeaderStructure (ReadOnlySpan data) if (headerSize > (ulong)data.Length) return HeaderParseInfo.Invalid (); - // Read child object count - var childCount = BinaryPrimitives.ReadUInt32LittleEndian (data[24..]); var offset = 30; // After header: GUID (16) + Size (8) + Count (4) + Reserved (2) - // Parse child objects - for (uint i = 0; i < childCount && offset < data.Length - 24; i++) { + // Every object in the header is carried across byte for byte, whatever the count says, and the objects must + // fill the header whole: bytes in it that are no object, or an object that runs past its end (a header size + // that cuts the header short), would be dropped or written twice, so the save fails instead (#200). + var headerEnd = (int)headerSize; + while (MoreObjects (offset, headerEnd)) { var guidResult = AsfGuid.Parse (data[offset..]); if (!guidResult.IsSuccess) - break; + return HeaderParseInfo.Refused (); var objectGuid = guidResult.Value; - if (offset + 24 > data.Length) - break; - var objectSize = BinaryPrimitives.ReadUInt64LittleEndian (data[(offset + 16)..]); if (objectSize < 24 || objectSize > int.MaxValue) - break; + return HeaderParseInfo.Refused (); var objSize = (int)objectSize; - if (offset + objSize > data.Length) - break; + 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) @@ -693,6 +700,8 @@ static HeaderParseInfo ParseHeaderStructure (ReadOnlySpan data) offset += objSize; } + if (offset != headerEnd) + return HeaderParseInfo.Refused (); return new HeaderParseInfo (true, (int)headerSize, preservedObjects); } @@ -718,6 +727,8 @@ public FileWriteResult SaveToFile (string path, ReadOnlySpan originalData, var fs = fileSystem ?? _sourceFileSystem ?? DefaultFileSystem.Instance; var rendered = Render (originalData); + if (rendered.Length == 0) + return FileWriteResult.Failure (HeaderNotWhole); return Source.Saved (AtomicFileWriter.Write (path, rendered, fs)); } @@ -774,6 +785,8 @@ FileWriteResult SaveFromSource (string destinationPath, IFileSystem? fileSystem, StreamCopy.Read (opened.Stream, header, 30, headerSize - 30, copyBuffer); var info = ParseHeaderStructure (header); + if (info.IsRefused) + return FileWriteResult.Failure (HeaderNotWhole); if (info.IsValid) { headerBytes = RenderRebuiltHeader (info); copyStart = info.HeaderEndOffset; @@ -860,6 +873,8 @@ public async Task SaveToFileAsync ( var fs = fileSystem ?? _sourceFileSystem ?? DefaultFileSystem.Instance; var rendered = Render (originalData.Span); + if (rendered.Length == 0) + return FileWriteResult.Failure (HeaderNotWhole); return Source.Saved (await AtomicFileWriter.WriteAsync (path, rendered, fs, cancellationToken).ConfigureAwait (false)); } @@ -928,13 +943,16 @@ public void Dispose () /// /// Result of reading an ASF file. /// -public readonly struct AsfFileReadResult : IEquatable +public readonly struct AsfFileReadResult : IEquatable, ISourceRecorder { /// /// Gets the parsed ASF file, or null if parsing failed. /// public AsfFile? File { get; } + /// + SourceLength? ISourceRecorder.Source => File?.Source; + /// /// Gets the error message if reading failed. /// diff --git a/src/TagLibSharp2/Asf/AsfFileProperties.cs b/src/TagLibSharp2/Asf/AsfFileProperties.cs index 94dda68b..39cc5d04 100644 --- a/src/TagLibSharp2/Asf/AsfFileProperties.cs +++ b/src/TagLibSharp2/Asf/AsfFileProperties.cs @@ -75,17 +75,29 @@ public sealed class AsfFileProperties public uint MaxBitrate { get; } /// - /// Gets the content duration (PlayDuration - Preroll). + /// Gets the content duration (PlayDuration - Preroll), or zero when it is unknown: while the Broadcast Flag is set + /// the Play Duration "is invalid" (ASF Specification 01.20.03, File Properties Object), and one past + /// is unknown too (#181, #183). /// public TimeSpan Duration { get { - // Preroll is in ms, PlayDuration is in 100ns units - var prerollNs = PrerollMs * 10_000; - var effectiveDurationNs = PlayDurationNs > prerollNs ? PlayDurationNs - prerollNs : 0; - return TimeSpan.FromTicks ((long)effectiveDurationNs); + if (IsBroadcast) + return TimeSpan.Zero; + + // Preroll is in ms, PlayDuration is in 100ns units. A preroll at or past the play duration leaves nothing, + // and is compared in ms first, so the preroll in 100ns units cannot wrap 64 bits (#193). + if (PrerollMs > PlayDurationNs / 10_000) + return TimeSpan.Zero; + return Core.Durations.FromTickCount (PlayDurationNs - (PrerollMs * 10_000)); } } + /// + /// Gets whether the Broadcast Flag (bit 0 of Flags) is set: the file "is in the process of being created" and the + /// header's durations and other values are invalid (ASF Specification 01.20.03). + /// + public bool IsBroadcast => (Flags & 0x01) != 0; + /// /// Gets whether the file is seekable. /// diff --git a/src/TagLibSharp2/Asf/AsfPictureSkip.cs b/src/TagLibSharp2/Asf/AsfPictureSkip.cs index f8d72761..9b90dacc 100644 --- a/src/TagLibSharp2/Asf/AsfPictureSkip.cs +++ b/src/TagLibSharp2/Asf/AsfPictureSkip.cs @@ -37,13 +37,12 @@ internal static class AsfPictureSkip return null; var length = (long)headerSize; - var count = BinaryPrimitives.ReadUInt32LittleEndian (head.AsSpan (24)); // The copy is never longer than the header, but the header size is the file's claim, and most of a header // with a picture is the picture: the buffer starts small and grows with what the walk keeps. var kept = new MemoryStream ((int)Math.Min (headerSize, InitialCopyBytes)); kept.Write (head, 0, head.Length); var prefix = new byte[ObjectHeaderSize]; - for (uint i = 0; AsfFile.MoreObjects (i, count, stream.Position, length); i++) { + while (AsfFile.MoreObjects (stream.Position, length)) { var objectStart = stream.Position; StreamBytes.Read (stream, prefix, 0, ObjectHeaderSize); var contentSize = AsfFile.ObjectContentSize (prefix, length - objectStart - ObjectHeaderSize, out var guid); diff --git a/src/TagLibSharp2/Audible/AudibleFile.cs b/src/TagLibSharp2/Audible/AudibleFile.cs index 86713532..5fd7ecbf 100644 --- a/src/TagLibSharp2/Audible/AudibleFile.cs +++ b/src/TagLibSharp2/Audible/AudibleFile.cs @@ -726,7 +726,7 @@ void RefreshLayout (Layout rendered, (byte[] Header, long Length)? source) var onDisk = ParseLayout (read.Header, read.Length, out _); if (onDisk is not null && onDisk.SameAs (rendered)) { _layout = onDisk; - Source.Record (read.Length); + Source.Rewrote (read.Length); } } @@ -748,9 +748,7 @@ void RefreshLayout (Layout rendered, (byte[] Header, long Length)? source) // The read-back runs after the atomic rename has committed the save, so nothing it meets may turn that // success into a failure: it does not observe the caller's token, and a failed read only skips the refresh. - static bool IsReadBackFailure (Exception ex) => - ex is IOException or UnauthorizedAccessException or NotSupportedException or ArgumentException - or OperationCanceledException or InvalidOperationException; // InvalidOperation covers ObjectDisposed + static bool IsReadBackFailure (Exception ex) => SavedOverSource.IsReadBackFailure (ex); async Task<(byte[] Header, long Length)?> ReadSourceHeaderAsync (IFileSystem? fileSystem) { diff --git a/src/TagLibSharp2/Core/AudioProperties.cs b/src/TagLibSharp2/Core/AudioProperties.cs index 71e616e2..c3a29d9c 100644 --- a/src/TagLibSharp2/Core/AudioProperties.cs +++ b/src/TagLibSharp2/Core/AudioProperties.cs @@ -64,7 +64,7 @@ public static AudioProperties FromFlac ( // Calculate bitrate: (samples * bits * channels) / duration in seconds / 1000 var bitrate = duration > TimeSpan.Zero - ? (int)((double)totalSamples * bitsPerSample * channels / duration.TotalSeconds / 1000) + ? Rates.Kbps ((double)totalSamples * bitsPerSample * channels / duration.TotalSeconds) : 0; return new AudioProperties (duration, bitrate, sampleRate, bitsPerSample, channels, "FLAC"); @@ -126,7 +126,7 @@ public static AudioProperties FromOpus ( // Calculate bitrate from file size and duration var bitrate = duration.TotalSeconds > 0 - ? (int)(fileSize * 8 / duration.TotalSeconds / 1000) + ? Rates.Kbps (fileSize * 8 / duration.TotalSeconds) : 0; return new AudioProperties (duration, bitrate, OutputSampleRate, 0, channels, "Opus"); @@ -150,7 +150,7 @@ public static AudioProperties FromDsf ( { // DSD bitrate: sampleRate * 1 bit * channels / 1000 // Use long arithmetic to prevent overflow with high sample rates + many channels - var bitrate = sampleRate > 0 ? (int)((long)sampleRate * channels / 1000) : 0; + var bitrate = sampleRate > 0 ? Rates.Kbps ((long)sampleRate * channels) : 0; return new AudioProperties (duration, bitrate, sampleRate, 1, channels, "DSD"); } @@ -175,7 +175,7 @@ public static AudioProperties FromDff ( { // DSD bitrate: sampleRate * 1 bit * channels / 1000 // Use long arithmetic to prevent overflow with high sample rates + many channels - var bitrate = sampleRate > 0 ? (int)((long)sampleRate * channels / 1000) : 0; + var bitrate = sampleRate > 0 ? Rates.Kbps ((long)sampleRate * channels) : 0; var codec = isDst ? "DST" : "DSD"; return new AudioProperties (duration, bitrate, sampleRate, 1, channels, codec); diff --git a/src/TagLibSharp2/Core/ChunkExtent.cs b/src/TagLibSharp2/Core/ChunkExtent.cs new file mode 100644 index 00000000..092092c9 --- /dev/null +++ b/src/TagLibSharp2/Core/ChunkExtent.cs @@ -0,0 +1,21 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +namespace TagLibSharp2.Core; + +/// +/// The one rule the RIFF (#192) and IFF (#197) chunk walks keep a chunk by, in memory and from a stream alike: a form +/// ends at its declared size, or at the end of the data when that size is the 0xFFFFFFFF a streamed writer leaves or +/// runs past the data; a chunk holds its bytes present, up to its declared size and never past the form's end. A size +/// past them (a cut-off file, a placeholder) keeps the bytes present, and bytes after the form are not the chunk's. +/// +internal static class ChunkExtent +{ + /// Where a form whose 8-byte header declares ends in bytes. + public static long FormEnd (uint declared, long length) => + declared == uint.MaxValue ? length : Math.Min (length, 8L + declared); + + /// The bytes a chunk that starts at and declares keeps. + public static long PresentBytes (uint size, long dataStart, long formEnd) => + Math.Max (0, Math.Min (size, formEnd - dataStart)); +} diff --git a/src/TagLibSharp2/Core/ChunkLayout.cs b/src/TagLibSharp2/Core/ChunkLayout.cs new file mode 100644 index 00000000..f54795f5 --- /dev/null +++ b/src/TagLibSharp2/Core/ChunkLayout.cs @@ -0,0 +1,48 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +namespace TagLibSharp2.Core; + +/// +/// The layout a chunk save writes: the form header, each chunk it writes from memory, and each chunk it copies from +/// the source, with the offset the copied bytes land at. A save over the source moves the chunks it copies when a +/// chunk ahead of them changes size (an edited AIFF NAME, a WAV LIST INFO before the data), and the next save from the +/// same object has to copy them from where they now are. After a save, reads the source back +/// (): when it is this layout, the object takes as the offsets of its +/// copied chunks, as a fresh read of the file would find them. A save elsewhere, or a source another program has +/// rewritten, keeps the offsets of the read. +/// +internal sealed class ChunkLayout +{ + readonly List _parts = []; + readonly List<(int Index, long Offset)> _copied = []; + + /// The bytes the layout covers so far, which is the offset of the next part. + public long Length { get; private set; } + + /// The copied chunks: each one's index in the caller's list and the offset its bytes were written at. + public IReadOnlyList<(int Index, long Offset)> Copied => _copied; + + /// Bytes written as they are: the form header, or a chunk rendered in memory. + public void Written (ReadOnlyMemory bytes) + { + _parts.Add (new WrittenBytes (Length, bytes)); + Length += bytes.Length; + } + + /// A chunk whose is written and whose bytes are copied from the source: + /// bytes in all, header and pad included; caller's index . + public void Copy (int index, ReadOnlyMemory header, long size) + { + _parts.Add (new WrittenBytes (Length, header)); + _copied.Add ((index, Length + header.Length)); + Length += size; + } + + /// Bytes after the form, copied as they were; the layout checks only the length. + public void Trail (long length) => Length += length; + + /// Whether the source is now this layout: as long, and holding every part written at its offset. + public bool Holds (string? sourcePath, IFileSystem? fileSystem) => + SavedOverSource.Holds (sourcePath, fileSystem, Length, [.. _parts]); +} diff --git a/src/TagLibSharp2/Core/Durations.cs b/src/TagLibSharp2/Core/Durations.cs index b41e8db4..9693a6f2 100644 --- a/src/TagLibSharp2/Core/Durations.cs +++ b/src/TagLibSharp2/Core/Durations.cs @@ -4,15 +4,40 @@ namespace TagLibSharp2.Core; /// -/// Durations from counts a file supplies. A sample count over a rate can be past , -/// and then throws (#175). +/// Durations from counts a file supplies, the one rule every reader goes through (#181). A duration that is not a +/// positive finite value can hold is unknown: , or null through +/// on a nullable property. No format spec sets a maximum or a clamp rule; ffprobe reports N/A +/// where a duration stops fitting its 64-bit time field. #175 saturated at instead, +/// and adding anything to that throws. /// internal static class Durations { - // Just under TimeSpan.MaxValue.TotalSeconds, so the conversion cannot round past it. + // Just under TimeSpan.MaxValue.TotalSeconds, so no conversion can round past it. const double MaxSeconds = 922_337_203_685d; + const double MaxTicks = MaxSeconds * TimeSpan.TicksPerSecond; - /// that saturates at instead of throwing. + /// Seconds as gives them, or unknown. public static TimeSpan FromSeconds (double seconds) => - seconds >= MaxSeconds ? TimeSpan.MaxValue : TimeSpan.FromSeconds (seconds); + IsKnown (seconds) ? TimeSpan.FromSeconds (seconds) : TimeSpan.Zero; + + /// + /// Seconds rounded to the nearest tick, or unknown. rounds to whole + /// milliseconds before .NET Core 3.0. + /// + public static TimeSpan FromSecondsToTicks (double seconds) => + IsKnown (seconds) ? TimeSpan.FromTicks ((long)Math.Round (seconds * TimeSpan.TicksPerSecond)) : TimeSpan.Zero; + + /// Ticks (100 ns units) rounded to the nearest tick, or unknown. + public static TimeSpan FromTicks (double ticks) => + ticks > 0 && ticks < MaxTicks ? TimeSpan.FromTicks ((long)Math.Round (ticks)) : TimeSpan.Zero; + + /// A count of ticks (100 ns units) a file states, or unknown when cannot hold it. + public static TimeSpan FromTickCount (ulong ticks) => + ticks is > 0 and < (ulong)MaxTicks ? TimeSpan.FromTicks ((long)ticks) : TimeSpan.Zero; + + /// A known duration, or null for unknown. + public static TimeSpan? OrNull (TimeSpan duration) => duration > TimeSpan.Zero ? duration : null; + + // NaN fails both comparisons. + static bool IsKnown (double seconds) => seconds > 0 && seconds < MaxSeconds; } diff --git a/src/TagLibSharp2/Core/FormTrail.cs b/src/TagLibSharp2/Core/FormTrail.cs new file mode 100644 index 00000000..58b7cdcf --- /dev/null +++ b/src/TagLibSharp2/Core/FormTrail.cs @@ -0,0 +1,95 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +namespace TagLibSharp2.Core; + +/// +/// The bytes of a file after its RIFF or IFF form ends, at its declared size. They are not the form's, so no chunk walk +/// reads them (#192, #197), but they are the file's, and a save writes them after the form as they were: a save never +/// drops them. Readers differ on such bytes (exiftool reads an ID3 chunk after the FORM of taglib-samples' sample.aif; +/// ffprobe and MediaInfo do not), and the library keeps them without reading them. A read of the bytes holds them. A +/// stream read leaves them in the file: they are its last bytes, which is where every save writes +/// them, so a save copies them from the end of its source, after a save over that source as well. A source another +/// program rewrote since the read is not detected, as it is not for the sound a stream read leaves in the file. +/// +internal sealed class FormTrail +{ + ReadOnlyMemory? _bytes; + + FormTrail (long length, ReadOnlyMemory? bytes, long superseded) + { + Length = length; + _bytes = bytes; + Superseded = superseded; + } + + /// The number of bytes after the form. + public long Length { get; } + + /// + /// How many of the first bytes are tag chunks the form's tag supersedes (): a save that + /// rewrites the form's tag drops them (). + /// + public long Superseded { get; } + + /// The bytes after the form ends at in , held, or null. + /// The first of them are superseded tag chunks. + public static FormTrail? Of (ReadOnlyMemory data, long formEnd, long superseded = 0) => + formEnd < data.Length ? new (data.Length - formEnd, data[(int)formEnd..], superseded) : null; + + /// The bytes after the form ends at in a source of + /// bytes, left there, or null. The first of them are superseded tag chunks. + public static FormTrail? InSource (long formEnd, long length, long superseded = 0) => + formEnd < length ? new (length - formEnd, null, superseded) : null; + + /// + /// The bytes a save writes after the form: these, or, when there are superseded tag chunks and + /// says the save writes the form's tag other than as it was read, the bytes after + /// those chunks (null when there are none). is asked only when there are such chunks. + /// + public FormTrail? For (Func tagRewritten) + { + if (Superseded == 0 || !tagRewritten ()) + return this; + return Length > Superseded ? new (Length - Superseded, _bytes?[(int)Superseded..], 0) : null; + } + + /// + /// Holds the bytes, read from the end of , bytes long, when + /// they were left there, for a render in memory. False when they do not fit in memory or the source no longer has + /// them. + /// + public bool TryLoad (Stream source, long sourceLength) + { + if (_bytes is not null) + return true; + if (Length > int.MaxValue || sourceLength < Length) + return false; + + source.Position = sourceLength - Length; + var bytes = StreamBytes.ReadAtMost (source, (int)Length); + if (bytes.Length != Length) + return false; + _bytes = bytes; + return true; + } + + /// The bytes, once held (). + public ReadOnlySpan Bytes => _bytes is { } bytes ? bytes.Span : throw new InvalidOperationException ("The bytes after the form were not loaded."); + + /// Whether the bytes are held. + public bool Held => _bytes is not null; + + /// Writes the bytes to : the ones held, or the last ones of + /// , bytes long. + public void Write (Stream output, Stream source, long sourceLength, byte[] scratch) + { + if (_bytes is { } bytes) { + StreamCopy.Write (output, bytes.Span, scratch); + return; + } + + source.Position = sourceLength - Length; + StreamCopy.Copy (source, output, Length, scratch); + } +} diff --git a/src/TagLibSharp2/Core/Rates.cs b/src/TagLibSharp2/Core/Rates.cs new file mode 100644 index 00000000..70adb054 --- /dev/null +++ b/src/TagLibSharp2/Core/Rates.cs @@ -0,0 +1,47 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +namespace TagLibSharp2.Core; + +/// +/// Sample rates and bit rates from fields a file supplies, read into the int properties without wrapping (#194). +/// A sample rate an int cannot hold is no sample rate (0), as WavPack's reader rules; a bit rate is worked out +/// in 64 bits. +/// +internal static class Rates +{ + /// A 32-bit sample rate field, or 0 past . + public static int SampleRate (uint value) => Count (value); + + /// A count field of up to 64 bits (Matroska's channels), or 0 past . + public static int Count (ulong value) => value <= int.MaxValue ? (int)value : 0; + + /// A 32-bit count field (channels, bits, a block size), or 0 past . + public static int Count (uint value) => value <= int.MaxValue ? (int)value : 0; + + /// A sample rate stored as a real number (AIFF's 80-bit extended), rounded, or 0 when it is not a + /// non-negative value an int holds. + public static int SampleRate (double value) + { + var rounded = Math.Round (value); + return rounded is >= 0 and <= int.MaxValue ? (int)rounded : 0; + } + + /// + /// Kilobits per second from a real number of bits per second (a size over a duration), or 0 when it is not a + /// non-negative value an int holds (#198). The cast this replaces saturated on net9.0 and later and wrapped + /// before. + /// + public static int Kbps (double bitsPerSecond) + { + var kbps = Math.Truncate (bitsPerSecond / 1000); + return kbps is >= 0 and <= int.MaxValue ? (int)kbps : 0; + } + + /// Kilobits per second from bits per second, or 0 past what an int holds. + public static int Kbps (long bitsPerSecond) + { + var kbps = bitsPerSecond / 1000; + return kbps is >= 0 and <= int.MaxValue ? (int)kbps : 0; + } +} diff --git a/src/TagLibSharp2/Core/SavedOverSource.cs b/src/TagLibSharp2/Core/SavedOverSource.cs new file mode 100644 index 00000000..f51e0fe5 --- /dev/null +++ b/src/TagLibSharp2/Core/SavedOverSource.cs @@ -0,0 +1,78 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +namespace TagLibSharp2.Core; + +/// Bytes a save wrote, and the offset in the file it wrote them at. +internal readonly struct WrittenBytes (long offset, ReadOnlyMemory bytes) +{ + /// The offset of the first byte in the file. + public long Offset { get; } = offset; + + /// The bytes. + public ReadOnlyMemory Bytes { get; } = bytes; +} + +/// +/// Whether a save rewrote the file an object was read from (#179). A format that keeps the offsets of the file it read +/// (a tag size, a metadata size, a stream's extent) takes the offsets of the file it wrote when that file is now its +/// source, so its next save reads the source at offsets that fit it. The source is read back after the save, so the +/// answer holds under any spelling of its path (case, ".", "..", a link). +/// +internal static class SavedOverSource +{ + /// + /// Whether the file at is bytes long and holds each of + /// at its offset. A save elsewhere leaves the source as it was, and answers false unless + /// the source already held those bytes at those offsets, which then give it the same layout. A source that cannot + /// be read answers false. + /// + public static bool Holds (string? sourcePath, IFileSystem? fileSystem, long length, params WrittenBytes[] parts) + { + if (sourcePath is null) + return false; + + byte[]? chunk = null; + try { + using var stream = (fileSystem ?? DefaultFileSystem.Instance).OpenRead (sourcePath); + if (stream.Length != length) + return false; + + chunk = StreamCopy.Rent (); + foreach (var part in parts) { + if (!Matches (stream, part, chunk)) + return false; + } + + return true; + } catch (Exception ex) when (IsReadBackFailure (ex)) { + return false; + } finally { + if (chunk is not null) + StreamCopy.Return (chunk); + } + } + + /// + /// 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. + /// + public static bool IsReadBackFailure (Exception ex) => + ex is IOException or UnauthorizedAccessException or NotSupportedException or ArgumentException + or OperationCanceledException or InvalidOperationException; // InvalidOperation covers ObjectDisposed + + static bool Matches (Stream stream, WrittenBytes part, byte[] chunk) + { + var expected = part.Bytes.Span; + stream.Position = part.Offset; + var done = 0; + while (done < expected.Length) { + var read = stream.Read (chunk, 0, Math.Min (chunk.Length, expected.Length - done)); + if (read <= 0 || !chunk.AsSpan (0, read).SequenceEqual (expected.Slice (done, read))) + return false; + done += read; + } + + return true; + } +} diff --git a/src/TagLibSharp2/Core/SourceLength.cs b/src/TagLibSharp2/Core/SourceLength.cs index e531c56e..0038bf82 100644 --- a/src/TagLibSharp2/Core/SourceLength.cs +++ b/src/TagLibSharp2/Core/SourceLength.cs @@ -13,16 +13,42 @@ internal sealed class SourceLength { readonly List _lengths = new (2); - /// Records the file a read saw, or the one file the object describes from now on. + // The first length is the file the object last saved over its source, not the one it read. + bool _rewritten; + + /// Records the file a read saw, the one file the object describes from now on. public void Record (long length) { _lengths.Clear (); _lengths.Add (length); + _rewritten = false; + } + + /// + /// Records the file a save wrote over the source, for a format that from then on describes that file in place of + /// the one it read (#179). + /// + public void Rewrote (long length) + { + Record (length); + _rewritten = true; } /// - /// Adds the file a successful save wrote, for a format whose state then describes that file. A file of - /// bytes or more cannot be passed as a span, so it is not added. + /// Records the length of the file a read saw in the file of , when the read made one, and + /// returns the result. A stream reader passes the stream's length: it parses only part of the stream. + /// + public static TResult Recorded (TResult result, long length) where TResult : ISourceRecorder + { + result.Source?.Record (length); + return result; + } + + /// + /// Adds the file a successful save wrote, for a format whose state then describes that file. A write of + /// bytes or more reports + /// ( is an ), which is not the file's length, so that + /// count is not added. /// public FileWriteResult Saved (FileWriteResult result) { @@ -40,20 +66,29 @@ public async Task Saved (Task save) => /// /// The failure a save from bytes returns when they are not a file the object describes, - /// or null when they are. + /// or null when they are. names them in the message: the original data a span save was + /// given, or the source file a path save copies from. /// - public FileWriteResult? Refuse (string format, long length) + public FileWriteResult? Refuse (string format, long length, string bytes = "the original data") { if (Describes (length)) return null; - var read = _lengths.Count > 0 ? _lengths[0] : 0; + var first = _lengths.Count > 0 ? _lengths[0] : 0; + var described = _rewritten ? "the file it last saved over its source" : "the file it was read from"; var saved = _lengths.Count switch { <= 1 => "", 2 => $", and the file it saved was {_lengths[1]} bytes", _ => $", and the files it saved were {string.Join (", ", _lengths.Skip (1))} bytes", }; return FileWriteResult.Failure ( - $"Cannot save this {format} file: the original data is {length} bytes, but the file it was read from was {read} bytes{saved}."); + $"Cannot save this {format} file: {bytes} is {length} bytes, but {described} was {first} bytes{saved}."); } } + +/// A read result whose file keeps the lengths of the files it describes. +internal interface ISourceRecorder +{ + /// The lengths the file of the result keeps, or null when the read failed. + SourceLength? Source { get; } +} diff --git a/src/TagLibSharp2/Core/TrailingTagChunk.cs b/src/TagLibSharp2/Core/TrailingTagChunk.cs new file mode 100644 index 00000000..24a15ba7 --- /dev/null +++ b/src/TagLibSharp2/Core/TrailingTagChunk.cs @@ -0,0 +1,125 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Buffers.Binary; +using TagLibSharp2.Id3.Id3v2; + +namespace TagLibSharp2.Core; + +/// +/// A tag chunk a tagger appended after a RIFF or IFF form without growing the form's size: the bytes right after the +/// form are one whole chunk whose identifier is the one the format reads its ID3 tag from, in either case (a WAV's +/// "id3 " or "ID3 "), and whose body is an ID3v2 tag (version 2.2, 2.3 or 2.4) that holds at least one field. exiftool +/// reads such a chunk in either format, and ffprobe in a WAV file. Every read takes it as the file's tag chunk when the +/// form holds none, so a save writes the tag in the form and the stale copy after it is gone. More such chunks right +/// after it, or right after a form that holds its own tag, are superseded +/// (): a save that rewrites the form's tag drops them, so +/// ffprobe shows no old title beside the new one, and a save that leaves the tag as read carries them as they were. +/// Every other byte after the form is the form's trail (), carried as it was: a chunk cut short +/// or declaring more than the file holds, a tag that reads no field (only its header is a tag's), and bytes before such +/// a chunk. An ID3v2.2 tag, such as taglib-samples' sample.aif holds, is read whole and written in the form as ID3v2.3 +/// (#187). +/// +internal static class TrailingTagChunk +{ + /// + /// The tag chunk at the start of , the bytes after the form: its body and the bytes it takes + /// (header, body and the pad byte of an odd body when it is there). + /// + public static bool TryRead (ReadOnlySpan trail, bool bigEndian, string[] tagIds, out TrailingTag tag) + { + tag = default; + if (!TryHeader (trail, bigEndian, tagIds, out var size) || 8 + size > trail.Length) + return false; + + var candidate = trail.Slice (8, (int)size); + if (!IsTag (candidate, droppedPictures: false)) + return false; + + tag = new TrailingTag (candidate.ToArray (), 8 + size + ((size & 1) == 1 && 8 + size < trail.Length ? 1 : 0), false); + return true; + } + + /// + /// The tag chunk at in , bytes long, as + /// finds it in bytes. With + /// the body is the tag copied without its pictures. The stream is left after the + /// chunk when it is one, and where it was otherwise. + /// + public static bool TryRead (Stream stream, long at, long length, bool bigEndian, string[] tagIds, bool skipPictures, + out TrailingTag tag) + { + tag = default; + if (at + 8 > length) + return false; + + var start = stream.Position; + stream.Position = at; + var header = StreamBytes.ReadAtMost (stream, 8); + if (!TryHeader (header, bigEndian, tagIds, out var size) || at + 8 + size > length) { + stream.Position = start; + return false; + } + + var bodyEnd = at + 8 + size; + var stripped = skipPictures ? Id3v2Tag.CopyWithoutPictures (stream, bodyEnd) : default; + var candidate = skipPictures ? stripped.Bytes : StreamBytes.ReadAtMost (stream, (int)size); + if (!IsTag (candidate, stripped.DroppedPictures)) { + stream.Position = start; + return false; + } + + var taken = 8 + size + ((size & 1) == 1 && bodyEnd < length ? 1 : 0); + tag = new TrailingTag (candidate, taken, stripped.DroppedPictures); + stream.Position = at + taken; + return true; + } + + /// + /// How many bytes at the start of , after a form whose tag is already read, are tag chunks + /// that tag supersedes: one after another, each a whole chunk that + /// would take. + /// + public static long Superseded (ReadOnlySpan trail, bool bigEndian, string[] tagIds) + { + long superseded = 0; + while (superseded < trail.Length && TryRead (trail[(int)superseded..], bigEndian, tagIds, out var tag)) + superseded += tag.Taken; + return superseded; + } + + /// + /// on the chunks at in + /// , bytes long. Their pictures are not read. The stream is left + /// where it was. + /// + public static long Superseded (Stream stream, long at, long length, bool bigEndian, string[] tagIds) + { + var start = stream.Position; + long superseded = 0; + while (TryRead (stream, at + superseded, length, bigEndian, tagIds, skipPictures: true, out var tag)) + superseded += tag.Taken; + stream.Position = start; + return superseded; + } + + // An ID3v2.2, v2.3 or v2.4 tag that reads and holds a field: a picture its copy left out is one. + static bool IsTag (ReadOnlySpan body, bool droppedPictures) => + body.Length > 3 && body[3] is 2 or 3 or 4 && Id3v2Tag.Read (body) is { IsSuccess: true, Tag: { } tag } && (droppedPictures || !tag.IsEmpty); + + // The chunk's identifier is one of the format's tag chunk identifiers, in either case. + static bool TryHeader (ReadOnlySpan header, bool bigEndian, string[] tagIds, out long size) + { + size = 0; + if (header.Length < 8) + return false; + + var fourCC = new string ([(char)header[0], (char)header[1], (char)header[2], (char)header[3]]); + size = bigEndian ? BinaryPrimitives.ReadUInt32BigEndian (header.Slice (4)) : BinaryPrimitives.ReadUInt32LittleEndian (header.Slice (4)); + return Array.Exists (tagIds, id => string.Equals (fourCC.TrimEnd ('\0'), id, StringComparison.OrdinalIgnoreCase)) && size <= int.MaxValue; + } +} + +/// A tag chunk read after the form: its body (without its pictures when they were not read, and then +/// says whether it had any) and the bytes it takes. +internal readonly record struct TrailingTag (byte[] Body, long Taken, bool DroppedPictures); diff --git a/src/TagLibSharp2/Dff/DffFile.cs b/src/TagLibSharp2/Dff/DffFile.cs index d2f273b8..53160b15 100644 --- a/src/TagLibSharp2/Dff/DffFile.cs +++ b/src/TagLibSharp2/Dff/DffFile.cs @@ -100,13 +100,13 @@ internal DffAudioProperties ( ulong sampleCount, DffCompressionType compressionType) { - SampleRate = (int)sampleRate; - Channels = (int)channelCount; + SampleRate = Rates.SampleRate (sampleRate); + Channels = Rates.Count (channelCount); CompressionType = compressionType; Codec = compressionType == DffCompressionType.Dst ? "DST" : "DSD"; // Calculate bitrate: sampleRate * channels / 1000 (1 bit per sample for DSD) - Bitrate = sampleRate > 0 ? (int)((long)sampleRate * channelCount / 1000) : 0; + Bitrate = Rates.Kbps ((long)SampleRate * Channels); // Calculate duration if (sampleRate > 0 && sampleCount > 0) @@ -152,6 +152,18 @@ internal void MarkPicturesSkipped () TagCreation? _creation; private IFileSystem? _sourceFileSystem; private ulong _sampleCount; + + /// + /// The samples per channel of a DSD chunk: its bits (DSD is 1 bit per sample, DSDIFF 1.5) over the channels, worked + /// out without wrapping (#182). A count past 64 bits is 0, unknown. + /// + static ulong SamplesPerChannel (ulong bytes, ulong channels) + { + var whole = bytes / channels; + if (whole > ulong.MaxValue / 8) + return 0; + return whole * 8 + bytes % channels * 8 / channels; + } /// The files this object describes; a save from caller bytes must be one of them (#178). internal SourceLength Source { get; } = new (); @@ -316,11 +328,9 @@ static DffFileReadResult Parse (ReadOnlySpan data, bool audioElided) if (!foundProp) return DffFileReadResult.Failure ("Invalid DFF file: PROP chunk must precede audio data"); - // Sample count = data size * 8 / channels (1 bit per sample) // Use chunk SIZE (not available data) to calculate samples - if (file.Channels > 0) { - file._sampleCount = chunkSize * 8 / (ulong)file.Channels; - } + if (file.Channels > 0) + file._sampleCount = SamplesPerChannel (chunkSize, (ulong)file.Channels); foundAudio = true; break; @@ -566,7 +576,7 @@ private static void ParsePropChunk (ReadOnlySpan data, DffFile file, ref b switch (chunkId) { case "FS ": // Sample rate if (chunkSize >= 4) { - file.SampleRate = (int)BinaryPrimitives.ReadUInt32BigEndian (data.Slice (offset + 12, 4)); + file.SampleRate = Rates.SampleRate (BinaryPrimitives.ReadUInt32BigEndian (data.Slice (offset + 12, 4))); file.DsdRate = file.SampleRate switch { 2822400 => DsfSampleRate.DSD64, 5644800 => DsfSampleRate.DSD128, diff --git a/src/TagLibSharp2/Dsf/DsfFile.cs b/src/TagLibSharp2/Dsf/DsfFile.cs index 15beb27a..50729141 100644 --- a/src/TagLibSharp2/Dsf/DsfFile.cs +++ b/src/TagLibSharp2/Dsf/DsfFile.cs @@ -49,17 +49,17 @@ public sealed class DsfAudioProperties : Core.IMediaProperties internal DsfAudioProperties (DsfFmtChunk fmtChunk) { - // A duration past TimeSpan.MaxValue is TimeSpan.MaxValue (DsfFmtChunk.Duration, #175). + // A duration TimeSpan cannot hold is unknown (DsfFmtChunk.Duration, #181). Duration = fmtChunk.Duration; - SampleRate = (int)fmtChunk.SampleRate; - Channels = (int)fmtChunk.ChannelCount; - BitsPerSample = (int)fmtChunk.BitsPerSample; + SampleRate = Rates.SampleRate (fmtChunk.SampleRate); + Channels = Rates.Count (fmtChunk.ChannelCount); + BitsPerSample = Rates.Count (fmtChunk.BitsPerSample); DsdRate = fmtChunk.DsdRate; ChannelType = fmtChunk.ChannelType; - BlockSizePerChannel = (int)fmtChunk.BlockSizePerChannel; + BlockSizePerChannel = Rates.Count (fmtChunk.BlockSizePerChannel); // Calculate bitrate: sampleRate * channels / 1000 (1 bit per sample for DSD) - Bitrate = SampleRate > 0 ? (int)((long)SampleRate * Channels / 1000) : 0; + Bitrate = Rates.Kbps ((long)SampleRate * Channels); } } @@ -153,6 +153,10 @@ internal void MarkPicturesSkipped () private readonly DsfFmtChunk _fmtChunk; private readonly DsfDataChunk _dataChunk; private readonly int _audioDataOffset; + + // Where the sound of the file that was read ends: its metadata offset, or the end of the file when it had no ID3 + // tag. Every file a save writes keeps the sound there, so the object describes each of them (#179). + private readonly long _audioDataEnd; private IFileSystem? _sourceFileSystem; /// The files this object describes; a save from caller bytes must be one of them (#178). internal SourceLength Source { get; } = new (); @@ -176,17 +180,17 @@ internal void MarkPicturesSkipped () /// /// Gets the sample rate in Hz. /// - public int SampleRate => (int)_fmtChunk.SampleRate; + public int SampleRate => Rates.SampleRate (_fmtChunk.SampleRate); /// /// Gets the number of audio channels. /// - public int Channels => (int)_fmtChunk.ChannelCount; + public int Channels => Rates.Count (_fmtChunk.ChannelCount); /// /// Gets the bits per sample (always 1 for DSD). /// - public int BitsPerSample => (int)_fmtChunk.BitsPerSample; + public int BitsPerSample => Rates.Count (_fmtChunk.BitsPerSample); /// /// Gets the total number of samples per channel. @@ -211,7 +215,7 @@ internal void MarkPicturesSkipped () /// /// Gets the block size per channel. /// - public int BlockSizePerChannel => (int)_fmtChunk.BlockSizePerChannel; + public int BlockSizePerChannel => Rates.Count (_fmtChunk.BlockSizePerChannel); /// /// Gets the audio properties for this file. @@ -254,6 +258,7 @@ private DsfFile ( DsfFmtChunk fmtChunk, DsfDataChunk dataChunk, int audioDataOffset, + long fileLength, Id3v2Tag? tag) { _originalData = originalData; @@ -261,6 +266,7 @@ private DsfFile ( _fmtChunk = fmtChunk; _dataChunk = dataChunk; _audioDataOffset = audioDataOffset; + _audioDataEnd = dsdChunk.HasMetadata ? (long)dsdChunk.MetadataOffset : fileLength; Id3v2Tag = tag; } @@ -342,7 +348,7 @@ public static DsfFileReadResult Read (ReadOnlySpan data) // Make a copy of the data for later rendering var originalData = data.ToArray (); - var file = new DsfFile (originalData, dsdChunk, fmtChunk, dataChunk, audioDataOffset, tag); + var file = new DsfFile (originalData, dsdChunk, fmtChunk, dataChunk, audioDataOffset, data.Length, tag); file.Properties = new DsfAudioProperties (fmtChunk); file.Source.Record (data.Length); return DsfFileReadResult.Success (file); @@ -415,7 +421,7 @@ internal static DsfFileReadResult Read (Stream stream, string? sourcePath, IFile } } - var parsed = new DsfFile (null, dsdChunk, fmtChunk, dataChunk, audioDataOffset, tag) { + var parsed = new DsfFile (null, dsdChunk, fmtChunk, dataChunk, audioDataOffset, stream.Length, tag) { Properties = new DsfAudioProperties (fmtChunk), SourcePath = sourcePath, _sourceFileSystem = fileSystem @@ -560,11 +566,9 @@ bool TryRenderFrom (ReadOnlySpan original, out BinaryData rendered, out st rendered = BinaryData.Empty; error = ""; // Calculate audio data size - var audioDataEnd = _dsdChunk.HasMetadata - ? (long)_dsdChunk.MetadataOffset - : original.Length; + var audioDataEnd = _audioDataEnd; if (audioDataEnd > original.Length || audioDataEnd < _audioDataOffset) { - error = "Cannot render this DSF file: the source no longer holds the sound it was read with."; + error = NoSound; return false; } var audioDataSize = (int)(audioDataEnd - _audioDataOffset); @@ -621,9 +625,9 @@ bool TryRenderFrom (ReadOnlySpan original, out BinaryData rendered, out st /// Saves the file to the specified path using atomic write. /// /// The target file path. - /// The bytes of the file this object was read from, or of a file it has saved since unless - /// that save gave an untagged file an ID3 tag; the sound is taken from them. Bytes of any other length fail with a - /// result, and nothing is written. A file read from memory holds its bytes and saves them, and these are not used. + /// The bytes of the file this object was read from, or of a file it has saved since; the + /// sound is taken from them. Bytes of any other length fail with a result, and nothing is written. A file read from + /// memory holds its bytes and saves them, and these are not used. /// Optional file system abstraction for testing. /// A result indicating success or failure. public FileWriteResult SaveToFile (string path, ReadOnlySpan originalData, IFileSystem? fileSystem = null) @@ -643,16 +647,10 @@ public FileWriteResult SaveToFile (string path, ReadOnlySpan originalData, if (rendered.IsEmpty) return FileWriteResult.Failure ("Failed to render DSF file"); - return Saved (AtomicFileWriter.Write (path, rendered.Span, fs)); + return Source.Saved (AtomicFileWriter.Write (path, rendered.Span, fs)); } - // The object describes the file a save wrote, except when the file it read had no ID3 tag and the save wrote one: - // the object still takes the sound to run to the end of the file, so the tag of the new file would be read as - // sound. - FileWriteResult Saved (FileWriteResult result) => - _dsdChunk.HasMetadata || Id3v2Tag is null ? Source.Saved (result) : result; - - async Task Saved (Task save) => Saved (await save.ConfigureAwait (false)); + const string NoSound = "Cannot render this DSF file: the source no longer holds the sound it was read with."; // Held bytes are the file and render as Render does; otherwise the caller's bytes are the source. bool TryRenderWith (ReadOnlySpan originalData, out BinaryData rendered, out string error) @@ -669,9 +667,9 @@ bool TryRenderWith (ReadOnlySpan originalData, out BinaryData rendered, ou /// Asynchronously saves the file to the specified path using atomic write. /// /// The target file path. - /// The bytes of the file this object was read from, or of a file it has saved since unless - /// that save gave an untagged file an ID3 tag; the sound is taken from them. Bytes of any other length fail with a - /// result, and nothing is written. A file read from memory holds its bytes and saves them, and these are not used. + /// The bytes of the file this object was read from, or of a file it has saved since; the + /// sound is taken from them. Bytes of any other length fail with a result, and nothing is written. A file read from + /// memory holds its bytes and saves them, and these are not used. /// Optional file system abstraction for testing. /// A token to cancel the operation. /// A task containing a result indicating success or failure. @@ -697,7 +695,7 @@ public Task SaveToFileAsync ( return Task.FromResult (FileWriteResult.Failure ("Failed to render DSF file")); cancellationToken.ThrowIfCancellationRequested (); - return Saved (AtomicFileWriter.WriteAsync (path, rendered.Memory, fs, cancellationToken)); + return Source.Saved (AtomicFileWriter.WriteAsync (path, rendered.Memory, fs, cancellationToken)); } /// @@ -724,19 +722,16 @@ public FileWriteResult SaveToFile (string path, IFileSystem? fileSystem = null) var fs = fileSystem ?? _sourceFileSystem; if (_originalData is not null) - return Saved (WriteHeld (path, fs)); + return Source.Saved (WriteHeld (path, fs)); - return Saved (SaveFromSource (path, fs)); + return Source.Saved (SaveFromSource (path, fs)); } // Same bytes as Render. The audio slice is the held sample bytes, written in chunks. // The source file is not opened: a later edit of the file on disk does not change this save. FileWriteResult WriteHeld (string destinationPath, IFileSystem? fileSystem, CancellationToken cancellationToken = default) { - var audioDataEnd = _dsdChunk.HasMetadata - ? (int)_dsdChunk.MetadataOffset - : _originalData!.Length; - var audioDataSize = audioDataEnd - _audioDataOffset; + var audioDataSize = (int)(_audioDataEnd - _audioDataOffset); if (audioDataSize < 0) return FileWriteResult.Failure ("Failed to render DSF file"); @@ -778,9 +773,9 @@ FileWriteResult SaveFromSource (string destinationPath, IFileSystem? fileSystem, if (!PathSave.TryOpen (SourcePath!, fileSystem, out source, out var error)) return error; - var fileLength = source!.Length; - var audioDataEnd = _dsdChunk.HasMetadata ? MetadataEnd () : fileLength; - var audioDataSize = audioDataEnd - _audioDataOffset; + if (_audioDataEnd > source!.Length) + return FileWriteResult.Failure (NoSound); + var audioDataSize = _audioDataEnd - _audioDataOffset; if (audioDataSize < 0) return FileWriteResult.Failure ("Failed to render DSF file"); @@ -821,16 +816,6 @@ FileWriteResult SaveFromSource (string destinationPath, IFileSystem? fileSystem, } } - // Render casts a metadata offset to int. Values that fit use that same cast. - long MetadataEnd () - { - var offset = _dsdChunk.MetadataOffset; - if (offset > int.MaxValue) - return (long)offset; - - return (int)offset; - } - /// /// Saves the file back to its source path. /// @@ -879,9 +864,9 @@ public Task SaveToFileAsync ( return Task.FromResult (FileWriteResult.Failure ("No source path available. File was not read from disk.")); if (_originalData is not null) - return Task.FromResult (Saved (WriteHeld (path, fileSystem ?? _sourceFileSystem, cancellationToken))); + return Task.FromResult (Source.Saved (WriteHeld (path, fileSystem ?? _sourceFileSystem, cancellationToken))); - return Task.FromResult (Saved (SaveFromSource (path, fileSystem ?? _sourceFileSystem, cancellationToken))); + return Task.FromResult (Source.Saved (SaveFromSource (path, fileSystem ?? _sourceFileSystem, cancellationToken))); } /// diff --git a/src/TagLibSharp2/Id3/Id3v2/Id3v2Header.cs b/src/TagLibSharp2/Id3/Id3v2/Id3v2Header.cs index 772097b5..e79d6a06 100644 --- a/src/TagLibSharp2/Id3/Id3v2/Id3v2Header.cs +++ b/src/TagLibSharp2/Id3/Id3v2/Id3v2Header.cs @@ -78,8 +78,42 @@ namespace TagLibSharp2.Id3.Id3v2; /// /// Gets the total size of the tag including header and optional footer. /// + /// + /// This trusts the footer flag. A reader that finds where the tag ends asks , + /// which counts the footer only when it is there. + /// public uint TotalSize => (uint)HeaderSize + TagSize + (HasFooter ? (uint)FooterSize : 0u); + /// The offset of the footer from the tag's start: the header and the body. + internal uint FooterOffset => (uint)HeaderSize + TagSize; + + /// + /// The size of the tag that starts : the header, the body, and the footer when the footer + /// flag is set and the footer is there. ID3v2.4 §3.4: the footer is a copy of the header whose identifier is "3DI". + /// A flag with no "3DI" after the body is not a footer, and the 10 bytes after the body are not the tag's: they are + /// the audio's (#202). Data that ends before the footer's identifier has no footer. + /// + internal uint TotalSizeIn (ReadOnlySpan data) => + HasFooter && FooterOffset <= (uint)data.Length && IsFooterIdentifier (data.Slice ((int)FooterOffset)) + ? TotalSize + : FooterOffset; + + /// + /// for the tag that starts at in a seekable + /// stream: the footer's identifier is read there. The stream position moves. + /// + internal uint TotalSizeIn (Stream stream, long tagStart) + { + if (!HasFooter || tagStart + FooterOffset > stream.Length) + return FooterOffset; + stream.Position = tagStart + FooterOffset; + return IsFooterIdentifier (StreamBytes.ReadAtMost (stream, 3)) ? TotalSize : FooterOffset; + } + + /// Whether starts with a footer's identifier, "3DI". + internal static bool IsFooterIdentifier (ReadOnlySpan data) => + data.Length >= 3 && data[0] == '3' && data[1] == 'D' && data[2] == 'I'; + /// /// Initializes a new instance of the struct. /// diff --git a/src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.PictureSkip.cs b/src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.PictureSkip.cs index 750e84ac..14f126f5 100644 --- a/src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.PictureSkip.cs +++ b/src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.PictureSkip.cs @@ -9,10 +9,11 @@ namespace TagLibSharp2.Id3.Id3v2; /// An ID3v2 tag copied without its picture frames. internal readonly struct StrippedId3v2Tag { - public StrippedId3v2Tag (byte[] bytes, int consumed) + public StrippedId3v2Tag (byte[] bytes, int consumed, bool droppedPictures = false) { Bytes = bytes; Consumed = consumed; + DroppedPictures = droppedPictures; } /// Gets the copy: a tag with the same frames except APIC, which reads. @@ -20,6 +21,9 @@ public StrippedId3v2Tag (byte[] bytes, int consumed) /// Gets how many bytes of the original a full read reports as consumed (). public int Consumed { get; } + + /// Gets whether the copy left out a picture frame, so a full read of the original reads a picture. + public bool DroppedPictures { get; } } public sealed partial class Id3v2Tag @@ -79,6 +83,7 @@ internal static StrippedId3v2Tag CopyWithoutPictures (Stream stream, long limit kept.Write (headerBytes, 0, headerBytes.Length); var consumed = 0; + var dropped = false; Span head = stackalloc byte[FrameHeaderSizeV23]; if (header.HasExtendedHeader && remaining >= 4) { reader.Read (head.Slice (0, 4)); @@ -104,6 +109,7 @@ internal static StrippedId3v2Tag CopyWithoutPictures (Stream stream, long limit consumed += headerSize + step.Size; if (step.Id == "APIC") { reader.Skip (step.Size); + dropped = true; continue; } @@ -111,19 +117,21 @@ internal static StrippedId3v2Tag CopyWithoutPictures (Stream stream, long limit reader.CopyTo (kept, step.Size); } - stream.Position = Math.Min (start + header.TotalSize, end); - return new StrippedId3v2Tag (Finish (kept, unsync), Consumed (header, available, consumed, unsync ? stopAt - bodyStart : consumed)); + // A footer counts only when its "3DI" is there, within the bytes a full read would be given (#202). + var totalSize = start + header.FooterOffset <= end ? header.TotalSizeIn (stream, start) : header.FooterOffset; + stream.Position = Math.Min (start + totalSize, end); + return new StrippedId3v2Tag (Finish (kept, unsync), Consumed (totalSize, available, consumed, unsync ? stopAt - bodyStart : consumed), dropped); } // The BytesConsumed rule of Read: a tag that fits reports its total size; a tag cut short by the data reports // the bytes its frames took, counted in stored bytes. - static int Consumed (Id3v2Header header, int available, int decodedConsumed, long storedConsumed) + static int Consumed (uint totalSize, int available, int decodedConsumed, long storedConsumed) { int consumed; - if (header.TotalSize > (uint)available) + if (totalSize > (uint)available) consumed = decodedConsumed <= 0 ? Id3v2Header.HeaderSize : Id3v2Header.HeaderSize + (int)storedConsumed; else - consumed = (int)header.TotalSize; + consumed = (int)totalSize; return consumed < Id3v2Header.HeaderSize ? Math.Min (Id3v2Header.HeaderSize, available) : consumed; } diff --git a/src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.cs b/src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.cs index e6595c30..e78df124 100644 --- a/src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.cs +++ b/src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.cs @@ -1451,7 +1451,8 @@ public static TagReadResult Read (ReadOnlySpan data) // Whole-tag unsync deletes FF 00 pairs, so the de-unsynced end is not a // stored offset. Walk those pairs instead of using the buffer length. int bytesConsumed; - if (header.TotalSize > (uint)data.Length) { + var totalSize = header.TotalSizeIn (data); + if (totalSize > (uint)data.Length) { if (unsyncBuffer is null) bytesConsumed = data.Length - frameData.Length; else { @@ -1461,7 +1462,7 @@ public static TagReadResult Read (ReadOnlySpan data) bytesConsumed = Id3v2Header.HeaderSize + StoredBytesForDecodedPrefix (storedBody, decodedConsumed); } } else - bytesConsumed = (int)Math.Min (header.TotalSize, (uint)data.Length); + bytesConsumed = (int)Math.Min (totalSize, (uint)data.Length); if (bytesConsumed < Id3v2Header.HeaderSize) bytesConsumed = Math.Min (Id3v2Header.HeaderSize, data.Length); diff --git a/src/TagLibSharp2/Image/ImagePlan.cs b/src/TagLibSharp2/Image/ImagePlan.cs index df1971f4..c6c88342 100644 --- a/src/TagLibSharp2/Image/ImagePlan.cs +++ b/src/TagLibSharp2/Image/ImagePlan.cs @@ -91,6 +91,24 @@ public void Append (ImagePlan other) } } + /// The new bytes the plan writes, each at the offset in its output where it starts. + public WrittenBytes[] Literals () + { + var literals = new List (); + long at = 0; + foreach (var piece in _pieces) { + if (!piece.IsRange) + literals.Add (new WrittenBytes (at, piece.Bytes!)); + at += piece.Length; + } + + return [.. literals]; + } + + /// Whether the plan is the whole original file of bytes, unchanged. + public bool IsWhole (long length) => + _pieces.Count == 1 && _pieces[0].IsRange && _pieces[0].Offset == 0 && _pieces[0].Length == length; + /// Copies the plan into one buffer. /// The original file. /// The bytes the plan produces. @@ -113,7 +131,7 @@ public byte[] Materialize (ReadOnlySpan source) /// The original file. public ReadOnlyMemory MaterializeShared (byte[] source) { - if (_pieces.Count == 1 && _pieces[0].IsRange && _pieces[0].Offset == 0 && _pieces[0].Length == source.Length) + if (IsWhole (source.Length)) return source; return Materialize (source); diff --git a/src/TagLibSharp2/Image/ImageRewrite.cs b/src/TagLibSharp2/Image/ImageRewrite.cs index 82f6af29..218e5e37 100644 --- a/src/TagLibSharp2/Image/ImageRewrite.cs +++ b/src/TagLibSharp2/Image/ImageRewrite.cs @@ -27,13 +27,28 @@ static class ImageRewrite return null; var tag = new ImageTag (format, stores); - if (format == MediaFormat.Png) + Read (data, tag); + return tag; + } + + /// + /// Makes what a fresh read of gives: the text the file holds, and + /// nothing changed since. + /// + internal static void Reread (ReadOnlySpan data, ImageTag tag) + { + tag.Reset (); + Read (data, tag); + } + + static void Read (ReadOnlySpan data, ImageTag tag) + { + if (tag.Format == MediaFormat.Png) PngRewriter.Read (data, tag); - else if (format == MediaFormat.Gif) + else if (tag.Format == MediaFormat.Gif) GifRewriter.Read (data, tag); else JpegRewriter.Read (data, tag); - return tag; } internal static byte[] RenderTag (ImageTag tag) diff --git a/src/TagLibSharp2/Image/ImageTag.cs b/src/TagLibSharp2/Image/ImageTag.cs index 9c633257..30ec8634 100644 --- a/src/TagLibSharp2/Image/ImageTag.cs +++ b/src/TagLibSharp2/Image/ImageTag.cs @@ -63,6 +63,14 @@ internal ImageTag (MediaFormat format, ImageStores stores) _ => null }; + /// Forgets every field and every change, as a tag before a read. + internal void Reset () + { + _title = _artist = _description = _copyright = _year = _comment = null; + _dirty = ImageStores.None; + DropUnmapped = false; + } + internal void ReadField (ImageStores field, string? value) { if (field == ImageStores.None || (_stores & field) == 0) diff --git a/src/TagLibSharp2/Image/StillImageFile.cs b/src/TagLibSharp2/Image/StillImageFile.cs index 3558fb12..874f0825 100644 --- a/src/TagLibSharp2/Image/StillImageFile.cs +++ b/src/TagLibSharp2/Image/StillImageFile.cs @@ -22,7 +22,8 @@ namespace TagLibSharp2.Image; /// public sealed class StillImageFile : IMediaFile { - readonly byte[] _data; + // The file the object describes: the one it read, or the one it last saved over its source (#179). + byte[] _data; readonly ImageTag? _tag; IFileSystem? _fileSystem; @@ -245,12 +246,27 @@ FileWriteResult WriteSpliceSource (string path, IFileSystem fileSystem, Cancella var opened = source!; source = null; - return CopyOpened (path, opened, plan, cancellationToken); + return Adopt (CopyOpened (path, opened, plan, cancellationToken), plan, fileSystem); } finally { source?.Dispose (); } } + // A save that rewrote the source leaves the object describing the file it wrote (#179): the next plan is made + // against those bytes, as the next save copies its ranges from them, and the tag holds their text with no change + // pending. An unchanged file stays as it is. + FileWriteResult Adopt (FileWriteResult result, ImagePlan plan, IFileSystem? fileSystem) + { + if (!result.IsSuccess || plan.IsWhole (_data.Length) + || !SavedOverSource.Holds (SourcePath, fileSystem, plan.Length, plan.Literals ())) + return result; + + _data = plan.Materialize (_data); + if (_tag is not null) + ImageRewrite.Reread (_data, _tag); + return result; + } + // Every format this file opens has a plan: a text rewriter, or the original bytes as one range. bool TryOutput ([NotNullWhen (true)] out ImagePlan? plan, [NotNullWhen (false)] out string? error) => ImageRewrite.TryPlan (_data, Format, _tag, out plan, out error); diff --git a/src/TagLibSharp2/Matroska/MatroskaAttachments.cs b/src/TagLibSharp2/Matroska/MatroskaAttachments.cs index 18d14891..92553a2b 100644 --- a/src/TagLibSharp2/Matroska/MatroskaAttachments.cs +++ b/src/TagLibSharp2/Matroska/MatroskaAttachments.cs @@ -276,16 +276,19 @@ public static bool TryBuild ( bool webm, out byte[] element, out bool changed, - out HashSet removed, + out ISet removed, out string error) { element = []; changed = false; - removed = new HashSet (); + // Ordered sets of the UIDs and names a file holds: no hash a file could make collide (#247). + removed = new SortedSet (CountedUidOrder.Instance); if (!TryCollect (data, ranges, out var existing, out var hadCrc, out error)) return false; var matched = new bool[existing.Count]; + // A file sets how many attachments there are, so a picture finds its own in constant time (#244). + var index = new PictureIndex (data, existing); var added = new List<(IPicture Picture, string MediaType)> (); for (var p = 0; p < pictures.Count; p++) { var picture = pictures[p]; @@ -293,12 +296,12 @@ public static bool TryBuild ( // A picture read from this file matches its own attachment with the media type as stored. // The reader surfaces any image/ type, so only a picture that will be written is validated. var stored = picture.MimeType ?? string.Empty; - var index = FindMatch (data, existing, matched, picture, stored); - var mediaType = index >= 0 ? stored : MediaTypeOf (picture); - if (index < 0 && mediaType is not null && !string.Equals (mediaType, stored, StringComparison.OrdinalIgnoreCase)) - index = FindMatch (data, existing, matched, picture, mediaType); - if (index >= 0) { - matched[index] = true; + var at = index.Find (data, existing, matched, picture, stored); + var mediaType = at >= 0 ? stored : MediaTypeOf (picture); + if (at < 0 && mediaType is not null && !string.Equals (mediaType, stored, StringComparison.OrdinalIgnoreCase)) + at = index.Find (data, existing, matched, picture, mediaType); + if (at >= 0) { + matched[at] = true; continue; } @@ -315,8 +318,9 @@ public static bool TryBuild ( added.Add ((picture, mediaType)); } - var usedUids = new HashSet (); - var usedNames = new HashSet (StringComparer.Ordinal); + var usedUids = new SortedSet (CountedUidOrder.Instance); + var usedNames = new SortedSet (StringComparer.Ordinal); + var nextNumbers = new SortedDictionary (StringComparer.Ordinal); var keptFront = false; long capacity = 16; for (var i = 0; i < existing.Count; i++) { @@ -359,7 +363,7 @@ public static bool TryBuild ( // A kept normal cover is already that cover, so a new one goes after the kept attachments. foreach (var (picture, mediaType) in added) { if (picture.PictureType == PictureType.FrontCover && !keptFront) { - AddAttachedFile (body, picture, mediaType, usedNames, usedUids); + AddAttachedFile (body, picture, mediaType, usedNames, nextNumbers, usedUids); attachedFiles++; } } @@ -375,7 +379,7 @@ public static bool TryBuild ( foreach (var (picture, mediaType) in added) { if (picture.PictureType != PictureType.FrontCover || keptFront) { - AddAttachedFile (body, picture, mediaType, usedNames, usedUids); + AddAttachedFile (body, picture, mediaType, usedNames, nextNumbers, usedUids); attachedFiles++; } } @@ -400,38 +404,174 @@ static bool IsNormalCover (string? name) return dot == FrontStem.Length && string.CompareOrdinal (name, 0, FrontStem, 0, FrontStem.Length) == 0; } - static int FindMatch (ReadOnlySpan data, List existing, bool[] matched, IPicture picture, string mediaType) + [ThreadStatic] + static long t_steps; + + // UIDs in order, each comparison counted in Steps. + sealed class CountedUidOrder : IComparer { - var bytes = picture.PictureData.Span; - for (var i = 0; i < existing.Count; i++) { - var entry = existing[i]; - if (matched[i] || !entry.IsPicture) - continue; - var info = entry.Info; - if (!string.Equals (info.MediaType, mediaType, StringComparison.OrdinalIgnoreCase)) - continue; - if (info.PictureType != picture.PictureType) - continue; - var description = picture.Description ?? string.Empty; - // An attachment without FileDescription reads its name as the description. - if (description != info.PictureDescription && !(description.Length == 0 && info.Description is null)) - continue; - if (!data.Slice (entry.Offset + entry.BodyOffset + info.DataOffset, info.DataLength).SequenceEqual (bytes)) - continue; - return i; + public static readonly CountedUidOrder Instance = new (); + + public int Compare (ulong x, ulong y) + { + t_steps++; + return x.CompareTo (y); + } + } + + // A name tried for a new attachment, counted. + static bool Probe (SortedSet usedNames, string name) + { + t_steps++; + return usedNames.Contains (name); + } + + /// + /// The comparisons a save makes to match pictures to attachments and to keep the UIDs it holds, and the names it + /// tries for new pictures, counted per thread, so tests bound this count instead of a wall-clock time. + /// + internal static long Steps { + get => t_steps; + set => t_steps = value; + } + + /// + /// The picture attachments a file holds, ordered by what a picture must share to be one of them: media type (in any + /// case), picture type, description, then the data, shorter first and then by its bytes. takes the + /// first one, in file order, not yet matched, whose data is the picture's: a binary search finds its run of equal + /// keys, walked from where the last match in it left off. Finding every picture takes O(n log n) comparisons, whatever + /// the content: no hash a file could make collide (#247). + /// + sealed class PictureIndex + { + readonly struct Key (int entry, string mediaType, PictureType type, string description, int offset, int length) + { + public int Entry { get; } = entry; + + public string MediaType { get; } = mediaType; + + public PictureType Type { get; } = type; + + public string Description { get; } = description; + + public int Offset { get; } = offset; + + public int Length { get; } = length; + } + + readonly Key[] _keys; + + // For each run of equal keys, by its first position, the position its walk has reached. + readonly int[] _next; + + public PictureIndex (ReadOnlySpan data, List existing) + { + var keys = new List (); + for (var i = 0; i < existing.Count; i++) { + var entry = existing[i]; + if (!entry.IsPicture) + continue; + var info = entry.Info; + var mediaType = (info.MediaType ?? string.Empty).ToUpperInvariant (); + var at = entry.Offset + entry.BodyOffset + info.DataOffset; + keys.Add (new Key (i, mediaType, info.PictureType, info.PictureDescription, at, info.DataLength)); + // An attachment without FileDescription reads its name as the description, and matches none too. + if (info.Description is null && info.PictureDescription.Length != 0) + keys.Add (new Key (i, mediaType, info.PictureType, string.Empty, at, info.DataLength)); + } + + _keys = [.. keys]; + Sort (data, _keys); + _next = new int[_keys.Length]; + for (var i = 0; i < _next.Length; i++) + _next[i] = i; + } + + static int Compare (ReadOnlySpan data, string mediaType, PictureType type, string description, ReadOnlySpan bytes, in Key key) + { + t_steps++; + var order = string.CompareOrdinal (mediaType, key.MediaType); + if (order == 0) + order = type.CompareTo (key.Type); + if (order == 0) + order = string.CompareOrdinal (description, key.Description); + return order != 0 ? order : ByteOrder.Compare (bytes, data.Slice (key.Offset, key.Length)); + } + + // Keys in order, equal keys by file order: a merge sort, stable and O(n log n) comparisons on any input. + static void Sort (ReadOnlySpan data, Key[] keys) + { + var from = keys; + var to = new Key[keys.Length]; + for (var width = 1; width < keys.Length; width *= 2) { + for (var low = 0; low < keys.Length; low += 2 * width) { + var mid = Math.Min (low + width, keys.Length); + var high = Math.Min (low + 2 * width, keys.Length); + int left = low, right = mid, at = low; + while (left < mid && right < high) { + var b = from[right]; + var order = Compare (data, b.MediaType, b.Type, b.Description, data.Slice (b.Offset, b.Length), from[left]); + // On equal keys the left one goes first: the sort is stable, so equal keys keep file order. + to[at++] = order < 0 ? from[right++] : from[left++]; + } + + while (left < mid) + to[at++] = from[left++]; + while (right < high) + to[at++] = from[right++]; + } + + (from, to) = (to, from); + } + + if (!ReferenceEquals (from, keys)) + from.CopyTo (keys, 0); } - return -1; + public int Find (ReadOnlySpan data, List existing, bool[] matched, IPicture picture, string mediaType) + { + var bytes = picture.PictureData.Span; + var upper = mediaType.ToUpperInvariant (); + var description = picture.Description ?? string.Empty; + + // The first key not before the picture's. + int low = 0, high = _keys.Length; + while (low < high) { + var mid = low + (high - low) / 2; + if (Compare (data, upper, picture.PictureType, description, bytes, _keys[mid]) > 0) + low = mid + 1; + else + high = mid; + } + + if (low == _keys.Length || Compare (data, upper, picture.PictureType, description, bytes, _keys[low]) != 0) + return -1; + + // Every key in the run is this picture; the ones already matched are passed for good. + var start = _next[low]; + while (start < _keys.Length && matched[_keys[start].Entry] && Compare (data, upper, picture.PictureType, description, bytes, _keys[start]) == 0) + start++; + _next[low] = start; + return start < _keys.Length && Compare (data, upper, picture.PictureType, description, bytes, _keys[start]) == 0 ? _keys[start].Entry : -1; + } } /// Writes one AttachedFile; the picture bytes are copied once. - static void AddAttachedFile (BinaryDataBuilder output, IPicture picture, string mediaType, HashSet usedNames, HashSet usedUids) + static void AddAttachedFile (BinaryDataBuilder output, IPicture picture, string mediaType, SortedSet usedNames, SortedDictionary nextNumbers, SortedSet usedUids) { var stem = StemOf (picture.PictureType); var extension = ExtensionOf (mediaType); var name = stem + "." + extension; - for (var n = 2; usedNames.Contains (name); n++) - name = stem + "_" + n + "." + extension; + // Each name's next number is kept, so no number is tried twice and many pictures of one type are not named in + // quadratic time. + if (usedNames.Contains (name)) { + var n = nextNumbers.TryGetValue (name, out var held) ? held : 2; + var first = name; + while (Probe (usedNames, name = stem + "_" + n + "." + extension)) + n++; + + nextNumbers[first] = n + 1; + } usedNames.Add (name); var uid = NewUid (usedUids); @@ -458,9 +598,10 @@ static void AddAttachedFile (BinaryDataBuilder output, IPicture picture, string /// /// FileUID: "not 0", "as random as possible" (RFC 9559 section 5.1.6.1.5), and unlike every - /// FileUID already in the file. Track, chapter and edition UIDs are separate spaces. + /// FileUID already in the file. Track, chapter and edition UIDs are separate spaces. The top bit is set: 63 random + /// bits, and the same width every time. /// - static ulong NewUid (HashSet used) + static ulong NewUid (SortedSet used) { var bytes = new byte[8]; using var random = RandomNumberGenerator.Create (); @@ -469,7 +610,9 @@ static ulong NewUid (HashSet used) ulong uid = 0; for (var i = 0; i < bytes.Length; i++) uid = (uid << 8) | bytes[i]; - if (uid != 0 && used.Add (uid)) + // Always 8 bytes wide, so the size of what a save writes does not depend on the draw (#244). + uid |= 1UL << 63; + if (used.Add (uid)) return uid; } } diff --git a/src/TagLibSharp2/Matroska/MatroskaChapters.cs b/src/TagLibSharp2/Matroska/MatroskaChapters.cs index b27a6665..a298778f 100644 --- a/src/TagLibSharp2/Matroska/MatroskaChapters.cs +++ b/src/TagLibSharp2/Matroska/MatroskaChapters.cs @@ -81,6 +81,10 @@ public sealed class MatroskaChapters readonly List _kept = new (); // The editions as read, to tell an edit (including a removal through the list) from a no-op. MatroskaEdition?[] _readEditions = []; + + // The Chapters element the editions and chapters were read from (or last written over the source); a node whose + // source is retired is in no file now (Rebase). + ChapterSource? _bytes; bool _hadElement; bool _cleared; @@ -195,6 +199,41 @@ internal bool HasOrderedEdition { } } + /// + /// After a save over the source wrote (a read of the Chapters element written, or null + /// when it wrote none), the chapters take what was written as what was read (#244), so a later save compares and + /// copies as a fresh read of that file would: each edition and chapter keeps its object and values, takes the bytes + /// written as its source, and a chapter written with a drawn UID keeps it. An edition or chapter read before that the + /// save did not write is no longer from the file. If the written tree does not pair with this one, + /// the chapters are left as they were: a save still compares them with the bytes it rewrites. + /// + internal void Rebase (MatroskaChapters? written) + { + var mine = new List (); + foreach (var edition in _editions) { + if (edition is not null && edition.HasAtoms) + mine.Add (edition); + } + + var theirs = written?._editions ?? []; + if (mine.Count != theirs.Count) + return; + for (var i = 0; i < mine.Count; i++) { + if (!mine[i].Pairs (theirs[i])) + return; + } + + // What was read before is in no file now: an edition or chapter the save did not write (one emptied, or removed + // and added back) is one added in code again. + _bytes?.Retire (); + _bytes = written?._bytes; + for (var i = 0; i < mine.Count; i++) + mine[i].Rebase (theirs[i], IsWebM); + _readEditions = [.. _editions.Where (edition => edition is not null && !IsUnwritten (edition))]; + _hadElement = written is not null && written._hadElement; + _cleared = false; + } + /// An edition added in code without a chapter is never written, so it is not an edit. static bool IsUnwritten (MatroskaEdition edition) => !((IReadFromFile)edition).IsFromFile && !edition.HasAtoms; @@ -313,38 +352,108 @@ void Write (ChapterWriter writer) internal static MatroskaChapters Read (ReadOnlySpan body, bool isWebM) { // One copy of the element, so an untouched edition or chapter is written back byte for byte. - var source = body.ToArray (); - var chapters = new MatroskaChapters (isWebM) { _hadElement = true }; + var bytes = new ChapterSource (body.ToArray ()); + var source = bytes.Bytes; + var chapters = new MatroskaChapters (isWebM) { _hadElement = true, _bytes = bytes }; var budget = MaxEntries; var offset = 0; while (TryNext (source, ref offset, ref budget, chapters._kept, out var element)) { if (element.Id == MatroskaIds.EditionEntry) - chapters._editions.Add (MatroskaEdition.Read (source, element, isWebM, ref budget)); + chapters._editions.Add (MatroskaEdition.Read (bytes, element, isWebM, ref budget)); else KeepUnknown (chapters._kept, source, element); } chapters._readEditions = chapters._editions.ToArray (); + chapters._budgetSpent = budget <= 0; return chapters; } + // The read reached MaxEntries: what followed it is kept as bytes. + bool _budgetSpent; + + /// + /// Whether a read of the Chapters this object writes models every value it holds. A read models + /// elements and keeps the rest as bytes, so a chapter added at the budget, or a change that + /// pushes part of the last chapter read past it (its title, its language), would be written and never read back; the + /// save is refused instead (#247). + /// + internal bool TryFitBudget (out string error) + { + error = ""; + var rendered = Render ().ToArray (); + if (rendered.Length == 0 || !EbmlReader.TryRead (rendered, 0, rendered.Length, out var element)) + return true; + var back = Read (rendered.AsSpan (element.DataOffset, (int)element.DataLength), IsWebM); + if (!back._budgetSpent || HeldBy (_editions, LastRead (_editions), back._editions, edition => edition.HasAtoms, (mine, read) => mine.HeldBy (read, IsWebM))) + return true; + error = $"Cannot save this Matroska file: its chapters would pass the {MaxEntries.ToString ("N0", System.Globalization.CultureInfo.InvariantCulture)} entries a read models, so the edit would not read back"; + return false; + } + + /// + /// Whether , the items a read of what wrote, holds each written item with + /// . A write puts the bytes kept past the budget after the item at , + /// so the items up to it begin the read list and the ones after it end it; between them is what the read takes back + /// from those bytes when the edit made room. + /// + internal static bool HeldBy (List mine, int anchor, List read, Func written, Func holds) where T : class + { + var count = 0; + var after = 0; + for (var i = 0; i < mine.Count; i++) { + if (mine[i] is { } item && written (item)) { + count++; + if (i > anchor) + after++; + } + } + + if (count > read.Count) + return false; + var head = 0; + var tail = read.Count - after; + for (var i = 0; i < mine.Count; i++) { + if (mine[i] is { } item && written (item) && !holds (item, read[i > anchor ? tail++ : head++])) + return false; + } + + return true; + } + + // Whether a read holds every written item of a list whose items are all written before the kept bytes. + internal static bool HeldBy (List mine, List read, Func holds) where T : class => + HeldBy (mine, mine.Count - 1, read, _ => true, holds); + + // Whether a read holds the values of a list of strings: the ones written begin it. + internal static bool HeldBy (List mine, List read) + { + var at = 0; + foreach (var value in mine) { + if (value is null) + continue; + if (at >= read.Count || read[at++] != value) + return false; + } + + return true; + } + static readonly RandomNumberGenerator Random = RandomNumberGenerator.Create (); [ThreadStatic] static byte[]? _uidBytes; - /// A random UID. RFC 9559 gives the UID elements the range "not 0". + /// + /// A random UID. RFC 9559 gives the UID elements the range "not 0". The top bit is set: 63 random bits, always 8 + /// bytes wide, so the size of what a save writes does not depend on the draw (#244). + /// internal static ulong NewUid () { var bytes = _uidBytes ??= new byte[8]; - ulong value; - do { - // RandomNumberGenerator instance methods are thread-safe. - Random.GetBytes (bytes); - value = EbmlReader.ReadUInt (bytes); - } while (value == 0); - - return value; + // RandomNumberGenerator instance methods are thread-safe. + Random.GetBytes (bytes); + return EbmlReader.ReadUInt (bytes) | (1UL << 63); } internal static ReadOnlySpan Payload (ReadOnlySpan body, EbmlElement element) => @@ -427,7 +536,7 @@ internal static void WriteChapters (ChapterWriter writer, IList } } - static int LastRead (IList items) where T : class, IReadFromFile + internal static int LastRead (IList items) where T : class, IReadFromFile { for (var i = items.Count - 1; i >= 0; i--) { if (items[i] is { IsFromFile: true }) @@ -482,10 +591,12 @@ public sealed class MatroskaEdition : IReadFromFile MatroskaEdition (ulong uid) => Uid = uid; - bool IReadFromFile.IsFromFile => _fromFile; + bool IReadFromFile.IsFromFile => FromFile; - bool _fromFile; - byte[]? _source; + // Read from the Chapters element the object last read or wrote over its source. + bool FromFile => _source is { IsCurrent: true }; + + ChapterSource? _source; int _sourceAt; int _sourceLength; string? _readState; @@ -498,7 +609,7 @@ public sealed class MatroskaEdition : IReadFromFile /// Gets a value indicating whether the edition is new or its own values (UID, flags) changed. /// WebM stores none of them, so there only a new edition counts. /// - internal bool ValuesChanged (bool isWebM) => !_fromFile || (!isWebM && OwnState != _readState); + internal bool ValuesChanged (bool isWebM) => !FromFile || (!isWebM && OwnState != _readState); /// Gets a value indicating whether the edition is new, or its own values or chapter list changed. internal bool OwnChanged (bool isWebM) => ValuesChanged (isWebM) || !MatroskaChapters.SameItems (_chapters, _readChapters); @@ -512,7 +623,7 @@ internal bool Prepare (bool isWebM) unchanged = false; } - _unchanged = unchanged && _source is not null; + _unchanged = unchanged && FromFile; return _unchanged; } @@ -568,7 +679,7 @@ internal void Write (ChapterWriter writer, bool isWebM) { // An unchanged edition in a Matroska file goes back byte for byte. WebM keeps to its subset instead. if (!isWebM && _unchanged) { - writer.Add (_source.AsSpan (_sourceAt, _sourceLength)); + writer.Add (_source!.Bytes.AsSpan (_sourceAt, _sourceLength)); return; } @@ -589,12 +700,38 @@ internal void Write (ChapterWriter writer, bool isWebM) writer.End (); } - internal static MatroskaEdition Read (byte[] source, EbmlElement entry, bool isWebM, ref int budget) + /// + /// Whether , a read of what this edition wrote, holds every value it does. A value at its + /// default holds nothing, so a read past the budget may have it otherwise. + /// + internal bool HeldBy (MatroskaEdition read, bool isWebM) => + (isWebM || ((Uid == 0 || read.Uid == Uid) && (!IsDefault || read.IsDefault) && (!IsOrdered || read.IsOrdered) && (!IsHidden || read.IsHidden))) + && MatroskaChapters.HeldBy (_chapters, MatroskaChapters.LastRead (_chapters), read._chapters, _ => true, (mine, back) => mine.HeldBy (back, isWebM, 1)); + + // Whether a read of what this edition wrote has its chapters, nested alike (Rebase). + internal bool Pairs (MatroskaEdition written) => MatroskaChapter.Pairs (_chapters, written._chapters, 1); + + internal void Rebase (MatroskaEdition written, bool isWebM) { + _source = written._source; + _sourceAt = written._sourceAt; + _sourceLength = written._sourceLength; + var at = 0; + foreach (var chapter in _chapters) { + if (chapter is not null && at < written._chapters.Count) + chapter.Rebase (written._chapters[at++], this, isWebM); + } + + _readState = OwnState; + _readChapters = _chapters.ToArray (); + } + + internal static MatroskaEdition Read (ChapterSource bytes, EbmlElement entry, bool isWebM, ref int budget) + { + var source = bytes.Bytes; // EditionUID is optional, so an edition read without one keeps 0. var edition = new MatroskaEdition (0) { - _fromFile = true, - _source = source, + _source = bytes, _sourceAt = entry.Position, _sourceLength = entry.End - entry.Position }; @@ -617,7 +754,7 @@ internal static MatroskaEdition Read (byte[] source, EbmlElement entry, bool isW edition.IsOrdered = MatroskaChapters.ReadFlag (payload, false); break; case MatroskaIds.ChapterAtom: - edition._chapters.Add (MatroskaChapter.Read (source, bodyAt, element, 1, isWebM, ref budget, edition)); + edition._chapters.Add (MatroskaChapter.Read (bytes, bodyAt, element, 1, isWebM, ref budget, edition)); break; default: MatroskaChapters.KeepUnknown (edition._kept, body, element); @@ -639,12 +776,17 @@ public sealed class MatroskaChapter : IReadFromFile readonly List _kept = new (); ulong _uid; + // The file's ChapterUID was there and 0. A chapter written as read writes it back so; a missing one stays missing. + bool _zeroUidRead; + MatroskaChapter (ulong uid) => _uid = uid; - bool IReadFromFile.IsFromFile => _fromFile; + bool IReadFromFile.IsFromFile => FromFile; - bool _fromFile; - byte[]? _source; + // Read from the Chapters element the object last read or wrote over its source. + bool FromFile => _source is { IsCurrent: true }; + + ChapterSource? _source; int _sourceAt; int _sourceLength; ulong _readUid; @@ -689,7 +831,7 @@ bool DisplaysAsRead (bool isWebM) /// The flags WebM does not store are not compared in a WebM file. /// internal bool OwnChanged (bool isWebM) => - !_fromFile + !FromFile || _uid != _readUid || StringUid != _readStringUid || StartNanoseconds != _readStart @@ -713,7 +855,7 @@ internal bool Prepare (int depth, bool isWebM) unchanged = false; } - _unchanged = unchanged && _source is not null; + _unchanged = unchanged && FromFile; return _unchanged; } @@ -722,17 +864,21 @@ public MatroskaChapter () : this (MatroskaChapters.NewUid ()) { } - /// Gets or sets the ChapterUID. RFC 9559 does not allow 0. - /// The value is 0. + /// + /// Gets or sets the ChapterUID. RFC 9559 does not allow 0. A chapter read without one, or with 0, reads 0 and + /// is written as it was. 0 means no UID yet, set or read: a save that writes the chapter's values changed (or the + /// chapter new) writes a new random UID, and a save over the source leaves the chapter holding it. + /// public ulong Uid { get => _uid; - set { - if (value == 0) - throw new ArgumentOutOfRangeException (nameof (value), "A ChapterUID cannot be 0."); - _uid = value; - } + set => _uid = value; } + // The UID drawn for a write of this chapter while it has none. It is part of no file until a save over the source + // writes it, and then the chapter takes it as read (MatroskaChapters.Rebase); a save that fails or goes elsewhere + // leaves Uid as it was, so the chapter's values alone decide whether it changed. + ulong? _drawnUid; + /// Gets or sets the ChapterStringUID, such as a WebVTT cue identifier, or null to leave it out. public string? StringUid { get; set; } @@ -830,12 +976,17 @@ internal void Write (ChapterWriter writer, bool isWebM, int depth) { // An unchanged chapter in a Matroska file goes back byte for byte. WebM keeps to its subset instead. if (!isWebM && _unchanged) { - writer.Add (_source.AsSpan (_sourceAt, _sourceLength)); + writer.Add (_source!.Bytes.AsSpan (_sourceAt, _sourceLength)); return; } writer.Begin (MatroskaIds.ChapterAtom); - writer.Unsigned (MatroskaIds.ChapterUid, _uid); + // ChapterUID is mandatory and not 0 (RFC 9559 section 5.1.7.1.4.1): a chapter without one written with values of + // its own gets a drawn one. One written unchanged, as WebM writes it, keeps what it was read with. + if (_uid == 0 && OwnChanged (isWebM)) + writer.Unsigned (MatroskaIds.ChapterUid, _drawnUid ??= MatroskaChapters.NewUid ()); + else if (_uid != 0 || _zeroUidRead) + writer.Unsigned (MatroskaIds.ChapterUid, _uid); if (StringUid is not null) writer.String (MatroskaIds.ChapterStringUid, StringUid); writer.Unsigned (MatroskaIds.ChapterTimeStart, StartNanoseconds); @@ -859,13 +1010,65 @@ internal void Write (ChapterWriter writer, bool isWebM, int depth) writer.End (); } - internal static MatroskaChapter Read (byte[] source, int parentAt, EbmlElement atom, int depth, bool isWebM, ref int budget, object container) + /// + /// Whether , a read of what this chapter wrote, holds every value it does, to the depth a write + /// goes. A UID of 0 is drawn when written, and a value at its default holds nothing. + /// + internal bool HeldBy (MatroskaChapter read, bool isWebM, int depth) => + (_uid == 0 || read._uid == _uid) + && (StringUid is null || read.StringUid == StringUid) + && (StartNanoseconds == 0 || read.StartNanoseconds == StartNanoseconds) + && (EndNanoseconds is null || read.EndNanoseconds == EndNanoseconds) + && (isWebM || ((!IsHidden || read.IsHidden) && (IsEnabled || !read.IsEnabled))) + // Displays are written before the kept bytes, and nested chapters as an edition's are. + && MatroskaChapters.HeldBy (_displays, read._displays, (mine, back) => mine.HeldBy (back, isWebM)) + && (depth >= MatroskaChapters.MaxDepth + || MatroskaChapters.HeldBy (_chapters, MatroskaChapters.LastRead (_chapters), read._chapters, _ => true, (mine, back) => mine.HeldBy (back, isWebM, depth + 1))); + + // Whether the written chapters are these, nested alike, to the depth a write goes. + internal static bool Pairs (List mine, List written, int depth) { + var count = 0; + foreach (var chapter in mine) { + if (chapter is null) + continue; + if (count >= written.Count) + return false; + var nested = depth < MatroskaChapters.MaxDepth ? chapter._chapters : []; + if (!Pairs (nested, written[count]._chapters, depth + 1)) + return false; + count++; + } + + return count == written.Count; + } + + internal void Rebase (MatroskaChapter written, object container, bool isWebM) + { + _source = written._source; + _sourceAt = written._sourceAt; + _sourceLength = written._sourceLength; + if (_uid == 0) + _uid = written._uid; + _drawnUid = null; + _readContainer = container; + var at = 0; + foreach (var chapter in _chapters) { + if (chapter is not null && at < written._chapters.Count) + chapter.Rebase (written._chapters[at++], this, isWebM); + } + + MarkRead (isWebM); + } + + internal static MatroskaChapter Read (ChapterSource bytes, int parentAt, EbmlElement atom, int depth, bool isWebM, ref int budget, object container) + { + var source = bytes.Bytes; ulong uid = 0; + var hasUid = false; var chapter = new MatroskaChapter (0) { _readContainer = container, - _fromFile = true, - _source = source, + _source = bytes, _sourceAt = parentAt + atom.Position, _sourceLength = atom.End - atom.Position }; @@ -877,6 +1080,7 @@ internal static MatroskaChapter Read (byte[] source, int parentAt, EbmlElement a switch (element.Id) { case MatroskaIds.ChapterUid: uid = EbmlReader.ReadUInt (payload); + hasUid = true; break; case MatroskaIds.ChapterStringUid: chapter.StringUid = EbmlReader.ReadString (payload); @@ -897,7 +1101,7 @@ internal static MatroskaChapter Read (byte[] source, int parentAt, EbmlElement a chapter._displays.Add (MatroskaChapterDisplay.Read (payload, ref budget)); break; case MatroskaIds.ChapterAtom when depth < MatroskaChapters.MaxDepth: - chapter._chapters.Add (Read (source, bodyAt, element, depth + 1, isWebM, ref budget, chapter)); + chapter._chapters.Add (Read (bytes, bodyAt, element, depth + 1, isWebM, ref budget, chapter)); break; default: // Too deep or not modelled: the bytes go back as they were. @@ -906,9 +1110,10 @@ internal static MatroskaChapter Read (byte[] source, int parentAt, EbmlElement a } } - // ChapterUID is mandatory and nonzero. A missing or 0 UID gets a new one, written only when the - // chapter itself is rewritten; until then the chapter keeps its bytes. - chapter._uid = uid != 0 ? uid : MatroskaChapters.NewUid (); + // A missing or 0 ChapterUID is kept as read, so a read is the same every time and a chapter written unchanged, + // as WebM always writes it, keeps its bytes; Prepare gives it a UID when its values change (#244). + chapter._uid = uid; + chapter._zeroUidRead = hasUid && uid == 0; chapter.MarkRead (isWebM); return chapter; } @@ -940,7 +1145,7 @@ internal bool TryValidate (bool ordered, bool all, object container, MatroskaCha // (RFC 9559 section 20.2.4 applies to a leaf moved into an ordered edition). all |= !ReferenceEquals (_readContainer, container); var changed = all || OwnChanged (isWebM); - var name = "Matroska chapter (" + path + ", UID " + _uid.ToString (System.Globalization.CultureInfo.InvariantCulture) + ")"; + var name = "Matroska chapter (" + path + (_uid == 0 ? ", no UID)" : ", UID " + _uid.ToString (System.Globalization.CultureInfo.InvariantCulture) + ")"); if (changed && EndNanoseconds is ulong end && end < StartNanoseconds) { error = name + " ends before it starts (RFC 9559 section 20.2.2)"; return false; @@ -1007,6 +1212,13 @@ public MatroskaChapterDisplay (string text, string? language = "eng") /// Gets the ChapCountry values. public IList Countries => _countries; + /// Whether , a read of what this display wrote, holds every value it does. + internal bool HeldBy (MatroskaChapterDisplay read, bool isWebM) => + (string.IsNullOrEmpty (Text) || read.Text == Text) + && MatroskaChapters.HeldBy (_languages, read._languages) + && (isWebM || MatroskaChapters.HeldBy (_languagesBcp47, read._languagesBcp47)) + && MatroskaChapters.HeldBy (_countries, read._countries); + /// Gets the display's values as one string, to tell an edit from a no-op. WebM stores no BCP 47 language. internal string State (bool isWebM) => Text + "\u0002" + string.Join ("\u0003", _languages) + "\u0002" + (isWebM ? "" : string.Join ("\u0003", _languagesBcp47)) @@ -1209,3 +1421,16 @@ public KeptElement (byte[] bytes, bool isRest = false) /// Gets a value indicating whether this holds the rest of a parent past the entry budget, which comes last. public bool IsRest { get; } } + +/// +/// The bytes of a Chapters element the chapters were read from. Once a save over the source writes another, these are +/// retired: an edition or chapter that still points here is in no file. +/// +internal sealed class ChapterSource (byte[] bytes) +{ + public byte[] Bytes { get; } = bytes; + + public bool IsCurrent { get; private set; } = true; + + public void Retire () => IsCurrent = false; +} diff --git a/src/TagLibSharp2/Matroska/MatroskaFile.cs b/src/TagLibSharp2/Matroska/MatroskaFile.cs index 5153d75e..4eed5ffb 100644 --- a/src/TagLibSharp2/Matroska/MatroskaFile.cs +++ b/src/TagLibSharp2/Matroska/MatroskaFile.cs @@ -242,14 +242,11 @@ public static MatroskaFileReadResult Read (ReadOnlySpan data) offset = element.End; } + // Duration is in Segment Ticks of TimestampScale nanoseconds (RFC 9559 §5.1.2.9, §5.1.2.10). TimeSpan? duration = null; - if (durationTicks is double ticks && scale > 0 && !double.IsNaN (ticks) && !double.IsInfinity (ticks)) { - var seconds = ticks * scale / 1_000_000_000d; - if (seconds > 0 && seconds <= TimeSpan.MaxValue.TotalSeconds) - duration = TimeSpan.FromSeconds (seconds); - } + if (durationTicks is double ticks && scale > 0) + duration = Durations.OrNull (Durations.FromSeconds (ticks * scale / 1_000_000_000d)); - tag.MarkRead (); return MatroskaFileReadResult.Success (new MatroskaFile (tag, chapters ?? MatroskaChapters.Empty (isWebM), duration, layout)); } @@ -577,7 +574,7 @@ public FileWriteResult SaveToFile (string path, ReadOnlySpan originalData, return FileWriteResult.Failure (error); fileSystem ??= _sourceFileSystem; - return AtomicFileWriter.Write (path, rewritten, fileSystem); + return AdoptWritten (AtomicFileWriter.Write (path, rewritten, fileSystem), rewritten, fileSystem); } /// Saves tags into , copying the container from . @@ -617,7 +614,18 @@ public Task SaveToFileAsync ( return Task.FromResult (FileWriteResult.Failure (error)); fileSystem ??= _sourceFileSystem; - return AtomicFileWriter.WriteAsync (path, rewritten, fileSystem, cancellationToken); + return AdoptWrittenAsync (AtomicFileWriter.WriteAsync (path, rewritten, fileSystem, cancellationToken), rewritten, fileSystem); + } + + async Task AdoptWrittenAsync (Task save, byte[] rewritten, IFileSystem? fileSystem) => + AdoptWritten (await save.ConfigureAwait (false), rewritten, fileSystem); + + // A span save that rewrote the source: the object takes what it wrote (MatroskaRewrite.Adopt). + FileWriteResult AdoptWritten (FileWriteResult result, byte[] rewritten, IFileSystem? fileSystem) + { + if (result.IsSuccess && SavedOverSource.Holds (SourcePath, fileSystem, rewritten.Length, new WrittenBytes (0, rewritten))) + MatroskaRewrite.Adopt (rewritten, Tag, Chapters); + return result; } /// Saves tags into , copying the container from . @@ -670,6 +678,9 @@ FileWriteResult SaveStreaming (string path, IFileSystem? fileSystem, Cancellatio var rewrite = plan!; var written = PathSave.Replace (path, opened, output => MatroskaRewrite.WritePlan (opened.Stream, output, rewrite, copy)); source = null; + // A path save that rewrote the source: the object takes what it wrote, checked by the metadata it wrote. + if (written.IsSuccess && SavedOverSource.Holds (SourcePath, fileSystem, rewrite.WrittenLength, rewrite.WrittenMetadata ())) + MatroskaRewrite.Adopt (rewrite, Tag, Chapters); return written; } finally { source?.Dispose (); @@ -841,6 +852,8 @@ static void ReadTrackEntry (ReadOnlySpan entry, ref TrackLayout layout) rate = 48000; else if (sawAudio && rate == 0) rate = 8000; + if (rate < 0) + rate = 0; var codec = CodecLabel (codecId, codecName, codecPrivate); layout.Tracks ??= new List (); if (layout.Tracks.Count >= MaxTracks) @@ -883,22 +896,29 @@ static void ReadAudio (ReadOnlySpan body, ref int rate, ref int outputRate break; var payload = body.Slice (element.DataOffset, (int)element.DataLength); if (element.Id == MatroskaIds.SamplingFrequency && EbmlReader.TryReadFloat (payload, out var frequency) && frequency > 0) - rate = (int)frequency; + rate = Stored (Rates.SampleRate (frequency)); else if (element.Id == MatroskaIds.OutputSamplingFrequency && EbmlReader.TryReadFloat (payload, out var output) && output > 0) { - outputRate = (int)output; + outputRate = Stored (Rates.SampleRate (output)); sawOutputRate = true; - } else if (element.Id == MatroskaIds.Channels && payload.Length > 0) - channels = (int)EbmlReader.ReadUInt (payload); - else if (element.Id == MatroskaIds.BitDepth && payload.Length > 0) - bits = (int)EbmlReader.ReadUInt (payload); + } else if (element.Id == MatroskaIds.Channels && payload.Length > 0) { + var count = EbmlReader.ReadUInt (payload); + channels = count == 0 ? 0 : Stored (Rates.Count (count)); + } else if (element.Id == MatroskaIds.BitDepth && payload.Length > 0) + bits = Rates.Count (EbmlReader.ReadUInt (payload)); offset = element.End; } - // The Channels element defaults to 1 when an Audio element omits it. + // The Channels element defaults to 1 when an Audio element omits it. A count past an int is no count (#198). if (channels == 0) channels = 1; + else if (channels < 0) + channels = 0; } + // A value the element stores that an int cannot hold (Rates gives 0) is -1 here, so a default for an absent element + // is not taken for it; the caller reads -1 as 0 (#198). + static int Stored (int value) => value > 0 ? value : -1; + static void ReadVideo (ReadOnlySpan body, ref int width, ref int height, ref int rotation) { var offset = 0; @@ -1064,6 +1084,53 @@ struct TrackLayout public int VideoRank; } + /// + /// The tags a read takes from the Tags elements at of , each + /// range one whole element (#244). + /// + internal static MatroskaTag TagsIn (ReadOnlySpan data, IReadOnlyList<(int Offset, int Length)> ranges) + { + var tag = new MatroskaTag (); + foreach (var (start, length) in ranges) { + if (EbmlReader.TryRead (data, start, start + length, out var element)) + ReadTags (data, Range (data, element, start + length), tag); + } + + return tag; + } + + /// + /// The Chapters element a read renders from the first of the Chapters elements at + /// of , as a read takes the first (#244). + /// + internal static byte[] RenderChaptersIn (ReadOnlySpan data, IReadOnlyList<(int Offset, int Length)> ranges, bool isWebM) => + ChaptersIn (data, ranges, isWebM)?.Render ().ToArray () ?? []; + + /// The chapters a read takes from the first Chapters element at , or null. + internal static MatroskaChapters? ChaptersIn (ReadOnlySpan data, IReadOnlyList<(int Offset, int Length)> ranges, bool isWebM) + { + foreach (var (start, length) in ranges) { + if (EbmlReader.TryRead (data, start, start + length, out var element)) + return MatroskaChapters.Read (Range (data, element, start + length), isWebM); + } + + return null; + } + + /// The segment title a read takes from the Info elements at , or null. + internal static string? SegmentTitleIn (ReadOnlySpan data, IReadOnlyList<(int Offset, int Length)> ranges) + { + var tag = new MatroskaTag (); + ulong scale = DefaultTimestampScale; + double? ticks = null; + foreach (var (start, length) in ranges) { + if (EbmlReader.TryRead (data, start, start + length, out var element)) + ReadInfo (data, Range (data, element, start + length), ref scale, ref ticks, tag); + } + + return tag.SegmentTitle; + } + static void ReadTags (ReadOnlySpan data, ReadOnlySpan body, MatroskaTag tag) { var offset = 0; @@ -1075,7 +1142,7 @@ static void ReadTags (ReadOnlySpan data, ReadOnlySpan body, Matroska var block = ReadTag (body.Slice (element.DataOffset, (int)element.DataLength)); if (!block.IsFileLevel) block.KeepOriginal (raw); - tag.AddBlock (block); + tag.AddReadBlock (block, raw); } if (element.UnknownSize) break; diff --git a/src/TagLibSharp2/Matroska/MatroskaRewrite.Stream.cs b/src/TagLibSharp2/Matroska/MatroskaRewrite.Stream.cs index b9b25591..d434d792 100644 --- a/src/TagLibSharp2/Matroska/MatroskaRewrite.Stream.cs +++ b/src/TagLibSharp2/Matroska/MatroskaRewrite.Stream.cs @@ -37,11 +37,13 @@ internal static bool TryPlanStream ( } } - var editChapters = chapters.IsModified; + var editChapters = chapters.IsModified || !ChaptersAsIn (doc.Data, doc.Layout, chapters); if (editChapters && !chapters.TryValidate (out error)) return false; + if (editChapters && !chapters.TryFitBudget (out error)) + return false; - HashSet? removed = null; + ISet? removed = null; var attachmentsChanged = false; if (tag.PicturesChanged) { if (!MatroskaAttachments.TryBuild (doc.Data, RangesOf (doc.Layout, MatroskaIds.Attachments), tag.Pictures, doc.Layout.IsWebM, out var attachments, out attachmentsChanged, out removed, out error)) @@ -53,8 +55,13 @@ internal static bool TryPlanStream ( if (editChapters && !TryStageStream (ref doc, MatroskaIds.Chapters, chapters.Render ().ToArray (), chapters.HasOrderedEdition, out error)) return false; - var tags = (attachmentsChanged ? tag.RenderWithout (removed) : tag.Render ()).ToArray (); - if (!tag.IsAsRead (tags) && !TryStageStream (ref doc, MatroskaIds.Tags, tags, false, out error)) + var tags = TagsToWrite (doc.Data, doc.Layout, tag, attachmentsChanged ? removed : null, out var tagsAsIn, out var refusal); + if (refusal is not null) { + error = refusal; + return false; + } + + if (!tagsAsIn && !TryStageStream (ref doc, MatroskaIds.Tags, tags, false, out error)) return false; if (tag.SegmentTitleChanged && RenderInfo (doc.Data, doc.Layout, tag.SegmentTitle) is byte[] info && !TryStageStream (ref doc, MatroskaIds.Info, info, false, out error)) @@ -1042,6 +1049,33 @@ internal StreamPlan (Document document, byte[]? size) internal Document Document { get; } internal byte[]? Size { get; } + + // Where the Segment's children start in the file written: after the head and the size field (WritePlan). + long Prefix => Document.Head.Length + (Document.Changed ? Size!.Length : Document.SizeField.Length); + + /// The length of the file writes. + internal long WrittenLength => Document.Changed + ? Prefix + Document.Layout.Starts[Document.Layout.Pieces.Count] + Document.TailLength + : Document.FileLength; + + /// + /// Every element of the Segment the save wrote but the Clusters, whose payloads it copied from the source, each at + /// its offset in the file written: what a read-back must find, with the length, for the object to take what it + /// wrote (#244). An edit is settled only by evidence of its own bytes, so a save elsewhere that matches the source + /// in length and in some elements (a picture of the same size, say) settles nothing. The head before them is the + /// source's EBML header and a Segment size the length fixes. + /// + internal WrittenBytes[] WrittenMetadata () + { + var parts = new List (); + var pieces = Document.Layout.Pieces; + for (var i = 0; i < pieces.Count; i++) { + if (pieces[i].Id != MatroskaIds.Cluster) + parts.Add (new WrittenBytes (Prefix + Document.Layout.Starts[i], Document.Data.AsMemory (pieces[i].Offset, pieces[i].Length))); + } + + return [.. parts]; + } } internal sealed class Document diff --git a/src/TagLibSharp2/Matroska/MatroskaRewrite.cs b/src/TagLibSharp2/Matroska/MatroskaRewrite.cs index 019e71d1..750a1e59 100644 --- a/src/TagLibSharp2/Matroska/MatroskaRewrite.cs +++ b/src/TagLibSharp2/Matroska/MatroskaRewrite.cs @@ -24,12 +24,14 @@ public static bool TryRewrite (ReadOnlySpan data, MatroskaTag tag, Matrosk rewritten = []; if (!TryParse (data, out var layout, out error) || layout is null) return false; - var editChapters = chapters.IsModified; + var editChapters = chapters.IsModified || !ChaptersAsIn (data, layout, chapters); if (editChapters && !chapters.TryValidate (out error)) return false; + if (editChapters && !chapters.TryFitBudget (out error)) + return false; byte[]? staged = null; - HashSet? removed = null; + ISet? removed = null; var attachmentsChanged = false; if (tag.PicturesChanged) { if (!MatroskaAttachments.TryBuild (data, RangesOf (layout, MatroskaIds.Attachments), tag.Pictures, layout.IsWebM, out var attachments, out attachmentsChanged, out removed, out error)) @@ -44,8 +46,13 @@ public static bool TryRewrite (ReadOnlySpan data, MatroskaTag tag, Matrosk return false; // Removed attachments also drop the tags that targeted only them. - var tags = (attachmentsChanged ? tag.RenderWithout (removed) : tag.Render ()).ToArray (); - if (!tag.IsAsRead (tags) && !TryStage (data, ref staged, ref layout, MatroskaIds.Tags, tags, false, out error)) + var tags = TagsToWrite (staged is null ? data : staged, layout, tag, attachmentsChanged ? removed : null, out var tagsAsIn, out var refusal); + if (refusal is not null) { + error = refusal; + return false; + } + + if (!tagsAsIn && !TryStage (data, ref staged, ref layout, MatroskaIds.Tags, tags, false, out error)) return false; if (tag.SegmentTitleChanged && RenderInfo (staged ?? data, layout, tag.SegmentTitle) is byte[] info && !TryStage (data, ref staged, ref layout, MatroskaIds.Info, info, false, out error)) @@ -102,6 +109,54 @@ static bool IsReferenced (ReadOnlySpan data, Layout layout, ulong id) return false; } + /// + /// After a save that rewrote the source with , the object describes that file, as a read + /// of it would (#244): the tags are the ones written, with an emptied Tag gone; the segment title is the one written, + /// with no edit pending; and the chapters take the bytes written as the ones read, each keeping the UID written + /// for it. A save that fails or goes elsewhere changes none of this. + /// + internal static void Adopt (byte[] written, MatroskaTag tag, MatroskaChapters chapters) + { + if (TryParse (written, out var layout, out _) && layout is not null) + Adopt (written, layout, tag, chapters); + } + + /// + internal static void Adopt (StreamPlan plan, MatroskaTag tag, MatroskaChapters chapters) => + Adopt (plan.Document.Data, plan.Document.Layout, tag, chapters); + + static void Adopt (ReadOnlySpan data, Layout layout, MatroskaTag tag, MatroskaChapters chapters) + { + tag.Adopt (MatroskaFile.TagsIn (data, RangesOf (layout, MatroskaIds.Tags)), MatroskaFile.SegmentTitleIn (data, RangesOf (layout, MatroskaIds.Info))); + chapters.Rebase (MatroskaFile.ChaptersIn (data, RangesOf (layout, MatroskaIds.Chapters), layout.IsWebM)); + } + + /// + /// The Tags element a save writes over , and whether it is the one a read of those bytes + /// renders, so the save can leave that element as it is (#244). The bytes a save rewrites are compared, not the + /// file the object read: after a save over its source they are the file it saved. + /// + static byte[] TagsToWrite (ReadOnlySpan data, Layout layout, MatroskaTag tag, ISet? removed, out bool asIn, out string? refusal) + { + var inData = MatroskaFile.TagsIn (data, RangesOf (layout, MatroskaIds.Tags)); + var tags = tag.RenderOver (inData, removed, out var entries).ToArray (); + asIn = tags.AsSpan ().SequenceEqual (inData.Render ().Span); + // A read models MatroskaTag.MaxEntries Tags and SimpleTags and keeps the rest as bytes, so Tags past it would be + // written and never read: a new Tag, or a SimpleTag that pushes the last Tag read past the budget (#247). + refusal = entries > MatroskaTag.MaxEntries + ? $"Cannot save this Matroska file: its Tags would hold {entries.ToString ("N0", System.Globalization.CultureInfo.InvariantCulture)} Tags and SimpleTags before the ones kept as read, and a read models {MatroskaTag.MaxEntries.ToString ("N0", System.Globalization.CultureInfo.InvariantCulture)}, so the edit would not read back" + : null; + return tags; + } + + /// + /// Whether renders the Chapters element a read of + /// renders (#244). An edit undone after a save over the source is not an edit of what was read, but it is one of + /// the file the save rewrites. + /// + static bool ChaptersAsIn (ReadOnlySpan data, Layout layout, MatroskaChapters chapters) => + chapters.Render ().Span.SequenceEqual (MatroskaFile.RenderChaptersIn (data, RangesOf (layout, MatroskaIds.Chapters), layout.IsWebM)); + static List<(int Offset, int Length)> RangesOf (Layout layout, ulong id) { var ranges = new List<(int, int)> (); diff --git a/src/TagLibSharp2/Matroska/MatroskaTag.cs b/src/TagLibSharp2/Matroska/MatroskaTag.cs index deda2c8c..14e19915 100644 --- a/src/TagLibSharp2/Matroska/MatroskaTag.cs +++ b/src/TagLibSharp2/Matroska/MatroskaTag.cs @@ -50,6 +50,30 @@ public override string? Title { set { if (IsWriteBackAt (value, TitlesRead (), TrackLevel, "TITLE")) return; + // ffmpeg's untargeted TITLE is the title, beside a segment title too, so it takes the new one in place: no + // reader is left showing the old one (exiftool shows the first TITLE, ffprobe and MediaInfo the last, and + // all three the TITLE tag when a save leaves out an Info/Title that does not fit; #221). When the title read + // is then the new one, an explicit album TITLE could still be the last TITLE a reader meets, so the title + // also goes at 30, in a new Tag after it, with its languages and sort, as an album edit keeps it; a narrower + // TITLE that shadows the untargeted one is written below as before. + if (!string.IsNullOrEmpty (value) && UntargetedTitles ().Length > 0) { + var copy = UntargetedTitleCopyAtTrack (); + ReplaceUntargetedTitle (value!); + SetSegmentTitleEdit (value); + if (FirstOf (TitlesRead ()) == value) { + if (ExplicitAlbumTitles ().Length > 0) + CopyUntargetedTitleToTrack (); + return; + } + + // The TITLEs at 30 are the copy an earlier edit made: they take the untargeted TITLEs again, every + // language, so a second edit writes what one edit to this title writes. + if (copy is not null) { + ReplaceTitleCopy (copy); + return; + } + } + SetValue (TrackLevel, "TITLE", value, [], ["TITLE_SORT"], shadows: false); if (string.IsNullOrEmpty (value)) ClearUntargeted ("TITLE", "TITLE_SORT"); @@ -78,6 +102,33 @@ string[] TitlesRead () string[] UntargetedTitles () => TextsOf (ValuesWhere (IsUntargeted, "TITLE")); + /// + /// Puts in the untargeted TITLE that Title reads (the first default-language one), keeping + /// its language and nested tags, and removes the other untargeted TITLEs in that language, which would show the old + /// title. A TITLE in another language stays: it is that language's title. + /// + void ReplaceUntargetedTitle (string value) + { + if (SortParentWhere (IsUntargeted, "TITLE") is not { } read) + return; + var language = LanguageOf (read); + foreach (var block in _blocks) { + if (IsUntargeted (block)) + block.Tags.RemoveAll (tag => tag.Name == "TITLE" && !ReferenceEquals (tag, read) && LanguageOf (tag) == language); + } + + ReplaceTag (read, CopyTag (read, value)); + } + + // A SimpleTag's language: its BCP 47 tag when it has one, else its TagLanguage, whose default is "und" (RFC 9559 + // §5.1.8.1.2.2, §5.1.8.1.2.3). + static string LanguageOf (SimpleTag tag) => tag.LanguageBcp47 ?? tag.Language ?? "und"; + + // Whether Title reads ffmpeg's untargeted TITLE: no track TITLE, no segment title, and no narrower TITLE. + bool ReadsUntargetedTitle () => + !HasFileLevelName (TrackLevel, "TITLE") && string.IsNullOrEmpty (_segmentTitle) + && MostSpecificFileTitleBelowCollection () == AlbumLevel && UntargetedTitles ().Length > 0; + static string? FirstOf (string[] values) => values.Length > 0 ? values[0] : null; /// @@ -122,7 +173,8 @@ public override string[] Performers { /// (https://www.matroska.org/technical/tagging.html), and ffmpeg's -metadata album= writes a /// simple tag named ALBUM in a Tag with an empty Targets, whose TargetTypeValue is 50 by /// default (RFC 9559 section 5.1.8.1.1.1). The getter reads the explicit target-50 TITLE first, - /// then ALBUM, then a TITLE in a Tag with no TargetTypeValue. + /// then ALBUM, and nothing else: a TITLE in a Tag with no TargetTypeValue is the title, as + /// ffprobe, exiftool and MediaInfo show it, though that Tag's TargetTypeValue is 50 by default (#221). /// /// /// Setting the album never changes , and never makes ffprobe or MediaInfo show the album @@ -134,7 +186,7 @@ public override string[] Performers { /// TITLE exists ("A tag defined for a given TargetTypeValue also applies to all Targets with /// numerically smaller TargetTypeValues"), so before it changes or goes, the title shown is kept at target /// 30, and the Tags with a narrower TITLE are moved after the album's. A clear removes every album - /// source, ffmpeg's untargeted TITLE included, after keeping the title the same way. + /// source, after keeping the title the same way; ffmpeg's untargeted TITLE is no album source, and stays. /// /// public override string? Album { @@ -146,8 +198,12 @@ public override string? Album { if (IsWriteBackAt (value, AlbumValues (), AlbumLevel, "TITLE")) return; if (string.IsNullOrEmpty (value)) { - KeepTrackTitle (); - SetValue (AlbumLevel, "TITLE", null, [], ["ALBUM_SORT"], shadows: false); + // Only an explicit target-50 TITLE is an album TITLE; ffmpeg's untargeted one is the title (#221). + if (hasExplicit) { + KeepTrackTitle (); + SetValue (AlbumLevel, "TITLE", null, [], ["ALBUM_SORT"], shadows: false); + } + WriteFlatAlbum (null); return; } @@ -452,14 +508,41 @@ public override string? DateTagged { /// public override string? TitleSort { - get => ReadSort ("TITLE", "TITLE_SORT", TrackLevel); + get => UntargetedTitleSort () ?? ReadSort ("TITLE", "TITLE_SORT", TrackLevel); set { + if (UntargetedTitleSort () is { } nested && IsValueRead (value, nested)) + return; if (IsSortWriteBack (value, "TITLE", "TITLE_SORT", TrackLevel)) return; + if (ReplaceUntargetedTitleSort (NullIfEmpty (value))) + return; SetSort ("TITLE", "TITLE_SORT", value, TrackLevel); } } + // The sort nested in ffmpeg's untargeted TITLE, when Title reads that TITLE: the title's sort (#221). + string? UntargetedTitleSort () + { + if (!ReadsUntargetedTitle () || SortParentWhere (IsUntargeted, "TITLE") is not { } tag) + return null; + foreach (var child in tag.Children) { + if (child.Name == "SORT_WITH" && !string.IsNullOrEmpty (child.Text)) + return child.Text; + } + + return null; + } + + bool ReplaceUntargetedTitleSort (string? value) + { + if (!ReadsUntargetedTitle () || SortParentWhere (IsUntargeted, "TITLE") is not { } tag || !tag.Children.Exists (child => child.Name == "SORT_WITH")) + return false; + tag.Children.RemoveAll (child => child.Name == "SORT_WITH"); + if (value is not null) + tag.Children.Add (new SimpleTag ("SORT_WITH", value)); + return true; + } + /// /// /// SORT_WITH nested in the ARTIST that reads, else the flat @@ -661,19 +744,13 @@ public override IPicture[] Pictures { public override void Clear () { _blocks.Clear (); + _keptTags.Clear (); _pictures.Clear (); _picturesChanged = true; SetSegmentTitleEdit (null); } bool _picturesChanged; - byte[] _baseline = []; - - /// Records the tags as read, so a save can leave an unedited Tags element as it was. - internal void MarkRead () => _baseline = Render ().ToArray (); - - /// Returns true when is the Tags element as read. - internal bool IsAsRead (ReadOnlySpan rendered) => rendered.SequenceEqual (_baseline); /// Gets a value indicating whether was set or cleared since reading. internal bool PicturesChanged => _picturesChanged; @@ -803,35 +880,120 @@ public override bool RemoveCustomField (string name) /// Writes the current tags as one Tags element. /// /// The EBML element, or empty when there are no tags. - public override BinaryData Render () => RenderWithout (null); + public override BinaryData Render () => RenderWithout (null, null, out _); + + /// + /// The Tags element a save writes over bytes whose tags read as (#244). A Tag + /// left empty is kept only where those bytes hold the same empty Tag, so a save writes what a fresh read of them + /// would: a Tag an earlier save filled and a clear emptied goes, as on a fresh object. + /// + internal BinaryData RenderOver (MatroskaTag inData, ISet? removedAttachments, out int entries) + { + // The empty Tags of the bytes, as a multiset ordered by content: a file sets how many there are and what they + // hold, so each is rendered once and found in O(log n) comparisons, with no hash an input could make collide. + var empty = new SortedDictionary (CountedByteOrder.Instance); + foreach (var block in inData._blocks) { + t_levelSteps++; + if (block.Tags.Count != 0) + continue; + var rendered = block.Render ().ToArray (); + empty[rendered] = empty.TryGetValue (rendered, out var count) ? count + 1 : 1; + } + + return RenderWithout (removedAttachments, rendered => { + var key = rendered.ToArray (); + if (!empty.TryGetValue (key, out var count)) + return false; + if (count == 1) + empty.Remove (key); + else + empty[key] = count - 1; + return true; + }, out entries); + } /// /// Writes the tags without the attachments in . /// A TagAttachmentUID MUST match an attachment in the Segment (RFC 9559 section 5.1.8.1.1.6). /// A tag left with no target at all is dropped, so it does not become a file-level tag. /// - internal BinaryData RenderWithout (HashSet? removedAttachments) + /// + /// is the count of Tags and SimpleTags written before the kept ones: a read of them models + /// that many, up to . + /// + BinaryData RenderWithout (ISet? removedAttachments, Func? keepsEmpty, out int entries) { using var tags = new BinaryDataBuilder (); var written = 0; + entries = 0; foreach (var block in _blocks) { + t_levelSteps++; // A Tag contains at least one SimpleTag (RFC 9559 section 5.1.8.1.2). One that a clear emptied is - // dropped. One that was already empty when read is kept, so a save leaves it as it was. - if (IsDropped (block)) - continue; + // dropped. One that was already empty when read is kept, so a save leaves it as it was; over given bytes, + // one that is empty there is kept. Each Tag is rendered once. + BinaryData? rendered = null; + if (block.Tags.Count == 0) { + if (keepsEmpty is null ? !block.WasEmpty : !keepsEmpty ((rendered = block.Render ()).Value)) + continue; + } + if (removedAttachments is { Count: > 0 } && block.TargetsAttachment (removedAttachments)) { var kept = block.RenderWithout (removedAttachments); if (kept is null) continue; tags.Add (kept.Value); } else - tags.Add (block.Render ()); + tags.Add (rendered ?? block.Render ()); + entries += 1 + CountSimpleTags (block.Tags); + written++; + } + + // The Tags past the entry budget, as they were read (MaxEntries). + foreach (var kept in _keptTags) { + tags.Add (kept); written++; } return written == 0 ? BinaryData.Empty : EbmlWriter.Master (MatroskaIds.Tags, tags.ToBinaryData ().Span); } + /// + /// The Tags and SimpleTags a read models, as Chapters bounds its entries (): + /// a file sets how many there are. The Tag elements past it are kept as their bytes and written back after the + /// modelled ones, unread and unedited. + /// + internal const int MaxEntries = MatroskaChapters.MaxEntries; + + readonly List _keptTags = new (); + int _entries; + + // Adds a Tag built in code (tests). + internal void AddBlock (TagBlock block) => _blocks.Add (block); + + /// + /// Adds a Tag a read parsed, or keeps its bytes when it would pass + /// (with every Tag after it, so the order is the file's). + /// + internal void AddReadBlock (TagBlock block, byte[] raw) + { + var entries = 1 + CountSimpleTags (block.Tags); + if (_keptTags.Count > 0 || _entries + entries > MaxEntries) { + _keptTags.Add (raw); + return; + } + + _entries += entries; + _blocks.Add (block); + } + + static int CountSimpleTags (List tags) + { + var count = tags.Count; + foreach (var tag in tags) + count += CountSimpleTags (tag.Children); + return count; + } + static bool IsDropped (TagBlock block) => block.Tags.Count == 0 && !block.WasEmpty; internal void SetSegmentTitle (string? title) @@ -858,7 +1020,21 @@ void SetSegmentTitleEdit (string? title) SegmentTitleChanged = true; } - internal void AddBlock (TagBlock block) => _blocks.Add (block); + /// + /// Takes , a read of the Tags a save over the source wrote, and the segment title it wrote, + /// as a read of that file holds them (MatroskaRewrite.Adopt): a Tag a clear emptied is gone, and nothing is pending. + /// + internal void Adopt (MatroskaTag written, string? segmentTitle) + { + _blocks.Clear (); + _blocks.AddRange (written._blocks); + _keptTags.Clear (); + _keptTags.AddRange (written._keptTags); + _entries = written._entries; + SetSegmentTitle (segmentTitle); + SegmentTitleChanged = false; + _picturesChanged = false; + } internal ulong ItemLevel { get { @@ -1182,6 +1358,58 @@ void SplitSharedArtist (string? value) CopyTags (artists, AlbumLevel); } + // ffmpeg's untargeted TITLE, every language with its nested tags, copied to a Tag at 30 (#221). + void CopyUntargetedTitleToTrack () => CopyTags (TagsWhere (IsUntargeted, "TITLE"), TrackLevel); + + /// + /// The TITLEs at 30 when they are a copy of the untargeted TITLEs (): the + /// same tags in the same order, each with its language and nested tags. Otherwise null: a TITLE at 30 of the + /// file's own is written as before. + /// + List? UntargetedTitleCopyAtTrack () + { + var track = TagsNamedAt (TrackLevel, "TITLE"); + var untargeted = TagsWhere (IsUntargeted, "TITLE"); + if (track.Count == 0 || track.Count != untargeted.Count) + return null; + for (var i = 0; i < track.Count; i++) { + if (!track[i].Render ().Span.SequenceEqual (CopyTag (untargeted[i], untargeted[i].Text).Render ().Span)) + return null; + } + + return track; + } + + // The copy at 30 takes the untargeted TITLEs as they are now, where the first copied TITLE was. + // A file sets how many TITLEs there are, so this is linear in them: one pass removes the copy, and the new one goes in + // as a range. + void ReplaceTitleCopy (List copy) + { + var block = BlockContaining (copy[0]); + var at = block.Tags.IndexOf (copy[0]); + var gone = new HashSet (copy); + foreach (var held in _blocks) + held.Tags.RemoveAll (gone.Contains); + block.Tags.InsertRange (at, TagsWhere (IsUntargeted, "TITLE").ConvertAll (tag => CopyTag (tag, tag.Text))); + } + + List TagsWhere (Func match, string name) + { + var found = new List (); + foreach (var block in _blocks) { + t_levelSteps++; + if (!match (block)) + continue; + foreach (var tag in block.Tags) { + t_levelSteps++; + if (tag.Name == name) + found.Add (tag); + } + } + + return found; + } + List TagsNamedAt (ulong level, string name) { var found = new List (); @@ -1190,6 +1418,7 @@ List TagsNamedAt (ulong level, string name) if (!block.IsFileLevel || block.Level != level) continue; foreach (var tag in block.Tags) { + t_levelSteps++; if (tag.Name == name) found.Add (tag); } @@ -1286,18 +1515,24 @@ bool ReplaceNestedSortAt (ulong level, string name, string? value) /// The SimpleTag whose SORT_WITH the sort getters read: the first non-empty /// at , preferring a default-language one. /// - SimpleTag? SortParentAt (ulong level, string name) + SimpleTag? SortParentAt (ulong level, string name) => + // The album TITLE is in an explicit target-50 Tag: ffmpeg's untargeted TITLE is the title, and the sort nested + // in it is the title's (#221). + SortParentWhere (block => + block.IsFileLevel && block.Level == level && !(level == AlbumLevel && name == "TITLE" && !block.HasTargetTypeValue), name); + + SimpleTag? SortParentWhere (Func holds, string name) { var preferDefault = false; foreach (var block in _blocks) { - if (!block.IsFileLevel || block.Level != level) + if (!holds (block)) continue; if (block.HasDefault (name)) preferDefault = true; } foreach (var block in _blocks) { - if (!block.IsFileLevel || block.Level != level) + if (!holds (block)) continue; foreach (var tag in block.Tags) { if (tag.Name == name && (!preferDefault || tag.IsDefault) && !string.IsNullOrEmpty (tag.Text)) @@ -1715,14 +1950,12 @@ static bool IsExplicitAlbum (TagBlock block) => string[] FileLevelValues (string name) => TextsOf (ValuesWhere (block => block.IsFileLevel, name)); - // Spec album first, then ffmpeg's ALBUM name, then a TITLE that shares the untargeted tag. + // The spec's album (an explicit target-50 TITLE), then ffmpeg's ALBUM. A TITLE in a Tag with an empty Targets is + // the title, as every reader shows it, though its TargetTypeValue defaults to 50 (#221). string[] AlbumValues () { var specified = ExplicitAlbumTitles (); - if (specified.Length > 0) - return specified; - var flat = FileLevelValues ("ALBUM"); - return flat.Length > 0 ? flat : AllAt (AlbumLevel, "TITLE"); + return specified.Length > 0 ? specified : FileLevelValues ("ALBUM"); } // Replace every ALBUM simple tag ffmpeg wrote, or add one at target 50. Do not add TITLE beside it. @@ -1762,6 +1995,13 @@ void KeepTrackTitle () { if (!HasFileLevelName (AlbumLevel, "TITLE") || HasFileLevelNameBelow (AlbumLevel, "TITLE")) return; + // A title read from ffmpeg's untargeted TITLE is copied with its languages and nested sort, so the title and + // its sort read as before (#221). + if (ReadsUntargetedTitle ()) { + CopyUntargetedTitleToTrack (); + return; + } + var shown = FirstOf (TitlesRead ()); if (!string.IsNullOrEmpty (shown)) SetValue (TrackLevel, "TITLE", shown, [], ["TITLE_SORT"], shadows: false); @@ -2313,7 +2553,7 @@ public TagBlock (ulong level, bool hasTargetTypeValue = true) /// Gets the nonzero TagAttachmentUID values in the targets. public List AttachmentUids { get; } = []; - public bool TargetsAttachment (HashSet uids) + public bool TargetsAttachment (ISet uids) { foreach (var uid in AttachmentUids) { if (uids.Contains (uid)) @@ -2327,7 +2567,7 @@ public bool TargetsAttachment (HashSet uids) /// Renders the tag with the TagAttachmentUID elements in removed. /// /// The element, or null when no target UID is left. - public BinaryData? RenderWithout (HashSet uids) + public BinaryData? RenderWithout (ISet uids) { var children = new List (); var targetsLeft = 0; @@ -2477,3 +2717,25 @@ public MatroskaPicture (string mimeType, PictureType pictureType, string descrip public BinaryData PictureData { get; } } + +/// +/// Byte arrays in order: shorter first, then by their bytes. An ordered structure keyed by content takes O(log n) +/// comparisons whatever the content, where a hash of it is a choice a file can make collide. +/// +internal static class ByteOrder +{ + public static int Compare (ReadOnlySpan x, ReadOnlySpan y) => + x.Length != y.Length ? x.Length.CompareTo (y.Length) : x.SequenceCompareTo (y); +} + +/// , each comparison counted in . +internal sealed class CountedByteOrder : IComparer +{ + public static readonly CountedByteOrder Instance = new (); + + public int Compare (byte[]? x, byte[]? y) + { + MatroskaTag.LevelSteps++; + return ByteOrder.Compare (x, y); + } +} diff --git a/src/TagLibSharp2/Mp4/AlacMagicCookie.cs b/src/TagLibSharp2/Mp4/AlacMagicCookie.cs index 751274b3..effb2efe 100644 --- a/src/TagLibSharp2/Mp4/AlacMagicCookie.cs +++ b/src/TagLibSharp2/Mp4/AlacMagicCookie.cs @@ -2,6 +2,7 @@ // Licensed under the MIT License. See LICENSE file in the project root for full license information. using System.Buffers.Binary; +using TagLibSharp2.Core; namespace TagLibSharp2.Mp4; @@ -68,7 +69,7 @@ internal static class AlacMagicCookie SampleSize = sampleSize, Channels = channels, AvgBitrate = avgBitrate, - SampleRate = (int)sampleRate + SampleRate = Rates.SampleRate (sampleRate) }; } } diff --git a/src/TagLibSharp2/Mp4/Mp4AudioPropertiesParser.cs b/src/TagLibSharp2/Mp4/Mp4AudioPropertiesParser.cs index 7e8ce293..0e0e8620 100644 --- a/src/TagLibSharp2/Mp4/Mp4AudioPropertiesParser.cs +++ b/src/TagLibSharp2/Mp4/Mp4AudioPropertiesParser.cs @@ -195,7 +195,7 @@ private static TimeSpan ParseMvhdDuration (ReadOnlySpan mvhdData) var timescale = BinaryPrimitives.ReadUInt32BigEndian (mvhdData.Slice (12, 4)); var duration = BinaryPrimitives.ReadUInt32BigEndian (mvhdData.Slice (16, 4)); - if (timescale == 0) + if (timescale == 0 || IsUnknownDuration (duration, sixtyFourBits: false)) return TimeSpan.Zero; return FromSeconds ((double)duration / timescale); @@ -207,7 +207,7 @@ private static TimeSpan ParseMvhdDuration (ReadOnlySpan mvhdData) var timescale = BinaryPrimitives.ReadUInt32BigEndian (mvhdData.Slice (20, 4)); var duration = BinaryPrimitives.ReadUInt64BigEndian (mvhdData.Slice (24, 8)); - if (timescale == 0) + if (timescale == 0 || IsUnknownDuration (duration, sixtyFourBits: true)) return TimeSpan.Zero; return FromSeconds ((double)duration / timescale); @@ -217,11 +217,19 @@ private static TimeSpan ParseMvhdDuration (ReadOnlySpan mvhdData) } /// - /// that saturates instead of throwing. A version 1 header holds a - /// 64-bit duration, and a small timescale can put it past (ISO 14496-12 §8.2.2). + /// : a version 1 header holds a 64-bit duration, and a small timescale + /// can put it past (ISO 14496-12 §8.2.2), which is unknown (#181). /// internal static TimeSpan FromSeconds (double seconds) => Durations.FromSeconds (seconds); + /// + /// Whether an mvhd, tkhd or mdhd duration is the value that means unknown: "If the duration cannot be determined + /// then duration is set to all 1s" (ISO 14496-12 §8.2.2.3, §8.3.2.3, §8.4.2.3), in 32 bits in version 0 and 64 + /// in version 1 (#183). + /// + internal static bool IsUnknownDuration (ulong duration, bool sixtyFourBits) => + duration == (sixtyFourBits ? ulong.MaxValue : uint.MaxValue); + /// /// Parses duration from mdhd (media header) box. /// @@ -241,7 +249,7 @@ private static TimeSpan ParseMdhdDuration (ReadOnlySpan mdhdData) var timescale = BinaryPrimitives.ReadUInt32BigEndian (mdhdData.Slice (12, 4)); var duration = BinaryPrimitives.ReadUInt32BigEndian (mdhdData.Slice (16, 4)); - if (timescale == 0) + if (timescale == 0 || IsUnknownDuration (duration, sixtyFourBits: false)) return TimeSpan.Zero; return FromSeconds ((double)duration / timescale); @@ -252,7 +260,7 @@ private static TimeSpan ParseMdhdDuration (ReadOnlySpan mdhdData) var timescale = BinaryPrimitives.ReadUInt32BigEndian (mdhdData.Slice (20, 4)); var duration = BinaryPrimitives.ReadUInt64BigEndian (mdhdData.Slice (24, 8)); - if (timescale == 0) + if (timescale == 0 || IsUnknownDuration (duration, sixtyFourBits: true)) return TimeSpan.Zero; return FromSeconds ((double)duration / timescale); @@ -352,7 +360,7 @@ private static AudioProperties ParseMp4aEntry ( // Prefer codec-specific values over AudioSampleEntry values var sampleRate = config.SampleRate > 0 ? config.SampleRate : sampleRateFromEntry; var channels = config.Channels > 0 ? config.Channels : channelsFromEntry; - var bitrate = config.AvgBitrate > 0 ? (int)(config.AvgBitrate / 1000) : 0; + var bitrate = Rates.Kbps ((long)config.AvgBitrate); // Determine AAC sub-type from objectTypeIndication var codecName = config.ObjectTypeIndication switch { @@ -388,7 +396,7 @@ private static AudioProperties ParseAlacEntry ( return new AudioProperties (duration, 0, sampleRateFromEntry, sampleSizeFromEntry, channelsFromEntry, "ALAC"); var config = alacConfig.Value; - var bitrate = config.AvgBitrate > 0 ? (int)(config.AvgBitrate / 1000) : 0; + var bitrate = Rates.Kbps ((long)config.AvgBitrate); // Prefer magic cookie values, fall back to AudioSampleEntry values var sampleRate = config.SampleRate > 0 ? config.SampleRate : sampleRateFromEntry; diff --git a/src/TagLibSharp2/Mp4/Mp4ChapterCodec.cs b/src/TagLibSharp2/Mp4/Mp4ChapterCodec.cs index 80fcf8bc..a8e63605 100644 --- a/src/TagLibSharp2/Mp4/Mp4ChapterCodec.cs +++ b/src/TagLibSharp2/Mp4/Mp4ChapterCodec.cs @@ -2264,10 +2264,12 @@ public static TimeSpan MovieDuration (Mp4Box moov) if (timescale == 0) return TimeSpan.Zero; - if (mvhd[0] == 1) - return mvhd.Length >= 32 ? ToTime (BinaryPrimitives.ReadUInt64BigEndian (mvhd.Slice (24)), timescale) : TimeSpan.Zero; + var wide = mvhd[0] == 1; + if (mvhd.Length < (wide ? 32 : 20)) + return TimeSpan.Zero; - return mvhd.Length >= 20 ? ToTime (BinaryPrimitives.ReadUInt32BigEndian (mvhd.Slice (16)), timescale) : TimeSpan.Zero; + var duration = wide ? BinaryPrimitives.ReadUInt64BigEndian (mvhd.Slice (24)) : BinaryPrimitives.ReadUInt32BigEndian (mvhd.Slice (16)); + return Mp4AudioPropertiesParser.IsUnknownDuration (duration, wide) ? TimeSpan.Zero : ToTime (duration, timescale); } static uint ReadMovieTimescale (Mp4Box moov) diff --git a/src/TagLibSharp2/Mp4/Mp4File.cs b/src/TagLibSharp2/Mp4/Mp4File.cs index 65110c3b..fb6536b0 100644 --- a/src/TagLibSharp2/Mp4/Mp4File.cs +++ b/src/TagLibSharp2/Mp4/Mp4File.cs @@ -993,6 +993,7 @@ static string ExtractFileType (Mp4Box ftypBox) // First try to get duration from mvhd (movie header) for overall duration uint movieTimescale = 0; ulong movieDuration = 0; + var wideDuration = false; var mvhd = moov.FindChild ("mvhd"); if (mvhd is not null && mvhd.Data.Length >= 20) { var mvhdData = mvhd.Data; @@ -1007,15 +1008,19 @@ static string ExtractFileType (Mp4Box ftypBox) if (mvhdData.Length >= 32) { movieTimescale = mvhdData.ToUInt32BE (20); movieDuration = mvhdData.ToUInt64BE (24); + wideDuration = true; } } } + // The duration from the movie header; all 1s is unknown (#183). + var unknown = Mp4AudioPropertiesParser.IsUnknownDuration (movieDuration, wideDuration); + var durationSeconds = movieTimescale > 0 && !unknown ? (double)movieDuration / movieTimescale : 0; + // ISO/IEC 14496-12 handler_type: "soun" is audio, "vide" is video. A visual sample // entry stores width and height where an audio entry stores the sample rate, so a // video track must not be parsed as audio. A track another track names in a tref/chap // (§8.3.3) is chapter media, such as Apple's chapter images, not the movie's video. - var durationSeconds = movieTimescale > 0 ? (double)movieDuration / movieTimescale : 0; var chapterMedia = new HashSet (Mp4ChapterCodec.FindChapterTracks (moov, textOnly: false).Select (track => track.Trak)); Mp4Box? sound = null; Mp4Box? picture = null; @@ -1110,11 +1115,11 @@ static string ExtractFileType (Mp4Box ftypBox) // For high sample rates like 96kHz, 176.4kHz, 192kHz, use mdhd timescale instead if (trackTimescale > 65535) { // mdhd has a sample rate that cannot fit in 16.16 fixed-point - sampleRate = (int)trackTimescale; + sampleRate = Rates.SampleRate (trackTimescale); } else { var rawSampleRate = entryData.ToUInt32BE (32); var stsdSampleRate = (int)(rawSampleRate >> 16); - sampleRate = stsdSampleRate > 0 ? stsdSampleRate : (int)trackTimescale; + sampleRate = stsdSampleRate > 0 ? stsdSampleRate : Rates.SampleRate (trackTimescale); } // Parse codec-specific extensions for bitrate @@ -1128,7 +1133,7 @@ static string ExtractFileType (Mp4Box ftypBox) // Fall back to track timescale if sample rate not found if (sampleRate == 0 && trackTimescale > 0) - sampleRate = (int)trackTimescale; + sampleRate = Rates.SampleRate (trackTimescale); var audioDuration = Mp4AudioPropertiesParser.FromSeconds (durationSeconds); @@ -1329,7 +1334,7 @@ static int ExtractBitrateFromCodecBox (BinaryData codecExtensions, Mp4AudioCodec if (boxSize < 12) return 0; var esds = EsdsParser.Parse (codecExtensions.Slice (offset + 12, (int)boxSize - 12).Span); - return esds is { } config ? (int)(config.AvgBitrate / 1000) : 0; + return esds is { } config ? Rates.Kbps ((long)config.AvgBitrate) : 0; } offset += (int)boxSize; diff --git a/src/TagLibSharp2/Mpeg/Mp3File.cs b/src/TagLibSharp2/Mpeg/Mp3File.cs index b9ebd988..36e3ebbb 100644 --- a/src/TagLibSharp2/Mpeg/Mp3File.cs +++ b/src/TagLibSharp2/Mpeg/Mp3File.cs @@ -47,6 +47,10 @@ internal void MarkPicturesSkipped () bool _disposed; TagCreation? _creation; + // The ID3v1 tag at the end of the file the object describes: 128 bytes, or 0 when it has none. The audio ends + // there, whatever tag the object holds now. + int _trailerSize; + /// /// Gets the source file path if the file was read from disk. /// @@ -87,7 +91,8 @@ internal void RememberSource (string path, IFileSystem? fileSystem) public Id3v1Tag? Id3v1Tag { get; set; } /// - /// Gets the size of the ID3v2 tag in bytes (0 if no tag). + /// Gets the size of the ID3v2 tag in bytes (0 if no tag) of the file the object describes: the one it read or, + /// after a save over its source, the one that save wrote. /// public int Id3v2Size { get; private set; } @@ -377,8 +382,10 @@ public static Mp3FileReadResult Read (ReadOnlySpan data) if (data.Length >= Id3v1Size) { var id3v1Data = data.Slice (data.Length - Id3v1Size, Id3v1Size); var id3v1Result = Id3v1Tag.Read (id3v1Data); - if (id3v1Result.IsSuccess) + if (id3v1Result.IsSuccess) { file.Id3v1Tag = id3v1Result.Tag; + file._trailerSize = Id3v1Size; + } } // Parse audio properties (duration, bitrate, etc.) @@ -450,7 +457,6 @@ static Mp3FileReadResult ReadSkippingPictures (Stream stream) if (parsed.IsSuccess && parsed.File?.Id3v2Tag is not null) parsed.File.Id3v2Size = tag.Consumed; - parsed.File?.Source.Record (length); return MarkSkipped (parsed); } @@ -684,8 +690,10 @@ static Mp3FileReadResult ReadWindows (byte[] prefix, byte[] tail, long fileLengt if (tail.Length >= Id3v1Size) { var id3v1Result = Id3v1Tag.Read (tail.AsSpan (tail.Length - Id3v1Size, Id3v1Size)); - if (id3v1Result.IsSuccess) + if (id3v1Result.IsSuccess) { file.Id3v1Tag = id3v1Result.Tag; + file._trailerSize = Id3v1Size; + } } if (MpegAudioProperties.TryParse (BinaryData.WrapUnsafe (prefix), file.Id3v2Size, fileLength, out var audioProps, out needsEntireFile, removedBytes)) @@ -772,45 +780,55 @@ public BinaryData Render (ReadOnlySpan originalData) _creation?.Settle ([Id3v2Tag, Id3v1Tag]); if (Id3v1Refusal () is string refusal) throw new InvalidOperationException (refusal); - // Calculate audio data bounds - var audioStart = Id3v2Size; - var audioEnd = HasId3v1Tag - ? originalData.Length - Id3v1Size - : originalData.Length; - - var audioLength = audioEnd - audioStart; - if (audioLength < 0) - audioLength = 0; - - // Render new ID3v2 tag - var newId3v2Data = Id3v2Tag?.Render () ?? BinaryData.Empty; - - // Render new ID3v1 tag (if present) - var newId3v1Data = Id3v1Tag?.Render () ?? BinaryData.Empty; + return Assemble (originalData, Plan (originalData.Length)); + } - // Build new file - var totalSize = newId3v2Data.Length + audioLength + newId3v1Data.Length; - using var builder = new BinaryDataBuilder (totalSize); + static BinaryData Assemble (ReadOnlySpan originalData, Written written) + { + using var builder = new BinaryDataBuilder ((int)written.Length); + builder.Add (written.Id3v2); + if (written.AudioLength > 0) + builder.Add (originalData.Slice ((int)written.AudioStart, (int)written.AudioLength)); + builder.Add (written.Id3v1); + return builder.ToBinaryData (); + } - if (newId3v2Data.Length > 0) - builder.Add (newId3v2Data); + // The file a save writes: the current tags around the audio of the file it copies. + readonly record struct Written (BinaryData Id3v2, long AudioStart, long AudioLength, BinaryData Id3v1) + { + public long Length => Id3v2.Length + AudioLength + Id3v1.Length; + } - if (audioLength > 0) - builder.Add (originalData.Slice (audioStart, audioLength)); + // The audio runs from the end of the ID3v2 tag to the ID3v1 tag of the file the object describes. + Written Plan (long fileLength) => + new (Id3v2Tag?.Render () ?? BinaryData.Empty, Id3v2Size, AudioByteCount (fileLength), Id3v1Tag?.Render () ?? BinaryData.Empty); - if (newId3v1Data.Length > 0) - builder.Add (newId3v1Data); + // A save that rewrote the source leaves the object describing the file it wrote (#179): its ID3v2 tag ends where + // the one written ends, and a save from those bytes, by span or by path, takes the audio from there. + FileWriteResult Adopt (FileWriteResult result, Written written, IFileSystem? fileSystem) + { + if (result.IsSuccess + && SavedOverSource.Holds (SourcePath, fileSystem, written.Length, + new WrittenBytes (0, written.Id3v2.Memory), + new WrittenBytes (written.Length - written.Id3v1.Length, written.Id3v1.Memory))) { + Id3v2Size = written.Id3v2.Length; + _trailerSize = written.Id3v1.Length; + Source.Rewrote (written.Length); + } - return builder.ToBinaryData (); + return result; } + async Task Adopt (Task save, Written written, IFileSystem? fileSystem) => + Adopt (await save.ConfigureAwait (false), written, fileSystem); + /// /// Saves the file to the specified path using atomic write. /// /// The target file path. - /// The bytes of the file this object was read from; the payload is taken from them at the - /// offsets the read found. Bytes of any other length, a file it has saved since among them, fail with a result, and - /// nothing is written. + /// The bytes of the file this object was read from or, after a save over its source, of the + /// file that save wrote; the payload is taken from them at the offsets of that file. Bytes of any other length, a + /// file it saved elsewhere among them, fail with a result, and nothing is written. /// Optional file system abstraction for testing. /// A result indicating success or failure. public FileWriteResult SaveToFile (string path, ReadOnlySpan originalData, IFileSystem? fileSystem = null) @@ -824,21 +842,22 @@ public FileWriteResult SaveToFile (string path, ReadOnlySpan originalData, if (Source.Refuse ("MP3", originalData.Length) is { } mismatch) return mismatch; - var rendered = Render (originalData); + var written = Plan (originalData.Length); + var rendered = Assemble (originalData, written); if (rendered.IsEmpty) return FileWriteResult.Failure ("Failed to render MP3 file"); fileSystem ??= _sourceFileSystem; - return AtomicFileWriter.Write (path, rendered.Span, fileSystem); + return Adopt (AtomicFileWriter.Write (path, rendered.Span, fileSystem), written, fileSystem); } /// /// Asynchronously saves the file to the specified path using atomic write. /// /// The target file path. - /// The bytes of the file this object was read from; the payload is taken from them at the - /// offsets the read found. Bytes of any other length, a file it has saved since among them, fail with a result, and - /// nothing is written. + /// The bytes of the file this object was read from or, after a save over its source, of the + /// file that save wrote; the payload is taken from them at the offsets of that file. Bytes of any other length, a + /// file it saved elsewhere among them, fail with a result, and nothing is written. /// Optional file system abstraction for testing. /// A token to cancel the operation. /// A task containing a result indicating success or failure. @@ -857,12 +876,13 @@ public Task SaveToFileAsync ( if (Source.Refuse ("MP3", originalData.Length) is { } mismatch) return Task.FromResult (mismatch); - var rendered = Render (originalData.Span); + var written = Plan (originalData.Length); + var rendered = Assemble (originalData.Span, written); if (rendered.IsEmpty) return Task.FromResult (FileWriteResult.Failure ("Failed to render MP3 file")); fileSystem ??= _sourceFileSystem; - return AtomicFileWriter.WriteAsync (path, rendered.Memory, fileSystem, cancellationToken); + return Adopt (AtomicFileWriter.WriteAsync (path, rendered.Memory, fileSystem, cancellationToken), written, fileSystem); } /// @@ -952,11 +972,14 @@ FileWriteResult SaveFromSource (string destinationPath, IFileSystem? fileSystem, try { if (!PathSave.TryOpen (SourcePath!, fileSystem, out source, out var error)) return error; - - var id3v2 = Id3v2Tag?.Render () ?? BinaryData.Empty; - var id3v1 = Id3v1Tag?.Render () ?? BinaryData.Empty; - var audioLength = AudioByteCount (source!.Length); - if (id3v2.IsEmpty && audioLength == 0 && id3v1.IsEmpty) + if (Source.Refuse ("MP3", source!.Length, "the source file") is { } changed) + return changed; + + var written = Plan (source!.Length); + var id3v2 = written.Id3v2; + var id3v1 = written.Id3v1; + var audioLength = written.AudioLength; + if (written.Length == 0) return FileWriteResult.Failure ("Failed to render MP3 file"); if (cancellationToken.IsCancellationRequested) @@ -965,10 +988,10 @@ FileWriteResult SaveFromSource (string destinationPath, IFileSystem? fileSystem, chunk = StreamCopy.Rent (); var copyBuffer = chunk; var opened = source; - var written = PathSave.Replace (destinationPath, opened, output => { + var saved = PathSave.Replace (destinationPath, opened, output => { StreamCopy.Write (output, id3v2.Span, copyBuffer); if (audioLength > 0) { - var audioStart = (long)Id3v2Size; + var audioStart = written.AudioStart; if (opened.Stream.Position != audioStart) opened.Stream.Position = audioStart; StreamCopy.Copy (opened.Stream, output, audioLength, copyBuffer); @@ -978,7 +1001,7 @@ FileWriteResult SaveFromSource (string destinationPath, IFileSystem? fileSystem, }); // Replace closes the source before the destination is replaced. source = null; - return written; + return Adopt (saved, written, fileSystem); } finally { source?.Dispose (); if (chunk is not null) @@ -986,12 +1009,7 @@ FileWriteResult SaveFromSource (string destinationPath, IFileSystem? fileSystem, } } - long AudioByteCount (long fileLength) - { - var audioEnd = HasId3v1Tag ? fileLength - Id3v1Size : fileLength; - var audioLength = audioEnd - Id3v2Size; - return audioLength < 0 ? 0 : audioLength; - } + long AudioByteCount (long fileLength) => Math.Max (0, fileLength - _trailerSize - Id3v2Size); /// /// Saves the file back to its source path. diff --git a/src/TagLibSharp2/Mpeg/MpegAudioProperties.cs b/src/TagLibSharp2/Mpeg/MpegAudioProperties.cs index fd1b1ff6..146c512f 100644 --- a/src/TagLibSharp2/Mpeg/MpegAudioProperties.cs +++ b/src/TagLibSharp2/Mpeg/MpegAudioProperties.cs @@ -188,26 +188,26 @@ internal static bool TryParse ( // VBR with Xing header - accurate duration frameCount = xingFrames; var totalSamples = (double)xingFrames * frame.SamplesPerFrame; - duration = TimeSpan.FromSeconds (totalSamples / frame.SampleRate); + duration = Durations.FromSeconds (totalSamples / frame.SampleRate); isVbr = xingHeader.IsVbr; // Calculate average bitrate if (xingHeader.ByteCount != null && duration.TotalSeconds > 0) - bitrate = (int)(xingHeader.ByteCount.Value * 8 / duration.TotalSeconds / 1000); + bitrate = Rates.Kbps (xingHeader.ByteCount.Value * 8 / duration.TotalSeconds); else if (duration.TotalSeconds > 0) - bitrate = (int)(audioDataSize * 8 / duration.TotalSeconds / 1000); + bitrate = Rates.Kbps (audioDataSize * 8 / duration.TotalSeconds); else bitrate = frame.Bitrate; } else if (trustVbri && vbriHeader is not null) { // VBR with VBRI header - accurate duration frameCount = vbriHeader.FrameCount; var totalSamples = (double)frameCount.Value * frame.SamplesPerFrame; - duration = TimeSpan.FromSeconds (totalSamples / frame.SampleRate); + duration = Durations.FromSeconds (totalSamples / frame.SampleRate); isVbr = true; // Calculate average bitrate if (vbriHeader.ByteCount > 0 && duration.TotalSeconds > 0) - bitrate = (int)(vbriHeader.ByteCount * 8 / duration.TotalSeconds / 1000); + bitrate = Rates.Kbps (vbriHeader.ByteCount * 8 / duration.TotalSeconds); else bitrate = frame.Bitrate; } else if (xingHeader?.FrameCount != null || vbriHeader is not null) { @@ -225,7 +225,7 @@ internal static bool TryParse ( bitrate = frame.Bitrate; if (counted > 0 && frame.SampleRate > 0) { frameCount = (uint)counted; - duration = TimeSpan.FromSeconds (counted * (double)frame.SamplesPerFrame / frame.SampleRate); + duration = Durations.FromSeconds (counted * (double)frame.SamplesPerFrame / frame.SampleRate); } else { duration = TimeSpan.Zero; } @@ -235,7 +235,7 @@ internal static bool TryParse ( bitrate = frame.Bitrate; if (bitrate > 0) - duration = TimeSpan.FromSeconds ((double)audioDataSize * 8 / (bitrate * 1000)); + duration = Durations.FromSeconds ((double)audioDataSize * 8 / (bitrate * 1000)); else duration = TimeSpan.Zero; } diff --git a/src/TagLibSharp2/Mpeg/MpegPsFile.cs b/src/TagLibSharp2/Mpeg/MpegPsFile.cs index ed303e7a..520bd9d2 100644 --- a/src/TagLibSharp2/Mpeg/MpegPsFile.cs +++ b/src/TagLibSharp2/Mpeg/MpegPsFile.cs @@ -248,7 +248,8 @@ internal void MarkPicturesSkipped () /// /// Gets the size in bytes of the ID3v2 tag in front of the stream, including its padding and - /// footer, or 0 when the file had none. The stream starts here. + /// footer, or 0 when the file had none. The stream starts here. The file is the one the object read or, after a + /// save over its source, the one that save wrote. /// public int Id3v2Size { get; private set; } @@ -306,7 +307,7 @@ public Id3v2Tag EnsureId3v2Tag () /// True when the data starts an MPEG program stream or video elementary stream. public static bool IsValidFormat (ReadOnlySpan data) { - var tag = TagLength (data, data.Length); + var tag = TagLength (data, data.Length, AfterBody (data)); return tag < data.Length && MpegPsScanner.StreamStart (data.Slice (tag)) >= 0; } @@ -319,7 +320,7 @@ public static bool IsValidFormat (ReadOnlySpan data) public static MpegPsFileReadResult Read (ReadOnlySpan data) { var length = data.Length; - var tagLength = TagLength (data, length); + var tagLength = TagLength (data, length, AfterBody (data)); var trailer = new TrailerLocator (length, tagLength); while (trailer.Next (out var offset, out var count)) trailer.Supply (count > 0 ? data.Slice ((int)offset, count) : []); @@ -354,7 +355,7 @@ internal static MpegPsFileReadResult Read (Stream stream, string? sourcePath, IF var length = stream.Length; var first = ReadAt (stream, 0, (int)Math.Min (Id3v2Header.HeaderSize, length)); - var tagLength = TagLength (first, length); + var tagLength = TagLength (first, length, FooterIdentifier (stream, first, length)); byte[] tag; if (tagLength <= 0) { tag = []; @@ -413,7 +414,7 @@ internal static async Task ReadAsync ( var length = stream.Length; var first = await ReadAtAsync (stream, 0, (int)Math.Min (Id3v2Header.HeaderSize, length), cancellationToken).ConfigureAwait (false); - var tagLength = TagLength (first, length); + var tagLength = TagLength (first, length, FooterIdentifier (stream, first, length)); var tag = tagLength > 0 ? await ReadAtAsync (stream, 0, tagLength, cancellationToken).ConfigureAwait (false) : []; if (tag.Length != tagLength) return MpegPsFileReadResult.Failure ("The stream ended inside the ID3v2 tag"); @@ -521,7 +522,7 @@ internal static bool StartsAfterId3v2 (Stream stream) { var length = stream.Length; var first = ReadAt (stream, 0, (int)Math.Min (Id3v2Header.HeaderSize, length)); - var tag = TagLength (first, length); + var tag = TagLength (first, length, FooterIdentifier (stream, first, length)); if (tag <= 0) return false; var next = ReadAt (stream, tag, (int)Math.Min (64, length - tag)); @@ -535,10 +536,16 @@ internal static bool StartsAfterId3v2 (Stream stream) /// /// ID3v2.4 structure 3.1: "ID3", a version and revision below 0xFF, flags, and a syncsafe /// size whose bytes are below 0x80. A version this library does not parse is still skipped, - /// as the specification asks, and its bytes are kept on save. A v2.4 footer adds 10 bytes. + /// as the specification asks, and its bytes are kept on save. A v2.4 footer adds 10 bytes when it + /// is there (3.4: a copy of the header whose identifier is "3DI"); a footer flag with no "3DI" + /// after the body does not take the 10 bytes after it from the stream (#202). /// https://id3.org/id3v2.4.0-structure /// - static int TagLength (ReadOnlySpan first, long length) + /// The tag's first 10 bytes, or more. + /// The file's length. + /// The bytes after the tag's body, where a footer's "3DI" would be: + /// in data, from a stream. + static int TagLength (ReadOnlySpan first, long length, ReadOnlySpan afterBody) { if (first.Length < Id3v2Header.HeaderSize || first[0] != 'I' || first[1] != 'D' || first[2] != '3') return 0; @@ -547,9 +554,30 @@ static int TagLength (ReadOnlySpan first, long length) if ((first[6] | first[7] | first[8] | first[9]) >= 0x80) return 0; - var size = ((long)first[6] << 21) | ((long)first[7] << 14) | ((long)first[8] << 7) | first[9]; - var footer = first[3] >= 4 && (first[5] & 0x10) != 0 ? Id3v2Header.FooterSize : 0; - return (int)Math.Min (Id3v2Header.HeaderSize + size + footer, length); + var body = Id3v2Header.HeaderSize + DeclaredSize (first); + var footer = first[3] >= 4 && (first[5] & 0x10) != 0 && Id3v2Header.IsFooterIdentifier (afterBody) ? Id3v2Header.FooterSize : 0; + return (int)Math.Min (body + footer, length); + } + + static long DeclaredSize (ReadOnlySpan first) => + ((long)first[6] << 21) | ((long)first[7] << 14) | ((long)first[8] << 7) | first[9]; + + // The bytes after the body of the ID3v2 tag that starts data, where a v2.4 footer's "3DI" would be, or empty. + static ReadOnlySpan AfterBody (ReadOnlySpan data) + { + if (data.Length < Id3v2Header.HeaderSize || (data[6] | data[7] | data[8] | data[9]) >= 0x80) + return []; + var body = Id3v2Header.HeaderSize + DeclaredSize (data); + return body < data.Length ? data.Slice ((int)body) : []; + } + + // The stream twin of AfterBody: the three bytes after the body of the tag whose header is first, read there. + static byte[] FooterIdentifier (Stream stream, ReadOnlySpan first, long length) + { + if (first.Length < Id3v2Header.HeaderSize || first[3] < 4 || (first[5] & 0x10) == 0 || (first[6] | first[7] | first[8] | first[9]) >= 0x80) + return []; + var body = Id3v2Header.HeaderSize + DeclaredSize (first); + return body + 3 > length ? [] : ReadAt (stream, body, 3); } /// @@ -759,6 +787,12 @@ public BinaryData Render (ReadOnlySpan originalData) _creation?.Settle (TagSources ()); if (Id3v1Refusal () is string refusal) throw new InvalidOperationException (refusal); + return Assemble (originalData, out _); + } + + BinaryData Assemble (ReadOnlySpan originalData, out Written written) + { + written = default; if (!SameFile (originalData.Length)) return BinaryData.Empty; if (MpegPsScanner.StreamStart (originalData.Slice (Id3v2Size, (int)Math.Min (64, _streamEnd - Id3v2Size))) < 0) @@ -771,6 +805,7 @@ public BinaryData Render (ReadOnlySpan originalData) var foot = RenderId3v1 (Id3v1Original (originalData)); var stream = originalData.Slice (Id3v2Size, (int)(_appendedStart - Id3v2Size)); var between = originalData.Slice ((int)_appendedEnd, (int)(_footerStart - _appendedEnd)); + written = new Written (head.Length, stream.Length, appended.Length, between.Length, foot.Length); using var builder = new BinaryDataBuilder (head.Length + stream.Length + appended.Length + between.Length + foot.Length); builder.Add (head); builder.Add (stream); @@ -780,6 +815,62 @@ public BinaryData Render (ReadOnlySpan originalData) return builder.ToBinaryData (); } + // The lengths of the parts a save writes: the tag in front, the stream, the tag at the end, the bytes between it + // and ID3v1, and ID3v1. + readonly record struct Written (int Head, long Stream, int Appended, long Between, int Foot) + { + public long Length => Head + Stream + Appended + Between + Foot; + } + + // A save that rewrote the source leaves the object describing the file it wrote (#179), as a read of that file + // would: the parts sit where they were written, and the tags it wrote are the ones that file holds. + FileWriteResult Adopt ( + FileWriteResult result, + Written written, + ReadOnlyMemory head, + ReadOnlyMemory appended, + ReadOnlyMemory foot, + IFileSystem? fileSystem) + { + var length = written.Length; + if (!result.IsSuccess + || !SavedOverSource.Holds (SourcePath, fileSystem, length, + new WrittenBytes (0, head), + new WrittenBytes (written.Head + written.Stream, appended), + new WrittenBytes (length - written.Foot, foot))) + return result; + + // The tag in front is the one read there while an appended tag is written (RenderPrependedId3v2), else the + // current tag; one that did not parse stays unparsed. An appended tag is written whenever WritesAppended + // (RenderAppendedId3v2), and it is an update of the tag in front when it was written as one. + var update = EarlierTag is not null; + var front = written.Head == 0 ? null : WritesAppended || Id3v2Tag is null ? _readId3v2 : Id3v2Tag; + var end = WritesAppended ? Id3v2Tag : null; + _readId3v2 = front; + _readAppended = end; + _earlierId3v2 = end is not null && update ? front : null; + _readId3v1 = written.Foot > 0 ? Id3v1Tag : null; + _streamEnd = written.Head + (_streamEnd - Id3v2Size); + Id3v2Size = written.Head; + _appendedStart = written.Head + written.Stream; + _appendedEnd = _appendedStart + written.Appended; + _footerStart = _appendedEnd + written.Between; + Source.Rewrote (length); + return result; + } + + FileWriteResult Adopt (FileWriteResult result, Written written, ReadOnlyMemory rendered, IFileSystem? fileSystem) => + Adopt ( + result, + written, + rendered[..written.Head], + rendered.Slice ((int)(written.Head + written.Stream), written.Appended), + rendered[(rendered.Length - written.Foot)..], + fileSystem); + + async Task Adopt (Task save, Written written, ReadOnlyMemory rendered, IFileSystem? fileSystem) => + Adopt (await save.ConfigureAwait (false), written, rendered, fileSystem); + bool SameFile (long length) => Source.Describes (length) && _footerStart <= length @@ -904,9 +995,9 @@ ReadOnlySpan RenderId3v1 (ReadOnlySpan original) /// Saves the file to using for the stream. /// /// The target path. - /// The bytes of the file this object was read from; the payload is taken from them at the - /// offsets the read found. Bytes of any other length, a file it has saved since among them, fail with a result, and - /// nothing is written. + /// The bytes of the file this object was read from or, after a save over its source, of the + /// file that save wrote; the payload is taken from them at the offsets of that file. Bytes of any other length, a + /// file it saved elsewhere among them, fail with a result, and nothing is written. /// Optional file system abstraction for testing. /// Whether the write succeeded. public FileWriteResult SaveToFile (string path, ReadOnlySpan originalData, IFileSystem? fileSystem = null) @@ -919,11 +1010,12 @@ public FileWriteResult SaveToFile (string path, ReadOnlySpan originalData, if (Source.Refuse ("MPEG-PS", originalData.Length) is { } mismatch) return mismatch; - var rendered = Render (originalData); + var rendered = Assemble (originalData, out var written); if (rendered.IsEmpty) return FileWriteResult.Failure ("The original data is not the MPEG stream that was read"); - return AtomicFileWriter.Write (path, rendered.Span, fileSystem ?? _sourceFileSystem); + fileSystem ??= _sourceFileSystem; + return Adopt (AtomicFileWriter.Write (path, rendered.Span, fileSystem), written, rendered.Memory, fileSystem); } /// @@ -968,9 +1060,9 @@ public FileWriteResult SaveToFile (IFileSystem? fileSystem = null) /// Asynchronously saves the file to using for the stream. /// /// The target path. - /// The bytes of the file this object was read from; the payload is taken from them at the - /// offsets the read found. Bytes of any other length, a file it has saved since among them, fail with a result, and - /// nothing is written. + /// The bytes of the file this object was read from or, after a save over its source, of the + /// file that save wrote; the payload is taken from them at the offsets of that file. Bytes of any other length, a + /// file it saved elsewhere among them, fail with a result, and nothing is written. /// Optional file system abstraction for testing. /// A token to cancel the write. /// Whether the write succeeded. @@ -988,11 +1080,12 @@ public Task SaveToFileAsync ( if (Source.Refuse ("MPEG-PS", originalData.Length) is { } mismatch) return Task.FromResult (mismatch); - var rendered = Render (originalData.Span); + var rendered = Assemble (originalData.Span, out var written); if (rendered.IsEmpty) return Task.FromResult (FileWriteResult.Failure ("The original data is not the MPEG stream that was read")); - return AtomicFileWriter.WriteAsync (path, rendered.Memory, fileSystem ?? _sourceFileSystem, cancellationToken); + fileSystem ??= _sourceFileSystem; + return Adopt (AtomicFileWriter.WriteAsync (path, rendered.Memory, fileSystem, cancellationToken), written, rendered.Memory, fileSystem); } /// @@ -1065,15 +1158,18 @@ FileWriteResult SaveFromSource (string destinationPath, IFileSystem? fileSystem, if (cancellationToken.IsCancellationRequested) return FileWriteResult.Failure ("Failed to re-read source file: Operation was cancelled"); - var written = PathSave.Replace (destinationPath, opened, output => { + var streamStart = (long)Id3v2Size; + var betweenStart = _appendedEnd; + var saved = PathSave.Replace (destinationPath, opened, output => { StreamCopy.Write (output, head, copyBuffer); - CopyRange (stream, output, Id3v2Size, streamCount, copyBuffer); + CopyRange (stream, output, streamStart, streamCount, copyBuffer); StreamCopy.Write (output, appended, copyBuffer); - CopyRange (stream, output, _appendedEnd, betweenCount, copyBuffer); + CopyRange (stream, output, betweenStart, betweenCount, copyBuffer); StreamCopy.Write (output, foot, copyBuffer); }); source = null; - return written; + var written = new Written (head.Length, Math.Max (0, streamCount), appended.Length, Math.Max (0, betweenCount), foot.Length); + return Adopt (saved, written, head, appended, foot, fileSystem); } finally { source?.Dispose (); if (chunk is not null) diff --git a/src/TagLibSharp2/Mpeg/MpegPsScanner.cs b/src/TagLibSharp2/Mpeg/MpegPsScanner.cs index f90513e7..90077dc4 100644 --- a/src/TagLibSharp2/Mpeg/MpegPsScanner.cs +++ b/src/TagLibSharp2/Mpeg/MpegPsScanner.cs @@ -513,7 +513,7 @@ static MpegPsAudio ReadLpcm (ReadOnlySpan probe) _ => 0 }; var channels = (info & 0x07) + 1; - var bitrate = (int)((long)sampleRate * bits * channels / 1000); + var bitrate = Rates.Kbps ((long)sampleRate * bits * channels); return new MpegPsAudio ("LPCM", sampleRate, channels, bitrate, bits); } @@ -541,9 +541,7 @@ static bool TryFindMpegAudio (ReadOnlySpan probe, out MpegFrame? frame) return false; } - // TimeSpan.FromSeconds rounds to whole milliseconds before .NET Core 3.0. - static TimeSpan Seconds (double seconds) => - TimeSpan.FromTicks ((long)Math.Round (seconds * TimeSpan.TicksPerSecond)); + static TimeSpan Seconds (double seconds) => Durations.FromSecondsToTicks (seconds); static long Modulo (long value) { diff --git a/src/TagLibSharp2/Musepack/MusepackFile.cs b/src/TagLibSharp2/Musepack/MusepackFile.cs index 17a2e500..296bc5ce 100644 --- a/src/TagLibSharp2/Musepack/MusepackFile.cs +++ b/src/TagLibSharp2/Musepack/MusepackFile.cs @@ -13,13 +13,16 @@ namespace TagLibSharp2.Musepack; /// /// Represents the result of parsing a Musepack file. /// -public readonly struct MusepackFileReadResult : IEquatable +public readonly struct MusepackFileReadResult : IEquatable, ISourceRecorder { /// /// Gets the parsed Musepack file, or null if parsing failed. /// public MusepackFile? File { get; } + /// + SourceLength? ISourceRecorder.Source => File?.Source; + /// /// Gets the error message if parsing failed, or null if successful. /// @@ -177,14 +180,7 @@ private MusepackFile () { } /// Parse a Musepack file from byte data. /// public static MusepackFileReadResult Read (ReadOnlySpan data) => - Recorded (Parse (data), data.Length); - - // The file a read made, recording the length of the file it read. - static MusepackFileReadResult Recorded (MusepackFileReadResult result, long length) - { - result.File?.Source.Record (length); - return result; - } + SourceLength.Recorded (Parse (data), data.Length); // The parse of Read without the length it records: a stream reader parses part of the stream and records the // stream's length. @@ -364,7 +360,7 @@ internal static MusepackFileReadResult Read (Stream stream, string? sourcePath, return Mark (Finish (Read (StreamBytes.ReadToEnd (stream)), sourcePath, fileSystem, keepPayload: sourcePath is null), options); } - return Mark (Finish (Recorded (Parse (Join (header, tag), header.Length), stream.Length), sourcePath, fileSystem, keepPayload: false, fileLength: stream.Length), options); + return Mark (Finish (SourceLength.Recorded (Parse (Join (header, tag), header.Length), stream.Length), sourcePath, fileSystem, keepPayload: false, fileLength: stream.Length), options); } static MusepackFileReadResult Mark (MusepackFileReadResult parsed, MediaReadOptions options) @@ -565,7 +561,7 @@ private void CalculateProperties () var bitrate = 0; var length = _fileLength > 0 ? _fileLength : _originalData.Length; if (length > 0 && durationSeconds > 0) - bitrate = (int)(length * 8 / durationSeconds / 1000); + bitrate = Rates.Kbps (length * 8 / durationSeconds); Properties = new AudioProperties ( duration, diff --git a/src/TagLibSharp2/Ogg/OggFlacFile.cs b/src/TagLibSharp2/Ogg/OggFlacFile.cs index bd0253ef..6017b346 100644 --- a/src/TagLibSharp2/Ogg/OggFlacFile.cs +++ b/src/TagLibSharp2/Ogg/OggFlacFile.cs @@ -17,13 +17,16 @@ namespace TagLibSharp2.Ogg; /// /// Represents the result of parsing an Ogg FLAC file. /// -public readonly struct OggFlacFileReadResult : IEquatable +public readonly struct OggFlacFileReadResult : IEquatable, ISourceRecorder { /// /// Gets the parsed Ogg FLAC file, or null if parsing failed. /// public OggFlacFile? File { get; } + /// + SourceLength? ISourceRecorder.Source => File?.Source; + /// /// Gets the error message if parsing failed, or null if successful. /// @@ -116,6 +119,9 @@ internal void MarkPicturesSkipped () private byte[] _originalData = Array.Empty (); private long _fileLength; + + // The last granule position: the stream's samples when STREAMINFO does not give them. + private ulong _granuleSamples; private PacketWalkResult? _cachedWalk; // Counts packet walks. A cache hit does not increment. Test hook only. @@ -205,18 +211,12 @@ internal List MetadataBlockPayloads (byte type) /// Parse an Ogg FLAC file from byte data. /// public static OggFlacFileReadResult Read (ReadOnlySpan data) => - Recorded (Parse (data), data.Length); - - // The file a read made, recording the length of the file it read. - static OggFlacFileReadResult Recorded (OggFlacFileReadResult result, long length) - { - result.File?.Source.Record (length); - return result; - } + SourceLength.Recorded (Parse (data), data.Length); // The parse of Read without the length it records: a stream reader parses part of the stream and records the // stream's length. - static OggFlacFileReadResult Parse (ReadOnlySpan data) + // granulePage: the page a stream read found the duration in; null when data is the whole file. + static OggFlacFileReadResult Parse (ReadOnlySpan data, byte[]? granulePage = null) { if (data.Length < MinHeaderSize) return OggFlacFileReadResult.Failure ("Invalid Ogg FLAC file: data too short for header"); @@ -278,12 +278,18 @@ static OggFlacFileReadResult Parse (ReadOnlySpan data) // Store original data file._originalData = data.ToArray (); + // Parse Vorbis Comment from subsequent Ogg pages + var headerBytes = file.ParseVorbisComment (data); + + // The header pages and the last page with a granule that is not -1 give the granule position, on every entry + // point (#175, #185). + file._granuleSamples = granulePage is null + ? OggWindow.DurationGranule (data, headerBytes) + : OggWindow.DurationGranule (data, headerBytes, granulePage); + // Calculate audio properties file.CalculateProperties (); - // Parse Vorbis Comment from subsequent Ogg pages - file.ParseVorbisComment (data); - return OggFlacFileReadResult.Success (file); } @@ -303,7 +309,7 @@ internal static OggFlacFileReadResult Read (Stream stream, string? sourcePath, I } var headers = OggWindow.ReadHeaders (stream, OggHeaderKind.Flac, options.SkipPictures); - var result = Recorded (Parse (headers), stream.Length); + var result = SourceLength.Recorded (Parse (headers, OggWindow.ReadGranulePage (stream)), stream.Length); if (options.SkipPictures && result.IsSuccess && result.File is not null) result.File.MarkPicturesSkipped (); return WithSource (result, sourcePath, fileSystem, stream.Length); @@ -402,20 +408,23 @@ private static void ParseStreamInfo (ReadOnlySpan data, OggFlacFile file) file.TotalSamples = packed & 0xFFFFFFFFF; } + // STREAMINFO's total of 0 means unknown (RFC 9639 §8.2), as ffmpeg writes it into Ogg; the duration then comes + // from the last granule position, as for Ogg Vorbis and Opus (#184). The other properties are STREAMINFO's. private void CalculateProperties () { - if (SampleRate <= 0 || TotalSamples == 0) { + if (SampleRate <= 0) { Properties = default; return; } - var durationSeconds = (double)TotalSamples / SampleRate; + var samples = TotalSamples > 0 ? TotalSamples : _granuleSamples; + var durationSeconds = (double)samples / SampleRate; var duration = Durations.FromSeconds (durationSeconds); var bitrate = 0; var length = _fileLength > 0 ? _fileLength : _originalData.Length; - if (length > 0 && durationSeconds > 0) - bitrate = (int)(length * 8 / durationSeconds / 1000); + if (length > 0 && duration > TimeSpan.Zero) + bitrate = Rates.Kbps (length * 8 / durationSeconds); Properties = new AudioProperties ( duration, @@ -427,7 +436,8 @@ private void CalculateProperties () ); } - private void ParseVorbisComment (ReadOnlySpan data) + // Returns the bytes of the header pages the walk read: the audio pages start there. + private int ParseVorbisComment (ReadOnlySpan data) { _metadataBlocks.Clear (); var walk = GetWalk (data); @@ -437,6 +447,7 @@ private void ParseVorbisComment (ReadOnlySpan data) if (walk.Comment is not null) VorbisComment = walk.Comment; _metadataBlocks.AddRange (walk.Blocks); + return walk.AudioDataStart; } private static ExtractPacketResult ExtractFirstPacket (ReadOnlySpan data) @@ -555,11 +566,11 @@ public byte[] Render (ReadOnlySpan originalData) } // Remaining pages: Audio data (renumbered) - if (headerInfo.AudioDataStart < originalData.Length) { - var audioPages = originalData.Slice (headerInfo.AudioDataStart); - var fixedAudio = OggPageHelper.RenumberAudioPages (audioPages, headerInfo.SerialNumber, startSequence: nextSequence); - builder.Write (fixedAudio, 0, fixedAudio.Length); - } + // The audio pages, carried across whole or not at all (#199). + var audio = OggPageHelper.CarryAudioPages (originalData, headerInfo.AudioDataStart, headerInfo.SerialNumber, nextSequence); + if (audio is null) + return Array.Empty (); + builder.Write (audio, 0, audio.Length); return builder.ToArray (); } diff --git a/src/TagLibSharp2/Ogg/OggHeaderSkip.cs b/src/TagLibSharp2/Ogg/OggHeaderSkip.cs index d48ac42b..f2d2aa3a 100644 --- a/src/TagLibSharp2/Ogg/OggHeaderSkip.cs +++ b/src/TagLibSharp2/Ogg/OggHeaderSkip.cs @@ -26,8 +26,8 @@ internal static partial class OggWindow /// page leaves a packet open, no packet is complete, a dropped comment value was not a picture, or the header page /// loop would stop within the rebuilt pages. The packet scan /// () stops or fails on the first four before their packets matter, - /// and a packet left open runs on into whatever page the reader appends (the last page of the file), which a - /// rebuilt packet cannot do. + /// and a packet left open at the end of the pages is cut there by the packet scan, which a rebuilt packet cannot + /// be. /// static byte[] ReadHeadersSkipping (Stream stream, OggHeaderKind kind, out bool fullRead) { @@ -51,7 +51,8 @@ static byte[] ReadHeadersSkipping (Stream stream, OggHeaderKind kind, out bool f break; var bodyAt = stream.Position; - if (ShouldStop (stream, header, kind, complete, open)) { + var flacHeaders = flac && packets.Count > 0 ? OggPageHelper.OggFlacHeaderPackets (packets[0]) : 0; + if (ShouldStop (stream, header, kind, complete, open, flacHeaders)) { stream.Position = pageAt; break; } diff --git a/src/TagLibSharp2/Ogg/OggOpusFile.cs b/src/TagLibSharp2/Ogg/OggOpusFile.cs index 778a9b08..5e66a059 100644 --- a/src/TagLibSharp2/Ogg/OggOpusFile.cs +++ b/src/TagLibSharp2/Ogg/OggOpusFile.cs @@ -253,18 +253,12 @@ public static async Task ReadFromFileAsync ( /// Whether to validate CRC-32 checksums. Defaults to false for performance. /// A result indicating success or failure. public static OggOpusFileReadResult Read (ReadOnlySpan data, bool validateCrc = false) => - Recorded (Parse (data, validateCrc), data.Length); - - // The file a read made, recording the length of the file it read. - static OggOpusFileReadResult Recorded (OggOpusFileReadResult result, long length) - { - result.File?.Source.Record (length); - return result; - } + SourceLength.Recorded (Parse (data, validateCrc), data.Length); // The parse of Read without the length it records: a stream reader parses part of the stream and records the // stream's length. - static OggOpusFileReadResult Parse (ReadOnlySpan data, bool validateCrc) + // granulePage: the page a stream read found the duration in; null when data is the whole file. + static OggOpusFileReadResult Parse (ReadOnlySpan data, bool validateCrc, byte[]? granulePage = null) { // Extract the first 2 header packets (OpusHead and OpusTags) var packetsResult = OggPageHelper.ExtractHeaderPackets (data, maxPackets: 2, validateCrc); @@ -300,8 +294,11 @@ static OggOpusFileReadResult Parse (ReadOnlySpan data, bool validateCrc) } } - // The header pages and the last page give the granule position, on every entry point (#175). - var granulePosition = OggWindow.DurationGranule (data, packetsResult.BytesConsumed); + // The header pages and the last page with a granule that is not -1 give the granule position, on every entry + // point (#175, #185). + var granulePosition = granulePage is null + ? OggWindow.DurationGranule (data, packetsResult.BytesConsumed) + : OggWindow.DurationGranule (data, packetsResult.BytesConsumed, granulePage); // Create audio properties (Opus always outputs at 48kHz) var properties = AudioProperties.FromOpus (granulePosition, preSkip, inputSampleRate, channels, data.Length); @@ -319,7 +316,7 @@ static OggOpusFileReadResult Parse (ReadOnlySpan data, bool validateCrc) } /// - /// Reads the Opus header pages and the last page. Audio pages between them are not copied. + /// Reads the Opus header pages and the page the duration comes from. Audio pages are not copied. /// internal static OggOpusFileReadResult Read (Stream stream, string? sourcePath, IFileSystem? fileSystem, bool validateCrc = false) => Read (stream, sourcePath, fileSystem, validateCrc, default); @@ -334,9 +331,8 @@ internal static OggOpusFileReadResult Read (Stream stream, string? sourcePath, I } var headers = OggWindow.ReadHeaders (stream, OggHeaderKind.Opus, options.SkipPictures); - var last = OggWindow.ReadLastPage (stream); - var window = last.Length == 0 ? headers : Concat (headers, last); - var result = WithSource (Recorded (Parse (window, validateCrc), stream.Length), sourcePath, fileSystem, stream.Length); + var granulePage = OggWindow.ReadGranulePage (stream); + var result = WithSource (SourceLength.Recorded (Parse (headers, validateCrc, granulePage), stream.Length), sourcePath, fileSystem, stream.Length); if (options.SkipPictures && result.IsSuccess && result.File is not null) result.File.MarkPicturesSkipped (); return result; @@ -360,7 +356,7 @@ void UseFileLength (long length) if (Properties.Duration.TotalSeconds <= 0) return; - var bitrate = (int)(length * 8 / Properties.Duration.TotalSeconds / 1000); + var bitrate = Rates.Kbps (length * 8 / Properties.Duration.TotalSeconds); Properties = new AudioProperties ( Properties.Duration, bitrate, @@ -370,14 +366,6 @@ void UseFileLength (long length) Properties.Codec); } - static byte[] Concat (byte[] left, byte[] right) - { - var combined = new byte[left.Length + right.Length]; - left.CopyTo (combined, 0); - right.CopyTo (combined, left.Length); - return combined; - } - /// /// Attempts to read an Ogg Opus file from binary data. /// @@ -654,11 +642,11 @@ public BinaryData Render (ReadOnlySpan originalData) builder.Add (page); // Renumber and fix audio pages (sequence numbers + EOS flag) - if (headerInfo.AudioDataStart < originalData.Length) { - var audioPages = originalData.Slice (headerInfo.AudioDataStart); - var fixedAudio = OggPageHelper.RenumberAudioPages (audioPages, headerInfo.SerialNumber, startSequence: nextSequence); - builder.Add (fixedAudio); - } + // The audio pages, carried across whole or not at all (#199). + var audio = OggPageHelper.CarryAudioPages (originalData, headerInfo.AudioDataStart, headerInfo.SerialNumber, nextSequence); + if (audio is null) + return BinaryData.Empty; + builder.Add (audio); return builder.ToBinaryData (); } @@ -838,7 +826,9 @@ static HeaderInfo ExtractHeaderInfo (ReadOnlySpan data) // Extract OpusHead (packet 0) and OpusTags (packet 1) // BytesConsumed gives us where audio data starts var packetsResult = OggPageHelper.ExtractHeaderPackets (data, maxPackets: 2); - if (!packetsResult.IsSuccess || packetsResult.Packets.Count < 1) + // A render rebuilds OpusTags, so it needs only OpusHead; a tags packet the end of the file cut off is refused, + // as Vorbis and Ogg FLAC refuse theirs (#199). + if (!packetsResult.IsSuccess || packetsResult.Packets.Count < 1 || packetsResult.HeaderCut) return HeaderInfo.Failure (); var opusHeadPacket = packetsResult.Packets[0]; @@ -852,13 +842,16 @@ static HeaderInfo ExtractHeaderInfo (ReadOnlySpan data) /// /// Represents the result of reading an from binary data. /// -public readonly struct OggOpusFileReadResult : IEquatable +public readonly struct OggOpusFileReadResult : IEquatable, ISourceRecorder { /// /// Gets the parsed file, or null if parsing failed. /// public OggOpusFile? File { get; } + /// + SourceLength? ISourceRecorder.Source => File?.Source; + /// /// Gets a value indicating whether parsing was successful. /// diff --git a/src/TagLibSharp2/Ogg/OggPageHelper.cs b/src/TagLibSharp2/Ogg/OggPageHelper.cs index b5dffc67..0485fcaa 100644 --- a/src/TagLibSharp2/Ogg/OggPageHelper.cs +++ b/src/TagLibSharp2/Ogg/OggPageHelper.cs @@ -1,6 +1,7 @@ // Copyright (c) 2025-2026 Stephen Shaw and contributors // Licensed under the MIT License. See LICENSE file in the project root for full license information. +using System.Buffers.Binary; using System.Diagnostics.CodeAnalysis; using TagLibSharp2.Core; @@ -127,40 +128,24 @@ public static OggPageWithSegmentsResult ReadOggPageWithSegments (ReadOnlySpan - /// Finds the granule position from the last Ogg page to calculate total samples. - /// - /// The file data to scan. - /// The granule position from the last valid page. - /// - /// Scans the entire file to find all Ogg pages and returns the granule position - /// from the page with the EOS flag, or the last valid page if no EOS is found. - /// Per RFC 3533, the EOS flag marks the last page of a logical stream. - /// - public static ulong FindLastGranulePosition (ReadOnlySpan data) => FindLastGranulePosition (data, []); - - /// - /// over followed by - /// , as if they were one buffer. + /// The granule of the last page in followed by , as if they were + /// one buffer, whose granule is not -1. The readers pass the header pages and the one page the duration comes + /// from, so an end-of-stream flag can only be on a header page, where RFC 3533 §6 ("the last page of a logical + /// bitstream") does not put it: the flag does not pick the granule, and every entry point reads the same whatever + /// flags a read rebuilds its header pages with (#190). /// internal static ulong FindLastGranulePosition (ReadOnlySpan first, ReadOnlySpan second) { var data = new JoinedBytes (first, second); - // Scan from the beginning to find all pages - // Track both the last valid granule and the EOS page's granule ulong lastGranulePosition = 0; - ulong eosGranulePosition = 0; - var foundEos = false; var offset = 0; - while (offset < data.Length - 27) { + // A page with no segments is 27 bytes (RFC 3533 §6), so one may start exactly 27 bytes from the end (#189). + while (offset <= data.Length - 27) { // Look for "OggS" magic if (data[offset] == 'O' && data[offset + 1] == 'g' && data[offset + 2] == 'g' && data[offset + 3] == 'S') { - // Read flags (byte 5) - var flags = data[offset + 5]; - var isEos = (flags & 0x04) != 0; - // Read granule position (8 bytes little-endian at offset 6) var granule = (ulong)data[offset + 6] | ((ulong)data[offset + 7] << 8) | @@ -173,16 +158,9 @@ internal static ulong FindLastGranulePosition (ReadOnlySpan first, ReadOnl // Only update if this looks like a valid granule position // (not -1 which is used for non-audio pages) - if (granule != 0xFFFFFFFFFFFFFFFF) { + if (granule != 0xFFFFFFFFFFFFFFFF) lastGranulePosition = granule; - // Per RFC 3533, prefer granule from EOS page - if (isEos) { - eosGranulePosition = granule; - foundEos = true; - } - } - // Skip to after this page to find next page var segmentCount = data[offset + 26]; if (offset + 27 + segmentCount <= data.Length) { @@ -203,8 +181,7 @@ internal static ulong FindLastGranulePosition (ReadOnlySpan first, ReadOnl offset++; } - // Prefer EOS page's granule if found, otherwise use last valid - return foundEos ? eosGranulePosition : lastGranulePosition; + return lastGranulePosition; } // Two spans read as one buffer, so a scan over both does not have to join them. @@ -467,6 +444,30 @@ public static (byte[][] Pages, uint NextSequence) BuildMultiPagePacket ( return (pages.ToArray (), sequenceNumber); } + /// + /// The audio pages a save writes after the header pages it rebuilt: the pages of from + /// , renumbered as does, + /// or null when that would not carry every audio page across (#199). Two shapes drop audio: bytes that are not a page + /// with a readable page after them (the walk stops there and drops the rest), and a page the duration comes from + /// that lies among the header pages (a header page whose declared body runs over audio pages). A save that gets null + /// fails and writes nothing, as an Ogg Vorbis save of a file whose header packets it cannot find does. Bytes after + /// the last page that hold no page (a page cut short, or other bytes at the end) are not audio. + /// + internal static byte[]? CarryAudioPages (ReadOnlySpan file, int audioStart, uint serialNumber, uint startSequence) + { + var audio = audioStart < file.Length ? file[audioStart..] : []; + var pages = WholePages (audio, out var walked); + var tail = audio[walked..]; + if (HasPageFrom (audio, walked) || OggWindow.DurationPageBefore (file, audioStart)) + return null; + + // The bytes after the last whole page (a last page the end cuts short, or bytes that are no page) are written + // after the pages as they were (#215). A page cut short ends the stream as in the source, so the last whole page + // is not marked as the end. + var renumbered = Renumber (audio, pages, walked, serialNumber, startSequence, endsStream: !IsPageCutShort (tail, tail.Length)); + return [.. renumbered, .. tail]; + } + /// /// Renumbers audio pages with sequential sequence numbers and ensures EOS flag on last page. /// @@ -474,13 +475,19 @@ public static (byte[][] Pages, uint NextSequence) BuildMultiPagePacket ( /// The stream serial number to set on all pages. /// The starting sequence number (typically 2 after header pages). /// The fixed audio pages with correct serial/sequence numbers and EOS flag. - public static byte[] RenumberAudioPages (ReadOnlySpan audioData, uint serialNumber, uint startSequence) + public static byte[] RenumberAudioPages (ReadOnlySpan audioData, uint serialNumber, uint startSequence) => + Renumber (audioData, WholePages (audioData, out var walked), walked, serialNumber, startSequence, endsStream: true); + + // walked: where the pages end, at the first bytes that are not a whole page. + // The whole pages from the start of , and where their walk stops. + static List<(int Offset, int Length)> WholePages (ReadOnlySpan audioData, out int walked) { // First pass: collect all pages to know which is the last one var pages = new List<(int Offset, int Length)> (); var offset = 0; - while (offset < audioData.Length - 27) { + // A page with no segments is 27 bytes and may end the data (#189). + while (offset <= audioData.Length - 27) { // Check for OggS magic if (audioData[offset] != 'O' || audioData[offset + 1] != 'g' || audioData[offset + 2] != 'g' || audioData[offset + 3] != 'S') @@ -502,8 +509,15 @@ public static byte[] RenumberAudioPages (ReadOnlySpan audioData, uint seri offset += totalPageSize; } + walked = offset; + return pages; + } + + static byte[] Renumber (ReadOnlySpan audioData, List<(int Offset, int Length)> pages, int walked, uint serialNumber, uint startSequence, bool endsStream) + { if (pages.Count == 0) return Array.Empty (); + var offset = walked; // Second pass: copy pages with renumbering and EOS fix var result = new byte[offset]; @@ -511,7 +525,7 @@ public static byte[] RenumberAudioPages (ReadOnlySpan audioData, uint seri for (var i = 0; i < pages.Count; i++) { var (pageOffset, pageLength) = pages[i]; - var isLastPage = (i == pages.Count - 1); + var isLastPage = endsStream && i == pages.Count - 1; // Copy the page audioData.Slice (pageOffset, pageLength).CopyTo (result.AsSpan (pageOffset)); @@ -550,54 +564,160 @@ public static byte[] RenumberAudioPages (ReadOnlySpan audioData, uint seri return result; } + /// + /// Whether a readable page (OggS, version 0, its segment table and body inside the data) starts at or after + /// . + /// + static bool HasPageFrom (ReadOnlySpan data, int from) + { + for (var at = from; at <= data.Length - 27; at++) { + var found = data[at..].IndexOf ("OggS"u8); + if (found < 0) + return false; + at += found; + if (IsPageAt (data[at..], data.Length - at)) + return true; + } + + return false; + } + + // A page header at the start of (OggS, version 0, its segment table held) whose page fits + // in the bytes from there to the end. + static bool IsPageAt (ReadOnlySpan header, long left) + { + if (header.Length < 27 || header[4] != 0) + return false; + var segmentCount = header[26]; + if (header.Length < 27 + segmentCount) + return false; + var body = 0; + for (var i = 0; i < segmentCount; i++) + body += header[27 + i]; + return left >= 27 + segmentCount + body; + } + /// /// Copies complete pages from to , /// applying the same serial, sequence, end-of-stream, and CRC update as - /// . + /// . /// /// Seekable stream positioned at the first audio page. /// Stream that receives the patched pages. /// Serial number written onto every page. /// Sequence number of the first audio page. /// - /// A short read or a header that is not OggS ends the copy. The incomplete tail is - /// not written, and only the last complete page gets the end-of-stream bit. The next page + /// A short read or a header that is not OggS ends the copy. The bytes from there to the end (a last page cut + /// short, or bytes that are no page) are written after the pages as they were (#215), and the last complete page + /// gets the end-of-stream bit unless a page cut short follows it, which ends the stream as in the source. The next page /// header is consumed instead of rewound, and reads are filled one maximum page at a time. /// The stream length is read once: on Unix, is an fstat. /// The page buffer is reused. /// - public static void CopyRenumberedPages (Stream source, Stream destination, uint serialNumber, uint startSequence) + /// False when a readable page follows the bytes the copy stopped at, so the pages after them were not + /// carried across (#199), as decides it. A copy + /// that reaches the end neither seeks nor asks for the length again. + public static bool CopyRenumberedPages (Stream source, Stream destination, uint serialNumber, uint startSequence) { var page = new byte[OggWindow.MaxPageBytes]; + var tailHead = new byte[27 + 255]; var peekHeader = new byte[27]; var peekSegments = new byte[255]; var sequence = startSequence; // Snapshot before wrapping. Later length checks would fstat a FileStream once per page. - var left = source.Length - source.Position; + var start = source.Position; + var sourceLength = source.Length; + var left = sourceLength - start; using var buffered = new BufferedStream (new NonClosingStream (source), OggWindow.MaxPageBytes); - if (!TryReadCompletePage (buffered, page, ref left, out var length)) - return; + // The bytes read past the last whole page when the copy stops: a header that is no page, or one whose page + // runs past the end. Unless a readable page follows them, they and every byte after them are written as they + // were (#215), as the scan for such a page reads them. + if (!TryReadCompletePage (buffered, page, ref left, out var length, out var pending)) + return !HasPageAfter (page.AsSpan (0, pending), buffered, start, sourceLength, destination); while (true) { - var last = !TryReadNextHeader (buffered, peekHeader, peekSegments, ref left, out var segmentCount, out var body); - PatchCopiedPage (page.AsSpan (0, length), serialNumber, sequence, last); + var next = sourceLength - left; + var last = !TryReadNextHeader (buffered, peekHeader, peekSegments, ref left, out var segmentCount, out var body, out pending); + if (last) { + Buffer.BlockCopy (peekHeader, 0, tailHead, 0, Math.Min (pending, 27)); + if (pending > 27) + Buffer.BlockCopy (peekSegments, 0, tailHead, 27, pending - 27); + } + + // A last page the end cuts short ends the stream as in the source: the page before it is not marked. + var cutAfter = last && IsPageCutShort (tailHead.AsSpan (0, pending), sourceLength - next); + PatchCopiedPage (page.AsSpan (0, length), serialNumber, sequence, last && !cutAfter); destination.Write (page, 0, length); if (last) - return; + return !HasPageAfter (tailHead.AsSpan (0, pending), buffered, next, sourceLength, destination); sequence++; if (!TakePageBody (buffered, page, peekHeader, peekSegments, segmentCount, body, ref left, out length)) - return; + return true; + } + } + + /// + /// Whether a readable page starts at or after , where a copy stopped: the stream twin of + /// . holds the bytes the copy read from + /// there; the rest is read on from in order, so the stream is not rewound. Each window holds + /// a page header and segment table past the bytes searched in it, so a header across two windows is read whole, and + /// no read asks for more than one maximum page. + /// + static bool HasPageAfter (ReadOnlySpan pending, Stream rest, long stoppedAt, long sourceLength, Stream echo) + { + const int Piece = 32 * 1024; + var window = new byte[Piece + 27 + 255]; + pending.CopyTo (window); + var held = pending.Length; + var windowAt = stoppedAt; + while (true) { + held += Fill (rest, window, held, window.Length - held); + var atEnd = windowAt + held >= sourceLength || held < window.Length; + var searched = atEnd ? held : Piece; + var span = window.AsSpan (0, held); + for (var i = 0; i + 27 <= held && i < searched; i++) { + var found = span[i..].IndexOf ("OggS"u8); + if (found < 0 || i + found >= searched) + break; + i += found; + if (IsPageAt (span[i..], sourceLength - (windowAt + i))) + return true; + } + + echo.Write (window, 0, searched); + if (atEnd) + return false; + + Buffer.BlockCopy (window, searched, window, 0, held - searched); + held -= searched; + windowAt += searched; + } + } + + static int Fill (Stream source, byte[] buffer, int offset, int count) + { + var filled = 0; + while (filled < count) { + var read = source.Read (buffer, offset + filled, count - filled); + if (read == 0) + break; + filled += read; } + + return filled; } - static bool TryReadCompletePage (Stream source, byte[] page, ref long left, out int length) + // consumed: the bytes read into page when the result is false. + static bool TryReadCompletePage (Stream source, byte[] page, ref long left, out int length, out int consumed) { length = 0; - // RenumberAudioPages enters only while offset < length - 27, so a 27-byte tail is not a page. - if (left < 28) + consumed = 0; + // A page with no segments is 27 bytes, as RenumberAudioPages reads it (#189). + if (left < 27) return false; + consumed = 27; if (!ReadExact (source, page, 0, 27) || !IsOggS (page, 0)) return false; @@ -608,6 +728,7 @@ static bool TryReadCompletePage (Stream source, byte[] page, ref long left, out if (segmentCount > 0 && !ReadExact (source, page, 27, segmentCount)) return false; + consumed = 27 + segmentCount; left -= segmentCount; var body = SegmentSum (page, 27, segmentCount); if (left < body) @@ -624,14 +745,22 @@ static bool TryReadCompletePage (Stream source, byte[] page, ref long left, out /// Reads the next page header and segment table without rewinding. /// A false result has consumed whatever prefix was present; that tail is not a page. /// - static bool TryReadNextHeader (Stream source, byte[] header, byte[] segments, ref long left, out int segmentCount, out int body) + // consumed: the bytes read into header, then segments. + static bool TryReadNextHeader (Stream source, byte[] header, byte[] segments, ref long left, out int segmentCount, out int body, out int consumed) { segmentCount = 0; body = 0; - if (left < 28) + consumed = 0; + // Fewer bytes than a header are read too, so the copy asks whether they start a page cut short, as a save of the + // bytes asks it of the whole tail (review 7, N1). + if (left < 27) { + consumed = (int)left; + _ = ReadExact (source, header, 0, consumed); return false; + } var remaining = left; + consumed = 27; if (!ReadExact (source, header, 0, 27) || !IsOggS (header, 0)) return false; @@ -642,6 +771,7 @@ static bool TryReadNextHeader (Stream source, byte[] header, byte[] segments, re if (segmentCount > 0 && !ReadExact (source, segments, 0, segmentCount)) return false; + consumed = 27 + segmentCount; left -= segmentCount; body = SegmentSum (segments, 0, segmentCount); return remaining >= 27 + segmentCount + body; @@ -748,6 +878,27 @@ public static HeaderPacketsResult ExtractPacketsUntilAudio ( int maxPacketSize = MaxPacketSize) => ScanPackets (data, maxPackets, validateCrc, maxPacketSize, stopAtFlacAudio: true, MaxFlacHeaderPages); + /// + /// The number of header packets after the first that an Ogg FLAC first packet declares, or 0 when it says unknown + /// or is not one. The Ogg FLAC mapping (xiph.org/flac/ogg_mapping.html): 0x7F, + /// "FLAC", the mapping version (2 bytes), then "the number of header packets, not including this one", 16 bits + /// big-endian, which "may be zero (0x0000) to signify 'unknown'". + /// + internal static int OggFlacHeaderPackets (ReadOnlySpan firstPacket) => + firstPacket.Length >= 9 && firstPacket[0] == 0x7F && firstPacket.Slice (1, 4).SequenceEqual ("FLAC"u8) + ? BinaryPrimitives.ReadUInt16BigEndian (firstPacket.Slice (7, 2)) + : 0; + + /// + /// Whether a page with segments ends the Ogg FLAC header pages: a page that holds no + /// packet (RFC 3533 §6 allows one), after every header packet the first packet declares, is no header page but the + /// stream's, as an end-of-stream page carrying the final granule is (#189). An unknown count (0) cannot tell, and + /// such a page stays with the headers. The packet walk and the stream header reads (OggWindow.ShouldStop, + /// which the SkipPictures read shares) ask this, so every walk ends the header pages at the same page. + /// + internal static bool EndsOggFlacHeaders (int declared, int completePackets, int segments) => + declared > 0 && completePackets >= 1 + declared && segments == 0; + static HeaderPacketsResult ScanPackets ( ReadOnlySpan data, int maxPackets, @@ -762,6 +913,7 @@ static HeaderPacketsResult ScanPackets ( var pageCount = 0; uint serialNumber = 0; var isFirstPage = true; + var headerCut = false; while (offset < data.Length && packets.Count < maxPackets && pageCount < maxPages) { var pageStart = offset; @@ -779,6 +931,7 @@ static HeaderPacketsResult ScanPackets ( return HeaderPacketsResult.Failure ( $"Ogg FLAC stopped before a readable audio page: {pageResult.Error}", packets, serialNumber, offset); + headerCut = IsPageCutShort (data[offset..], data.Length - offset); break; } @@ -800,6 +953,13 @@ static HeaderPacketsResult ScanPackets ( "Ogg FLAC packet was not finished before the next page", packets, serialNumber, pageStart); + if (stopAtFlacAudio + && !pageResult.Page.IsContinuation + && packetBuffer.Count == 0 + && packets.Count > 0 + && EndsOggFlacHeaders (OggFlacHeaderPackets (packets[0]), packets.Count, pageResult.Segments.Count)) + return HeaderPacketsResult.Success (packets, serialNumber, pageStart); + // RFC 9639 section 10.1: the first audio packet begins a fresh page. Do not consume it. if (stopAtFlacAudio && !pageResult.Page.IsContinuation @@ -889,9 +1049,34 @@ static HeaderPacketsResult ScanPackets ( "Ogg FLAC metadata exceeds the page limit", packets, serialNumber, offset); + // The data ended inside a header packet: the walk had not finished its packets when it reached a page the end + // cuts short, or the end itself with a packet open (#199). + if (headerCut || (packetBuffer.Count > 0 && offset >= data.Length)) + return HeaderPacketsResult.Success (packets, serialNumber, offset, headerCut: true); + return HeaderPacketsResult.Success (packets, serialNumber, offset); } + /// + /// Whether , the bytes at the start of a page with bytes from there to + /// the end of the file, is a page the end cuts short: the capture pattern "OggS" (as much of it as there is), stream + /// structure version 0, and a header, segment table or body that runs past the end. Other bytes that are no page are + /// not one. A header walk that stops at such a page before its header packets are done, or reaches the end with a + /// packet open, has a header packet cut off at the end of the file, and a save refuses it (#199): the packet walk + /// tells it (), and so does the stream header read + /// (OggWindow.ReadHeaders). + /// + internal static bool IsPageCutShort (ReadOnlySpan page, long left) + { + var pattern = "OggS"u8; + var held = Math.Min (page.Length, pattern.Length); + if (held == 0 || !page[..held].SequenceEqual (pattern[..held])) + return false; + if (page.Length > 4 && page[4] != 0) + return false; + return !IsPageAt (page, left); + } + static bool ExceedsPacketSize (int buffered, int fragmentLength, int maxPacketSize) => (long)buffered + fragmentLength > maxPacketSize; @@ -1044,17 +1229,25 @@ internal readonly struct HeaderPacketsResult /// public int BytesConsumed { get; } - HeaderPacketsResult (bool isSuccess, string? error, IReadOnlyList packets, uint serialNumber, int bytesConsumed) + /// + /// Whether the data ended inside a header packet: at a page the end cuts short, or with a packet open, before the + /// walk had its packets (). A save refuses such + /// a file (#199). + /// + public bool HeaderCut { get; } + + HeaderPacketsResult (bool isSuccess, string? error, IReadOnlyList packets, uint serialNumber, int bytesConsumed, bool headerCut = false) { IsSuccess = isSuccess; Error = error; Packets = packets; SerialNumber = serialNumber; BytesConsumed = bytesConsumed; + HeaderCut = headerCut; } - public static HeaderPacketsResult Success (List packets, uint serialNumber, int bytesConsumed) => - new (true, null, packets, serialNumber, bytesConsumed); + public static HeaderPacketsResult Success (List packets, uint serialNumber, int bytesConsumed, bool headerCut = false) => + new (true, null, packets, serialNumber, bytesConsumed, headerCut); public static HeaderPacketsResult Failure (string error) => new (false, error, Array.Empty (), 0, 0); diff --git a/src/TagLibSharp2/Ogg/OggStreamSave.cs b/src/TagLibSharp2/Ogg/OggStreamSave.cs index 49109c57..126192ad 100644 --- a/src/TagLibSharp2/Ogg/OggStreamSave.cs +++ b/src/TagLibSharp2/Ogg/OggStreamSave.cs @@ -58,14 +58,19 @@ void Close () return FileWriteResult.Failure ("Failed to re-read source file: source is not seekable"); byte[] headers; + bool headerCut; try { - headers = OggWindow.ReadHeaders (source, kind); + headers = OggWindow.ReadHeaders (source, kind, out headerCut); } catch (IOException ex) { return FileWriteResult.Failure ($"Failed to re-read source file: Failed to read file: {ex.Message}"); } catch (UnauthorizedAccessException ex) { return FileWriteResult.Failure ($"Failed to re-read source file: Access denied: {ex.Message}"); } + // A header packet the end of the file cuts off would be rebuilt without its lost bytes, or left out (#199). + if (headerCut) + return FileWriteResult.Failure (renderError); + var rendered = renderHeaders (headers); if (rendered is null || rendered.Length == 0 || !TryDescribe (rendered, out var serial, out var startSequence)) return FileWriteResult.Failure (renderError); @@ -77,7 +82,10 @@ void Close () return AtomicFileWriter.WriteStream (destinationPath, fs, output => { try { WritePages (output, rendered); - OggPageHelper.CopyRenumberedPages (source, output, serial, startSequence); + // A page the copy could not reach would be dropped with every page after it (#199): the write + // fails, and the atomic writer leaves the destination as it was. + if (!OggPageHelper.CopyRenumberedPages (source, output, serial, startSequence)) + throw new EndOfStreamException (renderError); } finally { Close (); } diff --git a/src/TagLibSharp2/Ogg/OggVorbisFile.cs b/src/TagLibSharp2/Ogg/OggVorbisFile.cs index 6db30a04..b0453c8e 100644 --- a/src/TagLibSharp2/Ogg/OggVorbisFile.cs +++ b/src/TagLibSharp2/Ogg/OggVorbisFile.cs @@ -207,18 +207,12 @@ public static async Task ReadFromFileAsync ( /// Whether to validate CRC-32 checksums. Defaults to false for performance. /// A result indicating success or failure. public static OggVorbisFileReadResult Read (ReadOnlySpan data, bool validateCrc = false) => - Recorded (Parse (data, validateCrc), data.Length); - - // The file a read made, recording the length of the file it read. - static OggVorbisFileReadResult Recorded (OggVorbisFileReadResult result, long length) - { - result.File?.Source.Record (length); - return result; - } + SourceLength.Recorded (Parse (data, validateCrc), data.Length); // The parse of Read without the length it records: a stream reader parses part of the stream and records the // stream's length. - static OggVorbisFileReadResult Parse (ReadOnlySpan data, bool validateCrc) + // granulePage: the page a stream read found the duration in; null when data is the whole file. + static OggVorbisFileReadResult Parse (ReadOnlySpan data, bool validateCrc, byte[]? granulePage = null) { // Extract the first 2 header packets (identification and comment) // We don't need setup header for metadata reading @@ -250,8 +244,11 @@ static OggVorbisFileReadResult Parse (ReadOnlySpan data, bool validateCrc) } } - // The header pages and the last page give the granule position, on every entry point (#175). - var totalSamples = OggWindow.DurationGranule (data, packetsResult.BytesConsumed); + // The header pages and the last page with a granule that is not -1 give the granule position, on every entry + // point (#175, #185). + var totalSamples = granulePage is null + ? OggWindow.DurationGranule (data, packetsResult.BytesConsumed) + : OggWindow.DurationGranule (data, packetsResult.BytesConsumed, granulePage); // Create audio properties var properties = AudioProperties.FromVorbis (totalSamples, sampleRate, channels, bitrateNominal); @@ -265,7 +262,7 @@ static OggVorbisFileReadResult Parse (ReadOnlySpan data, bool validateCrc) } /// - /// Reads header pages and the last page. Audio pages between them are not copied. + /// Reads header pages and the page the duration comes from. Audio pages are not copied. /// internal static OggVorbisFileReadResult Read (Stream stream, string? sourcePath, IFileSystem? fileSystem, bool validateCrc = false) => Read (stream, sourcePath, fileSystem, validateCrc, default); @@ -280,9 +277,8 @@ internal static OggVorbisFileReadResult Read (Stream stream, string? sourcePath, } var headers = OggWindow.ReadHeaders (stream, OggHeaderKind.Vorbis, options.SkipPictures); - var last = OggWindow.ReadLastPage (stream); - var window = last.Length == 0 ? headers : Concat (headers, last); - var result = WithSource (Recorded (Parse (window, validateCrc), stream.Length), sourcePath, fileSystem); + var granulePage = OggWindow.ReadGranulePage (stream); + var result = WithSource (SourceLength.Recorded (Parse (headers, validateCrc, granulePage), stream.Length), sourcePath, fileSystem); if (options.SkipPictures && result.IsSuccess && result.File is not null) result.File.MarkPicturesSkipped (); return result; @@ -298,14 +294,6 @@ static OggVorbisFileReadResult WithSource (OggVorbisFileReadResult result, strin return result; } - static byte[] Concat (byte[] left, byte[] right) - { - var combined = new byte[left.Length + right.Length]; - left.CopyTo (combined, 0); - right.CopyTo (combined, left.Length); - return combined; - } - /// /// Attempts to read an Ogg Vorbis file from binary data. /// @@ -553,11 +541,11 @@ public BinaryData Render (ReadOnlySpan originalData) } // Renumber and fix audio pages (sequence numbers + EOS flag) - if (headerInfo.AudioDataStart < originalData.Length) { - var audioPages = originalData.Slice (headerInfo.AudioDataStart); - var fixedAudio = OggPageHelper.RenumberAudioPages (audioPages, headerInfo.SerialNumber, startSequence: nextSequence); - builder.Add (fixedAudio); - } + // The audio pages, carried across whole or not at all (#199). + var audio = OggPageHelper.CarryAudioPages (originalData, headerInfo.AudioDataStart, headerInfo.SerialNumber, nextSequence); + if (audio is null) + return BinaryData.Empty; + builder.Add (audio); return builder.ToBinaryData (); } @@ -810,13 +798,16 @@ public void Dispose () /// /// Represents the result of reading an from binary data. /// -public readonly struct OggVorbisFileReadResult : IEquatable +public readonly struct OggVorbisFileReadResult : IEquatable, ISourceRecorder { /// /// Gets the parsed file, or null if parsing failed. /// public OggVorbisFile? File { get; } + /// + SourceLength? ISourceRecorder.Source => File?.Source; + /// /// Gets a value indicating whether parsing was successful. /// diff --git a/src/TagLibSharp2/Ogg/OggWindow.cs b/src/TagLibSharp2/Ogg/OggWindow.cs index bb82e3c4..d82400a7 100644 --- a/src/TagLibSharp2/Ogg/OggWindow.cs +++ b/src/TagLibSharp2/Ogg/OggWindow.cs @@ -1,6 +1,7 @@ // Copyright (c) 2025-2026 Stephen Shaw and contributors // Licensed under the MIT License. See LICENSE file in the project root for full license information. +using System.Buffers.Binary; using TagLibSharp2.Core; namespace TagLibSharp2.Ogg; @@ -14,13 +15,21 @@ enum OggHeaderKind } /// -/// Reads Ogg header pages and, when duration needs it, the last page. +/// Reads Ogg header pages and, when duration needs it, the page the duration comes from (). /// Audio pages in between are not copied. /// internal static partial class OggWindow { public const int MaxPageBytes = 27 + 255 + (255 * 255); + /// + /// How far from the end the page a duration comes from may start: two maximum pages, enough to step back past a + /// -1 page of the largest size to the page before it. A tail of junk or of a long run of -1 pages costs a bounded + /// read, not the whole file. ffprobe gives up sooner, black-box: a granule page more than about 64 KB from the + /// end reads as N/A (F/cap in the fix report). + /// + public const int StepBackBytes = 2 * MaxPageBytes; + readonly struct PageHeader { public PageHeader (byte[] prefix, int bodySize, bool continued, byte[] lacing) @@ -53,28 +62,54 @@ public static byte[] ReadHeaders (Stream stream, OggHeaderKind kind, bool skipPi // not a picture: the pages are read as they are, and the caller forgets the pictures they hold. } + return ReadHeaders (stream, kind, out _); + } + + /// + /// The header pages, as reads them, and whether the file ended inside + /// a header packet at a page the end of the file cuts short, which the header pages leave out + /// (). A save refuses such a file (#199). A + /// packet left open by the last whole page is in the header pages, and the packet walk over them tells it. + /// + public static byte[] ReadHeaders (Stream stream, OggHeaderKind kind, out bool headerCut) + { + headerCut = false; if (stream.Position != 0) stream.Position = 0; using var kept = new MemoryStream (); var complete = 0; var open = false; + var flacHeaders = 0; while (stream.Position < stream.Length) { var pageAt = stream.Position; - if (!TryReadHeader (stream, out var header)) + if (!TryReadHeader (stream, out var header)) { + var left = stream.Length - pageAt; + headerCut = !HeadersDone (kind, complete, open, flacHeaders) + && OggPageHelper.IsPageCutShort (StreamBytes.ReadAtMost (stream, (int)Math.Min (left, 27 + 255)), left); + stream.Position = pageAt; break; + } var bodyAt = stream.Position; - if (ShouldStop (stream, header, kind, complete, open)) { + if (ShouldStop (stream, header, kind, complete, open, flacHeaders)) { stream.Position = pageAt; break; } stream.Position = bodyAt; var body = StreamBytes.ReadAtMost (stream, header.BodySize); - if (body.Length != header.BodySize) + if (body.Length != header.BodySize) { + // A page cut short is no header page: the header pages end where it starts, as the packet walk ends + // them, so a save copies from there and finds any page after it (#199). The walk had not stopped, so + // the page held header bytes: a header packet is cut off. + headerCut = true; + stream.Position = pageAt; break; + } + if (kind == OggHeaderKind.Flac && kept.Length == 0) + flacHeaders = OggPageHelper.OggFlacHeaderPackets (body); StreamBytes.Append (kept, header.Prefix); StreamBytes.Append (kept, body); CountPackets (header, ref complete, ref open); @@ -83,56 +118,136 @@ public static byte[] ReadHeaders (Stream stream, OggHeaderKind kind, bool skipPi return kept.ToArray (); } + // Whether the header packets are all read: Opus has two, Vorbis three, and Ogg FLAC the first packet and the count + // it declares (an unknown count, 0, cannot say). A packet left open is never done. + static bool HeadersDone (OggHeaderKind kind, int complete, bool open, int flacHeaders) => + !open && kind switch { + OggHeaderKind.Opus => complete >= 2, + OggHeaderKind.Vorbis => complete >= 3, + _ => flacHeaders > 0 && complete >= 1 + flacHeaders, + }; + /// - /// The Ogg page that ends at EOF, or empty when the tail is not a page. - /// At most one maximum page is read. + /// The page a stream's duration comes from (see ), read from , + /// or empty when there is none. The stream reads pass it to their parse beside the header pages they hold: only + /// its granule is read, and the pages the parse walks are the header pages alone. /// - public static byte[] ReadLastPage (Stream stream) + public static byte[] ReadGranulePage (Stream stream) { - if (stream.Length < 27) + if (FindGranulePage (new OggTail (stream), new byte[(int)Math.Min (MaxPageBytes, stream.Length)]) is not var (start, length)) return []; + stream.Position = start; + return StreamBytes.ReadAtMost (stream, length); + } + + /// + /// Whether the page 's duration comes from () starts before + /// , among the header pages, with a granule position other than 0. Header pages carry 0 + /// (RFC 7845 §3, the Vorbis I and Ogg FLAC mappings), so such a page is an audio page a header page's declared body + /// runs over, and a save that rebuilds the header pages would drop it (#199). The path save asks it of the header + /// pages it read, which hold any page such a header page runs over. + /// + public static bool DurationPageBefore (ReadOnlySpan data, long headerEnd) => + FindGranulePage (new OggTail (data), []) is var (start, _) && start < headerEnd + && BinaryPrimitives.ReadUInt64LittleEndian (data.Slice ((int)start + 6)) != 0; - var window = (int)Math.Min (stream.Length, MaxPageBytes); - stream.Position = stream.Length - window; - var tail = StreamBytes.ReadAtMost (stream, window); - return LastPage (tail).ToArray (); + /// The page of its duration comes from (see ), or empty. + public static ReadOnlySpan GranulePage (ReadOnlySpan data) => + FindGranulePage (new OggTail (data), []) is var (start, length) ? data.Slice ((int)start, length) : []; + + /// + /// The granule position a stream's duration comes from: + /// over the header pages (the first of ) and + /// , the page finds in the whole file. + /// A stream read finds it in the stream and passes it in, so a read of the whole file in memory takes the same + /// pages and reports the same duration (#175). + /// + public static ulong DurationGranule (ReadOnlySpan data, int headerBytes, ReadOnlySpan granulePage) + { + var headers = data.Slice (0, Math.Min (Math.Max (headerBytes, 0), data.Length)); + return OggPageHelper.FindLastGranulePosition (headers, granulePage); } + /// when is the whole file. + public static ulong DurationGranule (ReadOnlySpan data, int headerBytes) => + DurationGranule (data, headerBytes, GranulePage (data)); + /// - /// The Ogg page that ends at the end of , or empty when the tail is not a page. Only the - /// last maximum page of bytes is searched, as reads them. + /// The last page whose granule position is not -1, as its start and its length cut at the end of the data (a + /// cut-off body still has its granule), or null. RFC 3533 §6: "A special value of -1 (in two's complement) + /// indicates that no packets finish on this page", so a -1 is that page's, not the stream's, and the scan steps + /// back past it to the page before (#185). The rightmost "OggS" whose header fits is a page. The page must start + /// within the last of the data; past that the granule is unknown, and the header pages' + /// granule stands. Windows of one maximum page are read from the end back, each once: at most three. /// - public static ReadOnlySpan LastPage (ReadOnlySpan data) + static (long Start, int Length)? FindGranulePage (OggTail source, byte[] buffer) { - if (data.Length < 27) - return []; + const int Header = 27 + 255; + var windowStart = long.MaxValue; + ReadOnlySpan window = []; + var floor = Math.Max (0, source.Length - StepBackBytes); + for (var at = source.Length - 27; at >= floor; at--) { + if (at < windowStart) { + var windowEnd = Math.Min (source.Length, at + Header); + windowStart = Math.Max (0, windowEnd - MaxPageBytes); + window = source.Read (windowStart, (int)(windowEnd - windowStart), buffer); + } - var tail = data.Slice (data.Length - Math.Min (data.Length, MaxPageBytes)); - for (var i = tail.Length - 27; i >= 0; i--) { - if (tail[i] != (byte)'O' || tail[i + 1] != (byte)'g' || tail[i + 2] != (byte)'g' || tail[i + 3] != (byte)'S') + var i = (int)(at - windowStart); + if (i + 27 > window.Length) continue; - if (!TryDeclaredPageLength (tail, i, out var length, out var complete)) + if (window[i] != (byte)'O' || window[i + 1] != (byte)'g' || window[i + 2] != (byte)'g' || window[i + 3] != (byte)'S') + continue; + if (!TryDeclaredPageLength (window, i, out var length, out _)) + continue; + if (BinaryPrimitives.ReadUInt64LittleEndian (window.Slice (i + 6)) == ulong.MaxValue) continue; - // The rightmost header is the last page. A cut-off body still has its granule. - if (!complete) - return tail.Slice (i); - return tail.Slice (i, length); + return (at, (int)Math.Min (length, source.Length - at)); } - return []; + return null; } - /// - /// The granule position a stream's duration comes from: - /// over the header pages (the first of ) and the last - /// page. A stream read holds only those pages, so a read of the whole file in memory takes the same ones and - /// reports the same duration (#175). - /// - public static ulong DurationGranule (ReadOnlySpan data, int headerBytes) + /// The bytes the tail scan reads: a span in memory, or a seekable stream. + readonly ref struct OggTail { - var headers = data.Slice (0, Math.Min (Math.Max (headerBytes, 0), data.Length)); - return OggPageHelper.FindLastGranulePosition (headers, LastPage (data)); + readonly ReadOnlySpan _span; + readonly Stream? _stream; + + public OggTail (ReadOnlySpan span) + { + _span = span; + _stream = null; + Length = span.Length; + } + + public OggTail (Stream stream) + { + _span = default; + _stream = stream; + Length = stream.Length; + } + + public long Length { get; } + + // A stream's bytes land in buffer, as long as the longest window: one maximum page, or the stream. + public ReadOnlySpan Read (long start, int count, byte[] buffer) + { + if (_stream is null) + return _span.Slice ((int)start, count); + + _stream.Position = start; + var read = 0; + while (read < count) { + var n = _stream.Read (buffer, read, count - read); + if (n <= 0) + break; + read += n; + } + + return buffer.AsSpan (0, read); + } } static bool TryDeclaredPageLength (ReadOnlySpan data, int offset, out int length, out bool complete) @@ -154,7 +269,8 @@ static bool TryDeclaredPageLength (ReadOnlySpan data, int offset, out int return true; } - static bool ShouldStop (Stream stream, PageHeader header, OggHeaderKind kind, int complete, bool open) + // flacHeaders: the header packets an Ogg FLAC first packet declares after itself (OggPageHelper.OggFlacHeaderPackets). + static bool ShouldStop (Stream stream, PageHeader header, OggHeaderKind kind, int complete, bool open, int flacHeaders) { // complete counts packets already kept. The page that finishes the last header // packet is still ahead of that count, so it stays. A later continuation, or a @@ -165,6 +281,8 @@ static bool ShouldStop (Stream stream, PageHeader header, OggHeaderKind kind, in return true; if (header.Continued || open) return false; + if (kind == OggHeaderKind.Flac && OggPageHelper.EndsOggFlacHeaders (flacHeaders, complete, header.Lacing.Length)) + return true; if (kind == OggHeaderKind.Opus) return complete >= 2; if (kind == OggHeaderKind.Vorbis && complete < 2) diff --git a/src/TagLibSharp2/Riff/AviFile.cs b/src/TagLibSharp2/Riff/AviFile.cs index bbe9a27e..294d9b54 100644 --- a/src/TagLibSharp2/Riff/AviFile.cs +++ b/src/TagLibSharp2/Riff/AviFile.cs @@ -156,14 +156,7 @@ internal void MarkPicturesSkipped () /// The whole file, or at least every chunk before movi. /// The parsed file, or a failure when the data is not an AVI file. public static AviFileReadResult Read (ReadOnlySpan data) => - Recorded (Parse (data), data.Length); - - // The file a read made, recording the length of the file it read. - static AviFileReadResult Recorded (AviFileReadResult result, long length) - { - result.File?.Source.Record (length); - return result; - } + SourceLength.Recorded (Parse (data), data.Length); // The parse of Read without the length it records: a stream reader parses part of the stream and records the // stream's length. @@ -271,7 +264,7 @@ internal static AviFileReadResult Read (Stream stream, string? sourcePath, IFile position = next; } - var parsed = WithSource (Recorded (Parse (kept.GetBuffer ().AsSpan (0, (int)kept.Length)), stream.Length), sourcePath, fileSystem); + var parsed = WithSource (SourceLength.Recorded (Parse (kept.GetBuffer ().AsSpan (0, (int)kept.Length)), stream.Length), sourcePath, fileSystem); if (options.SkipPictures && parsed.IsSuccess && parsed.File is not null) parsed.File.MarkPicturesSkipped (); return parsed; @@ -347,7 +340,7 @@ internal static async Task ReadAsync ( position = next; } - var parsed = WithSource (Recorded (Parse (kept.GetBuffer ().AsSpan (0, (int)kept.Length)), stream.Length), sourcePath, fileSystem); + var parsed = WithSource (SourceLength.Recorded (Parse (kept.GetBuffer ().AsSpan (0, (int)kept.Length)), stream.Length), sourcePath, fileSystem); return parsed; } @@ -622,7 +615,7 @@ public void Dispose () /// /// The result of reading an AVI file. /// -public readonly struct AviFileReadResult : IEquatable +public readonly struct AviFileReadResult : IEquatable, ISourceRecorder { AviFileReadResult (AviFile? file, string? error) { @@ -633,6 +626,9 @@ public void Dispose () /// Gets the parsed file, or null when the read failed. public AviFile? File { get; } + /// + SourceLength? ISourceRecorder.Source => File?.Source; + /// Gets the error message when the read failed. public string? Error { get; } diff --git a/src/TagLibSharp2/Riff/AviHeaders.cs b/src/TagLibSharp2/Riff/AviHeaders.cs index a2feeb5f..da8a3174 100644 --- a/src/TagLibSharp2/Riff/AviHeaders.cs +++ b/src/TagLibSharp2/Riff/AviHeaders.cs @@ -43,7 +43,7 @@ public AviStreamHeader (string type, uint handler, uint scale, uint rate, uint l public byte[] Format { get; } /// dwLength * dwScale / dwRate, or zero when the rate is zero. - public TimeSpan Duration => AviHeaders.Seconds (Rate == 0 ? 0 : (double)Length * Scale / Rate); + public TimeSpan Duration => Durations.FromSecondsToTicks (Rate == 0 ? 0 : (double)Length * Scale / Rate); } /// @@ -153,19 +153,6 @@ void ReadStreamList (ReadOnlySpan strl) strf.ToArray ())); } - /// - /// Seconds as a , or zero when the value is not a positive finite duration. - /// A 32-bit length times a 32-bit scale can exceed . - /// - internal static TimeSpan Seconds (double seconds) - { - const double MaxSeconds = long.MaxValue / (double)TimeSpan.TicksPerSecond / 2; - if (double.IsNaN (seconds) || seconds <= 0 || seconds >= MaxSeconds) - return TimeSpan.Zero; - - return TimeSpan.FromTicks ((long)Math.Round (seconds * TimeSpan.TicksPerSecond)); - } - internal static string FourCC (ReadOnlySpan data) => new ([(char)data[0], (char)data[1], (char)data[2], (char)data[3]]); @@ -243,14 +230,14 @@ public static TimeSpan Duration (AviHeaders headers) : video.Length != 0 ? video.Length : headers.TotalFrames; if (video.Rate != 0 && video.Scale != 0) - return AviHeaders.Seconds ((double)frames * video.Scale / video.Rate); - return AviHeaders.Seconds ((double)frames * headers.MicroSecondsPerFrame / 1_000_000d); + return Durations.FromSecondsToTicks ((double)frames * video.Scale / video.Rate); + return Durations.FromSecondsToTicks ((double)frames * headers.MicroSecondsPerFrame / 1_000_000d); } if (FindAudio (headers) is { } audio) return audio.Duration; - return AviHeaders.Seconds ((double)headers.TotalFrames * headers.MicroSecondsPerFrame / 1_000_000d); + return Durations.FromSecondsToTicks ((double)headers.TotalFrames * headers.MicroSecondsPerFrame / 1_000_000d); } public static AviStreamHeader? FindVideo (AviHeaders headers) @@ -322,7 +309,7 @@ public static TimeSpan Duration (AviHeaders headers) var sampleRate = BinaryPrimitives.ReadUInt32LittleEndian (format.AsSpan (4)); var bytesPerSecond = BinaryPrimitives.ReadUInt32LittleEndian (format.AsSpan (8)); var bits = BinaryPrimitives.ReadUInt16LittleEndian (format.AsSpan (14)); - var bitrate = (int)((long)bytesPerSecond * 8 / 1000); + var bitrate = Rates.Kbps ((long)bytesPerSecond * 8); return new AudioProperties ( duration, bitrate, diff --git a/src/TagLibSharp2/Riff/RiffChunk.cs b/src/TagLibSharp2/Riff/RiffChunk.cs index 271316b2..3a7716e5 100644 --- a/src/TagLibSharp2/Riff/RiffChunk.cs +++ b/src/TagLibSharp2/Riff/RiffChunk.cs @@ -101,7 +101,14 @@ internal static RiffChunk WithDeclaredSize (string fourCC, uint dataSize, Binary /// The offset where the chunk begins. /// The parsed chunk if successful. /// True if a valid chunk was parsed; false otherwise. - public static bool TryParse (BinaryData data, int offset, out RiffChunk chunk) + public static bool TryParse (BinaryData data, int offset, out RiffChunk chunk) => + TryParse (data, offset, data.Length, out chunk); + + /// + /// within a form that ends at : the + /// chunk holds , the rule the stream walk applies too. + /// + internal static bool TryParse (BinaryData data, int offset, int end, out RiffChunk chunk) { chunk = default; @@ -116,17 +123,8 @@ public static bool TryParse (BinaryData data, int offset, out RiffChunk chunk) // Read chunk data size (32-bit little-endian) var dataSize = data.ToUInt32LE (offset + 4); - // Overflow protection: reject chunks claiming > int.MaxValue size - if (dataSize > int.MaxValue) - return false; - - // Validate that we have enough data - // Note: We don't require padding byte to be present in source data - var availableData = data.Length - offset - HeaderSize; - var actualDataSize = Math.Min ((int)dataSize, availableData); - - if (actualDataSize < 0) - return false; + // The chunk holds the bytes present in the form, up to its size (#192). The padding byte need not be present. + var actualDataSize = (int)ChunkExtent.PresentBytes (dataSize, offset + HeaderSize, Math.Min (end, data.Length)); var chunkData = actualDataSize > 0 ? data.Slice (offset + HeaderSize, actualDataSize) diff --git a/src/TagLibSharp2/Riff/RiffFile.cs b/src/TagLibSharp2/Riff/RiffFile.cs index a7722e02..2c9b99be 100644 --- a/src/TagLibSharp2/Riff/RiffFile.cs +++ b/src/TagLibSharp2/Riff/RiffFile.cs @@ -126,13 +126,33 @@ public bool RemoveChunks (string fourCC) return removed; } + /// + /// The bytes after the RIFF form ends: not its chunks, but the file's, and a WAV save writes them after the form (#192). + /// + internal FormTrail? Trail { get; set; } + + /// + /// Whether a SkipPictures read left a picture out of the tag chunk ( + /// with a tag identifier): a full read reads the picture, so its tag cleared of pictures is not the tag as read. + /// + internal bool TagPicturesDropped { get; private set; } + /// /// Attempts to parse RIFF data. /// /// The source data. /// The parsed file if successful. /// True if parsing succeeded. - public static bool TryParse (BinaryData data, out RiffFile file) + public static bool TryParse (BinaryData data, out RiffFile file) => + TryParse (data, tagId: null, out file); + + /// + /// , reading a chunk named (in either case) + /// that a tagger appended after the form as one of its chunks, named , when the form holds + /// none, and marking the tag chunks after the form that the form's tag supersedes (, + /// #192). + /// + internal static bool TryParse (BinaryData data, string? tagId, out RiffFile file) { file = new RiffFile (); @@ -150,12 +170,11 @@ public static bool TryParse (BinaryData data, out RiffFile file) file.FormType = data.Slice (8, 4).ToStringLatin1 (); // 0xFFFFFFFF is a placeholder from streamed writers. RF64 is unsupported. - var formEnd = file.FileSize == 0xFFFFFFFF ? (long)data.Length : (long)file.FileSize + 8; - var limit = (int)Math.Min ((long)data.Length, formEnd); + var limit = (int)ChunkExtent.FormEnd (file.FileSize, data.Length); var offset = HeaderSize; while (offset + RiffChunk.HeaderSize <= limit) { - if (!RiffChunk.TryParse (data, offset, out var chunk)) + if (!RiffChunk.TryParse (data, offset, limit, out var chunk)) break; // ckSize is the data length and does not include the pad byte. @@ -173,6 +192,22 @@ public static bool TryParse (BinaryData data, out RiffFile file) offset = (int)next; } + var trailStart = (long)limit; + long superseded = 0; + if (tagId is not null) { + string[] tagIds = [tagId]; + var hasTag = file._chunks.Exists (chunk => chunk.FourCC == tagId); + if (!hasTag && TrailingTagChunk.TryRead (data.Span.Slice (limit), bigEndian: false, tagIds, out var tag)) { + file._chunks.Add (new RiffChunk (tagId, new BinaryData (tag.Body))); + trailStart += tag.Taken; + hasTag = true; + } + + if (hasTag) + superseded = TrailingTagChunk.Superseded (data.Span.Slice ((int)trailStart), bigEndian: false, tagIds); + } + + file.Trail = FormTrail.Of (data.Memory, trailStart, superseded); file.IsValid = true; return true; } @@ -203,9 +238,9 @@ public SkippedChunk (int index, long offset, uint presentBytes) /// is one , in file order. A later chunk is still parsed. /// internal static bool TryRead (Stream stream, out RiffFile file, out List skipped) => - TryRead (stream, skipPictures: false, out file, out skipped); + TryRead (stream, skipPictures: false, tagId: null, out file, out skipped); - internal static bool TryRead (Stream stream, bool skipPictures, out RiffFile file, out List skipped) + internal static bool TryRead (Stream stream, bool skipPictures, string? tagId, out RiffFile file, out List skipped) { file = new RiffFile (); skipped = []; @@ -218,8 +253,7 @@ internal static bool TryRead (Stream stream, bool skipPictures, out RiffFile fil file.FormType = FourCharacters (header, 8); // 0xFFFFFFFF is a placeholder from streamed writers, same as TryParse. - var formEnd = file.FileSize == 0xFFFFFFFF ? stream.Length : (long)file.FileSize + 8; - var limit = Math.Min (stream.Length, formEnd); + var limit = ChunkExtent.FormEnd (file.FileSize, stream.Length); while (stream.Position + RiffChunk.HeaderSize <= limit) { var chunkHeader = StreamBytes.ReadAtMost (stream, RiffChunk.HeaderSize); if (chunkHeader.Length < RiffChunk.HeaderSize) @@ -227,11 +261,11 @@ internal static bool TryRead (Stream stream, bool skipPictures, out RiffFile fil var fourCC = FourCharacters (chunkHeader, 0); var size = (uint)chunkHeader[4] | ((uint)chunkHeader[5] << 8) | ((uint)chunkHeader[6] << 16) | ((uint)chunkHeader[7] << 24); - var remaining = limit - stream.Position; - var available = remaining < size ? (uint)Math.Max (0, remaining) : size; - // A data chunk is reloaded on save. A ckSize past int.MaxValue cannot be - // copied here; skipping it in long arithmetic keeps the chunks after it. - if (fourCC == "data" || size > int.MaxValue) { + var available = (uint)ChunkExtent.PresentBytes (size, stream.Position, limit); + // A data chunk is reloaded on save. Other chunks are copied, but only the bytes present, as the span walk + // keeps them: a ckSize past int.MaxValue with bytes that fit is read like any other (#192), and only bytes + // present past int.MaxValue, which cannot be copied, are left in the file like samples. + if (fourCC == "data" || available > int.MaxValue) { if (available > 0) skipped.Add (new SkippedChunk (file._chunks.Count, stream.Position, available)); var pad = (size & 1) == 1 && available == size ? 1L : 0L; @@ -249,7 +283,9 @@ internal static bool TryRead (Stream stream, bool skipPictures, out RiffFile fil uint stored = size; if (skipPictures && (fourCC == "id3 " || fourCC == "ID32")) { var bodyEnd = stream.Position + available; - payload = TagLibSharp2.Id3.Id3v2.Id3v2Tag.CopyWithoutPictures (stream, bodyEnd).Bytes; + var stripped = TagLibSharp2.Id3.Id3v2.Id3v2Tag.CopyWithoutPictures (stream, bodyEnd); + payload = stripped.Bytes; + file.TagPicturesDropped |= fourCC == tagId && stripped.DroppedPictures; if (stream.Position < bodyEnd) PictureSkip.Discard (stream, bodyEnd - stream.Position); stored = (uint)payload.Length; @@ -266,6 +302,23 @@ internal static bool TryRead (Stream stream, bool skipPictures, out RiffFile fil break; } + var trailStart = limit; + long superseded = 0; + if (tagId is not null) { + string[] tagIds = [tagId]; + var hasTag = file._chunks.Exists (chunk => chunk.FourCC == tagId); + if (!hasTag && TrailingTagChunk.TryRead (stream, limit, stream.Length, bigEndian: false, tagIds, skipPictures, out var tag)) { + file._chunks.Add (new RiffChunk (tagId, new BinaryData (tag.Body))); + file.TagPicturesDropped |= tag.DroppedPictures; + trailStart += tag.Taken; + hasTag = true; + } + + if (hasTag) + superseded = TrailingTagChunk.Superseded (stream, trailStart, stream.Length, bigEndian: false, tagIds); + } + + file.Trail = FormTrail.InSource (trailStart, stream.Length, superseded); file.IsValid = true; return true; } diff --git a/src/TagLibSharp2/Riff/WavAudioProperties.cs b/src/TagLibSharp2/Riff/WavAudioProperties.cs index 6a61a97b..950111d3 100644 --- a/src/TagLibSharp2/Riff/WavAudioProperties.cs +++ b/src/TagLibSharp2/Riff/WavAudioProperties.cs @@ -186,8 +186,8 @@ public static class WavAudioPropertiesParser var formatCode = fmtData.ToUInt16LE (0); var channels = fmtData.ToUInt16LE (2); - var sampleRate = (int)fmtData.ToUInt32LE (4); - var byteRate = (int)fmtData.ToUInt32LE (8); + var sampleRate = Rates.SampleRate (fmtData.ToUInt32LE (4)); + var byteRate = fmtData.ToUInt32LE (8); // Block align at offset 12, not needed for basic properties var bitsPerSample = fmtData.ToUInt16LE (14); @@ -198,10 +198,10 @@ public static class WavAudioPropertiesParser // Calculate duration if we know the data size var duration = TimeSpan.Zero; if (dataChunkSize > 0 && byteRate > 0) - duration = TimeSpan.FromSeconds ((double)dataChunkSize / byteRate); + duration = Durations.FromSeconds ((double)dataChunkSize / byteRate); // Calculate bitrate in kbps - var bitrate = byteRate * 8 / 1000; + var bitrate = Rates.Kbps (byteRate * 8L); var codec = GetFormatDescription (formatCode); @@ -241,7 +241,7 @@ public static class WavAudioPropertiesParser return null; var channels = fmtData.ToUInt16LE (2); - var sampleRate = (int)fmtData.ToUInt32LE (4); + var sampleRate = Rates.SampleRate (fmtData.ToUInt32LE (4)); var bitsPerSample = fmtData.ToUInt16LE (14); var validBitsPerSample = fmtData.ToUInt16LE (18); var channelMask = fmtData.ToUInt32LE (20); diff --git a/src/TagLibSharp2/Riff/WavFile.cs b/src/TagLibSharp2/Riff/WavFile.cs index 0978f44f..ab1d765a 100644 --- a/src/TagLibSharp2/Riff/WavFile.cs +++ b/src/TagLibSharp2/Riff/WavFile.cs @@ -286,7 +286,7 @@ public void Dispose () /// A result containing the parsed file or error information. public static WavFileReadResult Read (ReadOnlySpan data) { - if (!RiffFile.TryParse (new BinaryData (data.ToArray ()), out var riff)) + if (!RiffFile.TryParse (new BinaryData (data.ToArray ()), Id3ChunkId, out var riff)) return WavFileReadResult.Failure ("Invalid WAV file: invalid RIFF structure"); return FromParsed (riff, null); @@ -309,7 +309,7 @@ internal static WavFileReadResult Read (Stream stream, string? sourcePath, IFile if (stream.Position != 0) stream.Position = 0; - if (!RiffFile.TryRead (stream, options.SkipPictures, out var riff, out var skipped)) + if (!RiffFile.TryRead (stream, options.SkipPictures, Id3ChunkId, out var riff, out var skipped)) return WavFileReadResult.Failure ("Invalid WAV file: invalid RIFF structure"); var result = FromParsed (riff, FirstDataBytes (riff, skipped)); @@ -559,7 +559,17 @@ public BinaryData Render () riff.SetChunk (new RiffChunk (Id3ChunkId, id3Data)); } - return riff.Render ("WAVE"); + var form = riff.Render ("WAVE"); + if (_riff.Trail?.For (TagRewritten) is not { } trail) + return form; + + // The bytes after the RIFF form are written after it as they were (#192). + if (form.Length + trail.Length > int.MaxValue) + throw new InvalidOperationException ("Cannot render a WAV file larger than supported memory."); + using var builder = new BinaryDataBuilder (form.Length + (int)trail.Length); + builder.Add (form); + builder.Add (trail.Bytes); + return builder.ToBinaryData (); } /// @@ -611,7 +621,7 @@ static uint MaxSampleBytes { bool TryLoadSkippedSamples (out string? error) { error = null; - if (_skippedChunks.Count == 0) + if (_skippedChunks.Count == 0 && _riff.Trail is null or { Held: true }) return true; foreach (var chunk in _skippedChunks) { @@ -622,19 +632,27 @@ bool TryLoadSkippedSamples (out string? error) } if (SourcePath is not { Length: > 0 } path) { - error = "Cannot save a WAV file whose sample data was not loaded."; + error = _skippedChunks.Count > 0 + ? "Cannot save a WAV file whose sample data was not loaded." + : "Cannot save a WAV file whose bytes after its RIFF form were not loaded."; return false; } var fs = _sourceFileSystem ?? DefaultFileSystem.Instance; using var stream = fs.OpenRead (path); + var length = stream.Length; foreach (var chunk in _skippedChunks) { - if (stream.Length < chunk.Offset + chunk.PresentBytes) { + if (length < chunk.Offset + chunk.PresentBytes) { error = "Cannot save a WAV file whose sample data is no longer in the source file."; return false; } } + if (_riff.Trail is { } trail && !trail.TryLoad (stream, length)) { + error = TrailMissing; + return false; + } + var loaded = new List (_skippedChunks.Count); foreach (var chunk in _skippedChunks) { stream.Position = chunk.Offset; @@ -657,12 +675,17 @@ bool TryLoadSkippedSamples (out string? error) return true; } - FileWriteResult? MissingDataChunkFailure () + // Render throws for a file without a sample rate or a data chunk; a save returns a failure and writes nothing + // (#194). + FileWriteResult? SaveRefusal () { - if (!IsValid || HasDataChunk) - return null; - - return FileWriteResult.Failure ("Cannot save a WAV file that has no data chunk."); + if (_riff?.IsValid != true) + return FileWriteResult.Failure ("Cannot save a WAV file whose RIFF structure is invalid."); + if (!IsValid) + return FileWriteResult.Failure ("Cannot save a WAV file that has no sample rate."); + if (!HasDataChunk) + return FileWriteResult.Failure ("Cannot save a WAV file that has no data chunk."); + return null; } /// @@ -671,16 +694,16 @@ bool TryLoadSkippedSamples (out string? error) /// The file path. /// Optional file system abstraction. /// - /// The write result. Fails without writing when the file has no data chunk. + /// The write result. Fails without writing when the file has no sample rate or no data chunk. /// public FileWriteResult SaveToFile (string path, IFileSystem? fileSystem = null) { if (PictureSkip.Refuse (this) is { } denied) return denied; - if (MissingDataChunkFailure () is { } failure) + if (SaveRefusal () is { } failure) return failure; - if (!IsValid || _skippedChunks.Count == 0) + if (_skippedChunks.Count == 0) return SaveLoaded (path, fileSystem); return SaveFromSource (path, fileSystem, default); @@ -693,7 +716,7 @@ public FileWriteResult SaveToFile (string path, IFileSystem? fileSystem = null) /// Optional file system abstraction. /// Cancellation token. /// - /// The write result. Fails without writing when the file has no data chunk. + /// The write result. Fails without writing when the file has no sample rate or no data chunk. /// public Task SaveToFileAsync ( string path, @@ -702,10 +725,10 @@ public Task SaveToFileAsync ( { if (PictureSkip.Refuse (this) is { } denied) return Task.FromResult (denied); - if (MissingDataChunkFailure () is { } failure) + if (SaveRefusal () is { } failure) return Task.FromResult (failure); - if (!IsValid || _skippedChunks.Count == 0) + if (_skippedChunks.Count == 0) return SaveLoadedAsync (path, fileSystem, cancellationToken); // Length and "was not loaded" are decided before the token, matching the sync save. @@ -732,17 +755,36 @@ Task SaveLoadedAsync (string path, IFileSystem? fileSystem, Can return AtomicFileWriter.WriteAsync (path, data.Memory, fileSystem, cancellationToken); } + const string TrailMissing = "Cannot save a WAV file whose bytes after its RIFF form are no longer in the source file."; + + /// + /// Whether a save writes the id3 chunk other than as the read found it, so the tag chunks after the form that it + /// supersedes are dropped (, #192): the tag it writes, rendered, against the + /// tag the chunk read, rendered, or a tag written or removed where there was none or one. A SkipPictures read that + /// left a picture out of the tag writes what a full read cleared of its pictures writes, which is not the tag read. + /// + bool TagRewritten () + { + if (_riff.TagPicturesDropped) + return true; + + var chunk = _riff.GetChunk (Id3ChunkId); + byte[]? read = chunk is { } found && found.Data.Length > 0 + && Id3v2Tag.Read (found.Data.Span) is { IsSuccess: true, Tag: { IsEmpty: false } readTag } + ? readTag.Render ().ToArray () + : null; + byte[]? written = Id3v2Tag is { IsEmpty: false } tag ? tag.Render ().ToArray () : null; + return read is null ? written is not null : written is null || !read.AsSpan ().SequenceEqual (written); + } + /// /// Writes the same bytes as without loading skipped samples. /// The read file system is the one from the stream read. is only the write target. /// FileWriteResult SaveFromSource (string path, IFileSystem? fileSystem, CancellationToken cancellationToken) { - foreach (var chunk in _skippedChunks) { - if (chunk.PresentBytes > MaxSampleBytes) - return FileWriteResult.Failure ("Cannot save a WAV file whose sample data does not fit in memory."); - } - + // A chunk of any size is copied from the source in pieces, as an AIFF save copies its sound (#197); only the + // RIFF's 32-bit size bounds the file (#203). if (SourcePath is not { Length: > 0 } sourcePath) return FileWriteResult.Failure ("Cannot save a WAV file whose sample data was not loaded."); @@ -764,15 +806,38 @@ FileWriteResult SaveFromSource (string path, IFileSystem? fileSystem, Cancellati if (!TryPlanPieces (open.Stream, out var pieces, out var planError)) return planError; + long chunksSize = 0; + foreach (var piece in pieces) + chunksSize += piece.Size; + if (4 + chunksSize > uint.MaxValue) + return FileWriteResult.Failure ("Cannot save a WAV file larger than its 32-bit RIFF size."); + var rented = StreamCopy.Rent (); buffer = rented; + var layout = new ChunkLayout (); + var trail = _riff.Trail?.For (TagRewritten); var result = AtomicFileWriter.WriteStream (path, writeFs, output => { try { - WritePlanned (output, open.Stream, pieces, rented); + WritePlanned (output, open.Stream, pieces, rented, layout); + trail?.Write (output, open.Stream, open.Length, rented); + layout.Trail (trail?.Length ?? 0); } finally { open.Dispose (); } }); + // A save over the source moved the samples when a chunk ahead of them changed size: the next save copies + // them from where this one wrote them. + if (result.IsSuccess && layout.Holds (SourcePath, readFs)) { + foreach (var (index, offset) in layout.Copied) { + var moved = _skippedChunks[index]; + _skippedChunks[index] = new RiffFile.SkippedChunk (moved.Index, offset, moved.PresentBytes); + } + + // The superseded tag chunks this save dropped are no longer in the source, so the next save copies the + // bytes that were after them. + _riff.Trail = trail; + } + return result; } finally { if (buffer is not null) @@ -967,7 +1032,7 @@ static void AddInline (List pieces, RiffChunk chunk, bool replace) /// /// ckSize is the bytes present, and an odd length gets a 0 pad that is not copied from the source. /// - void WritePlanned (Stream output, Stream source, List pieces, byte[] chunk) + void WritePlanned (Stream output, Stream source, List pieces, byte[] chunk, ChunkLayout layout) { long chunksSize = 0; foreach (var piece in pieces) @@ -985,14 +1050,16 @@ void WritePlanned (Stream output, Stream source, List pieces, byte header[10] = (byte)'V'; header[11] = (byte)'E'; output.Write (header, 0, header.Length); + layout.Written (header); - var chunkHeader = new byte[RiffChunk.HeaderSize]; foreach (var piece in pieces) { if (piece.Inline is not null) { StreamCopy.Write (output, piece.Inline, chunk); + layout.Written (piece.Inline); continue; } + var chunkHeader = new byte[RiffChunk.HeaderSize]; var skipped = _skippedChunks[piece.SkippedIndex]; var fourCC = piece.FourCC; chunkHeader[0] = (byte)fourCC[0]; @@ -1001,6 +1068,7 @@ void WritePlanned (Stream output, Stream source, List pieces, byte chunkHeader[3] = (byte)fourCC[3]; BinaryPrimitives.WriteUInt32LittleEndian (chunkHeader.AsSpan (4), skipped.PresentBytes); output.Write (chunkHeader, 0, chunkHeader.Length); + layout.Copy (piece.SkippedIndex, chunkHeader, piece.Size); source.Position = skipped.Offset; StreamCopy.Copy (source, output, skipped.PresentBytes, chunk); if ((skipped.PresentBytes & 1) == 0) diff --git a/src/TagLibSharp2/WavPack/WavPackFile.cs b/src/TagLibSharp2/WavPack/WavPackFile.cs index d69fa44d..f6138a0c 100644 --- a/src/TagLibSharp2/WavPack/WavPackFile.cs +++ b/src/TagLibSharp2/WavPack/WavPackFile.cs @@ -15,13 +15,16 @@ namespace TagLibSharp2.WavPack; /// /// Represents the result of parsing a WavPack file. /// -public readonly struct WavPackFileReadResult : IEquatable +public readonly struct WavPackFileReadResult : IEquatable, ISourceRecorder { /// /// Gets the parsed WavPack file, or null if parsing failed. /// public WavPackFile? File { get; } + /// + SourceLength? ISourceRecorder.Source => File?.Source; + /// /// Gets the error message if parsing failed, or null if successful. /// @@ -199,14 +202,7 @@ private WavPackFile () { } /// A result indicating success with the parsed file, or failure with an error message. [SuppressMessage ("Reliability", "CA2000:Dispose objects before losing scope", Justification = "Factory method transfers ownership to caller")] public static WavPackFileReadResult Read (ReadOnlySpan data) => - Recorded (Parse (data), data.Length); - - // The file a read made, recording the length of the file it read. - static WavPackFileReadResult Recorded (WavPackFileReadResult result, long length) - { - result.File?.Source.Record (length); - return result; - } + SourceLength.Recorded (Parse (data), data.Length); // The parse of Read without the length it records: a stream reader parses part of the stream and records the // stream's length. @@ -237,7 +233,10 @@ static WavPackFileReadResult Parse (ReadOnlySpan data, int tagFloor = 0) return WavPackFileReadResult.Failure ("Invalid WavPack file: data too short for block header"); } - ApplyBlockHeader (file, block); + // The block size counts the block after its first 8 bytes, and the header takes 24 of them. A smaller size + // is no block, and its header fields are not the stream's: the properties are unknown (#201). + if (HoldsBlockHeader (file.BlockSize)) + ApplyBlockHeader (file, block); } else if (!ApplyLegacyHeader (file, block, fmt, sawDataChunk, dataChunkSize)) { file.Dispose (); return WavPackFileReadResult.Failure ("Invalid WavPack file: data too short for block header"); @@ -258,7 +257,7 @@ static WavPackFileReadResult Parse (ReadOnlySpan data, int tagFloor = 0) static void ApplyBlockHeader (WavPackFile file, ReadOnlySpan block) { // [12-15] Total samples - file.TotalSamples = BinaryPrimitives.ReadUInt32LittleEndian (block.Slice (12, 4)); + file.TotalSamples = SampleCount (BinaryPrimitives.ReadUInt32LittleEndian (block.Slice (12, 4))); // [24-27] Flags var flags = BinaryPrimitives.ReadUInt32LittleEndian (block.Slice (24, 4)); @@ -322,7 +321,7 @@ internal static WavPackFileReadResult Read (Stream stream, string? sourcePath, I if (tagAt < block.Length) return Mark (Finish (Read (ReadWhole (stream)), sourcePath, fileSystem, keepPayload: sourcePath is null), options); - return Mark (Finish (Recorded (Parse (Join (block, tag), block.Length), stream.Length), sourcePath, fileSystem, keepPayload: false, fileLength: stream.Length), options); + return Mark (Finish (SourceLength.Recorded (Parse (Join (block, tag), block.Length), stream.Length), sourcePath, fileSystem, keepPayload: false, fileLength: stream.Length), options); } static WavPackFileReadResult Mark (WavPackFileReadResult result, MediaReadOptions options) @@ -340,9 +339,14 @@ static byte[] ReadWhole (Stream stream) return StreamBytes.ReadToEnd (stream); } + // Whether a version 4 block size can hold the 32-byte block header: the size counts the bytes after its first 8. + static bool HoldsBlockHeader (uint blockSize) => blockSize >= BlockHeaderSize - 8; + static byte[] ReadFirstBlock (Stream stream, byte[] header, uint blockSize) { - var total = 8L + blockSize; + // A size too small to hold the block header still has the header's 32 bytes read, as a read of the whole file + // sees them; the parse then reads no properties from them (#201). + var total = 8L + (HoldsBlockHeader (blockSize) ? blockSize : BlockHeaderSize - 8); if (total <= header.Length) return header.AsSpan (0, (int)Math.Min (header.Length, Math.Max (total, 0))).ToArray (); if (total <= 64 * 1024) { @@ -452,7 +456,7 @@ static WavPackFileReadResult ReadRiffWrapped (Stream stream, string? sourcePath, if (tagAt < window.Length) return Mark (Finish (Read (ReadWhole (stream)), sourcePath, fileSystem, keepPayload: sourcePath is null), options); - return Mark (Finish (Recorded (Parse (Join (window, tag), window.Length), stream.Length), sourcePath, fileSystem, keepPayload: false, fileLength: stream.Length), options); + return Mark (Finish (SourceLength.Recorded (Parse (Join (window, tag), window.Length), stream.Length), sourcePath, fileSystem, keepPayload: false, fileLength: stream.Length), options); } // Copies fmt and the wvpk header bytes that are present (at most 32). A declared @@ -579,7 +583,7 @@ static bool ApplyLegacyHeader ( if (block.Length < LegacyV3HeaderBytes) return false; - file.TotalSamples = BinaryPrimitives.ReadUInt32LittleEndian (block.Slice (16, 4)); + file.TotalSamples = SampleCount (BinaryPrimitives.ReadUInt32LittleEndian (block.Slice (16, 4))); } else if (file.Version == 2) { if (block.Length < LegacyV2HeaderBytes) return false; @@ -596,6 +600,12 @@ static bool ApplyLegacyHeader ( return true; } + // The WavPack file format, of the version 4 block header: total_samples "is only valid if block_index == 0 and a + // value of -1 indicates unknown length". The marker is no count, so the file has none, as when the header gives 0 + // (#191). The version 3 header, which that document does not describe, takes the same rule as the versions 1 and 2 + // data size, whose bit 31 already means an unknown length. + static uint SampleCount (uint totalSamples) => totalSamples == uint.MaxValue ? 0 : totalSamples; + // Version < 0x100 stores zeros in the v4 flag word, so that table reports 6000 Hz. static void ApplyWaveFormat (WavPackFile file, ReadOnlySpan fmt) { @@ -630,13 +640,13 @@ private void CalculateProperties () } var durationSeconds = (double)TotalSamples / SampleRate; - var duration = TimeSpan.FromSeconds (durationSeconds); + var duration = Durations.FromSeconds (durationSeconds); // Calculate bitrate from file size var bitrate = 0; var length = _fileLength > 0 ? _fileLength : _originalData.Length; if (length > 0 && durationSeconds > 0) - bitrate = (int)(length * 8 / durationSeconds / 1000); + bitrate = Rates.Kbps (length * 8 / durationSeconds); Properties = new AudioProperties ( duration, diff --git a/src/TagLibSharp2/Xiph/FlacFile.cs b/src/TagLibSharp2/Xiph/FlacFile.cs index 68d2812c..5d57771b 100644 --- a/src/TagLibSharp2/Xiph/FlacFile.cs +++ b/src/TagLibSharp2/Xiph/FlacFile.cs @@ -77,7 +77,8 @@ internal void RememberSource (string path, IFileSystem? fileSystem) } /// - /// Gets the size of the metadata section in bytes (magic + all metadata blocks). + /// Gets the size of the metadata section in bytes (magic + all metadata blocks) of the file the object describes: + /// the one it read or, after a save over its source, the one that save wrote. /// public int MetadataSize { get; private set; } @@ -422,18 +423,16 @@ public static async Task ReadFromFileAsync ( /// The file data. /// A result indicating success or failure. public static FlacFileReadResult Read (ReadOnlySpan data) => - Recorded (Parse (data), data.Length); - - // The file a read made, recording the length of the file it read. - static FlacFileReadResult Recorded (FlacFileReadResult result, long length) - { - result.File?.Source.Record (length); - return result; - } + SourceLength.Recorded (Parse (data), data.Length); // The parse of Read without the length it records: a stream reader parses part of the stream and records the // stream's length. - static FlacFileReadResult Parse (ReadOnlySpan data) + /// The file's bytes from its start, at least through its metadata. + /// + /// The first bytes after when it ends where the metadata ends but the file does not, as a + /// stream walk that buffered only the metadata finds them; empty at the end of the file. + /// + static FlacFileReadResult Parse (ReadOnlySpan data, ReadOnlySpan after = default) { if (data.Length < MagicSize) return FlacFileReadResult.Failure ("Invalid FLAC file: data too short for header"); @@ -480,43 +479,61 @@ static FlacFileReadResult Parse (ReadOnlySpan data) if (!headerResult.IsSuccess) break; - offset += FlacMetadataBlockHeader.HeaderSize; - - if (offset + headerResult.Header.DataLength > data.Length) + // A block that runs past the end of the data is not read, and the walk stops at its header: a save copies + // that header and every byte after it as they were, where it dropped the header's 4 bytes (#204). + if (offset + FlacMetadataBlockHeader.HeaderSize + headerResult.Header.DataLength > data.Length) break; + offset += FlacMetadataBlockHeader.HeaderSize; + var blockData = data.Slice (offset, headerResult.Header.DataLength); offset += headerResult.Header.DataLength; lastBlock = headerResult.Header.IsLast; switch (headerResult.Header.BlockType) { + case FlacBlockType.StreamInfo: + // Only the first STREAMINFO is the stream's (RFC 9639 §8.2); a save writes that one, so a second is + // a block it would not write back. + file._blockNotWritten = true; + break; + case FlacBlockType.VorbisComment: var commentResult = VorbisComment.Read (blockData); + file.NoteBlock (commentResult.IsSuccess, commentResult.BytesConsumed, blockData.Length, file.VorbisComment is not null); if (commentResult.IsSuccess) file.VorbisComment = commentResult.Tag; break; case FlacBlockType.Picture: var pictureResult = FlacPicture.Read (blockData); + file.NoteBlock (pictureResult.IsSuccess, pictureResult.BytesConsumed, blockData.Length, duplicate: false); if (pictureResult.IsSuccess) file._pictures.Add (pictureResult.Picture!); break; case FlacBlockType.CueSheet: var cueSheetResult = FlacCueSheet.Read (blockData); + file.NoteBlock (cueSheetResult.IsSuccess, cueSheetResult.BytesConsumed, blockData.Length, file.CueSheet is not null); if (cueSheetResult.IsSuccess) file.CueSheet = cueSheetResult.CueSheet; break; - case FlacBlockType.SeekTable: - case FlacBlockType.Application: - // Preserve these blocks to write back during save + case FlacBlockType.Padding: + // PADDING is not kept: a save writes fresh padding. Its bytes are zeros (RFC 9639 §8.3), but they + // carry no data, so stray bytes in it are no loss. A length grown past the block is: it took in the + // next block's header or the first bytes of the audio, which the save would drop. So padding that + // holds a byte that is not zero must end where a block header, a frame or the end of the file + // begins. + if (!AllZero (blockData) && !EndsWhereBlockEnds (data, offset, lastBlock, after)) + file._blockNotWritten = true; + break; + + default: + // SEEKTABLE, APPLICATION and the reserved types (7 to 126, RFC 9639 §8.1) are written back as they are. file._preservedBlocks.Add (new FlacPreservedBlock ( headerResult.Header.BlockType, new BinaryData (blockData))); break; - - // PADDING is not preserved - we generate fresh padding on save } } @@ -524,6 +541,29 @@ static FlacFileReadResult Parse (ReadOnlySpan data) return FlacFileReadResult.Success (file, offset); } + /// + /// Whether the read found a metadata block whose bytes a save would not write back (#204). A save writes the first + /// STREAMINFO, SEEKTABLE, APPLICATION and the reserved types as they are, and the comment, pictures and cue sheet + /// from what it parsed of them, then copies every byte after the last block it read. A block is lost when its + /// declared length runs past what it holds (a VORBIS_COMMENT grown into the audio took in the audio's first bytes, + /// past its last comment), when it does not parse, when it is a second STREAMINFO, comment or cue sheet, or when it + /// is padding that holds a byte that is not zero and does not end where a block header, a frame or the end of the file + /// begins (its length grew into what follows it). Nothing else is: stray bytes in padding, a block that runs past the + /// end of the file, or bytes after the last block that do not start with a frame. + /// + bool _blockNotWritten; + + void NoteBlock (bool parsed, int consumed, int length, bool duplicate) + { + if (duplicate || (length > 0 && (!parsed || consumed != length))) + _blockNotWritten = true; + } + + FileWriteResult? RefuseLostBlocks () => + _blockNotWritten ? FileWriteResult.Failure (BlockNotWrittenError) : null; + + const string BlockNotWrittenError = "Cannot save a FLAC file with a metadata block whose bytes the save would not write back."; + /// /// Reads FLAC metadata from a stream and stops at the last metadata block. /// Audio frames after that block are not read. @@ -555,7 +595,7 @@ internal static FlacFileReadResult Read (Stream stream, MediaReadOptions options break; } - return Recorded (Parse (metadata.ToArray ()), stream.Length); + return SourceLength.Recorded (Parse (metadata.ToArray (), PeekAfter (stream, metadata.Length)), stream.Length); } /// @@ -572,6 +612,7 @@ static FlacFileReadResult ReadSkippingPictures (Stream stream) var removedAfter = new List<(long End, long Removed)> (); long removed = 0; var last = false; + var pictureNotWhole = false; while (!last && stream.Position < stream.Length) { var headerBytes = StreamBytes.ReadAtMost (stream, FlacMetadataBlockHeader.HeaderSize); if (!TryBeginBlock (stream, headerBytes, out var declared, out var count, out var isLast, out var blockType)) @@ -580,7 +621,12 @@ static FlacFileReadResult ReadSkippingPictures (Stream stream) var whole = count == declared; byte[] body; if (blockType == FlacBlockType.Picture) { - PictureSkip.Discard (stream, count); + // The picture's data is not read, but its fields before the data are, to tell a block that holds more + // than the picture (#204) as a full read does. + if (whole && !PictureFillsBlock (stream, count)) + pictureNotWhole = true; + else if (!whole) + PictureSkip.Discard (stream, count); body = []; } else if (blockType == FlacBlockType.VorbisComment) { body = VorbisComment.CopyWithoutPictures (stream, count); @@ -597,7 +643,7 @@ static FlacFileReadResult ReadSkippingPictures (Stream stream) last = isLast; } - var parsed = Recorded (Parse (metadata.ToArray ()), stream.Length); + var parsed = Parse (metadata.ToArray (), PeekAfter (stream, metadata.Length + removed)); if (parsed.IsSuccess && parsed.File is not null) { var before = 0L; foreach (var (end, total) in removedAfter) { @@ -606,12 +652,98 @@ static FlacFileReadResult ReadSkippingPictures (Stream stream) } parsed.File.MetadataSize += (int)before; + if (pictureNotWhole) + parsed.File._blockNotWritten = true; parsed.File.MarkPicturesSkipped (); } return parsed; } + /// + /// Reads the fields of the PICTURE block of bytes at the stream position that come before + /// its data (type, MIME type, description, dimensions, data length: RFC 9639 §8.8), skips the rest, and says whether + /// those fields and the data fill the block exactly, as would find on the bytes. + /// + static bool PictureFillsBlock (Stream stream, int count) + { + var start = stream.Position; + var fills = false; + var head = StreamBytes.ReadAtMost (stream, (int)Math.Min (8, count)); + if (head.Length == 8) { + long consumed = 8 + BinaryPrimitives.ReadUInt32BigEndian (head.AsSpan (4)); + if (consumed + 4 <= count) { + stream.Position = start + consumed; + var description = StreamBytes.ReadAtMost (stream, 4); + consumed += 4 + BinaryPrimitives.ReadUInt32BigEndian (description) + 16; + if (consumed + 4 <= count) { + stream.Position = start + consumed; + var data = StreamBytes.ReadAtMost (stream, 4); + fills = consumed + 4 + BinaryPrimitives.ReadUInt32BigEndian (data) == count; + } + } + } + + stream.Position = start; + PictureSkip.Discard (stream, count); + return fills; + } + + + /// + /// Whether the bytes at , after a block, are what follows a block: the end of the file, the + /// header of a block that fits in (type 127 is not one, RFC 9639 §8.1) when the block was + /// not the last, or a frame's sync code (RFC 9639 §9.1: 0xFFF8 or 0xFFF9) when it was. + /// + static bool EndsWhereBlockEnds (ReadOnlySpan data, int offset, bool last, ReadOnlySpan after) + { + var next = offset < data.Length ? data.Slice (offset) : after; + if (next.IsEmpty) + return true; + if (last) + return next.Length >= 2 && next[0] == 0xFF && (next[1] & 0xFE) == 0xF8; + if (next.Length < FlacMetadataBlockHeader.HeaderSize || (next[0] & 0x7F) == 127) + return false; + + var header = FlacMetadataBlockHeader.Read (next.Slice (0, FlacMetadataBlockHeader.HeaderSize)); + return header.IsSuccess && FlacMetadataBlockHeader.HeaderSize + header.Header.DataLength <= next.Length; + } + + /// + /// The first bytes at , where the metadata a stream walk buffered ends in the source (fewer at + /// the end of the stream), with the stream left where it was: what a padding block's end is checked against + /// (). A header the walk could not read whole is not in the buffer, so it is read + /// here as a read of the bytes finds it. + /// + static byte[] PeekAfter (Stream stream, long at) + { + var position = stream.Position; + stream.Position = at; + var after = StreamBytes.ReadAtMost (stream, FlacMetadataBlockHeader.HeaderSize); + stream.Position = position; + return after; + } + + static async Task PeekAfterAsync (Stream stream, long at, CancellationToken cancellationToken) + { + var position = stream.Position; + stream.Position = at; + var after = await StreamBytes.ReadAtMostAsync (stream, FlacMetadataBlockHeader.HeaderSize, cancellationToken) + .ConfigureAwait (false); + stream.Position = position; + return after; + } + + static bool AllZero (ReadOnlySpan data) + { + foreach (var value in data) { + if (value != 0) + return false; + } + + return true; + } + static byte[] WithLength (byte[] header, int length) { var patched = (byte[])header.Clone (); @@ -649,7 +781,8 @@ internal static async Task ReadAsync (Stream stream, MediaRe break; } - return Recorded (Parse (metadata.ToArray ()), stream.Length); + var after = await PeekAfterAsync (stream, metadata.Length, cancellationToken).ConfigureAwait (false); + return SourceLength.Recorded (Parse (metadata.ToArray (), after), stream.Length); } static bool TryBeginBlock ( @@ -741,9 +874,9 @@ VorbisComment EnsureVorbisComment () /// Saves the file to the specified path using atomic write. /// /// The target file path. - /// The bytes of the file this object was read from; the payload is taken from them at the - /// offsets the read found. Bytes of any other length, a file it has saved since among them, fail with a result, and - /// nothing is written. + /// The bytes of the file this object was read from or, after a save over its source, of the + /// file that save wrote; the payload is taken from them at the offsets of that file. Bytes of any other length, a + /// file it saved elsewhere among them, fail with a result, and nothing is written. /// Optional file system abstraction for testing. /// A result indicating success or failure. public FileWriteResult SaveToFile (string path, ReadOnlySpan originalData, IFileSystem? fileSystem = null) @@ -755,21 +888,43 @@ public FileWriteResult SaveToFile (string path, ReadOnlySpan originalData, if (Source.Refuse ("FLAC", originalData.Length) is { } mismatch) return mismatch; + if (RefuseLostBlocks () is { } lost) + return lost; + var rendered = Render (originalData); if (rendered.IsEmpty) return FileWriteResult.Failure ("Failed to render FLAC file"); fileSystem ??= _sourceFileSystem; - return AtomicFileWriter.Write (path, rendered.Span, fileSystem); + return Adopt (AtomicFileWriter.Write (path, rendered.Span, fileSystem), MetadataOf (rendered, originalData.Length), rendered.Length, fileSystem); + } + + // The metadata a render of a file of sourceLength bytes wrote in front of its audio. + ReadOnlyMemory MetadataOf (BinaryData rendered, int sourceLength) => + rendered.Memory[..(rendered.Length - (sourceLength - MetadataSize))]; + + // A save that rewrote the source leaves the object describing the file it wrote (#179): its audio starts where the + // metadata written ends, and a save from those bytes, by span or by path, takes the audio from there. + FileWriteResult Adopt (FileWriteResult result, ReadOnlyMemory metadata, long length, IFileSystem? fileSystem) + { + if (result.IsSuccess && SavedOverSource.Holds (SourcePath, fileSystem, length, new WrittenBytes (0, metadata))) { + MetadataSize = metadata.Length; + Source.Rewrote (length); + } + + return result; } + async Task Adopt (Task save, ReadOnlyMemory metadata, long length, IFileSystem? fileSystem) => + Adopt (await save.ConfigureAwait (false), metadata, length, fileSystem); + /// /// Asynchronously saves the file to the specified path using atomic write. /// /// The target file path. - /// The bytes of the file this object was read from; the payload is taken from them at the - /// offsets the read found. Bytes of any other length, a file it has saved since among them, fail with a result, and - /// nothing is written. + /// The bytes of the file this object was read from or, after a save over its source, of the + /// file that save wrote; the payload is taken from them at the offsets of that file. Bytes of any other length, a + /// file it saved elsewhere among them, fail with a result, and nothing is written. /// Optional file system abstraction for testing. /// A token to cancel the operation. /// A task containing a result indicating success or failure. @@ -786,12 +941,15 @@ public Task SaveToFileAsync ( if (Source.Refuse ("FLAC", originalData.Length) is { } mismatch) return Task.FromResult (mismatch); + if (RefuseLostBlocks () is { } lost) + return Task.FromResult (lost); + var rendered = Render (originalData.Span); if (rendered.IsEmpty) return Task.FromResult (FileWriteResult.Failure ("Failed to render FLAC file")); fileSystem ??= _sourceFileSystem; - return AtomicFileWriter.WriteAsync (path, rendered.Memory, fileSystem, cancellationToken); + return Adopt (AtomicFileWriter.WriteAsync (path, rendered.Memory, fileSystem, cancellationToken), MetadataOf (rendered, originalData.Length), rendered.Length, fileSystem); } /// @@ -874,10 +1032,15 @@ FileWriteResult SaveFromSource (string destinationPath, IFileSystem? fileSystem, try { if (!PathSave.TryOpen (SourcePath!, fileSystem, out source, out var error)) return error; + if (Source.Refuse ("FLAC", source!.Length, "the source file") is { } changed) + return changed; if (source!.Length < MetadataSize) return FileWriteResult.Failure ("Failed to render FLAC file"); + if (RefuseLostBlocks () is { } lost) + return lost; + var metadata = RenderWithAudio (ReadOnlySpan.Empty); if (metadata.IsEmpty) return FileWriteResult.Failure ("Failed to render FLAC file"); @@ -889,7 +1052,7 @@ FileWriteResult SaveFromSource (string destinationPath, IFileSystem? fileSystem, chunk = StreamCopy.Rent (); var copyBuffer = chunk; var opened = source; - var written = PathSave.Replace (destinationPath, opened, output => { + var saved = PathSave.Replace (destinationPath, opened, output => { StreamCopy.Write (output, metadata.Span, copyBuffer); if (audioLength <= 0) return; @@ -900,7 +1063,7 @@ FileWriteResult SaveFromSource (string destinationPath, IFileSystem? fileSystem, StreamCopy.Copy (opened.Stream, output, audioLength, copyBuffer); }); source = null; - return written; + return Adopt (saved, metadata.Memory, metadata.Length + Math.Max (0, audioLength), fileSystem); } finally { source?.Dispose (); if (chunk is not null) @@ -908,6 +1071,7 @@ FileWriteResult SaveFromSource (string destinationPath, IFileSystem? fileSystem, } } + /// /// Saves the file back to its source path. /// @@ -943,6 +1107,9 @@ public BinaryData Render (ReadOnlySpan originalData) if (originalData.Length < MetadataSize) return BinaryData.Empty; + if (RefuseLostBlocks () is not null) + return BinaryData.Empty; + return RenderWithAudio (originalData.Slice (MetadataSize)); } @@ -1093,13 +1260,16 @@ public void Dispose () /// /// Represents the result of reading a from binary data. /// -public readonly struct FlacFileReadResult : IEquatable +public readonly struct FlacFileReadResult : IEquatable, ISourceRecorder { /// /// Gets the parsed file, or null if parsing failed. /// public FlacFile? File { get; } + /// + SourceLength? ISourceRecorder.Source => File?.Source; + /// /// Gets a value indicating whether parsing was successful. /// diff --git a/tests/TagLibSharp2.Tests/Aac/AacSaveStreamsAudioTests.cs b/tests/TagLibSharp2.Tests/Aac/AacSaveStreamsAudioTests.cs index 622c2dc8..85a51056 100644 --- a/tests/TagLibSharp2.Tests/Aac/AacSaveStreamsAudioTests.cs +++ b/tests/TagLibSharp2.Tests/Aac/AacSaveStreamsAudioTests.cs @@ -77,7 +77,8 @@ static void AssertSaved ( long allocated) { Assert.IsTrue (save.IsSuccess, save.Error); - Assert.AreEqual (1, fs.SourceLengthGets, "source length reads"); + // Open records the length once. The save then reads the source back to see whether it wrote over it (#179). + Assert.AreEqual (2, fs.SourceLengthGets, "source length reads"); Assert.IsTrue ( allocated < original.Length / 2, $"save allocated {allocated} bytes for a {original.Length} byte file"); diff --git a/tests/TagLibSharp2.Tests/Aiff/AiffChunkTests.cs b/tests/TagLibSharp2.Tests/Aiff/AiffChunkTests.cs index 28927b6e..b2c5f7c7 100644 --- a/tests/TagLibSharp2.Tests/Aiff/AiffChunkTests.cs +++ b/tests/TagLibSharp2.Tests/Aiff/AiffChunkTests.cs @@ -130,7 +130,7 @@ public void TotalSize_OddSize_IncludesPadding () } [TestMethod] - public void TryParse_SizeExceedsData_ReturnsFalse () + public void TryParse_SizeExceedsData_KeepsTheBytesPresent () { byte[] data = [ 0x43, 0x4F, 0x4D, 0x4D, // "COMM" @@ -138,9 +138,10 @@ public void TryParse_SizeExceedsData_ReturnsFalse () 0x01, 0x02 // Only 2 bytes ]; - var result = AiffChunk.TryParse (new BinaryData (data), 0, out _); + Assert.IsTrue (AiffChunk.TryParse (new BinaryData (data), 0, out var chunk)); - Assert.IsFalse (result); + Assert.AreEqual (256u, chunk!.Size); + Assert.AreEqual (2, chunk.Data.Length); } [TestMethod] @@ -149,34 +150,34 @@ public void HeaderSize_IsEight () Assert.AreEqual (8, AiffChunk.HeaderSize); } + // A size past the bytes present keeps the size and the bytes present, as the stream walk keeps them (#197). [TestMethod] - public void TryParse_SizeExceedsIntMax_ReturnsFalse () + public void TryParse_SizeExceedsIntMax_KeepsTheBytesPresent () { - // Size claims to be 0x80000000 (2GB+) - would overflow int byte[] data = [ 0x43, 0x4F, 0x4D, 0x4D, // "COMM" 0x80, 0x00, 0x00, 0x00, // Size = 2147483648 (> int.MaxValue) 0x01, 0x02 // Minimal data ]; - var result = AiffChunk.TryParse (new BinaryData (data), 0, out _); + Assert.IsTrue (AiffChunk.TryParse (new BinaryData (data), 0, out var chunk)); - Assert.IsFalse (result); + Assert.AreEqual (0x8000_0000u, chunk!.Size); + CollectionAssert.AreEqual (new byte[] { 0x01, 0x02 }, chunk.Data.ToArray ()); } [TestMethod] - public void TryParse_SizeAtIntMaxBoundary_ReturnsFalse () + public void TryParse_SizeAtIntMaxBoundary_KeepsTheBytesPresent () { - // Size just over int.MaxValue byte[] data = [ 0x43, 0x4F, 0x4D, 0x4D, // "COMM" 0x7F, 0xFF, 0xFF, 0xFF, // Size = 2147483647 (int.MaxValue) 0x01, 0x02 // Minimal data (not enough) ]; - // Should return false because we don't have enough data - var result = AiffChunk.TryParse (new BinaryData (data), 0, out _); + Assert.IsTrue (AiffChunk.TryParse (new BinaryData (data), 0, out var chunk)); - Assert.IsFalse (result); + Assert.AreEqual ((uint)int.MaxValue, chunk!.Size); + Assert.AreEqual (2, chunk.Data.Length); } } diff --git a/tests/TagLibSharp2.Tests/Aiff/AiffOversizedChunkSaveTests.cs b/tests/TagLibSharp2.Tests/Aiff/AiffOversizedChunkSaveTests.cs new file mode 100644 index 00000000..de1379a9 --- /dev/null +++ b/tests/TagLibSharp2.Tests/Aiff/AiffOversizedChunkSaveTests.cs @@ -0,0 +1,82 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Buffers.Binary; +using TagLibSharp2.Aiff; +using TagLibSharp2.Core; +using TagLibSharp2.Tests.Core; + +namespace TagLibSharp2.Tests.Aiff; + +/// +/// The review's aif-ssnd-ffff.aif (an SSND size of 0xFFFFFFFF, the placeholder a streamed writer leaves) and +/// aif-comm-19.aif (a COMM size of 19, so COMM takes a byte of SSND's header): a save threw +/// ("Cannot render an AIFF file larger than supported memory."), because it +/// sized the file by each chunk's declared size. It now writes each chunk with the bytes it holds, as a WAV save does +/// (#197): the save succeeds on every read and save entry point, and the file it writes reads as the source did. +/// +[TestClass] +[TestCategory ("Unit")] +[TestCategory ("Aiff")] +public sealed class AiffOversizedChunkSaveTests +{ + static byte[] Placeholder () + { + var aiff = TestBuilders.Aiff.CreateMinimal (soundBytes: 64); + BinaryPrimitives.WriteUInt32BigEndian (aiff.AsSpan (aiff.AsSpan ().IndexOf ("SSND"u8) + 4), uint.MaxValue); + return aiff; + } + + static byte[] Comm19 () + { + var aiff = TestBuilders.Aiff.CreateMinimal (soundBytes: 64); + BinaryPrimitives.WriteUInt32BigEndian (aiff.AsSpan (aiff.AsSpan ().IndexOf ("COMM"u8) + 4), 19); + return aiff; + } + + static readonly string[] Files = ["ssnd-ffff", "comm-19"]; + + static readonly string[] Reads = ["format-path", "path", "data"]; + + static readonly string[] Overloads = ["sync", "async", "source"]; + + public static IEnumerable Rows () => + from file in Files + from read in Reads + from overload in Overloads + select new object[] { file, read, overload }; + + [TestMethod] + [DynamicData (nameof (Rows))] + public async Task Save_WritesTheBytesPresent (string file, string read, string overload) + { + var original = file == "ssnd-ffff" ? Placeholder () : Comm19 (); + var files = new MockFileSystem (); + files.AddFile ("/in.aif", original); + var aiff = read switch { + "format-path" => AiffFile.ReadFromFile ("/in.aif", files).File!, + "path" => (AiffFile)MediaFile.Read ("/in.aif", files).File!, + _ => (AiffFile)MediaFile.ReadFromData (original, "/in.aif").File!, + }; + var before = Describe (aiff); + + var saved = overload switch { + "sync" => aiff.SaveToFile ("/out.aif", files), + "async" => await aiff.SaveToFileAsync ("/out.aif", files), + _ => aiff.SaveToFile (read == "data" ? "/out.aif" : "/in.aif", files), + }; + + Assert.IsTrue (saved.IsSuccess, saved.Error); + var written = files.ReadAllBytes (files.FileExists ("/out.aif") ? "/out.aif" : "/in.aif"); + Assert.AreEqual ((uint)(written.Length - 8), BinaryPrimitives.ReadUInt32BigEndian (written.AsSpan (4)), "the FORM size is the file's"); + for (var at = 12; at < written.Length;) { + var size = BinaryPrimitives.ReadUInt32BigEndian (written.AsSpan (at + 4)); + Assert.IsLessThanOrEqualTo ((long)written.Length, at + 8L + size + (size & 1), $"the chunk at {at} is written with the size of its bytes"); + at += 8 + (int)size + (int)(size & 1); + } + Assert.AreEqual (before, Describe (AiffFile.Read (written).File!)); + } + + static string Describe (AiffFile file) => + $"{file.Properties?.Duration}/{file.Properties?.SampleRate}/{file.Properties?.Channels}"; +} diff --git a/tests/TagLibSharp2.Tests/Aiff/AiffSaveRefusalTests.cs b/tests/TagLibSharp2.Tests/Aiff/AiffSaveRefusalTests.cs new file mode 100644 index 00000000..0d6fa486 --- /dev/null +++ b/tests/TagLibSharp2.Tests/Aiff/AiffSaveRefusalTests.cs @@ -0,0 +1,94 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Buffers.Binary; +using TagLibSharp2.Aiff; +using TagLibSharp2.Core; +using TagLibSharp2.Tests.Core; + +namespace TagLibSharp2.Tests.Aiff; + +/// +/// Review 4's N2: an AIFF file with no COMM chunk, such as aif-form-0.aif (a FORM size of 0, so the form ends before +/// its chunks), read as one with no audio properties, and a save reported success and wrote the 12 bytes of the FORM +/// header. Every AIFF file needs a COMM chunk, so the save is refused on every read and save entry point, and nothing +/// is written. +/// +[TestClass] +[TestCategory ("Unit")] +[TestCategory ("Aiff")] +public sealed class AiffSaveRefusalTests +{ + const string Source = "/in.aif"; + const string Target = "/out.aif"; + + static readonly string[] Files = ["form-0", "form-4", "form-12", "no-comm"]; + + static readonly string[] Reads = ["path", "async-path", "data", "stream", "format-path"]; + + static readonly string[] Saves = ["sync-path", "async-path", "sync-source", "async-in-place"]; + + public static IEnumerable Rows () => + from file in Files + from read in Reads + from save in Saves + select new object[] { file, read, save }; + + [TestMethod] + [DynamicData (nameof (Rows))] + public async Task NoComm_SaveIsRefusedAndWritesNothing (string file, string read, string save) + { + var bytes = Build (file); + var files = new MockFileSystem (); + files.AddFile (Source, bytes); + var aiff = Open (read, bytes, files); + Assert.IsNull (((IMediaFile)aiff).AudioProperties, "the read finds no COMM"); + + var result = save switch { + "sync-path" => aiff.SaveToFile (Target, files), + "async-path" => await aiff.SaveToFileAsync (Target, files), + "sync-source" => aiff.SaveToFile (Source, files), + _ => await aiff.SaveToFileAsync (files), + }; + + Assert.IsFalse (result.IsSuccess); + if (save != "async-in-place" || read is "path" or "async-path" or "format-path") + Assert.AreEqual ("Cannot save an AIFF file that has no valid COMM chunk.", result.Error); + Assert.IsFalse (files.FileExists (Target)); + CollectionAssert.AreEqual (bytes, files.ReadAllBytes (Source)); + } + + static AiffFile Open (string read, byte[] bytes, MockFileSystem files) + { + var result = read switch { + "format-path" => AiffFile.ReadFromFile (Source, files), + "stream" => AiffFile.Read (new MemoryStream (bytes, writable: false), null, null), + "data" => AiffFile.Read (bytes), + "async-path" => AiffFile.ReadFromFileAsync (Source, files).GetAwaiter ().GetResult (), + _ => AsAiff (MediaFile.Read (Source, files)), + }; + Assert.IsTrue (result.IsSuccess, read + ": " + result.Error); + return result.File!; + } + + static AiffFileReadResult AsAiff (MediaFileResult result) => + result.IsSuccess ? AiffFileReadResult.Success ((AiffFile)result.File!) : AiffFileReadResult.Failure (result.Error!); + + // The review's aif-form-0.aif and its siblings: a whole file whose FORM size ends the form before its chunks; and a + // FORM that holds an SSND but no COMM. + static byte[] Build (string file) + { + var aiff = TestBuilders.Aiff.CreateMinimal (soundBytes: 64); + switch (file) { + case "no-comm": { + var comm = aiff.AsSpan ().IndexOf ("COMM"u8); + byte[] without = [.. aiff.AsSpan (0, comm), .. aiff.AsSpan (comm + 8 + 18)]; + BinaryPrimitives.WriteUInt32BigEndian (without.AsSpan (4), (uint)(without.Length - 8)); + return without; + } + default: + BinaryPrimitives.WriteUInt32BigEndian (aiff.AsSpan (4), uint.Parse (file[5..], System.Globalization.CultureInfo.InvariantCulture)); + return aiff; + } + } +} diff --git a/tests/TagLibSharp2.Tests/Aiff/AiffSaveStreamsAudioTests.cs b/tests/TagLibSharp2.Tests/Aiff/AiffSaveStreamsAudioTests.cs index 8b678f3e..56bc56e4 100644 --- a/tests/TagLibSharp2.Tests/Aiff/AiffSaveStreamsAudioTests.cs +++ b/tests/TagLibSharp2.Tests/Aiff/AiffSaveStreamsAudioTests.cs @@ -157,7 +157,8 @@ static void AssertSaved ( long allocated) { Assert.IsTrue (save.IsSuccess, save.Error); - Assert.AreEqual (1, fs.SourceLengthGets, "source length reads"); + // Open records the length once. The save then reads the source back to see whether it wrote over it (#212). + Assert.AreEqual (2, fs.SourceLengthGets, "source length reads"); Assert.IsTrue ( allocated < original.Length / 2, $"save allocated {allocated} bytes for a {original.Length} byte file"); diff --git a/tests/TagLibSharp2.Tests/Aiff/AiffWalkAgreementTests.cs b/tests/TagLibSharp2.Tests/Aiff/AiffWalkAgreementTests.cs new file mode 100644 index 00000000..f09fc229 --- /dev/null +++ b/tests/TagLibSharp2.Tests/Aiff/AiffWalkAgreementTests.cs @@ -0,0 +1,132 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Buffers.Binary; +using TagLibSharp2.Aiff; +using TagLibSharp2.Core; +using TagLibSharp2.Tests.Core; +using TagLibSharp2.Tests.Kit; + +namespace TagLibSharp2.Tests.Aiff; + +/// +/// The AIFF twin of (#197): a read from memory and a read from a stream walk +/// the same IFF chunks by one rule, a chunk's bytes present up to its size and never past the end of the FORM. Every +/// chunk kind (COMM, SSND, NAME, one no reader knows), last in the form or not, is given a size below its bytes, past +/// them, past or 0xFFFFFFFF, with and without bytes after the form, in a FORM of its true +/// size, the placeholder, 0, 4, 12 (the review's aif-form-0.aif and its siblings), half its size or larger than the +/// file: the ten entry points must read the same file. +/// +[TestClass] +[TestCategory ("Unit")] +[TestCategory ("Aiff")] +public sealed class AiffWalkAgreementTests +{ + static readonly string[] Chunks = ["COMM", "SSND", "NAME", "junk"]; + + static readonly string[] Sizes = ["below", "+1", "+1000", "0x7FFFFFFF", "0x80000000", "0xFFFFFFFF"]; + + static readonly string[] Forms = ["exact", "placeholder", "0", "4", "12", "half", "larger"]; + + static readonly bool[] Booleans = [false, true]; + + public static IEnumerable Rows () => + from chunk in Chunks + from last in Booleans + from size in Sizes + from trailing in Booleans + from form in Forms + select new object[] { chunk, last, size, trailing, form }; + + [TestMethod] + [DynamicData (nameof (Rows))] + public void ChunkAndFormSizes_ReadTheSameOnEveryEntryPoint (string chunk, bool last, string size, bool trailing, string form) + { + var bytes = Aiff (chunk, last, size, trailing, form); + + var reads = ReadEverywhere (bytes); + + EntryAgreement.AssertAgree (reads, "read"); + } + + // The rule itself, not only agreement: a chunk past the FORM's end is not read (a FORM that ends after SSND leaves + // the NAME after it unread), and a FORM larger than the file reads every chunk. + [TestMethod] + public void FormEnd_BoundsTheChunks () + { + var nameOutside = Aiff ("NAME", last: true, "+1", trailing: false, "exact"); + BinaryPrimitives.WriteUInt32BigEndian (nameOutside.AsSpan (4), (uint)(nameOutside.Length - 8 - 8 - 6)); + var larger = Aiff ("NAME", last: true, "+1", trailing: false, "larger"); + + foreach (var read in ReadEverywhere (nameOutside)) + Assert.EndsWith (": 10000000/8000/1/", read); + foreach (var read in ReadEverywhere (larger)) + Assert.EndsWith ("/8000/1/Title", read); + } + + static string[] ReadEverywhere (byte[] bytes) => + EntryAgreement.ReadEverywhere (bytes, "/clip.aif", data => AiffFile.Read (data).File, (path, files) => AiffFile.ReadFromFile (path, files).File); + + // COMM (mono, 8,000 frames, 8 bits, 8,000 Hz: one second), SSND (offset and block size, then 8,000 bytes), NAME + // ("Title", odd, so padded) and a chunk no reader knows. The chunk under test goes last or stays in the middle; + // then its size and the FORM's size are set. + internal static byte[] Aiff (string target, bool last, string size, bool trailing, string form) + { + var order = new List { "COMM", "SSND", "NAME", "junk" }; + order.Remove (target); + if (last) + order.Add (target); + else + order.Insert (1, target); + + using var body = new MemoryStream (); + body.Write ("AIFF"u8); + var sizeAt = -1; + var trueSize = 0; + foreach (var id in order) { + var payload = Payload (id); + if (id == target) { + sizeAt = (int)body.Position + 4; + trueSize = payload.Length; + } + + var header = new byte[8]; + System.Text.Encoding.ASCII.GetBytes (id).CopyTo (header, 0); + BinaryPrimitives.WriteUInt32BigEndian (header.AsSpan (4), (uint)payload.Length); + body.Write (header); + body.Write (payload); + if ((payload.Length & 1) != 0) + body.WriteByte (0); + } + + var formBytes = body.ToArray (); + var declared = size switch { + "below" => (uint)(trueSize - 1), + "+1" => (uint)(trueSize + 1), + "+1000" => (uint)(trueSize + 1000), + _ => Convert.ToUInt32 (size, 16), + }; + BinaryPrimitives.WriteUInt32BigEndian (formBytes.AsSpan (sizeAt), declared); + + byte[] aiff = [.. "FORM"u8, .. new byte[4], .. formBytes, .. trailing ? Enumerable.Repeat ((byte)0x33, 128) : []]; + var formSize = form switch { + "placeholder" => uint.MaxValue, + "0" => 0u, + "4" => 4u, + "12" => 12u, + "half" => (uint)(formBytes.Length / 2), + "larger" => (uint)(formBytes.Length + 1000), + _ => (uint)formBytes.Length, + }; + BinaryPrimitives.WriteUInt32BigEndian (aiff.AsSpan (4), formSize); + return aiff; + } + + static byte[] Payload (string id) => id switch { + // channels, frames, bits, then 8,000 Hz as an 80-bit extended real: exponent 16383 + 12, mantissa 8000 / 2^12. + "COMM" => [0, 1, 0, 0, 0x1F, 0x40, 0, 8, 0x40, 0x0B, 0xFA, 0, 0, 0, 0, 0, 0, 0], + "SSND" => [0, 0, 0, 0, 0, 0, 0, 0, .. Enumerable.Range (0, 8000).Select (i => (byte)(i * 7))], + "NAME" => [.. "Title"u8], + _ => [.. Enumerable.Repeat ((byte)0x5A, 10)], + }; +} diff --git a/tests/TagLibSharp2.Tests/Asf/AsfFilePropertiesTests.cs b/tests/TagLibSharp2.Tests/Asf/AsfFilePropertiesTests.cs index 67d0da4b..63fd4dec 100644 --- a/tests/TagLibSharp2.Tests/Asf/AsfFilePropertiesTests.cs +++ b/tests/TagLibSharp2.Tests/Asf/AsfFilePropertiesTests.cs @@ -89,6 +89,28 @@ public void Duration_ZeroPreroll_UsesFullDuration () Assert.AreEqual (TimeSpan.FromSeconds (10), result.Value.Duration); } + // A preroll at or past the play duration leaves nothing to play. Preroll is in ms and the play duration in 100 ns: + // a preroll of 1,844,674,407,370,956 ms is 2^64 + 8,384 ticks, which wrapped to 8,384 in 64-bit arithmetic and + // read as a duration of 51.42 s less 0.8 ms (#193). + // A play duration that is not a whole number of ms keeps what is left after a preroll of its whole ms: 0.5 ms here. + [TestMethod] + [DataRow (514_200_000UL, 51_420UL, 0L)] + [DataRow (514_200_000UL, 60_000UL, 0L)] + [DataRow (514_200_000UL, 1_844_674_407_370_956UL, 0L)] + [DataRow (514_200_000UL, ulong.MaxValue, 0L)] + [DataRow (514_200_000UL, 51_419UL, 10_000L)] + [DataRow (514_205_000UL, 51_420UL, 5_000L)] + [DataRow (514_205_000UL, 51_421UL, 0L)] + public void Duration_PrerollAtOrPastThePlayDuration (ulong playTicks, ulong prerollMs, long expectedTicks) + { + var data = CreateFilePropertiesData (durationNs: playTicks, prerollMs: prerollMs); + + var result = AsfFileProperties.Parse (data); + + Assert.IsTrue (result.IsSuccess); + Assert.AreEqual (TimeSpan.FromTicks (expectedTicks), result.Value.Duration); + } + [TestMethod] public void Parse_TruncatedInput_ReturnsFailure () { diff --git a/tests/TagLibSharp2.Tests/Asf/AsfHeaderObjectsSaveTests.cs b/tests/TagLibSharp2.Tests/Asf/AsfHeaderObjectsSaveTests.cs new file mode 100644 index 00000000..1cf7aee8 --- /dev/null +++ b/tests/TagLibSharp2.Tests/Asf/AsfHeaderObjectsSaveTests.cs @@ -0,0 +1,159 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Buffers.Binary; +using TagLibSharp2.Core; +using TagLibSharp2.Tests.Core; + +namespace TagLibSharp2.Tests.Asf; + +/// +/// #200: an ASF Header Object whose count is short of the objects it holds (review 5's base.wma with a count of 1 saved +/// 19,384 of its 19,744 bytes). The walk stopped at the count, so the read did not see the objects after it, and a save +/// dropped them. The header's objects are now the ones that fill its declared size, whatever the count says: every +/// entry point reads them all, and every save carries each of them across byte for byte, parsed or not. A header whose +/// objects do not fill it whole, because its size cuts the last object short or leaves bytes that are no object, would +/// lose bytes or write them twice, so the save fails and writes nothing. +/// +[TestClass] +[TestCategory ("Unit")] +public sealed class AsfHeaderObjectsSaveTests +{ + static readonly string[] Counts = ["count-0", "count-1", "count-past"]; + + static readonly string[] NotWhole = ["size-cuts", "size-junk"]; + + static readonly string[] Reads = ["stream", "path", "data", "async-path", "format-path"]; + + static readonly string[] Saves = ["sync-path", "async-path", "span-sync", "span-async", "sync-in-place", "async-in-place"]; + + public static IEnumerable ReadRows () => + from shape in Counts.Concat (NotWhole) + from read in Reads + select new object[] { shape, read }; + + [TestMethod] + [DynamicData (nameof (ReadRows))] + public void HeaderObjects_ReadAsTheirSizeSays (string shape, string read) + { + var expected = Describe (SpanSaveKit.Open (".wma", read, Build ("valid"), new MockFileSystem ())); + + var file = SpanSaveKit.Open (".wma", read, Build (shape), new MockFileSystem ()); + + Assert.AreEqual (expected, Describe (file), read); + } + + // The header size ends before the Content Description: the objects after it are not the header's, on every entry + // point, so none reads the title (a read of the bytes walked on past the header to the end of the file). + public static IEnumerable EndRows () => Reads.Select (read => new object[] { read }); + + [TestMethod] + [DynamicData (nameof (EndRows))] + public void HeaderSizeBeforeTheTitle_NoReadTakesTheTitle (string read) + { + var file = SpanSaveKit.Open (".wma", read, Build ("size-before-title"), new MockFileSystem ()); + + Assert.AreEqual (TimeSpan.FromSeconds (1), file.AudioProperties?.Duration, read); + Assert.IsTrue (string.IsNullOrEmpty (file.Tag?.Title), read + ": " + file.Tag?.Title); + } + + public static IEnumerable CountRows () => + from shape in Counts + from save in Saves + select new object[] { shape, save }; + + [TestMethod] + [DynamicData (nameof (CountRows))] + public async Task CountShortOrLong_SaveCarriesEveryObject (string shape, string save) + { + var bytes = Build (shape); + var (files, file, target) = Open (bytes, save); + file.Tag!.Title = "New"; + + var result = await Save (file, save, bytes, files); + + Assert.IsTrue (result.IsSuccess, result.Error); + var written = files.ReadAllBytes (target); + foreach (var kept in new[] { FileProperties, StreamProperties, Unknown }) + Assert.IsGreaterThanOrEqualTo (0, written.AsSpan ().IndexOf (kept), $"{shape} {save}: a header object was not carried across"); + var back = (IMediaFile)MediaFile.ReadFromData (written, "/back.wma").File!; + Assert.AreEqual ("New", back.Tag?.Title); + Assert.AreEqual (TimeSpan.FromSeconds (1), back.AudioProperties?.Duration); + } + + public static IEnumerable NotWholeRows () => + from shape in NotWhole + from save in Saves + select new object[] { shape, save }; + + [TestMethod] + [DynamicData (nameof (NotWholeRows))] + public async Task HeaderNotFilledWhole_SaveFailsAndWritesNothing (string shape, string save) + { + var bytes = Build (shape); + var (files, file, target) = Open (bytes, save); + file.Tag!.Title = "New"; + + var result = await Save (file, save, bytes, files); + + Assert.IsFalse (result.IsSuccess, $"{shape} {save}: the save dropped or doubled header bytes and reported success"); + Assert.AreEqual ("Cannot save an ASF file whose header objects do not fill its header.", result.Error); + CollectionAssert.AreEqual (bytes, files.ReadAllBytes ("/in.wma"), "the source changed"); + if (target != "/in.wma") + Assert.IsFalse (files.FileExists (target), "a failed save wrote"); + } + + static (MockFileSystem Files, IMediaFile File, string Target) Open (byte[] bytes, string save) + { + var files = new MockFileSystem (); + var read = save.StartsWith ("span", StringComparison.Ordinal) ? "data" : "path"; + var file = SpanSaveKit.Open (".wma", read, bytes, files); + return (files, file, save.EndsWith ("path", StringComparison.Ordinal) ? "/out.wma" : "/in.wma"); + } + + static Task Save (IMediaFile file, string save, byte[] bytes, MockFileSystem files) => save switch { + "sync-path" => SpanSaveKit.SavePath (file, "/out.wma", sync: true, files), + "async-path" => SpanSaveKit.SavePath (file, "/out.wma", sync: false, files), + "span-sync" => SpanSaveKit.SaveSpan (file, "/in.wma", bytes, sync: true, files), + "span-async" => SpanSaveKit.SaveSpan (file, "/in.wma", bytes, sync: false, files), + "sync-in-place" => SpanSaveKit.SavePath (file, null, sync: true, files), + _ => SpanSaveKit.SavePath (file, null, sync: false, files), + }; + + static string Describe (IMediaFile file) => + $"{file.AudioProperties?.Duration.Ticks}/{file.AudioProperties?.SampleRate}/{file.AudioProperties?.Channels}/{file.Tag?.Title}"; + + static readonly byte[] FileProperties = AsfTestBuilder.CreateFilePropertiesObject (1000, 128000); + + static readonly byte[] StreamProperties = AsfTestBuilder.CreateAudioStreamPropertiesObject (44100, 2, 16); + + // An object no reader parses: its own GUID, then 40 bytes. + static readonly byte[] Unknown = [.. Enumerable.Range (0, 16).Select (i => (byte)(0xA0 + i)), .. BitConverter.GetBytes (64UL), .. SpanSaveKit.Sound (40)]; + + // A WMA header of File Properties, Stream Properties, a Content Description with the title "Title" and an unknown + // object, then the Data Object. count-*: the header's count is 0, 1, or 9 past the four objects. size-cuts: the + // header size ends 10 bytes into the unknown object. size-junk: 10 bytes that are no object end the header. + // size-before-title: the header size ends after Stream Properties. + static byte[] Build (string shape) + { + var description = AsfTestBuilder.CreateContentDescriptionObject ("Title", null); + var header = AsfTestBuilder.CreateHeaderObject (FileProperties, StreamProperties, description, Unknown); + if (shape == "size-junk") { + header = [.. header, .. Enumerable.Repeat ((byte)0x55, 10)]; + BinaryPrimitives.WriteUInt64LittleEndian (header.AsSpan (16), (ulong)header.Length); + } + + var count = shape switch { + "count-0" => 0u, + "count-1" => 1u, + "count-past" => 13u, + _ => 4u, + }; + BinaryPrimitives.WriteUInt32LittleEndian (header.AsSpan (24), count); + if (shape == "size-cuts") + BinaryPrimitives.WriteUInt64LittleEndian (header.AsSpan (16), (ulong)(header.Length - Unknown.Length + 10)); + if (shape == "size-before-title") + BinaryPrimitives.WriteUInt64LittleEndian (header.AsSpan (16), (ulong)(30 + FileProperties.Length + StreamProperties.Length)); + return [.. header, .. AsfTestBuilder.CreateDataObject (0)]; + } +} diff --git a/tests/TagLibSharp2.Tests/Asf/AsfMalformedInputTests.cs b/tests/TagLibSharp2.Tests/Asf/AsfMalformedInputTests.cs index c7efd17f..93867501 100644 --- a/tests/TagLibSharp2.Tests/Asf/AsfMalformedInputTests.cs +++ b/tests/TagLibSharp2.Tests/Asf/AsfMalformedInputTests.cs @@ -245,4 +245,13 @@ public void ZeroChildCount_ReturnsEmptyTag () Assert.IsTrue (result.IsSuccess); Assert.IsTrue (result.File!.Tag.IsEmpty); } + + // A header child that is only its 24-byte header may end the data: the walk reads it (the twin of #189's 27-byte + // Ogg page). One byte less and it does not fit. + [TestMethod] + [DataRow (76L, true)] + [DataRow (77L, false)] + [DataRow (99L, false)] + public void HeaderWalk_ReadsAnObjectThatEndsTheData (long offset, bool more) => + Assert.AreEqual (more, AsfFile.MoreObjects (offset, 100)); } diff --git a/tests/TagLibSharp2.Tests/Core/BigSoundSaveTests.cs b/tests/TagLibSharp2.Tests/Core/BigSoundSaveTests.cs new file mode 100644 index 00000000..05f37631 --- /dev/null +++ b/tests/TagLibSharp2.Tests/Core/BigSoundSaveTests.cs @@ -0,0 +1,221 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Buffers.Binary; +using TagLibSharp2.Aiff; +using TagLibSharp2.Core; +using TagLibSharp2.Id3.Id3v2; +using TagLibSharp2.Riff; +using TagLibSharp2.Tests.Kit; + +namespace TagLibSharp2.Tests.Core; + +/// +/// Review 4's B1: an AIFF file whose sound does not fit in an int (big.aif, 2,281,701,444 bytes) was read with +/// that SSND left in the file but not recorded, so a save wrote it as an empty chunk and reported success; over the +/// source, the file was destroyed. A save of a sound chunk the read left in the file now copies it from the source, +/// whatever its size. The sweep covers every format whose stream read leaves the sound in the file: WAV, AIFF, DSF and +/// DSDIFF, each with a sound chunk of 0x88000000 bytes, read from a path, given a new title and saved to a path and over +/// the source, sync and async: each keeps the source's sound byte for byte after the same chunk header, in a file that +/// reads as the edited file did. WAV refused a save of sample data past what an array holds; its streamed save now +/// copies the data chunk too (#203). WAV and AIFF, whose container size is 32 bits, also save an odd sound chunk with +/// its pad and a chunk after it, and a container of 0xFFFFFFFE whole, and fail a save past 32 bits and write nothing. +/// The files are s: the sound is a run that costs no memory, and the saved run is checked as it +/// streams. +/// +[TestClass] +[TestCategory ("Unit")] +public sealed class BigSoundSaveTests +{ + const long Sound = 0x88000000; + + static readonly string[] Formats = [".wav", ".aif", ".dsf", ".dff"]; + + // The formats whose container size is 32 bits. + static readonly string[] Containers = [".wav", ".aif"]; + + // The reads that leave the sound in the file and keep the path to copy it from. A format's own ReadFromFile reads + // the whole file into memory and cannot open a file this size; a SkipPictures read refuses every save. + static readonly string[] Reads = ["path", "async-path"]; + + static readonly string[] Saves = ["sync-path", "async-path", "sync-source", "async-source"]; + + public static IEnumerable Rows () => + from format in Formats + from read in Reads + from save in Saves + select new object[] { format, read, save }; + + [TestMethod] + [DynamicData (nameof (Rows))] + public async Task SoundPastInt_IsCopiedFromTheSource (string format, string read, string save) + { + var files = new SparseFileSystem (); + var (source, target) = Paths (format, save); + var file = Big (format, Sound); + files.Add (source, file); + var media = Open (read, source, files); + Retitle (media, "New"); + var expected = EntryAgreement.Describe (media); + + var result = await SpanSaveKit.SavePath (media, target, save.StartsWith ("sync", StringComparison.Ordinal), files); + + Assert.IsTrue (result.IsSuccess, result.Error); + var written = files.Get (target); + CollectionAssert.AreEqual (file.Head[^12..], written.Head[^12..], "the sound chunk's header, then its sound"); + Assert.AreEqual (Sound, written.RunLength, "the source's sound, byte for byte"); + Assert.AreEqual (expected, EntryAgreement.Describe (Open ("path", target, files)), "the saved file"); + } + + public static IEnumerable ContainerRows () => + from format in Containers + from read in Reads + from save in Saves + select new object[] { format, read, save }; + + // Review 5's big-mid-odd.aif and its WAV twin: a sound chunk of an odd size, with its pad byte, and a chunk after it + // that a save keeps as it is (AIFF's APPL, an unknown WAV chunk; a new title goes into the ID3 tag). + [TestMethod] + [DynamicData (nameof (ContainerRows))] + public async Task OddSoundNotLast_IsCopiedFromTheSource (string format, string read, string save) + { + const long OddSound = Sound + 1; + var files = new SparseFileSystem (); + var (source, target) = Paths (format, save); + var file = Big (format, OddSound, true); + files.Add (source, file); + var media = Open (read, source, files); + Retitle (media, "New"); + var expected = EntryAgreement.Describe (media); + + var result = await SpanSaveKit.SavePath (media, target, save.StartsWith ("sync", StringComparison.Ordinal), files); + + Assert.IsTrue (result.IsSuccess, result.Error); + var written = files.Get (target); + CollectionAssert.AreEqual (file.Head[^12..], written.Head[^12..], "the sound chunk's header, then its sound"); + Assert.AreEqual (OddSound, written.RunLength, "the source's sound, byte for byte"); + Assert.AreEqual (0, written.Tail[0], "the pad byte"); + Assert.IsGreaterThanOrEqualTo (0, written.Tail.AsSpan ().IndexOf (file.Tail.AsSpan (1)), "the chunk after the sound"); + Assert.AreEqual (expected, EntryAgreement.Describe (Open ("path", target, files)), "the saved file"); + } + + public static IEnumerable ContainerOnlyRows () => Containers.Select (format => new object[] { format }); + + // Review 5's near4g.aif and its WAV twin: a FORM or RIFF size of 0xFFFFFFFE, the largest that is not the streamed + // writer's placeholder, saved as it is: every byte of the 4 GB sound is copied. + [TestMethod] + [DynamicData (nameof (ContainerOnlyRows))] + public async Task ContainerOfFourGigabytesLessOne_SavesWhole (string format) + { + var files = new SparseFileSystem (); + var headLength = Big (format, 0).Head.Length; + var sound = 0xFFFFFFFEL + 8 - headLength; + var file = Big (format, sound); + Assert.AreEqual (0xFFFFFFFEL + 8, file.Length, "the container size"); + files.Add ("/big" + format, file); + var media = Open ("path", "/big" + format, files); + + var result = await SpanSaveKit.SavePath (media, "/out" + format, sync: true, files); + + Assert.IsTrue (result.IsSuccess, result.Error); + var written = files.Get ("/out" + format); + CollectionAssert.AreEqual (file.Head, written.Head, "the header"); + Assert.AreEqual (sound, written.RunLength, "the source's sound, byte for byte"); + Assert.IsEmpty (written.Tail); + } + + // A save whose FORM or RIFF size would pass 32 bits fails and writes nothing. The source's size is 4 GB less 18 + // bytes, and a new title adds an ID3 chunk. + [TestMethod] + [DynamicData (nameof (ContainerRows))] + public async Task ContainerPast32Bits_FailsAndWritesNothing (string format, string read, string save) + { + var files = new SparseFileSystem (); + var (source, target) = Paths (format, save); + var headLength = Big (format, 0).Head.Length; + var file = Big (format, uint.MaxValue - 17L - (headLength - 8)); + Assert.AreEqual (uint.MaxValue - 17L + 8, file.Length, "the source's container size"); + files.Add (source, file); + var media = Open (read, source, files); + Retitle (media, "A title the container has no room for"); + + var result = await SpanSaveKit.SavePath (media, target, save.StartsWith ("sync", StringComparison.Ordinal), files); + + Assert.AreEqual (format == ".wav" ? "Cannot save a WAV file larger than its 32-bit RIFF size." : "Cannot save an AIFF file larger than its 32-bit FORM size.", result.Error); + Assert.AreSame (file, files.Get (source)); + if (target != source) + Assert.IsFalse (files.FileExists (target)); + } + + static (string Source, string Target) Paths (string format, string save) => + ("/big" + format, save.EndsWith ("source", StringComparison.Ordinal) ? "/big" + format : "/out" + format); + + static IMediaFile Open (string read, string path, SparseFileSystem files) + { + var result = read == "async-path" ? MediaFile.ReadAsync (path, files).GetAwaiter ().GetResult () : MediaFile.Read (path, files); + Assert.IsTrue (result.IsSuccess, read + ": " + result.Error); + return (IMediaFile)result.File!; + } + + static void Retitle (IMediaFile file, string title) + { + if (file is AiffFile aiff) + aiff.Title = title; + else if (file is WavFile wav) + (wav.Id3v2Tag ??= new Id3v2Tag ()).Title = title; + else + SpanSaveKit.Retitle (file, title); + } + + // A built file whose sound chunk is made to declare bytes, which are the run, with the + // chunk's header last in the head; the container's sizes follow. + // With chunkAfter, a chunk follows the sound chunk, after its pad byte when the sound is odd. + static SparseFile Big (string format, long sound, bool chunkAfter = false) => format switch { + ".wav" => Wav (sound, chunkAfter), + ".aif" => Aiff (sound, chunkAfter), + ".dsf" => Dsf (sound), + _ => Dff (sound), + }; + + static SparseFile Wav (long sound, bool chunkAfter) + { + var head = TestBuilders.Wav.CreateMinimal (soundBytes: 0); + BinaryPrimitives.WriteUInt32LittleEndian (head.AsSpan (head.Length - 4), (uint)sound); + byte[] tail = chunkAfter ? [.. new byte[sound & 1], .. "odd!\u0004\0\0\0abcd"u8] : []; + BinaryPrimitives.WriteUInt32LittleEndian (head.AsSpan (4), (uint)(head.Length - 8 + sound + tail.Length)); + return new SparseFile (head, sound, tail); + } + + // COMM's frames (stereo, 16 bits), so the duration comes from the sound; the SSND holds its offset and block size, + // then the sound. + static SparseFile Aiff (long sound, bool chunkAfter) + { + var head = TestBuilders.Aiff.CreateMinimal (soundBytes: 0); + BinaryPrimitives.WriteUInt32BigEndian (head.AsSpan (head.AsSpan ().IndexOf ("COMM"u8) + 10), (uint)(sound / 4)); + BinaryPrimitives.WriteUInt32BigEndian (head.AsSpan (head.AsSpan ().IndexOf ("SSND"u8) + 4), (uint)(8 + sound)); + byte[] tail = chunkAfter ? [.. new byte[sound & 1], .. "APPL\0\0\0\u0004odd!"u8] : []; + BinaryPrimitives.WriteUInt32BigEndian (head.AsSpan (4), (uint)(head.Length - 8 + sound + tail.Length)); + return new SparseFile (head, sound, tail); + } + + static SparseFile Dsf (long sound) + { + var built = TestBuilders.Dsf.CreateMinimal (); + var data = built.AsSpan ().IndexOf ("data"u8); + var head = built.AsSpan (0, data + 12).ToArray (); + BinaryPrimitives.WriteUInt64LittleEndian (head.AsSpan (data + 4), (ulong)(12 + sound)); + BinaryPrimitives.WriteUInt64LittleEndian (head.AsSpan (12), (ulong)(head.Length + sound)); + return new SparseFile (head, sound, []); + } + + // The DSD chunk is the last "DSD " (the form type and PROP's CMPR say it too); its sound is 0x69 bytes. + static SparseFile Dff (long sound) + { + var built = TestBuilders.Dff.CreateMinimal (); + var dsd = built.AsSpan ().LastIndexOf ("DSD "u8); + var head = built.AsSpan (0, dsd + 12).ToArray (); + BinaryPrimitives.WriteUInt64BigEndian (head.AsSpan (dsd + 4), (ulong)sound); + BinaryPrimitives.WriteUInt64BigEndian (head.AsSpan (4), (ulong)(head.Length + sound - 12)); + return new SparseFile (head, sound, []); + } +} diff --git a/tests/TagLibSharp2.Tests/Core/BitRatePastIntTests.cs b/tests/TagLibSharp2.Tests/Core/BitRatePastIntTests.cs new file mode 100644 index 00000000..06ac1f71 --- /dev/null +++ b/tests/TagLibSharp2.Tests/Core/BitRatePastIntTests.cs @@ -0,0 +1,104 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Buffers.Binary; +using TagLibSharp2.Core; +using TagLibSharp2.Ogg; + +namespace TagLibSharp2.Tests.Core; + +/// +/// A bit rate worked out from a file's size over its duration, or from its sample rate, bits and channels, is a real +/// number cast to int; one too large to report read as 2,147,483,647 where the cast saturates (net9.0 and later) +/// and wrapped on older runtimes (#198). It is now 0, as #194's rule reads any rate too large to report. The tests +/// assert 0, which no cast gives, so they fail before the fix on every platform. +/// +[TestClass] +[TestCategory ("Unit")] +public sealed class BitRatePastIntTests +{ + // Six megabytes of bytes that are no Ogg page, between the header pages and the page the duration comes from. + const int Filler = 6 * 1024 * 1024; + + // The review's opus-1sample-big.opus: its last granule is one sample past the pre-skip, so the duration is one + // 48 kHz sample (20.8 µs) and six megabytes over it is 2.4e9 kbps. + static byte[] OpusOneSample () + { + var headers = TestBuilders.Opus.CreateMinimalFile (); + var page = OggPageHelper.BuildOggPage ([[0xFC, 0xFF, 0xFE]], OggPageFlags.EndOfStream, 312 + 1, 1, 2); + return [.. headers, .. new byte[Filler], .. page]; + } + + public static IEnumerable EntryRows () => DurationUnknownTests.Entries.Select (entry => new object[] { entry }); + + [TestMethod] + [DynamicData (nameof (EntryRows))] + public void OpusOneSampleInSixMegabytes_HasNoBitRate (string entry) + { + var file = (IMediaFile)DurationUnknownTests.Open (OpusOneSample (), ".opus", entry); + + Assert.AreEqual (TimeSpan.FromTicks (208), file.AudioProperties!.Duration, entry); + Assert.AreEqual (0, file.AudioProperties.Bitrate, entry); + } + + // The public factories' sites: a file size over a one-sample duration, bits times channels past an int, and a + // DSD rate times channels past an int. + [TestMethod] + public void FromOpus_BitRatePastInt_IsZero () => + Assert.AreEqual (0, AudioProperties.FromOpus (312 + 1, 312, 48_000, 2, Filler).Bitrate); + + [TestMethod] + public void FromFlac_BitRatePastInt_IsZero () => + Assert.AreEqual (0, AudioProperties.FromFlac (1, 44_100, int.MaxValue, 8).Bitrate); + + [TestMethod] + public void FromDsf_BitRatePastInt_IsZero () => + Assert.AreEqual (0, AudioProperties.FromDsf (TimeSpan.FromSeconds (1), int.MaxValue, int.MaxValue).Bitrate); + + [TestMethod] + public void FromDff_BitRatePastInt_IsZero () => + Assert.AreEqual (0, AudioProperties.FromDff (TimeSpan.FromSeconds (1), int.MaxValue, int.MaxValue).Bitrate); + + // The same factories within range keep their bit rate. + [TestMethod] + public void InRange_BitRatesAreKept () + { + Assert.AreEqual (1411, AudioProperties.FromFlac (44_100, 44_100, 16, 2).Bitrate); + Assert.AreEqual (5644, AudioProperties.FromDsf (TimeSpan.FromSeconds (1), 2_822_400, 2).Bitrate); + Assert.AreEqual (5644, AudioProperties.FromDff (TimeSpan.FromSeconds (1), 2_822_400, 2).Bitrate); + } + + // The sweep's twin: Matroska's SamplingFrequency is a float and its Channels an unsigned integer, cast to int + // unguarded. A frequency of 1e20 Hz and 2^40 channels read as 0, not as a saturated or wrapped int. + [TestMethod] + [DynamicData (nameof (EntryRows))] + public void MatroskaRateAndChannelsPastInt_AreZero (string entry) + { + byte[] channels = [0, 0, 1, 0, 0, 0, 0, 0]; + var audio = Matroska.MatroskaFileTests.Master (0xE1, [ + .. Matroska.MatroskaFileTests.Element (0xB5, Matroska.MatroskaFileTests.Float32 (1e20f)), + .. Matroska.MatroskaFileTests.Element (0x9F, channels)]); + var entry1 = Matroska.MatroskaFileTests.Master (0xAE, [ + .. Matroska.MatroskaFileTests.Element (0xD7, new byte[] { 1 }), + .. Matroska.MatroskaFileTests.Element (0x83, new byte[] { 2 }), + .. audio]); + var mkv = Matroska.MatroskaFileTests.Matroska (Matroska.MatroskaFileTests.Master (0x18538067, + Matroska.MatroskaFileTests.Master (0x1549A966, Matroska.MatroskaFileTests.Element (0x4489, Matroska.MatroskaFileTests.Float32 (1000f))), + Matroska.MatroskaFileTests.Master (0x1654AE6B, entry1))); + + var file = (IMediaFile)DurationUnknownTests.Open (mkv, ".mkv", entry); + + Assert.AreEqual (0, file.AudioProperties!.SampleRate, entry); + Assert.AreEqual (0, file.AudioProperties.Channels, entry); + } + + // The rule's edges on a real number of bits per second. + [TestMethod] + [DataRow (128_000.0, 128)] + [DataRow (2_147_483_647_999.0, int.MaxValue)] + [DataRow (2_147_483_648_000.0, 0)] + [DataRow (-1_000.0, 0)] + [DataRow (double.NaN, 0)] + [DataRow (double.PositiveInfinity, 0)] + public void KbpsOfRealBitsPerSecond (double bits, int expected) => Assert.AreEqual (expected, Rates.Kbps (bits)); +} diff --git a/tests/TagLibSharp2.Tests/Core/ChainedSaveTests.cs b/tests/TagLibSharp2.Tests/Core/ChainedSaveTests.cs new file mode 100644 index 00000000..3abd85da --- /dev/null +++ b/tests/TagLibSharp2.Tests/Core/ChainedSaveTests.cs @@ -0,0 +1,127 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Buffers.Binary; +using TagLibSharp2.Aiff; +using TagLibSharp2.Core; +using TagLibSharp2.Mp4; +using TagLibSharp2.Riff; +using TagLibSharp2.Tests.Matroska; + +namespace TagLibSharp2.Tests.Core; + +/// +/// #212: a file read from a path is edited and saved, and edited and saved again, from the same object, every save +/// after the first over the source, with each title long enough that the structure holding it, ahead of the payload in +/// most formats, outgrows any padding. Each save writes what a fresh read of the file on disk, given the same edit, +/// writes. An AIFF whose NAME chunk, or a WAV whose LIST INFO, sat ahead of the sound moved the sound on the first save +/// over the source (the edit writes the text after it), and the second save copied the sound from where the read had +/// found it: AIFF wrote other bytes in its place, WAV failed. On main as well. Every format with a path save is here: +/// the span-save fixtures (#179's chain tests cover them with shorter titles), AIFF and WAV with and without a chunk +/// ahead of the sound, MP4 and Matroska. +/// +[TestClass] +[TestCategory ("Unit")] +public sealed class ChainedSaveTests +{ + static readonly string[] Titles = ["One " + new string ('x', 8000), "Two", "Three " + new string ('y', 3000)]; + + // How the first save is made: over the source by its path, or to another file. Every later save is over the source. + static readonly string[] FirstSaves = ["source", "elsewhere"]; + + static readonly bool[] Syncs = [true, false]; + + static readonly Dictionary> Shapes = new () { + // A NAME chunk ahead of SSND, and a LIST INFO ahead of data: the edit drops each from there. + [".name.aif"] = () => WithChunkAhead (TestBuilders.Aiff.CreateMinimal (soundBytes: 1024), "SSND"u8, [.. "NAME"u8, 0, 0, 0, 100, .. Enumerable.Repeat ((byte)'n', 100)], bigEndian: true), + [".info.wav"] = () => WithChunkAhead (TestBuilders.Wav.CreateMinimal (soundBytes: 1024), "data"u8, + [.. "LIST"u8, 112, 0, 0, 0, .. "INFO"u8, .. "INAM"u8, 100, 0, 0, 0, .. Enumerable.Repeat ((byte)'n', 100)], bigEndian: false), + // The same, with 37 bytes after the form, which every save writes at the end (#192, #197). + [".name-trail.aif"] = () => [.. Shapes![".name.aif"] (), .. Enumerable.Repeat ((byte)0xA5, 37)], + [".info-trail.wav"] = () => [.. Shapes![".info.wav"] (), .. Enumerable.Repeat ((byte)0xA5, 37)], + [".aif"] = () => TestBuilders.Aiff.CreateMinimal (soundBytes: 1024), + [".wav"] = () => TestBuilders.Wav.CreateMinimal (soundBytes: 1024), + [".m4a"] = () => TestBuilders.Mp4.CreateMinimalM4a (Mp4CodecType.Aac), + [".mkv"] = () => MatroskaFileTests.Matroska (MatroskaFileTests.Master (0x18538067, + MatroskaFileTests.Master (0x1549A966, MatroskaFileTests.Element (0x4489, MatroskaFileTests.Float32 (1000f))), + MatroskaFileTests.Master (0x1F43B675, MatroskaFileTests.Element (0xA3, SpanSaveKit.Sound (256))))), + }; + + static byte[] Build (string fixture) => Shapes.TryGetValue (fixture, out var build) ? build () : SpanSaveKit.Fixtures[fixture].Build (); + + public static IEnumerable Rows () => + from fixture in SpanSaveKit.Fixtures.Keys.Concat (Shapes.Keys) + from first in FirstSaves + from sync in Syncs + select new object[] { fixture, first, sync }; + + [TestMethod] + [DynamicData (nameof (Rows))] + public async Task EachSave_WritesWhatAFreshReadOfTheFileOnDiskWrites (string fixture, string first, bool sync) + { + var extension = Path.GetExtension (fixture); + var source = "/in" + extension; + var files = new MockFileSystem (); + files.AddFile (source, Build (fixture)); + var read = MediaFile.Read (source, files); + Assert.IsTrue (read.IsSuccess, read.Error); + var file = (IMediaFile)read.File!; + + for (var i = 0; i < Titles.Length; i++) { + var target = i == 0 && first == "elsewhere" ? "/else" + extension : source; + var before = files.ReadAllBytes (source); + Retitle (file, Titles[i]); + + var saved = await SpanSaveKit.SavePath (file, target, sync, files); + + Assert.IsTrue (saved.IsSuccess, $"save {i + 1}: {saved.Error}"); + CollectionAssert.AreEqual (await FreshSave (extension, before, Titles[i], sync), files.ReadAllBytes (target), $"save {i + 1}"); + var back = (IMediaFile)MediaFile.ReadFromData (files.ReadAllBytes (target), "/back" + extension).File!; + Assert.AreEqual (Titles[i], back.Tag?.Title, $"save {i + 1}"); + } + } + + // What a read of bytes, from a path, given the edit and saved over that path, writes. + static async Task FreshSave (string extension, byte[] bytes, string title, bool sync) + { + var files = new MockFileSystem (); + var path = "/fresh" + extension; + files.AddFile (path, bytes); + var file = (IMediaFile)MediaFile.Read (path, files).File!; + Retitle (file, title); + var saved = await SpanSaveKit.SavePath (file, path, sync, files); + Assert.IsTrue (saved.IsSuccess, "fresh save: " + saved.Error); + return files.ReadAllBytes (path); + } + + // AIFF and WAV keep the text the edit sets in a chunk of their own (NAME or LIST INFO), MP4 in its tag. + static void Retitle (IMediaFile file, string title) + { + switch (file) { + case AiffFile aiff: + aiff.Title = title; + break; + case WavFile wav: + (wav.InfoTag ??= new RiffInfoTag ()).Title = title; + break; + case Mp4File mp4: + mp4.Title = title; + break; + default: + SpanSaveKit.Retitle (file, title); + break; + } + } + + // The form with put ahead of the chunk named , and its size grown. + static byte[] WithChunkAhead (byte[] form, ReadOnlySpan before, byte[] chunk, bool bigEndian) + { + var at = form.AsSpan ().IndexOf (before); + byte[] grown = [.. form.AsSpan (0, at), .. chunk, .. form.AsSpan (at)]; + if (bigEndian) + BinaryPrimitives.WriteUInt32BigEndian (grown.AsSpan (4), (uint)(grown.Length - 8)); + else + BinaryPrimitives.WriteUInt32LittleEndian (grown.AsSpan (4), (uint)(grown.Length - 8)); + return grown; + } +} diff --git a/tests/TagLibSharp2.Tests/Core/DurationOverflowTests.cs b/tests/TagLibSharp2.Tests/Core/DurationOverflowTests.cs deleted file mode 100644 index df609bd3..00000000 --- a/tests/TagLibSharp2.Tests/Core/DurationOverflowTests.cs +++ /dev/null @@ -1,177 +0,0 @@ -// Copyright (c) 2025-2026 Stephen Shaw and contributors -// Licensed under the MIT License. See LICENSE file in the project root for full license information. - -using System.Buffers.Binary; -using TagLibSharp2.Ape; -using TagLibSharp2.Core; -using TagLibSharp2.Dsf; -using TagLibSharp2.Musepack; -using TagLibSharp2.Ogg; - -namespace TagLibSharp2.Tests.Core; - -/// -/// A duration is a count of samples over a rate, and the file supplies both. One past -/// is reported as , not thrown (#175), and every -/// entry point that reads the same bytes reports the same duration. -/// -[TestClass] -[TestCategory ("Unit")] -public sealed class DurationOverflowTests -{ - // #175: a malformed 315-byte Opus file. Its third page has the end-of-stream flag and a granule position of - // about 2^63; the file ends with a second OpusHead page whose granule is 0. - const string MalformedOpus = - "T2dnUwACAAAAAAAAAAChC/sVAAAAAIDB4tgBE09wdXNIZWFkAAIAAAAAAAAAAABPZ2dTAAAAAAAA" + - "AAAAAKEL+xUBAAAAJAu0mwEuT3B1c1RhZ3MeAAAARW5jb2RlZCB3aXRoIEdTdHJlYW1lciBPcHVz" + - "ZW5jAAAAAE9nZ1MABNBcpMZiYiKloQv7FQIAAAAkH1KcAaaHhHLcTK2gTZklUstRBnnE+Lim/YMj" + - "EOeuRyfRYr/M+KU16bIVragluoAyGzGfowI7CMxF9AiskYMCuWzppRw8xafL///CaTFPbkw72vVf" + - "gArmiHwqDhE5EZAbuuZ65wO9xJkWprK55i9gRg/Ey1cBgMjbqpXcoPuGT2dnUwACAAAAAAAAAACl" + - "320HAAAAACIdAiwBE09wdXNIZWFkAQF4AIC7AAAA"; - - [TestMethod] - public void MalformedOpus_ReadsTheSameOnEveryEntryPoint () - { - var bytes = Convert.FromBase64String (MalformedOpus); - - var reads = ReadEveryWay (bytes, ".opus"); - - Assert.AreEqual (reads["stream"], reads["data"]); - Assert.AreEqual (reads["stream"], reads["path"]); - Assert.AreEqual (reads["stream"], reads["span"]); - } - - // The Vorbis twin of #175: an end-of-stream page with a huge granule position in the middle, and a last page. - [TestMethod] - [DataRow (".ogg")] - [DataRow (".opus")] - public void EndOfStreamPageBeforeTheLastPage_ReadsTheSameOnEveryEntryPoint (string extension) - { - var file = extension == ".ogg" ? TestBuilders.Ogg.CreateMinimalFile () : TestBuilders.Opus.CreateMinimalFile (); - var audio = OggPageHelper.BuildOggPage ([[1, 2, 3, 4]], OggPageFlags.EndOfStream, 0xA5A4_2262_62C6_A45C, 1, 2); - var last = OggPageHelper.BuildOggPage ([[5, 6, 7, 8]], OggPageFlags.None, 48_000, 1, 3); - var bytes = file.Concat (audio).Concat (last).ToArray (); - - var reads = ReadEveryWay (bytes, extension); - - Assert.AreEqual (reads["stream"], reads["data"]); - Assert.AreEqual (reads["stream"], reads["path"]); - Assert.AreEqual (reads["stream"], reads["span"]); - } - - [TestMethod] - public void SampleCountPastTimeSpan_IsTheLongestDuration () - { - Assert.AreEqual (TimeSpan.MaxValue, AudioProperties.FromOpus (ulong.MaxValue, 0, 48000, 2, 1000).Duration); - Assert.AreEqual (TimeSpan.MaxValue, AudioProperties.FromVorbis (ulong.MaxValue, 1, 2, 0).Duration); - Assert.AreEqual (TimeSpan.MaxValue, AudioProperties.FromFlac (ulong.MaxValue, 1, 16, 2).Duration); - } - - // The three readers that divide a 64-bit sample count by a rate of their own (#175): each built file has a count - // whose duration is past TimeSpan.MaxValue, and every entry point reports TimeSpan.MaxValue. - [TestMethod] - [DataRow (".ape")] - [DataRow (".mpc")] - [DataRow (".dsf")] - public void SampleCountPastTimeSpan_IsTheLongestDurationOnEveryEntryPoint (string extension) - { - var bytes = WithSampleCountPastTimeSpan (extension); - - var reads = ReadEveryWay (bytes, extension); - - foreach (var (entry, read) in reads) - Assert.AreEqual ($"True {TimeSpan.MaxValue}", read, entry); - } - - static byte[] WithSampleCountPastTimeSpan (string extension) - { - switch (extension) { - case ".ape": { - // New-format header after the 52-byte descriptor: blocks per frame at 60, total frames at 68. - // (2^32 - 2) * (2^32 - 1) blocks at 44,100 Hz is about 4.2e14 seconds. - var bytes = TestBuilders.MonkeysAudio.CreateMinimal (); - BinaryPrimitives.WriteUInt32LittleEndian (bytes.AsSpan (60), uint.MaxValue); - BinaryPrimitives.WriteUInt32LittleEndian (bytes.AsSpan (68), uint.MaxValue); - return bytes; - } - case ".mpc": - // SV8: a stream header packet whose sample count is the largest 9-byte count, 2^63 - 1 samples at - // 44,100 Hz (about 2.1e14 seconds), then the stream end packet. A packet size counts its key and - // size bytes. - return [ - (byte)'M', (byte)'P', (byte)'C', (byte)'K', - (byte)'S', (byte)'H', 20, 0, 0, 0, 0, 8, - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x7F, - 0, 0x00, 0x10, - (byte)'S', (byte)'E', 3, - ]; - default: { - // fmt chunk sample count at 64: 2^64 - 1 samples at 2,822,400 Hz is about 6.5e12 seconds. - var bytes = TestBuilders.Dsf.CreateMinimal (); - BinaryPrimitives.WriteUInt64LittleEndian (bytes.AsSpan (64), ulong.MaxValue); - return bytes; - } - } - } - - static Dictionary ReadEveryWay (byte[] bytes, string extension) - { - var name = "/file" + extension; - var files = new MockFileSystem (); - files.AddFile (name, bytes); - return new () { - ["stream"] = Describe (() => MediaFile.Read (new MemoryStream (bytes), name)), - ["path"] = Describe (() => MediaFile.Read (name, files)), - ["data"] = Describe (() => MediaFile.ReadFromData (bytes, name)), - ["span"] = Describe (() => ReadSpan (bytes, extension)), - }; - } - - static (bool, string?, TimeSpan?) ReadSpan (byte[] bytes, string extension) - { - switch (extension) { - case ".ogg": { - var r = OggVorbisFile.Read (bytes); - return (r.IsSuccess, r.Error, r.File?.Properties.Duration); - } - case ".opus": { - var r = OggOpusFile.Read (bytes); - return (r.IsSuccess, r.Error, r.File?.Properties.Duration); - } - case ".ape": { - var r = MonkeysAudioFile.Read (bytes); - return (r.IsSuccess, r.Error, r.File?.Properties.Duration); - } - case ".mpc": { - var r = MusepackFile.Read (bytes); - return (r.IsSuccess, r.Error, r.File?.Properties.Duration); - } - default: { - // DsfFile.Duration is the fmt chunk's own duration, beside the one in Properties. - var r = DsfFile.Read (bytes); - Assert.AreEqual (r.File?.Properties?.Duration, r.File?.Duration); - return (r.IsSuccess, r.Error, r.File?.Duration); - } - } - } - - static string Describe (Func read) - { - try { - var result = read (); - return $"{result.IsSuccess} {result.Error} {(result.File as IMediaFile)?.AudioProperties?.Duration}"; - } catch (OverflowException ex) { - return "threw " + ex.GetType ().Name; - } - } - - static string Describe (Func<(bool Success, string? Error, TimeSpan? Duration)> read) - { - try { - var (success, error, duration) = read (); - return $"{success} {error} {duration}"; - } catch (OverflowException ex) { - return "threw " + ex.GetType ().Name; - } - } -} diff --git a/tests/TagLibSharp2.Tests/Core/DurationUnknownTests.cs b/tests/TagLibSharp2.Tests/Core/DurationUnknownTests.cs new file mode 100644 index 00000000..2ba6ab33 --- /dev/null +++ b/tests/TagLibSharp2.Tests/Core/DurationUnknownTests.cs @@ -0,0 +1,458 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Buffers.Binary; +using System.Reflection; +using TagLibSharp2.Ape; +using TagLibSharp2.Asf; +using TagLibSharp2.Core; +using TagLibSharp2.Dsf; +using TagLibSharp2.Matroska; +using TagLibSharp2.Mp4; +using TagLibSharp2.Musepack; +using TagLibSharp2.Ogg; +using TagLibSharp2.Riff; +using TagLibSharp2.Tests.Asf; +using TagLibSharp2.Tests.Matroska; +using TagLibSharp2.Tests.Mp4; +using TagLibSharp2.Tests.Riff; + +namespace TagLibSharp2.Tests.Core; + +/// +/// A duration the file states but cannot hold is unknown (#181): on +/// every non-nullable duration and null on every nullable one, on every entry point. No format spec sets a maximum or +/// a clamp rule, and ffprobe reports N/A exactly where a duration stops fitting its 64-bit time field +/// (durations/report.md). #175 saturated at , and adding anything to that throws. +/// +[TestClass] +[TestCategory ("Unit")] +public sealed class DurationUnknownTests +{ + // A granule position of 2^62 is about 9.6e13 s at 48 kHz and 1.0e14 s at 44.1 kHz. + const ulong HugeGranule = 1UL << 62; + + /// One built file per format whose duration field can say more than TimeSpan holds. + internal static readonly Dictionary> PastTimeSpan = new () { + // New-format header after the 52-byte descriptor: blocks per frame at 60, total frames at 68. + // (2^32 - 1)^2 blocks at 44,100 Hz is about 4.2e14 s. + [".ape"] = () => { + var bytes = TestBuilders.MonkeysAudio.CreateMinimal (); + BinaryPrimitives.WriteUInt32LittleEndian (bytes.AsSpan (60), uint.MaxValue); + BinaryPrimitives.WriteUInt32LittleEndian (bytes.AsSpan (68), uint.MaxValue); + return bytes; + }, + // SV8: a stream header packet whose sample count is the largest 9-byte count, 2^63 - 1 samples at 44,100 Hz + // (about 2.1e14 s), then the stream end packet. A packet size counts its key and size bytes. + [".mpc"] = () => [ + (byte)'M', (byte)'P', (byte)'C', (byte)'K', + (byte)'S', (byte)'H', 20, 0, 0, 0, 0, 8, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x7F, + 0, 0x00, 0x10, + (byte)'S', (byte)'E', 3, + ], + // fmt chunk sample count at 64: 2^64 - 1 samples at 2,822,400 Hz is about 6.5e12 s. + [".dsf"] = () => { + var bytes = TestBuilders.Dsf.CreateMinimal (); + BinaryPrimitives.WriteUInt64LittleEndian (bytes.AsSpan (64), ulong.MaxValue); + return bytes; + }, + [".opus"] = () => [.. TestBuilders.Opus.CreateMinimalFile (), .. LastPage (HugeGranule)], + [".ogg"] = () => [.. TestBuilders.Ogg.CreateMinimalFile (), .. LastPage (HugeGranule)], + // An Ogg FLAC stream without a STREAMINFO total takes the granule (#184). + [".oga"] = () => TagLibSharp2.Tests.Ogg.OggDurationTests.OggFlacWithoutATotal (HugeGranule), + // mvhd v1 with timescale 1 and a duration of 2^64 - 1 (ISO 14496-12 §8.2.2). + [".m4a"] = Mp4MalformedInputTests.FileWithHugeMovieDuration, + // File Properties Play and Send Duration of 1e19 (100 ns units), 1e12 s: past 2^63 ticks. + [".wma"] = () => WithPlayDuration (AsfTestBuilder.CreateMinimalWma (), 10_000_000_000_000_000_000UL), + // Info/Duration of 1e20 ticks at the default TimestampScale of 1 ms: 1e17 s. + [".mkv"] = () => MatroskaFileTests.Matroska (MatroskaFileTests.Master (0x18538067, + MatroskaFileTests.Master (0x1549A966, MatroskaFileTests.Element (0x4489, MatroskaFileTests.Float32 (1e20f))))), + // A 'DSD ' chunk of 2^61 + 17 bytes: 2^63 + 68 samples per channel at 2,822,400 Hz, stereo (3.3e12 s). Its + // size in bits, the size times 8, does not fit 64 bits (#182); its odd last byte holds 4 samples a channel. + [".dff"] = () => WithDsdChunkSize (TestBuilders.Dff.CreateMinimal (), (1UL << 61) + 17), + // 2^63 + 2 bytes: not even the sample count fits 64 bits (it would wrap to 8). + [".huge.dff"] = () => WithDsdChunkSize (TestBuilders.Dff.CreateMinimal (), (1UL << 63) + 2), + // Every strh: scale 2^32 - 1, rate 1, length 2^32 - 1 (1.8e19 s); avih: 2^32 - 1 us per frame and frames. + [".avi"] = () => WithHugeAviHeaders (new AviTestBuilder ().Build ()), + }; + + /// + /// One built file per spec value that means "duration unknown" (#183): ISO 14496-12 §8.2.2.3, §8.3.2.3 and §8.4.2.3, + /// "If the duration cannot be determined then duration is set to all 1s", and the ASF File Properties Object, + /// whose Play Duration "is invalid if the Broadcast Flag bit in the Flags field is set to 1" (ASF 01.20.03 §3.2). + /// ffprobe reports both as N/A or measures the data. + /// + internal static readonly Dictionary> UnknownMarker = new () { + // mvhd and mdhd version 0, duration 2^32 - 1: at the builder's timescale a fake 27 hours. + [".v0.m4a"] = () => WithAllOnesDurations (Mp4ChapterTestBuilder.Build (new ())), + // mvhd version 1, duration 2^64 - 1 at timescale 2^32 - 1: 4.3e9 s, a value TimeSpan holds. Its track's + // mdhd keeps its own 10 s. + [".v1.m4a"] = () => Mp4MalformedInputTests.FileWithHugeMovieDuration (uint.MaxValue), + // A one-second file with the Broadcast Flag (bit 0 of Flags, 88 bytes into the object) set. + [".broadcast.wma"] = () => { + var wma = AsfTestBuilder.CreateMinimalWma (); + wma[FilePropertiesOffset (wma) + 88] |= 1; + return wma; + }, + // WavPack: total_samples "is only valid if block_index == 0 and a value of -1 indicates unknown length" (the + // WavPack file format). The block header keeps it 12 bytes in; a fake 27 hours at 44.1 kHz (#191). + [".unknown.wv"] = () => { + var wv = TestBuilders.WavPack.CreateMinimal (); + BinaryPrimitives.WriteUInt32LittleEndian (wv.AsSpan (12), uint.MaxValue); + return wv; + }, + // The version 3 header inside RIFF/WAVE keeps its sample count 16 bytes in (#191). + [".v3unknown.wv"] = () => TagLibSharp2.Tests.WavPack.WavPackFileTests.CreateLegacyRiffWavPack (3, uint.MaxValue, 4096), + }; + + // The WavPack marker is no sample count: TotalSamples is 0, as for a header with none (#191). + [TestMethod] + [DynamicData (nameof (WavPackMarkerRows))] + public void WavPackUnknownLength_HasNoSampleCount (string extension, string entry) + { + var file = (TagLibSharp2.WavPack.WavPackFile)Open (UnknownMarker[extension] (), extension, entry); + + Assert.AreEqual (0u, file.TotalSamples, $"{extension} {entry}"); + Assert.AreEqual (44_100, file.SampleRate, $"{extension} {entry}"); + } + + public static IEnumerable WavPackMarkerRows () => + from extension in UnknownMarker.Keys.Where (key => key.EndsWith (".wv", StringComparison.Ordinal)) + from entry in Entries + select new object[] { extension, entry }; + + public static IEnumerable MarkerRows () => + from extension in UnknownMarker.Keys + from entry in Entries + select new object[] { extension, entry }; + + [TestMethod] + [DynamicData (nameof (MarkerRows))] + public void UnknownDurationMarker_IsUnknown (string extension, string entry) + { + var file = Open (UnknownMarker[extension] (), extension, entry); + + foreach (var (name, value, nullable) in Durations (file)) { + // The v1 file's track states its own duration, which the audio properties take. + if (extension == ".v1.m4a" && value == TimeSpan.FromSeconds (10) && name != "Duration") + continue; + AssertUnknown (value, nullable, $"{extension} {entry} {name}"); + } + } + + // Mp4AudioPropertiesParser reads mdhd, then mvhd: both markers are unknown. + [TestMethod] + public void Mp4AudioPropertiesParser_AllOnesDurations_AreUnknown () => + Assert.AreEqual (TimeSpan.Zero, Mp4AudioPropertiesParser.Parse (UnknownMarker[".v0.m4a"] ()).Duration); + + // The last MP4 chapter ends at the movie duration; with the marker that is unknown, so it ends where it starts + // (Mp4Chapter.WithEndTime), not 49.7 days later. + [TestMethod] + public void Mp4LastChapter_AfterAnAllOnesMovieDuration_EndsWhereItStarts () + { + var bytes = WithAllOnesDurations (Mp4ChapterTestBuilder.Build (new () { + Chpl = [(TimeSpan.Zero, "One"), (TimeSpan.FromSeconds (1), "Two")], + })); + + var last = Mp4File.Read (bytes).File!.Chapters[^1]; + + Assert.AreEqual (TimeSpan.FromSeconds (1), last.EndTime); + } + + // A chapter list saved into such a file gives its last chapter the length the movie duration leaves it, which is + // unknown: one media unit, not 49.7 days (Mp4ChapterCodec.MovieDuration and SampleDeltas). + [TestMethod] + public void Mp4ChaptersSaved_AfterAnAllOnesMovieDuration_KeepTheLastChapterShort () + { + var bytes = WithAllOnesDurations (Mp4ChapterTestBuilder.Build (new ())); + var file = Mp4File.Read (bytes).File!; + file.Chapters = [new Mp4Chapter (TimeSpan.Zero, "One"), new Mp4Chapter (TimeSpan.FromSeconds (1), "Two")]; + var files = new MockFileSystem (); + Assert.IsTrue (file.SaveToFile ("/out.m4a", bytes, files).IsSuccess); + + var last = Mp4File.Read (files.ReadAllBytes ("/out.m4a")).File!.Chapters[^1]; + + Assert.AreEqual (TimeSpan.FromSeconds (1), last.StartTime); + Assert.IsLessThan (TimeSpan.FromSeconds (2), last.EndTime!.Value); + } + + // mvhd and mdhd keep the duration 16 bytes into their payload in version 0; patched in place, so no size moves. + static byte[] WithAllOnesDurations (byte[] mp4) + { + foreach (var box in new[] { "mvhd"u8.ToArray (), "mdhd"u8.ToArray () }) { + for (var at = 0; (at = mp4.AsSpan (at).IndexOf (box) is var i and >= 0 ? at + i : -1) >= 0; at += 4) { + Assert.AreEqual (0, mp4[at + 4], "a version 0 box"); + BinaryPrimitives.WriteUInt32BigEndian (mp4.AsSpan (at + 4 + 16), uint.MaxValue); + } + } + + return mp4; + } + + public static IEnumerable Rows () => + from extension in PastTimeSpan.Keys + from entry in Entries + select new object[] { extension, entry }; + + /// + /// Every entry point a read takes: 's four reads, each with and without + /// , and the format's own span and path reads. + /// + internal static readonly string[] Entries = [ + "stream", "path", "async-path", "data", + "skip-stream", "skip-path", "skip-async-path", "skip-data", + "format-span", "format-path"]; + + [TestMethod] + [DynamicData (nameof (Rows))] + public void DurationPastTimeSpan_IsUnknown (string extension, string entry) + { + var file = Open (PastTimeSpan[extension] (), extension, entry); + + foreach (var (name, value, nullable) in Durations (file)) + AssertUnknown (value, nullable, $"{extension} {entry} {name}"); + } + + // The read the #175 report found: a malformed 315-byte Opus file whose third page has the end-of-stream flag and + // a granule position of about 2^63, ending with a second OpusHead page whose granule is 0. + const string MalformedOpus = + "T2dnUwACAAAAAAAAAAChC/sVAAAAAIDB4tgBE09wdXNIZWFkAAIAAAAAAAAAAABPZ2dTAAAAAAAA" + + "AAAAAKEL+xUBAAAAJAu0mwEuT3B1c1RhZ3MeAAAARW5jb2RlZCB3aXRoIEdTdHJlYW1lciBPcHVz" + + "ZW5jAAAAAE9nZ1MABNBcpMZiYiKloQv7FQIAAAAkH1KcAaaHhHLcTK2gTZklUstRBnnE+Lim/YMj" + + "EOeuRyfRYr/M+KU16bIVragluoAyGzGfowI7CMxF9AiskYMCuWzppRw8xafL///CaTFPbkw72vVf" + + "gArmiHwqDhE5EZAbuuZ65wO9xJkWprK55i9gRg/Ey1cBgMjbqpXcoPuGT2dnUwACAAAAAAAAAACl" + + "320HAAAAACIdAiwBE09wdXNIZWFkAQF4AIC7AAAA"; + + [TestMethod] + public void MalformedOpus_ReadsTheSameOnEveryEntryPoint () + { + var bytes = Convert.FromBase64String (MalformedOpus); + + var reads = Entries.Select (entry => Describe (bytes, ".opus", entry)).Distinct ().ToArray (); + + Assert.HasCount (1, reads, string.Join (" | ", reads)); + } + + // An end-of-stream page with a huge granule position in the middle, and a last page. + [TestMethod] + [DataRow (".ogg")] + [DataRow (".opus")] + public void EndOfStreamPageBeforeTheLastPage_ReadsTheSameOnEveryEntryPoint (string extension) + { + var file = extension == ".ogg" ? TestBuilders.Ogg.CreateMinimalFile () : TestBuilders.Opus.CreateMinimalFile (); + var audio = OggPageHelper.BuildOggPage ([[1, 2, 3, 4]], OggPageFlags.EndOfStream, 0xA5A4_2262_62C6_A45C, 1, 2); + var last = OggPageHelper.BuildOggPage ([[5, 6, 7, 8]], OggPageFlags.None, 48_000, 1, 3); + byte[] bytes = [.. file, .. audio, .. last]; + + var reads = Entries.Select (entry => Describe (bytes, extension, entry)).Distinct ().ToArray (); + + Assert.HasCount (1, reads, string.Join (" | ", reads)); + } + + static string Describe (byte[] bytes, string extension, string entry) => + string.Join (", ", Durations (Open (bytes, extension, entry)).Select (d => $"{d.Name}={d.Value}")); + + internal static byte[] LastPage (ulong granule) => + OggPageHelper.BuildOggPage ([[1, 2, 3, 4]], OggPageFlags.EndOfStream, granule, 1, 2); + + // FRM8 holds its local chunks after the 4-byte form type: ID (4), size (8, big-endian), data, a pad byte to even. + internal static byte[] WithDsdChunkSize (byte[] dff, ulong size) + { + var at = 16; + while (!dff.AsSpan (at, 4).SequenceEqual ("DSD "u8)) { + at += 12 + (int)BinaryPrimitives.ReadUInt64BigEndian (dff.AsSpan (at + 4)); + at += at & 1; + } + + BinaryPrimitives.WriteUInt64BigEndian (dff.AsSpan (at + 4), size); + return dff; + } + + // The DSD sample count is the chunk's bits over the channels, worked out without wrapping (#182). + [TestMethod] + public void DsdChunkPastSixtyFourBitsOfBits_CountsItsSamples () + { + var file = TagLibSharp2.Dff.DffFile.Read (PastTimeSpan[".dff"] ()).File!; + + Assert.AreEqual ((1UL << 63) + 68, file.SampleCount); + } + + // The largest count that fits: (2^61 - 1) bytes a channel, 2^64 - 8 samples. + [TestMethod] + public void DsdChunkAtTheLargestCount_CountsItsSamples () + { + var file = TagLibSharp2.Dff.DffFile.Read (WithDsdChunkSize (TestBuilders.Dff.CreateMinimal (), (1UL << 62) - 2)).File!; + + Assert.AreEqual (ulong.MaxValue - 7, file.SampleCount); + } + + [TestMethod] + public void DsdChunkWhoseSampleCountIsPastSixtyFourBits_HasNoSampleCount () + { + var file = TagLibSharp2.Dff.DffFile.Read (PastTimeSpan[".huge.dff"] ()).File!; + + Assert.AreEqual (0UL, file.SampleCount); + } + + // The File Properties Object starts with its GUID; Play and Send Duration are 64 and 72 bytes into it. + internal static byte[] WithPlayDuration (byte[] wma, ulong ticks) + { + var at = FilePropertiesOffset (wma); + BinaryPrimitives.WriteUInt64LittleEndian (wma.AsSpan (at + 64), ticks); + BinaryPrimitives.WriteUInt64LittleEndian (wma.AsSpan (at + 72), ticks); + return wma; + } + + // A preroll that wraps 64 bits in 100 ns units (#193): the file plays for nothing, on every entry point. + [TestMethod] + [DynamicData (nameof (EntryRows))] + public void AsfPrerollPastThePlayDuration_IsZero (string entry) + { + var wma = WithPlayDuration (AsfTestBuilder.CreateMinimalWma (), 51_420_000); + BinaryPrimitives.WriteUInt64LittleEndian (wma.AsSpan (FilePropertiesOffset (wma) + 80), 1_844_674_407_370_956); + + var file = Open (wma, ".wma", entry); + + foreach (var (name, value, nullable) in Durations (file)) + AssertUnknown (value, nullable, $"{entry} {name}"); + } + + public static IEnumerable EntryRows () => Entries.Select (entry => new object[] { entry }); + + internal static int FilePropertiesOffset (byte[] wma) + { + byte[] guid = [0xA1, 0xDC, 0xAB, 0x8C, 0x47, 0xA9, 0xCF, 0x11, 0x8E, 0xE4, 0x00, 0xC0, 0x0C, 0x20, 0x53, 0x65]; + return wma.AsSpan ().IndexOf (guid); + } + + // avih: dwMicroSecPerFrame at 8, dwTotalFrames at 24 from the chunk ID. strh: dwScale, dwRate at 28, 32 and + // dwLength at 40 from the chunk ID. + static byte[] WithHugeAviHeaders (byte[] avi) + { + var avih = avi.AsSpan ().IndexOf ("avih"u8); + BinaryPrimitives.WriteUInt32LittleEndian (avi.AsSpan (avih + 8), uint.MaxValue); + BinaryPrimitives.WriteUInt32LittleEndian (avi.AsSpan (avih + 24), uint.MaxValue); + for (var at = 0; (at = avi.AsSpan (at).IndexOf ("strh"u8) is var i and >= 0 ? at + i : -1) >= 0; at += 4) { + BinaryPrimitives.WriteUInt32LittleEndian (avi.AsSpan (at + 28), uint.MaxValue); + BinaryPrimitives.WriteUInt32LittleEndian (avi.AsSpan (at + 32), 1); + BinaryPrimitives.WriteUInt32LittleEndian (avi.AsSpan (at + 40), uint.MaxValue); + } + + return avi; + } + + internal static object Open (byte[] bytes, string extension, string entry) + { + var name = "/file" + Path.GetExtension (extension); + var files = new MockFileSystem (); + files.AddFile (name, bytes); + if (entry.StartsWith ("format", StringComparison.Ordinal)) + return FormatRead (bytes, extension, entry == "format-path" ? name : null, files); + var skip = new MediaReadOptions { SkipPictures = true }; + var read = entry switch { + "stream" => MediaFile.Read (new MemoryStream (bytes, writable: false), name), + "path" => MediaFile.Read (name, files), + "async-path" => MediaFile.ReadAsync (name, files).GetAwaiter ().GetResult (), + "data" => MediaFile.ReadFromData (bytes, name), + "skip-stream" => MediaFile.Read (new MemoryStream (bytes, writable: false), skip, name), + "skip-path" => MediaFile.Read (name, skip, files), + "skip-async-path" => MediaFile.ReadAsync (name, skip, files).GetAwaiter ().GetResult (), + "skip-data" => MediaFile.ReadFromData (bytes, skip, name), + _ => throw new ArgumentException (entry, nameof (entry)), + }; + Assert.IsTrue (read.IsSuccess, $"{extension} {entry}: {read.Error}"); + return read.File!; + } + + // The format's own Read (span), or its ReadFromFile when a path is given. + static object FormatRead (byte[] bytes, string extension, string? path, MockFileSystem files) + { + var type = Path.GetExtension (extension) switch { + ".ape" => typeof (MonkeysAudioFile), + ".mpc" => typeof (MusepackFile), + ".dsf" => typeof (DsfFile), + ".dff" => typeof (TagLibSharp2.Dff.DffFile), + ".opus" => typeof (OggOpusFile), + ".ogg" => typeof (OggVorbisFile), + ".oga" => typeof (OggFlacFile), + ".m4a" => typeof (Mp4File), + ".wma" => typeof (AsfFile), + ".mkv" => typeof (MatroskaFile), + ".avi" => typeof (AviFile), + ".aif" => typeof (TagLibSharp2.Aiff.AiffFile), + ".wv" => typeof (TagLibSharp2.WavPack.WavPackFile), + ".wav" => typeof (WavFile), + _ => throw new ArgumentException (extension, nameof (extension)), + }; + object result = path is not null + ? ReadFromFile (type, path, files) + : type.GetMethod ("Read", [typeof (byte[])])?.Invoke (null, [bytes]) + ?? type.GetMethod ("Read", [typeof (BinaryData)])?.Invoke (null, [new BinaryData (bytes)]) + ?? ReadSpan (type, bytes); + var file = result.GetType ().GetProperty ("File")!.GetValue (result); + Assert.IsNotNull (file, $"{extension} {(path is null ? "span" : "path")}: {result.GetType ().GetProperty ("Error")!.GetValue (result)}"); + return file; + } + + // The format's ReadFromFile (path, fileSystem, ...), with the defaults of any later parameters. + static object ReadFromFile (Type type, string path, MockFileSystem files) + { + var method = type.GetMethods (BindingFlags.Public | BindingFlags.Static).First (m => m.Name == "ReadFromFile" + && m.GetParameters () is [{ ParameterType: var first }, { ParameterType: var second }, ..] + && first == typeof (string) && second == typeof (IFileSystem)); + var arguments = method.GetParameters ().Select ((p, i) => i == 0 ? path : i == 1 ? files : p.DefaultValue).ToArray (); + return method.Invoke (null, arguments)!; + } + + // Read (ReadOnlySpan) cannot be called through reflection; each format's is called here. + static object ReadSpan (Type type, byte[] bytes) => type.Name switch { + nameof (MonkeysAudioFile) => MonkeysAudioFile.Read (bytes), + nameof (MusepackFile) => MusepackFile.Read (bytes), + nameof (DsfFile) => DsfFile.Read (bytes), + "DffFile" => TagLibSharp2.Dff.DffFile.Read (bytes), + nameof (OggOpusFile) => OggOpusFile.Read (bytes), + nameof (OggVorbisFile) => OggVorbisFile.Read (bytes), + nameof (OggFlacFile) => OggFlacFile.Read (bytes), + nameof (Mp4File) => Mp4File.Read (bytes), + nameof (AsfFile) => AsfFile.Read (bytes), + nameof (MatroskaFile) => MatroskaFile.Read (bytes), + nameof (AviFile) => AviFile.Read (bytes), + "AiffFile" => TagLibSharp2.Aiff.AiffFile.Read (bytes), + "WavPackFile" => TagLibSharp2.WavPack.WavPackFile.Read (bytes), + nameof (WavFile) => WavFile.Read (bytes), + _ => throw new ArgumentException (type.Name, nameof (type)), + }; + + /// An unknown duration: null on a nullable property, zero on the others. + static void AssertUnknown (TimeSpan? value, bool nullable, string label) + { + if (nullable) + Assert.IsNull (value, label); + else + Assert.AreEqual (TimeSpan.Zero, value, label); + } + + /// + /// Every duration a caller can read from : its own Duration, its Properties' + /// Duration, and the audio and video properties of . + /// + internal static List<(string Name, TimeSpan? Value, bool Nullable)> Durations (object file) + { + var found = new List<(string, TimeSpan?, bool)> (); + void Add (string name, object? owner) + { + if (owner?.GetType ().GetProperty ("Duration", BindingFlags.Public | BindingFlags.Instance) is { } p) + found.Add ((name, (TimeSpan?)p.GetValue (owner), p.PropertyType == typeof (TimeSpan?))); + } + + Add ("Duration", file); + Add ("Properties.Duration", file.GetType ().GetProperty ("Properties")?.GetValue (file)); + if (file is IMediaFile media) { + Add ("AudioProperties.Duration", media.AudioProperties); + Add ("VideoProperties.Duration", media.VideoProperties); + } + + return found; + } +} diff --git a/tests/TagLibSharp2.Tests/Core/DurationsTests.cs b/tests/TagLibSharp2.Tests/Core/DurationsTests.cs new file mode 100644 index 00000000..43bfdd5e --- /dev/null +++ b/tests/TagLibSharp2.Tests/Core/DurationsTests.cs @@ -0,0 +1,54 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using TagLibSharp2.Core; + +namespace TagLibSharp2.Tests.Core; + +/// +/// The bounds of the one duration rule (#181): a positive finite value below 922,337,203,685 s (just under +/// , 922,337,203,685.4775807 s) is known; anything else is unknown. +/// +[TestClass] +[TestCategory ("Unit")] +public sealed class DurationsTests +{ + [TestMethod] + [DataRow (922_337_203_685d)] + [DataRow (1e14)] + [DataRow (double.PositiveInfinity)] + [DataRow (double.NaN)] + [DataRow (0d)] + [DataRow (-1d)] + public void Seconds_OutsideTheRange_AreUnknown (double seconds) + { + Assert.AreEqual (TimeSpan.Zero, Durations.FromSeconds (seconds)); + Assert.AreEqual (TimeSpan.Zero, Durations.FromSecondsToTicks (seconds)); + Assert.AreEqual (TimeSpan.Zero, Durations.FromTicks (seconds * TimeSpan.TicksPerSecond)); + } + + [TestMethod] + public void Seconds_InsideTheRange_AreKnown () + { + Assert.AreEqual (TimeSpan.FromSeconds (922_337_203_000d), Durations.FromSeconds (922_337_203_000d)); + Assert.AreEqual (TimeSpan.FromTicks (9_223_372_030_000_000_000), Durations.FromSecondsToTicks (922_337_203_000d)); + Assert.AreEqual (TimeSpan.FromTicks (9_223_372_030_000_000_000), Durations.FromTicks (9_223_372_030_000_000_000d)); + Assert.AreEqual (TimeSpan.FromTicks (1), Durations.FromTicks (0.6)); + } + + [TestMethod] + public void TickCounts_PastTheBound_AreUnknown () + { + Assert.AreEqual (TimeSpan.FromTicks (9_223_372_030_000_000_000), Durations.FromTickCount (9_223_372_030_000_000_000)); + Assert.AreEqual (TimeSpan.Zero, Durations.FromTickCount (9_223_372_036_860_000_000)); + Assert.AreEqual (TimeSpan.Zero, Durations.FromTickCount (0)); + Assert.AreEqual (TimeSpan.Zero, Durations.FromTickCount (ulong.MaxValue)); + } + + [TestMethod] + public void OrNull_IsNullForUnknownOnly () + { + Assert.IsNull (Durations.OrNull (TimeSpan.Zero)); + Assert.AreEqual (TimeSpan.FromTicks (1), Durations.OrNull (TimeSpan.FromTicks (1))); + } +} diff --git a/tests/TagLibSharp2.Tests/Core/EarlierSaveTests.cs b/tests/TagLibSharp2.Tests/Core/EarlierSaveTests.cs index ebe5f64f..adf0aa4d 100644 --- a/tests/TagLibSharp2.Tests/Core/EarlierSaveTests.cs +++ b/tests/TagLibSharp2.Tests/Core/EarlierSaveTests.cs @@ -2,7 +2,6 @@ // Licensed under the MIT License. See LICENSE file in the project root for full license information. using TagLibSharp2.Core; -using TagLibSharp2.Dsf; using static TagLibSharp2.Tests.Core.SpanSaveKit; namespace TagLibSharp2.Tests.Core; @@ -14,11 +13,11 @@ namespace TagLibSharp2.Tests.Core; /// /// Where the object describes what it wrote, that second save writes what a fresh read of those bytes with the /// same edit writes. -/// MP3, FLAC, AAC and MPEG-PS keep the offsets of the file they read (the ID3 tag size, the metadata size, the -/// stream's extent), and an -/// untagged DSF file that gains a tag keeps its untagged layout; a save from another file's bytes would apply them -/// to the wrong bytes, so it fails and writes nothing. -/// Audible takes the layout of the file it wrote only when it saved over its source. +/// MP3, FLAC, AAC, MPEG-PS and Audible keep the offsets of one file (the ID3 tag size, the metadata size, the +/// stream's extent, the TOC): the file they read, or the file they last saved over their source (#179). A save from +/// another file's bytes would apply them to the wrong bytes, so it fails and writes nothing. +/// A DSF file keeps its sound where the read found it, so it describes every file it saves, an untagged file +/// that gains a tag included (#179). /// /// [TestClass] @@ -43,14 +42,16 @@ public static IEnumerable Rows () } } - // Whether the object describes the file its first save wrote. Measured on main 88dfbe3f: the nine formats whose - // render parses the bytes it is given wrote that second save byte for byte as a fresh read does; MP3, FLAC and AAC - // wrote a different file (MP3 lost audio). - static bool Describes (string fixture, string first) => fixture switch { - ".mp3" or ".flac" or ".aac" or ".mpg" or ".untagged.dsf" => false, - ".aa" => first.StartsWith ("in-place", StringComparison.Ordinal), - _ => true, - }; + // Whether the object describes the file its first save wrote. The nine formats whose render parses the bytes it + // is given, and DSF and DFF, describe every file they save (measured on main 88dfbe3f: that second save matched a + // fresh read byte for byte). A format that keeps the offsets of one file describes it only when the save was over + // its source; on 01b8d6cc MP3, FLAC and AAC wrote a different file from any earlier save's bytes (MP3 lost audio). + static bool Describes (string fixture, string first) => + !TakesTheLayoutOfASaveOverItsSource (fixture) || first.StartsWith ("in-place", StringComparison.Ordinal); + + // The formats that keep the offsets of one file take those of the file a save wrote over their source, in place of + // the ones they had (#179). + static bool TakesTheLayoutOfASaveOverItsSource (string fixture) => fixture is ".aa" or ".mp3" or ".flac" or ".aac" or ".mpg"; // A DSF or DFF file read from memory holds its bytes and saves them, whatever bytes are passed (main's rule, // DffSaveStreamsAudioTests.SaveToFileAsync_WithOriginalData_MatchesTheSpanOverload). @@ -88,8 +89,8 @@ public async Task SpanSaveFromTheBytesOfAnEarlierSave (string fixture, string re CollectionAssert.AreEqual (await Fresh (fixture, written, "Second", files), files.ReadAllBytes ("/second" + Extension (fixture))); } - // The file it was read from stays a file it describes after a save, except for Audible, which takes the layout - // of the file it saved over its source. + // The file it was read from stays a file it describes after a save, except for a format that takes the layout of + // the file it saved over its source. [TestMethod] [DynamicData (nameof (Rows))] public async Task SpanSaveFromTheOriginalBytesAfterASave (string fixture, string read, string first, string second) @@ -98,14 +99,17 @@ public async Task SpanSaveFromTheOriginalBytesAfterASave (string fixture, string var files = new MockFileSystem (); var file = Open (fixture, read, original, files); Retitle (file, FirstTitle); - await FirstSave (file, fixture, first, original, files); + var written = await FirstSave (file, fixture, first, original, files); Retitle (file, "Second"); var saved = await SaveSpan (file, "/again" + Extension (fixture), original, second == "sync", files); - if (fixture == ".aa" && first.StartsWith ("in-place", StringComparison.Ordinal)) { + if (TakesTheLayoutOfASaveOverItsSource (fixture) && first.StartsWith ("in-place", StringComparison.Ordinal)) { Assert.IsFalse (saved.IsSuccess, "the save reported success"); - Assert.IsFalse (files.FileExists ("/again.aa"), "the save wrote a file"); + Assert.AreEqual ( + $"Cannot save this {Fixtures[fixture].Name} file: the original data is {original.Length} bytes, but the file it last saved over its source was {written.Length} bytes.", + saved.Error); + Assert.IsFalse (files.FileExists ("/again" + Extension (fixture)), "the save wrote a file"); return; } @@ -181,12 +185,4 @@ static async Task Fresh (string fixture, byte[] bytes, string title, Moc Assert.IsTrue (expected.IsSuccess, expected.Error); return files.ReadAllBytes ("/expected" + Extension (fixture)); } - - static void Retitle (IMediaFile file, string title) - { - if (file is DsfFile dsf) - dsf.EnsureId3v2Tag (); - Assert.IsNotNull (file.Tag, file.GetType ().Name + " has no tag to edit"); - file.Tag.Title = title; - } } diff --git a/tests/TagLibSharp2.Tests/Core/FormTrailSaveTests.cs b/tests/TagLibSharp2.Tests/Core/FormTrailSaveTests.cs new file mode 100644 index 00000000..5f5c2b7a --- /dev/null +++ b/tests/TagLibSharp2.Tests/Core/FormTrailSaveTests.cs @@ -0,0 +1,405 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Buffers.Binary; +using TagLibSharp2.Aiff; +using TagLibSharp2.Core; +using TagLibSharp2.Id3.Id3v2; +using TagLibSharp2.Id3.Id3v2.Frames; +using TagLibSharp2.Riff; +using TagLibSharp2.Tests.Kit; + +namespace TagLibSharp2.Tests.Core; + +/// +/// The bytes of a WAV or AIFF file after its RIFF or FORM form ends (#192, #197). They are not the form's chunks, but a +/// save wrote the form alone and dropped them: a form size short of the sound dropped the sound past it, and bytes that +/// are no chunk were lost. A save now writes them after the form as they were. An ID3v2 tag chunk a tagger appended +/// right after the form (exiftool reads it, and ffprobe in a WAV file), named as the format names it in either case, is +/// read as the file's tag chunk when the form holds none, on every entry point, so an edit writes the tag in the form +/// and leaves no stale copy after it for another reader to show. More such chunks right after it, or right after a form +/// with its own tag, are superseded: a save that rewrites the tag drops them, and one that leaves it as read carries +/// them. Every other byte after the form is carried as it was, a chunk whose tag reads no field among them. An ID3v2.2 +/// tag there, such as taglib-samples' sample.aif holds, is read and written in the form as ID3v2.3 (#187). +/// +[TestClass] +[TestCategory ("Unit")] +public sealed class FormTrailSaveTests +{ + const int Sound = 1024; + + const string AfterTheForm = "After the form"; + + static readonly string[] Formats = [".wav", ".aif"]; + + // tag-after-form: an ID3 chunk right after the form, as in sample.aif; tag-then-junk: that chunk, then 37 bytes that + // are no chunk; junk-after-form: those bytes alone; junk-then-tag: the bytes, then the chunk, which is then not right + // after the form; form-short-of-sound: the form's size 16 bytes short, so the last 16 bytes of the sound are after + // it; silent-tag-after-form: the chunk after a form with no sound (an empty data chunk; no SSND chunk), which a stream + // read leaves nothing in the file for; tag-in-form-and-after: a form with an ID3 chunk of its own, then the chunk; + // bad-tag-after-form: a chunk with the tag's identifier whose body is no ID3v2 tag, carried as it is; + // v23-tag-after-form: the chunk with an ID3v2.3 tag, read like the v2.4 one; v22-tag-after-form: the chunk with an + // ID3v2.2 tag, read like them too, and written in the form as ID3v2.3, as #187 writes a tag read as v2.2. Review 7 + // (N2 and nit 1): + // other-case-tag-after-form: the chunk named in the other case ("ID3 " after a WAV form, "id3 " after an AIFF one), + // read as the format's own; two-tags-after-form: the chunk, then a second one, which the first supersedes; + // empty-tag-after-form: a chunk whose ID3v2.3 header is followed by bytes that are no frame, so the read finds no + // field in it and carries it; tag-in-form-and-empty-after: that chunk after a form with a tag; cut-tag-after-form: + // the chunk with its last 10 bytes cut off, so it runs past the end of the file. A tag chunk right after the form + // whose tag the form already has (its own, or the one read from the chunk before it) is superseded: a save that + // rewrites the form's tag drops it, so no other reader shows the old title, and a save that leaves the tag as read + // carries it as it was. + static readonly string[] Shapes = ["tag-after-form", "tag-then-junk", "junk-after-form", "junk-then-tag", "form-short-of-sound", "silent-tag-after-form", "tag-in-form-and-after", "bad-tag-after-form", "v23-tag-after-form", "v22-tag-after-form", + "other-case-tag-after-form", "two-tags-after-form", "empty-tag-after-form", "tag-in-form-and-empty-after", "cut-tag-after-form"]; + + static readonly string[] Reads = ["path", "async-path", "data"]; + + static readonly string[] Saves = ["sync-path", "async-path", "sync-source", "async-source"]; + + static readonly bool[] Edits = [false, true]; + + public static IEnumerable Rows () => + from format in Formats + from shape in Shapes + from read in Reads + from save in Saves + from edit in Edits + select new object[] { format, shape, read, save, edit }; + + [TestMethod] + [DynamicData (nameof (Rows))] + public async Task BytesAfterTheForm_AreWrittenAfterItAsTheyWere (string format, string shape, string read, string save, bool edit) + { + var (bytes, carried, carriedOnEdit, title) = Build (format, shape); + if (edit) + carried = carriedOnEdit; + var files = new MockFileSystem (); + var file = SpanSaveKit.Open (format, read, bytes, files); + var duration = file.AudioProperties?.Duration; + Assert.AreEqual (title, file.Tag?.Title, "the title read"); + if (edit) + Retitle (file, "A new title"); + + var target = save.EndsWith ("source", StringComparison.Ordinal) ? "/in" + format : "/out" + format; + var result = await SpanSaveKit.SavePath (file, target, save.StartsWith ("sync", StringComparison.Ordinal), files); + + Assert.IsTrue (result.IsSuccess, result.Error); + var written = files.ReadAllBytes (target); + var trail = bytes.AsSpan (carried); + Assert.IsTrue (written.AsSpan ().EndsWith (trail), $"the {trail.Length} bytes carried, at the end as they were"); + Assert.AreEqual (written.Length - trail.Length, FormEnd (written, format), "the form, then those bytes and nothing else"); + var back = (IMediaFile)MediaFile.ReadFromData (written, "/back" + format).File!; + Assert.AreEqual (duration, back.AudioProperties?.Duration); + Assert.AreEqual (edit ? "A new title" : title, back.Tag?.Title); + // With no edit the form is written as it was read, so the sound in it and the sound after it are one run again. + // An edit adds a tag to the form, after the sound in it. + if (shape == "form-short-of-sound" && !edit) + Assert.IsGreaterThanOrEqualTo (0, written.AsSpan ().IndexOf (SoundBytes (bytes, format)), "the whole sound, in one run"); + } + + static readonly string[] EntryPoints = ["path", "async-path", "data", "stream", "async-stream", "skip-path", "skip-data", "skip-stream"]; + + public static IEnumerable ParityRows () => + from format in Formats + from shape in Shapes + select new object[] { format, shape }; + + // Every entry point reads the same title and duration, the SkipPictures reads among them. + [TestMethod] + [DynamicData (nameof (ParityRows))] + public void EveryEntryPoint_ReadsTheSameTag (string format, string shape) + { + var (bytes, _, _, title) = Build (format, shape); + foreach (var entry in EntryPoints) { + var file = ReadBy (entry, format, bytes); + Assert.AreEqual (title, file.Tag?.Title, entry); + Assert.AreEqual (ReadBy ("data", format, bytes).AudioProperties?.Duration, file.AudioProperties?.Duration, entry); + } + } + + // sample.aif, whose ID3 chunk follows the FORM's end, holds an ID3v2.2 tag (TT2, TP1, TAL and five more frames). + // Every entry point reads it, and a save, with no edit or a new title, sync and async, writes the tag in the FORM + // with nothing after it, keeping the other fields: exiftool and ffprobe then read the one tag. + [TestMethod] + [DataRow (true, false)] + [DataRow (false, false)] + [DataRow (true, true)] + [DataRow (false, true)] + public async Task SampleAif_V22TagAfterTheForm_IsReadAndWrittenInTheForm (bool sync, bool edit) + { + var bytes = File.ReadAllBytes (Corpus.Sample ("taglib-samples/sample.aif")); + Assert.IsLessThan (bytes.Length, FormEnd (bytes, ".aif"), "sample.aif has bytes after its FORM"); + foreach (var entry in EntryPoints) + Assert.AreEqual ("Aiff Title", ReadBy (entry, ".aif", bytes).Tag?.Title, entry); + var files = new MockFileSystem (); + files.AddFile ("/sample.aif", bytes); + var file = (IMediaFile)MediaFile.Read ("/sample.aif", files).File!; + if (edit) + Retitle (file, "A new title"); + + var result = await SpanSaveKit.SavePath (file, "/out.aif", sync, files); + + Assert.IsTrue (result.IsSuccess, result.Error); + var written = files.ReadAllBytes ("/out.aif"); + Assert.AreEqual (written.Length, FormEnd (written, ".aif"), "the FORM, with nothing after it"); + var back = ((IMediaFile)MediaFile.ReadFromData (written, "/back.aif").File!).Tag!; + Assert.AreEqual (edit ? "A new title" : "Aiff Title", back.Title); + Assert.AreEqual ("Aiff Album", back.Album); + Assert.AreEqual ("Aiff Artist", back.Performers?.Single ()); + } + + static IMediaFile ReadBy (string entry, string format, byte[] bytes) + { + var name = "/in" + format; + var skip = new MediaReadOptions { SkipPictures = true }; + if (!entry.StartsWith ("skip-", StringComparison.Ordinal)) + return SpanSaveKit.Open (format, entry, bytes, new MockFileSystem ()); + var files = new MockFileSystem (); + files.AddFile (name, bytes); + var result = entry switch { + "skip-path" => MediaFile.Read (name, skip, files), + "skip-data" => MediaFile.ReadFromData (bytes, skip, name), + _ => MediaFile.Read (new MemoryStream (bytes, writable: false), skip, name), + }; + Assert.IsTrue (result.IsSuccess, entry + ": " + result.Error); + return (IMediaFile)result.File!; + } + + static void Retitle (IMediaFile file, string title) + { + if (file is AiffFile aiff) + aiff.Title = title; + else + (((WavFile)file).Id3v2Tag ??= new Id3v2Tag ()).Title = title; + } + + // The shapes with a superseded tag chunk after the form. + static readonly string[] Superseded = ["tag-in-form-and-after", "two-tags-after-form"]; + + public static IEnumerable SupersededRows () => + from format in Formats + from shape in Superseded + from read in Reads + from save in Saves + select new object[] { format, shape, read, save }; + + // Removing the tag rewrites it too: the superseded chunk goes with it, so no read finds the old tag in its place. + [TestMethod] + [DynamicData (nameof (SupersededRows))] + public async Task RemovingTheTag_DropsTheSupersededChunk (string format, string shape, string read, string save) + { + var (bytes, _, carriedOnEdit, _) = Build (format, shape); + var files = new MockFileSystem (); + var file = SpanSaveKit.Open (format, read, bytes, files); + RemoveTag (file); + + var target = save.EndsWith ("source", StringComparison.Ordinal) ? "/in" + format : "/out" + format; + var result = await SpanSaveKit.SavePath (file, target, save.StartsWith ("sync", StringComparison.Ordinal), files); + + Assert.IsTrue (result.IsSuccess, result.Error); + var written = files.ReadAllBytes (target); + Assert.AreEqual (written.Length - (bytes.Length - carriedOnEdit), FormEnd (written, format), "the form, then nothing"); + Assert.IsNull (((IMediaFile)MediaFile.ReadFromData (written, "/back" + format).File!).Tag?.Title); + } + + // A second save over the source after one that dropped the superseded chunk copies the right bytes, with or without + // a second edit, whatever the second save decides (#212). + [TestMethod] + [DynamicData (nameof (SupersededTwiceRows))] + public async Task SavingAgainOverTheSource_AfterTheChunkWasDropped (string format, string shape, string second) + { + var (bytes, _, carriedOnEdit, _) = Build (format, shape); + var files = new MockFileSystem (); + var file = SpanSaveKit.Open (format, "path", bytes, files); + Retitle (file, "A new title"); + Assert.IsTrue ((await SpanSaveKit.SavePath (file, "/in" + format, sync: true, files)).IsSuccess); + if (second == "edit") + Retitle (file, "Again"); + else if (second == "back") + Retitle (file, ((IMediaFile)SpanSaveKit.Open (format, "data", bytes, new MockFileSystem ())).Tag!.Title!); + + var result = await SpanSaveKit.SavePath (file, "/in" + format, sync: true, files); + + Assert.IsTrue (result.IsSuccess, result.Error); + var written = files.ReadAllBytes ("/in" + format); + Assert.AreEqual (written.Length - (bytes.Length - carriedOnEdit), FormEnd (written, format), "the form, then the bytes after the dropped chunk"); + Assert.IsTrue (written.AsSpan ().EndsWith (bytes.AsSpan (carriedOnEdit))); + var back = ((IMediaFile)MediaFile.ReadFromData (written, "/back" + format).File!).Tag?.Title; + Assert.AreEqual (second switch { "edit" => "Again", "back" => file.Tag?.Title, _ => "A new title" }, back); + } + + static readonly string[] SecondSaves = ["none", "edit", "back"]; + + public static IEnumerable SupersededTwiceRows () => + from format in Formats + from shape in Superseded + from second in SecondSaves + select new object[] { format, shape, second }; + + // A SkipPictures read renders what a full read with its pictures cleared renders: clearing a picture from the form's + // tag rewrites it, so the superseded chunk is dropped from both. + [TestMethod] + [DynamicData (nameof (PictureRows))] + public void SkipPicturesRender_IsAFullReadWithItsPicturesCleared (string format, string shape) + { + var bytes = BuildWithPicture (format, shape); + var full = (IMediaFile)MediaFile.ReadFromData (bytes, "/in" + format).File!; + full.Tag!.Pictures = []; + // From a path: a SkipPictures read of bytes or a stream keeps no copy of the sound to render. + var skip = ReadBy ("skip-path", format, bytes); + + var expected = RenderOf (full); + CollectionAssert.AreEqual (expected, RenderOf (skip)); + Assert.AreEqual (FormEnd (expected, format), expected.Length, "the superseded chunk dropped"); + } + + public static IEnumerable PictureRows () => + from format in Formats + from shape in Superseded.Append ("picture-only-tag-after-form") + select new object[] { format, shape }; + + // The superseded shapes with a picture in the form's tag: in the form's own, or in the chunk read as it; and a chunk + // after the form whose tag holds a picture alone, which a SkipPictures read takes as a full read does, though the + // copy it reads holds no field. + static byte[] BuildWithPicture (string format, string shape) + { + var form = format == ".wav" ? TestBuilders.Wav.CreateMinimal (soundBytes: Sound) : TestBuilders.Aiff.CreateMinimal (soundBytes: Sound); + var tag = new Id3v2Tag (Id3v2Version.V24) { Title = "With a picture" }; + tag.Pictures = [new PictureFrame ("image/png", PictureType.FrontCover, "", new BinaryData ([1, 2, 3, 4]))]; + var pictured = Chunk (format, tag.Render ().ToArray ()); + var after = TagChunk (format, AfterTheForm); + if (shape == "picture-only-tag-after-form") { + tag.Title = null; + return [.. form, .. Chunk (format, tag.Render ().ToArray ())]; + } + + if (shape == "two-tags-after-form") + return [.. form, .. pictured, .. after]; + byte[] grown = [.. form, .. pictured]; + WriteSize (grown, format, (uint)(grown.Length - 8)); + return [.. grown, .. after]; + } + + static byte[] RenderOf (IMediaFile file) => file is AiffFile aiff ? aiff.Render ().ToArray () : ((WavFile)file).Render ().ToArray (); + + static void RemoveTag (IMediaFile file) + { + if (file is AiffFile aiff) + aiff.Id3v2Tag = null; + else + ((WavFile)file).Id3v2Tag = null; + } + + // A built file with Sound bytes of sound (none when silent), where the bytes a save carries after the form start + // when it leaves the tag as read and when it rewrites it, and the title a read finds. + static (byte[] Bytes, int Carried, int CarriedOnEdit, string? Title) Build (string format, string shape) + { + var (bytes, carried, title) = BuildShape (format, shape); + var carriedOnEdit = shape switch { + "tag-in-form-and-after" or "two-tags-after-form" => bytes.Length, + _ => carried, + }; + return (bytes, carried, carriedOnEdit, title); + } + + static (byte[] Bytes, int Carried, string? Title) BuildShape (string format, string shape) + { + var silent = shape == "silent-tag-after-form"; + var form = format == ".wav" ? TestBuilders.Wav.CreateMinimal (soundBytes: silent ? 0 : Sound) : TestBuilders.Aiff.CreateMinimal (soundBytes: Sound); + if (silent && format == ".aif") { + form = form[..form.AsSpan ().IndexOf ("SSND"u8)]; + BinaryPrimitives.WriteUInt32BigEndian (form.AsSpan (4), (uint)(form.Length - 8)); + } + + byte[] junk = [.. Enumerable.Repeat ((byte)0xA5, 37)]; + var chunk = TagChunk (format, AfterTheForm); + switch (shape) { + case "tag-after-form": + case "silent-tag-after-form": + return ([.. form, .. chunk], form.Length + chunk.Length, AfterTheForm); + case "v23-tag-after-form": { + var v23 = TagChunk (format, AfterTheForm, Id3v2Version.V23); + return ([.. form, .. v23], form.Length + v23.Length, AfterTheForm); + } + case "v22-tag-after-form": { + var v22 = Chunk (format, TestBuilders.Id3v2.CreateTagWithTextFrameV22 ("TT2", AfterTheForm)); + return ([.. form, .. v22], form.Length + v22.Length, AfterTheForm); + } + case "tag-then-junk": + return ([.. form, .. chunk, .. junk], form.Length + chunk.Length, AfterTheForm); + case "junk-after-form": + return ([.. form, .. junk], form.Length, null); + case "junk-then-tag": + return ([.. form, .. junk, .. chunk], form.Length, null); + case "bad-tag-after-form": { + byte[] bad = [.. chunk]; + bad[8] = (byte)'X'; + return ([.. form, .. bad], form.Length, null); + } + case "tag-in-form-and-after": { + byte[] grown = [.. form, .. TagChunk (format, "In the form")]; + WriteSize (grown, format, (uint)(grown.Length - 8)); + return ([.. grown, .. chunk], grown.Length, "In the form"); + } + case "other-case-tag-after-form": { + byte[] other = [.. chunk]; + (format == ".wav" ? "ID3 "u8 : "id3 "u8).CopyTo (other); + return ([.. form, .. other], form.Length + other.Length, AfterTheForm); + } + case "two-tags-after-form": + return ([.. form, .. chunk, .. TagChunk (format, "Second")], form.Length + chunk.Length, AfterTheForm); + case "empty-tag-after-form": + return ([.. form, .. EmptyTagChunk (format)], form.Length, null); + case "tag-in-form-and-empty-after": { + byte[] grown = [.. form, .. TagChunk (format, "In the form")]; + WriteSize (grown, format, (uint)(grown.Length - 8)); + return ([.. grown, .. EmptyTagChunk (format)], grown.Length, "In the form"); + } + case "cut-tag-after-form": + return ([.. form, .. chunk[..^10]], form.Length, null); + default: { + var size = format == ".wav" ? BinaryPrimitives.ReadUInt32LittleEndian (form.AsSpan (4)) : BinaryPrimitives.ReadUInt32BigEndian (form.AsSpan (4)); + WriteSize (form, format, size - 16); + return (form, form.Length - 16, null); + } + } + } + + // An ID3 chunk with an ID3v2.4 tag of the title: "id3 " in a WAV, "ID3 " in an AIFF. Its body is even. + static byte[] TagChunk (string format, string title, Id3v2Version version = Id3v2Version.V24) => + Chunk (format, new Id3v2Tag (version) { Title = title }.Render ().ToArray ()); + + // An ID3 chunk whose ID3v2.3 header declares 40 bytes of body that are no frame (review 7's d-trail-garbage-body). + static byte[] EmptyTagChunk (string format) => + Chunk (format, [(byte)'I', (byte)'D', (byte)'3', 3, 0, 0, 0, 0, 0, 40, .. Enumerable.Repeat ((byte)0xFF, 40)]); + + static byte[] Chunk (string format, byte[] tag) + { + var header = new byte[8]; + (format == ".wav" ? "id3 "u8 : "ID3 "u8).CopyTo (header); + if (format == ".wav") + BinaryPrimitives.WriteUInt32LittleEndian (header.AsSpan (4), (uint)tag.Length); + else + BinaryPrimitives.WriteUInt32BigEndian (header.AsSpan (4), (uint)tag.Length); + return [.. header, .. tag, .. (tag.Length % 2 == 1 ? new byte[1] : [])]; + } + + static void WriteSize (byte[] form, string format, uint size) + { + if (format == ".wav") + BinaryPrimitives.WriteUInt32LittleEndian (form.AsSpan (4), size); + else + BinaryPrimitives.WriteUInt32BigEndian (form.AsSpan (4), size); + } + + // Where the form of a RIFF or FORM file ends by its declared size. + static int FormEnd (byte[] bytes, string format) => + 8 + (int)(format == ".wav" ? BinaryPrimitives.ReadUInt32LittleEndian (bytes.AsSpan (4)) : BinaryPrimitives.ReadUInt32BigEndian (bytes.AsSpan (4))); + + // The sound bytes: the data chunk's or the SSND chunk's, after SSND's offset and block size. + static byte[] SoundBytes (byte[] bytes, string format) + { + var at = bytes.AsSpan ().IndexOf (format == ".wav" ? "data"u8 : "SSND"u8) + 8 + (format == ".wav" ? 0 : 8); + return bytes.AsSpan (at, bytes.Length - at).ToArray (); + } +} diff --git a/tests/TagLibSharp2.Tests/Core/InPlaceSaveBoundsTests.cs b/tests/TagLibSharp2.Tests/Core/InPlaceSaveBoundsTests.cs new file mode 100644 index 00000000..3c3365a2 --- /dev/null +++ b/tests/TagLibSharp2.Tests/Core/InPlaceSaveBoundsTests.cs @@ -0,0 +1,115 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Buffers.Binary; +using TagLibSharp2.Core; +using TagLibSharp2.Id3.Id3v2; +using TagLibSharp2.Image; +using TagLibSharp2.Tests.Aac; +using TagLibSharp2.Tests.Image; +using TagLibSharp2.Tests.Kit; +using TagLibSharp2.Tests.Mpeg; +using static TagLibSharp2.Tests.Core.SpanSaveKit; + +namespace TagLibSharp2.Tests.Core; + +/// +/// A save over its source reads the source back to see whether it wrote over it (#179): the bytes it wrote at their +/// offsets, in chunks, never the payload. Measured on real files at payloads of 1 MiB and 4 MiB, an in-place save of +/// an audio file stays under a fixed ceiling. A PNG, JPEG or GIF object holds its whole file, and after a save over +/// its source it holds the file it wrote: that costs one copy of the file. +/// +[TestClass] +[TestCategory ("Unit")] +[DoNotParallelize] +public sealed class InPlaceSaveBoundsTests +{ + const int N = 1024 * 1024; + const long Ceiling = 256 * 1024; + + static readonly Dictionary> Audio = new () { + [".mp3"] = n => [.. new Id3v2Tag { Title = "Title" }.Render ().Span, .. Mp3Frames (n / 417), .. TestBuilders.Id3v1.CreateTag (title: "Title")], + [".flac"] = n => [.. TestBuilders.Flac.CreateWithVorbisComment (title: "Title"), .. Sound (n)], + [".aac"] = n => [.. AacTestBuilder.Id3v2Bytes ("Title"), .. AacTestBuilder.Adts (n / 1024, length: 1024), .. AacTestBuilder.Id3v1Bytes ("Back")], + [".mpg"] = n => [ + .. new Id3v2Tag { Title = "Title" }.Render ().Span, + .. MpegPsTestBuilder.ProgramStream (new MpegPsTestBuilder.Options { + VideoFrames = 1, AudioFrames = 0, AudioKind = MpegPsTestBuilder.Audio.None, PaddingBytes = n, PaddingPack = 1 })], + [".untagged.dsf"] = UntaggedDsf, + }; + + [TestMethod] + [DataRow (".mp3")] + [DataRow (".flac")] + [DataRow (".aac")] + [DataRow (".mpg")] + [DataRow (".untagged.dsf")] + public void InPlaceSave_StaysUnderACeilingAsThePayloadGrows (string fixture) + { + var one = InPlaceSave (Audio[fixture] (N), Extension (fixture)); + var four = InPlaceSave (Audio[fixture] (4 * N), Extension (fixture)); + + Assert.IsLessThanOrEqualTo (Ceiling, one, $"{fixture} at 1 MiB"); + Assert.IsLessThanOrEqualTo (Ceiling, four, $"{fixture} at 4 MiB"); + } + + [TestMethod] + public void ImageInPlaceSave_CopiesTheFileOnce () + { + static byte[] Png (int n) => ImageTestBuilder.Concat ( + ImageTestBuilder.PngSignature, + ImageTestBuilder.PngChunk ("IHDR", [0, 0, 0, 2, 0, 0, 0, 3, 8, 0, 0, 0, 0]), + ImageTestBuilder.Text ("Comment", "Old"), + ImageTestBuilder.PngChunk ("IDAT", new byte[n]), + ImageTestBuilder.PngChunk ("IEND", [])); + + var one = InPlaceSave (Png (N), ".png"); + var four = InPlaceSave (Png (4 * N), ".png"); + + // The file is copied once more for each 3 MiB it grows, and not twice. + Assert.IsGreaterThanOrEqualTo (3L * N, four - one); + Assert.IsLessThan (6L * N, four - one); + } + + // TestBuilders.Dsf.CreateMinimal with n bytes of sound: the DSD chunk's file size (offset 12) and the data + // chunk's size (offset 84) grow with it. + static byte[] UntaggedDsf (int n) + { + var head = TestBuilders.Dsf.CreateMinimal ()[..92]; + BinaryPrimitives.WriteUInt64LittleEndian (head.AsSpan (12), (ulong)(92 + n)); + BinaryPrimitives.WriteUInt64LittleEndian (head.AsSpan (84), (ulong)(12 + n)); + return [.. head, .. Sound (n)]; + } + + // The least a save over the source allocates once the object describes that file, edited each time. + static long InPlaceSave (byte[] bytes, string extension) + { + var dir = Path.Combine (Path.GetTempPath (), "tls-inplace-" + Guid.NewGuid ().ToString ("N")); + Directory.CreateDirectory (dir); + try { + var path = Path.Combine (dir, "in" + extension); + File.WriteAllBytes (path, bytes); + var read = MediaFile.Read (path); + Assert.IsTrue (read.IsSuccess, read.Error); + var file = (IMediaFile)read.File!; + var edits = 0; + FileWriteResult saved = default; + var allocated = Bounds.LeastAllocated (() => { + Edit (file, "Saved " + edits++); + saved = SavePath (file, null, sync: true, DefaultFileSystem.Instance).GetAwaiter ().GetResult (); + }); + Assert.IsTrue (saved.IsSuccess, saved.Error); + return allocated; + } finally { + Directory.Delete (dir, recursive: true); + } + } + + static void Edit (IMediaFile file, string text) + { + if (file is StillImageFile image) + image.Tag!.Comment = text; + else + Retitle (file, text); + } +} diff --git a/tests/TagLibSharp2.Tests/Core/LookalikeSaveTests.cs b/tests/TagLibSharp2.Tests/Core/LookalikeSaveTests.cs new file mode 100644 index 00000000..6d731f49 --- /dev/null +++ b/tests/TagLibSharp2.Tests/Core/LookalikeSaveTests.cs @@ -0,0 +1,117 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using TagLibSharp2.Aac; +using TagLibSharp2.Ape; +using TagLibSharp2.Core; +using TagLibSharp2.Id3; +using TagLibSharp2.Id3.Id3v2; +using TagLibSharp2.Mpeg; +using TagLibSharp2.Tests.Aac; +using TagLibSharp2.Tests.Image; +using TagLibSharp2.Tests.Mpeg; +using static TagLibSharp2.Tests.Core.SpanSaveKit; + +namespace TagLibSharp2.Tests.Core; + +/// +/// A save elsewhere can write a file of the source's length with another layout: a tag in front grown by the 128 bytes +/// of an ID3v1 tag it dropped, or an ID3v1 tag in place of a 128-byte tag in front. The source is untouched, so the +/// object must keep the layout of the source (#179): the read-back compares the bytes the save wrote, not the length +/// alone. The next save in place writes what a fresh read of the source, given the same edits, writes. +/// +[TestClass] +[TestCategory ("Unit")] +public sealed class LookalikeSaveTests +{ + static readonly string Grown = new ('x', 128); + + public static IEnumerable Rows () => Cases.Keys.Select (key => new object[] { key }); + + static readonly Dictionary Build, Action Elsewhere, Action InPlace)> Cases = new () { + ["mp3: the ID3v1 tag's bytes moved to the tag in front"] = (".mp3", + () => [.. new Id3v2Tag { Title = "Title" }.Render ().Span, .. Mp3Frames (20), .. TestBuilders.Id3v1.CreateTag (title: "Title")], + file => { var mp3 = (Mp3File)file; mp3.Id3v1Tag = null; mp3.Id3v2Tag!.Title = "Title" + Grown; }, + file => ((Mp3File)file).Id3v2Tag!.Title = "Next"), + ["mp3: an ID3v1 tag in place of a 128-byte tag in front"] = (".mp3", + () => [.. Id3v2Of128Bytes (), .. Mp3Frames (20)], + file => { var mp3 = (Mp3File)file; mp3.Id3v2Tag = null; mp3.Id3v1Tag = Id3v1 ("Added"); }, + file => ((Mp3File)file).Id3v1Tag!.Title = "Next"), + ["aac: the ID3v1 tag's bytes moved to the tag in front"] = (".aac", + () => [.. AacTestBuilder.Id3v2Bytes ("Title"), .. AacTestBuilder.Adts (8), .. AacTestBuilder.Id3v1Bytes ("Back")], + file => { var aac = (AacFile)file; aac.Id3v1Tag = null; aac.Id3v2Tag!.Title = "Title" + Grown; }, + file => ((AacFile)file).Id3v2Tag!.Title = "Next"), + ["aac: an ID3v1 tag in place of a 128-byte tag in front"] = (".aac", + () => [.. Id3v2Of128Bytes (), .. AacTestBuilder.Adts (8)], + file => { var aac = (AacFile)file; aac.Id3v2Tag = null; aac.Id3v1Tag = Id3v1 ("Added"); }, + file => ((AacFile)file).Id3v1Tag!.Title = "Next"), + ["mpg: the ID3v1 tag's bytes moved to the tag in front"] = (".mpg", + () => [.. new Id3v2Tag { Title = "Title" }.Render ().Span, .. MpegPsTestBuilder.ProgramStream (), .. MpegPsFileTests.Id3v1 ("Back")], + file => { var mpg = (MpegPsFile)file; mpg.Id3v1Tag = null; mpg.Id3v2Tag!.Title = "Title" + Grown; }, + file => ((MpegPsFile)file).Id3v2Tag!.Title = "Next"), + ["mpg: an ID3v1 tag in place of a 128-byte tag in front"] = (".mpg", + () => [.. Id3v2Of128Bytes (), .. MpegPsTestBuilder.ProgramStream ()], + file => { var mpg = (MpegPsFile)file; mpg.Id3v2Tag = null; mpg.Id3v1Tag = Id3v1 ("Added"); }, + file => ((MpegPsFile)file).Id3v1Tag!.Title = "Next"), + ["aac: an APEv2 tag in place of a 128-byte tag in front"] = (".aac", + () => [.. Id3v2Of128Bytes (), .. AacTestBuilder.Adts (8)], + file => { var aac = (AacFile)file; aac.Id3v2Tag = null; aac.ApeTag = Ape128 (); }, + file => ((AacFile)file).ApeTag!.Artist = "Next"), + // The appended tag is rewritten, so the tag in front goes (RenderPrependedId3v2); the appended one grows by + // the front tag's length. + ["mpg: an appended tag grown by the length of the tag in front it drops"] = (".mpg", + () => [.. FrontTag (), .. MpegPsTestBuilder.ProgramStream (), .. MpegPsAppendedTagTests.Appended ("App"), .. MpegPsFileTests.Id3v1 ("Back")], + file => ((MpegPsFile)file).Id3v2Tag!.Title = "App" + new string ('x', FrontTag ().Length), + file => ((MpegPsFile)file).Id3v2Tag!.Title = "Next"), + // The comment after the image data goes; a title of the same chunk length is written in front of it. + ["png: a title chunk in front of the image data in place of a comment after it"] = (".png", + () => ImageTestBuilder.Concat ( + ImageTestBuilder.PngSignature, + ImageTestBuilder.PngChunk ("IHDR", [0, 0, 0, 2, 0, 0, 0, 3, 8, 0, 0, 0, 0]), + ImageTestBuilder.PngChunk ("IDAT", new byte[300]), + ImageTestBuilder.Text ("Comment", "Old"), + ImageTestBuilder.PngChunk ("IEND", [])), + file => { file.Tag!.Comment = null; file.Tag.Title = "ABCDE"; }, + file => file.Tag!.Title = "Next"), + }; + + [TestMethod] + [DynamicData (nameof (Rows))] + public async Task SaveInPlaceAfterALookalikeSaveElsewhere_WritesWhatAFreshReadWrites (string name) + { + var (extension, build, elsewhere, inPlace) = Cases[name]; + var original = build (); + var files = new MockFileSystem (); + var file = Open (extension, "path", original, files); + elsewhere (file); + Assert.IsTrue ((await SavePath (file, "/else" + extension, sync: true, files)).IsSuccess); + Assert.HasCount (original.Length, files.ReadAllBytes ("/else" + extension), "the save elsewhere has the source's length"); + inPlace (file); + + var saved = await SavePath (file, null, sync: true, files); + + Assert.IsTrue (saved.IsSuccess, saved.Error); + files.AddFile ("/oracle" + extension, original); + var fresh = (IMediaFile)MediaFile.Read ("/oracle" + extension, files).File!; + elsewhere (fresh); + inPlace (fresh); + Assert.IsTrue ((await SavePath (fresh, null, sync: true, files)).IsSuccess); + CollectionAssert.AreEqual (files.ReadAllBytes ("/oracle" + extension), files.ReadAllBytes ("/in" + extension)); + } + + // An ID3v2.3 tag of exactly 128 bytes: the header, a TIT2 frame "Title" (ISO-8859-1), and zero padding + // (ID3v2.3 section 3.0: the size excludes the 10-byte header). + static byte[] Id3v2Of128Bytes () + { + byte[] frame = [.. "TIT2"u8, 0, 0, 0, 6, 0, 0, 0, .. "Title"u8]; + byte[] header = [.. "ID3"u8, 3, 0, 0, 0, 0, 0, 118]; + return [.. header, .. frame, .. new byte[128 - header.Length - frame.Length]]; + } + + static byte[] FrontTag () => new Id3v2Tag (Id3v2Version.V24) { Title = "Front" }.Render ().ToArray (); + + // An APEv2 tag of 128 bytes with its header: 32 + one 64-byte item ("Title", 50 characters: 8 + 5 + 1 + 50) + 32. + static ApeTag Ape128 () => new () { Title = new string ('a', 50) }; + + static Id3v1Tag Id3v1 (string title) => Id3v1Tag.Read (TestBuilders.Id3v1.CreateTag (title: title)).Tag!; +} diff --git a/tests/TagLibSharp2.Tests/Core/PathSaveCancellationTests.cs b/tests/TagLibSharp2.Tests/Core/PathSaveCancellationTests.cs index 344d3e50..d02a1172 100644 --- a/tests/TagLibSharp2.Tests/Core/PathSaveCancellationTests.cs +++ b/tests/TagLibSharp2.Tests/Core/PathSaveCancellationTests.cs @@ -135,16 +135,18 @@ public async Task ShortSource_BeatsAnAlreadyCancelledToken (string kind, string Assert.IsFalse (fs.FileExists (Destination)); } + // A declared size past memory is a size past the bytes present: the save writes the bytes present (#197), so it + // reaches the token, where it used to throw "Cannot render an AIFF file larger than supported memory." first. [TestMethod] - public async Task AiffDeclaredSizePastMemory_BeatsAnAlreadyCancelledToken () + public async Task AiffDeclaredSizePastMemory_IsCancelledWithoutThrowing () { var fs = new ProbeFileSystem (); var file = Open ("aiff-huge", fs); - var thrown = await Assert.ThrowsExactlyAsync ( - () => Save (file, Destination, fs, Cancelled ())); + var save = await Save (file, Destination, fs, Cancelled ()); - Assert.AreEqual ("Cannot render an AIFF file larger than supported memory.", thrown.Message); + Assert.IsFalse (save.IsSuccess); + Assert.AreEqual ("Operation was cancelled", save.Error); Assert.IsFalse (fs.FileExists (Destination)); } @@ -228,8 +230,9 @@ public static IEnumerable StreamingKinds () public static IEnumerable ShortSources () { - yield return ["flac", "Failed to render FLAC file"]; - yield return ["dsf", "Failed to render DSF file"]; + // A FLAC source of another length is not a file the object describes (#179); the fixture is 74 bytes. + yield return ["flac", "Cannot save this FLAC file: the source file is 1 bytes, but the file it was read from was 74 bytes."]; + yield return ["dsf", "Cannot render this DSF file: the source no longer holds the sound it was read with."]; yield return ["vorbis", "Failed to render Ogg Vorbis file"]; yield return ["opus", "Failed to render Ogg Opus file"]; yield return ["oggflac", "Failed to render Ogg FLAC file"]; diff --git a/tests/TagLibSharp2.Tests/Core/PathSaveChainTests.cs b/tests/TagLibSharp2.Tests/Core/PathSaveChainTests.cs new file mode 100644 index 00000000..9cff40c2 --- /dev/null +++ b/tests/TagLibSharp2.Tests/Core/PathSaveChainTests.cs @@ -0,0 +1,192 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using TagLibSharp2.Ape; +using TagLibSharp2.Core; +using TagLibSharp2.Id3; +using TagLibSharp2.Id3.Id3v2; +using TagLibSharp2.Tests.Aac; +using TagLibSharp2.Tests.Mpeg; +using TagLibSharp2.Xiph; +using static TagLibSharp2.Tests.Core.SpanSaveKit; + +namespace TagLibSharp2.Tests.Core; + +/// +/// A file read from a path is saved, edited and saved again (#179). Each save after the first reads the file the save +/// before it left on disk, so it must write what a fresh read of that file, given the same edit, writes. On 01b8d6cc +/// an MP3, FLAC, AAC or untagged DSF file applied the offsets of the first read to the file the first save wrote and +/// wrote a damaged file, and MPEG-PS refused the second save. +/// +[TestClass] +[TestCategory ("Unit")] +public sealed class PathSaveChainTests +{ + // Each title has a length of its own, so each save moves what follows the tag. The first outgrows the padding + // a format keeps for its tags. + static readonly string[] Titles = [ + "A first title that is longer than the one it was read with " + new string ('x', 4000), + "Second", + "A third title, longer than the second " + new string ('y', 700), + ]; + + // How the first save is made. Every later save is over the source, by SourcePath. + // in-place: over the source by SourcePath. alias: over the source by another spelling of its path (MockFileSystem + // compares paths without case). elsewhere: to another file. span: a span save over the source from the bytes read. + static readonly string[] FirstSaves = ["in-place", "alias", "elsewhere", "span"]; + + // Tag layouts beyond SpanSaveKit's one file per format: each part a save moves or keeps (an ID3v1 tag, an APEv2 + // tag with and without a header, a Lyrics3 block, a tag appended after an MPEG stream, an update tag, the ID3 tag + // a save gives an untagged DSD file) has to be where the next save looks for it. + static readonly Dictionary> Shapes = new () { + [".v1only.mp3"] = () => [.. Mp3Frames (100), .. TestBuilders.Id3v1.CreateTag (title: "Title")], + [".bare.mp3"] = () => Mp3Frames (100), + [".tails.aac"] = () => [ + .. AacTestBuilder.Id3v2Bytes ("Title"), .. AacTestBuilder.Adts (8), + .. new ApeTag { Title = "Ape" }.RenderWithOptions (includeHeader: false).Span, + .. AacTestBuilder.Lyrics3V2 (), .. AacTestBuilder.Id3v1Bytes ("Back")], + // A tag in front far longer than the ones the chain writes, so a tail found from the read's audio start + // would start past the trailing tags of a later save. + [".big.tails.aac"] = () => [ + .. AacTestBuilder.Id3v2Bytes ("Big " + new string ('b', 9000)), .. AacTestBuilder.Adts (8), + .. new ApeTag { Title = "Ape" }.RenderWithOptions (includeHeader: false).Span, + .. AacTestBuilder.Lyrics3V2 (), .. AacTestBuilder.Id3v1Bytes ("Back")], + [".ape.aac"] = () => [.. AacTestBuilder.Adts (8), .. AacTestBuilder.ApeBytes ("Ape"), .. AacTestBuilder.Id3v1Bytes ("Back")], + [".appended.mpg"] = () => [ + .. MpegPsTestBuilder.ProgramStream (), .. MpegPsAppendedTagTests.Appended ("Appended"), + .. TestBuilders.Ape.CreateTag (title: "Ape"), .. MpegPsFileTests.Id3v1 ("Footer")], + [".untagged.dff"] = () => TestBuilders.Dff.CreateMinimal (), + [".update.mpg"] = () => [ + .. new Id3v2Tag (Id3v2Version.V24) { Title = "Front", Album = "Front Album" }.Render ().Span, + .. MpegPsTestBuilder.ProgramStream (), .. MpegPsAppendedTagTests.UpdateTag ("Back")], + }; + + static byte[] Build (string fixture) => Shapes.TryGetValue (fixture, out var build) ? build () : Fixtures[fixture].Build (); + + public static IEnumerable Rows () + { + foreach (var fixture in Fixtures.Keys.Concat (Shapes.Keys)) + foreach (var read in new[] { "path", "async-path", "format-path" }) + foreach (var first in FirstSaves) + foreach (var overload in new[] { "sync", "async" }) + yield return [fixture, read, first, overload]; + } + + [TestMethod] + [DynamicData (nameof (Rows))] + public async Task LaterSaves_WriteWhatAFreshReadOfTheFileOnDiskWrites (string fixture, string read, string first, string overload) + { + var original = Build (fixture); + var files = new MockFileSystem (); + var source = "/in" + Extension (fixture); + var file = Open (fixture, read, original, files); + var sync = overload == "sync"; + + Retitle (file, Titles[0]); + var saved = first switch { + "alias" => await SavePath (file, source.ToUpperInvariant (), sync, files), + "elsewhere" => await SavePath (file, "/else" + Extension (fixture), sync, files), + "span" => await SaveSpan (file, source, original, sync, files), + _ => await SavePath (file, null, sync, files), + }; + Assert.IsTrue (saved.IsSuccess, "first save: " + saved.Error); + + for (var i = 1; i < Titles.Length; i++) { + var before = files.ReadAllBytes (source); + Retitle (file, Titles[i]); + + var again = await SavePath (file, null, sync, files); + + Assert.IsTrue (again.IsSuccess, $"save {i + 1}: {again.Error}"); + CollectionAssert.AreEqual (FreshPathSave (fixture, before, Titles[i], files), files.ReadAllBytes (source), $"save {i + 1}"); + } + } + + // The whole tags a file holds, by property: each is dropped and then given back as a new tag, one save per step, + // so each save adds or removes a tag where the save before it left one (or none). + static readonly string[] WholeTags = ["Id3v2Tag", "Id3v1Tag", "ApeTag", "VorbisComment"]; + + public static IEnumerable TagRows () + { + foreach (var fixture in Fixtures.Keys.Concat (Shapes.Keys)) + foreach (var first in FirstSaves) + foreach (var overload in new[] { "sync", "async" }) + yield return [fixture, first, overload]; + } + + [TestMethod] + [DynamicData (nameof (TagRows))] + public async Task WholeTagSteps_WriteWhatAFreshReadOfTheFileOnDiskWrites (string fixture, string first, string overload) + { + var original = Build (fixture); + var files = new MockFileSystem (); + var source = "/in" + Extension (fixture); + var file = Open (fixture, "path", original, files); + var sync = overload == "sync"; + var steps = TagSteps (file); + if (steps.Count == 0) + return; + + steps[0] (file); + var saved = first switch { + "alias" => await SavePath (file, source.ToUpperInvariant (), sync, files), + "elsewhere" => await SavePath (file, "/else" + Extension (fixture), sync, files), + "span" => await SaveSpan (file, source, original, sync, files), + _ => await SavePath (file, null, sync, files), + }; + Assert.IsTrue (saved.IsSuccess, "first save: " + saved.Error); + + for (var i = 1; i < steps.Count; i++) { + var before = files.ReadAllBytes (source); + steps[i] (file); + + var again = await SavePath (file, null, sync, files); + + Assert.IsTrue (again.IsSuccess, $"step {i + 1}: {again.Error}"); + CollectionAssert.AreEqual (FreshPathSave (fixture, before, steps[i], files), files.ReadAllBytes (source), $"step {i + 1}"); + } + } + + // Drop, then add, each whole tag the file's type can set. + static List> TagSteps (object file) + { + var steps = new List> (); + foreach (var name in WholeTags) { + var property = file.GetType ().GetProperty (name); + if (property?.SetMethod is not { IsPublic: true }) + continue; + var title = "New " + name; + steps.Add (target => target.GetType ().GetProperty (name)!.SetValue (target, null)); + steps.Add (target => { + Tag tag = name switch { + "Id3v2Tag" => new Id3v2Tag (), + "Id3v1Tag" => new Id3v1Tag (), + "ApeTag" => new ApeTag (), + _ => new VorbisComment ("New"), + }; + tag.Title = title; + target.GetType ().GetProperty (name)!.SetValue (target, tag); + }); + } + + return steps; + } + + // The bytes a fresh path read of `bytes`, given `title` and saved over its source, writes. + static byte[] FreshPathSave (string fixture, byte[] bytes, string title, MockFileSystem files) => + FreshPathSave (fixture, bytes, file => Retitle ((IMediaFile)file, title), files); + + // The bytes a fresh path read of `bytes`, given `edit` and saved over its source, writes. + static byte[] FreshPathSave (string fixture, byte[] bytes, Action edit, MockFileSystem files) + { + var path = "/oracle" + Extension (fixture); + files.AddFile (path, bytes); + var read = MediaFile.Read (path, files); + Assert.IsTrue (read.IsSuccess, "oracle read: " + read.Error); + var fresh = read.File!; + edit (fresh); + var saved = SavePath (fresh, null, sync: true, files).GetAwaiter ().GetResult (); + Assert.IsTrue (saved.IsSuccess, "oracle save: " + saved.Error); + return files.ReadAllBytes (path); + } +} diff --git a/tests/TagLibSharp2.Tests/Core/PathSaveSourceTests.cs b/tests/TagLibSharp2.Tests/Core/PathSaveSourceTests.cs new file mode 100644 index 00000000..f3ed4a97 --- /dev/null +++ b/tests/TagLibSharp2.Tests/Core/PathSaveSourceTests.cs @@ -0,0 +1,48 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using TagLibSharp2.Core; +using static TagLibSharp2.Tests.Core.SpanSaveKit; + +namespace TagLibSharp2.Tests.Core; + +/// +/// MP3, FLAC, AAC and MPEG-PS copy the payload of a path save from their source at the offsets of the file they +/// describe (#179). When the file on disk is no longer one of a length they describe (another program rewrote it, or +/// the read-back after a save over it failed), those offsets do not fit it: the save fails, names the lengths, and +/// writes nothing. On 01b8d6cc MP3, FLAC and AAC wrote a damaged file. +/// +[TestClass] +[TestCategory ("Unit")] +public sealed class PathSaveSourceTests +{ + public static IEnumerable Rows () + { + foreach (var fixture in new[] { ".mp3", ".flac", ".aac" }) + foreach (var change in new[] { "longer", "shorter" }) + foreach (var save in new[] { "in-place", "in-place-async", "elsewhere", "elsewhere-async" }) + yield return [fixture, change, save]; + } + + [TestMethod] + [DynamicData (nameof (Rows))] + public async Task SourceOfAnotherLength_FailsAndWritesNothing (string fixture, string change, string save) + { + var original = Fixtures[fixture].Build (); + var files = new MockFileSystem (); + var file = Open (fixture, "path", original, files); + byte[] changed = change == "longer" ? [.. new byte[1000], .. original] : original[100..]; + files.AddFile ("/in" + fixture, changed); + Retitle (file, "Changed"); + + var target = save.StartsWith ("in-place", StringComparison.Ordinal) ? null : "/out" + fixture; + var saved = await SavePath (file, target, !save.EndsWith ("-async", StringComparison.Ordinal), files); + + Assert.IsFalse (saved.IsSuccess, "the save reported success"); + Assert.AreEqual ( + $"Cannot save this {Fixtures[fixture].Name} file: the source file is {changed.Length} bytes, but the file it was read from was {original.Length} bytes.", + saved.Error); + CollectionAssert.AreEqual (changed, files.ReadAllBytes ("/in" + fixture)); + Assert.IsFalse (files.FileExists ("/out" + fixture), "the save wrote a file"); + } +} diff --git a/tests/TagLibSharp2.Tests/Core/RatePastIntTests.cs b/tests/TagLibSharp2.Tests/Core/RatePastIntTests.cs new file mode 100644 index 00000000..1f7067e1 --- /dev/null +++ b/tests/TagLibSharp2.Tests/Core/RatePastIntTests.cs @@ -0,0 +1,197 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Buffers.Binary; +using TagLibSharp2.Asf; +using TagLibSharp2.Core; +using TagLibSharp2.Riff; +using TagLibSharp2.Tests.Asf; + +namespace TagLibSharp2.Tests.Core; + +/// +/// A sample rate or byte rate field holds an unsigned 32-bit value; one past was cast to a +/// negative int and read as a negative sample rate or bit rate (#194). Such a sample rate is no sample rate (0), +/// as WavPack's reader already rules; a byte rate is scaled in 64 bits, so its bit rate is the real one. Every format +/// that stores the rate as a 32-bit field is given 2^31, read on every entry point. +/// +[TestClass] +[TestCategory ("Unit")] +public sealed class RatePastIntTests +{ + const uint PastInt = 0x8000_0000; + + static readonly Dictionary> RatePastInt = new () { + // fmt: sample rate 4 bytes into the chunk's data, then the byte rate (24 and 28 from the file's start). + [".wav"] = () => { + var wav = TestBuilders.Wav.CreateMinimal (soundBytes: 4000); + BinaryPrimitives.WriteUInt32LittleEndian (wav.AsSpan (24), PastInt); + BinaryPrimitives.WriteUInt32LittleEndian (wav.AsSpan (28), PastInt); + return wav; + }, + // COMM holds the rate as an 80-bit extended float 8 bytes into its data: 2^40 Hz, exponent 16383 + 40. + [".aif"] = () => { + var aiff = TestBuilders.Aiff.CreateMinimal (); + var rate = aiff.AsSpan ().IndexOf ("COMM"u8) + 8 + 8; + BinaryPrimitives.WriteUInt16BigEndian (aiff.AsSpan (rate), 16383 + 40); + BinaryPrimitives.WriteUInt64BigEndian (aiff.AsSpan (rate + 2), 1UL << 63); + return aiff; + }, + [".dsf"] = () => TestBuilders.Dsf.CreateMinimal (sampleRate: unchecked((int)PastInt)), + [".dff"] = () => TestBuilders.Dff.CreateMinimal (sampleRate: unchecked((int)PastInt)), + [".ape"] = () => TestBuilders.MonkeysAudio.CreateMinimal (sampleRate: unchecked((int)PastInt)), + [".wma"] = () => AsfTestBuilder.CreateMinimalWma (sampleRate: PastInt), + // mdhd version 0: timescale 4 + 8 bytes into its payload. A timescale past 65535 is the sample rate. + [".m4a"] = () => { + var m4a = TestBuilders.Mp4.CreateMinimalM4a (Mp4CodecType.Aac); + var mdhd = m4a.AsSpan ().IndexOf ("mdhd"u8); + BinaryPrimitives.WriteUInt32BigEndian (m4a.AsSpan (mdhd + 4 + 4 + 8), PastInt); + return m4a; + }, + }; + + public static IEnumerable Rows () => + from extension in RatePastInt.Keys + from entry in DurationUnknownTests.Entries + select new object[] { extension, entry }; + + [TestMethod] + [DynamicData (nameof (Rows))] + public void SampleRatePastInt_IsNoSampleRate (string extension, string entry) + { + var file = (IMediaFile)DurationUnknownTests.Open (RatePastInt[extension] (), extension, entry); + + var audio = file.AudioProperties; + Assert.IsNotNull (audio, $"{extension} {entry}"); + Assert.AreEqual (0, audio.SampleRate, $"{extension} {entry}"); + Assert.IsGreaterThanOrEqualTo (0, audio.Bitrate, $"{extension} {entry}"); + // A file type with its own SampleRate (Monkey's Audio, DSDIFF) reads the same rule. + if (file.GetType ().GetProperty ("SampleRate") is { PropertyType: var type } own && type == typeof (int)) + Assert.AreEqual (0, (int)own.GetValue (file)!, $"{extension} {entry} {file.GetType ().Name}.SampleRate"); + } + + // A byte rate past int.MaxValue with a sample rate that fits: the bit rate is the byte rate times 8 over 1000. + [TestMethod] + [DynamicData (nameof (EntryRows))] + public void WavByteRatePastInt_GivesItsBitRate (string entry) + { + var wav = TestBuilders.Wav.CreateMinimal (soundBytes: 4000); + BinaryPrimitives.WriteUInt32LittleEndian (wav.AsSpan (28), uint.MaxValue); + + var file = (IMediaFile)DurationUnknownTests.Open (wav, ".wav", entry); + + Assert.AreEqual (44_100, file.AudioProperties!.SampleRate, entry); + Assert.AreEqual ((int)(uint.MaxValue * 8L / 1000), file.AudioProperties.Bitrate, entry); + } + + public static IEnumerable EntryRows () => DurationUnknownTests.Entries.Select (entry => new object[] { entry }); + + // DSF stores its channel count as a 32-bit field too: 2^31 channels is no channel count, and the bit rate (sample + // rate times channels) is not negative. + [TestMethod] + [DynamicData (nameof (EntryRows))] + public void DsfChannelCountPastInt_IsNoChannelCount (string entry) + { + var file = (IMediaFile)DurationUnknownTests.Open (TestBuilders.Dsf.CreateMinimal (channels: unchecked((int)PastInt)), ".dsf", entry); + + Assert.AreEqual (0, file.AudioProperties!.Channels, entry); + Assert.AreEqual (0, ((TagLibSharp2.Dsf.DsfFile)file).Channels, entry); + Assert.IsGreaterThanOrEqualTo (0, file.AudioProperties.Bitrate, entry); + } + + // DSDIFF's bit rate is the sample rate times the channels: 2^30 Hz over 4,096 channels is 4.4e9 kbps, past an + // int, so 0, where the cast wrapped it. + [TestMethod] + [DynamicData (nameof (EntryRows))] + public void DffBitRatePastInt_IsZero (string entry) + { + var dff = TestBuilders.Dff.CreateMinimal (sampleRate: 1 << 30); + BinaryPrimitives.WriteUInt16BigEndian (dff.AsSpan (dff.AsSpan ().IndexOf ("CHNL"u8) + 12), 4096); + + var file = (IMediaFile)DurationUnknownTests.Open (dff, ".dff", entry); + + Assert.AreEqual (1 << 30, file.AudioProperties!.SampleRate, entry); + Assert.AreEqual (0, file.AudioProperties.Bitrate, entry); + } + + // The rule's edges: the largest int is a sample rate, one more is none; a real number rounds first. + [TestMethod] + [DataRow (0u, 0)] + [DataRow (44_100u, 44_100)] + [DataRow (2_147_483_647u, int.MaxValue)] + [DataRow (2_147_483_648u, 0)] + [DataRow (uint.MaxValue, 0)] + public void SampleRateField (uint field, int expected) => Assert.AreEqual (expected, Rates.SampleRate (field)); + + [TestMethod] + [DataRow (44_100.4, 44_100)] + [DataRow (2_147_483_647.4, int.MaxValue)] + [DataRow (2_147_483_647.6, 0)] + [DataRow (-1.0, 0)] + [DataRow (double.NaN, 0)] + [DataRow (double.PositiveInfinity, 0)] + public void SampleRateReal (double value, int expected) => Assert.AreEqual (expected, Rates.SampleRate (value)); + + [TestMethod] + [DataRow (128_000L, 128)] + [DataRow (2_147_483_647_999L, int.MaxValue)] + [DataRow (2_147_483_648_000L, 0)] + [DataRow (-1_000L, 0)] + public void KbpsOfBitsPerSecond (long bits, int expected) => Assert.AreEqual (expected, Rates.Kbps (bits)); + + public static IEnumerable SaveRows () => + from file in SaveFiles + from read in SaveReads + from overload in Overloads + select new object[] { file, read, overload }; + + static readonly string[] SaveFiles = ["rate", "fmt-size"]; + + static readonly string[] SaveReads = ["format-path", "path", "async-path"]; + + static readonly string[] Overloads = ["sync", "async", "source"]; + + // A WAV file without a sample rate (its fmt rate past int.MaxValue, or a fmt chunk whose size runs past the data, + // the review's wav-fmt-ffff.wav) is not a WAV file a save can render: the save returns a failure and writes nothing, + // where it threw InvalidOperationException ("Cannot render invalid WAV file") out of Render. + [TestMethod] + [DynamicData (nameof (SaveRows))] + public async Task WavWithoutASampleRate_SaveFailsAndWritesNothing (string file, string read, string overload) + { + var original = TestBuilders.Wav.CreateMinimal (soundBytes: 4000); + BinaryPrimitives.WriteUInt32LittleEndian (original.AsSpan (file == "rate" ? 24 : 16), file == "rate" ? PastInt : uint.MaxValue); + var files = new MockFileSystem (); + files.AddFile ("/in.wav", original); + var wav = read switch { + "format-path" => WavFile.ReadFromFile ("/in.wav", files).File!, + "path" => (WavFile)MediaFile.Read ("/in.wav", files).File!, + _ => (WavFile)MediaFile.ReadAsync ("/in.wav", files).GetAwaiter ().GetResult ().File!, + }; + wav.InfoTag = new RiffInfoTag { Title = "Retitled" }; + + var saved = overload switch { + "sync" => wav.SaveToFile ("/in.wav", files), + "async" => await wav.SaveToFileAsync ("/in.wav", files), + _ => await wav.SaveToFileAsync (files), + }; + + Assert.IsFalse (saved.IsSuccess, "the save reported success"); + Assert.AreEqual (file == "rate" ? "Cannot save a WAV file that has no sample rate." : "Cannot save a WAV file that has no data chunk.", saved.Error); + CollectionAssert.AreEqual (original, files.ReadAllBytes ("/in.wav")); + } + + // A WAV file whose RIFF structure is no longer valid (here, disposed) is told apart from one without a sample rate. + [TestMethod] + public void WavWithAnInvalidRiffStructure_SaySo () + { + var files = new MockFileSystem (); + files.AddFile ("/in.wav", TestBuilders.Wav.CreateMinimal (soundBytes: 4000)); + var wav = WavFile.ReadFromFile ("/in.wav", files).File!; + wav.Dispose (); + + var saved = wav.SaveToFile ("/out.wav", files); + + Assert.AreEqual ("Cannot save a WAV file whose RIFF structure is invalid.", saved.Error); + Assert.IsFalse (files.FileExists ("/out.wav")); + } +} diff --git a/tests/TagLibSharp2.Tests/Core/SaveNeverThrowsTests.cs b/tests/TagLibSharp2.Tests/Core/SaveNeverThrowsTests.cs new file mode 100644 index 00000000..4c22ea0f --- /dev/null +++ b/tests/TagLibSharp2.Tests/Core/SaveNeverThrowsTests.cs @@ -0,0 +1,324 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Buffers.Binary; +using System.Text; +using TagLibSharp2.Core; +using TagLibSharp2.Tests.Image; +using TagLibSharp2.Tests.Kit; +using TagLibSharp2.Tests.Matroska; + +namespace TagLibSharp2.Tests.Core; + +/// +/// A save never throws on malformed input (#196): it writes the file, or returns a failure and writes nothing. Every +/// format's built file is mutated byte by byte (0x00 and 0xFF at each of its first bytes, and the 0xFFFFFFFF of a +/// streamed writer stamped at each offset), and every mutant that reads is saved on every save entry point: over its +/// source and to a path, sync and async, and from the bytes in memory where the format has that overload. A save that +/// reports success must also have written the file it read: the written file reads as the source did (its audio or +/// image properties and title), and it holds the source's payload, the bytes where a save of the unmutated file keeps +/// its longest run, but for a few header bytes a save may rewrite (review 4: a save that wrote an AIFF file's SSND empty reported success and passed a +/// test that looked only for throws). +/// +[TestClass] +[TestCategory ("Unit")] +public sealed class SaveNeverThrowsTests +{ + // How far into each file the bytes are mutated: past every header and chunk size of the built files. + const int Span = 96; + + static readonly Dictionary> Extra = new () { + [".wav"] = () => TestBuilders.Wav.CreateMinimal (soundBytes: 1024), + [".aif"] = Aiff, + // The review's aif-comm-19.aif: a COMM size of 19 in place of 18, so it takes the first byte of SSND's header. + [".comm19.aif"] = () => { + var aiff = Aiff (); + BinaryPrimitives.WriteUInt32BigEndian (aiff.AsSpan (aiff.AsSpan ().IndexOf ("COMM"u8) + 4), 19); + return aiff; + }, + [".m4a"] = () => TestBuilders.Mp4.CreateMinimalM4a (Mp4CodecType.Aac), + [".png"] = () => ImageTestBuilder.Png (ImageTestBuilder.Text ("Comment", "Old"), ImageTestBuilder.PngChunk ("prVt", SpanSaveKit.Sound (256))), + [".gif"] = () => ImageTestBuilder.Concat (ImageTestBuilder.GifScreen (1, 1, flags: 0), ImageTestBuilder.GifComment ("Old"), ImageTestBuilder.GifImage (512), [0x3B]), + [".jpg"] = () => ImageTestBuilder.Concat ( + [0xFF, 0xD8], + ImageTestBuilder.JpegSegment (0xFE, "Old"u8.ToArray ()), + ImageTestBuilder.JpegSegment (0xC0, [0x08, 0x00, 0x01, 0x00, 0x01, 0x01, 0x01, 0x11, 0x00]), + ImageTestBuilder.JpegSegment (0xDA, [0x01, 0x01, 0x00, 0x00, 0x3F, 0x00]), + SpanSaveKit.Sound (512).Select (b => b == 0xFF ? (byte)0x11 : b).ToArray (), + [0xFF, 0xD9]), + [".mkv"] = () => MatroskaFileTests.Matroska (MatroskaFileTests.Master (0x18538067, + MatroskaFileTests.Master (0x1549A966, MatroskaFileTests.Element (0x4489, MatroskaFileTests.Float32 (1000f))), + MatroskaFileTests.Master (0x1F43B675, MatroskaFileTests.Element (0xA3, SpanSaveKit.Sound (256))))), + // Review 4's six formats with no fixture here; each carries pixels, or bytes after the image, past the mutated span. + [".bmp"] = () => { + var bmp = ImageTestBuilder.Bmp (4, 2, length: 54 + 24); + BinaryPrimitives.WriteInt32LittleEndian (bmp.AsSpan (2), bmp.Length); + BinaryPrimitives.WriteInt32LittleEndian (bmp.AsSpan (10), 54); + SpanSaveKit.Sound (24).CopyTo (bmp, 54); + return [.. bmp, .. SpanSaveKit.Sound (96)]; + }, + [".pcx"] = () => [.. ImageTestBuilder.Pcx (0, 0, 7, 7, planes: 1), .. SpanSaveKit.Sound (128)], + [".pgm"] = () => [.. "P5\n8 8\n255\n"u8.ToArray (), .. SpanSaveKit.Sound (64), .. SpanSaveKit.Sound (96)], + [".tif"] = () => [.. ImageTestBuilder.TiffImage (2, 3), .. new byte[64], .. SpanSaveKit.Sound (96)], + [".dng"] = () => [.. ImageTestBuilder.TiffImage (2, 3, dng: true), .. new byte[64], .. SpanSaveKit.Sound (96)], + [".svg"] = () => Encoding.UTF8.GetBytes ( + "" + + "a description long enough to run past the mutated span of the file"), + }; + + // What the property finds on main as well, each an issue of its own: the mutated bytes, and what the save does. A + // listed byte that stops failing is reported, so the fix takes its entry out. Each one found so far is fixed (#199 to + // #204). + static readonly Dictionary Known = new () { + }; + + // Not gaps: a size the mutant changed makes the read take payload bytes for something else, and the save writes the + // file it read. A chunk size that grows into, or stops short of, the next chunk has the bytes after it read as + // chunks, whose sizes the save writes as the bytes they hold. (A FORM or RIFF size made smaller than its chunks is no + // longer here: the bytes after the form are written after it as they were, #192 and #197.) + static readonly Dictionary ReadOtherwise = new () { + [".aif"] = ([19, 45], "COMM grown into SSND (19), SSND 8 bytes short (45)"), + [".comm19.aif"] = ([19], "COMM grown further into SSND (19)"), + }; + + // The fixtures whose bytes past the mutated span hold no run a save keeps: the whole file is header and tag. Their + // saves are held to the read-back alone. Monkey's Audio and WavPack left this list when a save began to keep the + // APEv2 tag's header (#217): their saves now keep a run of 16 bytes or more past the span. + static readonly HashSet NoPayloadPastSpan = [".mpc"]; + + // Stereo, 16 bits, 1,024 bytes of sound: COMM counts its 256 frames. + static byte[] Aiff () + { + var aiff = TestBuilders.Aiff.CreateMinimal (soundBytes: 1024); + BinaryPrimitives.WriteUInt32BigEndian (aiff.AsSpan (aiff.AsSpan ().IndexOf ("COMM"u8) + 10), 256); + return aiff; + } + + public static IEnumerable Fixtures () => + SpanSaveKit.Fixtures.Keys.Concat (Extra.Keys).Select (fixture => new object[] { fixture }); + + static byte[] Build (string fixture) => Extra.TryGetValue (fixture, out var build) ? build () : SpanSaveKit.Fixtures[fixture].Build (); + + [TestMethod] + [DynamicData (nameof (Fixtures))] + public async Task EveryMutant_SavesOrFailsWithoutThrowing (string fixture) + { + var valid = Build (fixture); + var extension = Path.GetExtension (fixture); + var payload = await Payload (valid, extension, fixture); + var report = new StringBuilder (); + var thrown = 0; + var saves = 0; + var knownSeen = new HashSet (); + foreach (var (offset, label, bytes) in Mutants (valid)) { + foreach (var read in Reads) { + var files = new MockFileSystem (); + var source = "/in" + extension; + files.AddFile (source, bytes); + object? file; + try { + file = Open (read, source, bytes, files); + } catch (Exception ex) when (ex is not AssertFailedException) { + continue; // reads are another test's business; only files that read are saved + } + if (file is null) + continue; + var expected = Describe ((IMediaFile)file); + + foreach (var save in Saves) { + if (save.StartsWith ("span", StringComparison.Ordinal) && !SpanSaveKit.HasSpanSave (file)) + continue; + if (save.EndsWith ("in-place", StringComparison.Ordinal) && !SpanSaveKit.HasInPlaceSave (file, save.StartsWith ("sync", StringComparison.Ordinal))) + continue; + // Only the path saves write somewhere else; the span and in-place saves write over the source. + var target = save.EndsWith ("path", StringComparison.Ordinal) ? "/out" + extension : source; + var before = files.FileExists (target) ? files.ReadAllBytes (target) : null; + saves++; + try { + var result = await Save (file, save, source, bytes, files); + var after = files.FileExists (target) ? files.ReadAllBytes (target) : null; + if (!result.IsSuccess && !SameBytes (before, after)) + Note ($"{label} {read} {save}: failed with \"{result.Error}\" and wrote {after?.Length} bytes"); + if (result.IsSuccess && WrittenFileDiffers (after!, extension, expected, payload is { } range ? bytes.AsSpan (range) : []) is { } differs) { + if (Listed (fixture).Contains (offset)) + knownSeen.Add (offset); + else + Note ($"{label} {read} {save}: succeeded, and {differs}"); + } + } catch (Exception ex) when (ex is not AssertFailedException) { + Note ($"{label} {read} {save}: {ex.GetType ().Name}: {ex.Message}"); + } + } + + (file as IDisposable)?.Dispose (); + } + } + + foreach (var gap in Listed (fixture).Where (o => !knownSeen.Contains (o))) + Note ($"the listed byte {gap} no longer fails: take it out of Known or ReadOtherwise"); + + Assert.AreEqual (0, thrown, $"{fixture}: {thrown} of {saves} saves threw, wrote on failure, or wrote a file unlike the one read:{report}"); + + void Note (string line) + { + if (++thrown <= 8) + report.Append ("\n ").Append (line); + } + } + + // A file object made with a public parameterless constructor, with nothing read into it, is saved to a path, sync + // and async: the save fails or writes, and never throws. (A new AiffFile threw "Cannot render invalid AIFF file".) + public static IEnumerable Constructible () => + typeof (MediaFile).Assembly.GetTypes () + .Where (type => typeof (IMediaFile).IsAssignableFrom (type) && !type.IsAbstract && type.GetConstructor (Type.EmptyTypes) is { IsPublic: true }) + .Select (type => new object[] { type.Name }); + + [TestMethod] + [DynamicData (nameof (Constructible))] + public async Task NewFileObject_SaveFailsOrWritesWithoutThrowing (string typeName) + { + var type = typeof (MediaFile).Assembly.GetTypes ().Single (t => t.Name == typeName); + var files = new MockFileSystem (); + object file = Activator.CreateInstance (type)!; + + var sync = await SpanSaveKit.SavePath (file, "/new.bin", sync: true, files); + var async = await SpanSaveKit.SavePath (file, "/new-async.bin", sync: false, files); + + Assert.IsTrue (sync.IsSuccess || !files.FileExists ("/new.bin"), typeName + ": a failed save wrote"); + Assert.IsTrue (async.IsSuccess || !files.FileExists ("/new-async.bin"), typeName + ": a failed save wrote"); + } + + static readonly string[] Reads = ["path", "data"]; + + static readonly string[] Saves = ["sync-path", "async-path", "sync-source", "async-source", "span-sync", "span-async", "sync-in-place", "async-in-place"]; + + static object? Open (string read, string source, byte[] bytes, MockFileSystem files) + { + var result = read == "path" ? MediaFile.Read (source, files) : MediaFile.ReadFromData (bytes, source); + return result.IsSuccess ? result.File : null; + } + + static Task Save (object file, string save, string source, byte[] bytes, MockFileSystem files) => save switch { + "sync-path" => SpanSaveKit.SavePath (file, "/out" + Path.GetExtension (source), sync: true, files), + "async-path" => SpanSaveKit.SavePath (file, "/out" + Path.GetExtension (source), sync: false, files), + "sync-source" => SpanSaveKit.SavePath (file, source, sync: true, files), + "async-source" => SpanSaveKit.SavePath (file, source, sync: false, files), + "span-sync" => SpanSaveKit.SaveSpan (file, source, bytes, sync: true, files), + "span-async" => SpanSaveKit.SaveSpan (file, source, bytes, sync: false, files), + "sync-in-place" => SpanSaveKit.SavePath (file, null, sync: true, files), + _ => SpanSaveKit.SavePath (file, null, sync: false, files), + }; + + static string Describe (IMediaFile file) => EntryAgreement.Describe (file) + "/" + file.ImageProperties; + + // Null when the written file reads as the source did and holds the payload, else what differs. + static IEnumerable Listed (string fixture) => + (Known.TryGetValue (fixture, out var known) ? known.Offsets : []).Concat (ReadOtherwise.TryGetValue (fixture, out var other) ? other.Offsets : []); + + static string? WrittenFileDiffers (byte[] written, string extension, string expected, ReadOnlySpan payload) + { + var back = MediaFile.ReadFromData (written, "/back" + extension); + var actual = back.IsSuccess ? Describe ((IMediaFile)back.File!) : "FAIL " + back.Error; + (back.File as IDisposable)?.Dispose (); + if (actual != expected) + return $"the written file reads {actual}, the source {expected}"; + if (payload.IsEmpty) + return null; + if (!RewritesPageHeaders (extension)) + return written.AsSpan ().IndexOf (payload) < 0 ? $"the written file ({written.Length} bytes) does not hold the payload's {payload.Length} bytes whole" : null; + var kept = Kept (written, payload); + return kept < 0.5 ? $"the written file ({written.Length} bytes) holds {kept:P0} of the payload's {payload.Length} bytes" : null; + } + + // An Ogg save rewrites every page header it copies (the serial, the sequence and the CRC), and in these small pages + // those are inside the payload's run; every other format's save copies the payload as it is, and must hold it whole. + static bool RewritesPageHeaders (string extension) => extension is ".ogg" or ".opus" or ".oga"; + + // The share of the payload's 8-byte windows the written file holds anywhere: a payload copied whole is 1 and one + // written empty (review 4's B1) is 0. Half is the Ogg bar because a save rewrites header bytes inside the run (an + // Ogg page's serial and CRC), which in these small pages break more than a quarter of the windows. + static double Kept (byte[] written, ReadOnlySpan payload) + { + const int Window = 8; + var windows = new HashSet (); + for (var at = 0; at + Window <= written.Length; at++) + windows.Add (BinaryPrimitives.ReadUInt64LittleEndian (written.AsSpan (at))); + var count = payload.Length - Window + 1; + var found = 0; + for (var at = 0; at < count; at++) { + if (windows.Contains (BinaryPrimitives.ReadUInt64LittleEndian (payload[at..]))) + found++; + } + + return count <= 0 ? 1 : (double)found / count; + } + + // Where the payload is: the longest run of the file that a save of the unmutated file keeps both as it is and with a + // new title. That is the sound or the pixels, not a tag a title rewrites. A mutant's payload is its own bytes there: + // sound a mutant changes is still sound, and a save copies it as it is. + static async Task Payload (byte[] valid, string extension, string fixture) + { + var kept = new List (); + foreach (var retitle in new[] { false, true }) { + var files = new MockFileSystem (); + files.AddFile ("/valid" + extension, valid); + var read = MediaFile.Read ("/valid" + extension, files); + Assert.IsTrue (read.IsSuccess, read.Error); + var file = (IMediaFile)read.File!; + if (retitle && file.Tag is null) + continue; + if (retitle) + file.Tag!.Title = "A title that rewrites the tag"; + var saved = await SpanSaveKit.SavePath (file, "/saved" + extension, sync: true, files); + Assert.IsTrue (saved.IsSuccess, saved.Error); + kept.Add (files.ReadAllBytes ("/saved" + extension)); + } + + // Past the mutated bytes, where no mutant changes the payload and a save must copy it whole; an Ogg save rewrites + // page headers, and its payload is the longest run anywhere, held by half. + var (bestStart, bestLength) = (0, 0); + for (var start = RewritesPageHeaders (extension) ? 0 : Math.Min (Span + 3, valid.Length); start + bestLength < valid.Length; start++) { + // Grow the run at this start while every saved file still holds it. + var length = bestLength + 1; + while (start + length <= valid.Length && KeptByAll (kept, valid.AsSpan (start, length))) + (bestStart, bestLength) = (start, length++); + } + + var listed = NoPayloadPastSpan.Contains (fixture); + Assert.AreEqual (listed, bestLength < 16, $"{fixture}: the longest run a save keeps is {bestLength} bytes; NoPayloadPastSpan should {(listed ? "not " : "")}list it"); + return listed ? null : bestStart..(bestStart + bestLength); + } + + static bool KeptByAll (List kept, ReadOnlySpan run) + { + foreach (var file in kept) { + if (file.AsSpan ().IndexOf (run) < 0) + return false; + } + + return true; + } + + static bool SameBytes (byte[]? a, byte[]? b) => a is null ? b is null : b is not null && a.AsSpan ().SequenceEqual (b); + + // 0x00 and 0xFF at each of the first Span bytes, and 0xFFFFFFFF over each 4 bytes there. + static IEnumerable<(int Offset, string Label, byte[] Bytes)> Mutants (byte[] valid) + { + var end = Math.Min (valid.Length, Span); + for (var offset = 0; offset < end; offset++) { + foreach (var value in new byte[] { 0x00, 0xFF }) { + if (valid[offset] == value) + continue; + var bytes = (byte[])valid.Clone (); + bytes[offset] = value; + yield return (offset, $"[{offset}]=0x{value:X2}", bytes); + } + + if (offset + 4 <= valid.Length) { + var stamped = (byte[])valid.Clone (); + BinaryPrimitives.WriteUInt32LittleEndian (stamped.AsSpan (offset), uint.MaxValue); + yield return (offset, $"[{offset}..+4]=0xFFFFFFFF", stamped); + } + } + } +} diff --git a/tests/TagLibSharp2.Tests/Core/SavedOverSourceTests.cs b/tests/TagLibSharp2.Tests/Core/SavedOverSourceTests.cs new file mode 100644 index 00000000..26ade5ce --- /dev/null +++ b/tests/TagLibSharp2.Tests/Core/SavedOverSourceTests.cs @@ -0,0 +1,146 @@ +// 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 static TagLibSharp2.Tests.Core.SpanSaveKit; + +namespace TagLibSharp2.Tests.Core; + +/// +/// The read-back that tells a format whether its save rewrote its source (#179): the file's length, and the bytes the +/// save wrote at their offsets. +/// +[TestClass] +[TestCategory ("Unit")] +public sealed class SavedOverSourceTests +{ + // Longer than one 64 KiB copy chunk, so a part is compared in more than one read. + static readonly byte[] File = [.. Sound (70_000)]; + + static MockFileSystem Disk () + { + var files = new MockFileSystem (); + files.AddFile ("/f", File); + return files; + } + + [TestMethod] + public void Holds_TheBytesAtTheirOffsets_IsTrue () => + Assert.IsTrue (SavedOverSource.Holds ("/f", Disk (), File.Length, + new WrittenBytes (0, File.AsMemory (0, 66_000)), + new WrittenBytes (69_000, File.AsMemory (69_000)))); + + [TestMethod] + public void Holds_NoParts_IsTheLengthAlone () + { + Assert.IsTrue (SavedOverSource.Holds ("/f", Disk (), File.Length)); + Assert.IsFalse (SavedOverSource.Holds ("/f", Disk (), File.Length - 1)); + } + + [TestMethod] + [DataRow (0)] + [DataRow (65_536)] + [DataRow (69_999)] + public void Holds_ADifferentByte_IsFalse (int at) + { + var expected = (byte[])File.Clone (); + expected[at] ^= 0x80; + + Assert.IsFalse (SavedOverSource.Holds ("/f", Disk (), File.Length, new WrittenBytes (0, expected))); + } + + [TestMethod] + public void Holds_APartPastTheEnd_IsFalse () => + Assert.IsFalse (SavedOverSource.Holds ("/f", Disk (), File.Length, new WrittenBytes (File.Length - 1, File.AsMemory (0, 2)))); + + // The file ends after the bytes that match: the rest of the part is not there. + [TestMethod] + public void Holds_APartThatRunsPastTheEnd_IsFalse () => + Assert.IsFalse (SavedOverSource.Holds ("/f", Disk (), File.Length, new WrittenBytes (File.Length - 1, new byte[] { File[^1], 0 }))); + + [TestMethod] + public void Holds_ANegativeOffset_IsFalse () => + Assert.IsFalse (SavedOverSource.Holds ("/f", Disk (), File.Length, new WrittenBytes (-1, File.AsMemory (0, 1)))); + + [TestMethod] + public void Holds_NoSourcePath_IsFalse () => + Assert.IsFalse (SavedOverSource.Holds (null, Disk (), File.Length)); + + [TestMethod] + public void Holds_ASourceThatCannotBeRead_IsFalse () + { + var files = Disk (); + files.MarkInaccessible ("/f"); + + Assert.IsFalse (SavedOverSource.Holds ("/f", files, File.Length)); + } + + [TestMethod] + public void Holds_AMissingSource_IsFalse () => + Assert.IsFalse (SavedOverSource.Holds ("/missing", Disk (), File.Length)); + + // A read-back that fails after a save over the source leaves the object with the offsets of the file it had. The + // next path save then finds a source of another length and fails instead of applying them to it. + [TestMethod] + [DataRow (".mp3")] + [DataRow (".flac")] + [DataRow (".aac")] + public async Task ReadBackThatFails_TheNextSaveFailsAndWritesNothing (string fixture) + { + var original = Fixtures[fixture].Build (); + var files = new FailingReadBack (new MockFileSystem ()); + var file = Open (fixture, "path", original, files.Inner); + Retitle (file, "A first title that is longer than the one it was read with " + new string ('x', 4000)); + var first = await SavePath (file, null, sync: true, files); + Assert.IsTrue (first.IsSuccess, first.Error); + var onDisk = files.Inner.ReadAllBytes ("/in" + fixture); + Retitle (file, "Second"); + + var second = await SavePath (file, null, sync: true, files.Inner); + + Assert.AreEqual ( + $"Cannot save this {Fixtures[fixture].Name} file: the source file is {onDisk.Length} bytes, but the file it was read from was {original.Length} bytes.", + second.Error); + CollectionAssert.AreEqual (onDisk, files.Inner.ReadAllBytes ("/in" + fixture)); + } + + // Reads fail once a move has replaced a file, as when the source becomes unreadable right after a save. + sealed class FailingReadBack (MockFileSystem inner) : IFileSystem + { + bool _moved; + + public MockFileSystem Inner => inner; + + public bool FileExists (string path) => inner.FileExists (path); + + public Stream OpenRead (string path) => _moved ? throw new IOException ("unreadable") : inner.OpenRead (path); + + public Stream OpenReadWrite (string path) => inner.OpenReadWrite (path); + + public Stream Create (string path) => inner.Create (path); + + public byte[] ReadAllBytes (string path) => inner.ReadAllBytes (path); + + public Task ReadAllBytesAsync (string path, CancellationToken cancellationToken = default) => + inner.ReadAllBytesAsync (path, cancellationToken); + + public void WriteAllBytes (string path, ReadOnlySpan data) => inner.WriteAllBytes (path, data); + + public Task WriteAllBytesAsync (string path, ReadOnlyMemory data, CancellationToken cancellationToken = default) => + inner.WriteAllBytesAsync (path, data, cancellationToken); + + public void Delete (string path) => inner.Delete (path); + + public void Move (string sourcePath, string destinationPath) + { + inner.Move (sourcePath, destinationPath); + _moved = true; + } + + public string? GetDirectoryName (string path) => inner.GetDirectoryName (path); + + public string GetFileName (string path) => inner.GetFileName (path); + + public string CombinePath (string path1, string path2) => inner.CombinePath (path1, path2); + } +} diff --git a/tests/TagLibSharp2.Tests/Core/SecondSaveStateTests.cs b/tests/TagLibSharp2.Tests/Core/SecondSaveStateTests.cs new file mode 100644 index 00000000..b899f54e --- /dev/null +++ b/tests/TagLibSharp2.Tests/Core/SecondSaveStateTests.cs @@ -0,0 +1,122 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using TagLibSharp2.Aac; +using TagLibSharp2.Ape; +using TagLibSharp2.Core; +using TagLibSharp2.Id3; +using TagLibSharp2.Id3.Id3v2; +using TagLibSharp2.Mpeg; +using TagLibSharp2.Tests.Aac; +using TagLibSharp2.Tests.Image; +using TagLibSharp2.Tests.Mpeg; +using static TagLibSharp2.Tests.Core.SpanSaveKit; + +namespace TagLibSharp2.Tests.Core; + +/// +/// After a save over its source the object holds what a read of that file holds (#179), beyond offsets: which tag it +/// read in front, at the end and as ID3v1, whether its APEv2 tag had only a footer, and an image's text with nothing +/// pending. Each row edits, saves over the source, edits again and saves again; the second save writes what a fresh +/// read of the first save's file, given the second edit, writes. +/// +[TestClass] +[TestCategory ("Unit")] +public sealed class SecondSaveStateTests +{ + static readonly Dictionary Build, Action First, Action Second)> Cases = new () { + // The tag written in front is now the tag read there: removing it removes it, and does not keep its bytes as + // a tag that did not parse. + ["mpg: a tag written in front, then removed"] = (".mpg", + () => MpegPsTestBuilder.ProgramStream (), + file => ((MpegPsFile)file).EnsureId3v2Tag ().Title = "Front", + file => ((MpegPsFile)file).Id3v2Tag = null), + // The appended tag moved to the front as v2.3; a v2.4 tag after that is written in front too. + ["mpg: an appended tag moved to the front, then a v2.4 tag"] = (".mpg", + () => [.. MpegPsTestBuilder.ProgramStream (), .. MpegPsAppendedTagTests.Appended ("App"), .. MpegPsFileTests.Id3v1 ("Back")], + file => ((MpegPsFile)file).Id3v2Tag = new Id3v2Tag (Id3v2Version.V23) { Title = "Front" }, + file => ((MpegPsFile)file).Id3v2Tag = new Id3v2Tag (Id3v2Version.V24) { Title = "Next" }), + // An appended tag that is not an update stays one: the tag kept in front is not made its earlier tag. + ["mpg: a tag in front and an appended tag kept, ID3v1 edited twice"] = (".mpg", + () => [.. new Id3v2Tag (Id3v2Version.V24) { Title = "Front" }.Render ().Span, .. MpegPsTestBuilder.ProgramStream (), + .. MpegPsAppendedTagTests.Appended ("App"), .. MpegPsFileTests.Id3v1 ("Back")], + file => ((MpegPsFile)file).Id3v1Tag!.Title = "One", + file => ((MpegPsFile)file).Id3v1Tag!.Title = "Two"), + // An update tag replaced by a new tag is not an update of the tag that was in front. + ["mpg: an update tag replaced, then edited"] = (".mpg", + () => [.. new Id3v2Tag (Id3v2Version.V24) { Title = "Front", Album = "Front Album" }.Render ().Span, + .. MpegPsTestBuilder.ProgramStream (), .. MpegPsAppendedTagTests.UpdateTag ("Back")], + file => ((MpegPsFile)file).Id3v2Tag = new Id3v2Tag (Id3v2Version.V24) { Title = "New" }, + file => ((MpegPsFile)file).Id3v2Tag!.Title = "Next"), + // A footer-only APEv2 tag replaced by one written with a header; the first tag assigned back is written with a + // header too, as a read of the saved file would write it. + ["aac: a footer-only APEv2 tag replaced, then assigned back"] = (".aac", + () => [.. AacTestBuilder.Adts (8), .. new ApeTag { Title = "Ape" }.RenderWithOptions (includeHeader: false).Span], + file => { var aac = (AacFile)file; Read = aac.ApeTag; aac.ApeTag = new ApeTag { Title = "Other" }; }, + file => ((AacFile)file).ApeTag = Read), + // A tag parsed from footer-only bytes elsewhere and assigned is written with AAC's header; a second save with + // no edit writes it so again, as a read of the saved file would, not with the layout it was parsed with. + ["aac: a footer-only APEv2 tag parsed elsewhere and assigned, then no edit"] = (".aac", + () => [.. AacTestBuilder.Adts (8)], + file => ((AacFile)file).ApeTag = ApeTag.Parse (new ApeTag { Title = "Other" }.RenderWithOptions (includeHeader: false).Span).Tag, + NoEdit), + // The comment written is the text of the file, with nothing pending: a title edit after it changes only the + // title. + ["png: a comment, then a title"] = (".png", + () => ImageTestBuilder.Concat ( + ImageTestBuilder.PngSignature, + ImageTestBuilder.PngChunk ("IHDR", [0, 0, 0, 2, 0, 0, 0, 3, 8, 0, 0, 0, 0]), + ImageTestBuilder.Text ("Comment", "Old"), + ImageTestBuilder.PngChunk ("IDAT", new byte[300]), + ImageTestBuilder.Text ("Title", "Old"), + ImageTestBuilder.PngChunk ("IEND", [])), + file => file.Tag!.Comment = "A comment written by the first save", + file => file.Tag!.Title = "Next"), + ["png: cleared, then a title"] = (".png", + () => ImageTestBuilder.Concat ( + ImageTestBuilder.PngSignature, + ImageTestBuilder.PngChunk ("IHDR", [0, 0, 0, 2, 0, 0, 0, 3, 8, 0, 0, 0, 0]), + ImageTestBuilder.Text ("Comment", "Old"), + ImageTestBuilder.Text ("Software", "Unmapped"), + ImageTestBuilder.PngChunk ("IDAT", new byte[300]), + ImageTestBuilder.PngChunk ("IEND", [])), + file => file.Tag!.Clear (), + file => file.Tag!.Title = "Next"), + }; + + // A second save with no edit. + static void NoEdit (IMediaFile file) + { + } + + // The tag a row reads before its first edit, for a row that assigns it back. + static ApeTag? Read; + + public static IEnumerable Rows () => Cases.Keys.Select (key => new object[] { key }); + + [TestMethod] + [DynamicData (nameof (Rows))] + [DoNotParallelize] + public async Task SecondSave_WritesWhatAFreshReadOfTheFirstSaveWrites (string name) + { + var (extension, build, first, second) = Cases[name]; + var files = new MockFileSystem (); + var file = Open (extension, "path", build (), files); + first (file); + Assert.IsTrue ((await SavePath (file, null, sync: true, files)).IsSuccess); + var afterFirst = files.ReadAllBytes ("/in" + extension); + second (file); + + var saved = await SavePath (file, null, sync: true, files); + + Assert.IsTrue (saved.IsSuccess, saved.Error); + files.AddFile ("/oracle" + extension, afterFirst); + var fresh = (IMediaFile)MediaFile.Read ("/oracle" + extension, files).File!; + // The fresh read's own tag, for the row that assigns one back: the same text, read with a header. + if (fresh is AacFile) + Read = new ApeTag { Title = "Ape" }; + second (fresh); + Assert.IsTrue ((await SavePath (fresh, null, sync: true, files)).IsSuccess); + CollectionAssert.AreEqual (files.ReadAllBytes ("/oracle" + extension), files.ReadAllBytes ("/in" + extension), name); + } +} diff --git a/tests/TagLibSharp2.Tests/Core/SkipPicturesFixtures.cs b/tests/TagLibSharp2.Tests/Core/SkipPicturesFixtures.cs index 13ba3784..d158530b 100644 --- a/tests/TagLibSharp2.Tests/Core/SkipPicturesFixtures.cs +++ b/tests/TagLibSharp2.Tests/Core/SkipPicturesFixtures.cs @@ -598,13 +598,19 @@ static byte[] Id3Carrier (byte[] seed, string ext) file = read.File; break; } + // A stream read leaves the SSND sound in the stream, so the AIFF seed is read from memory to render it. (The + // builder's FORM used to end before SSND, so a stream read never reached it.) + case ".aif": { + var read = AiffFile.Read (seed); + Assert.IsTrue (read.IsSuccess, read.Error); + read.File!.Id3v2Tag = tag; + file = read.File; + break; + } default: { var read = MediaFile.Read (new MemoryStream (seed, writable: false), "seed" + ext); Assert.IsTrue (read.IsSuccess, ext + " " + read.Error); - if (read.File is WavFile wav) - wav.Id3v2Tag = tag; - else - ((AiffFile)read.File!).Id3v2Tag = tag; + ((WavFile)read.File!).Id3v2Tag = tag; file = read.File!; break; } diff --git a/tests/TagLibSharp2.Tests/Core/SourceLengthTests.cs b/tests/TagLibSharp2.Tests/Core/SourceLengthTests.cs new file mode 100644 index 00000000..2fe33e1f --- /dev/null +++ b/tests/TagLibSharp2.Tests/Core/SourceLengthTests.cs @@ -0,0 +1,71 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using TagLibSharp2.Core; + +namespace TagLibSharp2.Tests.Core; + +/// +/// The lengths of the files an object describes (#178), checked on the type itself where a file of the length in +/// question cannot be built in a test. +/// +[TestClass] +[TestCategory ("Unit")] +public sealed class SourceLengthTests +{ + // AtomicFileWriter reports a write of int.MaxValue bytes or more as int.MaxValue (FileWriteResult.BytesWritten is an + // int), so that count does not give the length of the file. A span over native memory can be exactly that long. + [TestMethod] + public void Saved_TheCountOfALargeWrite_IsNotAFileItDescribes () + { + var source = new SourceLength (); + source.Record (100); + + source.Saved (FileWriteResult.Success (int.MaxValue)); + + Assert.IsFalse (source.Describes (int.MaxValue)); + Assert.IsTrue (source.Describes (100)); + } + + [TestMethod] + public void Saved_TheLargestExactCount_IsAFileItDescribes () + { + var source = new SourceLength (); + source.Record (100); + + source.Saved (FileWriteResult.Success (int.MaxValue - 1)); + + Assert.IsTrue (source.Describes (int.MaxValue - 1)); + } + + // After a save over its source the object describes that file in place of the one it read (#179); the refusal + // names it as such. + [TestMethod] + public void Refuse_AfterASaveOverTheSource_NamesTheFileItSaved () + { + var source = new SourceLength (); + source.Record (100); + + source.Rewrote (200); + + Assert.IsTrue (source.Describes (200)); + Assert.IsFalse (source.Describes (100)); + Assert.AreEqual ( + "Cannot save this MP3 file: the original data is 100 bytes, but the file it last saved over its source was 200 bytes.", + source.Refuse ("MP3", 100)!.Value.Error); + } + + // A later read-style record (a reader of the object) names the file read again. + [TestMethod] + public void Refuse_AfterARecord_NamesTheFileItRead () + { + var source = new SourceLength (); + source.Rewrote (200); + + source.Record (100); + + Assert.AreEqual ( + "Cannot save this MP3 file: the original data is 5 bytes, but the file it was read from was 100 bytes.", + source.Refuse ("MP3", 5)!.Value.Error); + } +} diff --git a/tests/TagLibSharp2.Tests/Core/SpanSaveKit.cs b/tests/TagLibSharp2.Tests/Core/SpanSaveKit.cs index ab77abc9..2a0d62c6 100644 --- a/tests/TagLibSharp2.Tests/Core/SpanSaveKit.cs +++ b/tests/TagLibSharp2.Tests/Core/SpanSaveKit.cs @@ -71,7 +71,7 @@ public static byte[] Sound (int length) } // MPEG-1 Layer III, 128 kbps, 44.1 kHz frames of 417 bytes. - static byte[] Mp3Frames (int count) + public static byte[] Mp3Frames (int count) { var frames = new byte[417 * count]; for (var at = 0; at < frames.Length; at += 417) { @@ -177,6 +177,21 @@ static async Task FormatAsyncPathRead (string name, MockFileSystem f static (bool, string?, IMediaFile?) Of (DsfFileReadResult r) => (r.IsSuccess, r.Error, r.File); static (bool, string?, IMediaFile?) Of (DffFileReadResult r) => (r.IsSuccess, r.Error, r.File); + /// Sets the title, giving a DSF, DFF or MP3 file an ID3 tag when it has none. + public static void Retitle (IMediaFile file, string title) + { + if (file is Mp3File mp3) { + mp3.Title = title; + return; + } + if (file is DsfFile dsf) + dsf.EnsureId3v2Tag (); + if (file is DffFile dff) + dff.EnsureId3v2Tag (); + Assert.IsNotNull (file.Tag, file.GetType ().Name + " has no tag to edit"); + file.Tag.Title = title; + } + /// SaveToFile (path, span) when , else SaveToFileAsync (path, memory). public static Task SaveSpan (object file, string path, byte[] span, bool sync, MockFileSystem files) => file switch { FlacFile f => sync ? Task.FromResult (f.SaveToFile (path, span, files)) : f.SaveToFileAsync (path, span, files), @@ -197,8 +212,18 @@ static async Task FormatAsyncPathRead (string name, MockFileSystem f _ => throw new ArgumentException ("no span save on " + file.GetType ().Name, nameof (file)), }; + /// Whether has an overload for 's type. + public static bool HasSpanSave (object file) => file is FlacFile or OggVorbisFile or OggOpusFile or OggFlacFile or Mp3File + or AacFile or MonkeysAudioFile or MusepackFile or WavPackFile or AviFile or AudibleFile or AsfFile or MpegPsFile + or DsfFile or DffFile; + /// SaveToFile (path) or its async twin; with no path, the save over the source. - public static Task SavePath (object file, string? path, bool sync, MockFileSystem files) + /// Whether has the save over its own source, SaveToFile (IFileSystem) or its async twin. + public static bool HasInPlaceSave (object file, bool sync) => + sync ? file.GetType ().GetMethod ("SaveToFile", [typeof (IFileSystem)]) is not null + : file.GetType ().GetMethod ("SaveToFileAsync", [typeof (IFileSystem), typeof (CancellationToken)]) is not null; + + public static Task SavePath (object file, string? path, bool sync, IFileSystem files) { dynamic target = file; if (path is null) diff --git a/tests/TagLibSharp2.Tests/Core/SpanSaveSourceTests.cs b/tests/TagLibSharp2.Tests/Core/SpanSaveSourceTests.cs index 2d11a331..e07dfdaa 100644 --- a/tests/TagLibSharp2.Tests/Core/SpanSaveSourceTests.cs +++ b/tests/TagLibSharp2.Tests/Core/SpanSaveSourceTests.cs @@ -100,7 +100,7 @@ public void AudibleSavedOverItsSource_SavesFromTheNewBytes () Assert.IsTrue (fromNew.IsSuccess, fromNew.Error); Assert.AreEqual ("Again", MediaFile.ReadFromData (files.ReadAllBytes ("/new.aa"), "new.aa").Tag!.Title); Assert.AreEqual ( - $"Cannot save this Audible file: the original data is {first.Length} bytes, but the file it was read from was {written.Length} bytes.", + $"Cannot save this Audible file: the original data is {first.Length} bytes, but the file it last saved over its source was {written.Length} bytes.", fromFirst.Error); Assert.IsFalse (files.FileExists ("/first.aa")); } diff --git a/tests/TagLibSharp2.Tests/Core/TruncatedLastChunkSaveTests.cs b/tests/TagLibSharp2.Tests/Core/TruncatedLastChunkSaveTests.cs new file mode 100644 index 00000000..9a66deba --- /dev/null +++ b/tests/TagLibSharp2.Tests/Core/TruncatedLastChunkSaveTests.cs @@ -0,0 +1,151 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Buffers.Binary; +using TagLibSharp2.Aiff; +using TagLibSharp2.Core; +using TagLibSharp2.Id3.Id3v2; +using TagLibSharp2.Riff; +using TagLibSharp2.Tests.Kit; + +namespace TagLibSharp2.Tests.Core; + +/// +/// A chunk read with a declared size past its bytes keeps the bytes present (#192, #197), so a save must size and write +/// it by those bytes, never by the declared size. A tiny AIFF and a tiny WAV whose last chunk declares 256 MB, close to +/// 2 GB, or past it, are read from a path, from a stream and from memory, then saved as read and with a new title, to a +/// path and over the source, sync and async. Each save either writes a file no longer than the source and the new ID3 +/// chunk, which reads as the edited file did, or fails and leaves its target as it was; and a sync save allocates +/// nothing near the declared size. +/// +[TestClass] +[TestCategory ("Unit")] +public sealed class TruncatedLastChunkSaveTests +{ + // Far below any declared size here (2 GB and up), far above what a save of a file of a few hundred bytes needs. + const long AllocationBound = 16L << 20; + + // What a new title adds: an ID3 chunk of a few hundred bytes at most. + const int EditBound = 4096; + + static readonly string[] Reads = ["path", "stream", "data"]; + + static readonly string[] Saves = ["sync-path", "async-path", "sync-source", "async-source"]; + + // A save as read, and one with a new title, whose ID3 chunk is written after the cut chunk: a header that kept the + // declared size would swallow it. + static readonly string[] Edits = ["none", "title"]; + + // The last chunk: the sound itself, one a reader knows, and one no reader knows. + static readonly string[] Files = [".aif SSND", ".aif NAME", ".aif junk", ".wav data", ".wav LIST", ".wav junk"]; + + // 256 MB, which a save that sizes by the declared size allocates without complaint, and one byte more, whose odd + // size pads a chunk that holds an even number of bytes; then sizes at or past what a buffer can hold. + static readonly uint[] Sizes = [0x10000000, 0x10000001, 0x7FFFFFF0, 0x80000000, 0xFFFFFFF0]; + + static readonly string[] Forms = ["exact", "placeholder"]; + + public static IEnumerable Rows () => + from file in Files + from size in Sizes + from form in Forms + select new object[] { file, size, form }; + + [TestMethod] + [DynamicData (nameof (Rows))] + public async Task HugeLastChunk_SavesByTheBytesPresentOrFailsWritingNothing (string file, uint size, string form) + { + var extension = file[..4]; + var bytes = Build (extension, file[5..], size, form); + var label = $"{file} 0x{size:X8} {form}"; + var problems = new List (); + + foreach (var (read, edit, save) in from read in Reads from edit in Edits from save in Saves select (read, edit, save)) { + var files = new MockFileSystem (); + var source = "/in" + extension; + files.AddFile (source, bytes); + var opened = Open (read, source, bytes, files); + Assert.IsTrue (opened.IsSuccess, $"{label} {read}: {opened.Error}"); + var media = (IMediaFile)opened.File!; + if (edit == "title") + Retitle (media); + var expected = EntryAgreement.Describe (media); + + var target = save.EndsWith ("source", StringComparison.Ordinal) ? source : "/out" + extension; + var before = files.FileExists (target) ? files.ReadAllBytes (target) : null; + var sync = save.StartsWith ("sync", StringComparison.Ordinal); + var allocatedBefore = GC.GetAllocatedBytesForCurrentThread (); + FileWriteResult result; + try { + result = await SpanSaveKit.SavePath (media, target, sync, files); + } catch (Exception ex) when (ex is not AssertFailedException) { + problems.Add ($"{read} {edit} {save}: threw {ex.GetType ().Name}: {ex.Message}"); + continue; + } + var allocated = GC.GetAllocatedBytesForCurrentThread () - allocatedBefore; + if (sync && allocated > AllocationBound) + problems.Add ($"{read} {edit} {save}: allocated {allocated:N0} bytes"); + + var after = files.FileExists (target) ? files.ReadAllBytes (target) : null; + if (!result.IsSuccess) { + if (!(before is null ? after is null : after is not null && before.AsSpan ().SequenceEqual (after))) + problems.Add ($"{read} {edit} {save}: failed with \"{result.Error}\" and wrote"); + continue; + } + + if (after!.Length > bytes.Length + EditBound) { + problems.Add ($"{read} {edit} {save}: wrote {after.Length:N0} bytes from a source of {bytes.Length}"); + continue; + } + var reread = MediaFile.ReadFromData (after, source); + var actual = reread.IsSuccess ? EntryAgreement.Describe ((IMediaFile)reread.File!) : "FAIL " + reread.Error; + if (actual != expected) + problems.Add ($"{read} {edit} {save}: reads back {actual}, the source read {expected}"); + } + + Assert.IsEmpty (problems, label + ":\n " + string.Join ("\n ", problems)); + } + + static void Retitle (IMediaFile file) + { + if (file is AiffFile aiff) + aiff.Title = "Saved"; + else if (file is WavFile wav) + (wav.Id3v2Tag ??= new Id3v2Tag ()).Title = "Saved"; + } + + static MediaFileResult Open (string read, string source, byte[] bytes, MockFileSystem files) => read switch { + "path" => MediaFile.Read (source, files), + "stream" => MediaFile.Read (new MemoryStream (bytes, writable: false), source), + _ => MediaFile.ReadFromData (bytes, source), + }; + + // A valid file with 64 bytes of sound, whose last chunk (the sound itself, or one appended) declares + // and holds 10 to 14 bytes. The form's size is the file's, or the streamed writer's placeholder. + static byte[] Build (string extension, string chunk, uint size, string form) + { + var aiff = extension == ".aif"; + var file = aiff ? TestBuilders.Aiff.CreateMinimal (soundBytes: 64) : TestBuilders.Wav.CreateMinimal (soundBytes: 64); + if (chunk is "SSND" or "data") { + var at = file.AsSpan ().IndexOf (System.Text.Encoding.ASCII.GetBytes (chunk)) + 4; + WriteSize (file.AsSpan (at), size, aiff); + } else { + var body = chunk == "LIST" ? "INFOINAM\u0004\0\0\0ab"u8.ToArray () : "abcdefghij"u8.ToArray (); + var header = new byte[8]; + System.Text.Encoding.ASCII.GetBytes (chunk).CopyTo (header, 0); + WriteSize (header.AsSpan (4), size, aiff); + file = [.. file, .. header, .. body]; + } + + WriteSize (file.AsSpan (4), form == "exact" ? (uint)(file.Length - 8) : uint.MaxValue, aiff); + return file; + } + + static void WriteSize (Span at, uint size, bool bigEndian) + { + if (bigEndian) + BinaryPrimitives.WriteUInt32BigEndian (at, size); + else + BinaryPrimitives.WriteUInt32LittleEndian (at, size); + } +} diff --git a/tests/TagLibSharp2.Tests/Core/WindowedEdgeTests.cs b/tests/TagLibSharp2.Tests/Core/WindowedEdgeTests.cs index e1f1bf9c..9848a9e3 100644 --- a/tests/TagLibSharp2.Tests/Core/WindowedEdgeTests.cs +++ b/tests/TagLibSharp2.Tests/Core/WindowedEdgeTests.cs @@ -339,8 +339,8 @@ public void OggWindow_ContinuedAndTruncatedPages_Stop () var headers = OggWindow.ReadHeaders (stream, OggHeaderKind.Vorbis); Assert.IsTrue (headers.Length > 0); - Assert.IsEmpty (OggWindow.ReadLastPage (new MemoryStream (new byte[8]))); - Assert.IsEmpty (OggWindow.ReadLastPage (new MemoryStream (new byte[40]))); + Assert.IsEmpty (OggWindow.ReadGranulePage (new MemoryStream (new byte[8]))); + Assert.IsEmpty (OggWindow.ReadGranulePage (new MemoryStream (new byte[40]))); var cut = new byte[27]; "OggS"u8.CopyTo (cut); @@ -349,7 +349,7 @@ public void OggWindow_ContinuedAndTruncatedPages_Stop () var tail = new byte[30]; "OggS"u8.CopyTo (tail.AsSpan (20)); - Assert.IsEmpty (OggWindow.ReadLastPage (AtStart (tail))); + Assert.IsEmpty (OggWindow.ReadGranulePage (AtStart (tail))); } static void SameWhenCopied (byte[] file, string name) diff --git a/tests/TagLibSharp2.Tests/Core/WindowedReadDefectTests.cs b/tests/TagLibSharp2.Tests/Core/WindowedReadDefectTests.cs index c089dbb9..45788646 100644 --- a/tests/TagLibSharp2.Tests/Core/WindowedReadDefectTests.cs +++ b/tests/TagLibSharp2.Tests/Core/WindowedReadDefectTests.cs @@ -63,10 +63,14 @@ public void Read_EmptySecondDataChunk_DoesNotClearTheFirstPayload () Assert.IsEmpty (payloads[1]); } + // The save copies the 2 GB of samples from the source, as an AIFF save copies its sound (#203); it used to refuse + // them as past what an array holds. The samples are a Kit.SparseFile run, checked byte for byte as they stream. [TestMethod] - public void Read_DataChunkPastTwoGigabytes_KeepsTheFollowingTitleAndRefusesTheSave () + public void Read_DataChunkPastTwoGigabytes_KeepsTheFollowingTitleAndSavesTheSamples () { - var files = new SparseFileSystem (PastTwoGigabytes ()); + var layout = PastTwoGigabytes (); + var files = new Kit.SparseFileSystem (); + files.Add ("/song.wav", new Kit.SparseFile (layout.Head, layout.Hole, layout.Tail)); using var opened = files.OpenRead ("/song.wav"); var streamed = WavFile.Read (opened, "/song.wav", files); @@ -75,8 +79,10 @@ public void Read_DataChunkPastTwoGigabytes_KeepsTheFollowingTitleAndRefusesTheSa Assert.AreEqual (TimeSpan.FromSeconds (0x80000000 / 8000.0), streamed.File.Properties.Duration); var saved = streamed.File.SaveToFile ("/song.wav", files); - Assert.IsFalse (saved.IsSuccess, saved.Error); - Assert.AreEqual (0, files.Writes); + Assert.IsTrue (saved.IsSuccess, saved.Error); + Assert.AreEqual (0x80000000L, files.Get ("/song.wav").RunLength, "the samples, byte for byte"); + using var back = files.OpenRead ("/song.wav"); + Assert.AreEqual ("Window", WavFile.Read (back, "/song.wav", files).File!.Title); } [TestMethod] @@ -232,50 +238,6 @@ static SparseLayout XingPastFourGigabytes () return new SparseLayout (audio, (long)uint.MaxValue + 5000 - audio.Length, []); } - sealed class SparseFileSystem : IFileSystem - { - readonly SparseLayout _layout; - - public SparseFileSystem (SparseLayout layout) => _layout = layout; - - public int Writes { get; private set; } - - public bool FileExists (string path) => path == "/song.wav"; - - public Stream OpenRead (string path) => new SparseStream (_layout); - - public Stream OpenReadWrite (string path) => throw new NotSupportedException (); - - public Stream Create (string path) => throw new NotSupportedException (); - - public byte[] ReadAllBytes (string path) => throw new NotSupportedException (); - - public Task ReadAllBytesAsync (string path, CancellationToken cancellationToken = default) => - throw new NotSupportedException (); - - public void WriteAllBytes (string path, ReadOnlySpan data) => Writes++; - - public Task WriteAllBytesAsync (string path, ReadOnlyMemory data, CancellationToken cancellationToken = default) - { - Writes++; - return Task.CompletedTask; - } - - public void Delete (string path) - { - } - - public void Move (string sourcePath, string destinationPath) - { - } - - public string? GetDirectoryName (string path) => "/"; - - public string GetFileName (string path) => "song.wav"; - - public string CombinePath (string path1, string path2) => path1 + path2; - } - internal readonly struct SparseLayout { public SparseLayout (byte[] head, long hole, byte[] tail) diff --git a/tests/TagLibSharp2.Tests/Core/WindowedReadEdgeTests.cs b/tests/TagLibSharp2.Tests/Core/WindowedReadEdgeTests.cs index 83ec2a13..226e7a61 100644 --- a/tests/TagLibSharp2.Tests/Core/WindowedReadEdgeTests.cs +++ b/tests/TagLibSharp2.Tests/Core/WindowedReadEdgeTests.cs @@ -412,26 +412,25 @@ public void Read_UnknownRiffSize_ReadsTheChunkPastFourGigabytes () Assert.AreEqual ("Past", opened.Tag!.Title); } + // A data chunk one byte past what an array holds, after a RIFF size of the streamed writer's placeholder: the save + // copies its samples from the source (#203), where it refused them, and writes the RIFF size of the file. The + // samples are a Kit.SparseFile run, checked byte for byte as they stream. [TestMethod] - public void Save_DataChunkJustOverTheArrayLimit_FailsClosed () + public void Save_DataChunkJustOverTheArrayLimit_CopiesTheSamples () { var count = (uint)Array.MaxLength + 1; var prefix = WavPrefix (count); - var streamLength = prefix.Length + count; - var fs = new SparseFileSystem (streamLength, prefix); + var fs = new Kit.SparseFileSystem (); + fs.Add ("/huge.wav", new Kit.SparseFile (prefix, count, [])); var opened = WavFile.Read (fs.OpenRead ("/huge.wav"), "/huge.wav", fs); Assert.IsTrue (opened.IsSuccess, opened.Error); - FileWriteResult saved; - try { - saved = opened.File!.SaveToFile ("/huge.wav", fs); - } catch (Exception ex) { - Assert.Fail ("Save threw " + ex.GetType ().Name + " instead of returning a failure"); - return; - } + var saved = opened.File!.SaveToFile ("/huge.wav", fs); - Assert.IsFalse (saved.IsSuccess, saved.Error); - Assert.AreEqual (0, fs.Writes); + Assert.IsTrue (saved.IsSuccess, saved.Error); + var written = fs.Get ("/huge.wav"); + Assert.AreEqual ((long)count, written.RunLength, "the samples, byte for byte"); + Assert.AreEqual ((uint)(written.Length - 8), BitConverter.ToUInt32 (written.Head, 4), "the RIFF size of the file"); } [TestMethod] @@ -677,44 +676,6 @@ public Task WriteAllBytesAsync (string path, ReadOnlyMemory data, Cancella public string CombinePath (string path1, string path2) => _files.CombinePath (path1, path2); } - sealed class SparseFileSystem : IFileSystem - { - readonly long _length; - readonly byte[] _head; - public int Writes { get; private set; } - - public SparseFileSystem (long length, byte[] head) - { - _length = length; - _head = head; - } - - public bool FileExists (string path) => true; - public Stream OpenRead (string path) => new SparseStream (_length, _head, _length, Array.Empty ()); - public Stream OpenReadWrite (string path) => throw new NotSupportedException (); - public Stream Create (string path) - { - Writes++; - return new MemoryStream (); - } - - public byte[] ReadAllBytes (string path) => _head; - public Task ReadAllBytesAsync (string path, CancellationToken cancellationToken = default) => - Task.FromResult (_head); - public void WriteAllBytes (string path, ReadOnlySpan data) => Writes++; - public Task WriteAllBytesAsync (string path, ReadOnlyMemory data, CancellationToken cancellationToken = default) - { - Writes++; - return Task.CompletedTask; - } - - public void Delete (string path) { } - public void Move (string sourcePath, string destinationPath) => Writes++; - public string? GetDirectoryName (string path) => "/"; - public string GetFileName (string path) => "huge.wav"; - public string CombinePath (string path1, string path2) => path1 + path2; - } - sealed class SparseStream : Stream { readonly byte[] _head; diff --git a/tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v2FooterFlagTests.cs b/tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v2FooterFlagTests.cs new file mode 100644 index 00000000..31ddc2dd --- /dev/null +++ b/tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v2FooterFlagTests.cs @@ -0,0 +1,109 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using TagLibSharp2.Core; +using TagLibSharp2.Id3.Id3v2; +using TagLibSharp2.Tests.Core; + +namespace TagLibSharp2.Tests.Id3.Id3v2; + +/// +/// #202: an ID3v2.4 tag whose footer flag (0x10) is set with no footer after it. The reader took the 10 bytes after the +/// body for the footer, so they were not the audio's, and a save dropped them. ID3v2.4 §3.4: the footer is a copy of the +/// header whose identifier is "3DI". A footer now counts only when its "3DI" is there, on every ID3v2 reader that finds +/// where a tag ends (the tag read, the picture-skipping copy, AAC's audio start and detection, MPEG-PS's tag length), on +/// every read and save entry point of the formats that start with a tag: MP3, AAC and MPEG-PS. +/// +[TestClass] +[TestCategory ("Unit")] +public sealed class Id3v2FooterFlagTests +{ + static readonly string[] Fixtures = [".mp3", ".aac", ".mpg"]; + + static readonly string[] Reads = ["stream", "path", "data", "async-path", "format-path"]; + + // flag-only: the footer flag with no footer. footer: the flag and a "3DI" footer, which is the tag's. + static readonly string[] Shapes = ["flag-only", "footer"]; + + public static IEnumerable Rows () => + from fixture in Fixtures + from shape in Shapes + from read in Reads + select new object[] { fixture, shape, read }; + + [TestMethod] + [DynamicData (nameof (Rows))] + public async Task FooterFlag_TakesTheFooterOnlyWhenItIsThere (string fixture, string shape, string read) + { + var plain = SpanSaveKit.Fixtures[fixture].Build (); + var (bytes, audioStart) = WithFooterFlag (plain, shape == "footer"); + var audio = bytes.AsSpan (audioStart, Math.Min (512, bytes.Length - audioStart)).ToArray (); + var expected = Describe (SpanSaveKit.Open (fixture, read, plain, new MockFileSystem ())); + + var files = new MockFileSystem (); + var file = SpanSaveKit.Open (fixture, read, bytes, files); + + Assert.AreEqual (expected, Describe (file), "the read"); + var source = "/in" + SpanSaveKit.Extension (fixture); + var saved = read is "stream" or "data" + ? await SpanSaveKit.SaveSpan (file, source, bytes, sync: true, files) + : await SpanSaveKit.SavePath (file, "/out" + SpanSaveKit.Extension (fixture), sync: true, files); + Assert.IsTrue (saved.IsSuccess, saved.Error); + var written = files.ReadAllBytes (read is "stream" or "data" ? source : "/out" + SpanSaveKit.Extension (fixture)); + Assert.IsGreaterThanOrEqualTo (0, written.AsSpan ().IndexOf (audio), "the bytes after the tag, whole"); + Assert.AreEqual (expected, Describe (MediaFile.ReadFromData (written, source).File as IMediaFile), "the saved file"); + } + + // A SkipPictures read copies the tag without its pictures (Id3v2Tag.CopyWithoutPictures) and ends it by the same + // rule: its tag ends where a full read's does. + [TestMethod] + [DataRow (".mp3", "flag-only")] + [DataRow (".mp3", "footer")] + [DataRow (".aac", "flag-only")] + [DataRow (".aac", "footer")] + public void SkipPicturesRead_EndsTheTagWhereTheFullReadDoes (string fixture, string shape) + { + var (bytes, audioStart) = WithFooterFlag (SpanSaveKit.Fixtures[fixture].Build (), shape == "footer"); + var files = new MockFileSystem (); + var source = "/in" + fixture; + files.AddFile (source, bytes); + + var skip = MediaFile.Read (source, new MediaReadOptions { SkipPictures = true }, files); + + Assert.IsTrue (skip.IsSuccess, skip.Error); + Assert.AreEqual (audioStart, skip.File switch { + TagLibSharp2.Mpeg.Mp3File mp3 => mp3.Id3v2Size, + TagLibSharp2.Aac.AacFile aac => aac.Id3v2Size, + _ => -1, + }); + } + + [TestMethod] + public void Read_CountsTheFooterOnlyWhenItIsThere () + { + var plain = new Id3v2Tag (Id3v2Version.V24) { Title = "Title" }.Render ().ToArray (); + var (flagOnly, bodyEnd) = WithFooterFlag ([.. plain, .. new byte[16]], footer: false); + var (footer, footerEnd) = WithFooterFlag ([.. plain, .. new byte[16]], footer: true); + + Assert.AreEqual (bodyEnd, Id3v2Tag.Read (flagOnly).BytesConsumed); + Assert.AreEqual (footerEnd, Id3v2Tag.Read (footer).BytesConsumed); + Assert.AreEqual (bodyEnd + 10, footerEnd); + } + + static string Describe (IMediaFile? file) => + file is null ? "FAIL" : $"{file.AudioProperties?.Duration.Ticks}/{file.AudioProperties?.SampleRate}/{file.VideoProperties?.Duration.Ticks}/{file.Tag?.Title}"; + + // The file with its leading v2.4 tag's footer flag set, and a footer after the body when asked; and where the bytes + // after the tag start. + static (byte[] Bytes, int AudioStart) WithFooterFlag (byte[] plain, bool footer) + { + Assert.AreEqual ((byte)4, plain[3], "a v2.4 tag"); + var bodyEnd = 10 + ((plain[6] << 21) | (plain[7] << 14) | (plain[8] << 7) | plain[9]); + var bytes = (byte[])plain.Clone (); + bytes[5] |= 0x10; + if (!footer) + return (bytes, bodyEnd); + byte[] copy = [(byte)'3', (byte)'D', (byte)'I', .. bytes.AsSpan (3, 7)]; + return ([.. bytes.AsSpan (0, bodyEnd), .. copy, .. bytes.AsSpan (bodyEnd)], bodyEnd + 10); + } +} diff --git a/tests/TagLibSharp2.Tests/Image/ImagePathSaveChainTests.cs b/tests/TagLibSharp2.Tests/Image/ImagePathSaveChainTests.cs new file mode 100644 index 00000000..5735598a --- /dev/null +++ b/tests/TagLibSharp2.Tests/Image/ImagePathSaveChainTests.cs @@ -0,0 +1,165 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using TagLibSharp2.Core; +using TagLibSharp2.Image; +using TagLibSharp2.Tests.Core; +using static TagLibSharp2.Tests.Image.ImageTestBuilder; + +namespace TagLibSharp2.Tests.Image; + +/// +/// A PNG, JPEG or GIF read from a path is saved, edited and saved again (#179). Each later save must write what a fresh +/// read of the file on disk, given the same edit, writes. On 01b8d6cc the save planned its edit against the bytes it +/// read and copied the ranges from the file on disk, which after a save over the source is another file: the second +/// save wrote an unreadable JPEG, a GIF without its comment and a PNG that no longer reaches IEND, and later saves +/// failed. +/// +[TestClass] +[TestCategory ("Unit")] +public sealed class ImagePathSaveChainTests +{ + static readonly string[] Comments = [ + "A first comment that is longer than the one it was read with " + new string ('x', 600), + "Second", + "A third comment, longer than the second " + new string ('y', 300), + ]; + + static readonly Dictionary> Images = new () { + [".png"] = () => Concat ( + PngSignature, + PngChunk ("IHDR", [0, 0, 0, 2, 0, 0, 0, 3, 8, 0, 0, 0, 0]), + Text ("Comment", "Old"), + PngChunk ("IDAT", new byte[700]), + PngChunk ("IEND", [])), + [".jpg"] = () => Concat ( + [0xFF, 0xD8], + JpegSegment (0xFE, "Old"u8.ToArray ()), + JpegSegment (0xC0, [0x08, 0x00, 0x01, 0x00, 0x01, 0x01, 0x01, 0x11, 0x00]), + JpegSegment (0xDA, [0x01, 0x01, 0x00, 0x00, 0x3F, 0x00]), + Enumerable.Repeat ((byte)0x11, 700).ToArray (), + [0xFF, 0xD9]), + [".gif"] = () => Concat (GifScreen (1, 1, flags: 0), GifComment ("Old"), GifImage (700), [0x3B]), + }; + + public static IEnumerable Rows () + { + foreach (var image in Images.Keys) + foreach (var read in new[] { "path", "async-path", "format-path" }) + foreach (var first in new[] { "in-place", "alias", "elsewhere" }) + foreach (var overload in new[] { "sync", "async" }) + yield return [image, read, first, overload]; + } + + [TestMethod] + [DynamicData (nameof (Rows))] + public async Task LaterSaves_WriteWhatAFreshReadOfTheFileOnDiskWrites (string image, string read, string first, string overload) + { + var files = new MockFileSystem (); + var source = "/in" + image; + files.AddFile (source, Images[image] ()); + var file = Open (source, read, files); + var sync = overload == "sync"; + + file.Tag!.Comment = Comments[0]; + var saved = first switch { + "alias" => await Save (file, source.ToUpperInvariant (), sync, files), + "elsewhere" => await Save (file, "/else" + image, sync, files), + _ => await Save (file, null, sync, files), + }; + Assert.IsTrue (saved.IsSuccess, "first save: " + saved.Error); + + for (var i = 1; i < Comments.Length; i++) { + var before = files.ReadAllBytes (source); + file.Tag.Comment = Comments[i]; + + var again = await Save (file, null, sync, files); + + Assert.IsTrue (again.IsSuccess, $"save {i + 1}: {again.Error}"); + CollectionAssert.AreEqual (FreshSave (image, before, Comments[i], files), files.ReadAllBytes (source), $"save {i + 1}"); + } + } + + // Whole-tag steps: the text the read found is cleared, given back, cleared again and given back as a comment + // alone, one save per step, so each save adds or removes the chunk, segment or extension that holds it. + static readonly Action[] TagSteps = [ + file => file.Tag!.Clear (), + file => { + file.Tag!.Title = "New title"; + file.Tag.Comment = "New comment"; + }, + file => file.Tag!.Clear (), + file => file.Tag!.Comment = "Comment alone", + ]; + + public static IEnumerable TagRows () + { + foreach (var image in Images.Keys) + foreach (var first in new[] { "in-place", "alias", "elsewhere" }) + foreach (var overload in new[] { "sync", "async" }) + yield return [image, first, overload]; + } + + [TestMethod] + [DynamicData (nameof (TagRows))] + public async Task WholeTagSteps_WriteWhatAFreshReadOfTheFileOnDiskWrites (string image, string first, string overload) + { + var files = new MockFileSystem (); + var source = "/in" + image; + files.AddFile (source, Images[image] ()); + var file = Open (source, "path", files); + var sync = overload == "sync"; + + TagSteps[0] (file); + var saved = first switch { + "alias" => await Save (file, source.ToUpperInvariant (), sync, files), + "elsewhere" => await Save (file, "/else" + image, sync, files), + _ => await Save (file, null, sync, files), + }; + Assert.IsTrue (saved.IsSuccess, "first save: " + saved.Error); + + for (var i = 1; i < TagSteps.Length; i++) { + var before = files.ReadAllBytes (source); + TagSteps[i] (file); + + var again = await Save (file, null, sync, files); + + Assert.IsTrue (again.IsSuccess, $"step {i + 1}: {again.Error}"); + CollectionAssert.AreEqual (FreshSave (image, before, TagSteps[i], files), files.ReadAllBytes (source), $"step {i + 1}"); + } + } + + static StillImageFile Open (string path, string read, MockFileSystem files) + { + if (read == "format-path") { + var own = StillImageFile.ReadFromFile (path, files); + Assert.IsTrue (own.IsSuccess, own.Error); + return own.File!; + } + + var opened = read == "async-path" ? MediaFile.ReadAsync (path, files).GetAwaiter ().GetResult () : MediaFile.Read (path, files); + Assert.IsTrue (opened.IsSuccess, opened.Error); + return (StillImageFile)opened.File!; + } + + static Task Save (StillImageFile file, string? path, bool sync, MockFileSystem files) => + path is null + ? sync ? Task.FromResult (file.SaveToFile (files)) : file.SaveToFileAsync (files) + : sync ? Task.FromResult (file.SaveToFile (path, files)) : file.SaveToFileAsync (path, files); + + // The bytes a fresh path read of `bytes`, given `comment` and saved over its source, writes. + static byte[] FreshSave (string image, byte[] bytes, string comment, MockFileSystem files) => + FreshSave (image, bytes, file => file.Tag!.Comment = comment, files); + + // The bytes a fresh path read of `bytes`, given `edit` and saved over its source, writes. + static byte[] FreshSave (string image, byte[] bytes, Action edit, MockFileSystem files) + { + var path = "/oracle" + image; + files.AddFile (path, bytes); + var fresh = Open (path, "path", files); + edit (fresh); + var saved = fresh.SaveToFile (files); + Assert.IsTrue (saved.IsSuccess, "oracle save: " + saved.Error); + return files.ReadAllBytes (path); + } +} diff --git a/tests/TagLibSharp2.Tests/Image/ImagePathSaveTests.cs b/tests/TagLibSharp2.Tests/Image/ImagePathSaveTests.cs index 13d64ba6..232e3ea5 100644 --- a/tests/TagLibSharp2.Tests/Image/ImagePathSaveTests.cs +++ b/tests/TagLibSharp2.Tests/Image/ImagePathSaveTests.cs @@ -78,7 +78,8 @@ public async Task JpegPathSave_OverOneChunk_CopiesTheScanInChunks (bool saveAsyn : file.SaveToFile ("/out.jpg", fs); Assert.IsTrue (save.IsSuccess, save.Error); - Assert.AreEqual (1, fs.SourceLengthGets); + // Open records the length once. The save then reads the source back to see whether it wrote over it (#179). + Assert.AreEqual (2, fs.SourceLengthGets); var written = fs.Bytes ("/out.jpg"); CollectionAssert.AreEqual (rendered, written); Assert.AreEqual ("45C76CF7112DCCD5B2595DE1CFA0374CCD05E60FF8B1A0A7B147B3FB160A3937", Convert.ToHexString (SHA256.HashData (written))); @@ -205,7 +206,8 @@ public async Task PngPathSave_OverOneChunk_CopiesTheImageDataInChunks (bool save : read.File.SaveToFile ("/out.png", fs); Assert.IsTrue (save.IsSuccess, save.Error); - Assert.AreEqual (1, fs.SourceLengthGets); + // Open records the length once. The save then reads the source back to see whether it wrote over it (#179). + Assert.AreEqual (2, fs.SourceLengthGets); var written = fs.Bytes ("/out.png"); CollectionAssert.AreEqual (rendered, written); const string expected = "6911679D573A41B74F5D62F67F8E7861D80EF89E84BC57A7A43229FB2D2C7E24"; @@ -337,7 +339,8 @@ public async Task GifPathSave_OverOneChunk_CopiesTheImageInChunks (bool saveAsyn : read.File.SaveToFile ("/out.gif", fs); Assert.IsTrue (save.IsSuccess, save.Error); - Assert.AreEqual (1, fs.SourceLengthGets); + // Open records the length once. The save then reads the source back to see whether it wrote over it (#179). + Assert.AreEqual (2, fs.SourceLengthGets); var written = fs.Bytes ("/out.gif"); CollectionAssert.AreEqual (rendered, written); const string expected = "742A2C24C2F5A7CC72B01607DCB6B3517A46B7FD146388CF59F68A8AE175D287"; @@ -618,7 +621,8 @@ static async Task AssertEditedRangeCopiedInChunks ( : file.SaveToFile (destination, fs); Assert.IsTrue (save.IsSuccess, save.Error); - Assert.AreEqual (1, fs.SourceLengthGets); + // Open records the length once. The save then reads the source back to see whether it wrote over it (#179). + Assert.AreEqual (2, fs.SourceLengthGets); var written = fs.Bytes (destination); Assert.AreEqual (writtenLength, written.Length); CollectionAssert.AreEqual (rendered, written); @@ -791,26 +795,6 @@ static void ApplyGif (StillImageFile file, string op) file.Tag!.Clear (); } - static byte[] GifImage (int length) - { - var data = new byte[length]; - data[0] = 0x2C; - data[6] = 1; - data[8] = 1; - var at = 11; - var remain = length - 12; - while (remain > 0) { - var take = Math.Min (255, remain - 1); - if (take <= 0) - break; - data[at++] = (byte)take; - at += take; - remain -= 1 + take; - } - - return data; - } - static byte[] PngInput (string op) => op switch { "noop" or "clear" => Png (Text ("Title", "Old"), Text ("Comment", "Old")), "title" => Png (Text ("Title", "Old")), diff --git a/tests/TagLibSharp2.Tests/Image/ImageTestBuilder.cs b/tests/TagLibSharp2.Tests/Image/ImageTestBuilder.cs index ee84bfd8..7fea33e9 100644 --- a/tests/TagLibSharp2.Tests/Image/ImageTestBuilder.cs +++ b/tests/TagLibSharp2.Tests/Image/ImageTestBuilder.cs @@ -660,6 +660,27 @@ public static byte[] TitledPng (string title) => Concat (PngSignature, PngChunk ("IHDR", PngHeader (1, 1, 8, 2)), Text ("Title", title), PngChunk ("IEND", [])); /// A GIF89a header and logical screen descriptor (GIF89a §18) and nothing else. + /// A one-pixel image descriptor and image data, bytes in all, in sub-blocks. + public static byte[] GifImage (int length) + { + var data = new byte[length]; + data[0] = 0x2C; + data[6] = 1; + data[8] = 1; + var at = 11; + var remain = length - 12; + while (remain > 0) { + var take = Math.Min (255, remain - 1); + if (take <= 0) + break; + data[at++] = (byte)take; + at += take; + remain -= 1 + take; + } + + return data; + } + public static byte[] GifScreen (int width, int height, byte flags = 0x80 | (7 << 4) | 7) { var data = new byte[13]; diff --git a/tests/TagLibSharp2.Tests/Kit/EntryAgreement.cs b/tests/TagLibSharp2.Tests/Kit/EntryAgreement.cs new file mode 100644 index 00000000..dced08bf --- /dev/null +++ b/tests/TagLibSharp2.Tests/Kit/EntryAgreement.cs @@ -0,0 +1,62 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using TagLibSharp2.Core; +using TagLibSharp2.Tests.Core; + +namespace TagLibSharp2.Tests.Kit; + +/// +/// One read of a file on each entry point a format has, described by what a caller sees (duration, sample rate, +/// channels, title), for tests whose property is that every entry point reads the same file. A read that fails is +/// "FAIL", one that throws is "THREW" and the exception's type. +/// +internal static class EntryAgreement +{ + /// 's four reads, with and without SkipPictures, and the format's own span and path reads. + public static readonly string[] Entries = [ + "stream", "path", "async-path", "data", + "skip-stream", "skip-path", "skip-async-path", "skip-data", + "format-span", "format-path"]; + + /// + /// Each entry point's description of , as "entry: description". + /// and are the format's own reads, returning the file or null. + /// + public static string[] ReadEverywhere (byte[] bytes, string name, Func formatSpan, Func formatPath) => + [.. Entries.Select (entry => entry + ": " + Describe (bytes, name, entry, formatSpan, formatPath))]; + + /// Asserts that every entry point read the same thing. + public static void AssertAgree (string[] reads, string label) => + Assert.HasCount (1, reads.Select (r => r[(r.IndexOf (':') + 2)..]).Distinct (), label + ": " + string.Join (" | ", reads)); + + public static string Describe (IMediaFile file) => + $"{file.AudioProperties?.Duration.Ticks}/{file.AudioProperties?.SampleRate}/{file.AudioProperties?.Channels}/{file.Tag?.Title}"; + + static string Describe (byte[] bytes, string name, string entry, Func formatSpan, Func formatPath) + { + var files = new MockFileSystem (); + files.AddFile (name, bytes); + var skip = new MediaReadOptions { SkipPictures = true }; + try { + if (entry == "format-span") + return formatSpan (bytes) is { } own ? Describe (own) : "FAIL"; + if (entry == "format-path") + return formatPath (name, files) is { } fromPath ? Describe (fromPath) : "FAIL"; + + var read = entry switch { + "stream" => MediaFile.Read (new MemoryStream (bytes, writable: false), name), + "path" => MediaFile.Read (name, files), + "async-path" => MediaFile.ReadAsync (name, files).GetAwaiter ().GetResult (), + "data" => MediaFile.ReadFromData (bytes, name), + "skip-stream" => MediaFile.Read (new MemoryStream (bytes, writable: false), skip, name), + "skip-path" => MediaFile.Read (name, skip, files), + "skip-async-path" => MediaFile.ReadAsync (name, skip, files).GetAwaiter ().GetResult (), + _ => MediaFile.ReadFromData (bytes, skip, name), + }; + return read.IsSuccess ? Describe ((IMediaFile)read.File!) : "FAIL"; + } catch (Exception ex) when (ex is not AssertFailedException) { + return "THREW " + ex.GetType ().Name; + } + } +} diff --git a/tests/TagLibSharp2.Tests/Kit/SparseFileSystem.cs b/tests/TagLibSharp2.Tests/Kit/SparseFileSystem.cs new file mode 100644 index 00000000..ff5966f1 --- /dev/null +++ b/tests/TagLibSharp2.Tests/Kit/SparseFileSystem.cs @@ -0,0 +1,305 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using TagLibSharp2.Core; + +namespace TagLibSharp2.Tests.Kit; + +/// +/// A file of a head, a run of bytes and a tail. The run costs nothing to hold, so a file of +/// several gigabytes is a few hundred bytes of memory, and a save that copies its run is checked as it streams. +/// +internal sealed class SparseFile (byte[] head, long runLength, byte[] tail) +{ + public byte[] Head { get; } = head; + + public long RunLength { get; } = runLength; + + public byte[] Tail { get; } = tail; + + public long Length => Head.Length + RunLength + Tail.Length; + + /// Where the run starts. + public long RunStart => Head.Length; + + /// Copies the bytes at into . + public void Read (long position, Span into) + { + while (!into.IsEmpty) { + int count; + if (position < Head.Length) { + count = (int)Math.Min (into.Length, Head.Length - position); + Head.AsSpan ((int)position, count).CopyTo (into); + } else if (position < RunStart + RunLength) { + count = (int)Math.Min (into.Length, RunStart + RunLength - position); + count = Pattern.Copy (position - RunStart, into[..count]); + } else { + var at = position - RunStart - RunLength; + count = (int)Math.Min (into.Length, Tail.Length - at); + Tail.AsSpan ((int)at, count).CopyTo (into); + } + + position += count; + into = into[count..]; + } + } +} + +/// +/// The bytes of a 's run: a pseudo-random block of a prime length, repeated. A run copied to +/// another offset, cut, or shifted by any number of bytes but a multiple of no longer matches. +/// +internal static class Pattern +{ + public const int Period = 65_521; + + // A run is found in a written file by its first bytes. + public const int SignatureLength = 64; + + static readonly byte[] Block = Make (); + + public static ReadOnlySpan Signature => Block.AsSpan (0, SignatureLength); + + /// Copies the run's bytes from into , up to the end of a block. + public static int Copy (long index, Span into) + { + var at = (int)(index % Period); + var count = Math.Min (into.Length, Period - at); + Block.AsSpan (at, count).CopyTo (into); + return count; + } + + /// How many of 's first bytes are the run's bytes from . + public static int Matching (long index, ReadOnlySpan data) + { + var matched = 0; + while (matched < data.Length) { + var at = (int)((index + matched) % Period); + var count = Math.Min (data.Length - matched, Period - at); + var same = data.Slice (matched, count).CommonPrefixLength (Block.AsSpan (at, count)); + matched += same; + if (same < count) + break; + } + + return matched; + } + + static byte[] Make () + { + var block = new byte[Period]; + var state = 0x2545F491u; + for (var i = 0; i < block.Length; i++) { + state ^= state << 13; + state ^= state >> 17; + state ^= state << 5; + block[i] = (byte)state; + } + + return block; + } +} + +/// +/// A file system of s. A file written to it is kept as a head, the run of +/// bytes the writer copied (found by its first bytes, then checked byte by byte as it streams), +/// and a tail; at most 16 MB of head and of tail, so a save that copies a run of gigabytes needs no more memory. +/// +internal sealed class SparseFileSystem : IFileSystem +{ + const int MaxKept = 16 << 20; + + readonly Dictionary _files = new (StringComparer.Ordinal); + + public void Add (string path, SparseFile file) => _files[path] = file; + + public SparseFile Get (string path) => _files.TryGetValue (path, out var file) ? file : throw new FileNotFoundException (path); + + public bool FileExists (string path) => _files.ContainsKey (path); + + public Stream OpenRead (string path) => new Reader (Get (path)); + + public Stream OpenReadWrite (string path) => throw new NotSupportedException ("A sparse file is written whole."); + + public Stream Create (string path) => new Sink (this, path); + + public byte[] ReadAllBytes (string path) + { + var file = Get (path); + if (file.Length > MaxKept) + throw new IOException ($"{path} is {file.Length} bytes; a sparse file is read whole only up to {MaxKept}"); + var bytes = new byte[file.Length]; + file.Read (0, bytes); + return bytes; + } + + public Task ReadAllBytesAsync (string path, CancellationToken cancellationToken = default) => + Task.FromResult (ReadAllBytes (path)); + + public void WriteAllBytes (string path, ReadOnlySpan data) + { + using var sink = Create (path); + sink.Write (data); + } + + public Task WriteAllBytesAsync (string path, ReadOnlyMemory data, CancellationToken cancellationToken = default) + { + WriteAllBytes (path, data.Span); + return Task.CompletedTask; + } + + public void Delete (string path) => _files.Remove (path); + + public void Move (string sourcePath, string destinationPath) + { + _files[destinationPath] = Get (sourcePath); + _files.Remove (sourcePath); + } + + public string? GetDirectoryName (string path) => Path.GetDirectoryName (path); + + public string GetFileName (string path) => Path.GetFileName (path); + + public string CombinePath (string path1, string path2) => Path.Combine (path1, path2); + + sealed class Reader (SparseFile file) : Stream + { + long _position; + + public override bool CanRead => true; + public override bool CanSeek => true; + public override bool CanWrite => false; + public override long Length => file.Length; + + public override long Position { + get => _position; + set => _position = value >= 0 ? value : throw new ArgumentOutOfRangeException (nameof (value)); + } + + public override int Read (byte[] buffer, int offset, int count) => Read (buffer.AsSpan (offset, count)); + + public override int Read (Span buffer) + { + var count = (int)Math.Max (0, Math.Min (buffer.Length, file.Length - _position)); + file.Read (_position, buffer[..count]); + _position += count; + return count; + } + + public override long Seek (long offset, SeekOrigin origin) => Position = origin switch { + SeekOrigin.Begin => offset, + SeekOrigin.Current => _position + offset, + _ => file.Length + offset, + }; + + public override void Flush () { } + public override void SetLength (long value) => throw new NotSupportedException (); + public override void Write (byte[] buffer, int offset, int count) => throw new NotSupportedException (); + } + + // Head until the run's signature is written, then the run while each byte matches, then the tail. A writer may + // seek back to patch a size in the head or the tail; a patch over the run must leave it as it was. + sealed class Sink (SparseFileSystem owner, string path) : Stream + { + readonly MemoryStream _head = new (); + readonly MemoryStream _tail = new (); + long _runLength = -1; + bool _inTail; + long _length; + long _position; + bool _committed; + + public override bool CanRead => false; + public override bool CanSeek => true; + public override bool CanWrite => true; + public override long Length => _length; + + public override long Position { + get => _position; + set => _position = value >= 0 && value <= _length ? value : throw new IOException ("A sparse file is written in order, then patched"); + } + + public override long Seek (long offset, SeekOrigin origin) => Position = origin switch { + SeekOrigin.Begin => offset, + SeekOrigin.Current => _position + offset, + _ => _length + offset, + }; + + public override void Write (byte[] buffer, int offset, int count) => Write (buffer.AsSpan (offset, count)); + + public override void Write (ReadOnlySpan data) + { + if (_position < _length) { + Patch (data); + return; + } + + _length += data.Length; + _position = _length; + if (_inTail) { + Keep (_tail, data); + return; + } + + if (_runLength < 0) { + var searchFrom = (int)Math.Max (0, _head.Length - (Pattern.SignatureLength - 1)); + Keep (_head, data); + var held = _head.GetBuffer ().AsSpan (0, (int)_head.Length); + var found = held[searchFrom..].IndexOf (Pattern.Signature); + if (found < 0) + return; + + var start = searchFrom + found; + var after = held[start..].ToArray (); + _head.SetLength (start); + _runLength = 0; + data = after; + } + + var matched = Pattern.Matching (_runLength, data); + _runLength += matched; + if (matched < data.Length) { + _inTail = true; + Keep (_tail, data[matched..]); + } + } + + void Patch (ReadOnlySpan data) + { + if (_position + data.Length > _length) + throw new IOException ("A patch runs past the end of a sparse file"); + var runStart = _runLength < 0 ? _length : _head.Length; + var runEnd = runStart + Math.Max (0, _runLength); + if (_position + data.Length <= runStart) { + data.CopyTo (_head.GetBuffer ().AsSpan ((int)_position)); + } else if (_position >= runEnd) { + data.CopyTo (_tail.GetBuffer ().AsSpan ((int)(_position - runEnd))); + } else if (_position < runStart || _position + data.Length > runEnd || Pattern.Matching (_position - runStart, data) < data.Length) { + throw new IOException ("A patch changes the run of a sparse file"); + } + + _position += data.Length; + } + + static void Keep (MemoryStream into, ReadOnlySpan data) + { + if (into.Length + data.Length > MaxKept) + throw new IOException ($"A sparse file keeps at most {MaxKept} bytes before and after its run"); + into.Write (data); + } + + protected override void Dispose (bool disposing) + { + if (disposing && !_committed) { + _committed = true; + owner._files[path] = new SparseFile (_head.ToArray (), Math.Max (0, _runLength), _tail.ToArray ()); + } + + base.Dispose (disposing); + } + + public override void Flush () { } + public override int Read (byte[] buffer, int offset, int count) => throw new NotSupportedException (); + public override void SetLength (long value) => throw new NotSupportedException (); + } +} diff --git a/tests/TagLibSharp2.Tests/Matroska/MatroskaAlbumKeepsTitleTests.cs b/tests/TagLibSharp2.Tests/Matroska/MatroskaAlbumKeepsTitleTests.cs index 0433cb25..3c42a695 100644 --- a/tests/TagLibSharp2.Tests/Matroska/MatroskaAlbumKeepsTitleTests.cs +++ b/tests/TagLibSharp2.Tests/Matroska/MatroskaAlbumKeepsTitleTests.cs @@ -68,18 +68,20 @@ public partial class MatroskaFileTests [("segment title", "set album, then title")] = (NewTitle, NewAlbum, [NewTitle], [NewAlbum]), [("segment title", "set title, then album")] = (NewTitle, NewAlbum, [NewTitle], [NewAlbum]), - // The untargeted TITLE is ffmpeg's title. The album is read from it until an ALBUM exists; a clear moves the title to 30. + // The untargeted TITLE is the title alone, as ffprobe, exiftool and MediaInfo show it (#221): it is no album, a + // clear of the album leaves it where it is, and a new title replaces it in place. [("untargeted TITLE", "set album")] = (OldTitle, NewAlbum, [OldTitle], [NewAlbum]), [("untargeted TITLE", "clear album")] = (OldTitle, null, [OldTitle], []), - [("untargeted TITLE", "write back album")] = (OldTitle, OldTitle, [OldTitle], []), - [("untargeted TITLE", "set album, then title")] = (NewTitle, NewAlbum, [OldTitle, NewTitle], [NewAlbum]), - [("untargeted TITLE", "set title, then album")] = (NewTitle, NewAlbum, [OldTitle, NewTitle], [NewAlbum]), + [("untargeted TITLE", "write back album")] = (OldTitle, null, [OldTitle], []), + [("untargeted TITLE", "set album, then title")] = (NewTitle, NewAlbum, [NewTitle], [NewAlbum]), + [("untargeted TITLE", "set title, then album")] = (NewTitle, NewAlbum, [NewTitle], [NewAlbum]), [("segment title, untargeted TITLE", "set album")] = (OldTitle, NewAlbum, [OldAlbum], [NewAlbum]), - [("segment title, untargeted TITLE", "clear album")] = (OldTitle, null, [OldTitle], []), - [("segment title, untargeted TITLE", "write back album")] = (OldTitle, OldAlbum, [OldAlbum], []), - [("segment title, untargeted TITLE", "set album, then title")] = (NewTitle, NewAlbum, [OldAlbum, NewTitle], [NewAlbum]), - [("segment title, untargeted TITLE", "set title, then album")] = (NewTitle, NewAlbum, [OldAlbum, NewTitle], [NewAlbum]), + [("segment title, untargeted TITLE", "clear album")] = (OldTitle, null, [OldAlbum], []), + [("segment title, untargeted TITLE", "write back album")] = (OldTitle, null, [OldAlbum], []), + // The untargeted TITLE is a title beside the segment title: a new title replaces it in place too (review 8, N1). + [("segment title, untargeted TITLE", "set album, then title")] = (NewTitle, NewAlbum, [NewTitle], [NewAlbum]), + [("segment title, untargeted TITLE", "set title, then album")] = (NewTitle, NewAlbum, [NewTitle], [NewAlbum]), [("untargeted ALBUM", "set album")] = (null, NewAlbum, [], [NewAlbum]), [("untargeted ALBUM", "clear album")] = (null, null, [], []), @@ -136,23 +138,24 @@ public partial class MatroskaFileTests [("segment title, no Tags", "set album, then title")] = (NewTitle, NewAlbum, [NewTitle], [NewAlbum]), [("segment title, no Tags", "set title, then album")] = (NewTitle, NewAlbum, [NewTitle], [NewAlbum]), - // With an explicit album TITLE beside it, ffmpeg's untargeted TITLE is the title, whichever Tag comes first. + // With an explicit album TITLE beside it, ffmpeg's untargeted TITLE is the title, whichever Tag comes first, and a + // new title replaces it there as well as at 30, so no reader shows the old one (#221). [("untargeted TITLE, target 50 TITLE", "set album")] = (OldTitle, NewAlbum, [OldTitle, NewAlbum, OldTitle], []), [("untargeted TITLE, target 50 TITLE", "clear album")] = (OldTitle, null, [OldTitle], []), [("untargeted TITLE, target 50 TITLE", "write back album")] = (OldTitle, OldAlbum, [OldTitle, OldAlbum], []), - [("untargeted TITLE, target 50 TITLE", "set album, then title")] = (NewTitle, NewAlbum, [OldTitle, NewAlbum, NewTitle], []), - [("untargeted TITLE, target 50 TITLE", "set title, then album")] = (NewTitle, NewAlbum, [OldTitle, NewAlbum, NewTitle], []), + [("untargeted TITLE, target 50 TITLE", "set album, then title")] = (NewTitle, NewAlbum, [NewTitle, NewAlbum, NewTitle], []), + [("untargeted TITLE, target 50 TITLE", "set title, then album")] = (NewTitle, NewAlbum, [NewTitle, NewAlbum, NewTitle], []), [("target 50 TITLE, untargeted TITLE", "set album")] = (OldTitle, NewAlbum, [NewAlbum, OldTitle, OldTitle], []), [("target 50 TITLE, untargeted TITLE", "clear album")] = (OldTitle, null, [OldTitle], []), [("target 50 TITLE, untargeted TITLE", "write back album")] = (OldTitle, OldAlbum, [OldAlbum, OldTitle], []), - [("target 50 TITLE, untargeted TITLE", "set album, then title")] = (NewTitle, NewAlbum, [NewAlbum, OldTitle, NewTitle], []), - [("target 50 TITLE, untargeted TITLE", "set title, then album")] = (NewTitle, NewAlbum, [NewAlbum, OldTitle, NewTitle], []), + [("target 50 TITLE, untargeted TITLE", "set album, then title")] = (NewTitle, NewAlbum, [NewAlbum, NewTitle, NewTitle], []), + [("target 50 TITLE, untargeted TITLE", "set title, then album")] = (NewTitle, NewAlbum, [NewAlbum, NewTitle, NewTitle], []), [("none", "set album, then clear it")] = (null, null, [], []), [("segment title", "set album, then clear it")] = (OldTitle, null, [], []), [("untargeted TITLE", "set album, then clear it")] = (OldTitle, null, [OldTitle], []), - [("segment title, untargeted TITLE", "set album, then clear it")] = (OldTitle, null, [OldTitle], []), + [("segment title, untargeted TITLE", "set album, then clear it")] = (OldTitle, null, [OldAlbum], []), [("untargeted ALBUM", "set album, then clear it")] = (null, null, [], []), [("segment title, untargeted ALBUM", "set album, then clear it")] = (OldTitle, null, [], []), [("target 50 TITLE", "set album, then clear it")] = (OldAlbum, null, [OldAlbum], []), @@ -192,8 +195,8 @@ public partial class MatroskaFileTests [("untargeted TITLE, target 50 TITLE in two languages", "set album")] = (OldTitle, NewAlbum, [OldTitle, "AlbumFr", NewAlbum, OldTitle], []), [("untargeted TITLE, target 50 TITLE in two languages", "clear album")] = (OldTitle, null, [OldTitle], []), [("untargeted TITLE, target 50 TITLE in two languages", "write back album")] = (OldTitle, OldAlbum, [OldTitle, "AlbumFr", OldAlbum], []), - [("untargeted TITLE, target 50 TITLE in two languages", "set album, then title")] = (NewTitle, NewAlbum, [OldTitle, "AlbumFr", NewAlbum, NewTitle], []), - [("untargeted TITLE, target 50 TITLE in two languages", "set title, then album")] = (NewTitle, NewAlbum, [OldTitle, "AlbumFr", NewAlbum, NewTitle], []), + [("untargeted TITLE, target 50 TITLE in two languages", "set album, then title")] = (NewTitle, NewAlbum, [NewTitle, "AlbumFr", NewAlbum, NewTitle], []), + [("untargeted TITLE, target 50 TITLE in two languages", "set title, then album")] = (NewTitle, NewAlbum, [NewTitle, "AlbumFr", NewAlbum, NewTitle], []), [("untargeted TITLE, target 50 TITLE in two languages", "set album, then clear it")] = (OldTitle, null, [OldTitle], []), }; diff --git a/tests/TagLibSharp2.Tests/Matroska/MatroskaChapterEditTests.cs b/tests/TagLibSharp2.Tests/Matroska/MatroskaChapterEditTests.cs index 18884ed0..53e6ade5 100644 --- a/tests/TagLibSharp2.Tests/Matroska/MatroskaChapterEditTests.cs +++ b/tests/TagLibSharp2.Tests/Matroska/MatroskaChapterEditTests.cs @@ -100,7 +100,7 @@ public void SaveChapters_OrderedEditionWithAKeptLeaf_SavesAfterAnEdit () } [TestMethod] - public void SaveChapters_EditionsPastTheBudget_StayBeforeAnAddedEdition () + public void SaveChapters_AnEditionAddedPastTheBudget_IsRefused () { var count = 30_000; var editions = new byte[count][]; @@ -114,10 +114,13 @@ public void SaveChapters_EditionsPastTheBudget_StayBeforeAnAddedEdition () Assert.IsTrue (file.Chapters.Editions.Count < count); file.Chapters.AddEdition ().AddChapter (TimeSpan.Zero, null, "ADDED EDITION"); - var bytes = Save (file, data); + // An added edition goes after the editions kept past the budget, where a read never reaches it, so the save is + // refused rather than reporting a success no read shows (#247). + var result = file.SaveToFile ("/out.mka", data, new TagLibSharp2.Tests.Core.MockFileSystem ()); - Assert.IsTrue (bytes.AsSpan ().IndexOf (last) >= 0); - Assert.IsTrue (bytes.AsSpan ().IndexOf (last) < bytes.AsSpan ().IndexOf ("ADDED EDITION"u8)); + Assert.IsFalse (result.IsSuccess); + StringAssert.Contains (result.Error, "65,536"); + _ = last; } [TestMethod] diff --git a/tests/TagLibSharp2.Tests/Matroska/MatroskaChapterLimitTests.cs b/tests/TagLibSharp2.Tests/Matroska/MatroskaChapterLimitTests.cs index 06ea9e59..ecbe8832 100644 --- a/tests/TagLibSharp2.Tests/Matroska/MatroskaChapterLimitTests.cs +++ b/tests/TagLibSharp2.Tests/Matroska/MatroskaChapterLimitTests.cs @@ -60,12 +60,17 @@ public void ReadChapters_AMillionEmptyEditions_KeepAtMostTheBudget () } [TestMethod] - public void ReadChapters_DisplaysPastTheBudget_AreKeptAndWrittenBack () + [DataRow (true, DisplayName = "displays with a language")] + [DataRow (false, DisplayName = "displays without a language")] + public void ReadChapters_DisplaysPastTheBudget_AreKeptAndWrittenBack (bool languages) { var count = 70_000; var displays = new byte[count][]; - for (var i = 0; i < count; i++) - displays[i] = Master (0x80, Element (0x85, new[] { (byte)('a' + (i % 26)) })); + for (var i = 0; i < count; i++) { + var text = Element (0x85, new[] { (byte)('a' + (i % 26)) }); + displays[i] = Master (0x80, languages ? Concat (text, Element (0x437C, "fre"u8)) : text); + } + var last = Master (0x80, Element (0x85, "LAST"u8)); var atom = BigElement (0xB6, Concat (UInt (0x73C4, 1), UInt (0x91, 0), Concat (displays), last)); var data = Matroska (BigElement (0x18538067, Concat ( @@ -77,9 +82,20 @@ public void ReadChapters_DisplaysPastTheBudget_AreKeptAndWrittenBack () Assert.IsTrue (chapter.Displays.Count < count); chapter.Title = "First"; + if (!languages) { + // Each display read without a language is written with the default "eng" the read took, one element more, + // so the displays read last would go past the budget, where a read never reaches them: refused (#247). + var refused = file.SaveToFile ("/out.mka", data, new TagLibSharp2.Tests.Core.MockFileSystem ()); + Assert.IsFalse (refused.IsSuccess); + StringAssert.Contains (refused.Error, "65,536"); + return; + } + var bytes = Save (file, data); Assert.IsTrue (bytes.AsSpan ().IndexOf (last) >= 0); - Assert.AreEqual ("First", MatroskaFile.Read (bytes).File!.Chapters.Editions[0].Chapters[0].Title); + var back = MatroskaFile.Read (bytes).File!.Chapters.Editions[0].Chapters[0]; + Assert.AreEqual ("First", back.Title); + Assert.AreEqual (chapter.Displays.Count, back.Displays.Count, "every display read is read again"); } [TestMethod] @@ -98,14 +114,22 @@ public void ReadChapters_AtomsPastTheBudget_AreKeptAndWrittenBack () var edition = file.Chapters.Editions[0]; Assert.IsTrue (edition.Chapters.Count < count); - edition.Chapters[0].Title = "First"; + // An added atom would go after the kept ones, where a read never reaches it: the save is refused (#247). edition.AddChapter (TimeSpan.FromSeconds (5), null, "ADDED"); + var refused = file.SaveToFile ("/out.mka", data, new TagLibSharp2.Tests.Core.MockFileSystem ()); + Assert.IsFalse (refused.IsSuccess); + StringAssert.Contains (refused.Error, "65,536"); + edition.Chapters.RemoveAt (edition.Chapters.Count - 1); + + // These atoms hold only a UID, so any edit of one writes its start time too, one entry more, and pushes the last + // atom read past the budget: refused as well. With the added atom taken out, a save leaves the atoms read and the + // ones kept past the budget as they were. + edition.Chapters[0].Uid = 424_242; + Assert.IsFalse (file.SaveToFile ("/out.mka", data, new TagLibSharp2.Tests.Core.MockFileSystem ()).IsSuccess); + edition.Chapters[0].Uid = 1; var bytes = Save (file, data); Assert.IsTrue (bytes.AsSpan ().IndexOf (last) >= 0); - // File order holds: the kept atoms stay after the parsed ones, and an added atom comes last. - Assert.IsTrue (bytes.AsSpan ().IndexOf (last) < bytes.AsSpan ().IndexOf ("ADDED"u8)); - Assert.IsTrue (bytes.AsSpan ().IndexOf (Master (0xB6, UInt (0x73C4, (ulong)count))) > bytes.AsSpan ().IndexOf ("First"u8)); - Assert.AreEqual ("First", MatroskaFile.Read (bytes).File!.Chapters.Editions[0].Chapters[0].Title); + CollectionAssert.AreEqual (data, bytes); } [TestMethod] diff --git a/tests/TagLibSharp2.Tests/Matroska/MatroskaChapterTests.cs b/tests/TagLibSharp2.Tests/Matroska/MatroskaChapterTests.cs index cdb99784..2fb0760d 100644 --- a/tests/TagLibSharp2.Tests/Matroska/MatroskaChapterTests.cs +++ b/tests/TagLibSharp2.Tests/Matroska/MatroskaChapterTests.cs @@ -147,16 +147,34 @@ public void ReadChapters_DefaultEdition_IsTheFirstFlaggedOrTheFirst () Assert.AreEqual (2UL, second.DefaultEdition!.Uid); } + // ChapterUID is mandatory and not 0 (RFC 9559 section 5.1.7.1.4.1), but a read keeps a missing or 0 UID as it is, so + // two reads of the file are the same and a save that leaves the chapter alone writes it as it was (#244). A save + // that writes the chapter changed gives it a new random UID, which the chapter keeps. [TestMethod] - public void ReadChapters_MissingOrZeroUid_GetsANonzeroUid () + [DataRow ("matroska")] + [DataRow ("webm")] + public void ReadChapters_MissingOrZeroUid_ReadsAs0_AndAnEditWritesANewUid (string docType) { var chapters = ChaptersElement (EditionEntry ( - Master (0xB6, UInt (0x91, 0)), - Master (0xB6, Concat (UInt (0x73C4, 0), UInt (0x91, 0))))); - var edition = MatroskaFile.Read (FileWith (chapters)).File!.Chapters.Editions[0]; + Master (0xB6, Concat (UInt (0x91, 0), Display ("A"))), + Master (0xB6, Concat (UInt (0x73C4, 0), UInt (0x91, 0), Display ("B"))))); + var original = Matroska (Master (0x18538067, chapters), docType); + var file = MatroskaFile.Read (original).File!; + var edition = file.Chapters.Editions[0]; + Assert.AreEqual (0UL, edition.Chapters[0].Uid); + Assert.AreEqual (0UL, edition.Chapters[1].Uid); + CollectionAssert.AreEqual (original, file.Render (original).ToArray (), "a save with no edit"); + + edition.Chapters[0].Title = "Changed"; + var saved = file.Render (original).ToArray (); - Assert.AreNotEqual (0UL, edition.Chapters[0].Uid); - Assert.AreNotEqual (0UL, edition.Chapters[1].Uid); + var back = MatroskaFile.Read (saved).File!.Chapters.Editions[0]; + Assert.AreNotEqual (0UL, back.Chapters[0].Uid, "the chapter written changed"); + Assert.AreEqual (0UL, edition.Chapters[0].Uid, "a render is no save over the source: the object has no UID yet"); + Assert.AreEqual (0UL, back.Chapters[1].Uid, "the chapter left alone"); + // WebM writes the chapter left alone from the model, a Matroska file from its bytes: either way its UID of 0. + Assert.AreEqual (1, CountOf (saved, UInt (0x73C4, 0)), "the ChapterUID of 0, as read"); + CollectionAssert.AreEqual (saved, file.Render (original).ToArray (), "the UID drawn for the chapter is the same on every write"); } [TestMethod] @@ -245,10 +263,15 @@ public void ReadChapters_PastTheEntryLimit_AreKeptAsBytes () var file = MatroskaFile.Read (data).File!; Assert.IsTrue (file.Chapters.Editions.Count < count); + // A title adds a display to a chapter that had none: two more entries, which would push the last edition read + // past the budget, so the save is refused (#247). A start time keeps the count, and is saved. file.Chapters.Editions[0].Chapters[0].Title = "First"; + Assert.IsFalse (file.SaveToFile ("/out.mka", data, new TagLibSharp2.Tests.Core.MockFileSystem ()).IsSuccess); + file.Chapters.Editions[0].Chapters[0].Title = null; + file.Chapters.Editions[0].Chapters[0].StartNanoseconds = 5; var bytes = Save (file, data); var again = MatroskaFile.Read (bytes).File!; - Assert.AreEqual ("First", again.Chapters.Editions[0].Chapters[0].Title); + Assert.AreEqual (5UL, again.Chapters.Editions[0].Chapters[0].StartNanoseconds); Assert.IsTrue (bytes.AsSpan ().IndexOf (last) >= 0); } @@ -399,15 +422,54 @@ public void SaveChapters_NewUids_AreRandomAndNonzero () for (var i = 0; i < 64; i++) { var chapter = chapters.AddChapter (TimeSpan.FromSeconds (i)); Assert.AreNotEqual (0UL, chapter.Uid); + // Always 8 bytes wide, so a save's size does not depend on the draw (#244). + Assert.IsTrue (chapter.Uid >= 1UL << 63, $"{chapter.Uid:X}"); Assert.IsTrue (seen.Add (chapter.Uid)); } Assert.AreNotEqual (0UL, chapters.Editions[0].Uid); Assert.AreNotEqual (0UL, new MatroskaChapter ().Uid); - Assert.ThrowsExactly (() => new MatroskaChapter ().Uid = 0); Assert.ThrowsExactly (() => new MatroskaChapter ().Start = TimeSpan.FromSeconds (-1)); } + // A Uid of 0 means what a read 0 means: no UID yet. A chapter is not given one until a save writes it with values + // that changed; then it keeps the UID written (#244). So a read chapter's Uid can be copied to another. + [TestMethod] + public async Task ChapterUid_0_IsNoUidYet_AndASaveGivesOne () + { + var original = Matroska (Master (0x18538067, Concat ( + ChaptersElement (EditionEntry (Master (0xB6, Concat (UInt (0x91, 0), Display ("A"))), Atom (5, 0, null, Display ("B")))), + Master (0x1F43B675, new byte[] { 1 })))); + var fs = new MockFileSystem (); + fs.AddFile ("/in.mka", original); + var file = (MatroskaFile)MediaFile.Read ("/in.mka", fs).File!; + var edition = file.Chapters.Editions[0]; + var copy = new MatroskaChapter { Uid = edition.Chapters[0].Uid, Title = "Copy" }; + edition.Chapters[1].Uid = 0; + edition.Chapters.Add (copy); + Assert.AreEqual (0UL, copy.Uid); + Assert.AreEqual (0UL, edition.Chapters[1].Uid); + + Assert.IsTrue (file.SaveToFile (fs).IsSuccess); + + var back = MatroskaFile.Read (fs.ReadAllBytes ("/in.mka")).File!.Chapters.Editions[0]; + Assert.AreEqual (0UL, back.Chapters[0].Uid, "the chapter left alone has none, as read"); + Assert.AreNotEqual (0UL, back.Chapters[1].Uid, "set to 0: a new one"); + Assert.AreNotEqual (5UL, back.Chapters[1].Uid, "set to 0: a new one"); + Assert.AreNotEqual (0UL, back.Chapters[2].Uid, "a new chapter set to 0: one is drawn"); + Assert.AreEqual (back.Chapters[1].Uid, edition.Chapters[1].Uid, "the object keeps the UID the save wrote"); + Assert.AreEqual (back.Chapters[2].Uid, copy.Uid, "the object keeps the UID the save wrote"); + Assert.IsTrue ((await file.SaveToFileAsync (fs)).IsSuccess); + CollectionAssert.AreEqual (back.Chapters.Select (c => c.Uid).ToArray (), MatroskaFile.Read (fs.ReadAllBytes ("/in.mka")).File!.Chapters.Editions[0].Chapters.Select (c => c.Uid).ToArray (), "a second save keeps them"); + + // Set to 0 again: a new one, not the one written before. + var written = copy.Uid; + copy.Uid = 0; + Assert.IsTrue (file.SaveToFile (fs).IsSuccess); + Assert.AreNotEqual (0UL, copy.Uid); + Assert.AreNotEqual (written, copy.Uid); + } + [TestMethod] public void SaveChapters_Clear_RemovesTheElementAndItsSeek () { diff --git a/tests/TagLibSharp2.Tests/Matroska/MatroskaFileTests.cs b/tests/TagLibSharp2.Tests/Matroska/MatroskaFileTests.cs index 92f10fa7..58b0373d 100644 --- a/tests/TagLibSharp2.Tests/Matroska/MatroskaFileTests.cs +++ b/tests/TagLibSharp2.Tests/Matroska/MatroskaFileTests.cs @@ -2668,15 +2668,15 @@ static byte[] Simple (string name, string text, bool isDefault = true) return Master (0x67C8, body); } - static byte[] Matroska (byte[] segment, string docType = "matroska") + internal static byte[] Matroska (byte[] segment, string docType = "matroska") { var ebml = Master (0x1A45DFA3, Element (0x4282, Encoding.ASCII.GetBytes (docType))); return Concat (ebml, segment); } - static byte[] Master (ulong id, params byte[][] children) => Element (id, Concat (children)); + internal static byte[] Master (ulong id, params byte[][] children) => Element (id, Concat (children)); - static byte[] Element (ulong id, ReadOnlySpan payload) + internal static byte[] Element (ulong id, ReadOnlySpan payload) { var size = payload.Length < 0x7F ? new[] { (byte)(0x80 | payload.Length) } @@ -2708,7 +2708,7 @@ static byte[] Float64 (double value) return bytes; } - static byte[] Float32 (float value) + internal static byte[] Float32 (float value) { var bytes = new byte[4]; BinaryPrimitives.WriteSingleBigEndian (bytes, value); diff --git a/tests/TagLibSharp2.Tests/Matroska/MatroskaSaveStreamsTests.cs b/tests/TagLibSharp2.Tests/Matroska/MatroskaSaveStreamsTests.cs index df985960..c0ffbc70 100644 --- a/tests/TagLibSharp2.Tests/Matroska/MatroskaSaveStreamsTests.cs +++ b/tests/TagLibSharp2.Tests/Matroska/MatroskaSaveStreamsTests.cs @@ -109,7 +109,8 @@ static void AssertSaved ( long allocated) { Assert.IsTrue (save.IsSuccess, save.Error); - Assert.AreEqual (1, fs.SourceLengthGets, "source length reads"); + // The open, then the read-back that asks whether the save rewrote the source (#244), as AAC's and AIFF's do. + Assert.AreEqual (2, fs.SourceLengthGets, "source length reads"); Assert.IsTrue ( allocated < original.Length / 2, $"save allocated {allocated} bytes for a {original.Length} byte file"); diff --git a/tests/TagLibSharp2.Tests/Matroska/MatroskaSecondSaveTests.cs b/tests/TagLibSharp2.Tests/Matroska/MatroskaSecondSaveTests.cs new file mode 100644 index 00000000..5111a47e --- /dev/null +++ b/tests/TagLibSharp2.Tests/Matroska/MatroskaSecondSaveTests.cs @@ -0,0 +1,592 @@ +// 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.Reflection; +using TagLibSharp2.Core; +using TagLibSharp2.Matroska; +using TagLibSharp2.Tests.Core; +using TagLibSharp2.Tests.Kit; + +namespace TagLibSharp2.Tests.Matroska; + +/// +/// A second save from the same object writes what a fresh read of the first save would write (#244). Every field +/// is set, saved over the source, then cleared and saved again, by each of the six saves; the file must be the one +/// a fresh object, read from the first save, writes with the same clear. +/// +public partial class MatroskaFileTests +{ + static readonly Dictionary> SecondSaveShapes = new () { + // ffmpeg: the title is the segment title, and the only Tag is the untargeted one with ENCODER. + ["segment title, untargeted Tag"] = () => SecondSaveFile (SegmentInfo (OldTitle), Tags (Untargeted ())), + ["explicit target 50 TITLE only"] = () => SecondSaveFile ([], Tags (Tag (50, Simple ("TITLE", OldAlbum)))), + ["untargeted Tag with a track UID"] = () => SecondSaveFile ([], Tags (Master (0x7373, Concat (Master (0x63C0, UInt (0x63C5, 101)), Simple ("TITLE", OldTitle))))), + ["no Tags"] = () => SecondSaveFile ([]), + // Tags is identically recurring (RFC 8794 section 11.1.17): a read takes every copy. + ["two Tags elements"] = () => SecondSaveFile ([], Tags (Untargeted (Simple ("TITLE", OldTitle))), Tags (Tag (30, Simple ("ARTIST", "Art")))), + // A Tags element holding only an empty Tag: a read keeps it, and so does a save that leaves it empty. + ["Tags holding only an empty Tag"] = () => SecondSaveFile ([], Tags (Master (0x7373, Master (0x63C0, Array.Empty ())))), + // Two of them: a set fills the first, and a clear after a save keeps the one the file still holds empty. + ["Tags holding two empty Tags"] = () => SecondSaveFile ([], Tags (Master (0x7373, Master (0x63C0, Array.Empty ())), Master (0x7373, Master (0x63C0, Array.Empty ())))), + // RFC 9559 makes ChapterUID mandatory and not 0, but files without one exist. A WebM file's chapters are + // always written from the model, not copied, so whatever a read sets up is written. + ["chapter with no ChapterUID"] = () => SecondSaveFileWith ("matroska", ChaptersElement (EditionEntry (AtomWithoutUid ("Old")))), + ["WebM, chapter with a ChapterUID"] = () => SecondSaveFileWith ("webm", ChaptersElement (EditionEntry (Atom (1, 0, Second, Display ("Old")))), Tags (Untargeted (Simple ("TITLE", OldTitle)))), + ["WebM, chapter with no ChapterUID"] = () => SecondSaveFileWith ("webm", ChaptersElement (EditionEntry (AtomWithoutUid ("Old"))), Tags (Untargeted (Simple ("TITLE", OldTitle)))), + ["WebM, chapter with ChapterUID 0"] = () => SecondSaveFileWith ("webm", ChaptersElement (EditionEntry (Master (0xB6, Concat (UInt (0x73C4, 0), UInt (0x91, 0), UInt (0x92, Second), Display ("Old")))))), + ["WebM, a nested chapter with no ChapterUID"] = () => SecondSaveFileWith ("webm", ChaptersElement (EditionEntry (Atom (1, 0, Second, Display ("Old"), AtomWithoutUid ("Inner"))))), + // ffmpeg writes EditionEntry and ChapterAtom with 8-byte sizes, which a rewrite of either does not keep. + ["ffmpeg's chapters, 8-byte sizes"] = () => SecondSaveFileWith ("matroska", ChaptersElement (LongSized ([0x45, 0xB9], Concat ( + UInt (0x45BC, 0x1234), LongSized ([0xB6], Concat (UInt (0x73C4, 1), UInt (0x91, 0), UInt (0x92, Second), Display ("Old"))))))), + ["WebM, ffmpeg's chapters, 8-byte sizes"] = () => SecondSaveFileWith ("webm", ChaptersElement (LongSized ([0x45, 0xB9], LongSized ([0xB6], Concat ( + UInt (0x73C4, 1), UInt (0x91, 0), UInt (0x92, Second), Display ("Old")))))), + ["an EditionUID of 0"] = () => SecondSaveFileWith ("matroska", ChaptersElement (EditionEntry (UInt (0x45BC, 0), Atom (1, 0, Second, Display ("Old"))))), + // An album TITLE, then ffmpeg's untargeted Tag: a new album goes in the explicit Tag. + ["explicit target 50 TITLE, then an untargeted Tag"] = () => SecondSaveFile ([], Tags (Tag (50, Simple ("TITLE", OldAlbum)), Untargeted ())), + ["an empty Tag, then an untargeted TITLE"] = () => SecondSaveFile ([], Tags (Master (0x7373, Master (0x63C0, Array.Empty ())), Untargeted (Simple ("TITLE", OldTitle)))), + }; + + // An element whose size field is 8 bytes long, as ffmpeg writes it. + static byte[] LongSized (byte[] id, byte[] payload) + { + var size = new byte[8]; + size[0] = 0x01; + for (var i = 0; i < 7; i++) + size[7 - i] = (byte)((long)payload.Length >> (8 * i)); + return Concat (id, size, payload); + } + + static byte[] SecondSaveFile (byte[] info, params byte[][] tags) => + SecondSaveFileWith ("matroska", ChaptersElement (EditionEntry (Atom (1, 0, Second, Display ("Old")))), [info, .. tags]); + + static byte[] SecondSaveFileWith (string docType, byte[] chapters, params byte[][] infoAndTags) => Matroska (Master (0x18538067, Concat ( + infoAndTags.Length > 0 ? infoAndTags[0] : [], + Master (0x1654AE6B, AudioEntry (1, 44100)), + chapters, + Concat ([.. infoAndTags.Skip (1)]), + Master (0x1F43B675, new byte[] { 1 }))), docType); + + static byte[] AtomWithoutUid (string title) => Master (0xB6, Concat (UInt (0x91, 0), UInt (0x92, Second), Display (title))); + + // The tag properties a caller can set, each given a value of its type; an edit sets it, then clears it. + static readonly PropertyInfo[] SettableTagProperties = [.. typeof (MatroskaTag) + .GetProperties (BindingFlags.Public | BindingFlags.Instance) + .Where (p => p.CanWrite && p.SetMethod!.IsPublic && p.GetIndexParameters ().Length == 0 && SetValueFor (p.PropertyType) is not null) + .OrderBy (p => p.Name, StringComparer.Ordinal)]; + + static object? SetValueFor (Type type) => + type == typeof (string) ? "Set value" + : type == typeof (string[]) ? new[] { "Set value" } + : type == typeof (uint?) ? 7u + : type == typeof (int?) ? 7 + : type == typeof (double?) ? 0.5 + : type == typeof (bool) ? true + : null; + + static object? SetAgainValueFor (Type type) => + type == typeof (string) ? "Again" + : type == typeof (string[]) ? new[] { "Again" } + : type == typeof (uint?) ? 9u + : type == typeof (int?) ? 9 + : type == typeof (double?) ? 0.25 + : true; + + // Each edit: the set, the clear, what the file reads after the clear (null: what the original reads after the clear + // alone), and a set after that. + static readonly Dictionary Set, Action Clear, Action? Check, Action SetAgain)> SecondSaveEdits = BuildSecondSaveEdits (); + + static Dictionary, Action, Action?, Action)> BuildSecondSaveEdits () + { + var edits = new Dictionary, Action, Action?, Action)> { + ["chapter title, then back"] = ( + f => f.Chapters.Editions[0].Chapters[0].Title = "New", + f => f.Chapters.Editions[0].Chapters[0].Title = "Old", + f => Assert.AreEqual ("Old", f.Chapters.Editions[0].Chapters[0].Title), + f => f.Chapters.Editions[0].Chapters[0].Title = "Again"), + ["chapter added, then removed"] = ( + // A new chapter or edition draws a random UID; the oracle's must be the same one, so the edits give it. + f => f.Chapters.Editions[0].AddChapter (TimeSpan.FromSeconds (2), TimeSpan.FromSeconds (3), "Added").Uid = 0x7701, + f => f.Chapters.Editions[0].Chapters.RemoveAt (1), + f => Assert.AreEqual (1, f.Chapters.Editions[0].Chapters.Count), + f => f.Chapters.Editions[0].AddChapter (TimeSpan.FromSeconds (2), TimeSpan.FromSeconds (3), "Again").Uid = 0x7702), + ["edition added, then removed"] = ( + f => AddEdition (f, 0x8801, "Other"), + f => f.Chapters.RemoveEdition (f.Chapters.Editions[1]), + f => Assert.AreEqual (1, f.Chapters.Editions.Count), + f => AddEdition (f, 0x8802, "Again")), + ["picture, then none"] = ( + f => f.Tag.Pictures = [new TestPicture ("image/jpeg", PictureType.FrontCover, "", Jpeg)], + f => f.Tag.Pictures = [], + f => Assert.AreEqual (0, f.Tag.Pictures.Length), + f => f.Tag.Pictures = [new TestPicture ("image/jpeg", PictureType.FrontCover, "", Jpeg)]), + ["track disabled, then enabled"] = ( + f => f.Tracks[0].IsEnabled = false, + f => f.Tracks[0].IsEnabled = true, + f => Assert.IsTrue (f.Tracks[0].IsEnabled), + f => f.Tracks[0].IsEnabled = false), + }; + foreach (var property in SettableTagProperties) { + var value = SetValueFor (property.PropertyType); + var again = SetAgainValueFor (property.PropertyType); + edits[property.Name] = ( + f => property.SetValue (f.Tag, value), + // A clear sets a flag to false and the rest to null. + f => property.SetValue (f.Tag, property.PropertyType == typeof (bool) ? false : null), + null, + f => property.SetValue (f.Tag, again)); + } + + return edits; + } + + static void AddEdition (MatroskaFile file, ulong uid, string title) + { + var edition = file.Chapters.AddEdition (); + edition.Uid = uid; + edition.AddChapter (TimeSpan.Zero, TimeSpan.FromSeconds (1), title).Uid = uid + 1; + } + + // Each chapter of the fresh object that has no UID takes the one the object's chapter in its place has. + static void ShareDrawnUids (MatroskaChapters from, MatroskaChapters to) + { + for (var e = 0; e < Math.Min (from.Editions.Count, to.Editions.Count); e++) + ShareDrawnUids (from.Editions[e].Chapters, to.Editions[e].Chapters); + } + + static void ShareDrawnUids (IList from, IList to) + { + for (var c = 0; c < Math.Min (from.Count, to.Count); c++) { + if (to[c].Uid == 0 && from[c].Uid != 0) + to[c].Uid = from[c].Uid; + ShareDrawnUids (from[c].Chapters, to[c].Chapters); + } + } + + static string Describe (object? value) => value is string[] values ? $"[{string.Join (", ", values)}]" : value?.ToString () ?? "null"; + + public static IEnumerable SecondSaveCases () => + from shape in SecondSaveShapes.Keys + from edit in SecondSaveEdits.Keys + select new object[] { shape, edit }; + + // Pictures have an edit of their own below. + static readonly string[] Unswept = ["Pictures: IPicture[]"]; + + [TestMethod] + public void SecondSave_SweepsEveryTagFieldOfEveryType () + { + // A property of a type the sweep has no value for would drop out of it silently. + var unswept = typeof (MatroskaTag) + .GetProperties (BindingFlags.Public | BindingFlags.Instance) + .Where (p => p.CanWrite && p.SetMethod!.IsPublic && SetValueFor (p.PropertyType) is null) + .Select (p => $"{p.Name}: {p.PropertyType.Name}") + .OrderBy (n => n, StringComparer.Ordinal) + .ToArray (); + CollectionAssert.AreEqual (Unswept, unswept, string.Join (", ", unswept)); + Assert.IsTrue (SettableTagProperties.Length > 40, $"{SettableTagProperties.Length} properties"); + } + + // Set, save, clear, save, set again, save, on one object, each save over the source. Every save writes what a fresh + // object writes: one read from the file the save before left, given the same edits since that save, saved the same + // way, byte for byte (#244). After the clear, the value read is the one the original reads after the clear alone. + [TestMethod] + [DynamicData (nameof (SecondSaveCases))] + public async Task SecondSave_EverySaveWritesWhatAFreshReadWrites (string shape, string edit) + { + var (set, clear, check, setAgain) = SecondSaveEdits[edit]; + var original = SecondSaveShapes[shape] (); + var property = SettableTagProperties.FirstOrDefault (p => p.Name == edit); + Action[] steps = [set, clear, setAgain]; + foreach (var save in MatroskaSaves) { + var fs = new MockFileSystem (); + fs.AddFile ("/in.mka", original); + var file = (MatroskaFile)MediaFile.Read ("/in.mka", fs).File!; + for (var step = 0; step < steps.Length; step++) { + var before = fs.ReadAllBytes ("/in.mka"); + steps[step] (file); + var result = await SaveOverSource (file, save, fs); + var written = fs.ReadAllBytes ("/in.mka"); + + var oracleFs = new MockFileSystem (); + oracleFs.AddFile ("/in.mka", before); + var fresh = (MatroskaFile)MediaFile.Read ("/in.mka", oracleFs).File!; + steps[step] (fresh); + // A chapter written without a UID draws one; the fresh object takes the one this save drew. + ShareDrawnUids (file.Chapters, fresh.Chapters); + var expected = await SaveOverSource (fresh, save, oracleFs); + var label = $"{shape} / {edit} / {save} / save {step + 1}"; + Assert.AreEqual (expected.IsSuccess, result.IsSuccess, $"{label}: {result.Error} | {expected.Error}"); + var oracleBytes = oracleFs.ReadAllBytes ("/in.mka"); + // An added picture's attachment draws a random FileUID (RFC 9559 section 5.1.6.1.5) of any width, which a + // fresh object cannot share: those files are compared by every value read, pictures included. + if (edit == "picture, then none" && step != 1) + Assert.AreEqual (Facts.Of (MatroskaFile.Read (oracleBytes).File!, withoutPictures: false), Facts.Of (MatroskaFile.Read (written).File!, withoutPictures: false), label); + else + CollectionAssert.AreEqual (oracleBytes, written, label); + // WebM has no attachments: a picture is refused, by every save alike, and the file is left as it was. + if (!result.IsSuccess) { + Assert.IsTrue (file.Chapters.IsWebM && edit == "picture, then none", $"{label}: {result.Error}"); + CollectionAssert.AreEqual (before, written, label); + break; + } + + if (step != 1) + continue; + var back = MatroskaFile.Read (written).File!; + if (check is not null) { + check (back); + continue; + } + + // The value the original file reads after the clear alone, saved the same way. + var aloneFs = new MockFileSystem (); + aloneFs.AddFile ("/in.mka", original); + var alone = (MatroskaFile)MediaFile.Read ("/in.mka", aloneFs).File!; + clear (alone); + Assert.IsTrue ((await SaveOverSource (alone, save, aloneFs)).IsSuccess, label); + var clearedAlone = MatroskaFile.Read (aloneFs.ReadAllBytes ("/in.mka")).File!; + Assert.AreEqual (Describe (property!.GetValue (clearedAlone.Tag)), Describe (property.GetValue (back.Tag)), label); + } + } + } + + public static IEnumerable SaveEntryCases () => MatroskaSaves.Select (save => new object[] { save }); + + // A save that fails leaves the object as it was (#244). A chapter read without a ChapterUID that ends before it + // starts is renamed: the save is refused (RFC 9559 section 20.2.2). Set back, it is the file's chapter again, so a + // save leaves the file as it was. A UID drawn for the refused save is no part of the object. + [TestMethod] + [DynamicData (nameof (SaveEntryCases))] + public async Task SecondSave_AfterAFailedSave_AnEditSetBackLeavesTheFile (string save) + { + foreach (var docType in new[] { "webm", "matroska" }) { + var original = SecondSaveFileWith (docType, ChaptersElement (EditionEntry (Master (0xB6, Concat (UInt (0x91, Second), UInt (0x92, 0), Display ("Old")))))); + var fs = new MockFileSystem (); + fs.AddFile ("/in.mka", original); + var file = (MatroskaFile)MediaFile.Read ("/in.mka", fs).File!; + var chapter = file.Chapters.Editions[0].Chapters[0]; + chapter.Title = "Renamed"; + + var refused = await SaveOverSource (file, save, fs); + + Assert.IsFalse (refused.IsSuccess, $"{docType} {save}"); + StringAssert.Contains (refused.Error, "ends before it starts", $"{docType} {save}"); + Assert.AreEqual (0UL, chapter.Uid, $"{docType} {save}: no UID was given"); + chapter.Title = "Old"; + var saved = await SaveOverSource (file, save, fs); + Assert.IsTrue (saved.IsSuccess, $"{docType} {save}: {saved.Error}"); + CollectionAssert.AreEqual (original, fs.ReadAllBytes ("/in.mka"), $"{docType} {save}"); + } + } + + // A save elsewhere leaves the source, and so what the object holds for it: an edit saved elsewhere and set back + // leaves the source as it was, as a fresh read of it would. + [TestMethod] + [DynamicData (nameof (SaveEntryCases))] + public async Task SecondSave_AfterASaveElsewhere_AnEditSetBackLeavesTheSource (string save) + { + foreach (var shape in new[] { "chapter with no ChapterUID", "WebM, chapter with no ChapterUID", "WebM, chapter with ChapterUID 0", "segment title, untargeted Tag" }) { + var original = SecondSaveShapes[shape] (); + var fs = new MockFileSystem (); + fs.AddFile ("/in.mka", original); + var file = (MatroskaFile)MediaFile.Read ("/in.mka", fs).File!; + var chapter = file.Chapters.Editions[0].Chapters[0]; + chapter.Title = "Renamed"; + file.Tag.Album = "Elsewhere"; + Assert.IsTrue ((await SaveElsewhere (file, save, fs)).IsSuccess, $"{shape} {save}"); + + chapter.Title = "Old"; + file.Tag.Album = null; + Assert.IsTrue ((await SaveOverSource (file, save, fs)).IsSuccess, $"{shape} {save}"); + + CollectionAssert.AreEqual (original, fs.ReadAllBytes ("/in.mka"), $"{shape} {save}"); + Assert.AreEqual (MatroskaFile.Read (original).File!.Chapters.Editions[0].Chapters[0].Uid, chapter.Uid, $"{shape} {save}"); + } + } + + // After a save over the source nothing is pending, as on a fresh read of the saved file: no chapter, segment title + // or picture edit is left to write. + [TestMethod] + [DynamicData (nameof (SaveEntryCases))] + public async Task SecondSave_AfterASaveOverTheSource_NothingIsPending (string save) + { + var original = SecondSaveShapes["segment title, untargeted Tag"] (); + var fs = new MockFileSystem (); + fs.AddFile ("/in.mka", original); + var file = (MatroskaFile)MediaFile.Read ("/in.mka", fs).File!; + file.Tag.Title = "New"; + file.Tag.Pictures = [new TestPicture ("image/jpeg", PictureType.FrontCover, "", Jpeg)]; + file.Chapters.Editions[0].AddChapter (TimeSpan.FromSeconds (2), TimeSpan.FromSeconds (3), "Added"); + AddEdition (file, 0x8801, "Other"); + + Assert.IsTrue ((await SaveOverSource (file, save, fs)).IsSuccess, save); + + Assert.IsFalse (file.Chapters.IsModified, $"{save}: chapters"); + Assert.IsFalse (file.Tag.SegmentTitleChanged, $"{save}: segment title"); + Assert.IsFalse (file.Tag.PicturesChanged, $"{save}: pictures"); + } + + // The same after Clear: the save wrote the chapters left (none, or one edition added after the clear), and a clear + // of a file now without chapters is no edit, as on a fresh read of it. + [TestMethod] + [DynamicData (nameof (SaveEntryCases))] + public async Task SecondSave_AfterAChaptersClearIsSaved_NothingIsPending (string save) + { + foreach (var refill in new[] { false, true }) { + var fs = new MockFileSystem (); + fs.AddFile ("/in.mka", SecondSaveShapes["no Tags"] ()); + var file = (MatroskaFile)MediaFile.Read ("/in.mka", fs).File!; + file.Chapters.Clear (); + if (refill) + AddEdition (file, 0x8801, "Other"); + Assert.IsTrue ((await SaveOverSource (file, save, fs)).IsSuccess, save); + Assert.IsFalse (file.Chapters.IsModified, $"{save}, refilled {refill}: after the save"); + if (refill) + continue; + file.Chapters.Clear (); + Assert.IsFalse (file.Chapters.IsModified, $"{save}: a clear of no chapters"); + } + } + + // An edition emptied and saved is in no file: a chapter put back in it, the same object, is written as a fresh object + // writes a new edition and chapter with those values, not as the bytes it was first read with (ffmpeg's sizes). + [TestMethod] + [DynamicData (nameof (SaveEntryCases))] + public async Task SecondSave_AnEditionEmptiedAndSaved_IsWrittenAsNewWhenFilledAgain (string save) + { + var original = SecondSaveShapes["ffmpeg's chapters, 8-byte sizes"] (); + var fs = new MockFileSystem (); + fs.AddFile ("/in.mka", original); + var file = (MatroskaFile)MediaFile.Read ("/in.mka", fs).File!; + var edition = file.Chapters.Editions[0]; + var chapter = edition.Chapters[0]; + edition.Chapters.Clear (); + Assert.IsTrue ((await SaveOverSource (file, save, fs)).IsSuccess, save); + var before = fs.ReadAllBytes ("/in.mka"); + edition.Chapters.Add (chapter); + Assert.IsTrue ((await SaveOverSource (file, save, fs)).IsSuccess, save); + + var oracleFs = new MockFileSystem (); + oracleFs.AddFile ("/in.mka", before); + var fresh = (MatroskaFile)MediaFile.Read ("/in.mka", oracleFs).File!; + var again = fresh.Chapters.AddEdition (); + again.Uid = edition.Uid; + again.AddChapter (chapter.Start, chapter.End, chapter.Title).Uid = chapter.Uid; + Assert.IsTrue ((await SaveOverSource (fresh, save, oracleFs)).IsSuccess, save); + CollectionAssert.AreEqual (oracleFs.ReadAllBytes ("/in.mka"), fs.ReadAllBytes ("/in.mka"), save); + } + + // A file with its picture after the last Cluster, as a save writes one, for the edits a save elsewhere must not settle + // (review 12, B1). A new picture's attachment then has the same size as the old one. + static byte[] PendingEditFile () + { + var bare = Matroska (Master (0x18538067, Concat ( + Master (0x1654AE6B, AudioEntry (1, 44100)), + ChaptersElement (EditionEntry (Atom (1, 0, Second, Display ("Old")))), + Tags (Untargeted (Simple ("TITLE", OldTitle))), + Master (0x1F43B675, new byte[] { 1 })))); + var file = MatroskaFile.Read (bare).File!; + file.Tag.Pictures = [new TestPicture ("image/png", PictureType.FrontCover, "Desc", Png)]; + return file.Render (bare).ToArray (); + } + + static byte[] FlippedPng () + { + var data = (byte[])Png.Clone (); + data[^1] ^= 0xFF; + data[^2] ^= 0xFF; + return data; + } + + // Each pending edit, alone and all together. The picture edits keep every size, so neither the file's length nor + // the other elements can tell a save elsewhere from a save over the source. + static readonly Dictionary> PendingEdits = new () { + ["picture data, same size"] = f => f.Tag.Pictures = [new TestPicture ("image/png", PictureType.FrontCover, "Desc", FlippedPng ())], + ["picture media type, same size"] = f => f.Tag.Pictures = [new TestPicture ("image/bmp", PictureType.FrontCover, "Desc", Png)], + ["picture description, same size"] = f => f.Tag.Pictures = [new TestPicture ("image/png", PictureType.FrontCover, "Dscr", Png)], + ["title, same size"] = f => f.Tag.Title = NewTitle, + ["chapter title, same size"] = f => f.Chapters.Editions[0].Chapters[0].Title = "New", + ["track flag"] = f => f.Tracks[0].IsEnabled = false, + ["all of them"] = f => { + f.Tag.Pictures = [new TestPicture ("image/png", PictureType.FrontCover, "Dscr", FlippedPng ())]; + f.Tag.Title = NewTitle; + f.Chapters.Editions[0].Chapters[0].Title = "New"; + f.Tracks[0].IsEnabled = false; + }, + }; + + // A picture's new attachment draws a FileUID 8 bytes wide, so a new picture of the same size as the old one gives an + // attachment of the same size (#244). + [TestMethod] + public void NewPictureAttachments_HaveFileUidsEightBytesWide () + { + for (var i = 0; i < 64; i++) { + var bytes = PendingEditFile (); + var at = bytes.AsSpan ().IndexOf (FileUidId); + Assert.IsTrue (at >= 0, "a FileUID"); + Assert.IsTrue (EbmlReader.TryRead (bytes, at, bytes.Length, out var uid), "a FileUID"); + Assert.AreEqual (8L, uid.DataLength); + Assert.IsTrue (EbmlReader.ReadUInt (bytes.AsSpan (uid.DataOffset, 8)) >= 1UL << 63); + } + } + + static readonly byte[] FileUidId = [0x46, 0xAE]; + + // Each edit's way back to the file's values. + static readonly Action SetBackPicture = f => f.Tag.Pictures = [new TestPicture ("image/png", PictureType.FrontCover, "Desc", Png)]; + + static readonly Dictionary> PendingEditsSetBack = new () { + ["picture data, same size"] = SetBackPicture, + ["picture media type, same size"] = SetBackPicture, + ["picture description, same size"] = SetBackPicture, + ["title, same size"] = f => f.Tag.Title = OldTitle, + ["chapter title, same size"] = f => f.Chapters.Editions[0].Chapters[0].Title = "Old", + ["track flag"] = f => f.Tracks[0].IsEnabled = true, + ["all of them"] = f => { + SetBackPicture (f); + f.Tag.Title = OldTitle; + f.Chapters.Editions[0].Chapters[0].Title = "Old"; + f.Tracks[0].IsEnabled = true; + }, + }; + + // The other way round: an edit saved elsewhere and set back leaves the source as it was, as a fresh read of it would. + [TestMethod] + [DynamicData (nameof (PendingEditCases))] + public async Task SecondSave_AnEditSavedElsewhereAndSetBack_LeavesTheSource (string edit, string save) + { + var original = PendingEditFile (); + var fs = new MockFileSystem (); + fs.AddFile ("/in.mka", original); + var file = (MatroskaFile)MediaFile.Read ("/in.mka", fs).File!; + PendingEdits[edit] (file); + Assert.IsTrue ((await SaveElsewhere (file, save, fs)).IsSuccess, save); + PendingEditsSetBack[edit] (file); + + Assert.IsTrue ((await SaveOverSource (file, save, fs)).IsSuccess, save); + + CollectionAssert.AreEqual (original, fs.ReadAllBytes ("/in.mka"), $"{edit} / {save}"); + } + + public static IEnumerable PendingEditCases () => + from edit in PendingEdits.Keys + from save in MatroskaSaves + select new object[] { edit, save }; + + // An edit saved elsewhere is still pending for the source: a save over it writes it, as a fresh object given the same + // edit writes it. A save elsewhere settles nothing in the object, whatever it wrote matching the source. + [TestMethod] + [DynamicData (nameof (PendingEditCases))] + public async Task SecondSave_AnEditSavedElsewhere_IsWrittenOverTheSource (string edit, string save) + { + var original = PendingEditFile (); + var fs = new MockFileSystem (); + fs.AddFile ("/in.mka", original); + var file = (MatroskaFile)MediaFile.Read ("/in.mka", fs).File!; + PendingEdits[edit] (file); + Assert.IsTrue ((await SaveElsewhere (file, save, fs)).IsSuccess, save); + CollectionAssert.AreEqual (original, fs.ReadAllBytes ("/in.mka"), $"{save}: a save elsewhere leaves the source"); + + Assert.IsTrue ((await SaveOverSource (file, save, fs)).IsSuccess, save); + + var oracleFs = new MockFileSystem (); + oracleFs.AddFile ("/in.mka", original); + var fresh = (MatroskaFile)MediaFile.Read ("/in.mka", oracleFs).File!; + PendingEdits[edit] (fresh); + Assert.IsTrue ((await SaveOverSource (fresh, save, oracleFs)).IsSuccess, save); + var written = MatroskaFile.Read (fs.ReadAllBytes ("/in.mka")).File!; + Assert.AreEqual (Facts.Of (MatroskaFile.Read (oracleFs.ReadAllBytes ("/in.mka")).File!, withoutPictures: false), Facts.Of (written, withoutPictures: false), $"{edit} / {save}"); + Assert.AreNotEqual (Facts.Of (MatroskaFile.Read (original).File!, withoutPictures: false), Facts.Of (written, withoutPictures: false), $"{edit} / {save}: the edit is in the source"); + } + + // Each of the six saves, to another path: the span saves are given the source's bytes. + static async Task SaveElsewhere (MatroskaFile file, string save, MockFileSystem fs) => save switch { + "span-sync" => file.SaveToFile ("/out.mka", fs.ReadAllBytes ("/in.mka"), fs), + "span-async" => await file.SaveToFileAsync ("/out.mka", fs.ReadAllBytes ("/in.mka"), fs), + "async-path" or "async-in-place" => await file.SaveToFileAsync ("/out.mka", fs), + _ => file.SaveToFile ("/out.mka", fs), + }; + + // A save with no edit leaves every shape as it was, on each of the six saves, a second save included: the tags and + // chapters are compared with the ones in the bytes rewritten, every Tags element of them. + [TestMethod] + [DynamicData (nameof (SecondSaveShapeCases))] + public async Task SecondSave_NoEdit_LeavesTheFileAsItWas (string shape) + { + var original = SecondSaveShapes[shape] (); + foreach (var save in MatroskaSaves) { + var fs = new MockFileSystem (); + fs.AddFile ("/in.mka", original); + var file = (MatroskaFile)MediaFile.Read ("/in.mka", fs).File!; + Assert.IsTrue ((await SaveOverSource (file, save, fs)).IsSuccess, save); + Assert.IsTrue ((await SaveOverSource (file, save, fs)).IsSuccess, save); + CollectionAssert.AreEqual (original, fs.ReadAllBytes ("/in.mka"), $"{shape} / {save}"); + } + } + + // An empty Tag stays only as the file holds it: a Tag a set filled and a clear after a save emptied goes, as a fresh + // read of the saved file drops it, and the Tag the file still holds empty stays (one each, not one for both). + [TestMethod] + public async Task SecondSave_TwoEmptyTags_TheOneFilledThenClearedGoes () + { + var original = SecondSaveShapes["Tags holding two empty Tags"] (); + var empty = Master (0x7373, Master (0x63C0, Array.Empty ())); + foreach (var save in MatroskaSaves) { + var fs = new MockFileSystem (); + fs.AddFile ("/in.mka", original); + var file = (MatroskaFile)MediaFile.Read ("/in.mka", fs).File!; + file.Tag.Album = "Set"; + Assert.IsTrue ((await SaveOverSource (file, save, fs)).IsSuccess, save); + Assert.AreEqual (1, CountOf (fs.ReadAllBytes ("/in.mka"), empty), $"{save}: the first save fills one"); + file.Tag.Album = null; + Assert.IsTrue ((await SaveOverSource (file, save, fs)).IsSuccess, save); + Assert.AreEqual (1, CountOf (fs.ReadAllBytes ("/in.mka"), empty), $"{save}: the one the file held empty stays, the other goes"); + } + } + + // A title edit, by each of the six saves: the six files are one, and the Chapters element is the file's, byte for + // byte. A read sets up nothing that differs from one read to the next. + [TestMethod] + [DynamicData (nameof (SecondSaveShapeCases))] + public async Task SecondSave_TitleEdit_EverySaveWritesOneFile_AndKeepsTheChapters (string shape) + { + var original = SecondSaveShapes[shape] (); + var written = new List (); + foreach (var save in MatroskaSaves) { + var fs = new MockFileSystem (); + fs.AddFile ("/in.mka", original); + var file = (MatroskaFile)MediaFile.Read ("/in.mka", fs).File!; + file.Tag.Title = "New"; + Assert.IsTrue ((await SaveOverSource (file, save, fs)).IsSuccess, save); + written.Add (fs.ReadAllBytes ("/in.mka")); + } + + for (var i = 1; i < written.Count; i++) + CollectionAssert.AreEqual (written[0], written[i], $"{shape}: {MatroskaSaves[i]} against {MatroskaSaves[0]}"); + CollectionAssert.AreEqual (ChaptersIn (original), ChaptersIn (written[0]), $"{shape}: Chapters"); + } + + // The first Chapters element of a built file, whole. + static byte[] ChaptersIn (byte[] file) + { + var at = file.AsSpan ().IndexOf (ChaptersId); + Assert.IsTrue (at >= 0, "a Chapters element"); + Assert.IsTrue (EbmlReader.TryRead (file, at, file.Length, out var element), "a Chapters element"); + return file.AsSpan (element.Position, element.End - element.Position).ToArray (); + } + + static readonly byte[] ChaptersId = [0x10, 0x43, 0xA7, 0x70]; + + public static IEnumerable SecondSaveShapeCases () => SecondSaveShapes.Keys.Select (shape => new object[] { shape }); + + // Each of the six saves, writing over the file the object was read from: the span saves are given the bytes + // that file holds now. + static async Task SaveOverSource (MatroskaFile file, string save, MockFileSystem fs) => save switch { + "sync-path" => file.SaveToFile ("/in.mka", fs), + "async-path" => await file.SaveToFileAsync ("/in.mka", fs), + "span-sync" => file.SaveToFile ("/in.mka", fs.ReadAllBytes ("/in.mka"), fs), + "span-async" => await file.SaveToFileAsync ("/in.mka", fs.ReadAllBytes ("/in.mka"), fs), + "sync-in-place" => file.SaveToFile (fs), + _ => await file.SaveToFileAsync (fs), + }; +} diff --git a/tests/TagLibSharp2.Tests/Matroska/MatroskaTagScaleTests.cs b/tests/TagLibSharp2.Tests/Matroska/MatroskaTagScaleTests.cs new file mode 100644 index 00000000..440ce40e --- /dev/null +++ b/tests/TagLibSharp2.Tests/Matroska/MatroskaTagScaleTests.cs @@ -0,0 +1,662 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using TagLibSharp2.Core; +using TagLibSharp2.Matroska; + +namespace TagLibSharp2.Tests.Matroska; + +/// +/// A file sets how many Tags it holds, so a save is not quadratic in them but O(n log n) comparisons (#244): a save keeps +/// an emptied Tag only where the bytes it rewrites hold the same empty Tag, which it finds in a multiset by content, each +/// Tag rendered once. Past Tags and SimpleTags, the rest are kept as their bytes, as +/// Chapters keeps its entries past . +/// +public partial class MatroskaFileTests +{ + static readonly byte[] EmptyTag = Master (0x7373, Master (0x63C0, Array.Empty ())); + + // An untargeted TITLE, then many empty Tags. + static byte[] ManyEmptyTags (int count) + { + var tags = new byte[count][]; + Array.Fill (tags, EmptyTag); + return Matroska (WideElement (0x18538067, Concat ( + WideElement (0x1254C367, Concat (Untargeted (Simple ("TITLE", OldTitle)), Concat (tags))), + Master (0x1F43B675, new byte[] { 1 })))); + } + + // 2^doublings different suffixes of 4 * doublings printable bytes that leave FNV-1a (32-bit) in the same state from + // state, found by chaining colliding 4-byte blocks (Joux's multicollision): what a file can do to an unkeyed hash. A + // lookup must not depend on a hash an input can choose. + static List FnvMulticollision (uint state, int doublings) + { + static uint Step (uint hash, ReadOnlySpan bytes) + { + foreach (var value in bytes) + hash = (hash ^ value) * 16777619u; + return hash; + } + + var random = new Random (244); + var pairs = new List<(byte[] A, byte[] B)> (); + for (var d = 0; d < doublings; d++) { + var seen = new Dictionary (); + while (true) { + var block = new byte[4]; + for (var i = 0; i < 4; i++) + block[i] = (byte)random.Next (0x21, 0x7F); + var next = Step (state, block); + if (seen.TryGetValue (next, out var other) && !other.AsSpan ().SequenceEqual (block)) { + pairs.Add ((other, block)); + state = next; + break; + } + + seen[next] = block; + } + } + + var suffixes = new List { Array.Empty () }; + foreach (var (a, b) in pairs) + suffixes = [.. suffixes.SelectMany (s => new[] { (byte[])[.. s, .. a], [.. s, .. b] })]; + return suffixes; + } + + static uint Fnv (ReadOnlySpan bytes) + { + var hash = 2166136261u; + foreach (var value in bytes) + hash = (hash ^ value) * 16777619u; + return hash; + } + + // Empty Tags whose bytes differ only in a TargetType that collides under FNV-1a: every one renders differently, and + // all hash alike under the old comparer. + static (byte[] File, byte[] TagPrefix) CollidingEmptyTags (int doublings) + { + var prefix = Master (0x7373, Master (0x63C0, Element (0x63CA, new byte[4 * doublings]))); + prefix = prefix[..^(4 * doublings)]; + var tags = FnvMulticollision (Fnv (prefix), doublings).Select (suffix => (byte[])[.. prefix, .. suffix]).ToArray (); + Assert.AreEqual (1, tags.Select (tag => Fnv (tag)).Distinct ().Count (), "the empty Tags collide under FNV-1a"); + Assert.AreEqual (tags.Length, tags.Select (Convert.ToHexString).Distinct ().Count (), "and differ"); + return (Matroska (WideElement (0x18538067, Concat (WideElement (0x1254C367, Concat (tags)), Master (0x1F43B675, new byte[] { 1 })))), prefix); + } + + [TestMethod] + [Timeout (60_000)] + public void Save_EmptyTagsThatCollideUnderFnv_IsNLogN () + { + static long Steps (int doublings) + { + var (bytes, prefix) = CollidingEmptyTags (doublings); + var file = MatroskaFile.Read (bytes).File!; + MatroskaTag.LevelSteps = 0; + // Every save matches each empty Tag the object holds against the ones in the bytes. + var saved = file.Render (bytes).ToArray (); + var steps = MatroskaTag.LevelSteps; + Assert.AreEqual (1 << doublings, CountOf (saved, prefix), "every empty Tag is kept"); + CollectionAssert.AreEqual (bytes, saved, "a save with no edit"); + return steps; + } + + var one = Steps (12); + var four = Steps (14); + Assert.IsTrue (one >= 4_096, $"{one} steps for 4,096 empty Tags: the counter is not counting"); + Assert.IsTrue (four <= 6 * one, $"{one} steps for 4,096 empty Tags that collide under FNV-1a, {four} for 16,384: not n log n"); + } + + // Track Tags whose COMMENT a clear takes, then as many empty Tags: each emptied track Tag matches none of the empty + // Tags the bytes hold, the worst case for a search through them. + static byte[] EmptyAndTrackTags (int count) + { + var tags = new byte[2 * count][]; + Array.Fill (tags, Tag (30, Simple ("COMMENT", "c")), 0, count); + Array.Fill (tags, EmptyTag, count, count); + return Matroska (WideElement (0x18538067, Concat (WideElement (0x1254C367, Concat (tags)), Master (0x1F43B675, new byte[] { 1 })))); + } + + [TestMethod] + [Timeout (60_000)] + public void Save_ManyEmptyTags_IsNotQuadraticInThem () + { + static long Steps (int count) + { + var bytes = EmptyAndTrackTags (count); + var file = MatroskaFile.Read (bytes).File!; + file.Tag.Comment = null; + MatroskaTag.LevelSteps = 0; + var saved = file.Render (bytes).ToArray (); + var steps = MatroskaTag.LevelSteps; + Assert.AreEqual (count, CountOf (saved, EmptyTag), "every empty Tag the file holds is kept"); + Assert.AreEqual (0, CountOf (saved, Tag (30, Array.Empty ())), "every emptied track Tag goes"); + Assert.IsNull (MatroskaFile.Read (saved).File!.Tag.Comment); + return steps; + } + + // The quadratic search took 29 s for 8,000 of each on this machine, and would take hours at 30,000. + var one = Steps (7_500); + var four = Steps (30_000); + Assert.IsTrue (one >= 15_000, $"{one} steps for 15,000 Tags: the counter is not counting"); + Assert.IsTrue (four <= 5 * one, $"{one} steps for 15,000 Tags, {four} for 60,000: quadratic"); + } + + // Many small image attachments (a file sets how many), each a picture. + static byte[] ManyPictures (int count, bool identical = false) + { + var files = new byte[count][]; + for (var i = 0; i < count; i++) + files[i] = identical + ? Picture ("img.png", "image/png", null, [0x89, 0x50, 0x4E, 0x47], 1) + : Picture ($"img{i}.png", "image/png", null, [0x89, 0x50, 0x4E, 0x47, (byte)i, (byte)(i >> 8), (byte)(i >> 16)], 1); + return Matroska (WideElement (0x18538067, Concat (Master (0x1F43B675, new byte[] { 1 }), WideElement (MatroskaIds.Attachments, Concat (files))))); + } + + // Pictures of one name, type and size whose data collide under FNV-1a. + static byte[] CollidingPictures (int doublings) + { + byte[] prefix = [0x89, 0x50, 0x4E, 0x47]; + var data = FnvMulticollision (Fnv (prefix), doublings).Select (suffix => (byte[])[.. prefix, .. suffix]).ToArray (); + Assert.AreEqual (1, data.Select (bytes => Fnv (bytes)).Distinct ().Count (), "the pictures collide under FNV-1a"); + var files = data.Select (bytes => Picture ("img.png", "image/png", null, bytes, 1)).ToArray (); + return Matroska (WideElement (0x18538067, Concat (Master (0x1F43B675, new byte[] { 1 }), WideElement (MatroskaIds.Attachments, Concat (files))))); + } + + [TestMethod] + [Timeout (60_000)] + public void Save_PicturesThatCollideUnderFnvSetBack_IsNLogN () + { + static long Steps (int doublings) + { + var bytes = CollidingPictures (doublings); + var file = MatroskaFile.Read (bytes).File!; + file.Tag.Pictures = [.. Enumerable.Reverse (file.Tag.Pictures)]; + MatroskaAttachments.Steps = 0; + CollectionAssert.AreEqual (bytes, file.Render (bytes).ToArray (), "the same pictures: the file as it was"); + return MatroskaAttachments.Steps; + } + + var one = Steps (11); + var four = Steps (13); + Assert.IsTrue (one >= 2_048, $"{one} steps for 2,048 pictures: the counter is not counting"); + Assert.IsTrue (four <= 6 * one, $"{one} steps for 2,048 pictures that collide under FNV-1a, {four} for 8,192: not n log n"); + } + + // Font attachments whose FileUIDs share a hash code ((k << 32) | k: the two halves cancel), and a picture added: the + // save keeps every UID it holds and draws a new one in O(n log n) comparisons. (Fonts, so no picture index is built + // and the count is the UIDs'.) + [TestMethod] + [Timeout (60_000)] + public void Save_AttachmentsWhoseUidsShareAHashCode_IsNLogN () + { + static long Steps (int count) + { + var files = new byte[count][]; + for (var i = 0; i < count; i++) { + var half = (ulong)(uint)(i + 1); + var uid = (half << 32) | half; + files[i] = Master (MatroskaIds.AttachedFile, Concat ( + Element (MatroskaIds.FileName, System.Text.Encoding.UTF8.GetBytes ($"font{i}.ttf")), + Element (MatroskaIds.FileMimeType, "application/x-truetype-font"u8), + Element (MatroskaIds.FileData, FontBytes), + UInt (MatroskaIds.FileUid, uid))); + } + + var bytes = Matroska (WideElement (0x18538067, Concat (Master (0x1F43B675, new byte[] { 1 }), WideElement (MatroskaIds.Attachments, Concat (files))))); + var file = MatroskaFile.Read (bytes).File!; + file.Tag.Pictures = [new TestPicture ("image/png", PictureType.FrontCover, "", Png)]; + MatroskaAttachments.Steps = 0; + var saved = file.Render (bytes).ToArray (); + Assert.AreEqual (1, MatroskaFile.Read (saved).File!.Tag.Pictures.Length); + Assert.AreEqual (count + 1, CountOf (saved, AttachedFileId), "every font kept, and the picture"); + return MatroskaAttachments.Steps; + } + + var one = Steps (4_096); + var four = Steps (16_384); + Assert.IsTrue (one >= 4_096, $"{one} steps for 4,096 attachments: the counter is not counting"); + Assert.IsTrue (four <= 6 * one, $"{one} steps for 4,096 attachments whose UIDs share a hash code, {four} for 16,384: not n log n"); + } + + static readonly byte[] AttachedFileId = [0x61, 0xA7]; + + // Of attachments alike in all a picture is matched by (two copies of one picture, under different names and UIDs), + // the first in file order is the picture's: the other one goes. + [TestMethod] + public void Save_OfTwoAlikeAttachments_TheFirstIsKept () + { + static byte[] Copy (string name, byte uid) => Master (MatroskaIds.AttachedFile, Concat ( + Element (MatroskaIds.FileDescription, "Same"u8), + Element (MatroskaIds.FileName, System.Text.Encoding.UTF8.GetBytes (name)), + Element (MatroskaIds.FileMimeType, "image/png"u8), + Element (MatroskaIds.FileData, Png), + Element (MatroskaIds.FileUid, new[] { uid }))); + var bytes = Matroska (WideElement (0x18538067, Concat (Master (0x1F43B675, new byte[] { 1 }), WideElement (MatroskaIds.Attachments, Concat (Copy ("first.png", 1), Copy ("second.png", 2)))))); + var file = MatroskaFile.Read (bytes).File!; + file.Tag.Pictures = [file.Tag.Pictures[0]]; + + var saved = file.Render (bytes).ToArray (); + + Assert.AreEqual (1, CountOf (saved, "first.png"u8.ToArray ())); + Assert.AreEqual (0, CountOf (saved, "second.png"u8.ToArray ())); + } + + // Each picture set back finds its own attachment in constant time: the pictures read, in the other order. + [TestMethod] + [Timeout (60_000)] + [DataRow (false)] + [DataRow (true)] + public void Save_ManyPicturesSetBack_IsNotQuadraticInThem (bool identical) + { + long Steps (int count) + { + var bytes = ManyPictures (count, identical); + var file = MatroskaFile.Read (bytes).File!; + file.Tag.Pictures = [.. Enumerable.Reverse (file.Tag.Pictures)]; + MatroskaAttachments.Steps = 0; + CollectionAssert.AreEqual (bytes, file.Render (bytes).ToArray (), "the same pictures: the file as it was"); + return MatroskaAttachments.Steps; + } + + // The search went through every attachment for each picture: 16,000 took 17 s on this machine. + var one = Steps (10_000); + var four = Steps (40_000); + Assert.IsTrue (one >= 10_000, $"{one} steps for 10,000 pictures: the counter is not counting"); + Assert.IsTrue (four <= 5 * one, $"{one} steps for 10,000 pictures, {four} for 40,000: quadratic"); + } + + // New pictures of one type are named cover.png, cover_2.png, and on, each name tried once: not quadratic in them. + [TestMethod] + [Timeout (60_000)] + public void Save_ManyNewPicturesOfOneType_AreNotNamedInQuadraticTime () + { + static long Steps (int count) + { + var bytes = Matroska (WideElement (0x18538067, Master (0x1F43B675, new byte[] { 1 }))); + var file = MatroskaFile.Read (bytes).File!; + var pictures = new IPicture[count]; + for (var i = 0; i < count; i++) + pictures[i] = new TestPicture ("image/png", PictureType.BackCover, "", [0x89, 0x50, (byte)i, (byte)(i >> 8), (byte)(i >> 16)]); + file.Tag.Pictures = pictures; + MatroskaAttachments.Steps = 0; + var saved = MatroskaFile.Read (file.Render (bytes).ToArray ()).File!; + Assert.AreEqual (count, saved.Tag.Pictures.Length); + return MatroskaAttachments.Steps; + } + + var one = Steps (2_000); + var four = Steps (8_000); + Assert.IsTrue (one >= 1_000, $"{one} name steps for 2,000 pictures: the counter is not counting"); + Assert.IsTrue (four <= 5 * one, $"{one} name steps for 2,000 pictures, {four} for 8,000: quadratic"); + } + + // A Tag past the budget is not read: its TITLE is not the title, and a save leaves it as it was. + [TestMethod] + [Timeout (60_000)] + public void Read_ATagPastTheBudget_IsNotRead () + { + var tags = new byte[MatroskaTag.MaxEntries + 1][]; + Array.Fill (tags, EmptyTag, 0, MatroskaTag.MaxEntries); + tags[^1] = Tag (30, Simple ("TITLE", "Past")); + var bytes = Matroska (WideElement (0x18538067, Concat (WideElement (0x1254C367, Concat (tags)), Master (0x1F43B675, new byte[] { 1 })))); + var file = MatroskaFile.Read (bytes).File!; + Assert.IsNull (file.Tag.Title); + CollectionAssert.AreEqual (bytes, file.Render (bytes).ToArray (), "a save with no edit keeps it as it was"); + } + + // The budget counts SimpleTags too: one Tag holding nearly all of it leaves no room for the next. + [TestMethod] + [Timeout (60_000)] + public void Read_ATagPastTheBudgetOfSimpleTags_IsNotRead () + { + var simples = new byte[MatroskaTag.MaxEntries - 1][]; + Array.Fill (simples, Simple ("COMMENT", "c")); + var bytes = Matroska (WideElement (0x18538067, Concat ( + WideElement (0x1254C367, Concat (WideElement (0x7373, Concat (Master (0x63C0, Array.Empty ()), Concat (simples))), Tag (30, Simple ("TITLE", "Past")))), + Master (0x1F43B675, new byte[] { 1 })))); + + Assert.IsNull (MatroskaFile.Read (bytes).File!.Tag.Title); + } + + // The Tags past the budget stay in the file through saves over the source: the object takes them from what it wrote. + [TestMethod] + [Timeout (60_000)] + public async Task Save_TagsPastTheBudget_StayThroughSavesOverTheSource () + { + var count = MatroskaTag.MaxEntries + 100; + var fs = new TagLibSharp2.Tests.Core.MockFileSystem (); + fs.AddFile ("/in.mka", ManyEmptyTags (count)); + var file = (MatroskaFile)TagLibSharp2.Core.MediaFile.Read ("/in.mka", fs).File!; + file.Tag.Title = NewTitle; + Assert.IsTrue (file.SaveToFile (fs).IsSuccess); + file.Tag.Title = "Again"; + Assert.IsTrue ((await file.SaveToFileAsync (fs)).IsSuccess); + + Assert.AreEqual (count, CountOf (fs.ReadAllBytes ("/in.mka"), EmptyTag)); + } + + // A Tag of one SimpleTag that no getter reads: it targets an attachment. + static readonly byte[] FillerTag = Master (0x7373, Concat (Master (0x63C0, Element (0x63C6, new byte[] { 9 })), Simple ("COMMENT", "f"))); + + // A first Tag, then fillers up to exactly the budget, then one Tag past it. + static byte[] AtTheBudget (byte[] first, byte[] past) + { + var tags = new byte[(MatroskaTag.MaxEntries - 2) / 2 + 2][]; + Array.Fill (tags, FillerTag); + tags[0] = first; + tags[^1] = past; + return Matroska (WideElement (0x18538067, Concat (WideElement (0x1254C367, Concat (tags)), Master (0x1F43B675, new byte[] { 1 })))); + } + + // A save writes the Tags a read of the saved file models in full, or fails: an edit that would put a value past the + // budget (a new Tag, or a SimpleTag that pushes the last modelled Tag past it) is refused with a result, and the + // file and the object stay as they were. An edit that replaces a value in place is saved (#247). + [TestMethod] + [Timeout (60_000)] + [DataRow ("a TITLE in a new Tag")] + [DataRow ("an ARTIST in the first Tag")] + public async Task Save_AnEditPastTheTagsBudget_IsRefused (string edit) + { + // The first Tag is an album's ARTIST, so a title needs a Tag at 30 of its own; or a track's TITLE, which an + // artist joins. + var newTag = edit == "a TITLE in a new Tag"; + var bytes = AtTheBudget (newTag ? Tag (50, Simple ("ARTIST", "Band")) : Tag (30, Simple ("TITLE", OldTitle)), Untargeted (Simple ("TITLE", "Past"))); + var fs = new TagLibSharp2.Tests.Core.MockFileSystem (); + fs.AddFile ("/in.mka", bytes); + var file = (MatroskaFile)TagLibSharp2.Core.MediaFile.Read ("/in.mka", fs).File!; + if (newTag) + file.Tag.Title = NewTitle; + else + file.Tag.Artist = "Artist"; + + foreach (var save in MatroskaSaves) { + var result = await SaveOverSource (file, save, fs); + Assert.IsFalse (result.IsSuccess, $"{edit} / {save}"); + StringAssert.Contains (result.Error, "65,536", $"{edit} / {save}"); + CollectionAssert.AreEqual (bytes, fs.ReadAllBytes ("/in.mka"), $"{edit} / {save}"); + Assert.AreEqual (newTag ? NewTitle : OldTitle, file.Tag.Title, $"{edit} / {save}: the object keeps the edit, unsaved"); + } + } + + [TestMethod] + [Timeout (60_000)] + public async Task Save_AValueReplacedInPlaceAtTheTagsBudget_IsSaved () + { + var bytes = AtTheBudget (Tag (30, Simple ("TITLE", OldTitle)), Untargeted (Simple ("ARTIST", "Past"))); + foreach (var save in MatroskaSaves) { + var fs = new TagLibSharp2.Tests.Core.MockFileSystem (); + fs.AddFile ("/in.mka", bytes); + var file = (MatroskaFile)TagLibSharp2.Core.MediaFile.Read ("/in.mka", fs).File!; + file.Tag.Title = NewTitle; + Assert.IsTrue ((await SaveOverSource (file, save, fs)).IsSuccess, save); + Assert.AreEqual (NewTitle, file.Tag.Title, save); + var back = MatroskaFile.Read (fs.ReadAllBytes ("/in.mka")).File!; + Assert.AreEqual (NewTitle, back.Tag.Title, save); + Assert.IsNull (back.Tag.Artist, $"{save}: the Tag past the budget is still past it"); + Assert.AreEqual (1, CountOf (fs.ReadAllBytes ("/in.mka"), System.Text.Encoding.UTF8.GetBytes ("Past")), save); + } + } + + // The same at the Chapters budget: a chapter added there would be written past it, so the save is refused. So is a + // title edit there when the display was read without a language: the edit writes the default "eng" the read took, one + // element more, which pushes the last title read past the budget. + static byte[] AtTheChaptersBudget () + { + // An EditionEntry, then atoms of five entries each (the atom, its UID, start, display and string) past the budget. + var atoms = new byte[MatroskaChapters.MaxEntries / 5 + 10][]; + for (var i = 0; i < atoms.Length; i++) + atoms[i] = Atom ((ulong)i + 1, (ulong)i, null, Display ($"c{i}")); + return Matroska (WideElement (0x18538067, Concat (WideElement (0x1043A770, WideElement (0x45B9, Concat (atoms))), Master (0x1F43B675, new byte[] { 1 })))); + } + + [TestMethod] + [Timeout (60_000)] + [DataRow ("a chapter added")] + [DataRow ("a title on a display without a language")] + public async Task Save_AnEditPastTheChaptersBudget_IsRefused (string edit) => + await AssertChapterSaveRefused (AtTheChaptersBudget (), chapters => { + if (edit == "a chapter added") + chapters.Editions[0].AddChapter (TimeSpan.FromSeconds (1), null, "Added"); + else + chapters.Editions[0].Chapters[0].Title = "c0!"; + }, edit); + + // Chapters as a muxer writes them: an edition with a UID and two flags set (four entries, which a save writes alike), + // then atoms of six entries (the atom, start, end, and a display holding a string and a French language), or seven + // with a UID. A second edition can follow. The read's budget counts every element, so it can run out inside a chapter. + static byte[] MuxedChapters (bool uids, bool titleLast, int chapters, int secondEdition = 0) + { + static byte[] Edition (int first, int count, bool uids, bool titleLast) + { + var children = new byte[count + 1][]; + children[0] = Concat (UInt (MatroskaIds.EditionUid, (ulong)first + 1), UInt (MatroskaIds.EditionFlagHidden, 1), UInt (MatroskaIds.EditionFlagDefault, 1)); + for (var i = 0; i < count; i++) { + var at = first + i; + var title = Element (MatroskaIds.ChapString, System.Text.Encoding.UTF8.GetBytes ($"C{at}")); + var language = Element (MatroskaIds.ChapLanguage, "fre"u8); + children[i + 1] = Master (0xB6, Concat ( + uids ? UInt (0x73C4, 1_000_000 + (ulong)at) : Array.Empty (), + UInt (0x91, (ulong)at * 1_000_000_000), + UInt (0x92, ((ulong)at + 1) * 1_000_000_000), + Master (0x80, titleLast ? Concat (language, title) : Concat (title, language)))); + } + + return WideElement (0x45B9, Concat (children)); + } + + var editions = Edition (0, chapters, uids, titleLast); + if (secondEdition > 0) + editions = Concat (editions, Edition (chapters, secondEdition, uids, titleLast)); + return Matroska (WideElement (0x18538067, Concat (WideElement (0x1043A770, editions), Master (0x1F43B675, new byte[] { 1 })))); + } + + // 4 + 7 × 9,361 + 5: the read stops inside chapter 9,361, after its display began, so its display reads empty. + static byte[] ChaptersStoppingInADisplay () => MuxedChapters (uids: true, titleLast: false, chapters: 9_361 + 60); + + // 4 + 6 × 10,922: the read stops at the end of chapter 10,921, its last element its title or its language. + static byte[] ChaptersStoppingAtAChapterEnd (bool titleLast) => MuxedChapters (uids: false, titleLast, chapters: 10_922 + 60); + + static async Task AssertChapterSaveRefused (byte[] bytes, Action edit, string name) + { + var fs = new TagLibSharp2.Tests.Core.MockFileSystem (); + fs.AddFile ("/in.mka", bytes); + var file = (MatroskaFile)TagLibSharp2.Core.MediaFile.Read ("/in.mka", fs).File!; + edit (file.Chapters); + foreach (var save in MatroskaSaves) { + var result = await SaveOverSource (file, save, fs); + Assert.IsFalse (result.IsSuccess, $"{name} / {save}"); + StringAssert.Contains (result.Error, "65,536", $"{name} / {save}"); + CollectionAssert.AreEqual (bytes, fs.ReadAllBytes ("/in.mka"), $"{name} / {save}"); + } + } + + // A save writes the chapters a read of the saved file models with every value the object holds, or fails. The + // budget counts elements, so an edit can push part of a chapter past it (its title, its language) while the chapter + // is still read: such a save is refused (#247). + [TestMethod] + [Timeout (120_000)] + public async Task Save_ATitleOnTheChapterTheReadStopsIn_IsRefused () + { + var bytes = ChaptersStoppingInADisplay (); + await AssertChapterSaveRefused (bytes, chapters => { + var last = chapters.Editions[0].Chapters[^1]; + Assert.AreEqual (9_362, chapters.Editions[0].Chapters.Count); + Assert.AreEqual ("", last.Title, "the read stops inside the last chapter's display"); + last.Title = "Renamed"; + }, "the title of the last chapter read"); + } + + [TestMethod] + [Timeout (120_000)] + [DataRow (true, DisplayName = "the title goes past the budget")] + [DataRow (false, DisplayName = "the language goes past the budget")] + public async Task Save_AnEditThatPushesPartOfTheLastChapterPastTheBudget_IsRefused (bool titleLast) + { + // Chapter 0 has no UID, so a rename draws one: one element more, and the last chapter's last element goes past. + var bytes = ChaptersStoppingAtAChapterEnd (titleLast); + await AssertChapterSaveRefused (bytes, chapters => { + Assert.AreEqual (10_922, chapters.Editions[0].Chapters.Count); + Assert.AreEqual ("C10921", chapters.Editions[0].Chapters[^1].Title); + Assert.AreEqual ("fre", chapters.Editions[0].Chapters[^1].Displays[0].Languages[0]); + chapters.Editions[0].Chapters[0].Title = "Renamed"; + }, titleLast ? "title" : "language"); + } + + [TestMethod] + [Timeout (120_000)] + [DataRow (true, DisplayName = "chapters with UIDs, the read stopping in a display")] + [DataRow (false, DisplayName = "chapters without UIDs, the read stopping at a chapter's end")] + public async Task Save_AChapterRemovedAndOneAddedAtTheChaptersBudget_IsRefused (bool uids) + { + // The removed chapter lets the read take a kept one back, so as many chapters are read; the added one, written + // after the kept ones, is not. + var bytes = uids ? ChaptersStoppingInADisplay () : ChaptersStoppingAtAChapterEnd (titleLast: true); + await AssertChapterSaveRefused (bytes, chapters => { + var edition = chapters.Editions[0]; + edition.RemoveChapter (edition.Chapters[0]); + edition.AddChapter (TimeSpan.FromSeconds (1), null, "Swap"); + }, uids ? "UIDs" : "no UIDs"); + } + + // Each chapter sets every value a chapter holds: twelve elements (the atom, UID, string UID, start, end, both flags, + // and a display holding a string, a language, a BCP 47 language and a country). The first edition holds EditionDisplay + // elements, which it keeps as read, so that the read stops after element `read` of the last chapter it reaches; or, + // with `inEdition`, of a second edition that sets every value an edition holds (its entry, UID and three flags). + static byte[] ChaptersStoppingAfter (int read, bool inEdition) + { + const int PerChapter = 12; + var padding = (MatroskaChapters.MaxEntries - 1 - read) % PerChapter; + var full = (MatroskaChapters.MaxEntries - 1 - read - padding) / PerChapter; + var count = inEdition ? full : full + 1 + 20; + var children = new byte[padding + count][]; + for (var i = 0; i < padding; i++) + children[i] = Master (0x4520, Element (0x4521, "Cut"u8)); + for (var i = 0; i < count; i++) + children[padding + i] = FullChapter (i); + var editions = WideElement (0x45B9, Concat (children)); + if (inEdition) { + editions = Concat (editions, Master (0x45B9, Concat ( + UInt (MatroskaIds.EditionUid, 77), UInt (MatroskaIds.EditionFlagHidden, 1), UInt (MatroskaIds.EditionFlagDefault, 1), + UInt (0x45DD, 1), FullChapter (count)))); + } + + return Matroska (WideElement (0x18538067, Concat (WideElement (0x1043A770, editions), Master (0x1F43B675, new byte[] { 1 })))); + + static byte[] FullChapter (int i) => Master (0xB6, Concat ( + UInt (0x73C4, 1_000_000 + (ulong)i), + Element (MatroskaIds.ChapterStringUid, System.Text.Encoding.UTF8.GetBytes ($"cue{i}")), + UInt (0x91, ((ulong)i + 1) * 1_000_000_000), + UInt (0x92, ((ulong)i + 2) * 1_000_000_000), + UInt (0x98, 1), + UInt (MatroskaIds.ChapterFlagEnabled, 0), + Master (0x80, Concat ( + Element (MatroskaIds.ChapString, System.Text.Encoding.UTF8.GetBytes ($"C{i}")), + Element (MatroskaIds.ChapLanguage, "fre"u8), + Element (MatroskaIds.ChapLanguageBcp47, "fr-FR"u8), + Element (MatroskaIds.ChapCountry, "fr"u8))))); + } + + static IEnumerable ValuesOf (MatroskaChapters chapters) => chapters.Editions.Select (edition => + string.Join ("|", edition.Uid, edition.IsHidden, edition.IsDefault, edition.IsOrdered, "", + string.Join ("/", edition.Chapters.Select (chapter => string.Join ("|", chapter.Uid, chapter.StringUid, chapter.StartNanoseconds, + chapter.EndNanoseconds, chapter.IsHidden, chapter.IsEnabled, string.Join (";", chapter.Displays.Select (display => + display.Text + "," + string.Join ("+", display.Languages) + "," + string.Join ("+", display.LanguagesBcp47) + "," + + string.Join ("+", display.Countries)))))))); + + // The matrix over where the read stops in the last chapter or edition it reaches, so each value it holds is the one an + // edit pushes past the budget: an edit that writes one element more is refused, and one that writes as many is saved + // and read back with every value (#247). + [TestMethod] + [Timeout (600_000)] + [DataRow (false, 12, DisplayName = "in the last chapter read")] + [DataRow (true, 5, DisplayName = "in the last edition read")] + public async Task Save_AtEachElementOfTheLastChapterRead_IsRefusedOrReadBack (bool inEdition, int elements) + { + for (var read = 1; read <= elements; read++) { + var bytes = ChaptersStoppingAfter (read, inEdition); + await AssertChapterSaveRefused (bytes, chapters => { + var last = chapters.Editions[^1]; + Assert.AreEqual (read == elements, inEdition ? last.IsOrdered : last.Chapters[^1].Displays is [{ Countries.Count: 1 }], + $"the read stops in the last {(inEdition ? "edition" : "chapter")}, read {read}"); + chapters.Editions[0].Chapters[0].Displays[0].Countries.Add ("ca"); + }, $"one more element, read {read}"); + + foreach (var save in MatroskaSaves) { + var fs = new TagLibSharp2.Tests.Core.MockFileSystem (); + fs.AddFile ("/in.mka", bytes); + var file = (MatroskaFile)TagLibSharp2.Core.MediaFile.Read ("/in.mka", fs).File!; + file.Chapters.Editions[0].Chapters[0].Title = "C0 renamed"; + var values = ValuesOf (file.Chapters).ToList (); + Assert.IsTrue ((await SaveOverSource (file, save, fs)).IsSuccess, $"as many elements, read {read} / {save}"); + + var back = MatroskaFile.Read (fs.ReadAllBytes ("/in.mka")).File!.Chapters; + CollectionAssert.AreEqual (values, ValuesOf (back).ToList (), $"as many elements, read {read} / {save}"); + } + } + } + + // The edits that fit are saved on every entry point, and a fresh read holds every value the object does: the + // chapters read before, in order, each with its title and language. + [TestMethod] + [Timeout (120_000)] + [DataRow ("rename a chapter with a UID")] + [DataRow ("remove a chapter")] + [DataRow ("swap in a chapter the read now reaches")] + public async Task Save_AChapterEditThatFitsTheChaptersBudget_IsSaved (string edit) + { + var swap = edit == "swap in a chapter the read now reaches"; + // The swap: two chapters out and one in, written after the first edition's one kept chapter, which the read now + // reaches; the second edition is still past the budget. + var bytes = edit switch { + "rename a chapter with a UID" => ChaptersStoppingInADisplay (), + "remove a chapter" => ChaptersStoppingAtAChapterEnd (titleLast: true), + _ => MuxedChapters (uids: false, titleLast: true, chapters: 10_923, secondEdition: 1), + }; + foreach (var save in MatroskaSaves) { + var fs = new TagLibSharp2.Tests.Core.MockFileSystem (); + fs.AddFile ("/in.mka", bytes); + var file = (MatroskaFile)TagLibSharp2.Core.MediaFile.Read ("/in.mka", fs).File!; + var edition = file.Chapters.Editions[0]; + if (edit == "rename a chapter with a UID") + edition.Chapters[0].Title = "Renamed"; + else + edition.RemoveChapter (edition.Chapters[0]); + if (swap) { + edition.RemoveChapter (edition.Chapters[0]); + edition.AddChapter (TimeSpan.FromSeconds (1), null, "Swap"); + } + + // The last chapter of the rename's file was read with an empty display, which holds no value; a read of the + // saved file can take more of it, as the save leaves out the edition's FlagHidden of 0. + var kept = edition.Chapters.Take (edition.Chapters.Count - (swap ? 1 : 0)).Where (chapter => chapter.Title is { Length: > 0 }) + .Select (chapter => (chapter.Title, chapter.Displays[0].Languages[0])).ToList (); + Assert.IsTrue ((await SaveOverSource (file, save, fs)).IsSuccess, $"{edit} / {save}"); + + var back = MatroskaFile.Read (fs.ReadAllBytes ("/in.mka")).File!.Chapters.Editions[0].Chapters; + CollectionAssert.AreEqual (kept, back.Take (kept.Count).Select (chapter => (chapter.Title, chapter.Displays[0].Languages[0])).ToList (), $"{edit} / {save}"); + if (swap) + Assert.AreEqual ("Swap", back[^1].Title, $"{save}: the added chapter follows the one the read now reaches"); + } + } + + // Past the budget, Tags are kept as their bytes: a save with no edit leaves the file, and an edit of what was read + // writes every Tag past it back. + [TestMethod] + [Timeout (60_000)] + public void Read_TagsPastTheBudget_AreKeptAsTheirBytes () + { + var count = MatroskaTag.MaxEntries + 4_464; + var bytes = ManyEmptyTags (count); + var file = MatroskaFile.Read (bytes).File!; + Assert.AreEqual (OldTitle, file.Tag.Title); + CollectionAssert.AreEqual (bytes, file.Render (bytes).ToArray (), "a save with no edit"); + + file.Tag.Title = NewTitle; + var saved = file.Render (bytes).ToArray (); + + Assert.AreEqual (count, CountOf (saved, EmptyTag), "every empty Tag is written"); + var back = MatroskaFile.Read (saved).File!; + Assert.AreEqual (NewTitle, back.Tag.Title); + CollectionAssert.AreEqual (saved, back.Render (saved).ToArray (), "a save of the saved file with no edit"); + } +} diff --git a/tests/TagLibSharp2.Tests/Matroska/MatroskaUntargetedTitleTests.cs b/tests/TagLibSharp2.Tests/Matroska/MatroskaUntargetedTitleTests.cs new file mode 100644 index 00000000..b929b583 --- /dev/null +++ b/tests/TagLibSharp2.Tests/Matroska/MatroskaUntargetedTitleTests.cs @@ -0,0 +1,328 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using TagLibSharp2.Core; +using TagLibSharp2.Matroska; +using TagLibSharp2.Tests.Core; +using TagLibSharp2.Tests.Kit; + +namespace TagLibSharp2.Tests.Matroska; + +/// +/// A Tag with an empty Targets has a TargetTypeValue of 50 by default (RFC 9559 §5.1.8.1.1.1), but the values in it are +/// the file's own, as ffmpeg and mkvmerge write them: ffprobe, exiftool and MediaInfo show its TITLE as the title, and +/// no album (#221). So an untargeted TITLE is the title alone: the album is an explicit target-50 TITLE or ffmpeg's +/// ALBUM, a new title replaces the untargeted one in place, and the sort nested in it is the title's. +/// +public partial class MatroskaFileTests +{ + const string Test1Title = "Big Buck Bunny - test 1"; + + // The Matroska test suite's test1.mkv: its only title is a TITLE in a Tag with an empty Targets. + [TestMethod] + [DataRow ("MatroskaFile.Read")] + [DataRow ("ReadFromData")] + [DataRow ("stream")] + [DataRow ("path")] + [DataRow ("async path")] + public async Task Test1Mkv_UntargetedTitle_IsTheTitleOnly_AndANewTitleReplacesIt (string entry) + { + var original = File.ReadAllBytes (Corpus.Sample ("matroska/test1.mkv")); + var read = MatroskaFile.Read (original).File!.Tag; + Assert.AreEqual (Test1Title, read.Title); + Assert.IsNull (read.Album); + + var saved = await EditAndSave (original, entry, tag => tag.Title = NewTitle); + + var tag = MatroskaFile.Read (saved).File!.Tag; + Assert.AreEqual (NewTitle, tag.Title); + Assert.IsNull (tag.Album); + CollectionAssert.AreEqual (new[] { NewTitle }, FileLevelTexts (saved, "TITLE"), "the old TITLE replaced, in its Tag"); + } + + static readonly string[] UntargetedTitleOnly = [OldTitle]; + + // A built file with the same shape: a clear of the album leaves the title, and a write-back of the album is a no-op. + [TestMethod] + [DataRow ("MatroskaFile.Read")] + [DataRow ("path")] + public async Task UntargetedTitle_AlbumClear_LeavesTheTitle (string entry) + { + var original = AlbumLayout (null, Untargeted (Simple ("TITLE", OldTitle))); + + var saved = await EditAndSave (original, entry, tag => tag.Album = null); + + CollectionAssert.AreEqual (original, saved, "nothing to clear"); + CollectionAssert.AreEqual (UntargetedTitleOnly, FileLevelTexts (saved, "TITLE")); + } + + // The sort nested in an untargeted TITLE is the title's sort, not the album's: AlbumSort reads none, and a set + // goes beside the album as ALBUM_SORT without touching the title's. + [TestMethod] + public async Task UntargetedTitle_ItsSortIsTheTitleSort_NotTheAlbumSort () + { + var original = AlbumLayout (null, Untargeted (SimpleSorted ("TITLE", OldTitle, "Title key"))); + var tag = MatroskaFile.Read (original).File!.Tag; + Assert.AreEqual ("Title key", tag.TitleSort); + Assert.IsNull (tag.AlbumSort); + + var saved = await EditAndSave (original, "path", t => { t.Album = NewAlbum; t.AlbumSort = "Album key"; }); + + var back = MatroskaFile.Read (saved).File!.Tag; + Assert.AreEqual (OldTitle, back.Title); + Assert.AreEqual ("Title key", back.TitleSort); + Assert.AreEqual (NewAlbum, back.Album); + Assert.AreEqual ("Album key", back.AlbumSort); + } + + // A new title sort replaces the one nested in the untargeted TITLE, in place. + [TestMethod] + public async Task UntargetedTitle_ANewTitleSortReplacesItsNestedSort () + { + var original = AlbumLayout (null, Untargeted (SimpleSorted ("TITLE", OldTitle, "Title key"))); + + var saved = await EditAndSave (original, "path", t => t.TitleSort = "New key"); + + var back = MatroskaFile.Read (saved).File!.Tag; + Assert.AreEqual (OldTitle, back.Title); + Assert.AreEqual ("New key", back.TitleSort); + Assert.IsEmpty (FileLevelTexts (saved, "TITLE_SORT"), "no flat sort beside it"); + } + + public static IEnumerable SegmentTitleCases () + { + foreach (var entry in MatroskaEntryPoints) { + yield return ["New", entry]; + yield return ["A title longer than the Info element has room for", entry]; + } + } + + // With a segment title too, the untargeted TITLE takes the new title in place: whether Info/Title is rewritten in + // place (a short title) or left out because it does not fit (a long one), every reader shows only the new title + // (review 8, N1). + [TestMethod] + [DynamicData (nameof (SegmentTitleCases))] + public async Task SegmentTitleAndUntargetedTitle_ANewTitleLeavesNoOldTitle (string newTitle, string entry) + { + var original = AlbumLayout ("Song", Untargeted (Simple ("TITLE", "Song"))); + + var saved = await EditAndSave (original, entry, tag => tag.Title = newTitle); + + var tag = MatroskaFile.Read (saved).File!.Tag; + Assert.AreEqual (newTitle, tag.Title); + Assert.IsNull (tag.Album); + CollectionAssert.AreEqual (new[] { newTitle }, FileLevelTexts (saved, "TITLE"), "one TITLE, the new one"); + Assert.AreEqual (-1, saved.AsSpan ().IndexOf ("Song"u8), "no byte of the old title"); + } + + static readonly string[] NewTitleAndFrench = [NewTitle, "Chanson"]; + + // A title in two languages: the one Title reads (the first default-language TITLE) takes the new title, and the + // other language stays (review 8, nit 2). + [TestMethod] + [DataRow ("MatroskaFile.Read")] + [DataRow ("ReadFromData")] + [DataRow ("stream")] + [DataRow ("path")] + [DataRow ("async path")] + public async Task UntargetedTitleInTwoLanguages_ANewTitleReplacesTheOneRead (string entry) + { + var original = AlbumLayout (null, Untargeted (SimpleInLanguage ("TITLE", OldTitle, "eng"), SimpleInLanguage ("TITLE", "Chanson", "fre"))); + Assert.AreEqual (OldTitle, MatroskaFile.Read (original).File!.Tag.Title); + + var saved = await EditAndSave (original, entry, tag => tag.Title = NewTitle); + + Assert.AreEqual (NewTitle, MatroskaFile.Read (saved).File!.Tag.Title); + CollectionAssert.AreEqual (NewTitleAndFrench, FileLevelTexts (saved, "TITLE")); + } + + static readonly string[] NewTitleOnly = [NewTitle]; + + // Two untargeted Tags that each hold the title in the same language (review 8's h-two-untargeted): the second is a + // copy of the title read, so it goes, and the file holds one TITLE. + [TestMethod] + public async Task TwoUntargetedTitles_ANewTitleLeavesOne () + { + var original = AlbumLayout (null, Untargeted (Simple ("TITLE", OldTitle)), Untargeted (Simple ("TITLE", OldTitle))); + + var saved = await EditAndSave (original, "path", tag => tag.Title = NewTitle); + + CollectionAssert.AreEqual (NewTitleOnly, FileLevelTexts (saved, "TITLE")); + } + + // Languages named by BCP 47 alone (TagLanguageBCP47, with TagLanguage left at "und"): the same rule. + [TestMethod] + public async Task UntargetedTitleInTwoBcp47Languages_ANewTitleReplacesTheOneRead () + { + var original = AlbumLayout (null, Untargeted (SimpleInBcp47 ("TITLE", OldTitle, "en"), SimpleInBcp47 ("TITLE", "Chanson", "fr"))); + + var saved = await EditAndSave (original, "path", tag => tag.Title = NewTitle); + + CollectionAssert.AreEqual (NewTitleAndFrench, FileLevelTexts (saved, "TITLE")); + } + + static byte[] SimpleInBcp47 (string name, string text, string language) => + Master (0x67C8, Concat (Element (0x45A3, System.Text.Encoding.UTF8.GetBytes (name)), Element (MatroskaIds.TagLanguageBcp47, System.Text.Encoding.ASCII.GetBytes (language)), + Element (0x4487, System.Text.Encoding.UTF8.GetBytes (text)))); + + static readonly string[] UntargetedAlbumAndTrackTitles = [NewTitle, OldAlbum, NewTitle]; + + // An untargeted TITLE before an explicit album TITLE (review 8's b2): ffprobe and MediaInfo show the last TITLE, the + // album's, so a new title also goes at 30, in a new Tag after the album's, as on main; the untargeted one takes it + // too, for exiftool, which shows the first. + [TestMethod] + public async Task UntargetedTitleBeforeAnAlbumTitle_ANewTitleIsAlsoTheLastTitle () + { + var original = AlbumLayout (null, Untargeted (Simple ("TITLE", OldTitle)), Tag (50, Simple ("TITLE", OldAlbum))); + + var saved = await EditAndSave (original, "path", tag => tag.Title = NewTitle); + + CollectionAssert.AreEqual (UntargetedAlbumAndTrackTitles, FileLevelTexts (saved, "TITLE")); + var back = MatroskaFile.Read (saved).File!.Tag; + Assert.AreEqual (NewTitle, back.Title); + Assert.AreEqual (OldAlbum, back.Album); + } + + // The same, with the untargeted TITLE in two languages (review 9's u): a second title edit, from the same object or + // from a read of the first save, keeps the other language in the copy at 30 as the first edit does, so two edits + // write the file one edit to the last title writes. + [TestMethod] + [DataRow ("MatroskaFile.Read")] + [DataRow ("ReadFromData")] + [DataRow ("stream")] + [DataRow ("path")] + [DataRow ("async path")] + public async Task UntargetedTitleInTwoLanguagesBeforeAnAlbumTitle_ASecondEditKeepsTheOtherLanguage (string entry) + { + var original = AlbumLayout (null, + Untargeted (SimpleInLanguage ("TITLE", OldTitle, "eng"), SimpleInLanguage ("TITLE", "Chanson", "fre")), + Tag (50, Simple ("TITLE", OldAlbum))); + var once = await EditAndSave (original, entry, tag => tag.Title = "Newer"); + + var twice = await EditAndSave (original, entry, tag => { + tag.Title = NewTitle; + tag.Title = "Newer"; + }); + var again = await EditAndSave (await EditAndSave (original, entry, tag => tag.Title = NewTitle), entry, tag => tag.Title = "Newer"); + + CollectionAssert.AreEqual (new[] { "Newer", "Chanson", OldAlbum, "Newer", "Chanson" }, FileLevelTexts (once, "TITLE")); + CollectionAssert.AreEqual (once, twice, "two edits on one object"); + // The first save moves what follows the Tags it grows, so the Tags element is compared. + CollectionAssert.AreEqual (TagsOf (once), TagsOf (again), "an edit of the first save"); + Assert.AreEqual ("Newer", MatroskaFile.Read (twice).File!.Tag.Title); + } + + static byte[] TagsOf (byte[] file) => MatroskaFile.Read (file).File!.Tag.Render ().ToArray (); + + public static IEnumerable AlbumEditKeepsTitleSortCases () + { + foreach (var entry in MatroskaEntryPoints) { + yield return ["set", entry]; + yield return ["clear", entry]; + } + } + + // An explicit album TITLE beside an untargeted TITLE with a nested sort: an album edit keeps the title at 30 with + // that sort, so the title and its sort read as before (review 8, nit 3). + [TestMethod] + [DynamicData (nameof (AlbumEditKeepsTitleSortCases))] + public async Task AlbumEdit_KeepsTheTitleAndItsSort (string edit, string entry) + { + var original = AlbumLayout (null, Tag (50, Simple ("TITLE", OldAlbum)), Untargeted (SimpleSorted ("TITLE", "The Song", "Song, The"))); + var read = MatroskaFile.Read (original).File!.Tag; + Assert.AreEqual ("The Song", read.Title); + Assert.AreEqual ("Song, The", read.TitleSort); + + var saved = await EditAndSave (original, entry, tag => tag.Album = edit == "set" ? NewAlbum : null); + + var back = MatroskaFile.Read (saved).File!.Tag; + Assert.AreEqual ("The Song", back.Title); + Assert.AreEqual ("Song, The", back.TitleSort); + Assert.AreEqual (edit == "set" ? NewAlbum : null, back.Album); + } + + static readonly string[] MatroskaSaves = ["sync-path", "async-path", "span-sync", "span-async", "sync-in-place", "async-in-place"]; + + // Each #221 shape and edit, saved by each of the six saves from a path read: the six files are the same, and read + // back with the title and album the edit gives. + static readonly Dictionary Build, Action Edit, string Title, string? Album, string? TitleSort)> SixSaveShapes = new () { + ["untargeted TITLE, new title"] = (() => AlbumLayout (null, Untargeted (Simple ("TITLE", OldTitle))), t => t.Title = NewTitle, NewTitle, null, null), + ["segment title and untargeted TITLE, new title"] = (() => AlbumLayout (OldTitle, Untargeted (Simple ("TITLE", OldTitle))), t => t.Title = NewTitle, NewTitle, null, null), + ["two languages, new title"] = (() => AlbumLayout (null, Untargeted (SimpleInLanguage ("TITLE", OldTitle, "eng"), SimpleInLanguage ("TITLE", "Chanson", "fre"))), t => t.Title = NewTitle, NewTitle, null, null), + ["album TITLE and sorted untargeted TITLE, new album"] = (() => AlbumLayout (null, Tag (50, Simple ("TITLE", OldAlbum)), Untargeted (SimpleSorted ("TITLE", OldTitle, "Sort key"))), t => t.Album = NewAlbum, OldTitle, NewAlbum, "Sort key"), + ["album TITLE and sorted untargeted TITLE, new title"] = (() => AlbumLayout (null, Tag (50, Simple ("TITLE", OldAlbum)), Untargeted (SimpleSorted ("TITLE", OldTitle, "Sort key"))), t => t.Title = NewTitle, NewTitle, OldAlbum, "Sort key"), + ["two languages before an album TITLE, two title edits"] = (() => AlbumLayout (null, Untargeted (SimpleInLanguage ("TITLE", OldTitle, "eng"), SimpleInLanguage ("TITLE", "Chanson", "fre")), Tag (50, Simple ("TITLE", OldAlbum))), t => { + t.Title = NewTitle; + t.Title = "Newer"; + }, "Newer", OldAlbum, null), + ["sorted untargeted TITLE, new title sort"] = (() => AlbumLayout (null, Untargeted (SimpleSorted ("TITLE", OldTitle, "Sort key"))), t => t.TitleSort = "New key", OldTitle, null, "New key"), + }; + + public static IEnumerable SixSaveCases () => SixSaveShapes.Keys.Select (shape => new object[] { shape }); + + [TestMethod] + [DynamicData (nameof (SixSaveCases))] + public async Task UntargetedTitleEdits_EverySaveWritesTheSameFile (string shape) + { + var (build, edit, title, album, titleSort) = SixSaveShapes[shape]; + var original = build (); + var written = new List (); + foreach (var save in MatroskaSaves) { + var fs = new MockFileSystem (); + fs.AddFile ("/in.mka", original); + var file = (MatroskaFile)MediaFile.Read ("/in.mka", fs).File!; + edit (file.Tag); + var result = save switch { + "sync-path" => file.SaveToFile ("/out.mka", fs), + "async-path" => await file.SaveToFileAsync ("/out.mka", fs), + "span-sync" => file.SaveToFile ("/out.mka", original, fs), + "span-async" => await file.SaveToFileAsync ("/out.mka", original, fs), + "sync-in-place" => file.SaveToFile (fs), + _ => await file.SaveToFileAsync (fs), + }; + Assert.IsTrue (result.IsSuccess, $"{shape} {save}: {result.Error}"); + written.Add (fs.ReadAllBytes (save.EndsWith ("in-place", StringComparison.Ordinal) ? "/in.mka" : "/out.mka")); + } + + for (var i = 1; i < written.Count; i++) + CollectionAssert.AreEqual (written[0], written[i], $"{shape}: {MatroskaSaves[i]} against {MatroskaSaves[0]}"); + var back = MatroskaFile.Read (written[0]).File!.Tag; + Assert.AreEqual (title, back.Title, shape); + Assert.AreEqual (album, back.Album, shape); + Assert.AreEqual (titleSort, back.TitleSort, shape); + } + + // The copy at 30 of an untargeted TITLE in many languages (a file sets how many): a second title edit takes the + // untargeted TITLEs again in time linear in them. + [TestMethod] + [Timeout (60_000)] + public void TitleEdit_ACopyInManyLanguages_IsLinearInThem () + { + static long Steps (int count) + { + var titles = new byte[count][]; + for (var i = 0; i < count; i++) + titles[i] = SimpleInLanguage ("TITLE", i == 0 ? OldTitle : $"t{i}", $"l{i}"); + var bytes = Matroska (WideElement (0x18538067, Concat ( + WideElement (0x1254C367, Concat (WideElement (0x7373, Concat (Master (0x63C0, Array.Empty ()), Concat (titles))), Tag (50, Simple ("TITLE", OldAlbum)))), + Master (0x1F43B675, new byte[] { 1 })))); + var tag = MatroskaFile.Read (bytes).File!.Tag; + tag.Title = "First"; + MatroskaTag.LevelSteps = 0; + tag.Title = NewTitle; + Assert.AreEqual (NewTitle, tag.Title); + return MatroskaTag.LevelSteps; + } + + // The copy was replaced one TITLE at a time, each a search and a removal through the Tag: 40,000 TITLEs took + // longer than the timeout. + var one = Steps (10_000); + var four = Steps (40_000); + Assert.IsTrue (one >= 10_000, $"{one} steps for 10,000 TITLEs: the counter is not counting"); + Assert.IsTrue (four <= 5 * one, $"{one} steps for 10,000 TITLEs, {four} for 40,000: not linear"); + } + + static byte[] SimpleInLanguage (string name, string text, string language) => + Master (0x67C8, Concat (Element (0x45A3, System.Text.Encoding.UTF8.GetBytes (name)), Element (0x447A, System.Text.Encoding.ASCII.GetBytes (language)), + Element (0x4487, System.Text.Encoding.UTF8.GetBytes (text)))); +} diff --git a/tests/TagLibSharp2.Tests/Mp4/Mp4MalformedInputTests.cs b/tests/TagLibSharp2.Tests/Mp4/Mp4MalformedInputTests.cs index d995eb3b..9844fb40 100644 --- a/tests/TagLibSharp2.Tests/Mp4/Mp4MalformedInputTests.cs +++ b/tests/TagLibSharp2.Tests/Mp4/Mp4MalformedInputTests.cs @@ -336,13 +336,16 @@ public void ZeroLengthDataAtom () /// /// A version 1 mvhd holds a 64-bit duration. With timescale 1 it is past TimeSpan.MaxValue (ISO 14496-12 §8.2.2). /// - static byte[] FileWithHugeMovieDuration () + internal static byte[] FileWithHugeMovieDuration () => FileWithHugeMovieDuration (1); + + /// A version 1 mvhd whose duration is all 1s at . + internal static byte[] FileWithHugeMovieDuration (uint timescale) { var mvhd = new BinaryDataBuilder (); mvhd.AddUInt32BE (0x01000000); mvhd.AddUInt64BE (0); mvhd.AddUInt64BE (0); - mvhd.AddUInt32BE (1); + mvhd.AddUInt32BE (timescale); mvhd.AddUInt64BE (ulong.MaxValue); mvhd.AddUInt32BE (0x00010000); mvhd.AddUInt16BE (0x0100); @@ -357,19 +360,20 @@ static byte[] FileWithHugeMovieDuration () return [.. Mp4TestBuilder.CreateFtypBox (), .. Mp4TestBuilder.CreateMoovBox (children)]; } + // A duration TimeSpan cannot hold is unknown, not TimeSpan.MaxValue (#181; #175 saturated). [TestMethod] - public void Read_MovieDurationPastTimeSpan_SaturatesInsteadOfThrowing () + public void Read_MovieDurationPastTimeSpan_IsUnknown () { var result = Mp4File.Read (FileWithHugeMovieDuration ()); Assert.IsTrue (result.IsSuccess, result.Error); - Assert.AreEqual (TimeSpan.MaxValue, result.File!.Duration); + Assert.AreEqual (TimeSpan.Zero, result.File!.Duration); } [TestMethod] - public void AudioPropertiesParser_MovieDurationPastTimeSpan_SaturatesInsteadOfThrowing () + public void AudioPropertiesParser_MovieDurationPastTimeSpan_TakesTheTrackDuration () { - // The mvhd duration no longer throws; the audio track's mdhd duration (10 s) wins as before. + // The mvhd duration does not throw; the audio track's mdhd duration (10 s) wins as before. var properties = Mp4AudioPropertiesParser.Parse (FileWithHugeMovieDuration ()); Assert.AreEqual (TimeSpan.FromSeconds (10), properties.Duration); diff --git a/tests/TagLibSharp2.Tests/Mpeg/Mp3SaveStreamsAudioTests.cs b/tests/TagLibSharp2.Tests/Mpeg/Mp3SaveStreamsAudioTests.cs index 12ea8fe8..4d01f094 100644 --- a/tests/TagLibSharp2.Tests/Mpeg/Mp3SaveStreamsAudioTests.cs +++ b/tests/TagLibSharp2.Tests/Mpeg/Mp3SaveStreamsAudioTests.cs @@ -39,7 +39,8 @@ public void SaveToFile_CopiesAudioWithoutLoadingTheFile () var allocated = GC.GetAllocatedBytesForCurrentThread () - before; Assert.IsTrue (save.IsSuccess, save.Error); - Assert.AreEqual (1, fs.SourceLengthGets, "source length reads"); + // Open records the length once. The save then reads the source back to see whether it wrote over it (#179). + Assert.AreEqual (2, fs.SourceLengthGets, "source length reads"); Assert.IsTrue ( allocated < original.Length / 2, $"save allocated {allocated} bytes for a {original.Length} byte file"); @@ -65,7 +66,8 @@ public async Task SaveToFileAsync_CopiesAudioWithoutLoadingTheFile () var allocated = GC.GetAllocatedBytesForCurrentThread () - before; Assert.IsTrue (save.IsSuccess, save.Error); - Assert.AreEqual (1, fs.SourceLengthGets, "source length reads"); + // Open records the length once. The save then reads the source back to see whether it wrote over it (#179). + Assert.AreEqual (2, fs.SourceLengthGets, "source length reads"); Assert.IsTrue ( allocated < original.Length / 2, $"save allocated {allocated} bytes for a {original.Length} byte file"); diff --git a/tests/TagLibSharp2.Tests/Mpeg/Mp3TrailerTests.cs b/tests/TagLibSharp2.Tests/Mpeg/Mp3TrailerTests.cs new file mode 100644 index 00000000..5ad98243 --- /dev/null +++ b/tests/TagLibSharp2.Tests/Mpeg/Mp3TrailerTests.cs @@ -0,0 +1,91 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using TagLibSharp2.Core; +using TagLibSharp2.Id3; +using TagLibSharp2.Id3.Id3v2; +using TagLibSharp2.Mpeg; +using TagLibSharp2.Tests.Core; +using static TagLibSharp2.Tests.Core.SpanSaveKit; + +namespace TagLibSharp2.Tests.Mpeg; + +/// +/// The audio of an MP3 ends where the file's ID3v1 tag starts, or at the end of the file when it has none, whatever tag +/// the object holds when it saves. On 01b8d6cc the audio ended 128 bytes before the end whenever the object held an +/// ID3v1 tag: removing the tag (Id3v1Tag = null) kept its bytes as audio, and adding one cut the last 128 bytes +/// of audio. +/// +[TestClass] +[TestCategory ("Unit")] +[TestCategory ("Mpeg")] +public sealed class Mp3TrailerTests +{ + static readonly byte[] Audio = Mp3Frames (100); + + public static IEnumerable Rows () + { + foreach (var change in new[] { "remove", "add" }) + foreach (var save in new[] { "span", "span-async", "path", "path-async", "in-place", "in-place-async" }) + yield return [change, save]; + } + + [TestMethod] + [DynamicData (nameof (Rows))] + public async Task Save_TakesTheAudioUpToTheTagTheFileHolds (string change, string save) + { + var original = Build (withTrailer: change == "remove"); + var files = new MockFileSystem (); + var file = (Mp3File)Open (".mp3", save.StartsWith ("span", StringComparison.Ordinal) ? "data" : "path", original, files); + file.Id3v1Tag = change == "remove" ? null : Trailer (); + + var written = await Save (file, save, original, files); + + AssertLayout (written, trailer: change == "add"); + } + + // After an in-place save the file on disk has the other layout; a second save keeps the same audio. + [TestMethod] + [DynamicData (nameof (Rows))] + public async Task SaveAfterAnInPlaceSave_TakesTheAudioUpToTheTagTheFileNowHolds (string change, string save) + { + var original = Build (withTrailer: change == "remove"); + var files = new MockFileSystem (); + var file = (Mp3File)Open (".mp3", "path", original, files); + file.Id3v1Tag = change == "remove" ? null : Trailer (); + Assert.IsTrue ((await SavePath (file, null, sync: true, files)).IsSuccess); + var onDisk = files.ReadAllBytes ("/in.mp3"); + file.Title = "Saved again"; + + var written = await Save (file, save, onDisk, files); + + AssertLayout (written, trailer: change == "add"); + } + + static async Task Save (Mp3File file, string save, byte[] bytes, MockFileSystem files) + { + var sync = !save.EndsWith ("-async", StringComparison.Ordinal); + var result = save switch { + _ when save.StartsWith ("span", StringComparison.Ordinal) => await SaveSpan (file, "/out.mp3", bytes, sync, files), + _ when save.StartsWith ("path", StringComparison.Ordinal) => await SavePath (file, "/out.mp3", sync, files), + _ => await SavePath (file, null, sync, files), + }; + Assert.IsTrue (result.IsSuccess, result.Error); + return files.ReadAllBytes (save.StartsWith ("in-place", StringComparison.Ordinal) ? "/in.mp3" : "/out.mp3"); + } + + // The written file is its ID3v2 tag, the audio, and a 128-byte ID3v1 tag when one is expected. + static void AssertLayout (byte[] written, bool trailer) + { + var tagEnd = Id3v2Header.Read (written).Header.TotalSize; + var end = trailer ? written.Length - 128 : written.Length; + CollectionAssert.AreEqual (Audio, written[(int)tagEnd..end], "the audio"); + if (trailer) + CollectionAssert.AreEqual ("TAG"u8.ToArray (), written[end..(end + 3)], "the ID3v1 tag"); + } + + static byte[] Build (bool withTrailer) => + [.. new Id3v2Tag { Title = "Title" }.Render ().Span, .. Audio, .. withTrailer ? TestBuilders.Id3v1.CreateTag (title: "Title") : []]; + + static Id3v1Tag Trailer () => Id3v1Tag.Read (TestBuilders.Id3v1.CreateTag (title: "Added")).Tag!; +} diff --git a/tests/TagLibSharp2.Tests/Mpeg/MpegPsSaveStreamsAudioTests.cs b/tests/TagLibSharp2.Tests/Mpeg/MpegPsSaveStreamsAudioTests.cs index 31e64903..0f82b331 100644 --- a/tests/TagLibSharp2.Tests/Mpeg/MpegPsSaveStreamsAudioTests.cs +++ b/tests/TagLibSharp2.Tests/Mpeg/MpegPsSaveStreamsAudioTests.cs @@ -77,7 +77,8 @@ static void AssertSaved ( long allocated) { Assert.IsTrue (save.IsSuccess, save.Error); - Assert.AreEqual (1, fs.SourceLengthGets, "source length reads"); + // Open records the length once. The save then reads the source back to see whether it wrote over it (#179). + Assert.AreEqual (2, fs.SourceLengthGets, "source length reads"); Assert.IsTrue ( allocated < original.Length / 2, $"save allocated {allocated} bytes for a {original.Length} byte file"); diff --git a/tests/TagLibSharp2.Tests/Ogg/OggAudioCarriedSaveTests.cs b/tests/TagLibSharp2.Tests/Ogg/OggAudioCarriedSaveTests.cs new file mode 100644 index 00000000..3218dda6 --- /dev/null +++ b/tests/TagLibSharp2.Tests/Ogg/OggAudioCarriedSaveTests.cs @@ -0,0 +1,285 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Buffers.Binary; +using TagLibSharp2.Core; +using TagLibSharp2.Ogg; +using TagLibSharp2.Tests.Core; +using TagLibSharp2.Xiph; + +namespace TagLibSharp2.Tests.Ogg; + +/// +/// #199: a save of an Ogg file carries every audio page across, or fails and writes nothing. An Opus file whose tags +/// page is broken read 2.0 s, and its save, with no edit, reported success and wrote its two header pages without the +/// audio; Ogg FLAC did the same, and Ogg Vorbis refused. One rule now decides for all three, on every save entry point +/// (the path saves sync and async, the saves from the bytes, and the saves in place): the save fails when the page walk +/// stops at bytes that are no page with a readable page after them, or when the page the duration comes from lies +/// among the header pages (a header page whose declared body runs over the audio pages). A header packet cut off at +/// the end of the file, which Vorbis refused, is refused by every codec: the packet walk tells it. Bytes after the last +/// page that hold no page, and a last audio page cut short, are written after the pages as they were (#215), where a +/// save dropped them: a truncated file kept its duration. +/// +[TestClass] +[TestCategory ("Unit")] +public sealed class OggAudioCarriedSaveTests +{ + const int AudioPages = 4; + + static readonly string[] Codecs = ["opus", "vorbis", "flac"]; + + // tags-capture: one byte of the page after the first breaks its capture pattern (review 5's opus-tagspage.opus). + // header-runs-over: the audio pages are the body of a header page (the s072 fuzz files). junk-between: bytes that + // are no page between two audio pages. header-cut: the file ends 10 bytes into the second header page, and + // header-open: after a page whose last packet goes on (granule 0, as header pages carry); header-cut-head: 20 + // bytes into the second page's own header. A header packet is cut off at the end of the file (eight s072 files), + // and a save would rebuild it without its lost bytes or leave it out. + static readonly string[] Dropping = ["tags-capture", "header-runs-over", "junk-between", "header-cut", "header-open", "header-cut-head"]; + + // junk-at-end: bytes that are no page after the last page. cut-last-page: the last page ends 10 bytes short. + static readonly string[] Kept = ["junk-at-end", "cut-last-page"]; + + static readonly string[] Saves = ["sync-path", "async-path", "span-sync", "span-async", "sync-in-place", "async-in-place"]; + + public static IEnumerable DroppingRows () => + from codec in Codecs + from shape in Dropping + from save in Saves + select new object[] { codec, shape, save }; + + [TestMethod] + [DynamicData (nameof (DroppingRows))] + public async Task AudioThatWouldBeDropped_SaveFailsAndWritesNothing (string codec, string shape, string save) + { + var bytes = Build (codec, shape); + var (files, source, file) = Read (codec, bytes); + + var result = await Save (file, save, source, bytes, files); + + Assert.IsFalse (result.IsSuccess, $"{codec} {shape} {save}: the save dropped audio and reported success"); + Assert.AreEqual ("Failed to render " + Name (codec) + " file", result.Error); + CollectionAssert.AreEqual (bytes, files.ReadAllBytes (source), "the source changed"); + Assert.IsFalse (files.FileExists (Target (codec)), "a failed save wrote"); + } + + public static IEnumerable KeptRows () => + from codec in Codecs + from shape in Kept + from save in Saves + select new object[] { codec, shape, save }; + + [TestMethod] + [DynamicData (nameof (KeptRows))] + public async Task BytesAfterTheLastPage_SaveKeepsEveryAudioPage (string codec, string shape, string save) + { + var bytes = Build (codec, shape); + var (files, source, file) = Read (codec, bytes); + var duration = ((IMediaFile)file).AudioProperties?.Duration; + + var result = await Save (file, save, source, bytes, files); + + Assert.IsTrue (result.IsSuccess, $"{codec} {shape} {save}: {result.Error}"); + var written = files.ReadAllBytes (save.StartsWith ("span", StringComparison.Ordinal) || save.EndsWith ("in-place", StringComparison.Ordinal) ? source : Target (codec)); + // The whole audio pages before the cut or the bytes at the end. + for (var page = 0; page < (shape == "cut-last-page" ? AudioPages - 1 : AudioPages); page++) + Assert.IsGreaterThanOrEqualTo (0, written.AsSpan ().IndexOf (AudioPacket (codec, page)), $"{codec} {shape} {save}: audio page {page} was dropped"); + // Then the bytes after the last whole page, as they were (#215): the last page cut short carries the duration. + var tail = bytes.AsSpan (shape == "cut-last-page" ? bytes.Length - (CutPageLength (codec) - 10) : bytes.Length - 100); + Assert.IsTrue (written.AsSpan ().EndsWith (tail), $"{codec} {shape} {save}: the {tail.Length} bytes after the last whole page"); + // The last whole page ends the stream unless the page after it, cut short, does, as in the source. + var lastWhole = AudioPacket (codec, shape == "cut-last-page" ? AudioPages - 2 : AudioPages - 1); + var lastPage = written.AsSpan (0, written.AsSpan ().IndexOf (lastWhole)).LastIndexOf ("OggS"u8); + Assert.AreEqual (shape != "cut-last-page", (written[lastPage + 5] & 0x04) != 0, $"{codec} {shape} {save}: end of stream on the last whole page"); + var back = MediaFile.ReadFromData (written, source); + Assert.IsTrue (back.IsSuccess, back.Error); + Assert.AreEqual (duration, ((IMediaFile)back.File!).AudioProperties?.Duration); + } + + public static IEnumerable CutInHeaderRows () => + from codec in Codecs + from cut in Enumerable.Range (1, 27) + select new object[] { codec, cut }; + + // The file ends 1 to 27 bytes into the last page's header (27: the header whole, its segment table gone). Every save + // writes the same bytes: the pages before it, the last whole one not marked as the end of the stream, since the cut + // page holds that mark in the source, then the cut bytes as they were (review 7, N1). + [TestMethod] + [DynamicData (nameof (CutInHeaderRows))] + public async Task LastPageCutInItsHeader_EverySaveWritesTheSameBytes (string codec, int cut) + { + var whole = Build (codec, "whole"); + var lastPage = whole.AsSpan ().LastIndexOf ("OggS"u8); + byte[] bytes = [.. whole.AsSpan (0, lastPage + cut)]; + var written = new List (); + foreach (var save in Saves) { + var (files, source, file) = Read (codec, bytes); + var result = await Save (file, save, source, bytes, files); + Assert.IsTrue (result.IsSuccess, $"{codec} {cut} {save}: {result.Error}"); + written.Add (files.ReadAllBytes (save.StartsWith ("span", StringComparison.Ordinal) || save.EndsWith ("in-place", StringComparison.Ordinal) ? source : Target (codec))); + } + + for (var i = 1; i < Saves.Length; i++) + CollectionAssert.AreEqual (written[0], written[i], $"{codec} {cut}: {Saves[i]} against {Saves[0]}"); + Assert.IsTrue (written[0].AsSpan ().EndsWith (bytes.AsSpan (lastPage)), $"{codec} {cut}: the cut bytes, as they were"); + var lastWhole = written[0].AsSpan (0, written[0].Length - cut).LastIndexOf ("OggS"u8); + Assert.AreEqual (0, written[0][lastWhole + 5] & 0x04, $"{codec} {cut}: the last whole page is not marked as the end of the stream"); + } + + static string Name (string codec) => codec switch { + "opus" => "Ogg Opus", + "vorbis" => "Ogg Vorbis", + _ => "Ogg FLAC", + }; + + static string Extension (string codec) => codec switch { + "opus" => ".opus", + "vorbis" => ".ogg", + _ => ".oga", + }; + + static string Target (string codec) => "/out" + Extension (codec); + + static (MockFileSystem Files, string Source, object File) Read (string codec, byte[] bytes) + { + var files = new MockFileSystem (); + var source = "/in" + Extension (codec); + files.AddFile (source, bytes); + var read = MediaFile.Read (source, files); + Assert.IsTrue (read.IsSuccess, codec + ": " + read.Error); + return (files, source, read.File!); + } + + static Task Save (object file, string save, string source, byte[] bytes, MockFileSystem files) => save switch { + "sync-path" => SpanSaveKit.SavePath (file, "/out" + Path.GetExtension (source), sync: true, files), + "async-path" => SpanSaveKit.SavePath (file, "/out" + Path.GetExtension (source), sync: false, files), + "span-sync" => SpanSaveKit.SaveSpan (file, source, bytes, sync: true, files), + "span-async" => SpanSaveKit.SaveSpan (file, source, bytes, sync: false, files), + "sync-in-place" => SpanSaveKit.SavePath (file, null, sync: true, files), + _ => SpanSaveKit.SavePath (file, null, sync: false, files), + }; + + // The header packets of each codec, then AudioPages audio pages of one packet each, granules rising; the last page + // ends the stream. + static byte[] Build (string codec, string shape) + { + const uint Serial = 0x5EED; + var headers = HeaderPackets (codec); + var first = OggPageHelper.BuildOggPage ([headers[0]], OggPageFlags.BeginOfStream, 0, Serial, 0); + var audio = new List (); + for (var page = 0; page < AudioPages; page++) { + var flags = page == AudioPages - 1 ? OggPageFlags.EndOfStream : OggPageFlags.None; + audio.Add (OggPageHelper.BuildOggPage ([AudioPacket (codec, page)], flags, (ulong)(48_000 * (page + 1)), Serial, (uint)(2 + page))); + } + + byte[] Concat (IEnumerable parts) => [.. parts.SelectMany (part => part)]; + + // The audio pages are one more packet on the second header page. + if (shape == "header-runs-over") + return [.. first, .. OggPageHelper.BuildOggPage ([.. headers.Skip (1), Concat (audio)], OggPageFlags.None, 0, Serial, 1)]; + + var second = OggPageHelper.BuildOggPage ([.. headers.Skip (1)], OggPageFlags.None, 0, Serial, 1); + if (shape == "header-cut") + return [.. first, .. second[..^10]]; + if (shape == "header-cut-head") + return [.. first, .. second[..20]]; + if (shape == "header-open") + return [.. first, .. WithGranuleZero (OggPageHelper.BuildMultiPagePacket ([.. headers[1], .. new byte[70_000]], OggPageFlags.None, 0, Serial, 1).Pages[0])]; + if (shape == "tags-capture") + second[0] = 0; + byte[] junk = [.. Enumerable.Repeat ((byte)0x55, 100)]; + byte[] file = shape switch { + "junk-between" => [.. first, .. second, .. Concat (audio.Take (2)), .. junk, .. Concat (audio.Skip (2))], + "junk-at-end" => [.. first, .. second, .. Concat (audio), .. junk], + _ => [.. first, .. second, .. Concat (audio)], + }; + return shape == "cut-last-page" ? file[..^10] : file; + } + + // The page with granule position 0 and its CRC set again. + static byte[] WithGranuleZero (byte[] page) + { + var copy = (byte[])page.Clone (); + copy.AsSpan (6, 8).Clear (); + copy.AsSpan (22, 4).Clear (); + BinaryPrimitives.WriteUInt32LittleEndian (copy.AsSpan (22), OggCrc.Calculate (copy)); + return copy; + } + + // An Opus file that ends after OpusHead with no more pages, or with bytes that are no page, cut no header packet: + // the bytes after OpusHead are not audio, and a save writes OpusHead and the tags it holds, as a file with junk + // after its last page saves. + static readonly string[] OpusEndings = ["nothing", "junk"]; + + public static IEnumerable OpusHeadOnlyRows () => + from ending in OpusEndings + from save in Saves + select new object[] { ending, save }; + + [TestMethod] + [DynamicData (nameof (OpusHeadOnlyRows))] + public async Task OpusHeadThenNoPage_Saves (string ending, string save) + { + var first = OggPageHelper.BuildOggPage ([TestBuilders.Opus.CreateOpusHeadPacket ()], OggPageFlags.BeginOfStream, 0, 0x5EED, 0); + // Ten zero bytes: no capture pattern, though a version byte of 0 where a page would have it. + byte[] bytes = ending == "junk" ? [.. first, .. new byte[10]] : first; + var (files, source, file) = Read ("opus", bytes); + + var result = await Save (file, save, source, bytes, files); + + Assert.IsTrue (result.IsSuccess, $"{ending} {save}: {result.Error}"); + } + + // With every header packet read, a page the end of the file cuts inside its own header is the audio's, not a header + // packet's: the file saves (with no whole audio page), as one whose last page is cut short does. + static readonly string[] Rebuilt = ["opus", "vorbis"]; + + public static IEnumerable HeadersThenCutRows () => + from codec in Rebuilt + from save in Saves + select new object[] { codec, save }; + + [TestMethod] + [DynamicData (nameof (HeadersThenCutRows))] + public async Task HeadersThenAPageCutInItsHeader_Saves (string codec, string save) + { + var whole = Build (codec, "junk-at-end"); + var audioStart = whole.AsSpan ().IndexOf (AudioPacket (codec, 0)) - 28; + byte[] bytes = [.. whole.AsSpan (0, audioStart + 20)]; + var (files, source, file) = Read (codec, bytes); + + var result = await Save (file, save, source, bytes, files); + + Assert.IsTrue (result.IsSuccess, $"{codec} {save}: {result.Error}"); + } + + // The length of the last audio page, which cut-last-page cuts 10 bytes short. + static int CutPageLength (string codec) => + OggPageHelper.BuildOggPage ([AudioPacket (codec, AudioPages - 1)], OggPageFlags.EndOfStream, 0, 0, 0).Length; + + static byte[][] HeaderPackets (string codec) + { + var comment = new VorbisComment ("TagLibSharp2") { Title = "Title" }; + return codec switch { + "opus" => [TestBuilders.Opus.CreateOpusHeadPacket (), TestBuilders.Opus.CreateOpusTagsPacket (comment)], + "vorbis" => [TestBuilders.Ogg.CreateIdentificationPacket (), TestBuilders.Ogg.CreateCommentPacket (comment), TestBuilders.Ogg.CreateSetupPacket ()], + _ => [.. OggPageHelper.ExtractHeaderPackets (TestBuilders.OggFlac.CreateWithMetadata ("Title"), maxPackets: 2).Packets], + }; + } + + // A packet of 200 bytes the codec reads as audio (Opus TOC, a Vorbis audio packet, a FLAC frame sync), marked with + // its page so each can be found in a saved file. + static byte[] AudioPacket (string codec, int page) + { + var packet = new byte[200]; + packet[0] = codec switch { + "opus" => 0xFC, + "vorbis" => 0x00, + _ => 0xFF, + }; + if (codec == "flac") + packet[1] = 0xF8; + for (var i = 2; i < packet.Length; i++) + packet[i] = (byte)(page * 37 + i); + return packet; + } +} diff --git a/tests/TagLibSharp2.Tests/Ogg/OggDurationGranuleTests.cs b/tests/TagLibSharp2.Tests/Ogg/OggDurationGranuleTests.cs index 0094e45a..c4727ff8 100644 --- a/tests/TagLibSharp2.Tests/Ogg/OggDurationGranuleTests.cs +++ b/tests/TagLibSharp2.Tests/Ogg/OggDurationGranuleTests.cs @@ -56,7 +56,7 @@ public void TwoPartScan_IsTheScanOfTheConcatenation () for (var run = 0; run < 400; run++) { var bytes = RandomPages (random); for (var cut = 0; cut <= bytes.Length; cut++) { - var joined = OggPageHelper.FindLastGranulePosition (bytes); + var joined = OggPageHelper.FindLastGranulePosition (bytes, []); var parts = OggPageHelper.FindLastGranulePosition (bytes.AsSpan (0, cut), bytes.AsSpan (cut)); Assert.AreEqual (joined, parts, $"run {run}, cut {cut} of {bytes.Length}"); } diff --git a/tests/TagLibSharp2.Tests/Ogg/OggDurationTests.cs b/tests/TagLibSharp2.Tests/Ogg/OggDurationTests.cs new file mode 100644 index 00000000..0d496c46 --- /dev/null +++ b/tests/TagLibSharp2.Tests/Ogg/OggDurationTests.cs @@ -0,0 +1,399 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Buffers.Binary; +using TagLibSharp2.Core; +using TagLibSharp2.Ogg; +using TagLibSharp2.Tests.Core; + +namespace TagLibSharp2.Tests.Ogg; + +/// +/// The duration of an Ogg stream is its last granule position (RFC 3533 §6) in the codec's units, read the same way +/// on every entry point. +/// +[TestClass] +[TestCategory ("Unit")] +[TestCategory ("Ogg")] +public sealed class OggDurationTests +{ + // Every entry point, with and without SkipPictures (DurationUnknownTests.Entries). + public static IEnumerable EntryRows () => DurationUnknownTests.EntryRows (); + + // ffmpeg writes STREAMINFO total samples = 0 into Ogg FLAC, which RFC 9639 §8.2 calls unknown; the granule + // position carries the length. A 2-second ffmpeg file reads 2.0 s in ffprobe, MediaInfo and mutagen (#184). + [TestMethod] + [DynamicData (nameof (EntryRows))] + public void OggFlacWithoutATotal_TakesTheDurationFromTheGranule (string entry) + { + var file = DurationUnknownTests.Open (OggFlacWithoutATotal (granule: 88_200), ".oga", entry); + + var flac = (OggFlacFile)file; + Assert.AreEqual (TimeSpan.FromSeconds (2), flac.Properties.Duration, entry); + Assert.AreEqual (44_100, flac.Properties.SampleRate, entry); + Assert.AreEqual (2, flac.Properties.Channels, entry); + Assert.AreEqual (16, flac.Properties.BitsPerSample, entry); + Assert.AreEqual (0UL, flac.TotalSamples, entry); + } + + // No total and no granule: the duration is unknown, the other properties are still STREAMINFO's (#184). + [TestMethod] + [DynamicData (nameof (EntryRows))] + public void OggFlacWithoutATotalOrAGranule_KeepsItsOtherProperties (string entry) + { + var bytes = OggFlacWithoutATotal (granule: 0); + + var flac = (OggFlacFile)DurationUnknownTests.Open (bytes, ".oga", entry); + + Assert.AreEqual (TimeSpan.Zero, flac.Properties.Duration, entry); + Assert.AreEqual (44_100, flac.Properties.SampleRate, entry); + Assert.AreEqual (2, flac.Properties.Channels, entry); + Assert.AreEqual (16, flac.Properties.BitsPerSample, entry); + } + + // A STREAMINFO total wins over the granule. + [TestMethod] + [DynamicData (nameof (EntryRows))] + public void OggFlacWithATotal_TakesTheDurationFromStreamInfo (string entry) + { + byte[] bytes = [.. TestBuilders.OggFlac.CreateMinimal (), .. DurationUnknownTests.LastPage (88_200)]; + + var flac = (OggFlacFile)DurationUnknownTests.Open (bytes, ".oga", entry); + + Assert.AreEqual (TimeSpan.FromSeconds (1), flac.Properties.Duration, entry); + } + + // Each codec's minimal file and an audio page whose granule is 2 s, without end of stream: what a tail follows. + // Each codec's minimal file: its header pages alone. + static readonly Dictionary> HeaderPages = new () { + ["opus"] = () => TestBuilders.Opus.CreateMinimalFile (), + ["vorbis"] = () => TestBuilders.Ogg.CreateMinimalFile (), + ["oggflac"] = OggFlacNoTotal, + }; + + static readonly Dictionary Build, ulong Granule, ulong Rate)> Codecs = new () { + // Opus granules count 48 kHz samples from the start of the pre-skip (RFC 7845 §4): 96,000 + 312. + ["opus"] = (".opus", () => [.. HeaderPages["opus"] (), .. Page (96_000 + 312, 2)], 96_000 + 312, 48_000), + ["vorbis"] = (".ogg", () => [.. HeaderPages["vorbis"] (), .. Page (88_200, 2)], 88_200, 44_100), + ["oggflac"] = (".oga", () => [.. HeaderPages["oggflac"] (), .. Page (88_200, 2)], 88_200, 44_100), + }; + + public static IEnumerable CodecRows () => + from codec in Codecs.Keys + from entry in DurationUnknownTests.Entries + select new object[] { codec, entry }; + + // RFC 3533 §6 lets a page hold no segments: "a page may contain no packets at all" (an end-of-stream page that + // only carries the final granule, as some muxers write it). Such a page is 27 bytes; the scan that reads the + // granule stopped one byte before a page of exactly that length at the end, and the duration was 0 (#189). + // ffprobe and MediaInfo read the 2 s. + [TestMethod] + [DynamicData (nameof (CodecRows))] + public void EmptyLastPage_CarriesTheDuration (string codec, string entry) + { + var (extension, build, granule, _) = Codecs[codec]; + byte[] bytes = [.. build (), .. EmptyPage (granule, 3)]; + + var file = DurationUnknownTests.Open (bytes, extension, entry); + + Assert.AreEqual (TimeSpan.FromSeconds (2), ((IMediaFile)file).AudioProperties!.Duration, $"{codec} {entry}"); + } + + // The same page as the only page after the headers: no audio page precedes it. For Ogg FLAC every header walk + // (span, stream, SkipPictures) tells it from a header page by the header count the first packet declares (#189). + [TestMethod] + [DynamicData (nameof (CodecRows))] + public void EmptyLastPageAlone_CarriesTheDuration (string codec, string entry) + { + var (extension, _, granule, _) = Codecs[codec]; + byte[] bytes = [.. HeaderPages[codec] (), .. EmptyPage (granule, 2)]; + + var file = DurationUnknownTests.Open (bytes, extension, entry); + + Assert.AreEqual (TimeSpan.FromSeconds (2), ((IMediaFile)file).AudioProperties!.Duration, $"{codec} {entry}"); + } + + // RFC 3533 §6: the end-of-stream flag marks "the last page of a logical bitstream". On a header page it is wrong, + // and the granule scan preferred that page's granule (0) over the audio page after it: a full read reported 0 + // while a SkipPictures read, whose header pages are rebuilt without the flag, reported the audio page's 2 s + // (#190). The flag no longer picks the granule; ffprobe reads 2.0065 s for the review's eoshead-base.opus. + [TestMethod] + [DynamicData (nameof (CodecRows))] + public void EndOfStreamOnAHeaderPage_DoesNotPickTheGranule (string codec, string entry) + { + var (extension, build, _, _) = Codecs[codec]; + var bytes = build (); + bytes[5] |= (byte)OggPageFlags.EndOfStream; + + var file = DurationUnknownTests.Open (bytes, extension, entry); + + Assert.AreEqual (TimeSpan.FromSeconds (2), ((IMediaFile)file).AudioProperties!.Duration, $"{codec} {entry}"); + } + + // An Ogg FLAC header page with no packets between the identification page and the comment page. The first packet's + // header count tells such a page from the stream's only when it is known: with 1 the comment is still ahead, and + // with 0 (unknown) nothing says the headers are done, so the walks keep reading headers and every entry point + // still reads the comment (#189). + [TestMethod] + [DynamicData (nameof (DeclaredRows))] + public void OggFlacEmptyPageBeforeTheComment_KeepsTheComment (int declared, string entry) + { + var file = TestBuilders.OggFlac.CreateWithMetadata (title: "Title"); + var second = file.AsSpan (4).IndexOf ("OggS"u8) + 4; + BinaryPrimitives.WriteUInt16BigEndian (file.AsSpan (file.AsSpan ().IndexOf ("FLAC"u8) + 6), (ushort)declared); + byte[] bytes = [.. file.AsSpan (0, second), .. EmptyPage (0, 1, OggPageFlags.None), .. file.AsSpan (second)]; + + var read = (IMediaFile)DurationUnknownTests.Open (bytes, ".oga", entry); + + Assert.AreEqual ("Title", read.Tag?.Title, $"{declared} {entry}"); + } + + // A file whose first packet declares one header packet after it, then holds a padding block, a page with no packets + // and the comment: by the declared count the headers end at the empty page, and the comment after it is not a header. + // Every walk (the packet walk, the stream header read, the SkipPictures read) must end the headers at the same page, + // so every entry point reads the same file, with or without pictures (#189). + [TestMethod] + [DynamicData (nameof (EntryRowsOfCodecs))] + public void OggFlacEmptyPageAfterTheDeclaredHeaders_EndsThemOnEveryEntryPoint (string entry) + { + var file = TestBuilders.OggFlac.CreateWithMetadata (title: "Title"); + var second = file.AsSpan (4).IndexOf ("OggS"u8) + 4; + BinaryPrimitives.WriteUInt16BigEndian (file.AsSpan (file.AsSpan ().IndexOf ("FLAC"u8) + 6), 1); + byte[] padding = [0x01, 0, 0, 4, 0, 0, 0, 0]; + byte[] bytes = [ + .. file.AsSpan (0, second), + .. OggPageHelper.BuildOggPage ([padding], OggPageFlags.None, 0, 1, 1), + .. EmptyPage (0, 2, OggPageFlags.None), + .. file.AsSpan (second), + .. Page (44_100, 4)]; + + var read = (IMediaFile)DurationUnknownTests.Open (bytes, ".oga", entry); + + Assert.IsNull (read.Tag?.Title, entry); + Assert.AreEqual (TimeSpan.FromSeconds (1), read.AudioProperties!.Duration, entry); + } + + public static IEnumerable EntryRowsOfCodecs () => DurationUnknownTests.Entries.Select (entry => new object[] { entry }); + + static readonly int[] Declared = [0, 1]; + + public static IEnumerable DeclaredRows () => + from declared in Declared + from entry in DurationUnknownTests.Entries + select new object[] { declared, entry }; + + static readonly string[] Saves = ["path", "async-path", "span", "async-span"]; + + static readonly bool[] Alone = [false, true]; + + public static IEnumerable SaveRows () => + from codec in Codecs.Keys + from save in Saves + from alone in Alone + select new object[] { codec, save, alone }; + + // The save twins of #189: the render's page walk (RenumberAudioPages) and the path save's page copy + // (CopyRenumberedPages, both its first page and the pages after) also stopped before a 27-byte page at the end, + // and dropped it. Here it ends the file half a second after the audio page, so a save that drops it shortens the + // file to 2 s; alone, it is the only page after the headers. + [TestMethod] + [DynamicData (nameof (SaveRows))] + public async Task EmptyLastPage_IsKeptBySaves (string codec, string save, bool alone) + { + var (extension, build, granule, rate) = Codecs[codec]; + var original = (byte[])[.. alone ? HeaderPages[codec] () : build (), .. EmptyPage (granule + (rate / 2), 3)]; + var files = new MockFileSystem (); + var file = SpanSaveKit.Open (extension, "path", original, files); + SpanSaveKit.Retitle (file, "Saved"); + var sync = !save.StartsWith ("async", StringComparison.Ordinal); + + var saved = save.EndsWith ("span", StringComparison.Ordinal) + ? await SpanSaveKit.SaveSpan (file, "/in" + extension, original, sync, files) + : await SpanSaveKit.SavePath (file, null, sync, files); + + Assert.IsTrue (saved.IsSuccess, saved.Error); + var written = files.ReadAllBytes ("/in" + extension); + Assert.AreEqual (0, written[written.Length - 1], "the last page has no segments"); + Assert.AreEqual (granule + (rate / 2), BinaryPrimitives.ReadUInt64LittleEndian (written.AsSpan (written.Length - 27 + 6))); + Assert.AreEqual (TimeSpan.FromSeconds (2.5), ((IMediaFile)DurationUnknownTests.Open (written, extension, "data")).AudioProperties!.Duration); + } + + // RFC 3533 §6: "A special value of -1 (in two's complement) indicates that no packets finish on this page." The + // -1 belongs to that page, not to the stream: the duration is the last granule that is not -1 (#185). ffprobe + // and mutagen step back the same way. Each row ends with -1 pages after an audio page whose granule is 2 s + // (Codecs): one small page, three pages, and a page of a full 255 segments of 255 bytes, longer than one read + // window. + static readonly Dictionary> Tails = new () { + ["one"] = sequence => Page (ulong.MaxValue, sequence, OggPageFlags.EndOfStream), + ["three"] = sequence => [.. Page (ulong.MaxValue, sequence), .. Page (ulong.MaxValue, sequence + 1), .. Page (ulong.MaxValue, sequence + 2, OggPageFlags.EndOfStream)], + ["long"] = sequence => [ + .. OggPageHelper.BuildOggPage ([new byte[255 * 255 - 1]], OggPageFlags.None, ulong.MaxValue, 1, sequence), + .. Page (ulong.MaxValue, sequence + 1, OggPageFlags.EndOfStream)], + }; + + public static IEnumerable StepBackRows () => + from codec in Codecs.Keys + from tail in Tails.Keys + from entry in DurationUnknownTests.Entries + select new object[] { codec, tail, entry }; + + [TestMethod] + [DynamicData (nameof (StepBackRows))] + public void LastPagesWithoutAGranule_TakeTheGranuleBeforeThem (string codec, string tail, string entry) + { + var (extension, build, _, _) = Codecs[codec]; + byte[] bytes = [.. build (), .. Tails[tail] (10)]; + + var file = DurationUnknownTests.Open (bytes, extension, entry); + + Assert.AreEqual (TimeSpan.FromSeconds (2), ((IMediaFile)file).AudioProperties!.Duration, $"{codec} {tail} {entry}"); + } + + // The review's eoshead-minus1.opus: -1 pages at the end and the end-of-stream flag on header page 0. With the + // flag picking the granule, full reads gave 0 and SkipPictures reads 1.9935 s; main gave 0 on all (#190). + [TestMethod] + [DynamicData (nameof (CodecRows))] + public void LastPagesWithoutAGranule_AfterAHeaderPageThatEndsTheStream (string codec, string entry) + { + var (extension, build, _, _) = Codecs[codec]; + byte[] bytes = [.. build (), .. Tails["one"] (10)]; + bytes[5] |= (byte)OggPageFlags.EndOfStream; + + var file = DurationUnknownTests.Open (bytes, extension, entry); + + Assert.AreEqual (TimeSpan.FromSeconds (2), ((IMediaFile)file).AudioProperties!.Duration, $"{codec} {entry}"); + } + + // The step back is bounded (OggWindow.StepBackBytes): a tail of junk with no "OggS", or a long run of -1 pages, + // costs the same read at 1 MB as at 64 MB, and no page is found in it. + [TestMethod] + [DataRow ("junk", 1)] + [DataRow ("junk", 64)] + [DataRow ("minus1", 1)] + [DataRow ("minus1", 64)] + public void StepBack_ReadsABoundedTail (string tail, int megabytes) + { + var size = megabytes * 1024 * 1024; + byte[] bytes = [.. TestBuilders.Ogg.CreateMinimalFile (), .. Page (88_200, 2), .. Tail (tail, size)]; + using var stream = new TagLibSharp2.Tests.Aac.AacTestBuilder.CountingStream (bytes); + + var page = OggWindow.ReadGranulePage (stream); + + Assert.HasCount (0, page); + Assert.AreEqual (0, OggWindow.GranulePage (bytes).Length); + Assert.IsLessThanOrEqualTo (3L * OggWindow.MaxPageBytes, stream.BytesRead, $"read {stream.BytesRead} of {bytes.Length}"); + } + + // Both arms of the bound, on the span and the stream: a page that starts StepBackBytes from the end is found, one + // byte further back it is not, and the duration is then the header pages' (here none). + [TestMethod] + [DataRow (0, true)] + [DataRow (1, false)] + public void StepBack_FindsAPageUpToItsBound (int pastTheBound, bool found) + { + var page = Page (88_200, 2); + byte[] bytes = [.. page, .. new byte[OggWindow.StepBackBytes - page.Length + pastTheBound]]; + using var stream = new MemoryStream (bytes, writable: false); + + var fromStream = OggWindow.ReadGranulePage (stream); + var fromSpan = OggWindow.GranulePage (bytes).ToArray (); + + CollectionAssert.AreEqual (found ? page : [], fromStream, "stream"); + CollectionAssert.AreEqual (fromStream, fromSpan, "the span read agrees"); + } + + // The scan reads one maximum page at a time from the end back, and loads the next window when it passes the start + // of the one it holds. That window ends 27 + 255 bytes past the position that loads it, so a page starting there, + // or up to 255 bytes below it, has its header and segment table in the window. Here the granule page starts + // `below` bytes under that position with below + 1 segments; a window ending 27 bytes past the position (the + // review's surviving mutant) cuts its segment table and misses it. Junk without "OggS" fills the rest. + [TestMethod] + [DataRow (0)] + [DataRow (1)] + [DataRow (254)] + public void StepBack_LoadsEachWindowWithTheSegmentTableOfAPageAtItsEdge (int below) + { + var page = OggPageHelper.BuildOggPage ([.. Enumerable.Range (0, below + 1).Select (_ => new byte[] { 1 })], OggPageFlags.None, 88_200, 1, 2); + const int Start = 100; + var bytes = Enumerable.Repeat ((byte)0x5A, Start + OggWindow.MaxPageBytes + 1 + below).ToArray (); + page.CopyTo (bytes, Start); + using var stream = new MemoryStream (bytes, writable: false); + + CollectionAssert.AreEqual (page, OggWindow.ReadGranulePage (stream), "stream"); + CollectionAssert.AreEqual (page, OggWindow.GranulePage (bytes).ToArray (), "span"); + } + + // Junk without "OggS", or -1 pages of 4,000 bytes, to size bytes. + static byte[] Tail (string kind, int size) + { + if (kind == "junk") + return Enumerable.Repeat ((byte)0x5A, size).ToArray (); + var pages = new List (size + 4_100); + for (uint sequence = 3; pages.Count < size; sequence++) + pages.AddRange (OggPageHelper.BuildOggPage ([new byte[4_000]], OggPageFlags.None, ulong.MaxValue, 1, sequence)); + return [.. pages]; + } + + // The step back finds the page the duration comes from, and only its granule is read: the pages the parse walks + // are the header pages alone. Passing the stepped-back page in as a page to walk put a copy of a header page after + // the header pages of fuzzed files main read (a comment packet over -1 pages, cut inside it), and the stream read + // failed with "Invalid field 7 length". The stream and span reads find the same page. + [TestMethod] + public void GranulePage_IsThePageBeforeTheMinus1Pages () + { + var first = Page (4_800, 0, OggPageFlags.BeginOfStream); + byte[] bytes = [.. first, .. Page (ulong.MaxValue, 1), .. Page (ulong.MaxValue, 2)]; + using var stream = new MemoryStream (bytes, writable: false); + + CollectionAssert.AreEqual (first, OggWindow.ReadGranulePage (stream), "the page with the granule"); + CollectionAssert.AreEqual (first, OggWindow.GranulePage (bytes).ToArray (), "the same page in memory"); + Assert.AreEqual (4_800UL, OggWindow.DurationGranule (bytes, 0)); + } + + // A stream that holds less than its Length says reads short at the end; the scan skips what it did not get. + [TestMethod] + public void GranulePage_OfAStreamShorterThanItsLength_IsTheLastPageItHolds () + { + var page = Page (4_800, 0, OggPageFlags.BeginOfStream); + using var stream = new LongerThanItIs (page, 1_000); + + CollectionAssert.AreEqual (page, OggWindow.ReadGranulePage (stream)); + } + + sealed class LongerThanItIs (byte[] data, int missing) : MemoryStream (data, writable: false) + { + public override long Length => base.Length + missing; + } + + // An audio packet that starts with a FLAC frame sync (RFC 9639 §9.1), so an Ogg FLAC header read stops before it. + static byte[] Page (ulong granule, uint sequence, OggPageFlags flags = OggPageFlags.None) => + OggPageHelper.BuildOggPage ([[0xFF, 0xF8, 0x69, 0x08]], flags, granule, 1, sequence); + + // A page with no segments (27 bytes), end of stream unless told otherwise, its CRC worked out over the page with the + // field zeroed. + static byte[] EmptyPage (ulong granule, uint sequence, OggPageFlags flags = OggPageFlags.EndOfStream) + { + var page = OggPageHelper.BuildOggPage ([], flags, granule, 1, sequence).AsSpan (0, 27).ToArray (); + page[26] = 0; + BinaryPrimitives.WriteUInt32LittleEndian (page.AsSpan (22), 0); + BinaryPrimitives.WriteUInt32LittleEndian (page.AsSpan (22), OggCrc.Calculate (page)); + return page; + } + + // The Ogg FLAC identification packet holds STREAMINFO after 0x7F "FLAC", the mapping version, the header count + // and "fLaC" (13 bytes) and the block header (4): total samples' low 32 bits are 14 bytes into it. The page CRC + // is not checked by these reads. + internal static byte[] OggFlacWithoutATotal (ulong granule) => [.. OggFlacNoTotal (), .. DurationUnknownTests.LastPage (granule)]; + + // The builder's minimal file ends its comment page with end of stream; here audio pages follow, so that flag + // (bit 2 of the page's flags, RFC 3533 §6) is cleared. + static byte[] OggFlacNoTotal () + { + var bytes = TestBuilders.OggFlac.CreateMinimal (); + var streamInfo = bytes.AsSpan ().IndexOf ("fLaC"u8) + 8; + BinaryPrimitives.WriteUInt32BigEndian (bytes.AsSpan (streamInfo + 14), 0); + var commentPage = bytes.AsSpan (4).IndexOf ("OggS"u8) + 4; + bytes[commentPage + 5] &= unchecked((byte)~0x04); + return bytes; + } +} diff --git a/tests/TagLibSharp2.Tests/Ogg/OggFlacFileTests.cs b/tests/TagLibSharp2.Tests/Ogg/OggFlacFileTests.cs index 98fa757b..0ba0fd53 100644 --- a/tests/TagLibSharp2.Tests/Ogg/OggFlacFileTests.cs +++ b/tests/TagLibSharp2.Tests/Ogg/OggFlacFileTests.cs @@ -394,13 +394,17 @@ public void OggFlacFile_Properties_ZeroSampleRate_ReturnsNull () Assert.IsFalse (result.File!.Properties.IsValid); } + // STREAMINFO total 0 is unknown (RFC 9639 §8.2): the duration comes from the last granule position (#184). This + // builder writes the header packet's length plus 20, 71, on its end page, a page with no segments that the + // granule scan stopped one byte short of until #189. [TestMethod] - public void OggFlacFile_Properties_ZeroTotalSamples_ReturnsNull () + public void OggFlacFile_Properties_ZeroTotalSamples_TakesTheGranule () { var data = CreateMinimalOggFlacFile (totalSamples: 0); var result = OggFlacFile.Read (data); Assert.IsTrue (result.IsSuccess); - Assert.IsFalse (result.File!.Properties.IsValid); + Assert.AreEqual (TimeSpan.FromSeconds (71 / 44_100d), result.File!.Properties.Duration); + Assert.AreEqual (44_100, result.File.Properties.SampleRate); } [TestMethod] diff --git a/tests/TagLibSharp2.Tests/Ogg/OggPageHelperTests.cs b/tests/TagLibSharp2.Tests/Ogg/OggPageHelperTests.cs index a3028ee3..c6d431f5 100644 --- a/tests/TagLibSharp2.Tests/Ogg/OggPageHelperTests.cs +++ b/tests/TagLibSharp2.Tests/Ogg/OggPageHelperTests.cs @@ -160,7 +160,7 @@ public void FindLastGranulePosition_EmptyData_ReturnsZero () { var data = Array.Empty (); - var result = OggPageHelper.FindLastGranulePosition (data); + var result = OggPageHelper.FindLastGranulePosition (data, []); Assert.AreEqual (0ul, result); } @@ -170,7 +170,7 @@ public void FindLastGranulePosition_NoValidPages_ReturnsZero () { var data = new byte[100]; // All zeros, no valid pages - var result = OggPageHelper.FindLastGranulePosition (data); + var result = OggPageHelper.FindLastGranulePosition (data, []); Assert.AreEqual (0ul, result); } @@ -181,7 +181,7 @@ public void FindLastGranulePosition_SinglePageWithGranule_ReturnsGranule () var granulePosition = 48000ul; // 1 second at 48kHz var page = CreatePageWithGranule (granulePosition, OggPageFlags.EndOfStream); - var result = OggPageHelper.FindLastGranulePosition (page); + var result = OggPageHelper.FindLastGranulePosition (page, []); Assert.AreEqual (granulePosition, result); } @@ -194,7 +194,7 @@ public void FindLastGranulePosition_MultiplePagesWithGranules_ReturnsLast () builder.Add (CreatePageWithGranule (96000ul, OggPageFlags.None, sequence: 1)); builder.Add (CreatePageWithGranule (144000ul, OggPageFlags.EndOfStream, sequence: 2)); - var result = OggPageHelper.FindLastGranulePosition (builder.ToArray ()); + var result = OggPageHelper.FindLastGranulePosition (builder.ToArray (), []); Assert.AreEqual (144000ul, result); } @@ -205,23 +205,22 @@ public void FindLastGranulePosition_GranuleIsAllOnes_ReturnsZero () // Granule position of 0xFFFFFFFFFFFFFFFF indicates "no packets complete on this page" var page = CreatePageWithGranule (0xFFFFFFFFFFFFFFFF, OggPageFlags.EndOfStream); - var result = OggPageHelper.FindLastGranulePosition (page); + var result = OggPageHelper.FindLastGranulePosition (page, []); Assert.AreEqual (0ul, result); } + // The last page's granule, whatever flags the pages carry: an end-of-stream page before it does not win (#190). [TestMethod] - public void FindLastGranulePosition_PageWithEosFlag_PrefersEosPage () + public void FindLastGranulePosition_EndOfStreamPageBeforeTheLast_TakesTheLast () { - // When there are multiple valid granules, prefer the one from EOS page using var builder = new BinaryDataBuilder (); - builder.Add (CreatePageWithGranule (999999ul, OggPageFlags.None, sequence: 0)); // Not EOS - builder.Add (CreatePageWithGranule (48000ul, OggPageFlags.EndOfStream, sequence: 1)); // EOS + builder.Add (CreatePageWithGranule (48000ul, OggPageFlags.EndOfStream, sequence: 0)); + builder.Add (CreatePageWithGranule (96000ul, OggPageFlags.None, sequence: 1)); - var result = OggPageHelper.FindLastGranulePosition (builder.ToArray ()); + var result = OggPageHelper.FindLastGranulePosition (builder.ToArray (), []); - // Should return the last valid granule (48000 from EOS page) - Assert.AreEqual (48000ul, result); + Assert.AreEqual (96000ul, result); } [TestMethod] @@ -234,7 +233,7 @@ public void FindLastGranulePosition_LargeFile_FindsLastPage () builder.AddZeros (70000); // 70KB of padding builder.Add (CreatePageWithGranule (500000ul, OggPageFlags.EndOfStream, sequence: 1)); - var result = OggPageHelper.FindLastGranulePosition (builder.ToArray ()); + var result = OggPageHelper.FindLastGranulePosition (builder.ToArray (), []); Assert.AreEqual (500000ul, result); } @@ -249,7 +248,7 @@ public void FindLastGranulePosition_PagesNotInLast64KB_StillFindsLastPage () builder.Add (CreatePageWithGranule (96000ul, OggPageFlags.EndOfStream, sequence: 1)); builder.AddZeros (80000); // 80KB of garbage/padding at the end - var result = OggPageHelper.FindLastGranulePosition (builder.ToArray ()); + var result = OggPageHelper.FindLastGranulePosition (builder.ToArray (), []); Assert.AreEqual (96000ul, result); } @@ -267,7 +266,7 @@ public void FindLastGranulePosition_TruncatedPage_ReturnsLastValidGranule () // Truncate the second page - cut off 10 bytes from the end var truncatedData = fullData[..(fullData.Length - 10)]; - var result = OggPageHelper.FindLastGranulePosition (truncatedData); + var result = OggPageHelper.FindLastGranulePosition (truncatedData, []); // Should return the granule from the first (complete) page Assert.AreEqual (48000ul, result); @@ -280,7 +279,7 @@ public void FindLastGranulePosition_CorruptedSegmentCount_HandlesGracefully () var page = CreatePageWithGranule (48000ul, OggPageFlags.EndOfStream); page[26] = 255; // Set segment count to max (255) but page only has 1 byte of data - var result = OggPageHelper.FindLastGranulePosition (page); + var result = OggPageHelper.FindLastGranulePosition (page, []); // The granule can still be read from the header (bytes 6-13) // This is graceful handling - returns what it can read @@ -323,7 +322,7 @@ public void FindLastGranulePosition_TruncatedMidPageData_ReturnsValidGranules () // Truncate to keep only 50 bytes of the 100-byte data section var truncatedData = fullData[..(page1.Length + 28 + 50)]; - var result = OggPageHelper.FindLastGranulePosition (truncatedData); + var result = OggPageHelper.FindLastGranulePosition (truncatedData, []); // Should return the granule from page 2 since header is readable // But the calculated page size (128) exceeds the remaining data @@ -331,18 +330,16 @@ public void FindLastGranulePosition_TruncatedMidPageData_ReturnsValidGranules () Assert.AreEqual (96000ul, result); } + // A last page with a lower granule than the page before it is still the last page. [TestMethod] - public void FindLastGranulePosition_OnlyEosPageGranule_IgnoresNonEosPages () + public void FindLastGranulePosition_LowerGranuleOnTheLastPage_TakesTheLast () { - // If a later page has EOS flag but lower granule, we should still prefer - // the granule from the EOS page as it represents the true end of stream using var builder = new BinaryDataBuilder (); builder.Add (CreatePageWithGranule (999999ul, OggPageFlags.BeginOfStream, sequence: 0)); builder.Add (CreatePageWithGranule (50000ul, OggPageFlags.EndOfStream, sequence: 1)); - var result = OggPageHelper.FindLastGranulePosition (builder.ToArray ()); + var result = OggPageHelper.FindLastGranulePosition (builder.ToArray (), []); - // Should return 50000 from the EOS page, not 999999 Assert.AreEqual (50000ul, result); } diff --git a/tests/TagLibSharp2.Tests/Ogg/OggSaveStreamsAudioTests.cs b/tests/TagLibSharp2.Tests/Ogg/OggSaveStreamsAudioTests.cs index 4170945a..d98fba0f 100644 --- a/tests/TagLibSharp2.Tests/Ogg/OggSaveStreamsAudioTests.cs +++ b/tests/TagLibSharp2.Tests/Ogg/OggSaveStreamsAudioTests.cs @@ -109,7 +109,9 @@ public void CopyRenumberedPages_DoesNotSeek () OggPageHelper.CopyRenumberedPages (counting, dest, serialNumber: 0x01020304, startSequence: 7); - var expected = OggPageHelper.RenumberAudioPages (file, 0x01020304, 7); + // The pages renumbered, then the bytes after the last whole page as they were (#215), as a save from bytes + // writes them. + var expected = OggPageHelper.CarryAudioPages (file, 0, 0x01020304, 7)!; AssertSameBytes (expected, dest.ToArray ()); Assert.AreEqual (0, counting.PositionSets, "page copy rewound the stream"); } @@ -123,7 +125,9 @@ public void CopyRenumberedPages_DoesNotStatEachPage () OggPageHelper.CopyRenumberedPages (counting, dest, serialNumber: 0x01020304, startSequence: 7); - var expected = OggPageHelper.RenumberAudioPages (file, 0x01020304, 7); + // The pages renumbered, then the bytes after the last whole page as they were (#215), as a save from bytes + // writes them. + var expected = OggPageHelper.CarryAudioPages (file, 0, 0x01020304, 7)!; AssertSameBytes (expected, dest.ToArray ()); // FileStream.Length is an fstat on Unix. Once per page dominated the copy. Assert.AreEqual (1, counting.LengthGets, "page copy asked for the stream length"); diff --git a/tests/TagLibSharp2.Tests/PublicApi/Snapshots/TagLibSharp2.PublicApi.verified.txt b/tests/TagLibSharp2.Tests/PublicApi/Snapshots/TagLibSharp2.PublicApi.verified.txt index cb3f554a..955ef0ad 100644 --- a/tests/TagLibSharp2.Tests/PublicApi/Snapshots/TagLibSharp2.PublicApi.verified.txt +++ b/tests/TagLibSharp2.Tests/PublicApi/Snapshots/TagLibSharp2.PublicApi.verified.txt @@ -540,6 +540,7 @@ namespace TagLibSharp2.Asf public TagLibSharp2.Asf.AsfGuid FileId { get; } public ulong FileSize { get; } public uint Flags { get; } + public bool IsBroadcast { get; } public bool IsSeekable { get; } public uint MaxBitrate { get; } public uint MaxPacketSize { get; } diff --git a/tests/TagLibSharp2.Tests/Riff/RiffWalkAgreementTests.cs b/tests/TagLibSharp2.Tests/Riff/RiffWalkAgreementTests.cs new file mode 100644 index 00000000..15444c9e --- /dev/null +++ b/tests/TagLibSharp2.Tests/Riff/RiffWalkAgreementTests.cs @@ -0,0 +1,165 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Buffers.Binary; +using TagLibSharp2.Core; +using TagLibSharp2.Riff; +using TagLibSharp2.Tests.Core; +using TagLibSharp2.Tests.Kit; + +namespace TagLibSharp2.Tests.Riff; + +/// +/// A read of a WAV file from memory and a read from a stream walk the same RIFF chunks by the same rule (#192): a chunk +/// holds the bytes present up to the end of the form, whatever size it declares. Every chunk kind (fmt, data, a LIST +/// INFO, one no reader knows), last in the form or not, is given a size below its bytes, past them, past +/// or the 0xFFFFFFFF of a streamed writer, with and without bytes after the form, in a form +/// of its true size, the placeholder, 0, 4, half its size or larger than the file: the ten entry points must read the +/// same file, and a save after a read from memory and after a stream read must write the same bytes. +/// +[TestClass] +[TestCategory ("Unit")] +[TestCategory ("Riff")] +public sealed class RiffWalkAgreementTests +{ + static readonly string[] Chunks = ["fmt ", "data", "LIST", "junk"]; + + // The declared size: one byte below the chunk's true size, past its bytes by one and by a thousand, then past + // int.MaxValue. + static readonly string[] Sizes = ["below", "+1", "+1000", "0x7FFFFFFF", "0x80000000", "0xFFFFFFFF"]; + + // The RIFF size: the form's true length, the placeholder a streamed writer leaves, 0, 4 (the form type alone), half + // the form, and a thousand bytes past the file. + static readonly string[] Forms = ["exact", "placeholder", "0", "4", "half", "larger"]; + + static readonly bool[] Booleans = [false, true]; + + public static IEnumerable Rows () => + from chunk in Chunks + from last in Booleans + from size in Sizes + from trailing in Booleans + from form in Forms + select new object[] { chunk, last, size, trailing, form }; + + [TestMethod] + [DynamicData (nameof (Rows))] + public void OversizedChunk_ReadsTheSameOnEveryEntryPoint (string chunk, bool last, string size, bool trailing, string form) + { + var bytes = Wave (chunk, last, size, trailing, form); + + var reads = EntryAgreement.ReadEverywhere (bytes, Name, FormatSpan, FormatPath); + + EntryAgreement.AssertAgree (reads, "read"); + } + + // A save after a read from memory (WavFile.ReadFromFile reads the bytes) and after a stream read (MediaFile.Read of + // a path) writes the same file, or both end the same way. + [TestMethod] + [DynamicData (nameof (Rows))] + public void OversizedChunk_SavesTheSameFromEveryRead (string chunk, bool last, string size, bool trailing, string form) + { + var bytes = Wave (chunk, last, size, trailing, form); + + var fromMemory = Save (bytes, files => WavFile.ReadFromFile (Name, files).File); + var fromStream = Save (bytes, files => MediaFile.Read (Name, files).File as WavFile); + + Assert.AreEqual (fromMemory, fromStream); + } + + // The rule itself, not only agreement: bytes after the form are not samples (a data size of 0xFFFFFFFF, last, with + // 128 bytes after the form reads 1 s, its 8,000 bytes), and a chunk past the form's end is not read (a RIFF size that + // ends before the LIST leaves no title). + [TestMethod] + public void FormEnd_BoundsTheChunks () + { + var trailing = Wave ("data", last: true, "0xFFFFFFFF", trailing: true, "exact"); + var listOutside = Wave ("LIST", last: true, "+1", trailing: false, "exact"); + BinaryPrimitives.WriteUInt32LittleEndian (listOutside.AsSpan (4), (uint)(listOutside.Length - 8 - 8 - 22)); + + foreach (var read in EntryAgreement.ReadEverywhere (trailing, Name, FormatSpan, FormatPath)) + Assert.EndsWith (": 10000000/8000/1/Title", read); + foreach (var read in EntryAgreement.ReadEverywhere (listOutside, Name, FormatSpan, FormatPath)) + Assert.EndsWith (": 10000000/8000/1/", read); + } + + const string Name = "/clip.wav"; + + static IMediaFile? FormatSpan (byte[] bytes) => WavFile.Read (bytes).File; + + static IMediaFile? FormatPath (string path, MockFileSystem files) => WavFile.ReadFromFile (path, files).File; + + // The outcome of retitling the file a read gives and saving it over its source: the bytes written, or how it ended. + static string Save (byte[] bytes, Func read) + { + var files = new MockFileSystem (); + files.AddFile (Name, bytes); + try { + if (read (files) is not { } wav) + return "unreadable"; + wav.InfoTag = new RiffInfoTag { Title = "Saved" }; + var saved = wav.SaveToFile (Name, files); + return saved.IsSuccess ? Convert.ToHexString (files.ReadAllBytes (Name)) : "failed"; + } catch (Exception ex) when (ex is not AssertFailedException) { + return "threw " + ex.GetType ().Name; + } + } + + // fmt (8 kHz mono 8-bit, 8,000 bytes a second), data (8,000 bytes), LIST INFO with a title, and a chunk no reader + // knows. The chunk under test goes last or stays in the middle; then its size and the form's size are set. + internal static byte[] Wave (string target, bool last, string size, bool trailing, string form) + { + var order = new List { "fmt ", "data", "LIST", "junk" }; + order.Remove (target); + if (last) + order.Add (target); + else + order.Insert (1, target); + + using var body = new MemoryStream (); + body.Write ("WAVE"u8); + var sizeAt = -1; + var trueSize = 0; + foreach (var id in order) { + var payload = Payload (id); + if (id == target) { + sizeAt = (int)body.Position + 4; + trueSize = payload.Length; + } + + body.Write (System.Text.Encoding.ASCII.GetBytes (id)); + body.Write (BitConverter.GetBytes ((uint)payload.Length)); + body.Write (payload); + if ((payload.Length & 1) != 0) + body.WriteByte (0); + } + + var formBytes = body.ToArray (); + var declared = size switch { + "below" => (uint)(trueSize - 1), + "+1" => (uint)(trueSize + 1), + "+1000" => (uint)(trueSize + 1000), + _ => Convert.ToUInt32 (size, 16), + }; + BinaryPrimitives.WriteUInt32LittleEndian (formBytes.AsSpan (sizeAt), declared); + + byte[] riff = [.. "RIFF"u8, .. new byte[4], .. formBytes, .. trailing ? Enumerable.Repeat ((byte)0x33, 128) : []]; + var formSize = form switch { + "placeholder" => uint.MaxValue, + "0" => 0u, + "4" => 4u, + "half" => (uint)(formBytes.Length / 2), + "larger" => (uint)(formBytes.Length + 1000), + _ => (uint)formBytes.Length, + }; + BinaryPrimitives.WriteUInt32LittleEndian (riff.AsSpan (4), formSize); + return riff; + } + + static byte[] Payload (string id) => id switch { + "fmt " => [1, 0, 1, 0, 0x40, 0x1F, 0, 0, 0x40, 0x1F, 0, 0, 1, 0, 8, 0], + "data" => [.. Enumerable.Range (0, 8000).Select (i => (byte)(i * 7))], + "LIST" => [.. "INFO"u8, .. "INAM"u8, 6, 0, 0, 0, .. "Title\0"u8], + _ => [.. Enumerable.Repeat ((byte)0x5A, 10)], + }; +} diff --git a/tests/TagLibSharp2.Tests/Riff/WavFileSavePreservationTests.cs b/tests/TagLibSharp2.Tests/Riff/WavFileSavePreservationTests.cs index 67783c27..d8e70a5e 100644 --- a/tests/TagLibSharp2.Tests/Riff/WavFileSavePreservationTests.cs +++ b/tests/TagLibSharp2.Tests/Riff/WavFileSavePreservationTests.cs @@ -16,41 +16,75 @@ public class WavFileSavePreservationTests const int LoudnessOffset = 412; const int LoudnessSize = 10; + // A data chunk of size 0xFFFFFFFF, as a streamed writer leaves it, holds the samples to the end of the file. The read + // of bytes in memory used to drop the chunk at a size past int.MaxValue, and these saves were refused so as not to + // write a file without its samples; the chunk is now kept, as a stream read keeps it, and a save writes the samples + // present with their size (#192). [TestMethod] - public void SaveToFile_DataChunkSizeSentinel_LeavesOriginalBytes () + public void SaveToFile_DataChunkSizeSentinel_KeepsTheSamples () { - var original = CreateWaveWithDataChunkSize (0xFFFFFFFF); - AssertSaveLeavesBytes (original, (file, fs) => file.SaveToFile ("/clip.wav", fs)); + var fs = new MockFileSystem (); + fs.AddFile ("/clip.wav", CreateWaveWithDataChunkSize (0xFFFFFFFF)); + var read = WavFile.ReadFromFile ("/clip.wav", fs); + Assert.IsTrue (read.IsSuccess, read.Error); + read.File!.InfoTag = new RiffInfoTag { Title = "Retitled" }; + + var save = read.File.SaveToFile ("/clip.wav", fs); + + Assert.IsTrue (save.IsSuccess, save.Error); + AssertKeepsTheSamples (fs.ReadAllBytes ("/clip.wav")); } [TestMethod] - public async Task SaveToFileAsync_DataChunkSizeSentinel_LeavesOriginalBytes () + public async Task SaveToFileAsync_DataChunkSizeSentinel_KeepsTheSamples () { - var original = CreateWaveWithDataChunkSize (0xFFFFFFFF); var fs = new MockFileSystem (); - fs.AddFile ("/clip.wav", original); - + fs.AddFile ("/clip.wav", CreateWaveWithDataChunkSize (0xFFFFFFFF)); var read = WavFile.ReadFromFile ("/clip.wav", fs); Assert.IsTrue (read.IsSuccess, read.Error); read.File!.InfoTag = new RiffInfoTag { Title = "Retitled" }; var save = await read.File.SaveToFileAsync ("/clip.wav", fs); - AssertMissingDataSaveFailed (original, fs.ReadAllBytes ("/clip.wav"), save); + + Assert.IsTrue (save.IsSuccess, save.Error); + AssertKeepsTheSamples (fs.ReadAllBytes ("/clip.wav")); } [TestMethod] - public async Task SaveToFileAsync_BackToSource_DataChunkSizeSentinel_LeavesOriginalBytes () + public async Task SaveToFileAsync_BackToSource_DataChunkSizeSentinel_KeepsTheSamples () { - var original = CreateWaveWithDataChunkSize (0xFFFFFFFF); var fs = new MockFileSystem (); - fs.AddFile ("/clip.wav", original); - + fs.AddFile ("/clip.wav", CreateWaveWithDataChunkSize (0xFFFFFFFF)); var read = WavFile.ReadFromFile ("/clip.wav", fs); Assert.IsTrue (read.IsSuccess, read.Error); read.File!.InfoTag = new RiffInfoTag { Title = "Retitled" }; var save = await read.File.SaveToFileAsync (fs); - AssertMissingDataSaveFailed (original, fs.ReadAllBytes ("/clip.wav"), save); + + Assert.IsTrue (save.IsSuccess, save.Error); + AssertKeepsTheSamples (fs.ReadAllBytes ("/clip.wav")); + } + + [TestMethod] + public void Render_DataChunkSizeSentinel_KeepsTheSamples () + { + var read = WavFile.Read (CreateWaveWithDataChunkSize (0xFFFFFFFF)); + Assert.IsTrue (read.IsSuccess, read.Error); + Assert.IsNull (read.File!.InfoTag); + read.File.InfoTag = new RiffInfoTag { Title = "Retitled" }; + + AssertKeepsTheSamples (read.File.Render ().ToArray ()); + } + + // The four sample bytes of CreateWaveWithDataChunkSize, in a data chunk of their size, and the new title. + static void AssertKeepsTheSamples (byte[] saved) + { + Assert.IsTrue (RiffFile.TryParse (new BinaryData (saved), out var riff)); + var data = riff.GetChunk ("data"); + Assert.IsTrue (data.HasValue, "the data chunk was dropped"); + Assert.AreEqual (4u, data.Value.DataSize); + CollectionAssert.AreEqual (new byte[] { 0x11, 0x22, 0x33, 0x44 }, data.Value.Data.ToArray ()); + Assert.AreEqual ("Retitled", WavFile.Read (saved).File?.InfoTag?.Title); } [TestMethod] @@ -74,16 +108,6 @@ public async Task SaveToFileAsync_ContainerSizeEndsBeforeData_LeavesTrailingByte AssertMissingDataSaveFailed (original, fs.ReadAllBytes ("/clip.wav"), save); } - [TestMethod] - public void Render_DataChunkSizeSentinel_DoesNotReturnTruncatedWave () - { - var read = WavFile.Read (CreateWaveWithDataChunkSize (0xFFFFFFFF)); - Assert.IsTrue (read.IsSuccess, read.Error); - Assert.IsNull (read.File!.InfoTag); - - Assert.ThrowsExactly (() => read.File.Render ()); - } - [TestMethod] public void SaveToFile_ShortBextAndOpaqueId3_SurviveTitleSave () { diff --git a/tests/TagLibSharp2.Tests/Riff/WavSaveStreamsAudioTests.cs b/tests/TagLibSharp2.Tests/Riff/WavSaveStreamsAudioTests.cs index f951f5d1..4befe81d 100644 --- a/tests/TagLibSharp2.Tests/Riff/WavSaveStreamsAudioTests.cs +++ b/tests/TagLibSharp2.Tests/Riff/WavSaveStreamsAudioTests.cs @@ -154,7 +154,8 @@ static void AssertSaved ( long allocated) { Assert.IsTrue (save.IsSuccess, save.Error); - Assert.AreEqual (1, fs.SourceLengthGets, "source length reads"); + // Open records the length once. The save then reads the source back to see whether it wrote over it (#212). + Assert.AreEqual (2, fs.SourceLengthGets, "source length reads"); Assert.IsTrue ( allocated < original.Length / 2, $"save allocated {allocated} bytes for a {original.Length} byte file"); diff --git a/tests/TagLibSharp2.Tests/Riff/WavUnknownDataSizeTests.cs b/tests/TagLibSharp2.Tests/Riff/WavUnknownDataSizeTests.cs new file mode 100644 index 00000000..ac44e4ca --- /dev/null +++ b/tests/TagLibSharp2.Tests/Riff/WavUnknownDataSizeTests.cs @@ -0,0 +1,85 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using TagLibSharp2.Core; +using TagLibSharp2.Riff; +using TagLibSharp2.Tests.Core; + +namespace TagLibSharp2.Tests.Riff; + +/// +/// A WAV file written to a pipe has a data chunk of size 0xFFFFFFFF, its sound running to the end of the file: +/// ffmpeg writes it so, and ffprobe reads the duration of the samples present (#192). Every entry point reads that +/// duration and keeps those samples. On 28960fe7 a read of bytes in memory stopped at a chunk size past +/// and lost the data chunk, while a stream read kept it. +/// +[TestClass] +[TestCategory ("Unit")] +[TestCategory ("Riff")] +public sealed class WavUnknownDataSizeTests +{ + // 8 kHz mono 8-bit: 8,000 bytes a second. + const int SampleBytes = 16_000; + + internal static byte[] Piped (uint dataSize = uint.MaxValue, int sampleBytes = SampleBytes) + { + using var file = new BinaryDataBuilder (44 + sampleBytes); + file.AddStringLatin1 ("RIFF"); + file.AddUInt32LE (uint.MaxValue); + file.AddStringLatin1 ("WAVE"); + file.AddStringLatin1 ("fmt "); + file.AddUInt32LE (16); + file.AddUInt16LE (1); + file.AddUInt16LE (1); + file.AddUInt32LE (8000); + file.AddUInt32LE (8000); + file.AddUInt16LE (1); + file.AddUInt16LE (8); + file.AddStringLatin1 ("data"); + file.AddUInt32LE (dataSize); + for (var i = 0; i < sampleBytes; i++) + file.Add ((byte)(i * 7)); + return file.ToBinaryData ().ToArray (); + } + + public static IEnumerable Rows () => + from size in new[] { uint.MaxValue, 0x8000_0000u } + from entry in DurationUnknownTests.Entries + select new object[] { size, entry }; + + [TestMethod] + [DynamicData (nameof (Rows))] + public void Duration_IsTheSamplesPresent (uint dataSize, string entry) + { + var file = (WavFile)DurationUnknownTests.Open (Piped (dataSize), ".wav", entry); + + Assert.AreEqual (TimeSpan.FromSeconds (2), file.Properties.Duration, entry); + } + + // A save keeps the samples, whichever read: the data chunk is written with the size of the samples present. + [TestMethod] + [DataRow ("format-path")] + [DataRow ("path")] + [DataRow ("async-path")] + public void Save_KeepsTheSamples (string read) + { + var files = new MockFileSystem (); + var original = Piped (); + files.AddFile ("/in.wav", original); + var file = read switch { + "format-path" => WavFile.ReadFromFile ("/in.wav", files).File!, + "path" => (WavFile)MediaFile.Read ("/in.wav", files).File!, + _ => (WavFile)MediaFile.ReadAsync ("/in.wav", files).GetAwaiter ().GetResult ().File!, + }; + file.InfoTag = new RiffInfoTag { Title = "Retitled" }; + + var saved = file.SaveToFile ("/in.wav", files); + + Assert.IsTrue (saved.IsSuccess, saved.Error); + Assert.IsTrue (RiffFile.TryParse (new BinaryData (files.ReadAllBytes ("/in.wav")), out var riff)); + var data = riff.GetChunk (WavFile.DataChunkId)!.Value; + Assert.AreEqual ((uint)SampleBytes, data.DataSize); + CollectionAssert.AreEqual (original.AsSpan (44).ToArray (), data.Data.ToArray ()); + Assert.AreEqual ("Retitled", WavFile.Read (files.ReadAllBytes ("/in.wav")).File!.InfoTag!.Title); + } +} diff --git a/tests/TagLibSharp2.Tests/TestBuilders.cs b/tests/TagLibSharp2.Tests/TestBuilders.cs index 89eb9387..b363d029 100644 --- a/tests/TagLibSharp2.Tests/TestBuilders.cs +++ b/tests/TagLibSharp2.Tests/TestBuilders.cs @@ -412,6 +412,15 @@ public static class Flac static readonly byte[] ZeroFrameSizes = [0x00, 0x00, 0x00, 0x00, 0x00, 0x00]; static readonly byte[] Default44100StreamInfo = [0x0A, 0xC4, 0x42, 0xF0, 0x00, 0x00, 0x00, 0x00]; + /// + /// + /// bytes of audio as a FLAC file holds them after its metadata: a frame sync code + /// (RFC 9639 §9.1: 0xFF, 0xF8), then the kit's sound pattern. A save keeps such audio; it fails when the bytes after + /// the metadata are not a frame (#204). + /// + public static byte[] Frames (int length) => + length <= 0 ? [] : length == 1 ? [0xFF] : [0xFF, 0xF8, .. Core.SpanSaveKit.Sound (length - 2)]; + /// /// Creates a minimal valid FLAC file with STREAMINFO. /// Default properties: 44100Hz, 2 channels, 16-bit, 0 samples. @@ -1910,7 +1919,9 @@ public static byte[] CreateMinimal ( // FORM header builder.Add (TestConstants.Magic.Form); - builder.AddUInt32BE ((uint)(30 + soundBytes)); // File size - 8 (placeholder) + // The form: "AIFF" (4), COMM (8 + 18) and SSND (8 + 8 + the sound). It was 16 short, which the stream read + // honoured and the read from memory ignored until both took the FORM's end (#197). + builder.AddUInt32BE ((uint)(4 + 8 + TestConstants.Aiff.CommChunkSize + 8 + 8 + soundBytes)); builder.Add (TestConstants.Magic.Aiff); // COMM chunk diff --git a/tests/TagLibSharp2.Tests/WavPack/WavPackBlockSizeTests.cs b/tests/TagLibSharp2.Tests/WavPack/WavPackBlockSizeTests.cs new file mode 100644 index 00000000..96df2ce8 --- /dev/null +++ b/tests/TagLibSharp2.Tests/WavPack/WavPackBlockSizeTests.cs @@ -0,0 +1,115 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Buffers.Binary; +using TagLibSharp2.Core; +using TagLibSharp2.Tests.Core; + +namespace TagLibSharp2.Tests.WavPack; + +/// +/// #201: a WavPack file whose first block declares a size too small to hold the 32-byte block header (0, 1, 23: the +/// size counts the block after its first 8 bytes). A stream or path read took the 8 bytes it named and the APE tag after +/// them for the block header, and read 2 days 20 hours at 6,000 Hz; a read of the bytes read the header as a block. +/// Such a size is no block: every entry point reads the file's properties as unknown and its tag as it is, and a save +/// keeps the audio whole or fails and writes nothing. +/// +[TestClass] +[TestCategory ("Unit")] +public sealed class WavPackBlockSizeTests +{ + const int Audio = 1024; + + static readonly uint[] Sizes = [0, 1, 23]; + + static readonly string[] Reads = ["stream", "path", "data", "async-path", "format-path"]; + + static readonly string[] Saves = ["sync-path", "async-path", "span-sync", "span-async", "sync-in-place", "async-in-place"]; + + public static IEnumerable ReadRows () => + from size in Sizes + from read in Reads + select new object[] { size, read }; + + [TestMethod] + [DynamicData (nameof (ReadRows))] + public void BlockSizeTooSmallForTheHeader_ReadsNoProperties (uint size, string read) + { + var file = SpanSaveKit.Open (".wv", read, Build (size), new MockFileSystem ()); + + Assert.AreEqual (TimeSpan.Zero, file.AudioProperties?.Duration ?? TimeSpan.Zero, read); + Assert.AreEqual (0, file.AudioProperties?.SampleRate ?? 0, read); + Assert.AreEqual ("Title", file.Tag?.Title, read); + } + + // Without a tag after the block, a stream read held only the 8 bytes the size named and failed, where a read of the + // bytes read the header as a block. Both now read the file with no properties. + [TestMethod] + [DynamicData (nameof (ReadRows))] + public void BlockSizeTooSmallForTheHeader_NoTag_ReadsNoProperties (uint size, string read) + { + var file = SpanSaveKit.Open (".wv", read, Build (size, tag: false), new MockFileSystem ()); + + Assert.AreEqual (TimeSpan.Zero, file.AudioProperties?.Duration ?? TimeSpan.Zero, read); + Assert.AreEqual (0, file.AudioProperties?.SampleRate ?? 0, read); + } + + // The same file with a block size that holds its header, just (24) or with the audio, reads its properties, on every + // entry point. + public static IEnumerable ValidRows () => + from size in new uint[] { 24, 24 + Audio } + from read in Reads + select new object[] { size, read }; + + [TestMethod] + [DynamicData (nameof (ValidRows))] + public void BlockSizeThatHoldsTheHeader_ReadsTheProperties (uint size, string read) + { + var file = SpanSaveKit.Open (".wv", read, Build (size), new MockFileSystem ()); + + Assert.AreEqual (44_100, file.AudioProperties!.SampleRate, read); + Assert.AreNotEqual (TimeSpan.Zero, file.AudioProperties.Duration, read); + } + + public static IEnumerable SaveRows () => + from size in Sizes + from save in Saves + select new object[] { size, save }; + + [TestMethod] + [DynamicData (nameof (SaveRows))] + public async Task BlockSizeTooSmallForTheHeader_SaveKeepsTheAudio (uint size, string save) + { + var bytes = Build (size); + var files = new MockFileSystem (); + var read = save.StartsWith ("span", StringComparison.Ordinal) ? "data" : "path"; + var file = SpanSaveKit.Open (".wv", read, bytes, files); + file.Tag!.Title = "New"; + + var result = save switch { + "sync-path" => await SpanSaveKit.SavePath (file, "/out.wv", sync: true, files), + "async-path" => await SpanSaveKit.SavePath (file, "/out.wv", sync: false, files), + "span-sync" => await SpanSaveKit.SaveSpan (file, "/in.wv", bytes, sync: true, files), + "span-async" => await SpanSaveKit.SaveSpan (file, "/in.wv", bytes, sync: false, files), + "sync-in-place" => await SpanSaveKit.SavePath (file, null, sync: true, files), + _ => await SpanSaveKit.SavePath (file, null, sync: false, files), + }; + + Assert.IsTrue (result.IsSuccess, result.Error); + var written = files.ReadAllBytes (save.EndsWith ("path", StringComparison.Ordinal) ? "/out.wv" : "/in.wv"); + Assert.IsGreaterThanOrEqualTo (0, written.AsSpan ().IndexOf (bytes.AsSpan (0, 32 + Audio)), "the block and the audio, whole"); + var back = MediaFile.ReadFromData (written, "/back.wv"); + Assert.IsTrue (back.IsSuccess, back.Error); + Assert.AreEqual ("New", ((IMediaFile)back.File!).Tag?.Title); + } + + // A version 4 block header (44.1 kHz, 16 bits, stereo, 44,100 samples) declaring blockSize, then the audio, then the + // builder's APE tag with the title "Title" when asked. + static byte[] Build (uint blockSize, bool tag = true) + { + var built = TestBuilders.WavPack.CreateWithMetadata (title: "Title"); + var header = built.AsSpan (0, 32).ToArray (); + BinaryPrimitives.WriteUInt32LittleEndian (header.AsSpan (4), blockSize); + return [.. header, .. SpanSaveKit.Sound (Audio), .. (tag ? built.AsSpan (32) : [])]; + } +} diff --git a/tests/TagLibSharp2.Tests/Xiph/FlacBlockLengthSaveTests.cs b/tests/TagLibSharp2.Tests/Xiph/FlacBlockLengthSaveTests.cs new file mode 100644 index 00000000..ffcd86fc --- /dev/null +++ b/tests/TagLibSharp2.Tests/Xiph/FlacBlockLengthSaveTests.cs @@ -0,0 +1,268 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using TagLibSharp2.Core; +using TagLibSharp2.Tests.Core; +using TagLibSharp2.Xiph; + +namespace TagLibSharp2.Tests.Xiph; + +/// +/// #204: a FLAC save writes the first STREAMINFO, SEEKTABLE, APPLICATION and the reserved block types as they are, the +/// comment, pictures and cue sheet from what it parsed of them, and fresh padding, then copies every byte after the +/// last block it read. A block whose bytes that does not write back was lost: a VORBIS_COMMENT length grown from 35 to +/// 255 took in the first 220 bytes of the audio, past its last comment, and the save dropped them. Such a save fails +/// and writes nothing, on every save. Padding is refused only when it holds a byte that is not zero and does not end +/// where a block header, a frame or the end of the file begins: its length grew into what follows it. Nothing else is +/// refused: stray bytes in padding (a save writes fresh padding in its place), a block that runs past the end of the +/// file, a file whose blocks are not flagged last, bytes after the metadata that do not start with a frame, and a +/// preserved block grown into the audio keep every byte, as main kept them (review 6's 446 files), and a block that +/// runs past the end of the file keeps its header, which the save dropped. +/// +[TestClass] +[TestCategory ("Unit")] +public sealed class FlacBlockLengthSaveTests +{ + const int Audio = 1024; + + static readonly string[] Saves = ["sync-path", "async-path", "span-sync", "span-async", "sync-in-place", "async-in-place"]; + + // Each shape: a comment, and a block after it, the last one flagged, with one declared length changed, so the save + // would drop bytes the block holds. + static readonly Dictionary> Lost = new () { + // The comment's length grown into the audio: 1 byte, and 220 (35 to 255, review 6's byte 45). + ["comment-into-audio-1"] = () => Build (Comment (), extra: 1), + ["comment-into-audio-220"] = () => Build (Comment (), extra: 220), + // Cut short: the comment no longer parses. + ["comment-short"] = () => Build (Comment (), extra: -4), + // Grown into the next block: the comment holds the picture's header past its last comment. + ["comment-into-next-block"] = () => Build (Comment (), extra: 4, next: Picture ()), + // A picture grown into the audio. + ["picture-into-audio"] = () => Build (Comment (), extra: 0, next: Picture (), nextExtra: 8), + // Padding grown into the audio: it took in the first frame's first 8 bytes, and a frame does not follow it. + ["padding-into-audio"] = () => Build (Comment (), extra: 0, next: Padding (), nextExtra: 8), + // Padding grown into the next block: it took in that block's header, and what follows it is no block header. + ["padding-into-next-block"] = () => Build (Padding (), extra: 4, next: Application ()), + // Padding with stray bytes, not flagged last, then 3 bytes: no block header, and every read finds the same 3 bytes + // (a stream read does not buffer a header it cannot read whole). + ["padding-not-zeros-then-cut-header"] = () => Build (Comment (), extra: 0, next: StrayPadding (), lastFlag: false, audio: 3), + // Padding with stray bytes, then the header of a block of type 127, which RFC 9639 §8.1 forbids. + ["padding-not-zeros-then-type-127"] = () => Build (StrayPadding (), extra: 0, next: (127, [1, 2, 3, 4])), + // A second comment, and a second STREAMINFO: the save writes one of each. + ["second-comment"] = () => Build (Comment (), extra: 0, next: Comment ()), + ["second-streaminfo"] = () => Build (Comment (), extra: 0, next: (0, TestBuilders.Flac.CreateMinimal ().AsSpan (8, 34).ToArray ())), + // A cue sheet that does not parse: the save writes no cue sheet. + ["cuesheet-unparsable"] = () => Build (Comment (), extra: 0, next: (5, [.. "not a cue sheet"u8])), + }; + + public static IEnumerable LostRows () => + from shape in Lost.Keys + from save in Saves + select new object[] { shape, save }; + + [TestMethod] + [DynamicData (nameof (LostRows))] + public async Task BlockWhoseBytesTheSaveWouldNotWriteBack_SaveFailsAndWritesNothing (string shape, string save) + { + var bytes = Lost[shape] (); + var files = new MockFileSystem (); + var file = Open (bytes, save, files); + + var result = await Save (file, bytes, save, files); + + Assert.IsFalse (result.IsSuccess, shape + " " + save); + Assert.AreEqual ("Cannot save a FLAC file with a metadata block whose bytes the save would not write back.", result.Error); + CollectionAssert.AreEqual (bytes, files.ReadAllBytes ("/in.flac"), "the source"); + Assert.IsFalse (files.FileExists ("/out.flac")); + } + + // A read of the bytes, a stream read and a SkipPictures stream read refuse alike, with the pictures cleared: the + // SkipPictures walk reads a picture's fields before its data to tell a picture block that holds more than the + // picture, and clearing the pictures does not make the bytes such a block took in the picture's. + static readonly string[] Reads = ["data", "stream", "skip-stream"]; + + public static IEnumerable LostReads () => + from shape in Lost.Keys + from read in Reads + select new object[] { shape, read }; + + [TestMethod] + [DynamicData (nameof (LostReads))] + public void BlockWhoseBytesTheSaveWouldNotWriteBack_RendersNothing (string shape, string read) + { + var bytes = Lost[shape] (); + var file = ReadBy (read, bytes); + file.RemoveAllPictures (); + + Assert.IsTrue (file.Render (bytes).IsEmpty); + } + + static FlacFile ReadBy (string read, byte[] bytes) => read switch { + "data" => FlacFile.Read (bytes).File!, + "stream" => (FlacFile)MediaFile.Read (new MemoryStream (bytes, writable: false), "/in.flac").File!, + _ => (FlacFile)MediaFile.Read (new MemoryStream (bytes, writable: false), new MediaReadOptions { SkipPictures = true }, "/in.flac").File!, + }; + + // Every length right, with and without audio, with a picture, padding, a seek table and a block of a reserved type + // (RFC 9639 §8.1: 7 to 126, written back as they are, like SEEKTABLE and APPLICATION; a save dropped them), and the + // damaged shapes that lose nothing: a seek table or an APPLICATION block grown into the audio (written back with the + // bytes it took in), a block that runs past the end of the file (review 6's faulty/11 shape), no block flagged last + // (the walk reads the frame header as a block that runs past the end), and audio that does not start with a frame. + // Padding is padding whatever bytes it holds when a block header, a frame or the end of the file follows it, so + // padding with bytes that are not zeros saves with fresh padding in its place: before a block, before a frame of + // either blocking strategy, and at the end of a file with no audio. + static readonly Dictionary> Kept = new () { + ["comment"] = () => Build (Comment (), extra: 0), + ["comment-no-audio"] = () => Build (Comment (), extra: 0, audio: 0), + // A variable-blocksize stream: its frames' sync code ends in 1 (0xFF, 0xF9). + ["comment-variable-blocksize"] = () => Build (Comment (), extra: 0, variable: true), + ["comment-picture"] = () => Build (Comment (), extra: 0, next: Picture ()), + ["padding"] = () => Build (Comment (), extra: 0, next: Padding ()), + // Zeros hold nothing, so what follows padding of zeros is not checked: here, audio that does not start with a frame. + ["padding-then-audio-not-a-frame"] = () => Build (Comment (), extra: 0, next: Padding (), noFrame: true), + ["padding-not-zeros"] = () => Build (Comment (), extra: 0, next: StrayPadding ()), + ["padding-not-zeros-then-block"] = () => Build (StrayPadding (), extra: 0, next: Comment ()), + ["padding-not-zeros-variable-blocksize"] = () => Build (Comment (), extra: 0, next: StrayPadding (), variable: true), + ["padding-not-zeros-no-audio"] = () => Build (Comment (), extra: 0, next: StrayPadding (), audio: 0), + // After a picture, which a SkipPictures read leaves out of what it buffers: the frame after the padding is still + // found where it is in the file. + ["picture-then-padding-not-zeros"] = () => Build (Picture (), extra: 0, next: StrayPadding ()), + ["seektable"] = () => Build (Comment (), extra: 0, next: SeekTable ()), + ["reserved-7"] = () => Build (Comment (), extra: 0, next: Reserved (7)), + ["reserved-126"] = () => Build (Comment (), extra: 0, next: Reserved (126)), + ["seektable-into-audio"] = () => Build (Comment (), extra: 0, next: SeekTable (), nextExtra: 8), + ["application-into-audio"] = () => Build (Comment (), extra: 0, next: Application (), nextExtra: 8), + ["block-past-the-end"] = () => Build (Comment (), extra: 0, next: Application (), nextExtra: 1_000_000), + ["no-last-flag"] = () => Build (Comment (), extra: 0, lastFlag: false), + ["audio-not-a-frame"] = () => Build (Comment (), extra: 0, noFrame: true), + }; + + public static IEnumerable KeptRows () => + from shape in Kept.Keys + from save in Saves + select new object[] { shape, save }; + + [TestMethod] + [DynamicData (nameof (KeptRows))] + public async Task BlocksTheSaveWritesBack_SaveKeepsEveryByte (string shape, string save) + { + var bytes = Kept[shape] (); + var files = new MockFileSystem (); + var file = Open (bytes, save, files); + file.Tag!.Title = "New"; + + var result = await Save (file, bytes, save, files); + + Assert.IsTrue (result.IsSuccess, result.Error); + var written = files.ReadAllBytes (save.EndsWith ("path", StringComparison.Ordinal) ? "/out.flac" : "/in.flac"); + var after = bytes.AsSpan (WalkEnd (bytes)); + Assert.IsTrue (written.AsSpan ().EndsWith (after), $"the {after.Length} bytes after the blocks read, whole, after the metadata"); + var back = FlacFile.Read (written); + Assert.IsTrue (back.IsSuccess, back.Error); + Assert.AreEqual ("New", back.File!.VorbisComment?.Title); + // Every block but STREAMINFO, the comment the save rewrote and the padding it writes fresh is written as it was. + var kept = Blocks (written); + foreach (var (type, body) in Blocks (bytes).Where (block => block.Type is not (0 or 1 or 4))) + Assert.IsTrue (kept.Any (block => block.Type == type && block.Body.SequenceEqual (body)), $"block type {type}, as it was"); + } + + public static IEnumerable KeptReads () => + from shape in Kept.Keys + from read in Reads + select new object[] { shape, read }; + + // Every read takes these as a save would write them back, a SkipPictures stream read too, so each renders. + [TestMethod] + [DynamicData (nameof (KeptReads))] + public void BlocksTheSaveWritesBack_Render (string shape, string read) + { + var bytes = Kept[shape] (); + var file = ReadBy (read, bytes); + file.RemoveAllPictures (); + + Assert.IsFalse (file.Render (bytes).IsEmpty, shape + " " + read); + } + + // Where a walk of the blocks by their declared lengths stops: after the one flagged last, or at the header of one + // that runs past the end of the file. + static int WalkEnd (byte[] bytes) + { + var offset = 4; + while (offset + 4 <= bytes.Length) { + var length = (bytes[offset + 1] << 16) | (bytes[offset + 2] << 8) | bytes[offset + 3]; + if (offset + 4 + length > bytes.Length) + return offset; + offset += 4 + length; + if ((bytes[offset - 4 - length] & 0x80) != 0) + return offset; + } + + return offset; + } + + // The metadata blocks of a FLAC file that the walk reads whole. + static List<(int Type, byte[] Body)> Blocks (byte[] bytes) + { + var blocks = new List<(int, byte[])> (); + var offset = 4; + var end = WalkEnd (bytes); + while (offset < end) { + var length = (bytes[offset + 1] << 16) | (bytes[offset + 2] << 8) | bytes[offset + 3]; + blocks.Add ((bytes[offset] & 0x7F, bytes.AsSpan (offset + 4, length).ToArray ())); + offset += 4 + length; + } + + return blocks; + } + + static IMediaFile Open (byte[] bytes, string save, MockFileSystem files) => + SpanSaveKit.Open (".flac", save.StartsWith ("span", StringComparison.Ordinal) ? "data" : "path", bytes, files); + + static Task Save (IMediaFile file, byte[] bytes, string save, MockFileSystem files) => save switch { + "sync-path" => SpanSaveKit.SavePath (file, "/out.flac", sync: true, files), + "async-path" => SpanSaveKit.SavePath (file, "/out.flac", sync: false, files), + "span-sync" => SpanSaveKit.SaveSpan (file, "/in.flac", bytes, sync: true, files), + "span-async" => SpanSaveKit.SaveSpan (file, "/in.flac", bytes, sync: false, files), + "sync-in-place" => SpanSaveKit.SavePath (file, null, sync: true, files), + _ => SpanSaveKit.SavePath (file, null, sync: false, files), + }; + + // fLaC, STREAMINFO, the block (and the next one), then the audio: frames, which begin with the sync code. Each + // block's declared length is its body's plus extra (nextExtra for the next one); the last block is flagged unless + // lastFlag is false; the frames are a variable-blocksize stream's when variable is true, and do not start with the + // sync code when noFrame is true. + static byte[] Build ((byte Type, byte[] Body) block, int extra, (byte Type, byte[] Body)? next = null, int nextExtra = 0, + bool lastFlag = true, int audio = Audio, bool variable = false, bool noFrame = false) + { + var head = TestBuilders.Flac.CreateMinimal (); + head[4] &= 0x7F; + byte[] blocks = next is { } following + ? [.. Header (block.Type, block.Body.Length + extra, last: false), .. block.Body, .. Header (following.Type, following.Body.Length + nextExtra, lastFlag), .. following.Body] + : [.. Header (block.Type, block.Body.Length + extra, lastFlag), .. block.Body]; + var frames = TestBuilders.Flac.Frames (audio); + if (variable) + frames[1] = 0xF9; + if (noFrame) + frames[0] = 0x00; + return [.. head, .. blocks, .. frames]; + } + + static byte[] Header (byte type, int length, bool last) => + [(byte)((last ? 0x80 : 0) | type), (byte)(length >> 16), (byte)(length >> 8), (byte)length]; + + static (byte, byte[]) Comment () => (4, new VorbisComment ("TagLibSharp2") { Title = "Title" }.Render ().ToArray ()); + + static (byte, byte[]) Padding () => (1, new byte[16]); + + static (byte, byte[]) StrayPadding () => (1, [.. Enumerable.Range (1, 16).Select (b => (byte)b)]); + + // One seek point: sample 0 at offset 0, 4,096 samples. + static (byte, byte[]) SeekTable () => (3, [.. new byte[16], 0x10, 0x00]); + + static (byte, byte[]) Application () => (2, [.. "TEST"u8, 1, 2, 3, 4]); + + static (byte, byte[]) Picture () => + (6, new FlacPicture ("image/png", PictureType.FrontCover, "", new BinaryData ([1, 2, 3]), 1, 1, 24, 0).RenderContent ().ToArray ()); + + static (byte, byte[]) Reserved (byte type) => (type, [.. "reserved"u8]); +} diff --git a/tests/TagLibSharp2.Tests/Xiph/FlacSaveStreamsAudioTests.cs b/tests/TagLibSharp2.Tests/Xiph/FlacSaveStreamsAudioTests.cs index d87b54aa..8fc0eccf 100644 --- a/tests/TagLibSharp2.Tests/Xiph/FlacSaveStreamsAudioTests.cs +++ b/tests/TagLibSharp2.Tests/Xiph/FlacSaveStreamsAudioTests.cs @@ -36,7 +36,8 @@ public void SaveToFile_CopiesAudioWithoutLoadingTheFile () var allocated = GC.GetAllocatedBytesForCurrentThread () - before; Assert.IsTrue (save.IsSuccess, save.Error); - Assert.AreEqual (1, fs.SourceLengthGets, "source length reads"); + // Open records the length once. The save then reads the source back to see whether it wrote over it (#179). + Assert.AreEqual (2, fs.SourceLengthGets, "source length reads"); Assert.IsTrue ( allocated < original.Length / 2, $"save allocated {allocated} bytes for a {original.Length} byte file"); @@ -62,7 +63,8 @@ public async Task SaveToFileAsync_CopiesAudioWithoutLoadingTheFile () var allocated = GC.GetAllocatedBytesForCurrentThread () - before; Assert.IsTrue (save.IsSuccess, save.Error); - Assert.AreEqual (1, fs.SourceLengthGets, "source length reads"); + // Open records the length once. The save then reads the source back to see whether it wrote over it (#179). + Assert.AreEqual (2, fs.SourceLengthGets, "source length reads"); Assert.IsTrue ( allocated < original.Length / 2, $"save allocated {allocated} bytes for a {original.Length} byte file");