Skip to content

decoder: handle MMCO 5 and gaps in frame_num - #2

Merged
oops1 merged 2 commits into
oops1:mainfrom
tannevaled:avkit-d1-mmco
Nov 10, 2026
Merged

oops1 merged 2 commits into
oops1:mainfrom
tannevaled:avkit-d1-mmco

Conversation

@tannevaled

Copy link
Copy Markdown
Contributor

What

Two decoder defects found by decoding the ITU-T H.264.1 conformance bitstreams
(AVCv1 set, 81 tried) and comparing every picture with ffmpeg and with the
suite's own reference yuv. Commit message has the details.

  1. memory_management_control_operation 5: the buffer was emptied but the
    picture kept its frame_num, the order-count / FrameNumOffset state was not
    restarted, and pictures waiting for output were not flushed first (new
    pictures with a restarted order count were output ahead of old ones).
  2. Gaps in frame_num (gaps_in_frame_num_value_allowed_flag) were not handled:
    the "non-existing" frames never entered the sliding window.

Evidence

Bitstream Before After
MR2_TANDBERG_E (POC type 2, MMCO 5) wrong from picture 30 300/300 match ffmpeg and the suite yuv
MR3_TANDBERG_B wrong from picture 84 300/300
MR4_TANDBERG_C (POC type 0, gaps, MMCO 5) wrong from picture 2 300/300
MR5_TANDBERG_C wrong from picture 15 300/300
the other 69 Baseline/Main frame-coded streams tried match still match

Reproduce: go run github.com/go-avkit/decode/tools/jvt@<ref> fetch/compare (see
https://github.com/go-avkit/decode), or decode the four zips from
https://www.itu.int/wftp3/av-arch/jvt-site/draft_conformance/AVCv1/ and compare
with the .yuv inside. The bitstreams are not added here because their
redistribution terms are not stated.

Tests

Unit tests for store with and without MMCO 5, fillGap on every branch
(including a 65536-wide gap bounded to max_num_ref_frames allocations and
order-count type 2 counters) and finishPicture output order.
go test ./internal/decoder passes. The full go test ./... hit a 10 minute
timeout in an encoder test (TestDeblockingDefaultsToTheOldStream) on a machine
at load 50; all other packages pass.

Not in this PR (seen while here)

  • Frame order count ignores delta_pic_order_cnt_bottom (frame POC should be
    min(top, bottom)).
  • Decoder errors for unsupported features are not exported as a sentinel
    (ErrUnsupported is in an internal package), so callers match on text.
  • Interlaced coding (PAFF/MBAFF) is refused; 5 suite streams need it.

….4.4)

Found by decoding the ITU-T H.264.1 conformance bitstreams MR2_TANDBERG_E,
MR3_TANDBERG_B, MR4_TANDBERG_C and MR5_TANDBERG_C (Baseline, multiple
reference frames, reordering, long-term references, MMCO) and comparing each
picture with ffmpeg and with the suite's own reference yuv. All four decoded
to the wrong pictures before this change and match both after it. The 73 other
Baseline/Main frame-coded streams tried matched before and still do.

Two defects:

1. memory_management_control_operation 5 was applied (the buffer is emptied)
   but nothing else of it was:
   - the picture kept its frame_num; section 7.4.3 infers 0, so every later
     picNum and the next picture's FrameNum wrap were measured from the wrong
     number (MR2: wrong pictures from the 31st on);
   - the order count and FrameNumOffset state were not restarted (8.2.1);
   - the pictures still waiting for output were not flushed first and the
     picture's order count was not reset to 0, so after the operation the
     minimum-order-count output picked new pictures ahead of old ones
     (MR4: pictures right, order wrong, from the 3rd output).
   store() now reports the operation and finishPicture drains the output
   queue, as for an IDR picture (C.4.4).

2. Gaps in frame_num (gaps_in_frame_num_value_allowed_flag) were not handled
   at all. fillGap inserts the "non-existing" short-term frames of 8.2.5.2
   through the sliding window, keeps PrevRefFrameNum, and carries the order
   count counters of types 1 and 2 across the gap. The frames borrow the
   nearest real reference's picture, are marked so operation 3 cannot mark
   that picture, and at most max_num_ref_frames of them are ever allocated
   however wide the gap, so a stream cannot make it allocate more.

