Skip to content

feat: Read and write MPEG program streams and video elementary streams - #143

Merged
decriptor merged 19 commits into
mainfrom
feat/mpeg-ps
Nov 22, 2026
Merged

decriptor merged 19 commits into
mainfrom
feat/mpeg-ps

Conversation

@decriptor

@decriptor decriptor commented Nov 21, 2026 •

Copy link
Copy Markdown
Owner

Description

Adds MpegPsFile and MediaFormat.MpegPs for MPEG-1 system streams, MPEG-2 program streams, and MPEG-1/MPEG-2 video elementary streams (.mpg, .mpeg, .mpe, .vob, .mpv, .m1v, .m2v).

  • Properties: systems version (1 for 11172-1, 2 for 13818-1), video version, width, height, frame rate (including the MPEG-2 size and frame-rate extensions), and the sequence header bit rate. The first audio stream is read too: MPEG audio through the existing MpegFrame parser, AC-3 (sample rate, bit rate, channels, LFE), LPCM (sample rate, sample size, channels). DTS is identified only. MediaTypes, IMediaFile.AudioProperties and IMediaFile.VideoProperties are all filled in.
  • Duration: runs from the earliest PTS in the head to the latest PTS in the tail, plus the length of the frame that last PTS stamps. The span is taken modulo 2^33, so one wrap is handled. Without a PTS, the first and last SCR are used. An elementary stream counts pictures: first GOP time code to last GOP time code (drop-frame included), plus the pictures after the last GOP header. When the time codes do not advance, it falls back to stream size / bit rate.
  • Stream bounds: the stream ends at the first tag after it (an appended ID3v2 tag, an APEv2 tag, including one just before the appended tag, or ID3v1), and both the head and the tail windows stop there, so pack-like bytes inside a tag never reach the scanner. Every trailing tag, ID3v1 included, must start at or after the stream, and the first pack header must be followed by a start code, so the reader and detection agree on very short streams. A property test cuts and rewrites the last 300 bytes of seven small fixtures (over 10,000 inputs) and checks that no reader throws and all agree.
  • Reads only the ends: the first and last 256 KiB of the stream. Either window grows once to 4 MiB if it lacks a codec header or a time stamp (13818-1 2.7.4 requires a PTS at least every 0.7 s). Read(span), ReadFromFile, ReadFromFileAsync, MediaFile.Read(path|stream) and ReadAsync all share that logic. A 5 GB sparse stream is opened after reading under 2 MiB (test).
  • Tags: an ID3v2 tag in front of the stream, an ID3v2.4 tag appended after it (found from the back of the file by its 3DI footer, 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 a CombinedTag view (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.
  • Detection: 00 00 01 BA with valid pack marker bits and a start code after the header, or 00 00 01 B3 with a non-reserved sequence header. Up to 16 leading zero bytes are allowed. This check runs after the MP4 ftyp check. An ID3v2 tag followed by a pack or sequence header is MpegPs, 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 .m2v map to MpegPs.

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)

  • ISO/IEC 11172-1 2.4.3.2 pack header ('0010', SCR, mux_rate), 2.4.3.3 packet header (stuffing, STD buffer, PTS/DTS)
  • ISO/IEC 13818-1 2.5.3.3 Table 2-33 pack header ('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 interval
  • ISO/IEC 11172-2 2.4.2.3 / 13818-2 6.2.2.1 sequence header (sizes, aspect, frame_rate_code, bit_rate_value, quantiser matrices), 13818-2 6.2.2.3 sequence extension, 6.2.2.6 / Table 6-11 GOP time_code, Table 6-4 frame rates
  • ATSC A/52 5.3 syncinfo/BSI (fscod, frmsizecod, acmod, lfeon)
  • ID3v2.4 structure 3.1 (a version this library does not parse is skipped and kept)

Design 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:

Tool ID3v2 in front ID3v1 at end APEv2 at end
exiftool 13.55 reads reads (when ID3v2 is also present) ignores
ffprobe 9.0.2 no tags shown, stream still detected no tags shown no tags shown
mediainfo no tags shown no tags shown no tags shown
ffmpeg decode (-v error -f null) clean clean on a PS clean

So ID3v2 and ID3v1 are read and written. A new tag is ID3v2, in front.

TagLib# 2.3 itself (black box) tags a .mpg as stream, [APEv2], ID3v2.4 with a 3DI footer, ID3v1. Only TagLib# reads that appended tag (exiftool, mutagen and ffprobe do not), and TagLib# throws CorruptFileException: Marker not found on 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 on Turning Lime.mpg tagged 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 one ID3 and one 3DI, TagLib# reads our new title, ffmpeg -v error is 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:

  • On a video elementary stream, a trailing ID3v1 tag is read as part of the last picture (slice too small). The default is ID3v2 only, and ID3v1 is written only when the file already has one or the caller sets Id3v1Tag.
  • ffmpeg probes about 1 MiB. An ID3v2 tag larger than ~1 MiB (1,000,000 bytes is fine, 1,100,000 is not) makes ffmpeg probe the file as MP3. This is not enforced. The doc says so.

Duration matches ffprobe's container duration exactly on 7 of the 9 program streams below. On mpeg1.mpg it 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 reports r_frame_rate=50/1 for 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_value is 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

  • New feature (non-breaking change that adds functionality)

Checklist

  • I have read the CONTRIBUTING guidelines
  • My code follows the project's code style
  • I have added tests that prove my fix/feature works
  • All new and existing tests pass (dotnet test)
  • I have updated documentation as needed
  • My changes generate no new warnings

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: clean
  • PublicApi snapshot updated (new types only; MediaFormat.MpegPs = 16 appended)

Unit tests build every structure in code with MpegPsTestBuilder (no media committed):

  • MPEG-1 and MPEG-2 packs (with stuffing), the system header, MPEG-1 and MPEG-2 PES headers, and the sequence header and extension
  • GOP time codes, including drop-frame across minute marks, MP2, AC-3 (every acmod plus LFE), and LPCM
  • PTS wrap between head and tail, SCR wrap, audio stamped before the first video stamp
  • window growth at either end, a stream cut mid-GOP whose sequence header is split across two PES packets
  • ID3-prefixed detection on both span and stream paths (sync and async), MP3-after-ID3 still MP3, MP4 ftyp and free boxes whose size spells 00 00 01 BA
  • save, unchanged save, removing tags, APE kept in place, the source changing between read and save, saving with no source

Malformed 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. MpegPsGuardTests adds 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), and MpegPsAppendedTagTests covers 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.mpg and corrupt/a.mpg, plus ffmpeg 9.0.2 output from lavfi sources):

