Repository navigation
fix: Save after a save, read unknown durations as unknown, and keep every byte a save cannot place - #249
Conversation
Review 5 of #157 found code the length rule of #178 left behind. - The nine formats that parse the bytes they save from (FLAC, Ogg Vorbis, Opus, Ogg FLAC, Monkey's Audio, Musepack, WavPack, AVI, ASF) each wrote out the same four-line Recorded helper. It is now one generic SourceLength.Recorded; each read result exposes its file's lengths through the internal ISourceRecorder. - The skip reads of ASF and FLAC recorded a length through Recorded, and the MP3 skip read recorded one again after its window read. A skip read cannot save (PictureSkip.Refuse runs before Source.Refuse at every save, and nothing clears the flag), so nothing read those lengths. The ASF and FLAC skip reads now call Parse directly, and the MP3 call is gone. - The int.MaxValue bound in SourceLength.Saved stays. Its comment said a file of that size cannot be passed as a span, which is wrong; the bound is there because AtomicFileWriter reports a write of int.MaxValue bytes or more as int.MaxValue, which is not the file's length. The comment now says so, and SourceLengthTests pins it. - The length set is not bounded. Every length in it is a file the object can still save from: the formats that parse their bytes take the layout from each of them. No behaviour changes.
A path save reads the file the save before it left on disk. Read an MP3, FLAC, AAC or untagged DSF file from a path, edit, SaveToFile (), edit, SaveToFile () again, and the second save applied the offsets of the first read to the file the first save wrote, 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 (from the third save no duration could be read), and an untagged DSF file kept the first save's ID3 tag as sound. MPEG-PS refused its second save in place. The same matrix over every format found PNG, JPEG and GIF broken the same way: they planned the edit against the bytes they read and copied ranges from the file on disk, so the second save wrote an unreadable JPEG, a GIF without its comment and a PNG whose chunks no longer reach IEND. After a save, the object now describes the file it wrote over its source, as Audible already did: - SavedOverSource (Core) reads the source back after a successful save and answers whether it is now the file written: its length, and the bytes the save wrote at their offsets. It holds under any spelling of the path, and a save elsewhere answers false. Audible shares its rule for read-back failures, which never turn a committed save into a failure. - MP3 takes the ID3v2 size and the ID3v1 tag it wrote, FLAC the metadata size, AAC the ID3v2 size, its audio start, and the APEv2 tag it wrote as the tag read, with the layout it wrote it with (a tag parsed elsewhere from footer-only bytes and assigned is written with AAC's header, and a second save writes the header again, as a read of that file would; ApeTag.HeaderForSave), MPEG-PS every offset of its layout and the tags it wrote in front, at the end and as ID3v1. Each records the saved length in its SourceLength, in place of the one it read, so a span save from the saved bytes works and one from the read bytes fails; its refusal names the file last saved over the source (SourceLength.Rewrote), which Audible's said was the file read. The span save and the path save of each format share one plan of what they write, so both adopt the same layout. - PNG, JPEG and GIF take the bytes they wrote as the file they plan against, and their tag the text of those bytes with nothing pending. An unchanged save keeps the file as it is. - DSF keeps its sound where the read found it (the metadata offset, or the end of an untagged file), so every file it saves is one it describes; the untagged exception of #178 is gone. - An MP3, FLAC or AAC path save whose source is no longer of a length the object describes (another program rewrote it, or the read-back failed) fails and writes nothing. A known limit, as on 01b8d6c, filed as #195: an MP3 or AAC file with two tags of one kind stacked. The read takes the outer tag and leaves the inner one in the audio; a save that drops the outer tag uncovers the inner one, which a fresh read takes as the file's tag and this object does not. No audio is lost. Changing which tag a stacked file holds is a change to the read, not to the save, so it is left to its own issue. MP3 also took the end of its audio from the tag the object held, not the file: Id3v1Tag = null kept the old tag's 128 bytes as audio, and adding an ID3v1 tag dropped the last 128 bytes of audio. The audio now ends at the ID3v1 tag of the file. Tests, test first (each red on 01b8d6c): - PathSaveChainTests: SpanSaveKit's 18 fixtures and 8 more tag layouts (ID3v1 only, no tag, AAC with APEv2, Lyrics3 and ID3v1 behind a short and a 9 KB tag, MPEG-PS with an appended tag, APEv2 and ID3v1, an update tag, untagged DFF), read by path three ways, first saved in place, through another spelling, elsewhere or by span over the source, then saved twice more in place, sync and async: each later save equals a fresh read of the file on disk with the same edit. - WholeTagSteps (both chain classes): each whole tag the type can set (ID3v2, ID3v1, APEv2, Vorbis comment; an image's text) is dropped and given back, one save per step, after each kind of first save, sync and async; each step equals a fresh read of the file on disk with the same edit. - ImagePathSaveChainTests: the same chain for PNG, JPEG and GIF. - Mp3TrailerTests: removing or adding an ID3v1 tag keeps the audio, for every save and after an in-place save. - LookalikeSaveTests: a save elsewhere that writes a file of the source's length with another layout (a tag in front grown by a dropped ID3v1 tag, an ID3v1 or APEv2 tag in place of a 128-byte tag in front, a grown appended MPEG tag, a PNG title chunk moved in front of the image data) is not taken for a save over the source. - SecondSaveStateTests: after a save over the source the object holds the tags a read of that file holds (MPEG-PS front, appended, update and ID3v1 tags; AAC footer-only APEv2; PNG text with nothing pending). - InPlaceSaveBoundsTests: on real files at 1 MiB and 4 MiB of payload, an in-place save of MP3, FLAC, AAC, MPEG-PS and untagged DSF stays under 256 KiB of allocation (the read-back reads the written parts in chunks); a PNG save over its source copies the file once. - PathSaveSourceTests and SavedOverSourceTests: a source of another length, and a read-back that fails, end in a failure that writes nothing; the read-back itself. - SecondSaveStateTests: AAC, a footer-only tag replaced, then assigned back; a footer-only tag parsed elsewhere and assigned, then a save with no edit (red on the first form of this AAC rule, which took the parsed tag's own layout: 363 bytes for a fresh read's 395; F/r11/red-179-aac.log). - EarlierSaveTests: MP3, FLAC, AAC and MPEG-PS describe the file they saved over their source and no longer the one they read; an untagged DSF describes every save. PathSaveCancellationTests: a one-byte source now fails a FLAC save with the length message and a DSF save with the message Render gives for a source that ends before the sound, still ahead of a cancelled token. The streaming tests now count two source length reads for these formats (the open, then the read-back), as Audible's do.
An ID3v2.4 tag whose footer flag (0x10) is set with no footer after it: the reader counted the footer from the flag alone, so the 10 bytes after the body were the tag's, not the audio's, and a save dropped them. An MP3, AAC or MPEG-PS file lost the first 10 bytes of its audio (review 5's v24-footerflag.mp3; SaveNeverThrowsTests found it at byte 5 of the MP3, AAC and MPEG-PS fixtures). On main. ID3v2.4 §3.4: the footer is a copy of the header whose identifier is "3DI". Id3v2Header.TotalSizeIn (data or stream) counts the footer only when the flag is set and "3DI" follows the body; data that ends before it has no footer. The sweep of every reader that finds where a tag ends: - Id3v2Tag.Read's BytesConsumed, the audio start of MP3 and of every format that reads a tag from bytes (the AIFF, WAV, DSF and DSDIFF ID3 chunks read through it too); - Id3v2Tag.CopyWithoutPictures, the SkipPictures copy; - AacFile's audio start on a stream read, and its detection from a stream and from bytes; - MpegPsFile's tag length, from bytes and from a stream (it already checked "3DI" for an appended tag, and now does for a prepended one). The MP3 stream read's window sizes still take the flag: they only say how many bytes to read, and the tag read above decides where the audio starts. Id3v2Header.TotalSize, which trusts the flag, is unchanged. Tests, red on the previous commit for 18 of 35: - Id3v2FooterFlagTests: the MP3, AAC and MPEG-PS span-save fixtures with the flag and no footer, and with the flag and a "3DI" footer, read from a stream, a path, bytes, a path async and the format's own path read, then saved: each reads as the file without the flag does, and the saved file holds the bytes after the tag whole (15 rows failed, the flag-only ones). A SkipPictures read ends the tag where a full read does (Mp3File and AacFile Id3v2Size; 2 failed), and Id3v2Tag.Read's BytesConsumed counts the footer only when it is there (failed). - Mutants of each changed site fail them (F/r6/mut/results-202.txt).
) 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: review 6's byte 45, 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. On main. The read now notes such a block, and every save fails with "Cannot save a FLAC file with a metadata block whose bytes the save would not write back." and writes nothing (the span saves, the path saves, and Render, which 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; padding grown into what follows it (below). A SkipPictures read, which does not read picture data, reads each picture's fields before its data to tell a block that holds more than the picture, so it refuses as the full read does. Padding carries no data, so stray bytes in it are no loss: a save writes fresh padding in its place (68 fuzzed files with bytes that are not zeros in their padding save, as on main). A padding length grown into what follows it is a loss: it took in the next block's header or the audio's first bytes, which the save would drop. So padding that holds a byte that is not zero must end where a block header that fits in the file (not type 127, RFC 9639 §8.1), a frame sync (0xFFF8 or 0xFFF9) after the last block, or the end of the file begins; otherwise the save is refused. Padding of zeros is not checked. A stream read, which buffers only the metadata, reads the bytes after it from the source, where a read of the bytes finds them, a SkipPictures read included. Nothing else is refused, which review 6 asked for: its 446 files saved on main with every byte after the metadata. The walk now stops at the header of a block that runs past the end of the file, so a save copies that header and every byte after it (main dropped the header's 4 bytes), and a file whose blocks are not flagged last, whose audio does not start with a frame, or whose SEEKTABLE or APPLICATION took in audio bytes (written back inside the block) saves with every byte. Of the 446, 444 now save with every byte after the walk; the 2 refused are real losses: flac-testbench "faulty/11 - incorrect metadata block length.flac", whose comment declares 128 bytes and holds 40, the other 88 a PADDING block and the first frame's sync and header, and the fuzz file s028-045.flac, whose comment holds 51,712 bytes past its contents. This replaces this commit's first rule, that the audio must start with a frame sync, which refused those 446. The twin, a block the save drops: a block of a reserved type (7 to 126, RFC 9639 §8.1) was left out of a save; it is now written back as it is, like SEEKTABLE and APPLICATION (input-SCVAUP.flac has two of type 126). Tests, red on the previous commit for 132 of 279 (F/r7/red-padfollow-202.log): - FlacBlockLengthSaveTests: twelve shapes that lose bytes (the comment grown 1 and 220 bytes into the audio, cut 4 short, grown into the next block; a picture grown into the audio; padding grown into the audio and into the next block; padding with stray bytes before 3 bytes that are no header, and before a type 127 header; a second comment, a second STREAMINFO; a cue sheet that does not parse), each saved to a path, from the bytes and in place, sync and async, fail with the message, leave the source as it was and write nothing; read from the bytes, a stream and a SkipPictures stream, with the pictures cleared, they render nothing. Nineteen shapes the save writes back (every length right, no audio, a variable-blocksize stream, a picture, padding, padding of zeros before audio that is no frame, padding with stray bytes before a frame of either blocking strategy, before a block, at the end of the file and after a picture, a seek table, reserved types 7 and 126, a seek table or APPLICATION block grown into the audio, a block that runs past the end, no block flagged last, audio that does not start with a frame) save six ways, end with every byte after the walk, and write every block but the rewritten comment and the padding as it was; read from the bytes, a stream and a SkipPictures stream, they render. - The padding rule's rows: 36 fail with padding not checked (F/r7/red-padfollow-relaxed.log). - Mutants of each block's check, the duplicate check, the empty-block case, the SkipPictures picture check, the walk's stop at the header, Render's and the path save's refusal, and of the padding rule (no check, zeros only, any end, the end of the file, the sync mask, the sync, type 127, the header's fit, the bytes after a stream's metadata, their offset, and their offset in a SkipPictures read) fail them (F/r7/results-204-v3.txt).
Three durations came from 64-bit arithmetic that wrapped or ran past TimeSpan. They share one root cause, unchecked duration arithmetic on values the file supplies, and one fix: a value no duration can hold is unknown (0). #181 is the shared rule; #182 (DSDIFF's sample count) and applied. Each part below was red on the commit before it when it was its own commit. == #181: Report a duration too long for TimeSpan as unknown A file can state a duration past TimeSpan.MaxValue (about 9.22e11 s), and the readers gave four answers: TimeSpan.MaxValue (MP4, DSDIFF, DSF, Opus, Ogg Vorbis, Monkey's Audio, Musepack SV8, from #175), zero (AVI), null (Matroska, with a bound of its own), and a negative value (ASF, a (long) cast of a Play Duration of 2^63 ticks or more: 1e12 s read as -8.4e11 s). Adding anything to TimeSpan.MaxValue throws, so summing a playlist broke on such a file. No format spec sets a maximum or a clamp rule. ffprobe reports N/A exactly where a duration stops fitting its 64-bit time field (durations/report.md). Such a duration is now unknown, the answer the library already gives for a spec "unknown": TimeSpan.Zero on the Duration properties that are not nullable, null on the nullable ones. Durations is the one rule: FromSeconds, FromSecondsToTicks and FromTicks give unknown for NaN, zero or less, and from 922,337,203,685 s on; FromTickCount does the same for a stated tick count; OrNull maps unknown to null. Every reader goes through it: ASF (no cast), AVI (its Seconds folds in, and its bound moves from half of TimeSpan.MaxValue to the shared one), Matroska (its bound folds in), MP4, MPEG audio, MPEG-PS, AAC, WAV, AIFF, WavPack, and the readers already on it. Audible cannot overflow (its TOC sizes are uint) and is left as it is. Tests: DurationUnknownTests replaces DurationOverflowTests. One built file per format whose field can say more than TimeSpan holds (Monkey's Audio, Musepack SV8, DSF, Opus, Ogg Vorbis, MP4 v1, ASF, Matroska, AVI), read by stream, path, async path and ReadFromData, each with and without SkipPictures, and by the format's Read and its ReadFromFile: every Duration the file exposes is zero, or null where the property is nullable. Red on the previous commit for 70 of the 90 rows, 7 of the 9 files on each of the ten entry points (MaxValue, and a negative ASF value); the Matroska and AVI rows held already. The #175 entry-point consistency tests stay; the test that reached the overflow only by calling AudioProperties.FromFlac (ulong.MaxValue) directly is gone (STREAMINFO's 36-bit count at 1 Hz is 6.9e10 s). The MP4 test that pinned MaxValue now pins zero. DurationsTests pins the bounds of the rule. == #182: Check the DSDIFF duration before it overflows DffFile took the samples per channel of a DSD chunk as its size times 8 over the channels, in unchecked 64-bit arithmetic. A chunk of 2^61 + 16 bytes, stereo at 2,822,400 Hz, wrapped: it read as 22.6 microseconds instead of 3.3e12 s. The count is now the whole bytes per channel times 8 plus the bits of the rest, so nothing wraps: 2^63 + 64 samples for 2^61 + 16 bytes. The duration that gives is past TimeSpan, so it is unknown, as every format reports it (#181). A count past 64 bits (a chunk of 2^63 bytes, stereo) is 0. Tests: DurationUnknownTests gains a .dff row (2^61 + 17 bytes) and a .huge.dff row (2^63 + 2 bytes) on every entry point, and pins the sample count of each and of the largest count that fits (2^64 - 8). Red on the previous commit for all 23: the 20 rows of the two files on the ten entry points (22.6 us, and a wrapped count) and the three counts (the wrapped values). == #193: Keep a hostile ASF preroll from wrapping the duration AsfFileProperties.Duration is the Play Duration (100 ns units) less the Preroll (ms). It scaled the preroll by 10,000 in unchecked ulong, so a preroll of 1,844,674,407,370,956 ms (the review's asf-preroll-wrap.wma) became 2^64 + 8,384 ticks, wrapped to 8,384, and a file that plays for nothing read 5.1412 s. It is the twin of #182's unchecked multiply. The preroll is now compared with the play duration in ms first: at or past it the duration is 0, and below it the preroll in 100 ns units is at most the play duration, so the product cannot wrap. Other values are unchanged. Tests, red on the previous commit for 11 of 17: - AsfFilePropertiesTests.Duration_PrerollAtOrPastThePlayDuration: a preroll equal to the play duration, past it, wrapping, ulong.MaxValue (all 0), and one ms short of it (1 ms); a play duration 0.5 ms over a whole ms keeps the 0.5 ms after a preroll of those whole ms, and reads 0 after one ms more (that row kills `>` mutated to `>=`). Only the wrapping row failed. - DurationUnknownTests.AsfPrerollPastThePlayDuration_IsZero: the wrapping file reads 0 on all ten entry points.
Two formats define a value that means the duration is unknown, and the readers took it as a count. Same root cause, same fix: the marker reads as unknown. #183 covers MP4 and ASF, #191 WavPack. Each part below was red on the commit before it when it was its own commit. == #183: Read the spec's unknown-duration markers as unknown Two formats have a value that means "duration unknown", and both were read as a real duration. - MP4: "If the duration cannot be determined then duration is set to all 1s" (ISO 14496-12 §8.2.2.3 mvhd, §8.3.2.3 tkhd, §8.4.2.3 mdhd). A version 0 mvhd and mdhd of 2^32 - 1 read as 49.7 days at the test file's timescale of 1000 (27 hours at 44.1 kHz); a version 1 mvhd of 2^64 - 1 at a timescale of 2^32 - 1 read as 4.3e9 s. Both are now unknown, in Mp4File's movie duration, in Mp4AudioPropertiesParser's mvhd and mdhd (a known mdhd still wins), and in the movie duration that MP4 chapters end at. Mp4AudioPropertiesParser.IsUnknownDuration is the one test. tkhd's duration is not read. - ASF: the File Properties Object's Play Duration and Send Duration "is invalid if the Broadcast Flag bit in the Flags field is set to 1" (ASF Specification 01.20.03). Duration is now unknown while it is set; the new AsfFileProperties.IsBroadcast reports the flag. The raw PlayDurationNs and SendDurationNs are unchanged. ffprobe reports the MP4 marker as N/A and, for ASF, measures the data (durations/report.md). Unknown is TimeSpan.Zero, or null where the property is nullable, as in #181. Tests: DurationUnknownTests gains three files on every entry point (MP4 version 0 mvhd and mdhd, MP4 version 1 mvhd, a broadcast WMA), each read the ten ways #181's rows are. Red on the previous commit for all 30 (49.7 days, 4.3e9 s, 1 s). The past-TimeSpan rows and these share one assertion: null on a nullable Duration, zero on the others. Also pinned: Mp4AudioPropertiesParser reads the markers as unknown, and the last chapter of a file with the marker ends where it starts, not 49.7 days later, and a chapter list saved into it keeps its last chapter short. The public API snapshot gains IsBroadcast. == #191: Read WavPack's unknown-length marker as unknown The WavPack file format says of the block header's total_samples that it "is only valid if block_index == 0 and a value of -1 indicates unknown length". We read 0xFFFFFFFF as a count: the corpus 24bit.wv with that marker read 97,391.5 s (a fake 27 hours at 44.1 kHz) on every entry point, where ffprobe reports N/A. It is the twin of #183's MP4 and ASF markers, which the sentinel sweep of that commit missed. Both header readers, the version 4 block header and the version 3 header inside RIFF/WAVE, now read the marker as no count (SampleCount), so TotalSamples is 0 and the file reads as one whose header gives 0: the duration is unknown. The document quoted is the version 4 block header's; it does not describe version 3. The version 3 count follows the reader's own rule for versions 1 and 2, which already read a data size with bit 31 set as unknown. Tests, red on the previous commit for all 40 rows: DurationUnknownTests gains a version 4 file and a version 3 RIFF file with the marker, read the ten ways (every Duration is unknown), and WavPackUnknownLength_HasNoSampleCount (TotalSamples is 0, the sample rate stays 44,100).
A WavPack file whose first block declares a size of 0 (review 5;
SaveNeverThrowsTests found it at byte 4 of the WavPack fixture), or any
size below 24: the size counts the block after its first 8 bytes, and
the version 4 block header takes 24 of them. A stream or path read took
the 8 bytes the size named and the bytes after them, the APE tag, for
the block header, and read 2 days 20 hours at 6,000 Hz; with no tag
after the block it failed ("data too short"). A read of the bytes read
the header as a block (1 s at 44.1 kHz). On main.
Such a size is no block. The parse no longer reads the header's fields
(HoldsBlockHeader): the properties are unknown, on every entry point,
and the tag reads as it is. The stream read takes the header's 32 bytes
as a read of the whole file sees them, so both reads parse the same
bytes. The other block-size checks, the sub-block walks for a custom
sample rate and the channel layout, end at 8 + the size and so read
nothing from such a block; they run only for a block whose header was
read. The legacy versions (1 to 3) keep their own header lengths; their
block size is not checked this way. A save keeps the block and the
audio as they are, as it did.
Tests, red on the previous commit for 30 of 58:
- WavPackBlockSizeTests: a version 4 block declaring 0, 1 and 23, with
1,024 bytes of audio and an APE tag, read from a stream, a path,
bytes, a path async and the format's own path read, reads no duration
and no sample rate, and the title (15 failed); the same without a tag
(15 failed: the stream reads failed, the others read the header);
sizes 24 (the header alone) and 24 + the audio read the properties;
and saves to a path, from the bytes and in place, sync and async,
keep the block and the audio whole and the new title.
- Mutants of the parse rule, the stream read and the bound fail them
(F/r6/mut/results-201.txt).
#192 and #197 are one defect in the WAV and AIFF chunk walks, twins: the read from memory and the read from a stream kept different chunks, and the bytes after the form were lost. One rule in Core (ChunkExtent, FormTrail, TrailingTagChunk) fixes both. #203 is the WAV twin of #197's AIFF path save, which copies a chunk of any size from the source. Each part below was red on the commit before it when it was its own commit. == #192: Read a WAV data chunk of unknown size the same from memory ffmpeg writes a data chunk size of 0xFFFFFFFF when its output is a pipe; the samples run to the end of the file, and ffprobe reads their duration (2.1196 s for the review's wav-ffff.wav). A stream or path read kept the chunk with the bytes present and read that duration. A read of bytes in memory (MediaFile.ReadFromData, WavFile.Read, ReadFromFile) went through RiffChunk.TryParse, which refused any size past int.MaxValue: the walk stopped there, the data chunk was lost, the duration read 0 and a save was refused for having no data chunk. Two walks of one structure disagreed on one rule. Both walks now keep a chunk by one rule, RiffFile.PresentBytes: its bytes present, up to its size and never past the end of the RIFF form. The span walk passes the form's end into RiffChunk.TryParse (which kept bytes up to the end of the data, so 128 bytes after the form of the review's wav-ffff-trailing.wav were samples and ReadFromData read 2.00145 s against 2.0 s), and the stream walk copies a chunk other than data whose size is past int.MaxValue from the bytes present, as the span walk does (it kept it empty, so a LIST INFO of size 0x80000000 had a title from memory and none from a stream: wav-list-8000.wav; ffprobe reads the title). Only bytes present past int.MaxValue, which no copy can hold, stay in the file like samples. The walks still end at a chunk that runs past the form. A save from any read writes the samples present with their size. Bytes after the form are not samples, but they are the file's, and a save dropped them: it wrote the form alone, so bytes that are no chunk, a chunk after the form, and the samples past a RIFF size short of them were lost. They are now written after the form as they were (Core FormTrail, which #197 uses for AIFF too). A read of the bytes holds them; a stream read leaves them in the file, as its last bytes, which is where every save writes them, so the streamed save copies them from the end of the source, after a save over that source as well, and Render loads them with the samples. The RIFF size of a save does not count them, as it did not on the read. An id3 chunk a tagger appended right after the form without growing the RIFF size (exiftool and ffprobe read it; review 6's trail-id3.wav) is read as the file's tag chunk when the form holds none, on every entry point, read from bytes, a stream and SkipPictures (Core TrailingTagChunk: a whole chunk right after the form whose body is an ID3v2 tag); the bytes after it are the trail. So a save writes the tag in the form and no stale copy stays after it: carried, it left an old title that ffprobe showed beside the new one. A chunk with that identifier whose body is no tag, or one not right after the form, is carried as it is. Review 7 found the shapes the read left stale for ffprobe, and one it dropped. The chunk is now named "id3 " or "ID3 " (either case of the identifier the format reads its tag from). More such chunks right after it, or right after a form that has its own tag, are superseded by the form's tag: a save that writes the tag other than as it was read (an edit, or removing it; the tag rendered against the tag read, rendered) drops them, so ffprobe shows no old title beside the new one and a removed tag does not come back from them, and a save that leaves the tag as read carries them as they were (FormTrail.For). A SkipPictures read that left a picture out of the tag counts as rewritten, as a full read cleared of its pictures is (the stripped copy says whether it left one out). A chunk whose ID3v2 header is followed by no field is no longer taken as the file's tag, which a save then dropped (48 bytes); it is carried, so a chunk the read does not take is always kept as it was. A chunk cut short or declaring more than the file holds is carried as it was: it is not a whole tag, and ffprobe still shows its title beside a new one. Tests, red on the previous commit for 11 of 27, and 21 of 160 for the property test (all on main too): - RiffWalkAgreementTests: fmt, data, LIST INFO and an unknown chunk, last in the form or not, given a size 1 and 1,000 past its bytes, 0x7FFFFFFF, 0x80000000 and 0xFFFFFFFF, with and without 128 bytes after the form and with a placeholder form size (160 files): the ten entry points read the same duration, format and title. Main fails 21 (data chunks counting bytes after the form, and oversized chunks the span walk dropped); the first version of this commit fixed 12 of those and broke 32 cells main had right (every fmt and LIST size past int.MaxValue), 41 in all (r3/red in the fix report). Its matrix also has a declared size below the true size and forms of size 0, 4, half the form and larger than the file (1,152 rows with the save rows), and each row is saved after a read from memory and after a stream read: both write the same bytes or end the same way. FormEnd_BoundsTheChunks pins the rule itself, not only agreement: bytes after the form are not samples, and a chunk past the form's end is not read (a mutant that ignores the form's end changes every walk alike and passes the agreement rows). Main fails 185 of those 1,153. - WavUnknownDataSizeTests: a piped file with a data size of 0xFFFFFFFF, and one of 0x80000000, reads 2 s on all ten entry points; a save after a format path read, a path read and an async path read keeps the samples, in a data chunk of their size. - WavFileSavePreservationTests: the four DataChunkSizeSentinel tests pinned the refusal that followed from the lost chunk (the saves and Render failed rather than write a WAV without its samples); they now pin that the save and Render keep the samples. - FormTrailSaveTests: a WAV with an id3 chunk right after the form, that chunk then 37 bytes that are no chunk, those bytes alone, the bytes then the chunk, a RIFF size 16 bytes short of the samples, the chunk after a form whose data chunk is empty, a form with an id3 chunk of its own then the chunk, and a chunk with that identifier whose body is no tag, read from a path, a path async and memory, saved to a path and over the source, sync and async, with and without a new title: the read finds the trailing tag where there is one; the saved file is the form, then the bytes carried as they were, and reads with the source's duration and the title it was given or read; with no edit the samples are one run again. Every entry point (path, async path, bytes, stream, async stream, and the three SkipPictures reads) reads the same title and duration. The tag rows use v2.2, v2.3 and v2.4 tags. Red in two steps: the trail's 96 rows all failed on the previous commit (round 6), and with the trail in, 100 of 250 failed before the tag read (every row of the shapes with a tag read, and their parity rows; F/r7/red-tag-192.log). Mutants of each read, the tag read in each walk, the tag check, the version guard, Render, the streamed save, the load and the copy's offset fail them (F/r6/mut/results-trail-192.txt, F/r7/results-tag-v2.txt). - FormTrailSaveTests, round 8: the chunk named "ID3 ", two chunks after the form, a chunk with an ID3v2.3 header and no field, alone and after a form with a tag, and a chunk cut 10 bytes short. Removing the tag drops the superseded chunk on every read and save, and a SkipPictures read renders what a full read cleared of its pictures renders (a picture in the form's tag, in the tag read from after the form, and a tag after the form that holds a picture alone). 99 of 402 failed before (F/r8/red-tag-192.log); mutants of the case rule, the field check, the picture flag, each walk's superseded count, Render's and the streamed save's choice, and the removal fail them (F/r8/results-tag8.txt). == #197: Read and save AIFF chunks by one rule, memory and stream The AIFF twin of #192's RIFF fix. A read of bytes in memory walked the chunks to the end of the data and ignored the FORM size; a stream read stopped at the FORM's end. The span walk also dropped a chunk whose size ran past the data or past int.MaxValue, where the stream walk kept the bytes present, and the stream walk kept a non-SSND chunk past int.MaxValue empty. The review's aif-form-0.aif (FORM size 0; also 4 and 12) read 2.0 s from memory and no audio properties on the seven other entry points, on main too; ffprobe rejects it. ChunkExtent (Core) is now the one rule both chunk families use: a form ends at its declared size, or at the end of the data when that size is the 0xFFFFFFFF placeholder or runs past it; a chunk holds its bytes present, up to its size and never past the form's end. RiffFile's PresentBytes moves there; AiffChunk.TryParse takes the form's end and keeps such a chunk with its declared size and the bytes present (it returned false); the stream walk copies a non-SSND chunk past int.MaxValue from the bytes present, and leaves only bytes past int.MaxValue in the file, as the RIFF walk does. The span walk needs no stop of its own at a cut chunk: its declared size puts the next offset past the FORM's end (a mutant that removed such a stop survived, so it is gone). A chunk kept with its declared size past its bytes is now saved by the bytes it holds, as a WAV chunk is: AiffChunk.RenderedSize (the header, the bytes present and their pad) sizes Render's buffer and the file in Render, and the streamed save writes a skipped SSND with the size and pad of its bytes present. They sized and wrote the declared size, so a file of a few hundred bytes that declared a 256 MB chunk made a save allocate 512 MB, a declared size near 2 GB or past it threw "Cannot render an AIFF file larger than supported memory.", and a header that kept the declared size swallowed the ID3 chunk written after it. The review's aif-ssnd-ffff.aif (SSND 0xFFFFFFFF, the placeholder a streamed writer leaves; ffprobe reads 2.0 s) and aif-comm-19.aif (COMM 19, so COMM takes a byte of SSND's header) threw that way from a path read, on main too; they now save and read back as the source did. The streamed save copied only the bytes present; its header, pad and FORM size were the declared ones. A stream read kept such a chunk before this commit, so #192 has the same failures; keeping it on a read from memory too made them reachable from every entry point. RIFF chunks are already written by the bytes they hold (RiffChunk.RenderedSize, and the WAV streamed save's PresentBytes), and DSF and DSDIFF size their saves from the bytes present; neither uses the declared size for a buffer. A stream read leaves an SSND in the file and records it, so a save copies it from the source. It recorded one only up to int.MaxValue bytes; a larger one (review 4's big.aif, a 2,281,701,444-byte file) was left in the file unrecorded, so a save took the in-memory path and, with chunks now written by the bytes they hold, wrote an SSND with no bytes and reported success. Over the source, that destroyed the file; main threw instead. Every SSND left in the file is now recorded, whatever its size, and the streamed save copies it in pieces: only the FORM's 32-bit size bounds the file, and a save past it fails with "Cannot save an AIFF file larger than its 32-bit FORM size." and writes nothing (the streamed save threw "larger than supported memory" for any chunk sum past int.MaxValue). The same sweep: DSF and DSDIFF save a 2 GB sound by copying it; WAV refuses it before writing ("does not fit in memory"), as on main; no render treats a chunk left in the file as empty. Bytes after the FORM are written after it as they were, as a WAV save writes the bytes after its RIFF form (#192, Core FormTrail), and an ID3 chunk right after the FORM is read as the file's tag chunk when the FORM holds none, on every entry point (Core TrailingTagChunk, as #192 reads a WAV's). The real taglib-samples sample.aif has its ID3 chunk after the FORM's declared end; exiftool reads its Title, Album and Artist (ffprobe and MediaInfo read no tag there). A save with no edit dropped the chunk (177,704 bytes to 176,454, on main as well), and a FORM size short of the sound dropped the sound past it. The first version of this commit carried the chunk without reading it, which left the old tag after an edit for a reader that reads past the FORM (review 6). Now the tag is read, from bytes, a stream and SkipPictures, so a save writes it in the FORM and no stale copy stays after it; any other bytes after the FORM, and a tag chunk when the FORM has its own, are carried as they were. The tag read takes ID3v2.2, v2.3 and v2.4 tags: sample.aif's tag is ID3v2.2, which #186's reader reads whole and #187 writes back as ID3v2.3. After an edit, exiftool, ffprobe and MediaInfo show only the new title, with the artist, album, comment and the other fields kept. The tag chunks after the FORM follow #192's rule (review 7): the chunk is "ID3 " or "id3 ", one whose ID3v2 header is followed by no field is carried, and more such chunks right after the one read, or right after a FORM with its own ID3 chunk, are dropped by a save that writes the tag other than as it was read and carried by one that does not (AiffFile.TagRewritten, against the tag the last ID3 chunk that reads holds, as the read takes it). The test AIFF builder declared a FORM 16 bytes short of its chunks, so a stream read never reached SSND and a read from memory ignored it. It now declares the true size; the SkipPictures fixture that rendered an AIFF seed after a stream read reads it from memory instead, as a stream read leaves the sound in the stream. Tests, red on the previous commit for 351 of 685, and 37 of 79 for the save tests; the B1 tests are red on this commit's first version (9fe27c89) for 16 of 40: - AiffWalkAgreementTests: COMM, SSND, NAME and an unknown chunk, last or not, a size below the bytes, +1, +1000, 0x7FFFFFFF, 0x80000000, 0xFFFFFFFF, with and without 128 bytes after the form, in a FORM of its true size, the placeholder, 0, 4, 12, half and larger than the file (672 files): the ten entry points read the same. 347 failed. - FormEnd_BoundsTheChunks: a NAME past the FORM's end is not read, and a FORM larger than the file reads every chunk, on all ten entry points: the rule itself, which a mutant that ignores the FORM's end would keep in agreement. - AiffChunkTests: the three tests that pinned TryParse refusing a size past the data or past int.MaxValue now pin the size and the bytes present. - TruncatedLastChunkSaveTests: a tiny AIFF and a tiny WAV whose last chunk (the sound, a chunk a reader knows, an unknown one) declares 256 MB, 256 MB and one byte, 0x7FFFFFF0, 0x80000000 or 0xFFFFFFF0, in a FORM of its true size or the placeholder (60 rows), read from a path, a stream and memory, saved as read and with a new title, to a path and over the source, sync and async: each save writes a file no longer than the source and the ID3 chunk, which reads as the edited file did, or fails and writes nothing, and a sync save allocates under 16 MB. All 30 AIFF rows failed (a throw, 512 MB allocated, or the title lost); the 30 WAV rows pass on #192. - AiffOversizedChunkSaveTests: both review repros, read from a format path, a path and memory, saved to a path and over the source, sync and async: each save succeeds, writes the FORM size of the file and every chunk with the size of its bytes, and reads as the source did (18 rows; the 6 after a path read failed). - PathSaveCancellationTests: the test that pinned the throw for a declared size past memory now pins the cancelled save's failure. - BigSoundSaveTests: a WAV, AIFF, DSF and DSDIFF file whose sound chunk holds 0x88000000 bytes, as Kit/SparseFileSystem files (the sound is a run of a pattern that costs no memory and is checked byte by byte as a save streams it), read from a path sync and async, retitled, and saved to a path and over the source, sync and async: AIFF, DSF and DSDIFF keep the sound after the same chunk header and read back as the edited file; WAV fails and writes nothing. An AIFF whose FORM is 4 GB less 18 bytes, retitled, fails with the FORM message and writes nothing. Review 5's shapes: an odd SSND with its pad byte and a chunk after it keeps the sound, the pad and the chunk; a FORM of 0xFFFFFFFE saved as it is copies all 4 GB of the sound. Each saved sound is exactly the source's length. 25 of 49 failed on 9fe27c89 (every AIFF row). - FormTrailSaveTests gains the AIFF rows of #192's shapes (the empty sound is a FORM with no SSND chunk), with v2.3 and v2.4 tags after the form. Red in two steps: the trail's 96 AIFF rows failed on the previous commit (round 6), and the 100 AIFF rows of the tag shapes failed on this commit's code without the AIFF tag read (100 of 500; F/r7/red-tag-197-v2.log). Mutants of each read, Render, the streamed save, the load, the tag read in each walk, the tag check and the version guard fail them (F/r6/mut/results-trail-197.txt, F/r7/results-tag-v2.txt). - Round 8: the AIFF rows of #192's new shapes, the removal test and the SkipPictures render test. 50 of 804 failed with no superseded chunks in the AIFF walks (F/r8/red-tag-197.log); mutants of each walk's count, the picture flags, Render's and the streamed save's choice and the removal fail them (F/r8/results-tag8.txt). == #203: Copy a WAV chunk of any size from the source on a path save A WAV path save refused any chunk past the array limit (about 2 GB), with "Cannot save a WAV file whose sample data does not fit in memory.", though the save never holds the chunk: it copies it from the source in 64 KB pieces (WritePlanned). A 2.28 GB WAV, or one whose data chunk ends with the 0xFFFFFFFF size a streamed writer leaves, could be read and retitled but not saved. On main. An AIFF save copies its sound of any size from the source since #197; WAV now does the same. WavFile.SaveFromSource drops the refusal and sums the planned pieces instead: a save whose RIFF size (4 + the chunks) would pass 32 bits fails with "Cannot save a WAV file larger than its 32-bit RIFF size." and writes nothing, as AIFF's FORM guard does. Every piece is 8 bytes, the bytes present and a pad, so the size is even and 0xFFFFFFFE is the largest; it saves. The in-memory render and the span saves still load the samples and keep the memory refusal (TryLoadSkippedSamples), as AIFF's TryLoadSkipped does. This reverses two tests that pinned the old rule, that a save of such a file "fails closed"; they now pin the new one: - WindowedReadDefectTests.Read_DataChunkPastTwoGigabytes_ KeepsTheFollowingTitleAndRefusesTheSave is now ..._KeepsTheFollowingTitleAndSavesTheSamples: the 2 GB data chunk is copied whole, and the title after it reads back. - WindowedReadEdgeTests.Save_DataChunkJustOverTheArrayLimit_FailsClosed is now ..._CopiesTheSamples: every sample is copied and the RIFF size is the file's length less 8. Both now use the kit's SparseFileSystem, and their private copies of it are gone. Tests, red on the previous commit for 27 of 116: - BigSoundSaveTests gives WAV rows for each shape AIFF has: a sound past int.MaxValue, an odd sound followed by another chunk, a container of 0xFFFFFFFE bytes saved whole, and a save that would pass 32 bits failing and writing nothing; read from a path and a path async, saved to a path and over the source, sync and async. Every WAV row failed (25), and the two rewritten tests above; the AIFF rows pass. - Mutants: removing the RIFF guard, or restoring the refusal, fails them. Making the guard >= is equivalent, since the size is always even (F/r6/mut/results-203.txt). - On #186 (the branch now sits on it): the v2.2 shape is read like the v2.3 and v2.4 ones, and sample.aif from the corpus is read with its title on every entry point and saved with no edit or a new title, sync and async, as one tag in the FORM keeping its album and artist. 54 of 808 failed while v2.2 was carried (F/r8/red-v22-C.log).
int properties wrapped, and now go through Core Rates, which reads 0 when an int cannot hold the value. #194 covers the sample rates, counts and integer bit rates, #198 the bit rates worked out as real numbers. Each part below was red on the commit before it when it was its own commit. == #194: Read rate fields past int range without wrapping The WAV fmt chunk stores its sample rate and byte rate as unsigned 32-bit fields; WavAudioProperties cast both to int. A sample rate of 2^31 read as -2,147,483,648, and a byte rate past int.MaxValue gave a negative or zero bit rate. A WAV file with no sample rate is invalid, and SaveToFile and SaveToFileAsync then threw InvalidOperationException ("Cannot render invalid WAV file") out of Render, where a save returns a failure (the review's wav-fmt-ffff.wav threw on main and at the head of round 2). The sweep of the other readers found the same cast of a 32-bit sample rate in DSF, DSDIFF (both of its reads), Monkey's Audio (both header versions), ASF, MP4 (the mdhd timescale it takes as the sample rate, three sites) and the ALAC magic cookie; AIFF rounds its 80-bit real into an int, which saturates at int.MaxValue. AVI already scales its byte rate in 64 bits, and WavPack already refuses a rate past int.MaxValue. The tests found two more: DSF's own SampleRate, Channels, BitsPerSample and BlockSizePerChannel cast their 32-bit fields too, and the DSF and DSDIFF bit rates (sample rate times channels) were cast from 64 bits to int, so 2^30 Hz over 4,096 DSDIFF channels read 103,079,215 kbps. Rates (Core) is now the one rule: a sample rate an int cannot hold is no sample rate (0), as WavPack rules, and a bit rate is worked out in 64 bits. Every site above goes through it. WavFile refuses a save of a file without a sample rate, as it refuses one without a data chunk (SaveRefusal), before anything is written, and says which: a RIFF structure that is invalid, no sample rate, or no data chunk. Tests, red on the previous commit for 110 of the 119 that build without Rates (the three edge tests call it): - RatePastIntTests.SampleRatePastInt_IsNoSampleRate: WAV, AIFF (2^40 Hz), DSF, DSDIFF, Monkey's Audio, ASF and MP4 files with a rate of 2^31, on all ten entry points: the sample rate is 0 and the bit rate is not negative, and a type's own SampleRate is 0 too (-2,147,483,648 before, and 2,147,483,647 for AIFF; Monkey's Audio's properties already dropped a rate below 1, its own SampleRate did not). - WavWithAnInvalidRiffStructure_SaySo: a save of a WAV file whose RIFF structure is no longer valid (disposed) says so, apart from "no sample rate". - WavByteRatePastInt_GivesItsBitRate: a byte rate of 0xFFFFFFFF gives 34,359,738 kbps on all ten (0 before). - WavWithoutASampleRate_SaveFailsAndWritesNothing: a rate of 2^31, and a fmt chunk whose size is 0xFFFFFFFF, read three ways and saved three ways, fail and leave the file as it was (the rate rows threw). - DsfChannelCountPastInt_IsNoChannelCount, DffBitRatePastInt_IsZero: 2^31 DSF channels read 0 (-2,147,483,648 before), and the DSDIFF bit rate past an int is 0, on all ten entry points. - SampleRateField, SampleRateReal, KbpsOfBitsPerSecond: the rule's edges. == #198: Report a bit rate too large for an int as unknown 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. One too large to report read as 2,147,483,647 where the cast saturates (net9.0 and later) and wrapped on older runtimes. The review's opus-1sample-big.opus (6 MB, its last granule one sample past the pre-skip) read 2,147,483,647 kbps; the true value is 2.4e9. #194's rule reads a rate too large to report as 0; its sweep took the integer casts and missed these. Rates.Kbps now has a real-number overload (truncated, 0 when negative, not a number or past an int), and every such site goes through it: AudioProperties.FromFlac and FromOpus, Ogg FLAC, Opus, WavPack, Monkey's Audio, Musepack, AAC, and MPEG audio's three (Xing, VBRI, the data size). AudioProperties.FromDsf and FromDff, whose 64-bit product was cast back to int, take the integer overload. The sweep for any other cast of a rate found Matroska's SamplingFrequency and OutputSamplingFrequency (a float cast to int) and its Channels and BitDepth (an unsigned integer cast to int): they read 0 past an int, and a stored value too large is no longer taken for an absent one (Matroska's 8,000 Hz and one-channel defaults apply only when the element is absent). MPEG-PS LPCM, AVI, ASF, and the MP4 average bit rates are bounded by their fields and now go through the same rule. Tests, red on the previous commit for 24 of the 25 that build without the new overload: - BitRatePastIntTests: the Opus file on all ten entry points (bit rate 0, duration 208 ticks); FromOpus, FromFlac, FromDsf and FromDff past an int; a Matroska file with a 1e20 Hz rate and 2^40 channels on all ten (2,147,483,647 before); the factories in range keep their bit rate; the rule's edges on a real number. The tests assert 0, which no cast gives, so they fail before the fix on every platform.
…written (#196) A save returns a failure and writes nothing on malformed input; it never throws, and it never reports success for a file it did not write whole. The review's two AIFF repros (aif-ssnd-ffff.aif and aif-comm-19.aif) threw because a save sized chunks by their declared size; #197 writes each chunk by the bytes it holds, and saves a sound of any size from the source, so they save. What is left for an AIFF save: - A new AiffFile (), which has read nothing, threw "Cannot render invalid AIFF file". It now fails with "Cannot save an invalid AIFF file." - A file with no valid COMM chunk saved "successfully" as its 12-byte FORM header (review 4's aif-form-0.aif, whose FORM size of 0 ends the form before its chunks; every entry point reads it with no audio properties). Every AIFF file needs a COMM chunk (AIFF 1.3, "Common Chunk"), so the save fails with "Cannot save an AIFF file that has no valid COMM chunk." IsValid keeps its meaning (a FORM header that parsed); SaveRefusal holds what a save needs, on both path saves and the save over the source. - An in-memory save whose chunks would pass int.MaxValue fails before it renders, where Render threw "larger than supported memory". It needs more than 2 GB of chunks held in memory: a stream read leaves any SSND, and any chunk too large to copy, in the file, and #197's streamed save copies them. This guard has no test. The sweep of every throw site on a save path, in every format: WAV refuses before Render (#194); DSF and DFF saves do not go through their throwing Render; RenderSource, Matroska's cluster bound and the end-of-stream checks of the stream copies are Render-only or caught by the atomic writer; ObjectDisposedException on a disposed object is the documented contract. Tests, red on the previous commit for 73 of 113: - SaveNeverThrowsTests: every built file (the 18 span-save fixtures, WAV, AIFF, an AIFF with COMM 19, MP4, PNG, GIF, JPEG, Matroska, and BMP, PCX, Netpbm, TIFF, DNG and SVG; the WAV and AIFF hold 1,024 bytes of sound and the images pixels past the mutated span), with 0x00 and 0xFF at each of its first 96 bytes and 0xFFFFFFFF stamped at each offset, read from a path and from memory, then saved to a path, over the source, in place, sync and async, and from the bytes where the format has that overload. No save throws, and a failed save leaves its target as it was. A save that succeeds wrote the file it read: the written file reads with the source's audio or image properties and title, and holds the source's payload. The payload is the longest run past the mutated bytes that a save of the unmutated file keeps as it is and retitled, and the written file must hold it whole; an Ogg save rewrites every page header it copies (serial, sequence, CRC), so an Ogg payload is the longest run anywhere and is held by half of its 8-byte windows. A save that writes the sound empty (review 4's B1) or drops part of it fails. The span saves are checked over the source, which they write. The bytes this property finds on main as well are listed in Known with what the save does, each an issue of its own: an Opus tags page that is broken, where the save drops the audio page (#199), and an ASF header object size or count that cuts the header short (#200). The WavPack block size the read took for 2 days 20 hours (#201) and the ID3v2 footer flag that took 10 audio bytes (#202), which it found too, are fixed before this commit. ReadOtherwise lists the mutated sizes that make the read take payload bytes for something else, where the save writes the file it read: an AIFF chunk size grown into or short of the next chunk (COMM grown into SSND, SSND 8 bytes short). A FORM or RIFF size short of the sound, and a FLAC VORBIS_COMMENT length grown into the sound, which the property also found, are fixed before this commit: the bytes after the form are written after it (#192, #197), and a FLAC save that would drop bytes a metadata block holds fails (#204). NoPayloadPastSpan lists the three fixtures (APE, Musepack, WavPack) whose bytes past the span are all tag. A listed byte that stops failing fails the test. Against the half bar of round 5, an AIFF render that dropped a quarter of each chunk passed; it now fails the AIFF and COMM-19 AIFF rows (F/r6/mut/half.txt). - NewFileObject_SaveFailsOrWritesWithoutThrowing: every file type a caller can construct with no arguments (AiffFile) is saved to a path, sync and async, without throwing. It threw "Cannot render invalid AIFF file". - AiffSaveRefusalTests: FORM sizes 0, 4 and 12 (aif-form-0.aif and its siblings) and a FORM with an SSND but no COMM, read from a path, a path async, a format path, memory and a stream, saved to a path and over the source, sync and async: each save fails and writes nothing. 72 of 80 failed; the 8 that passed are the in-place save after a read with no source path. (With 1,024 bytes of sound, no single mutated byte of the property's AIFF ends the FORM before COMM, so this test, not the property, pins that refusal.)
…#212) A file read from a path, edited and saved over its source, then edited and saved again from the same object. The path save copies the sound from the source at the offset the read found it (SSND, the data chunk). When a chunk ahead of the sound changed size on the first save, the sound moved: an edited AIFF NAME is written to the ID3 chunk after the sound, and a WAV LIST INFO before the data is written after it. The second save copied the bytes now at the old offset: AIFF wrote them in place of the sound and reported success, WAV failed with "Cannot save a WAV file whose sample data is no longer in the source file." On main as well. #179 fixed the same class for MP3, FLAC, AAC, MPEG-PS and DSF; the AIFF and WAV saves kept the offsets of the read. The save now records its layout as it writes (Core ChunkLayout: the form header, each chunk it writes from memory, each chunk it copies with the offset its bytes land at, and the bytes after the form, #192 and #197). After a save, SavedOverSource reads the source back; when it is that layout, the object takes the offsets the save wrote its copied chunks at, as a fresh read of the file finds them. A save elsewhere, or a source another program rewrote, keeps the offsets of the read. The bytes after the form need nothing: they are the file's last bytes before and after every save. The read-back is one more read of the source's length: AiffSaveStreamsAudioTests and WavSaveStreamsAudioTests now count two, as the FLAC and MP3 ones do since #179. The sweep, every format with a path save, chained three times with titles that outgrow any padding (8,000, 3 and 3,000 characters) and compared with a fresh read at each step: MP4, Matroska, AVI, ASF, Audible, DSF and DSDIFF write what a fresh read writes and need nothing (DSF and DSDIFF keep no chunk ahead of the sound an edit changes; their tags are at the end); the formats of #179's chain tests pass as well. A save over the source that dropped the superseded tag chunks after the form (#192, #197) also takes the bytes after the form as they now are, without those chunks, so the next save copies the right bytes even when it leaves the tag as it was read (round 8). Tests, red on the previous commit for 16 of 104: - ChainedSaveTests: SpanSaveKit's fixtures, an AIFF with a NAME chunk ahead of SSND, a WAV with a LIST INFO ahead of data, both again with 37 bytes after the form, plain AIFF and WAV, MP4 and Matroska, read from a path, first saved over the source or elsewhere, then over the source, sync and async: each save equals what a fresh read of the file before it, given the same edit, writes, and reads back with the title. The 16 rows of the four AIFF and WAV shapes failed. - Mutants: no adoption in AIFF, in WAV, adoption without the read-back, the copied offset without its header, and a layout that leaves out the bytes after the form each fail them (F/r6/mut/results-chain.txt). - FormTrailSaveTests.SavingAgainOverTheSource_AfterTheChunkWasDropped: a WAV and an AIFF with a tag in the form, or two after it, edited and saved over the source, then saved again with no edit, another edit, or the tag set back as read: the file is the form, then the bytes after the dropped chunks. The 4 rows that set the tag back failed without the adoption (F/r8/red-tag-212.log); its mutants in WAV and AIFF fail them (F/r8/results-tag8.txt).
…none (#184) ffmpeg muxes FLAC into Ogg with STREAMINFO total samples = 0, which RFC 9639 §8.2 defines as "the number of total samples is unknown". OggFlacFile then set Properties to default: a duration of 0, and a sample rate, channels and bits per sample of 0 too. The Ogg granule position, which carries the length, was never read. ffprobe, MediaInfo and mutagen read 2.0 s for a 2-second ffmpeg file. When STREAMINFO has no total, the duration now comes from the granule position of the header pages and the last page (OggWindow. DurationGranule), as Ogg Vorbis and Opus take it (#175): the stream read appends the last page to the header pages it reads, as theirs do, so every entry point reads the same value. A STREAMINFO total still wins. The sample rate, channels and bits per sample are STREAMINFO's even when the duration is unknown; TotalSamples stays STREAMINFO's value. A granule past TimeSpan is unknown (#181). Tests: OggDurationTests reads an Ogg FLAC file with total 0 and a last granule of 88,200 at 44.1 kHz on every entry point, with and without SkipPictures (DurationUnknownTests.Entries, ten): 2 s, 44,100 Hz, 2 channels, 16 bits. A file with a total keeps STREAMINFO's 1 s; one with no total and no granule keeps its sample rate, channels and bits. Red on the previous commit for all 20 rows of the two files without a total (duration 0, properties 0). Durations- UnknownTests gains an Ogg FLAC row with a granule of 2^62.
RFC 3533 §6 lets a page hold no packets: a muxer may end a stream with an end-of-stream page that only carries the final granule, 27 bytes long. OggPageHelper.FindLastGranulePosition walked pages while offset < Length - 27, one byte short of a page of exactly that length at the end, so the header pages' granule (0) stood. The review's emptyeos-base.opus, .ogg and .oga (the ffmpeg base files with the end of stream moved to such a page) read 0 on all eight entry points; ffprobe reads 2.0065 s, 2.0 s and 2.0 s, MediaInfo 2007, 2000 and 2000 ms. The bound is now offset <= Length - 27. Twins of the bound, found by sweeping every page and object walk: - The saves. RenumberAudioPages (the render) walked with the same bound, and CopyRenumberedPages (the path save) refused a tail under 28 bytes in both of its page reads, with a comment that said so: a save dropped the empty last page. Both now take 27 bytes as a page. - The Ogg FLAC packet walk (ExtractPacketsUntilAudio) tells audio by a FLAC frame sync, so a page with no packets right after the headers was taken for a header page, and a save of a file with no audio page dropped it. The first packet declares how many header packets follow it (the Ogg FLAC mapping, xiph.org/flac/ogg_mapping.html): after all of them, a page with no packets is the stream's (OggPageHelper.EndsOggFlacHeaders). The stream header reads ask the same rule (OggWindow.ShouldStop, which the SkipPictures read shares): a SkipPictures read rebuilds the header pages from their packets, so a page with no packets is gone before the packet walk could stop at it, and without the rule there a full read and a SkipPictures read of a file that declares fewer header packets than it holds disagreed (the byte-flip property test caught it at this commit). A declared count of 0 means unknown, and then nothing tells such a page from a header page that holds no packet; it stays with the headers, as before. - The ASF header walk, named apart in the CHANGELOG: AsfFile.MoreObjects, which the read and the picture skip share, stopped one byte short of an object that is only its 24-byte header at the end of the data. The render's own walk had the same bound; it now uses MoreObjects. Tests, red on the previous commit for 96 of 118 (the 20 rows of the unknown-count guard pass there and pin it against a mutant): - OggDurationTests.EmptyLastPage_CarriesTheDuration: Opus, Vorbis and Ogg FLAC files that end with a 27-byte end-of-stream page read 2 s on all ten entry points. - EmptyLastPage_IsKeptBySaves: that page, half a second after the audio page, survives a path save and a span save, sync and async, and the saved file reads 2.5 s; also as the only page after the headers, which the path save's first-page read takes, and which an Ogg FLAC header walk now tells from a header page by the declared count. - EmptyLastPageAlone_CarriesTheDuration: that page alone after the headers reads 2 s on all ten entry points. - OggFlacEmptyPageBeforeTheComment_KeepsTheComment: a page with no packets between the identification and comment pages, with a declared count of 1 and of 0 (unknown): the comment is read on all ten entry points. With the unknown count taken as known, the comment was lost (10 rows; a mutant, as the rule is new). - OggFlacEmptyPageAfterTheDeclaredHeaders_EndsThemOnEveryEntryPoint: a file that declares one header packet, then a padding block, a page with no packets and the comment: every entry point ends the headers at that page (no title, 1 s). Without the rule in the stream walks the four SkipPictures reads read the title. - AsfMalformedInputTests.HeaderWalk_ReadsAnObjectThatEndsTheData: the bound, both sides. - OggFlacFileTests: the zero-total test read its builder's 27-byte end page as absent; with the page read it takes that page's granule, as #184 says it should (71 samples).
…says (#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; SaveNeverThrowsTests found it at the count and at the first object's size): the walk stopped at the count, so the read did not see the objects after it, and a save, which rebuilds the header from the objects it walked, dropped them. On main. The header's objects are now the ones that fill its declared size, whatever the count says (AsfFile.MoreObjects no longer takes the count). The read of the bytes, the stream read and the SkipPictures copy walk to the header's end, so a count of 0 or 1 reads every object, and a read of the bytes no longer walks past the header into the file (with a header size that ends before the Content Description, it read the title where the stream read did not). A save carries every object across byte for byte, parsed or not, rebuilding only the two descriptions, and writes the count of the objects it wrote. 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 those bytes or write them twice after the rebuilt header: the save fails with "Cannot save an ASF file whose header objects do not fill its header." and writes nothing, from the bytes and from the source, sync and async. Render returns no bytes for such a file. This comes after #189, which also changed the header walk (its bound for an object of only a header that ends the header), so the two walks are one change apart; the #189 test of that bound now calls the walk without a count. Tests, red on the previous commit for 37 of 93: - AsfHeaderObjectsSaveTests: a WMA header of File Properties, Stream Properties, a Content Description and an unknown object, with a count of 0, 1, or 9 past the four objects, reads like the file with the right count on five entry points (10 failed), and saves to a path, from the bytes and in place, sync and async, carry every object byte for byte and the new title (12 failed). A header size 10 bytes into the unknown object, or 10 bytes of no object ending the header, reads as the file does and its saves fail and write nothing (12 failed). A header size that ends before the Content Description reads no title on any entry point (2 failed: the reads of the bytes). - SaveNeverThrowsTests: the ASF entry of Known (bytes 16, 24-27, 43-53) is gone; the property holds on those bytes (it failed). - Mutants of the read bound, the fill check and the streamed save's refusal fail them; the save's own bound on an object past the header is equivalent to the fill check that follows it (F/r6/mut/results-200.txt).
) RFC 3533 §6 sets the end-of-stream flag on "the last page of a logical bitstream". The readers' granule scan (FindLastGranulePosition over the header pages and the page the duration comes from, #175) preferred the granule of a page with that flag. Set on a header page, it made a full read report the header's granule, 0. A SkipPictures read rebuilds the header pages, without the flag, and reported the audio page's granule. The review's eoshead-base.opus (valid CRCs; ffprobe 2.0065 s) read 0 on four entry points and 2.0 s on the other four, on main as on the head. The scan only ever sees the header pages and one page after them, so the flag could only pick a header page over the audio granule. The scan no longer prefers it. The one-part overload, which only tests called once the readers took the two-part scan (#175), and its preference go: the class is internal, and its tests now run on the two-part scan, the one the readers use (the two that pinned the preference now pin the last page's granule). This lands before the step-back of #185 so that no commit is worse than its parent: on top of #185, a file with -1 pages at its end and the flag on a header page (eoshead-minus1.opus) read 0 on full reads and 1.9935 s on SkipPictures reads, where main read 0 on all eight. Tests, red on the previous commit for 13 of 43: - OggDurationTests.EndOfStreamOnAHeaderPage_DoesNotPickTheGranule: the Opus, Vorbis and Ogg FLAC files with the flag on header page 0 read 2 s on all ten entry points. Opus and Vorbis failed on the six full reads; Ogg FLAC's scan held no header pages yet. - OggPageHelperTests: the one-part scan's tests run on the two-part scan. FindLastGranulePosition_EndOfStreamPageBeforeTheLast_TakesTheLast (an end-of-stream page before a later page: 96,000, not 48,000) is the red one; the two that pinned the preference now pin the last page. - OggDurationGranuleTests.TwoPartScan_IsTheScanOfTheConcatenation now compares the two-part scan at every cut with itself uncut; the one-part scan it compared with is gone.
An Ogg Opus file whose tags page was broken (review 5's opus-tagspage.opus: one byte of page 2's capture pattern) read 2.0 s, and a save with no edit reported success and wrote its two header pages without the audio, 19,569 bytes to 103; an Ogg FLAC file did the same (tagspage-base.oga, 31,142 bytes to 79). Ogg Vorbis refused the save, because its header packets were not all found. On main too; and #185, which comes after this commit, makes 49 fuzzed Opus files (the s072-* of the grid corpus) readable on every entry point, where a save wrote the same 103 bytes. This commit comes first so that widening never meets a save that empties the file. One rule now decides for all three codecs (OggPageHelper.CarryAudioPages for the saves from memory, CopyRenumberedPages for the path saves): a save carries every audio page across, or fails with "Failed to render Ogg ... file" and writes nothing. - The page walk stops at the first bytes that are no page. If a readable page follows them (OggS, version 0, its segment table and body inside the file), the save would drop it and every page after it, so it fails. The path save's copy looks on from where it stopped in the stream it is reading, so a copy that reaches the end neither seeks nor asks for the length again (the OggSaveStreamsAudioTests pins hold), and no read asks for more than one maximum page. - The page the duration comes from (OggWindow.LastPage) must not lie among the header pages with a granule 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 that a header page's declared body runs over, and a save that rebuilds the header pages would drop it. The path save asks it of the header pages it read, which hold any page such a header page runs over. - OggWindow.ReadHeaders ends the header pages where a page cut short starts, as the packet walk does, so the path save copies from there and sees any page after it; it used to leave the stream at the end. Bytes after the last page that hold no page, and a last page cut short, are not audio: such a file saves as before, without them. A header packet cut off at the end of the file is refused by every codec, as Vorbis refused it (it needs all three header packets). Opus rebuilds OpusTags, so it needs only OpusHead: a file of OpusHead and a tags packet cut at the end (the seven s072 fuzz files that still saved: s072-012, -017, -022, -027, -042, -047 and -057; s072-032 ends the same way and was refused already) saved as OpusHead and a rebuilt tags page, dropping the cut bytes, and an Ogg FLAC path save left a cut header page out. One rule, which the packet walk tells: a header walk that has not finished its header packets and reaches the end of the file inside a page (OggPageHelper.IsPageCutShort: "OggS", as much of it as there is, version 0, and a header, segment table or body that runs past the end) or with a packet open has a header packet cut off. ScanPackets reports it (HeaderPacketsResult.HeaderCut), which Opus's render refuses; the stream header read (OggWindow.ReadHeaders) reports a cut page it leaves out of the header pages, which every path save refuses; a packet left open by the last whole page is in the header pages, so the render's own walk tells it. Bytes that are no page after OpusHead, or the end right after it, cut no packet and save as before, and so does a page cut in its own header once the header packets are read. Tests, red on the previous commit for 41 of 123: - OggAudioCarriedSaveTests: built Opus, Vorbis and Ogg FLAC files with four audio pages, in three shapes that would drop audio (the tags page's capture pattern broken; the audio pages as one more packet of the second header page; 100 bytes that are no page between two audio pages), saved to a path sync and async, from the bytes sync and async, and in place sync and async: each save fails with the codec's message, the source is unchanged and nothing is written (54 rows; 40 failed: every Opus row, Vorbis's two shapes past its header check, and Ogg FLAC's broken-capture and junk rows). Two shapes that keep the audio (100 bytes after the last page; a last page 10 bytes short), saved the same six ways, succeed and keep every whole audio page (36 rows). - SaveNeverThrowsTests: the Opus entry of Known (the tags page's capture pattern and header, bytes 47-50 and 70-74) is gone, and as it was the last, Known is empty; the property holds on those bytes (it failed: a listed byte that stops failing fails the test). - OggAudioCarriedSaveTests gains three shapes of a header packet cut off: the file ends 10 bytes into the second header page, 20 bytes into its own header, or after a page whose last packet goes on; each is saved the six ways by all three codecs and fails with the codec's message, leaves the source as it was and writes nothing. OpusHead then nothing, or ten bytes that are no page, saves; Opus and Vorbis headers then a page cut in its header save. 26 of 168 failed on this commit's first version (every Opus row of the three shapes, and Ogg FLAC's path and in-place rows of the two cut shapes). Mutants of the scan's two cases, the capture check, Opus's render, the path save and the stream read's two cases fail them (F/r6/mut/results-199b.txt).
A save of an Ogg Opus, Vorbis or FLAC file copied its whole audio pages and dropped the bytes after the last one: a last page the end of the file cuts short (a truncated download) and bytes that are no page. Review 6's cut-last.ogg, its last 50 bytes removed, read 2.0 s; a save wrote 7,011 of its 10,689 bytes, and the result read 1.0 s, because the cut page carries the final granule. The Opus twin went from 19,519 to 19,222 bytes. On main as well. Those bytes are now written after the pages as they were, as the bytes after a RIFF or IFF form are (#192, #197). The save from bytes (OggPageHelper.CarryAudioPages) appends them; the path save (CopyRenumberedPages) writes them as its scan for a page after them reads them, so it still neither seeks nor asks for the length again. #199's refusal is unchanged: a readable page after them still fails the save. When they start with a page cut short, the last whole page is not marked as the end of the stream, since the cut page holds that mark in the source; otherwise it is, as before. The path save reads the bytes after the last whole page even when they are fewer than a page header (27), so all six saves agree on that mark: it asked about no bytes there, and marked the page the save from bytes leaves unmarked (review 7, N1). The public RenumberAudioPages still returns the whole pages alone. Tests, red on the previous commit for 36 of 180: - OggAudioCarriedSaveTests: the two shapes that save (100 bytes that are no page after the last page, and a last page 10 bytes short), by all three codecs and the six saves, now end with those bytes as they were, read back with the source's duration, and mark the end of the stream on the last whole page only when no cut page follows (36 failed: every row). - OggSaveStreamsAudioTests: the path copy's no-seek and one-length tests compare it with CarryAudioPages, which writes the same bytes. - LastPageCutInItsHeader_EverySaveWritesTheSameBytes: the file cut 1 to 27 bytes into its last page's header, by all three codecs: the six saves write the same bytes, ending with the cut bytes as they were, and leave the last whole page unmarked. 78 of 81 failed before the path save read a short tail (cuts 1 to 26; F/r8/red-215-cut.log). - Mutants of each copy's tail and end-of-stream mark fail them (F/r7/results-215.txt).
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. OggWindow took the duration's granule from the header pages and the last page, so a stream whose last pages had a granule of -1 fell back to the header pages' 0: Opus, Ogg Vorbis and Ogg FLAC read with a duration of 0. ffprobe and mutagen step back to the last page with a granule position (2.0 s and 0.998 s for the crafted Opus and Vorbis files in durations/report.md). The page the duration comes from is now the last page whose granule is not -1. OggWindow.FindGranulePage scans back from the end for the rightmost "OggS" whose header fits, as #175's LastPage did, and steps back past each -1 page, reading one window of one maximum page at a time; the stream read sizes its buffer to the stream and skips what a short read did not return. The step back is bounded: the page must start within the last two maximum pages (StepBackBytes, 130,614 bytes), enough to step back past a -1 page of the largest size to the page before it. Past that the granule is unknown and the header pages' granule stands. Unbounded, a tail of junk with no "OggS" or a long run of -1 pages made an open read the whole file back to its headers. ffprobe, black-box, gives up sooner: a granule page more than about 64 KB from the end (64 KB of junk, twenty -1 pages of 4 KB, or one -1 page of 65 KB) reads as N/A. The span and stream reads share the scan (OggTail), so every entry point reads the same value (#175), and the Opus pre-skip still applies. Only that page's granule is used, and the pages a parse walks are the header pages alone: a stream read finds the granule page itself (ReadGranulePage) and passes it to the parse beside them. Appending the stepped-back page to the pages walked, the first try, put a copy of a header page after the header pages of 16 fuzzed Ogg files in the grid corpus (a comment packet over -1 pages, cut inside it), and their stream reads failed with "Invalid field N length". The last page that #175's stream reads appended to their header pages (ReadLastPage, LastPage) is gone: once the duration comes from the granule page nothing reads it, and it was a second tail scanner for one structure. Without it a stream read parses what ReadFromData parses up to the audio: in 49 fuzzed Opus files of the grid corpus (s072-*) whose comment packet is cut at the end of the header pages, the appended page ran into the packet, and on main the seven other entry points failed ("Invalid field 1 length") where ReadFromData read 395 s; all eight now read it alike. ffprobe rejects those files (CRC mismatch). Ogg FLAC's stream read again parses its header pages alone, as it did before #184, and takes the granule page beside them; its parse counts its header pages as Vorbis and Opus do. The scan sees no end-of-stream flag on a header page as the stream's end, and reads a 27-byte page at the end, since Tests: OggDurationTests reads Opus, Vorbis and Ogg FLAC files whose audio page (a FLAC frame sync, so Ogg FLAC's header read stops before it) gives 2 s, followed by one -1 page, by three, and by a -1 page longer than a window, on all ten entry points; and the same files with one -1 page and the end-of-stream flag on header page 0 (the review's eoshead-minus1.opus). Red on the previous commit for all 120 rows (0 s). Also: - GranulePage_IsThePageBeforeTheMinus1Pages: the stream and the span find the same page, and DurationGranule reads its granule. - StepBack_ReadsABoundedTail: a junk tail or a run of -1 pages of 1 MB and of 64 MB costs at most three maximum pages read and finds nothing. - StepBack_FindsAPageUpToItsBound: a page starting StepBackBytes from the end is found and one byte further is not, on the span and the stream alike (without the bound five of those six fail). - StepBack_LoadsEachWindowWithTheSegmentTableOfAPageAtItsEdge: a granule page that starts where the scan loads its next window, or up to 254 bytes below, with more segments than a window cut 27 bytes past that point would hold, is found (that mutant of the window end fails all three rows). - A stream that holds less than its Length says is scanned without reading past what it holds. - WindowedEdgeTests: the short-stream checks of the removed ReadLastPage now run on ReadGranulePage. #199's DurationPageBefore, which comes before this commit, now asks the page the duration comes from (FindGranulePage) instead of the last page.
A Matroska Tag with an empty Targets has a TargetTypeValue of 50 by default (RFC 9559 §5.1.8.1.1.1), so Album fell back to its TITLE (AllAt (AlbumLevel, "TITLE") in AlbumValues). ffprobe, exiftool and MediaInfo show that TITLE as the title and show no album. The Matroska test suite's test1.mkv read Album = Title = "Big Buck Bunny - test 1". Setting Title on such a file added a TITLE at target 30 and kept the old one, so Album still read the old title, and exiftool, which shows the first TITLE, still showed it. On main. - Album reads an explicit target-50 TITLE, then ffmpeg's ALBUM, and nothing else. A clear of the album touches an explicit album TITLE only: the untargeted TITLE stays where it is. - A new title replaces the untargeted TITLE in place, with a segment title too (the segment title is rewritten as before, or left out of a save where it does not fit, and either way no TITLE keeps the old title). It replaces the TITLE Title reads (the first default-language one) and the other untargeted TITLEs in that language (by BCP 47 tag, else TagLanguage); a TITLE in another language stays. When Title then reads the new title, nothing more is written, unless an explicit album TITLE could be the last TITLE ffprobe and MediaInfo meet: then the untargeted TITLE, every language with its nested sort, is copied to a new Tag at 30 after it. A narrower TITLE that shadows the untargeted one (at 30, or a part's at 40) is written as before. - An album edit keeps the title shown at 30 (KeepTrackTitle, #188) by copying the untargeted TITLE with its languages and nested sort, so the title and TitleSort read as before. - The sort nested in the untargeted TITLE is the title's: TitleSort reads and replaces it there, and AlbumSort no longer reads it (the album's TITLE parent is an explicit target-50 Tag). After an edit of test1.mkv, ffprobe, exiftool and MediaInfo all show the new title, with no album and no byte of the old title left. The same holds for review 8's 17 built shapes (F/r9/bb/readers-final.txt): after a title edit no reader, exiftool -a included, shows the old title and no byte of it is left, except a part's TITLE at 40 and an explicit album TITLE, which are their own targets' titles; MediaInfo shows the French TITLE of a two-language file, as it did before the edit. A second title edit on such a file keeps every language: when the TITLEs at 30 are the copy an earlier edit made (the untargeted TITLEs, in order, each with its language and nested tags), they take the untargeted TITLEs again where the copy was, so two edits write what one edit to the last title writes (review 9, nit). A TITLE at 30 of the file's own is written as before. The ARTIST twin is #245 (the write side) and #246 (the album-artist read), both held for v0.8.0 with the album-artist model; neither is on this branch. The rule for a file with a TITLE at 30 beside the untargeted TITLE: a title edit renames the untargeted TITLE in the language read, as above, and the TITLE at 30 takes the new title too, since Title reads it. A file's own TITLE at 30 equal to the untargeted one cannot be told from the copy an edit makes, so equal bytes get the copy's rule, and a fresh read of the file gives the same result. Measured on <-: TITLE=Same> <30: TITLE=Same>, both Tag orders, and on two different TITLEs (F/r11/bb/bb-221.txt): after Title = "New title", ffprobe, exiftool (plain and -a) and MediaInfo show only "New title", here and on round 9's head. On main, exiftool shows the old title on the first order and ffprobe and MediaInfo on the second, since main keeps the untargeted TITLE. Tests, red on the previous commit for 68 of 1,621 (F/r8/red-221.log): - Test1Mkv_UntargetedTitle_IsTheTitleOnly_AndANewTitleReplacesIt (corpus): Title is the title and Album null; a new title saved from each of the five entry points reads back with Album null and is the only TITLE in the file. - UntargetedTitle_AlbumClear_LeavesTheTitle: a built file, byte for byte unchanged. - UntargetedTitle_ItsSortIsTheTitleSort_NotTheAlbumSort and UntargetedTitle_ANewTitleSortReplacesItsNestedSort. - AlbumEdit_NeverChangesTheTitleReadersShow: the untargeted TITLE rows (write back, set title with album, clear album) and the rows with an explicit album TITLE beside it, where the old untargeted TITLE used to stay beside the new one. - Review 8 (F/r9/red-221.log; 38 of 1,656 failed on the first version of this commit): SegmentTitleAndUntargetedTitle_ANewTitleLeavesNoOld Title (a title that fits Info and one that does not, five entry points), UntargetedTitleInTwoLanguages and InTwoBcp47Languages, TwoUntargetedTitles_ANewTitleLeavesOne, UntargetedTitleBeforeAnAlbumTitle_ANewTitleIsAlsoTheLastTitle, AlbumEdit_KeepsTheTitleAndItsSort (set and clear, five entry points), and UntargetedTitleEdits_EverySaveWritesTheSameFile: six shapes, each saved to a path, a path async, from the bytes sync and async, and in place sync and async, which write the same file. - Mutants of the album fallback, the clear's guard, the in-place replace, the segment-title edit, the early return, the album TITLE copy at 30 and its sort, the language rule (all languages, no same- language copies, no BCP 47), the album edit's sort copy, the album sort's parent, and the title sort's read and write: 15, all killed (F/r9/results-221-final.txt). - Review 9's nit (F/r10/red-221-nit.log; 5 of 5 failed with the re-copy disabled): UntargetedTitleInTwoLanguagesBeforeAnAlbumTitle_ASecond EditKeepsTheOtherLanguage, five entry points, two edits on one object and an edit of the first save, and a seventh shape in the six-save parity test. - The second edit replaces the copy in one pass (the copy's TITLEs out by a set, the new ones in as a range): it went one TITLE at a time, a search and a removal through the Tag each, quadratic in the TITLEs a file holds (40,000 languages: 1,226 ms, now 79 ms). TitleEdit_ACopy InManyLanguages_IsLinearInThem bounds the SimpleTags visited (LevelSteps now counts them) at 10,000 and 40,000 (F/r13/red-scale.log; red on the previous source, where the count saw only Tags).
Read a Matroska file, set Title, save it over its source, then clear Title on the same object and save again: both saves report success, and the file still reads the title. On main. Root cause: a save leaves the Tags element as it is when the tags it renders equal a baseline taken at the read (MatroskaTag.MarkRead and IsAsRead). After a save over the source, the source holds the saved tags, but the baseline still holds the tags read. The clear renders the tags as read, so the save kept the Tags element of the first save. The shapes where the first save adds a Tag (a segment title only, as ffmpeg writes, an explicit target-50 TITLE, a Tag with a track UID) showed it for Title; every tag field showed it. Chapters have the same rule (IsModified compares with the chapters read), so an edit undone after a save, or a chapter or edition added, saved and removed, was not written. Pictures and the track enabled flag were already written: their changes are compared with the bytes being rewritten. - A save now compares the Tags element it renders with the one a read of the bytes it rewrites renders (MatroskaRewrite.TagsToWrite), and writes Chapters when they were edited or differ from the ones a read of those bytes renders (RenderChaptersIn). The bytes are the file the span saves are given and the source the path saves copy from, so all six save entry points follow one rule. The baseline is gone. - A save with no edit still leaves both elements byte for byte. For that the read model holds nothing random: a chapter read without a ChapterUID, or with 0, kept a random UID from the read, and WebM writes chapters from the model, so the object and a read of the bytes never agreed and every save of such a WebM file rewrote Chapters, differently each time (review 10, B1). The chapter now reads Uid 0 and is written as read: no ChapterUID, or the 0 it had. RFC 9559 section 5.1.7.1.4.1 makes ChapterUID mandatory and not 0, so when a save writes the chapter's own values changed (or the chapter new), it writes a UID drawn then. The draw is no part of the object: Uid stays as it was until a save over the source has written it, so a save that fails or goes elsewhere leaves the chapter as before, and the chapter's values alone decide whether it changed (review 11, N1: the UID used to be drawn while the save was planned and kept, so after a refused save, setting the edit back no longer undid it). Setting Uid to 0 means the same, no UID yet (it threw). Read-time randomness swept: editions keep a missing UID as 0 and write none; a new attachment's FileUID is drawn only for a picture that is added; track and tag reads draw nothing. - An empty Tag is kept only where the bytes a save rewrites hold the same empty Tag, one for one (MatroskaTag.RenderOver). A Tag the object read empty, filled and saved, then emptied by a clear, used to stay, where a fresh read of the saved file drops it (review 10, nit 1). - After a save that rewrote the source (checked by reading back what it wrote, as #179 does: the whole file for a span save, and for a path save the length and every element of the Segment it wrote but the Clusters, whose payloads it copied from the source), the object takes what it wrote as what it read: the Tags written (an emptied Tag gone), the segment title written with nothing pending, the pictures with nothing pending, and the chapters rebased in place (each edition and chapter keeps its object and values, takes the bytes written as its source and the UID written; what was read before is retired, so an edition or chapter the save did not write is one added in code again). A later save then writes what a fresh read of the saved file would: review 11's nit 1 (Album set, saved, cleared, saved, set again: the emptied Tag was reused) and nit 2 (a chapter added, saved, removed, saved: the edition went back as the bytes first read, such as ffmpeg's 8-byte sizes, where a fresh object re-serialises it). A save elsewhere leaves the object as it was. If the written chapters do not pair with the object's, they are left as they were, and the comparison with the bytes rewritten still holds. - One rule settles every pending edit: the object takes what it wrote only when the read-back found every element the save wrote, so each thing Adopt clears or rebases (the Tags, the segment title in Info, the pictures in Attachments, the chapters) is settled by its own bytes; the track flag is compared with the bytes on every save and Adopt leaves it alone. The path save's read-back first covered Info, Tags and Chapters only, so a save elsewhere that changed a picture by the same size (its data, media type or description) matched the source in length and in those three, Adopt cleared the picture edit, and the save over the source then left the old picture and reported success (review 12, B1). The read-back costs the size of the metadata, as the plan does, and streams in chunks. - A save is O(n log n) in the empty Tags a file holds, whatever they hold (the security review's findings). The empty Tags a save keeps are found in a multiset ordered by content (MatroskaTag.RenderOver, a SortedDictionary with ByteOrder: shorter first, then by the bytes), each Tag rendered once. They were found by a list search that rendered the Tag again for every entry, quadratic in the empty Tags (8,000 emptied track Tags before 8,000 empty ones: 29,416 ms, now 43 ms); and a first fix keyed them by an FNV-1a hash, unkeyed, so empty Tags whose TargetType collides under it (Joux's multicollision: chained colliding 4-byte blocks) made every lookup walk them all. An ordered structure needs no hash, and works the same on all four target frameworks. This commit's Chapters, Rebase pairing, Adopt and read-back visit each element a bounded number of times. The sweep's finds on main (the picture matching, the naming, the Tags read's missing budget) are #247. - A UID the library draws (a new chapter, edition or picture attachment) has its top bit set: 63 random bits, always 8 bytes wide, so the size of a save does not depend on the draw. RFC 9559 asks for a UID "as random as possible" and not 0 (section 5.1.6.1.5). Tests: MatroskaSecondSaveTests sweeps every settable MatroskaTag property (by reflection; a test fails if one of a type the sweep has no value for appears), chapter edits, pictures and the track flag, on seventeen shapes and all six saves: Matroska and WebM; chapters with and without a UID, a UID of 0, a nested chapter without one, ffmpeg's 8-byte sizes and an EditionUID of 0; no Tags, two Tags elements, Tags holding one or two empty Tags, an empty Tag before an untargeted TITLE, and an album TITLE before ffmpeg's Tag. On one object: set, save over the source, clear, save, set again, save. Each save must write what a fresh object writes: one read from the file the save before left, given the same edits, saved the same way, byte for byte. A chapter or edition added gets a fixed UID, and a chapter written without one gives the fresh object the UID it drew; an added picture's random FileUID (any width) is the one thing a fresh object cannot share, so those saves are compared by every value read. WebM refuses a picture on every save. After the clear, each value must be the one the original reads after the clear alone. SecondSave_NoEdit_LeavesTheFileAsItWas pins two saves with no edit, and SecondSave_TitleEdit_EverySaveWritesOneFile_AndKeepsTheChapters one file from the six saves with the file's Chapters element byte for byte. SecondSave_TwoEmptyTags_TheOneFilledThenClearedGoes, ReadChapters_ MissingOrZeroUid_ReadsAs0_AndAnEditWritesANewUid (it replaces ..._Gets ANonzeroUid, which pinned the random read UID; a render is no save, so the object has no UID after it), ChapterUid_0_IsNoUidYet_AndASaveGives One (the setter takes 0; the line pinning the throw is gone), SecondSave_AfterAFailedSave_AnEditSetBackLeavesTheFile, SecondSave_ AfterASaveElsewhere_AnEditSetBackLeavesTheSource, SecondSave_AnEdit SavedElsewhere_IsWrittenOverTheSource and SecondSave_AnEditSaved ElsewhereAndSetBack_LeavesTheSource (a picture's data, media type and description changed by the same size, the title and a chapter title by the same size, the track flag, and all at once, on all six saves, with a fresh-object oracle), NewPictureAttachments_HaveFileUidsEightBytes Wide, SecondSave_AfterA SaveOverTheSource_NothingIsPending, SecondSave_AfterAChaptersClearIs Saved_NothingIsPending and SecondSave_AnEditionEmptiedAndSaved_IsWritten AsNewWhenFilledAgain pin the rules above. The six large-cluster save tests now count two source length reads (the open, then the read-back), as AAC's and AIFF's do. Red on the previous commit: 266 of the 413 SecondSave tests (F/r10/red-244.log); with review 10's shapes, 179 of 988 (F/r11/red-244.log); with review 11's, 188 of 1,435 on the round 11 source (F/r12/red-244.log), 182 without the six count changes; with review 12's, 14 of 86 on the round 12 source (F/r13/red-244.log): the three same-size picture edits on the four path saves, and the two UID width tests. Black box (F/r10/bb/bb-244.txt): review 9's ffmpeg file, explicit-50- only and track-UID files, each read, titled, saved over its source, cleared on the same object and saved again. ffprobe, exiftool (plain and -a) and MediaInfo show no "New title", and no byte of it is left; the album TITLE and the track's TITLE stay as before the edits. Mutants of the Tags and Chapters comparisons, the staged bytes the span save compares, and the read of every Tags element: 4, all killed (F/r10/mutants.txt). Of the UID rule (a random UID at the read, no UID for a changed chapter, a UID always written, a 0 dropped) and the empty Tag rule (by the read, matched twice): 6, all killed (F/r11/mutants.txt). Of the adoption and the drawn UID (adoption off for tags or chapters, adoption without the read-back on either save path, a wrong offset in the path save's read-back, the UID drawn at the plan, the written UID not taken, the drawn UID kept, the segment title, pictures, edition list, clear and element flags left pending, the read bytes not retired): 14, all killed (F/r12/mutants.txt). Of the read-back's reach (Info, Tags and Chapters only; all but Attachments) and the UID width (attachments, chapters): 4, all killed (F/r13/mutants.txt). Save_ManyEmptyTags_IsNotQuadraticInThem (MatroskaTagScaleTests) bounds a step counter at N and 4N under a timeout; on the round 13 source it timed out at 60 s (F/r13/red-scale.log). Save_EmptyTagsThatCollideUnderFnv _IsNLogN builds 2^12 and 2^14 empty Tags that collide under FNV-1a and bounds the comparisons at 6x: on the hashed version, with its comparer counted, 33,566,720 for 4,096 and 536,920,064 for 16,384 (F/r14/red.log). Mutants of the multiset (not decremented, an empty Tag always kept): 2, killed (F/r13/mutants-scale.txt). Black box (F/r12/bb/bb-12.txt): review 11's scenario A passes (the refused rename set back saves, the file as it was, Uid 0); scenario B leaves the source as it was on cb, cc, cj and w4. Album set, saved, cleared, saved, set again, saved: every save writes what a fresh object writes on 15 files (round 9's b, b2, k, u; te; e1 to e10). A chapter added, saved, removed, saved: the same on ffmpeg's ff-chap.mka, ffv-chap.mkv, ffv-chap.webm and ff-chap.webm, and on ca, cc and cd.
…s, and bound the Tags read (#247) Two saves were quadratic in what a file holds, and the Tags reader had no bound on how many Tags and SimpleTags it models. All three are on main; #244's security sweep found them. - A picture found its attachment by a search through every attachment (MatroskaAttachments.FindMatch), so setting the pictures back on a file with many image attachments was quadratic in them (16,000 set back in the other order: 17,562 ms, now 42 ms). A picture now finds its own in a sorted index (PictureIndex): keys ordered by media type in any case, picture type, description, then the data (ByteOrder), sorted by a stable merge sort, found by binary search, each run of equal keys walked from where the last match left it. O(n log n) comparisons whatever the content: a first version keyed the index by an FNV-1a hash, and pictures whose data collide under it made each lookup walk them all. The rule is FindMatch's: the first unmatched attachment in file order with that media type, type, description (or none, read as its name) and data. - The FileUIDs a save keeps and draws, the UIDs of the pictures it removes, and the names it gives were in hash sets. A UID's hash is its two halves xor-ed, so (k << 32) | k all hash to 0, and a file of such attachments made every insert walk them (65,536 of them: 8,258 ms, now 267 ms). They are in ordered sets now, and the name counter in an ordered dictionary; the removed UIDs reach the Tags as an ISet<ulong>. - New pictures of one type were named by trying every number from _2 up for each, quadratic in them; each name now continues from the last number used. - A read models at most MatroskaTag.MaxEntries (65,536) Tags and SimpleTags, as MatroskaChapters.MaxEntries bounds chapters, and with its behaviour: the Tag elements past it are kept as their bytes, written back after the modelled ones, unread and unedited, and a save over the source carries them (MatroskaTag.Adopt). - A save never reports success for an edit a read of the saved file cannot show (review 13, N1). It used to write a Tag past the budget (a new Tag in a file at it, or a SimpleTag that pushed the last Tag read past it), report success, and leave the object and a fresh read without the value. Now the Tags render counts the Tags and SimpleTags it writes before the kept ones, and a save past MaxEntries fails with a result naming the budget; the file and the object's edits stay as they were. An edit that keeps the count (a value replaced in place) is saved. The twin in Chapters, on main: an added edition or chapter goes after the entries kept past the chapter budget, and an edit that writes more elements (a title on a chapter without a display, a display read without a language, which is written with the "eng" the read took, or a chapter without a UID, which draws one) pushes part of the last chapter read past it: a whole chapter, or only its title, language, times or flags. The read's budget counts every element, so it can stop inside a chapter, which is still read while its rest is kept as bytes (review 15, N1). MatroskaChapters.TryFitBudget reads back the Chapters a save would write and refuses the save unless that read holds every value the object does: each edition and chapter, each display, and each value set (UIDs, times, flags, strings, languages, countries; one at its default holds nothing). The items up to the last one read pair with the start of the read list and the ones added after it with the end, since a write puts the kept bytes between them, and the read may take some of those back when an edit made room. The cost is one pass over the modelled items. Four tests from main pinned the old success and change on purpose: SaveChapters_EditionsPastTheBudget_StayBeforeAnAddedEdition (now ..._AnEditionAddedPastTheBudget_IsRefused), ReadChapters_AtomsPastTheBudget_AreKeptAndWrittenBack (the added atom, and a UID edit that writes a start time too, are refused; a save without them leaves the file), ReadChapters_PastTheEntryLimit _AreKeptAsBytes (the title is refused; a start time is saved) and ReadChapters_DisplaysPastTheBudget_AreKeptAndWrittenBack (a title edit is saved when the displays have a language, and refused when they have none). Budget refusals: Save_AnEditPastTheTagsBudget_IsRefused (a TITLE in a new Tag, an ARTIST in the first Tag; six saves), Save_AValueReplacedInPlaceAtTheTagsBudget_IsSaved and Save_AnEditPastTheChaptersBudget_IsRefused (an added chapter, a title on a display without a language; six saves). With chapters as a muxer writes them (times, a display with a language): Save_ATitleOnThe ChapterTheReadStopsIn_IsRefused, Save_AnEditThatPushesPartOfTheLast ChapterPastTheBudget_IsRefused (its title, its language), Save_AChapterRemovedAndOneAddedAtTheChaptersBudget_IsRefused (with and without UIDs) and Save_AChapterEditThatFitsTheChaptersBudget_IsSaved (a rename, a removal, a chapter swapped in that the read now reaches), each on six saves; and the matrix Save_AtEachElementOfTheLastChapter Read_IsRefusedOrReadBack, which stops the read after each element of the last chapter or edition it reaches and pins both sides: one element more is refused, as many is saved and read back with every value. Red on the round 14 source (F/r15/red.log): 9 of 14, every refusal, the matrix and the changed main test; the round 14 version was red 6 of 13 (F/r14b/red.log). Mutants of the read-back comparison, each value it compares, the pairing and the count: 21, all killed (F/r15/mutants.txt). Tests (MatroskaTagScaleTests): Save_PicturesThatCollideUnderFnvSetBack _IsNLogN (2^11 and 2^13 pictures whose data collide under FNV-1a), Save_AttachmentsWhoseUidsShareAHashCode_IsNLogN (4,096 and 16,384 font attachments, UIDs (k << 32) | k), each bounding comparisons at 6x, and Save_OfTwoAlikeAttachments_TheFirstIsKept (file order among equal keys). Red on the hashed version (F/r14/red.log): the colliding pictures 2,098,176 steps for 2,048 and 33,558,528 for 8,192; the UID sets counted nothing (a HashSet's probes are its own; the timing above shows them). Save_ManyPicturesSetBack_IsNotQuadraticInThem (distinct and identical pictures) and Save_ManyNewPicturesOfOneType_ AreNotNamedInQuadraticTime bound a step counter (MatroskaAttachments.Steps) at N and 4N under a 60 s timeout; Read_TagsPastTheBudget_AreKeptAs TheirBytes, Read_ATagPastTheBudget_IsNotRead, Read_ATagPastTheBudgetOf SimpleTags_IsNotRead and Save_TagsPastTheBudget_StayThroughSavesOver TheSource pin the budget. Red on the round 13 source, with a stub for the two new names (F/r13/red-scale.log): the distinct pictures time out at 60 s, the identical pictures and the naming fail their counters, and the two budget reads fail. Mutants of the budget (none, Tags only), the kept Tags (not written, not adopted), the index (no cursor, no key for a missing description) and the numbering: 7, all killed (F/r13/mutants-scale.txt). Of the sorted index and the sets (byte order by length only, no cursor, a search past the run, an unstable sort, no description, the UID set uncounted): 6, all killed (F/r14/mutants.txt).
|
Review: 0 findings at 162a44f. What was checked:
History: 21 commits, one per issue or per group of closely related issues, so this is rebase-merged rather than squashed. |
Description
Fixes the save and duration bugs found while working on #157 (SkipPictures). After this, a save made after a save writes the right bytes, a damaged or unusual file reads an unknown duration rather than a wrong one, and a save that cannot keep every byte fails instead of dropping some. It also fixes Matroska title, save-after-save and scaling bugs.
Each issue has its own commit, or shares one with issues that are the same fix.
299527aca3c04990(#179)3eec724b(#202)3DIis there, so a footer flag with no footer no longer drops 10 bytes of audio.b4d85a4d(#204)aa017626(#181, #182, #193)TimeSpan, a DSDIFF chunk of 2^61 bytes or more, or a hostile ASF preroll reads as unknown. They read MaxValue, zero, a negative value or a wrapped value before.665b459a(#183, #191)AsfFileProperties.IsBroadcast.1c067141(#201)18dab687(#192, #197, #203)0xFFFFFFFFand on a FORM size smaller than the file. A WAV with more than 2 GB of sound can be saved. Tag chunks after the form are read and kept by one rule.471a08ee(#194, #198)d3e29093(#196)ba8cc13f(#212)66b0e4de(#184)5f723ae2(#189)2b7843f4(#200)a01faceb(#190)8fe8c86f(#199)5bc42b90(#215)285a2a21(#185)3824c1c9(#221)TITLEis the title alone, not the album too, and a title edit replaces it in place.42fe22fe(#244)ChapterUID(or 0) readsUid0 and is written as read. A UID the library draws is now always 8 bytes wide.162a44f9(#247)Motivation and Context
These turned up while working on #157 and in the reviews of #180 and #186. Behaviour was checked against ffprobe, exiftool and MediaInfo.
Fixes #179
Fixes #181
Fixes #182
Fixes #183
Fixes #184
Fixes #185
Fixes #189
Fixes #190
Fixes #191
Fixes #192
Fixes #193
Fixes #194
Fixes #196
Fixes #197
Fixes #198
Fixes #199
Fixes #200
Fixes #201
Fixes #202
Fixes #203
Fixes #204
Fixes #212
Fixes #215
Fixes #221
Fixes #244
Fixes #247
Related and still open, held for v0.8.0: #245 and #246, which need a decision on #186's Matroska album-artist model, and #248, hash-keyed sets of file values in other formats.
Type of Change
Behaviour callers may rely on that changes:
nullor zero).TITLEno longer reads asAlbum.MatroskaChapter.Uidaccepts 0, meaning no UID yet.ChapterUID, or UID 0, readsUidas 0. It used to read a random value. A save that changes the chapter gives it a new non-zero UID (RFC 9559 §5.1.7.1.4.1).Public API, from the snapshot:
AsfFileProperties.IsBroadcast.Checklist
dotnet format --verify-no-changespasses)dotnet test): see TestingImplementation guide (docs/IMPLEMENTATION-GUIDE.md)
Testing
At head
162a44f9, a Release build of all target frameworks has 0 warnings, anddotnet format --verify-no-changesis clean.