Tests: store with and without MMCO 5, fillGap on every branch (no gap, gap,
wrap, not allowed, IDR, empty buffer, 65536-wide gap bounded, POC type 2
counters, operation 3 on a non-existing frame), and finishPicture ordering.
The conformance bitstreams are not committed (their redistribution terms are
not stated); the commands to reproduce are in the pull request.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
tannevaled added a commit to go-avkit/decode that referenced this pull request Nov 7, 2026
* .github/workflows/ci.yml: gofmt, 3 OS with race + exact coverage gate
  (tools/covergate), fuzz, govulncheck, amd64/arm64, 386, riscv64/loong64/
  ppc64le/s390x under qemu.
* testdata/jvt: ffmpeg framemd5 MD5s for 73 ITU-T H.264.1 AVCv1 streams;
  TestJVTConformance runs them when DECODE_JVT_DIR is set. MR2..MR5_TANDBERG
  are pendingUpstream (oops1/go.264#2).
* testdata/fuzz: seed corpus; Fuzz{ParseAVCC,DecodeSample,DecodeAnnexB}.
* testdata/real-files.txt: hashes of 5 real MP4/MKV files, 900 pictures each.
* tools/jvt: fetch, compare, diff, bits, file, clip, seeds.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
…MMCO 5

PicOrderCnt of a frame is Min(TopFieldOrderCnt, BottomFieldOrderCnt) (8-1),
but computePOC returned the top count only, ignoring delta_pic_order_cnt_bottom
(type 0, 8-5) and offset_for_top_to_bottom_field / delta_pic_order_cnt[1]
(type 1, 8-10). It now derives both and keeps them.

That lets operation 5 follow 8.2.1 and 8.2.1.1 exactly: tempPicOrderCnt =
Min(top, bottom) is taken off both counts, and the next picture starts from
PicOrderCntMsb 0 and prevPicOrderCntLsb = the rebased TopFieldOrderCnt (not
always 0: it is top - bottom when the bottom field comes first). The previous
commit set it to 0.

Tests: both counts for types 0 and 1, and the rebased lsb for deltas -3, 0, 2.
The conformance results are unchanged (MR2..MR5 and 4 others re-run).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
tannevaled added a commit to go-avkit/decode that referenced this pull request Nov 8, 2026
…(D1 of avkit#89) (#1)

* decode: H.264 decoder over avkit container samples, checked against ffmpeg

Package decode takes an avcC record (ISO/IEC 14496-15 5.3.3.1) or an avkit
container.TrackConfig plus length-prefixed samples, and returns pictures in
display order with their PTS, chroma format and bit depth. The decoding itself
is github.com/oops1/go.264 (BSD-2-Clause, pure Go), pinned at v1.12.0 and
forced onto its software path.

Resource bounds: MaxFrameMBs (default 36864) and MaxSampleBytes (default
64 MiB) are enforced before any buffer sized by the stream is allocated; a
bomb SPS is refused under a 256 MiB memory limit.

tools/ holds the oracle harness (jvt: download ITU-T H.264.1 streams, compare
every picture's MD5 with ffmpeg -f framemd5) and covergate, which reads the
cover profile itself instead of trusting a rounded percentage.

Refs go-avkit/avkit#89

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* decode: CI, conformance manifests, fuzz corpus, real-file hashes, README

* .github/workflows/ci.yml: gofmt, 3 OS with race + exact coverage gate
  (tools/covergate), fuzz, govulncheck, amd64/arm64, 386, riscv64/loong64/
  ppc64le/s390x under qemu.
* testdata/jvt: ffmpeg framemd5 MD5s for 73 ITU-T H.264.1 AVCv1 streams;
  TestJVTConformance runs them when DECODE_JVT_DIR is set. MR2..MR5_TANDBERG
  are pendingUpstream (oops1/go.264#2).
* testdata/fuzz: seed corpus; Fuzz{ParseAVCC,DecodeSample,DecodeAnnexB}.
* testdata/real-files.txt: hashes of 5 real MP4/MKV files, 900 pictures each.
* tools/jvt: fetch, compare, diff, bits, file, clip, seeds.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* ci: fix the Windows lane (CRLF in checked-out manifests) and govulncheck

* Windows checks text files out with CRLF, so every ffmpeg MD5 carried a
  trailing \r and no picture matched. Read the manifests tolerantly and mark
  testdata -text so the bytes are never rewritten.
* govulncheck v1.1.4 panics on Go 1.27.3 (x/tools/go/ssa: unexpected expr
  *ast.KeyValueExpr); use @latest as the org's tooling rule says.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* ci: run the test job's steps in bash

PowerShell on the Windows runner split `-coverprofile=cover.out` at the dot
("FAIL .out [setup failed]"). The first Windows failure (CRLF) was fixed in the
previous commit; this is the second.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* docs: cite only what was opened (H.264 PDF read; 14496-15 not opened)

Downloaded ITU-T H.264 (V16, 06/2026) and checked every clause cited against
it: 7.4.3, 8.2.1 (+8.2.1.1..8.2.1.3), 8.2.5.1..8.2.5.4, C.4.4 are right. Table
numbers and sub-clause numbers that were not opened (Table 6-1, Table A-1,
7.3.2.1.1) are dropped. ISO/IEC 14496-15 is paywalled: the avcC comments now
cite mp4ff's reader, which was opened, and the High-profile extension is read
for every profile except 66/77/88 as mp4ff does (it also covers 244).

Coverage was checked per function (`go tool cover -func`: every line 100.0%);
tools/covergate already fails on any statement block that never ran, which is
stricter than per function.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* docs: state what was found in ffmpeg and that the upstream fix now rebases exactly

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
@oops1
oops1 merged commit 3d9bf6b into oops1:main Nov 10, 2026
7 of 9 checks passed
tannevaled added a commit to go-avkit/h264 that referenced this pull request Nov 10, 2026
* TestJVTConformance took the stream to be NAME/NAME.ext; two archives name it
  otherwise (cabac_mot_frm0_full.zip holds camp_mot_frm0_full.26l), so CI, which
  fails on a missing stream, failed on them. It takes the largest file with a
  bitstream extension, as jvtfetch does. Locally 69 of 73 streams are bit-exact,
  4 pending the MMCO 5 fix (oops1/go.264#2).
* TestStartCodeStormStaysLinear and TestScannerCostIsLinearInTheInput compared
  a wall-clock time with a fixed bound, which the riscv64 lane under qemu
  exceeded (780 ms against 500 ms). They now compare the time for N bytes with
  the time for 4N: linear is about 4, the quadratic scanner they guard about 16.
tannevaled added a commit to go-avkit/h264 that referenced this pull request Nov 10, 2026
* decoder: import the decoding layer of oops1/go.264 v1.12.0

h264 read headers and derived the reference structure; it did not turn a
stream into pixels. This adds a decoder, as decided for go-avkit/decode#10:

* decoder/ is the public package (Decoder, Limits, Frame, errors); no hardware
  back end, no encoder.
* internal/{bits,cabac,cavlc,deblock,decoder,frame,level,loopfilter,mc,nal,
  parallel,pred,simd,syntax,transform,testutil} are go.264's packages of that
  name at commit 3373a3f (v1.12.0), import path rewritten, nothing else
  changed. Their tests come with them and pass under -race.
* LICENSE-go.264 keeps Valery Chukalin's BSD 2-Clause text; README says what was
  imported and from which commit.
* testdata/conformance (go.264's 35 x264 streams with their ffmpeg output),
  testdata/jvt (ffmpeg framemd5 manifests of 73 ITU-T H.264.1 streams).

Conformance: TestJVTConformance, 67 of 73 streams bit-exact against ffmpeg
framemd5 with the local copy of the vectors, 4 pending the MMCO 5 fix of
oops1/go.264#2 (the test fails if one starts to pass), 2 not downloaded here;
CI downloads all of them with tools/jvtfetch and sets H264_JVT_REQUIRE=1.

CI: the 100 % gate applies to the root package as before; the decoder runs
under -race on three OSes, on every architecture lane, in a conformance job and
in a fuzz job (FuzzDecode, FuzzStream).

* decoder: find a JVT stream whatever its name, judge linearity by ratio

* TestJVTConformance took the stream to be NAME/NAME.ext; two archives name it
  otherwise (cabac_mot_frm0_full.zip holds camp_mot_frm0_full.26l), so CI, which
  fails on a missing stream, failed on them. It takes the largest file with a
  bitstream extension, as jvtfetch does. Locally 69 of 73 streams are bit-exact,
  4 pending the MMCO 5 fix (oops1/go.264#2).
* TestStartCodeStormStaysLinear and TestScannerCostIsLinearInTheInput compared
  a wall-clock time with a fixed bound, which the riscv64 lane under qemu
  exceeded (780 ms against 500 ms). They now compare the time for N bytes with
  the time for 4N: linear is about 4, the quadratic scanner they guard about 16.

* jvtfetch: fetch eight archives at a time; CI tests the tools module

The sequential download of the 73 archives took about ten minutes in CI.
tannevaled added a commit to go-avkit/h264 that referenced this pull request Nov 10, 2026
… Frame is valid until the next call (#40)

Every decoded picture allocated and zeroed three planes (1.4 MB at 1280x720): 82 MB
of the 127 MB a 46-picture decode allocated, and about 10 % of its CPU in
madvise, memclr and page faults. The planes of a picture that was returned by an
earlier call and is neither a reference nor waiting to be output now go to a free
list (bounded at 34) and serve the next picture of that size.

This is a change of contract, stated on decoder.Frame: a Frame is valid until the
next call to Decode or Flush on the same Decoder. The internal decoder keeps the
old behaviour unless SetRecycle(true) (the public decoder sets it), so nothing
else that uses it changes. go-avkit/decode copies every picture out at once, so
it is unaffected. A macroblock a corrupt stream never states keeps the samples of
the picture that was there before instead of zero (documented in the README).

Checked: TestRecyclingChangesNoOutput decodes every conformance clip one access
unit per call with and without reuse and compares every picture;
TestRecyclingBoundsTheBytesAllocated requires less than half the bytes; 69 of 73
JVT streams stay bit-exact (4 pending oops1/go.264#2); race detector clean.
Timing deferred: load above 8 when written.

Needs a MINOR release (a documented lifetime is a contract change below v1).

Refs go-avkit/decode#10

🤖 Generated with [Claude Code](https://claude.com/claude-code)
tannevaled added a commit to go-avkit/h264 that referenced this pull request Nov 10, 2026
…s (step 2c)

The decoder parsed its streams with internal/syntax, a second implementation of
what the root package reads. It now uses the root: ParseSPS, ParsePPS (with PPSIDs
to pick its sequence set), SlicePPSID and ParseSliceReferences, whose DataBit says
where the macroblocks start.

* internal/decoder/header.go joins the two halves of a slice header into the one
  value the decoder uses, with the weight defaults filled in (an entry that states
  no weight weighs 2^denominator, offset 0).
* level, loopfilter and the decoder take h264.SPS, h264.PPS and h264.ChromaQP.
* The root keeps its stricter checks and gains the ones the decoder's reader had:
  seq_parameter_set_id <= 31, max_num_ref_frames <= 16, a picture at most 1024
  macroblocks across (read before the +1 that wraps), a crop that does not remove
  the picture (computed in 64 bits; the 32-bit difference could wrap).
* A parameter set the root refuses as unsupported surfaces as ErrUnsupported.
  Parameter sets still refer to each other as before: a picture set read before its
  sequence set is read as 8-bit 4:2:0, and one that states scaling lists needs it.

Checked: 69 of 73 JVT streams bit-exact against ffmpeg as before (4 pending
oops1/go.264#2); every test of ./... passes; the stream-building tests keep
internal/syntax's fixture writers and a converter (compat_test.go) until the
parsers there are removed (next step). Timing is deferred: slices are now
unescaped twice (once by the reader of the header, once for the macroblock data).

Refs go-avkit/decode#10

🤖 Generated with [Claude Code](https://claude.com/claude-code)
tannevaled added a commit to go-avkit/h264 that referenced this pull request Nov 10, 2026
…s (step 2c) (#44)

The decoder parsed its streams with internal/syntax, a second implementation of
what the root package reads. It now uses the root: ParseSPS, ParsePPS (with PPSIDs
to pick its sequence set), SlicePPSID and ParseSliceReferences, whose DataBit says
where the macroblocks start.

* internal/decoder/header.go joins the two halves of a slice header into the one
  value the decoder uses, with the weight defaults filled in (an entry that states
  no weight weighs 2^denominator, offset 0).
* level, loopfilter and the decoder take h264.SPS, h264.PPS and h264.ChromaQP.
* The root keeps its stricter checks and gains the ones the decoder's reader had:
  seq_parameter_set_id <= 31, max_num_ref_frames <= 16, a picture at most 1024
  macroblocks across (read before the +1 that wraps), a crop that does not remove
  the picture (computed in 64 bits; the 32-bit difference could wrap).
* A parameter set the root refuses as unsupported surfaces as ErrUnsupported.
  Parameter sets still refer to each other as before: a picture set read before its
  sequence set is read as 8-bit 4:2:0, and one that states scaling lists needs it.

Checked: 69 of 73 JVT streams bit-exact against ffmpeg as before (4 pending
oops1/go.264#2); every test of ./... passes; the stream-building tests keep
internal/syntax's fixture writers and a converter (compat_test.go) until the
parsers there are removed (next step). Timing is deferred: slices are now
unescaped twice (once by the reader of the header, once for the macroblock data).

Refs go-avkit/decode#10

🤖 Generated with [Claude Code](https://claude.com/claude-code)
tannevaled added a commit to go-avkit/h264 that referenced this pull request Nov 10, 2026
…es (step 2d)

internal/syntax was go.264's reader of the parameter sets and slice headers. The
decoder has read them with the root package since the previous step, so the second
reader goes:

* ParseSPS, ParsePPS, ParseSliceHeader, the VUI/HRD readers, the scaling list
  reader and the list resolution, the SEI reader and writer (nothing here uses
  SEI) and their tests are deleted.
* What stays is what tests need to build a stream: the structs and the writers
  (WriteSPS, WritePPS, WriteSliceHeader), as internal/syntaxfixture, which
  reads nothing. The stream-building decoder tests keep using it through
  compat_test.go.
* levelreorder_test patches level_idc in place (the third byte of the set) and
  reads the result with the root.
* The root keeps its 100 % gate: corpus_test.go reads every set and slice of the
  repository's streams (what the removed differential tests did against the old
  reader, which agreed field by field when it was replaced), and the set bounds
  of the previous step have tests at their edges.

JVT: 69 of 73 bit-exact, unchanged (4 pending oops1/go.264#2).

Refs go-avkit/decode#10

🤖 Generated with [Claude Code](https://claude.com/claude-code)
tannevaled added a commit to go-avkit/h264 that referenced this pull request Nov 10, 2026
…es (step 2d) (#45)

internal/syntax was go.264's reader of the parameter sets and slice headers. The
decoder has read them with the root package since the previous step, so the second
reader goes:

* ParseSPS, ParsePPS, ParseSliceHeader, the VUI/HRD readers, the scaling list
  reader and the list resolution, the SEI reader and writer (nothing here uses
  SEI) and their tests are deleted.
* What stays is what tests need to build a stream: the structs and the writers
  (WriteSPS, WritePPS, WriteSliceHeader), as internal/syntaxfixture, which
  reads nothing. The stream-building decoder tests keep using it through
  compat_test.go.
* levelreorder_test patches level_idc in place (the third byte of the set) and
  reads the result with the root.
* The root keeps its 100 % gate: corpus_test.go reads every set and slice of the
  repository's streams (what the removed differential tests did against the old
  reader, which agreed field by field when it was replaced), and the set bounds
  of the previous step have tests at their edges.

JVT: 69 of 73 bit-exact, unchanged (4 pending oops1/go.264#2).

Refs go-avkit/decode#10

🤖 Generated with [Claude Code](https://claude.com/claude-code)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants