Repository navigation
feat: Read files without their pictures (#157) - #180
Merged
Merged
Conversation
Kit.Corpus.Sample looks a file up under the roots in TAGLIBSHARP2_TEST_CORPUS: the root itself, or a TagLib# checkout's tests/TaglibSharp.Tests/samples. A test whose file is in no root is inconclusive, so CI, which has no corpus, skips it. The roots are split on Path.PathSeparator, so a Windows drive letter no longer splits a root. MakerNoteByteTests uses the helper instead of its own copy.
A DSDIFF chunk size is a 64-bit unsigned count (DSDIFF 1.5 §2). The stream read of a .dff file added it to the position as a signed number, so a size of 2^64 - 12 or 2^64 - 13 put the chunk's end back on the chunk. MediaFile.Read of a path or stream then never finished. A "DSD " or "DST " chunk of that size also appended its header on every pass, so memory grew until the process died. ReadFromData and DffFile.Read, which parse the whole file in memory, returned. The size is now compared with the bytes left in the file before it is added. A chunk that does not fit ends past the file, so every branch of the walk stops there and every pass advances by at least a chunk header. The stream read also used to move every sound chunk header to the end of its copy. When a later chunk ran past the file, or a second sound chunk was present, the parser then stopped at a different chunk than a read of the whole file does. The two reads reported different durations, compression, or even "missing DSD or DST audio data chunk". The headers now stay in place, and one parser reads both copies. It passes over a sound chunk the walk did not copy by its header alone. DffChunkSizeTests reads a minimal file plus one such chunk (COMT, DSD, DST, ID3; sizes FFFFFFFFFFFFFFF4, FFFFFFFFFFFFFFF3, 8000000000000000) in a child process, through DffFile.Read, a stream, a path and ReadFromData, and requires the four results to match. On 88dfbe3, four rows time out, two run out of memory and two disagree. Fixes #177
ISO 14496-12 §4.2 lets any box contain boxes and sets no limit, and the file controls how deep they go. Mp4BoxParser.ParseBox and ParseChildren recursed once per nested container box, and each level copied its whole payload. A moov > udta chain 100,000 deep ran out of memory at about 500 levels, or overflowed the stack at about 1,600, and a stack overflow ends the host process. The save's chunk-offset walk (PatchChunkOffsets and WalkBoxes) and its track-layout walk (CollectTrackLayout) recursed the same way down trak and mdia. All three now follow containers to Mp4BoxParser.MaxContainerDepth (32) levels. A container nested deeper is kept as its bytes: no reader looks inside it, and it renders exactly as it was read. The boxes the library reads sit at most a few levels down. ParseBox copies the box it is asked for once. Every box under it is a view of that copy, and Mp4Box.Data copies a box's bytes only when it is read. NestingDepthTests no longer lists mp4-udta and mp4-track-layout as known overflows, so their 100,000-level rows run: span, stream, async and path reads, an edit, a save and a reread, in a child process with a 1 GiB heap. On 88dfbe3 both rows fail with OutOfMemoryException. Fixes #174
MediaFile.ReadFromData threw OverflowException out of the read for a malformed 315-byte Opus file, while a path or stream read of the same bytes succeeded. The in-memory read took the granule position from the end-of-stream page anywhere in the file, about 2^63 here, and TimeSpan.FromSeconds threw. A stream read holds only the header pages and the last page, so it took the granule from those. OggWindow.DurationGranule is now the one rule for Opus and Ogg Vorbis: the header pages the packet scan consumed, plus the page that ends the file (OggWindow.LastPage, the search ReadLastPage already did). Every entry point reads the same pages and reports the same duration. The scan reads the two in place, so an in-memory read does not copy header pages that hold a cover. A duration past TimeSpan.MaxValue now saturates at TimeSpan.MaxValue, through Durations.FromSeconds, instead of throwing. That is what the MP4 reader and DSDIFF already did; they now use the same helper. It applies to AudioProperties.FromOpus, FromVorbis and FromFlac, Ogg FLAC, Monkey's Audio, Musepack and DSF, where a 64-bit sample count could overflow. DsfAudioProperties no longer catches the OverflowException itself. DurationOverflowTests reads the file from the issue through a stream, a path, ReadFromData and OggOpusFile.Read, and requires one answer. It does the same for an Ogg Vorbis and an Opus file with an end-of-stream page before the last page, and checks the three factories with a sample count of 2^64 - 1. It reads a built Monkey's Audio, Musepack and DSF file whose sample count is past TimeSpan.MaxValue through the same four entry points, and requires TimeSpan.MaxValue from each. On 88dfbe3 these seven rows fail with OverflowException. OggDurationGranuleTests pins the in-place scan: it allocates under 1 KB for 8 MB of header pages, reads what a scan of the joined bytes reads at every cut point, and takes a header page's granule when the last page has none. Fixes #175
A path or stream read of a DSF or DFF file leaves the sound on disk, and
Render did not read it back. The DSF render threw ArgumentNullException
from inside Array.Copy. The DFF render threw InvalidOperationException
("no original data available"). Every other format renders after a path
read.
Render now reads the source file through RenderSource.Read and renders
from it: the same bytes a path save writes. After a stream read there is
no source to read, and when the source can no longer be read Render
throws InvalidOperationException that says so. The render uses the array
the file system returned, without copying it. The DSF render works on a
span of it, and the DFF render sizes its stream for the result, so it
does not grow by doubling. Neither copies its result again into the
BinaryData it returns.
The DSF render checks that its source holds the sound the read found.
Render throws InvalidOperationException when it does not. SaveToFile
(path, span) and SaveToFileAsync (path, memory) return the same message
as a failure result and write nothing. On 88dfbe3 these saves threw
ArgumentException from Array.Copy. The DFF span saves already turned a
render error into a failure result. A span of another length that still
holds some sound is #178.
DsdRenderTests, for DSF and DFF:
- edits the title of a path read and renders it; the render must equal
the render of ReadFromData with the same edit, and the bytes SaveToFile
writes;
- requires a clear InvalidOperationException after a stream read,
after the source is deleted, and (DSF) after the source is cut short;
- bounds what a path render allocates beside the file at 1 MiB and
4 MiB of sound: 1.1 times the file for DSF, 2.1 for DFF. Before this
change the render allocated 4.0 and 6.0 times the file. An odd-length
DFF file with no ID3 chunk and a tag of odd length stays within the
same bound, so the stream is sized for both pad bytes;
- saves a tagged and an untagged DSF file, read by stream and by path,
sync and async, from a span that ends before the sound, and requires
the failure result and no output. On the previous commit all eight
rows throw ArgumentException.
DsfSaveStreamsAudioTests now expects the failure result for an empty
span.
Fixes #176
SaveToFile (path, span) and SaveToFileAsync (path, memory) take the payload from the bytes passed in, whatever read made the file. DSF, DFF, FLAC, Ogg Vorbis, Opus, Ogg FLAC, MP3, AAC, Monkey's Audio, Musepack, WavPack, AVI, Audible and ASF did not check those bytes. Most reported success and wrote whatever part of the payload the bytes held: an empty span wrote an empty ASF file, a DFF file with no sound, and an MP3, AAC, Monkey's Audio, Musepack or WavPack file of its tags alone. The rule: the bytes must be a file the object describes. One Core type, SourceLength, holds those files' lengths and answers Refuse. Each of the 15 formats (MPEG-PS's own length field, comparison and message fold into it) has one Source property and calls Refuse from both overloads. - A read records the length of the file it read, once, where it knows it: Read (span) records the span's length, and a stream reader the stream's. The parse a stream reader runs over part of the stream (Parse) records nothing, so MediaFile no longer corrects a length afterwards. - Ogg Vorbis, Opus, Ogg FLAC, Monkey's Audio, Musepack, WavPack, AVI, ASF and DFF parse the bytes they save from, so after a successful save (span or path, sync or async, over the source or elsewhere) they also describe the file they wrote. A save from the bytes of an earlier save writes what a fresh read of those bytes writes, as on 88dfbe3. DSF does the same unless the save gave a file with no ID3 tag one: its sound then runs to the metadata offset, which the object does not have. - MP3, FLAC, AAC and MPEG-PS keep the offsets of the file they read (the ID3 tag size, the metadata size, the stream's extent), so they describe only that file. On 88dfbe3 a save from an earlier save's bytes wrote a damaged MP3 (1,001 bytes of audio lost for a 7-byte title change) and a different FLAC and AAC file. It now fails and writes nothing. MPEG-PS refused it already; its message is now the shared one. - Audible describes the file it saved over its source in place of the one it read, as it did. - A DSF or DFF file read from memory holds its bytes and saves them, whatever bytes are passed, as on 88dfbe3. The check compares lengths: another file of the same length passes. Render (span) is unchanged. MP4 and Matroska are left as they are: their save parses the bytes it is given as a file of its own and rejects bytes it cannot rewrite. Tests, on files built in the test (SpanSaveKit), 18 fixtures: the 15 formats, plus a Musepack SV7, a RIFF-wrapped WavPack and an untagged DSF; the MP3 is long enough for the read's prefix and tail windows. - SpanSaveSourceTests and DsdSpanSaveTests: each read (stream, path, data, async stream, async path, the format's own ReadFromFile and ReadFromFileAsync, and for DSD its own stream reader, seekable and not) saved, sync and async, from an empty span, one byte short, one long and half the file: each fails with the message and writes nothing; the whole file saves what a save of an in-memory read writes. - EarlierSaveTests: a first save by span or path, sync or async, elsewhere or over the source; then a save from the bytes it wrote, and one from the bytes it was read from. The second save writes what a fresh read of those bytes with the same edit writes, or, for MP3, FLAC, AAC, MPEG-PS, an untagged DSF given a tag, and Audible saved elsewhere, fails with the message and writes nothing. A failed save adds no file; a refusal names the files the object describes. On the previous commit 936 wrong-span rows fail (702 report success). On this commit as first reviewed (dde5c0a4), with the read's length alone, 309 rows fail: 232 refuse an earlier save's bytes in the formats that describe what they save, 76 are MPEG-PS rows on its old message, and 1 is the message after saves. DsfSaveStreamsAudioTests expects the new message for an empty span, and DsdRenderTests no longer repeats the DSF rows that DsdSpanSaveTests covers. Fixes #178
…eaders Pull the decisions each reader makes while it walks a structure into one place, so a second walk of the same structure can call them instead of copying them. No reader changes what it returns. - ID3v2: Id3v2Tag.ExtendedHeaderLength and Id3v2Tag.NextFrame hold the extended-header rule and the frame-header rule of Read (padding, frame ID, size, the iTunes syncsafe size in v2.3, the empty frame). - APE: ApeTag.ItemBudgetError, MoreItems and CountMismatchError hold the item-region rules of Parse; AacTail.ItemsAreValid uses them. ApeTag.IsPictureItem is the rule the Pictures getter applies. - ASF: AsfFile.MoreObjects and ObjectContentSize hold the header-object walk; AsfExtendedContentDescription.DescriptorError and AsfMetadataRecord.TryMeasure hold the descriptor and record layouts; AsfPicture.IsPictureName is the WM/Picture name rule of AsfTag. - MP4: Mp4File measures boxes with Mp4BoxParser.TryMeasureAt, which rejects a size whose end does not fit a signed offset; the old stream measure returned a wrapped end that the caller then rejected. Mp4BoxParser.IsIsoMeta also takes the first bytes of a payload and its full length, so a walk that holds only those bytes decides the same way. Mp4ChapterCodec's depth limit is Mp4BoxParser.MaxContainerDepth. - Vorbis comment: MetadataBlockPictureProbe decides whether a METADATA_BLOCK_PICTURE value is a picture, reading the value once and keeping only the picture header's lengths. VorbisComment.Read decodes a value only when the probe accepts it. A test checks the probe against Convert.FromBase64String and FlacPicture.Read on generated values. - Matroska: AttachedFileInfo.IsPictureOf is the image-attachment rule.
MediaReadOptions.SkipPictures reads a file without its embedded pictures. MediaFile.Read, ReadAsync and ReadFromData take the options, and the existing overloads read every picture as before. A skip read returns what a full read returns once its pictures are cleared: Tag.Pictures is empty, IMediaFile.PicturesLoaded is false, and a file that a full read rejects is rejected with the same error. Every save of such a file fails with PictureSkip.SaveRefused and writes nothing; a disposed file still throws ObjectDisposedException first. Render stays available. A WAV, AIFF, DSF or DFF file read this way from memory or a stream keeps no copy of its sound, as a stream read keeps none, so its Render throws as it does after a stream read; the docs and the DSF/DFF message say to read it from a path. Each format's walk takes its decisions from the full reader's rules for that structure, through the functions the previous commit shares, and hands what it cannot walk to that reader unchanged: - ID3v2 (MP3, WAV, AIFF, DSF, DFF, raw AAC, MPEG-PS, AVI): the frames are walked with NextFrame and ExtendedHeaderLength, and APIC and PIC are left out. A whole-tag unsynchronisation is decoded while it is copied. Bytes that are not a tag are copied as they are. The size a full read reports as consumed is reported too. - APE (Monkey's Audio, WavPack, Musepack, raw AAC): a binary "Cover Art" item keeps its key with an empty value, so the items, their order and the count rules stay those of ApeTag.Parse. Only binary "Cover Art" items are dropped afterwards; text and locator items under such a key are kept. - ASF: WM/Picture descriptors are left out and WM/Picture records keep no data. An object a full read fails to parse is written so that it fails the same way, and every object ends at its declared size. - MP4: covr items and QuickTime artwork keys of an ilst are left out; the artwork keys are those Mp4QuickTimeKeys reads. A box that cannot be walked, or a truncated top-level box, is copied as it is, and so is a container nested past Mp4BoxParser.MaxContainerDepth, which the parser keeps as its bytes (#174). - FLAC: a PICTURE block keeps its header with length 0, and a cut block keeps its declared length. MetadataSize is the offset in the file. - Vorbis comments (FLAC, Ogg Vorbis, Opus, Ogg FLAC): one push walk, VorbisCommentFilter, replaces each field MetadataBlockPictureProbe takes for a picture by an empty field, so the count and every field index stay the same. A value that does not decode stays a text field. - Ogg: the header pages are taken by the loop of a full read, and a page cut short is not taken. The rebuilt packets share pages, the identification packet alone on the first, so they take no more pages than the original. Pages the packet scan would stop on and pages that leave a packet open at the end are read in full. The rebuilt pages go to the packet scan, which reads the same packets from them as from the original pages. - MP3: the window of a full read (tag, audio probe, ID3v1 footer) is read with the tag copied; a Xing or VBRI byte count is checked against the file as stored. - Matroska: image attachments, by AttachedFileInfo.IsPictureOf, are left out, and the render rewrites the Attachments element as a full read with its pictures cleared does. - The Audible cover is not read. PictureSkip.Forget then drops any picture a skip read still holds, through each format's picture rule. ReadFromData and a stream that cannot seek are walked the same way in memory, so they return what a stream read returns and keep no copy of a picture. DSDIFF: a chunk too long for one copy ends the walk before the ID3 chunk is copied, as it does on a full read.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Description
Adds
MediaReadOptions.SkipPictures, which reads a file without its embedded pictures (#157). It also fixes five bugs from main that this work ran into, each in its own commit (#174–#178).A skip read returns what a full read returns once its pictures are cleared:
Tag.Picturesis empty and the newIMediaFile.PicturesLoadedis false.PictureSkip.SaveRefusedand writes nothing.Renderstays unguarded.StillImageFile.PicturesLoadedis always true, because the image is the picture.Each format's skip walk takes its decisions from the full reader's rules for that structure, through walkers it shares with that reader: ID3v2, APE, ASF, MP4, the Vorbis comment list, FLAC blocks and Ogg pages. Anything it cannot walk goes to the full reader unchanged.
Motivation and Context
Fixes #157
Fixes #174
Fixes #175
Fixes #176
Fixes #177
Fixes #178
Type of Change
The breaking changes are listed in the CHANGELOG:
IMediaFilehas a newPicturesLoadedproperty.MediaFile.ReadAsync (path, default)andReadAsync (stream, default)no longer compile (CS0121). Passnull, or name the parameter.Checklist
dotnet test)Commits
Each commit builds in Release with 0 warnings, passes
dotnet format --verify-no-changes, and passes the net10.0 and net8.0 suites. Each one ships something on its own.test: Find real samples through one corpus helper: tests that need real files find them throughKit.Corpus, underTAGLIBSHARP2_TEST_CORPUS, and are inconclusive without it. A hard-coded local path is gone.fix: End the DFF chunk walk when a chunk size does not fit (#177): a 64-bit chunk size that wrapped the chunk end used to hang the path and stream reads.fix: Bound the nesting the MP4 reader follows (#174): deeply nested boxes used to overflow the stack. A box nested deeper than 32 levels is now kept as its bytes and saved as it was read.fix: Read the same Opus duration on every entry point (#175):ReadFromDataused to throwOverflowExceptionon malformed Opus files. A duration too long for aTimeSpannow reportsTimeSpan.MaxValue, as MP4 and DSDIFF already did.fix: Render a DSF or DFF file read from a path (#176):Renderused to throw after a path read. It now reads the sound from the source, and a path render holds the file once.fix: Fail a save from bytes that are not the file that was read (#178):SaveToFile (path, span)in 13 formats used to report success and write a short or empty file. One shared Core rule (SourceLength) now refuses bytes that are not a file the object describes: the file it read, or a file it has since saved. A save from an earlier save's bytes still works wherever main wrote it correctly. MP3, FLAC and AAC refuse it, because main wrote a damaged file there.refactor: Share the walk rules of the ID3, APE, ASF, MP4 and Vorbis readers: no change in behaviour.feat: Read files without their pictures (#157): the feature.Testing
Head totals:
TargetInvocationExceptionto the file's bytes ([Bug]: DSF and DFF Render throws after a path or stream read #176).Follow-ups