Repository navigation
feat: Read and write MPEG program streams and video elementary streams - #143
Merged
Merged
Conversation
Codecov Report❌ Patch coverage is Additional details and impacted files@@ Coverage Diff @@
## main #143 +/- ##
==========================================
+ Coverage 93.07% 93.12% +0.04%
==========================================
Files 298 310 +12
Lines 61380 63960 +2580
Branches 6067 6440 +373
==========================================
+ Hits 57129 59560 +2431
- Misses 2420 2536 +116
- Partials 1831 1864 +33 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
decriptor
force-pushed
the
feat/mpeg-ps
branch
2 times, most recently
from
November 22, 2026 01:52
227d654 to
eb0675f
Compare
MpegPsFile opens MPEG-1 system streams (ISO/IEC 11172-1), MPEG-2 program streams (ISO/IEC 13818-1) and MPEG-1/MPEG-2 video elementary streams. Only the first and last 256 KiB of the stream are read (4 MiB when those lack a codec header or a time stamp). Duration is the earliest PTS in the head to the latest PTS in the tail plus one access unit, modulo 2^33, with the first and last SCR as the fallback. An elementary stream counts pictures from its GOP time codes, drop-frame included, or divides its size by the sequence header's bit rate. Video size, frame rate and bit rate come from the sequence header and the MPEG-2 sequence extension. The first audio stream is MPEG audio, AC-3 (ATSC A/52), LPCM, or DTS in private_stream_1. The systems layer has no tag container. An ID3v2 tag in front of the stream and an ID3v1 tag after it are read and written, the tags exiftool reads there. Saving copies the stream bytes unchanged, and a save with no tag change writes the original bytes. A file that starts with ID3v2 followed by a pack or sequence header opens as MpegPs, not MP3.
…tream TagLib# tags .mpg files with an ID3v2.4 tag appended after the stream, before ID3v1, ending with the "3DI" footer that ID3v2.4 structure 3.4 requires for an appended tag. That tag was copied as stream bytes, so it was not read, and a save put a second ID3v2 tag in front with different values. The footer is now looked for from the back of the file (section 5), before ID3v1 or at the end, and also before an APEv2 tag, where section 5 places an appended tag. The appended tag is Id3v2Tag. A prepended tag it replaces is discarded on the first changed save; with the update flag set (3.2) the prepended tag fills the fields the update lacks and both are kept. A tag is written back where it was read: an appended tag stays appended, with a footer and no padding (3.3), so TagLib# still reads it. A v2.2 or v2.3 replacement goes in front. RenderId3v1 loses a branch no input reaches: a trailing ID3v1 tag is found only when it parses.
Each check gets an input it exists for: a tail stamp just before the start, an MPEG-2 PTS with a wrong prefix, 59.94 Hz drop-frame time code, a same-length original whose tag size differs, the all-ones MPEG-2 bit rate with extension bits, an ID3 header with version or revision 0xFF, a prepended v2.4 tag with a footer, and E-AC-3 in private_stream_1. The stream cap goes: keys are stream_ids and private_stream_1 sub-stream ids, so there are at most 323, and probes hold only head-window payload. A file with 100 sub-streams before its audio still reads that audio.
A footer is a v2.4 copy of the header with the footer flag set (ID3v2.4 structure 3.1, 3.4); a header that does not match, a v2.3 version, a missing footer flag, an APE header where an APE footer should be, or a size that reaches back into the prepended tag leaves the bytes as stream data. The APE length needs no bounds of its own: a length past the stream start finds no footer before it.
Reading the appended tag reordered RenderPrependedId3v2 so an unparsed prepended tag was kept even when the caller set a new tag to go in front. The unparsed bytes now stay only while no tag replaces them.
ID3v1 was taken from the last 128 bytes whenever they started with "TAG", before any footer was checked. An appended ID3v2 tag or an APEv2 tag that ends the file and holds "TAG" 128 bytes from the end was read as ID3v1, and a save wrote ID3v1 fields over the end of that tag or added a second ID3v2 tag in front. ID3v2.4 section 5 searches from the back of the file for a footer. A "3DI" footer with a matching header, or an APEv2 footer, at the end of the file now comes first, and only without one are the last 128 bytes ID3v1. One locator runs this search for the span, stream and async readers. The stream now ends at the first tag after it, including an APEv2 tag before the appended tag, and the head window ends there too. Pack and PES bytes inside a tag after a short stream no longer add audio or length. The update flag is a local of Build.
…aches The search ends on a flag rather than on a sentinel stream end. A tail that already holds the whole stream saw every stamp the head did, so it is not tested before the tail grows; an APEv2 footer before ID3v1 that reaches into the prepended tag gets a test.
…ream The trailer locator dropped the floor that the ID3v1 check had before it: when the last 128 bytes started inside the prepended ID3v2 tag with "TAG", ID3v1 was placed before the stream start, the span reader sliced a negative length and threw, and the stream readers rejected the file. ID3v1 now needs the 128 bytes to start at or after the stream, like every other tag the locator finds. Tests cover that file on the span, stream, async and ReadFromData paths, a cut tag-only file, and a property test that cuts and rewrites the last 300 bytes of six small fixtures (over 10,000 inputs) and checks that no reader throws, the readers agree, and a no-op render is byte-identical. The update test now has extended headers with only the CRC or restrictions flag, which are not updates (ID3v2.4 3.2).
The start check accepted a pack header with nothing after it when the bytes ran out. Since the reader sees the stream cut at the first tag after it, a pack header that ends the stream passed there while detection, which sees the ID3v1 bytes after it, rejected it: the span reader called the file a program stream and MediaFile called it MP3. A start code must now follow, as it always does in a real stream, so both give the same answer. The tail property test checks that the readers agree on the format.
decriptor
force-pushed
the
feat/mpeg-ps
branch
from
November 22, 2026 02:09
eb0675f to
71f9305
Compare
Owner
Author
|
Review: 0 findings at 71f9305. What was checked:
|
8 of 10 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
MpegPsFileandMediaFormat.MpegPsfor MPEG-1 system streams, MPEG-2 program streams, and MPEG-1/MPEG-2 video elementary streams (.mpg,.mpeg,.mpe,.vob,.mpv,.m1v,.m2v).MpegFrameparser, AC-3 (sample rate, bit rate, channels, LFE), LPCM (sample rate, sample size, channels). DTS is identified only.MediaTypes,IMediaFile.AudioPropertiesandIMediaFile.VideoPropertiesare all filled in.Read(span),ReadFromFile,ReadFromFileAsync,MediaFile.Read(path|stream)andReadAsyncall share that logic. A 5 GB sparse stream is opened after reading under 2 MiB (test).3DIfooter, per §5: a footer or an APEv2 footer that ends the file is checked before the last 128 bytes are taken for ID3v1; the appended tag may also sit before ID3v1 or before an APEv2 tag; the layout TagLib# writes), and an ID3v1 tag, behind aCombinedTagview (ID3v2 wins; a write goes to every tag). Per ID3v2.4 §5 an appended tag replaces a prepended one unless its extended header has the update flag, in which case the prepended tag supplies the missing fields. Each tag is saved where it was read, so a TagLib#-tagged file keeps one ID3v2 tag at the end; a v2.2/v2.3 replacement, which cannot carry a footer, goes in front. A save copies the stream bytes unchanged. A save with no tag change is byte-identical, including foreign tag layouts (an ID3v2.3 tag with no padding, an ID3v1 tag padded with spaces) and an ID3v2 tag of a version we do not parse.00 00 01 BAwith valid pack marker bits and a start code after the header, or00 00 01 B3with a non-reserved sequence header. Up to 16 leading zero bytes are allowed. This check runs after the MP4ftypcheck. An ID3v2 tag followed by a pack or sequence header isMpegPs, not MP3, both for in-memory data and on the stream path: the 32-byte peek holds only the tag header, so the stream path reads the bytes after the tag. Without a matching file signature, the extensions.mpg .mpeg .mpe .vob .mpv .m1v .m2vmap toMpegPs.Motivation and Context
TagLib# 2.3 reads and writes these files. TagLibSharp2 reported them as unknown.
Closes #108
Spec references (cited in the XML docs)
'0010', SCR, mux_rate), 2.4.3.3 packet header (stuffing, STD buffer, PTS/DTS)'01', SCR base/extension, pack_stuffing_length), 2.4.3.7 PES header, Table 2-22 stream_ids without a PES header extension, 2.7.4 PTS intervalDesign decisions
Which tags. I checked what other tools read from a PS, black-box, using ffmpeg-generated MPEG-1 and MPEG-2 (
-f mpeg,-f vob,-f dvd) files with ID3v2 in front, ID3v1 at the end, APEv2 at the end, and combinations:-v error -f null)So ID3v2 and ID3v1 are read and written. A new tag is ID3v2, in front.
TagLib# 2.3 itself (black box) tags a
.mpgas stream, [APEv2], ID3v2.4 with a3DIfooter, ID3v1. Only TagLib# reads that appended tag (exiftool, mutagen and ffprobe do not), and TagLib# throwsCorruptFileException: Marker not foundon a file with a prepended ID3v2 tag plus ID3v1. So an appended tag is rewritten in place (v2.4, footer, no padding per §3.3), not moved to the front. Checked onTurning Lime.mpgtagged by TagLib# (ID3v2+ID3v1, APE+ID3v2+ID3v1, ID3v2 alone at the end, and a file with a stale prepended tag): after our save there is exactly oneID3and one3DI, TagLib# reads our new title,ffmpeg -v erroris clean, framemd5 is unchanged, and an unchanged save is byte-identical. TagLib# still shows its own APE title on the APE file: APE is not read or written here. An APEv2 tag between the stream and ID3v1 is kept byte-for-byte but not read, because no tool tested reads it. exiftool cannot write MPEG at all (Writing of MPEG files is not yet supported). The Turning Lime sample has no tags.Two ffmpeg limits found while testing, documented in the remarks:
slice too small). The default is ID3v2 only, and ID3v1 is written only when the file already has one or the caller setsId3v1Tag.Duration matches ffprobe's container duration exactly on 7 of the 9 program streams below. On
mpeg1.mpgit is 6.8 ms longer: our value is the true span from the first audio sample to the end of the last video frame. ffprobe reportsr_frame_rate=50/1for that MPEG-1 video and uses a half-length frame. LPCM frames add no length, so an LPCM file can read one packet short. That matches mediainfo, not ffprobe.Bit rate: if
bit_rate_valueis all ones and has no extension bits, it is reported as 0. That is the MPEG-1 code for a variable rate, and ffmpeg writes it for MPEG-2 when it has no peak rate. ffprobe reports N/A for that value. In all other cases it is the header's value (a peak for VBR). The elementary-stream fallback (stream size divided by bit rate) is used only when GOP time codes are unusable.Out of scope: reading or writing APEv2 in a PS (only TagLib# reads it; it is kept byte-for-byte); H.264 or other video carried in a PS via a program stream map (properties stay null); DTS and LPCM last-packet length; MPEG-TS (a different container).
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(rebased on main 304bc06): net8.0 4813 passed / 18 skipped / 0 failed; net10.0 4813 passed / 18 skipped / 0 failed. The skips are the existing env-gated integration tests plus the 5 new ones.dotnet format --verify-no-changes: cleanMediaFormat.MpegPs = 16appended)Unit tests build every structure in code with
MpegPsTestBuilder(no media committed):ftypandfreeboxes whose size spells00 00 01 BAMalformed input: every truncation of four sample files, every byte replaced by 00/01/BA/FF, packet lengths past the end, an oversized ID3v2 claim, and 4 MiB floods of pack, GOP and picture start codes (linear time). The format is also added to
ScanWithoutAudioTests: a 1 MiB payload stays unread on sync and async reads and saves.I reverted guards one at a time to confirm the tests go red: the post-pack start-code check, the mod-2^33 span, the earliest-head-PTS minimum, the stream-path ID3 check, keeping the original tag bytes, window growth, the pictures after the last GOP, the original-length check, the frame-length end, and the AC-3 LFE bit. Each one fails at least one test.
MpegPsGuardTestsadds one test per remaining check (tail stamp just before the start, MPEG-2 PTS prefix, 59.94 Hz drop-frame, same-length original, all-ones bit-rate extension, ID3 version/revision 0xFF, prepended footer, E-AC-3 bsid), andMpegPsAppendedTagTestscovers every check on the appended footer (header match, v2.4 only, footer flag, floor, APE header vs footer). The 64-stream cap is gone: keys are bounded (323) and probes hold only head payload; a file with 100 private sub-streams before its audio now reads that audio.Real files (TagLib#
Turning Lime.mpgandcorrupt/a.mpg, plus ffmpeg 9.0.2 output from lavfi sources):-f mpegmpeg1video+mp2-f vobmpeg2video+ac3-f dvd(NAV packs)-f vobpcm_dvd 48k/16-f vobpcm_dvd 48k/24 2ch, 96k/16 2ch-f mpeg-f vob+ ac3,-f mpeg+ mp2-f mpeg1video.mpv-f mpeg2video.m2v 1080 29.97-timecode 01:00:00;00drop-frameAfter every save (title + artist set through
MpegPsFile.ReadFromFile+SaveToFile) on 11 of those files, covering PS, VOB, DVD, LPCM, HD, audio-only,.mpv,.m2v, and pre-tagged ID3v2+ID3v1 and APE+ID3v1:ffmpeg -v error -i out -f null -: no output.ffmpeg -f framemd5of the original and the saved file: identical.mpeg/mpegvideo.Removing both tags from a tagged VOB gives back the untagged original exactly.
Env-gated integration tests (
MpegPsIntegrationTests,TAGLIBSHARP2_TEST_MPEGPSandTAGLIBSHARP2_TEST_MPEGVIDEO) were run locally on net8.0 and net10.0 against Turning Lime.mpg, the VOB, the tagged VOB, and the HD MPEG-1 PS, each paired with .m2v/.mpv files: 5/5 passed every time.Additional Notes
Found while sweeping twins, not changed here:
Mp3File.Rendermeasures the audio end from the currentHasId3v1Tag. So settingId3v1Tag = nullon an MP3 that had one leaves the old 128-byte tag in the output; I confirmed this with a 962-byte file that still ends inTAGafter the removal.MpegPsFilerecords the original layout instead. That fix belongs in its own PR.