File Kind Ours: duration / video / audio ffprobe duration mediainfo
Turning Lime.mpg MPEG-1 PS, MPEG-2 video 1.130911 s / 640x480 25 fps MPEG-2 / MP2 44.1k 2ch 128k 1.130911 1120 ms
corrupt/a.mpg (0 bytes) — failure result, no throw — —
-f mpeg mpeg1video+mp2 MPEG-1 PS 3.010911 / 352x288 25 / MP2 44.1k 2ch 3.004089 3004
-f vob mpeg2video+ac3 MPEG-2 PS 3.005333 / 720x576 25 / AC-3 48k 2ch 192k 3.005333 3008
-f dvd (NAV packs) MPEG-2 PS 2.976000 / 720x480 29.97 / MP2 48k 2.976000 3003
-f vob pcm_dvd 48k/16 MPEG-2 PS 3.000000 / LPCM 48k 1ch 16 bit 3.007622 3000
-f vob pcm_dvd 48k/24 2ch, 96k/16 2ch MPEG-2 PS 0.994 / 0.998767, LPCM fields match ffprobe 1.000956 / 1.003511 994 / 998
video-only / audio-only -f mpeg MPEG-1 PS 3.000000 / 3.000000 2.98 / 3.00 3000 / 3000
1080i 25 Mbit/s -f vob + ac3, -f mpeg + mp2 PS 4.009333 / 4.014022, 25000 kbps 4.009334 / 4.014023 4004 / 4008
-f mpeg1video .mpv ES 3.000000 (GOP time codes) 0.010640 3000
-f mpeg2video .m2v 1080 29.97 ES 3.003000 N/A 3003
70 s .m2v, non-drop and -timecode 01:00:00;00 drop-frame ES 70.003267 both N/A 70003

