Repository navigation
Conversation
Codecov Report❌ Patch coverage is Additional details and impacted files@@ Coverage Diff @@
## main #141 +/- ##
==========================================
+ Coverage 93.16% 93.20% +0.04%
==========================================
Files 382 392 +10
Lines 80902 83610 +2708
Branches 9096 9512 +416
==========================================
+ Hits 75369 77931 +2562
- Misses 3260 3356 +96
- Partials 2273 2323 +50 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
decriptor
force-pushed
the
feat/avi
branch
4 times, most recently
from
November 22, 2026 17:59
95c228a to
c495966
Compare
AviFile reads the RIFF 'AVI ' form, including OpenDML odml/indx and AVIX forms. Duration uses the dmlh total frames when present and the video stream's rate and scale. Tags come from every LIST INFO in the first form and from an ID32 (ID3v2) chunk. Saving never changes the movi sample bytes. New tags go into the tag and JUNK space before movi, so no offset changes. When they do not fit, the data moves and the RIFF size, absolute idx1 offsets, indx super index entries and standard index base offsets are shifted; the save is refused when an index cannot be verified first. An unchanged save writes the original bytes. Specifications: AVI RIFF File Reference (https://learn.microsoft.com/en-us/windows/win32/directshow/avi-riff-file-reference) and OpenDML AVI File Format Extensions 1.02.
The 32-byte peek decided whether to take the 4095-byte one by detecting with the file name. A known extension then always skipped the long peek, so an MP3 whose frames start past byte 32 failed as '.avi', '.wav' or '.mkv' while MediaFile.ReadFromData found it. The long-peek decision now uses the magic alone; the extension still breaks ties after it.
- A move now shifts a standard index's dwOffset entries when its qwBaseOffset stays before the moved data (AVISTDINDEX allows any base), checks each entry table fits its chunk, and refuses a field index it cannot patch entry by entry. - A changed INFO or ID3 chunk cut off by the end of the file becomes JUNK of the length present, so a cleared or removed value does not come back on the next read. - Tags go only into space between hdrl and movi; JUNK ahead of hdrl is left alone, since hdrl must be the first list. - Index values are judged against the original bytes when collected, so an entry that points before the moved data is never shifted. - INFO text is read as UTF-8 when it is valid UTF-8 (ffmpeg's encoding), else Latin-1, and written as UTF-8; an unchanged value keeps its bytes. WAV INFO stays Latin-1. - An unfinalized file (RIFF size 0xFFFFFFFF) reports no duration. - The chunk walk no longer builds a list or a string per chunk, and an in-place save reuses the bytes it re-read instead of copying them. - AviFile.ReadFromFile and ReadFromFileAsync read only the header and tag chunks, and MediaFile.ReadAsync uses the asynchronous reader.
…source buffer alone - INFO text follows MPIDS 1.0: a CSET chunk names the code page and its absence means ISO 8859-1. Reads honour CSET 65001, 0 and 28591; with no CSET, valid UTF-8 (what ffmpeg and TagLib# write) is read as UTF-8 and anything else as ISO 8859-1. A save writes an all-ASCII list plain with no CSET; anything else is written as UTF-8 with a CSET of code page 65001 before the list. An unchanged value keeps its bytes when they are ASCII or UTF-8. A rewritten list replaces the old CSET. - An in-place save writes into the re-read bytes only when they come from DefaultFileSystem; IFileSystem.ReadAllBytes does not promise a fresh array, and MockFileSystem returns the stored file itself. - Pin the overflow refusal for a dwOffset shifted relative to its base.
An INFO save re-encoded every non-ASCII value from its Latin-1 reading and replaced the file's CSET with 65001, so changing one ASCII field turned Shift-JIS, cp1252 or cp1251 text into mojibake. - A value the caller did not change now keeps its exact bytes. - Changed values are written in the file's declared code page when they all fit it (65001, 1252, 0/28591; ASCII only with no CSET or a code page this library does not encode), and the file's own CSET is written back in front of the list. - Otherwise the list becomes UTF-8 under a 65001 CSET, which is only done when every unchanged non-ASCII value is already UTF-8. A save that would have to rewrite another code page's text is refused, naming the field. - CSET 1252 and text with no CSET that is not UTF-8 are decoded as Windows-1252. - A cleared list leaves the CSET alone.
…ed and decoded A non-ASCII edit refused whenever an untouched value was non-ASCII and not UTF-8, even under CSET 1252, 28591 or 0, whose text is known. Such a value is now decoded with the declared code page and written as UTF-8 of the same text under CSET 65001. The save is refused only when the untouched text's code page is a guess (no CSET and not UTF-8), is not decoded here (932, 1251, ...), or holds a byte the declared code page leaves undefined (0x81 in 1252, 0x80-0x9F under CSET 0).
… in AVI saves - A CSET rewritten to 65001 keeps the file's wCountryCode, wLanguage and wDialect. MPIDS 1.0 reads zeros as USA and US English, so zeroing them made a German file declare US English. A file without a CSET, or with one too short to hold the codes, still gets zeros. - The Windows-1252 encoder no longer writes the five bytes CP1252.TXT leaves undefined (0x81, 0x8D, 0x8F, 0x90, 0x9D). Its decoder reads them as undefined, so the library refused a later edit of text it wrote; a value holding one of those code points now goes to UTF-8. - The refusal names its reason: no CSET and not UTF-8, a code page this library does not decode, or a byte the declared code page leaves undefined. Control characters in the value are shown escaped.
Owner
Author
|
Review: 0 findings at 39dc549. What was checked:
|
9 of 12 tasks
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
AviFile: read and write AVI (RIFFAVIform), including OpenDML files (odml/dmlh,indxsuper indexes,ix##standard indexes,RIFF 'AVIX'continuation forms).MediaFile.Readdetects it as the newMediaFormat.Avi(appended, so existing enum values are unchanged); a RIFFWAVEfile is still WAV, and.aviis the extension fallback.Properties
strhdwRate/dwScale times a frame count that isdmlhdwTotalFrames when present (OpenDML), else the videostrhdwLength, elseavihdwTotalFrames (first RIFF only). No rate falls back toavihdwMicroSecPerFrame. Audio-only files use the audio stream's length.VideoProperties): width and height from BITMAPINFOHEADER (absolute biHeight; falls back toavih), frame rate, and the biCompression FourCC as the codec (FMP4,XVID,MJPG,H264,I420...; BI_RGB isRGB).iavs(DV) is treated as video.AudioProperties, firstaudsstream): WAVEFORMATEX sample rate, channels, bits, bitrate (nAvgBytesPerSec), codec from wFormatTag (WAVE_FORMAT_EXTENSIBLE names its SubFormat), and the audio stream's own duration.Tags
InfoTag(RiffInfoTag, never null): everyLIST INFOin the first RIFF form, merged the same wayWavFiledoes (first list wins), in an AVI text mode ofRiff/RiffInfoTag(helpers inRiff/InfoText.cs). MPIDS 1.0 ("CSET (Character Set) Chunk") puts INFO text in the code page of the file'sCSETchunk; without one, or with code page 0, it is ISO 8859/1. ffmpeg and TagLib# write UTF-8 with no CSET; Windows tools write the ANSI code page. Reading: CSET 65001 is UTF-8, 1252 is Windows-1252, 0 and 28591 are ISO 8859-1; with no CSET, valid UTF-8 is UTF-8 and other text is Windows-1252 (as exiftool reads it); any other code page (932, 1251, ...) is read as a best effort. Writing keeps one invariant: a value the caller did not change keeps its exact bytes, and so its meaning under the file's CSET. Changed values are written in the file's code page when they all fit it (with no CSET, or a code page this library does not encode, only ASCII fits), and the file's own CSET (or its absence) is kept, written right before the list. When a changed value does not fit, the list becomes UTF-8 with a CSET of code page 65001 before it. Unchanged ASCII and UTF-8 values keep their bytes; unchanged text in a declared code page that is decoded exactly (CSET 1252, 28591, or 0 without a byte in its undefined columns 8 and 9) is written as UTF-8 of the same text, checked against .NET's own 1252/Latin-1 decoders. The save is refused, naming the field and the reason, only when an unchanged value's code page is a guess (no CSET and not UTF-8, e.g. cp1251 from VirtualDub), is not decoded here (Shift-JIS under CSET 932), or holds a byte its declared code page leaves undefined (0x81, 0x8D, 0x8F, 0x90, 0x9D in 1252; 0x80-0x9F under code page 0), so no untouched text is ever transcoded from a guess. The new 65001 CSET keeps the old CSET's country, language and dialect codes (zeros only when there was no full CSET). The 1252 encoder never writes the five undefined bytes, so whatever the encoder writes its decoder reads back as exact. A cleared list leaves the CSET alone. Readers on our output: ASCII and the file's own code page read as before in every tool; UTF-8 + CSET reads correctly in ffprobe, TagLib# and exiftool, and mediainfo ignores CSET (it shows ffmpeg's own UTF-8 files the same way). WAV INFO is unchanged (Latin-1).Id3v2Tag: anID32(orid3) chunk. AVI files in the wild do carry one: the taglib-sharpsample.avi(VirtualDubMod) hasID32next toLIST INFO,LIST MIDandIDVX. ffmpeg and mediainfo ignore it, so the unifiedTag(andMediaFileResult.Tag) is aCombinedTagwith INFO first, falling back to ID3v2 (sample.avi's album only lives there).Save design
Invariant: after any save, every
idx1and OpenDML index entry resolves to the same sample bytes it did before, and themovisample bytes are unchanged.JUNKchunks betweenhdrlandmovi(the AVI RIFF reference requireshdrlto be the first list, so JUNK ahead of it is never used); a run of adjacent ones is a slot. The new INFO list (plus ID3v2 chunk if it changed) goes into the first slot that holds it exactly or with room for a JUNK header; every other slot and any rewritten tag chunk elsewhere becomes JUNK of the same size. A changed tag chunk cut off by the end of the file becomes JUNK of the length present, so a cleared or removed value does not come back. ffmpeg reserves 1016 bytes of JUNK beforemovi, so ordinary edits never move data. The file length and every offset are unchanged.movi) grows by a delta rounded up toavihdwPaddingGranularity, leaving 1024 bytes of JUNK so the next edit fits in place. Everything after the slot shifts by delta, and every absolute offset pointing at or past the slot is patched: the first RIFF size,idx1dwChunkOffset when the index is absolute (detected from the first entry that names a chunk at movi-relative or file-absolute position; relative entries move withmoviand stay), eachindxsuper index qwOffset, and each standard/field/timed index: its qwBaseOffset when the base points at or past the slot, otherwise each dwOffset whose data moves (AVISTDINDEX: "qwBaseOffset + AVISTDINDEX_ENTRY.dwOffset gives the offset from the start of the file to the data", for any base). Each index is collected once even if two super index entries name it, and whether a value moves is decided from the original bytes, so an entry that points before the slot is never shifted. The move is refused, writing nothing, when it cannot be verified first: anidx1matching neither base, anindxof an unknown bIndexType, a super index count past its chunk or pointing at a non-index or into the rewritten space, a standard index whose entry table runs past its chunk, a field index whose base stays while its data moves (its second-field offsets are not patched), an offset that would overflow, a RIFF size past the file (which includes the 0xFFFFFFFF placeholder), or growth past 4 GiB/2 GiB limits. A tag that fits in place never needs those checks, so such files still save in place.DefaultFileSystem(a freshFile.ReadAllBytesarray; any otherIFileSystemmay hand back its own storage, so its bytes are copied first) (one file's worth; 1.16 GB file: peak RSS 1.21 GB, was 2.37 GB); a move needs a second copy. Files of 2 GiB or more cannot be saved yet (README, CHANGELOG and XML docs say so). Save goes throughAtomicFileWriter, like the sibling formats:SaveToFile(path, originalData),SaveToFile(path)/SaveToFile()re-readSourcePath, and async twins;Render(originalData)returns empty on refusal.Reading through
MediaFile.Read(path/stream),MediaFile.ReadAsync(asynchronous twin) andAviFile.ReadFromFile(Async)copies onlyLIST hdrl,LIST INFO,CSET(it decides how INFO decodes) and ID3 chunks of the first form;movi,idx1,JUNKandAVIXstay on disk (added toScanWithoutAudioTests). Every size from the file is clamped to the bytes present; tag/header chunks above 256 MiB are not read; the chunk walk is linear and allocates nothing per chunk (15 MiB of 2M empty chunks: read 0 MiB, save 1x the file). A file whose RIFF size is still the 0xFFFFFFFF streaming placeholder reports no duration, because its frame counts were never filled in.Detection fix in the same PR: the path/stream reader now takes the long 4095-byte peek whenever the 32-byte peek matches no magic, regardless of extension, so a mislabeled file (an MP3 named
.avi, and the pre-existing.wav/.mkvcases) is found by its content asReadFromDataalready did.Spec references
Clean room: implemented from those documents only; ffmpeg/ffprobe/mediainfo were used as black boxes to generate and check files.
Motivation and Context
Closes #107
Type of Change
Checklist
dotnet test)Testing
Gates (local, macOS):
dotnet build -c Release: 0 warnings, 0 errors (netstandard2.0, netstandard2.1, net8.0, net10.0)dotnet test -c Release: net8.0 6301 passed / 45 skipped, net10.0 6301 passed / 45 skipped after rebasing on main 7f7bcb7 (the skips are the existing env-gated tests plus the 4 AVI integration tests)dotnet format --verify-no-changes: cleanNew tests:
AviFileTests(properties, duration fallbacks, codecs, INFO/ID32, detection, stream vs byte read, every-prefix truncation),AviSaveTests(no-op, in place, slot selection incl. the 2-6 byte remainder boundary, clear, INFO aftermovi, move with relative/absoluteidx1, OpenDML super/standard index and AVIX shift, duplicate super entry, granularity, every refusal case, ID3 add/change/remove/unparsable, async/sync/source-path twins, every-prefix truncation), plus AVI entries inMalformedInputTests(incl. 200 rounds of random byte flips through a forced move),ScanWithoutAudioTests,WindowedEdgeTestsandSaveThroughReadFileSystemTests.AviTestBuilderwrites OpenDML files with AVIX; ffmpeg reads its output (b_odml: 75 frames, 3.0 s, decode clean). Every save test checks that each index entry resolves to the same bytes. Each of these reverts was applied alone and turned at least one test red: absolute idx1 patch, the 32-bit and 64-bit "points at or past the slot" checks, super index entry patch, per-entry dwOffset patch, base-offset shift, field-index refusal, entry-table bound, one-visit dedupe, overflow refusal (Fits), RIFF size past the file, cut-off tag reclaim, slots only after hdrl, JUNK-header slot rule, granularity, RIFF size write, no-op path, rewritten-chunk JUNK, UTF-8 write, unchanged-bytes reuse, unfinalized duration, and the magic-only peek. The in-place buffer reuse is pinned too: withMockFileSystem, saving to another path leaves the source file's bytes unchanged (sync and async). The per-entry dwOffset overflow refusal is pinned by a base-0 index entry near 0xFFFFFFFF. The encoding rules are pinned byAviInfoTextTests: a 36-cell matrix over {CSET none/0/28591/932/1252/65001} x {unchanged ASCII/UTF-8/legacy} x {changed ASCII/non-ASCII} where each cell keeps the untouched field's bytes and text, rewrites it as the same text in UTF-8 (declared and decodable code page, checked against .NET's decoder), or refuses, plus tests for text that fits the declared code page, padding kept on unchanged fields, a CSET written after the list moving in front of it, the file's own CSET (with country codes) written back, CSET 0/28591/65001/1252/932/short reads, and stream reads honouring CSET.Integration (
TAGLIBSHARP2_TEST_AVI, run locally for sample.avi, 12 ffmpeg AVIs (incl. piped/unfinalized, UTF-8, two-audio, negative-height RGB, AAC, 6-channel float) and the 1.16 GB OpenDML file on net10.0, and sample.avi and piped.avi on net8.0): read matches a byte read; unchanged save is byte-identical; a short title saves with all indexes resolving; an 8000-char comment forces a move and every index entry still resolves (an unfinalized file instead reports zero duration and refuses the move).Real files: properties
sample.avi(VirtualDubMod, XviD + MP3, INFO + ID32 + MID + IDVX)-reserve_index_space 65536indx+ 4ix##)Our
Durationis the video stream's duration; ffprobe's format duration is the longest stream (e.g. 4.04898 s for the mp3 file), and ourAudioProperties.Durationmatches that.Real files: saves
For every file above: unchanged save
cmp-identical; in-place title save keeps the size, ffprobe packet positions shift 0, ffprobe reads the new title; forced move (4000-char comment) shifts every packet by the same delta. In both casesffmpeg -v error -i out -f null -is clean,ffmpeg -map 0 -c copy -f framemd5is identical to the original for every packet, and an independent resolver (Python, readsidx1and everyindx/ix##entry) finds every entry pointing at a chunk with the same id, size and SHA-256.Also: a 600 MB prefix of the OpenDML file (truncated
movi, noidx1) saves a short title in place (41 bytes differ) and refuses a move with an error; truncations of sample.avi at 10 points and every taglib-sharpcorrupt/file read without exceptions (the corrupt files are not AVI and keep their existing results). An ffmpeg file with UTF-8 INFO values (Café ☕,Björk) keeps those bytes through a save of another field (ffprobe reads them unchanged).Additional Notes
Out of scope, deliberately:
IDVXand MovieIDLIST MIDtags are not parsed; they are kept byte-for-byte (noted in the migration guide).