After 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:

  • The stream bytes between the tags are byte-identical (python comparison).
  • ffmpeg -v error -i out -f null -: no output.
  • ffmpeg -f framemd5 of the original and the saved file: identical.
  • ffprobe still reports mpeg / mpegvideo.
  • exiftool reads the new Title and Artist.
  • An unchanged re-save is byte-identical.

Removing both tags from a tagged VOB gives back the untagged original exactly.

Env-gated integration tests (MpegPsIntegrationTests, TAGLIBSHARP2_TEST_MPEGPS and TAGLIBSHARP2_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.Render measures the audio end from the current HasId3v1Tag. So setting Id3v1Tag = null on 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 in TAG after the removal. MpegPsFile records the original layout instead. That fix belongs in its own PR.

@codecov

codecov Bot commented Nov 21, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 93.73550% with 162 lines in your changes missing coverage. Please review.
✅ Project coverage is 93.12%. Comparing base (304bc06) to head (71f9305).

Files with missing lines Patch % Lines
.../TagLibSharp2.Tests/Mpeg/MpegPsIntegrationTests.cs 7.93% 58 Missing ⚠️
src/TagLibSharp2/Mpeg/MpegPsFile.cs 93.76% 15 Missing and 12 partials ⚠️
src/TagLibSharp2/Mpeg/MpegPsScanner.cs 93.90% 9 Missing and 13 partials ⚠️
tests/TagLibSharp2.Tests/Mpeg/MpegPsFileTests.cs 95.10% 21 Missing ⚠️
tests/TagLibSharp2.Tests/Mpeg/MpegPsTestBuilder.cs 96.21% 7 Missing and 3 partials ⚠️
src/TagLibSharp2/Mpeg/MpegVideoSequenceHeader.cs 92.52% 6 Missing and 2 partials ⚠️
...s/TagLibSharp2.Tests/Mpeg/MpegPsTinyStreamTests.cs 93.75% 3 Missing and 3 partials ⚠️
src/TagLibSharp2/Mpeg/Ac3SyncFrame.cs 90.90% 2 Missing and 1 partial ⚠️
src/TagLibSharp2/Core/MediaFile.cs 88.23% 0 Missing and 2 partials ⚠️
src/TagLibSharp2/Mpeg/MpegAudioProperties.cs 33.33% 1 Missing and 1 partial ⚠️
... and 2 more
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.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@decriptor
decriptor force-pushed the feat/mpeg-ps branch 2 times, most recently from 227d654 to eb0675f Compare November 22, 2026 01:52
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

Copy link
Copy Markdown
Owner Author

Review: 0 findings at 71f9305.

What was checked:

  • All four round-3 findings are fixed. Their pinning tests fail at 174d791 and pass at the head.
    • The ID3v1 floor (_length - Id3v1Size >= _floor) now applies to every trailer step.
    • The appended ID3v2 IsUpdate flag test follows ID3v2.4 §3.2.
    • README and comments are accurate.
  • The required start code after the first pack header follows the ISO/IEC 13818-1 program stream syntax. It changes nothing across a 101-file detection grid, a 579-file corpus and a 26×7 save matrix. The matrix stays byte-identical, apart from the overlapping-ID3v1 case, which now saves as intended.
  • About 205k inputs were fuzzed across six reader entry points, with 0 disagreements and 0 exceptions. Truncation at every trailer boundary throws nothing.
  • 39 targeted reverts were tried; every one turns the suite red except the two that earlier rounds accepted.
  • Release build: 0 warnings on all four frameworks.
  • Tests: net8.0 and net10.0 each 4813 passed / 18 skipped. Format, pack and the vulnerable-package scan are clean.
  • The env-gated real-file tests pass 5/5.
  • CI: 8/8 green, codecov patch 93.7%. The branch is up to date with main 304bc06.

@decriptor decriptor added the approved AI has reviewed and signed off label Nov 22, 2026
@decriptor
decriptor merged commit ebd6138 into main Nov 22, 2026
8 checks passed
@decriptor
decriptor deleted the feat/mpeg-ps branch November 22, 2026 02:49
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

approved AI has reviewed and signed off

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature]: Read and write MPEG program stream metadata

1 participant