forge
Explore
Log in

Don't you dare go Hollow

Commits

Commits on 682c080551bbe0ebee106d55c19fcc95b260a4f9Filtered to crates/ec-h264/src/decoder.rsClear filter

2026-08-23

feat(h264): code P_8x8, and count shapes as well as bitsAhmet Kaan Gümüş · 2b1c4a3
feat(h264): code P_8x8, and count shapes as well as bits

The encoder had no partition smaller than 8x16. It now codes P_8x8 with
four P_L0_8x8 sub-partitions, including the sub_mb_type writer both
entropy coders were missing.

The first measurement of it read flat, as had the split-gate sweep before
it, and a shape histogram said why: the partition search runs only at
Preset::Balanced, and the x264 comparison runs Preset::Fast by default,
so 1,200,000 macroblocks were coded whole and nothing was ever split.
Measured where the shapes are searched, P_8x8 is worth 0.005 dB BD-PSNR
on the film clip and 0.016 on the screen capture, with the optimum at
twelve bits of signalling on both.

The bit-exactness sweeps ran the default preset too, so no sub_mb_type
had ever faced another decoder: balanced_partitions_decode_bit_exactly
encodes at Balanced under CABAC and CAVLC, requires ffmpeg to reproduce
the reconstruction sample for sample, and requires every shape to appear.
The decoder now reports MbShapes alongside BitAccount, which puts our
partition mix next to x264's: we still split about half as often.
feat(h264): count CABAC bits by syntax class in the decoderAhmet Kaan Gümüş · 0723a49
feat(h264): count CABAC bits by syntax class in the decoder

The rate gate says how much we overspend against x264; it cannot say on
what. BitAccount marks the arithmetic decoder's position before and after
each syntax element and attributes the difference to one of eight classes,
so any conforming stream -- ours or x264's -- is measured by one
instrument. bit_account_vs_x264 encodes both, decodes both, prints the
table.

The answer is the same on all three sources: we spend fewer bits than
x264 on skip, mb_type and mvd, and more on residual luma, cbp+qp and
intra modes. x264 buys a cheaper residual by paying more for the motion
field. That points the next lane at prediction, not at entropy coding.
refactor(h264rd/r3): extract decoder bS derivation; inter trial deblocking rejectedAhmet Kaan Gümüş · d3d7ad4
refactor(h264rd/r3): extract decoder bS derivation; inter trial deblocking rejected

bs_side/bs_between extracted from boundary_strength (8.7.2.1 in one
place); ssd_mb_deblocked parametrised by a bs closure, intra trials pass
intra_bs. Output byte-identical to r2.

The chartered change — derived per-edge bS in the inter cost4/cost8
trial — regressed the 720p clip in all three measured variants
(+0.818/+0.794/+0.821 vs +0.827 dB BD-PSNR; obs flat): the trial's
pre-filter neighbour aprons make weak inter strengths (bS 1/2) model
noise. Reverted per charter; numbers in lanes/h264rd-r3.report.md.

2026-08-20

feat(h264-enc): Intra_8x8 prediction and the 8x8 transform for inter residuals, chosen on rate-distortion costAhmet Kaan Gümüş · 4e4673b
feat(h264-enc): Intra_8x8 prediction and the 8x8 transform for inter residuals, chosen on rate-distortion cost

transform_size_8x8_flag now follows a real decision: Intra_8x8 is coded
alongside Intra_4x4 and Intra_16x16 (decoder's filtered reference samples
and neighbour-mode rule), P macroblocks try both transform sizes on the
same prediction, and the residual writer takes the cat-5 / interleaved
path. Encoder::transform_8x8_mbs() counts what was chosen; the
reconstruction, ffmpeg and VA-API gates run with 8x8 macroblocks present.
fix(h264): drop leading pictures after a seek's open-GOP recovery pointAhmet Kaan Gümüş · 03dc6e9
fix(h264): drop leading pictures after a seek's open-GOP recovery point

Root cause (crates/ec-h264/src/dpb.rs, crates/ec-h264/src/decoder.rs;
mirrored in crates/ec-hw/src/dec/dpb264.rs, crates/ec-hw/src/dec/h264.rs):
an open-GOP I picture is not an IDR — it is a plain I slice whose
predecessors in decode order can still be referenced by pictures that
follow it. A decoder started fresh at that I (exactly what a seek does)
has none of those earlier references, so `build_ref_lists` pads the
missing entries with whatever it has. The old code decoded and output
those leading pictures anyway, handing back frames predicted from padded
(garbage) references before the stream ever reaches a picture whose
references are all real.

Annex D.2.8 defines a `recovery_point` SEI whose absence (the common
case, and this fixture's case) defaults `recovery_frame_cnt` to 0: the
recovery point is the RAP's own POC, i.e. only pictures with a POC at or
after the leading I's own POC are guaranteed fully referenced. The SEI
itself is deliberately not parsed — the default already gives the
correct threshold for the case that matters (mid-GOP seek), and a real
non-zero `recovery_frame_cnt` is out of scope for this fix.

`build_ref_lists` now returns whether it had to pad a list
((lists, padded)); `Decoder`/`H264Decoder` OR that per-slice into
`cur_ref_padded`/`Current::ref_padded`, latch the first post-reset
picture's POC into `recovery_poc` on `end_picture`/`finish_picture`, and
compute `output_ok = !(ref_padded && poc < recovery_poc)`. `Dpb::store`
takes that flag and marks the picture `Mark::Unused`-eligible for output
gating (`pic.output = output_ok`) — it still joins the DPB as a
reference and for bookkeeping, but a gated picture is never handed to a
caller. `reset_pictures` clears `recovery_poc` so a later seek gets its
own threshold.

New test `h264_seek_matches_linear_open_gop` in both suites drives this
through the real entry surface: fixtures/video/h264-open-gop.mp4
(x264 open-GOP, generated via scripts/gen-fixtures.sh) primes a fresh
decoder with the leading IDR's parameter sets, resets picture state (a
seek's exact contract), feeds it from the open-GOP I access unit before
display frame 30, and asserts the first decoded picture matches a linear
decode of frame 30. Confirmed failing before this fix (forcing
output_ok true reproduces the mismatch) and passing after, on both the
software decoder (crates/ec-h264/tests/conformance.rs) and the VA-API
path (crates/ec-hw/tests/gpu.rs, real hardware).

cargo test -p ec-h264: 70 lib + 23 conformance + 8 encode passed, 0
failed. cargo test -p ec-hw --test gpu -- --test-threads=1: 19 passed
(18 pre-existing + the new one), 0 failed.

2026-08-14

perf(h264): close the decode gap on inter contentAhmet Kaan Gümüş · 4cab1f0
perf(h264): close the decode gap on inter content

Instruction counts, single thread, measured with perf over whole streams:
1080p WEB-DL 100 frames 38.23G -> 30.02G (-21.5%), QCIF B streams
-47% and -29%. The changes, each measured on its own and kept only
where it paid:

- chroma interpolation takes a const-width kernel plus a full-sample
  copy path, so the 2x2 blocks that dominate real motion stop paying
  for eight lanes and four multiplies they discard;
- single-list, default-weight prediction interpolates straight into
  the picture at the picture's pitch, and declares no scratch at all;
- boundary strength is decided once per macroblock for all 24 internal
  edges (intra gives 3, no coefficients plus one motion vector gives 0)
  instead of 24 times from the block tables;
- the luma half-sample filter splits by partition width, because a
  16-lane vector is two SSE2 registers and half of it is thrown away
  for an 8- or 4-wide partition;
- a horizontal chroma edge deblocks as one 8-lane pass;
- the rounded average is written as the plain byte idiom the compiler
  turns into pavgb;
- an output frame is grown row by row rather than allocated zeroed;
- a direct-mode quadrant whose four 4x4 blocks derive the same motion
  compensates once as an 8x8 (interpolation is position-invariant, so
  this is bit-exact).

Reverted, measured worse: combining at the picture pitch (+6 to +9%),
blanket 8-lane luma taps (+2.2%), window slices for the deblock line
filters (+0.8%).

Conformance unchanged: 22 conformance tests and 55 unit tests green,
JVT full sequences and the real library sweep still bit-exact.
feat(h264): software encoder, I and P pictures, CAVLC, slice-parallelAhmet Kaan Gümüş · 6d22228
feat(h264): software encoder, I and P pictures, CAVLC, slice-parallel

The encoder shares the decoder's reconstruction rather than owning one:
prediction (pred, inter), dequantisation and the inverse transforms
(transform), the deblocking filter and the per-macroblock metadata are the
decoder's own code and the decoder's own Picture. What is new here is the
forward direction — forward transforms and quantisation (quant), CAVLC
writing derived at compile time from the decoder's tables (vlc), parameter
sets and slice headers (headers), mode decision and macroblock coding (mb),
and rate control (rc).

Scope: Baseline-profile syntax (8-bit 4:2:0 progressive, CAVLC, one
reference, pic_order_cnt_type 2), intra 16x16 and 4x4 with chroma modes,
P_Skip and P_L0_16x16 with a diamond search to quarter sample, and CBR
rate control with a per-macroblock-row correction. Coding a picture as one
slice per worker gives the parallelism inside the encoder: a slice is
independent by definition, so every worker owns its picture buffer and its
bitstream, and the bands are stitched and filtered once at the end.

B pictures and CABAC are not coded yet; the bframes field is accepted and
coded as zero rather than refused.
feat(h264): High-profile 8x8 transform, both entropy codersAhmet Kaan Gümüş · 49bb32e
feat(h264): High-profile 8x8 transform, both entropy coders

transform_size_8x8_flag (7.3.5) in the intra and inter positions with
the neighbour context of 9.3.3.1.1.10, Intra_8x8 prediction with the
reference sample filter of 8.3.2.2.1, the 8x8 residual under CAVLC
(four interleaved 4x4 blocks) and CABAC (ctxBlockCat 5, ctxIdx 402..435
transcribed from Table 9-24, no coded_block_flag), the 8x8 scaling and
inverse transform of 8.5.13 with the 8x8 scaling lists, and the 8.7
rule that an 8x8 macroblock has no transform edge at luma 4 or 12.

This is what real content needs: every H.264 file in the library that
is not Main profile uses it, so eight of twelve were refused by name
before and all twelve now decode 500 frames bit-exactly against ffmpeg.
The MP4 whose Annex B extraction ffmpeg itself could only decode three
frames of is demuxed by ec-mp4 instead, which restores the oracle.

Coverage: 51 quantisers x both coders all-intra, P and B sequences with
and without sub-8x8 partitions, and a parameter-set assertion so an
encoder silently dropping back to 4x4 cannot make the sweep vacuous.
fix(h264): colZeroFlag reads the co-located block's own reference indexAhmet Kaan Gümüş · b5f5ec8
fix(h264): colZeroFlag reads the co-located block's own reference index

Spatial direct prediction (8.4.1.2.2) zeroes a motion vector when the
co-located block sits still on a short-term picture referencing entry 0
of that picture's list. The index that decides it is refIdxCol, of the
list clause 8.4.1.2.1 selected; accepting "either index is 0" instead
zeroes vectors that must keep their prediction whenever the co-located
block is bi-predicted with a non-zero list 0 index.

That only happens when the co-located picture is itself a coded B
picture, which is the first B of every run under a B pyramid: two real
1080p library files decoded with localized wrong regions in exactly
those pictures and nowhere else. The new test reproduces it with
b-pyramid and four references, and fails on the previous reading.
feat(h264): display-order output reaches the packet entry surfaceAhmet Kaan Gümüş · 5a58bb1
feat(h264): display-order output reaches the packet entry surface

A player never touches the NAL-level API, so the reordering has to arrive
at H264Decoder: packets in, frames out, timestamps travelling with their
pictures rather than with the packets that carried them.

packet_entry_surface_reorders_and_carries_timestamps drives exactly that
path — one access unit per packet, frames pulled with receive_frame —
and proves three things at once: every frame is bit-exact against
ffmpeg, the output order is a real permutation of the packet order, and
the tag on each emitted frame identifies the packet whose picture it
actually is (checked against the same stream decoded in decode order).

Also: the crate description now states the scope it reached, the debug
tracing added while chasing the inter defects is gone, and clippy and
rustfmt are clean.
test(h264): B pictures, display order, frame_num gaps, zero-alloc on BAhmet Kaan Gümüş · 6e48da7
test(h264): B pictures, display order, frame_num gaps, zero-alloc on B

- b_pictures_match_ffmpeg_every_frame: spatial and temporal direct,
  B-pyramid and weighted prediction, under both entropy coders, every
  frame bit-exact. The first version of this test measured nothing:
  x264's adaptive decision produced no B slices at all on the synthetic
  source, so the test now counts slice types out of the stream and fails
  if the encoder did not actually emit any.
- output_is_display_order_and_the_reorder_is_real: display order matches
  ffmpeg frame for frame, and the same stream decoded in decode order is
  a genuine permutation of it — 15 of 20 frames move.
- a_frame_num_gap_keeps_decoding: dropping a whole picture leaves the
  remaining 11 decodable, which is what a seek into a GOP looks like.
- The zero-allocation proof now covers a B-slice, multi-reference stream
  and counts a whole second pass over the stream rather than one
  picture, so picture-pool recycling is part of the claim.

Emitting a picture no longer looks its parameter set up: a stored
picture carries its own crop, output size and colour description, which
also removes the per-slice parameter-set clone that made the decode loop
allocate.
fix(h264): constrained intra prediction stops at predictionAhmet Kaan Gümüş · 18b2689
fix(h264): constrained intra prediction stops at prediction

constrained_intra_pred_flag makes an inter neighbour unavailable as an
intra *prediction* source (8.3.1.1, 8.3.1.2). It does not change the
neighbour availability the residual contexts read: clause 9.2.1 and
9.3.3.1.1.9 exclude an inter neighbour there only when slice data
partitioning is in use, which this decoder refuses outright. Feeding the
constrained availability into nC and coded_block_flag desynchronised
CI_MW_D, whose whole point is constrained intra prediction.

JVT full-sequence sweep: 26 of 26 in-scope vectors bit-exact end to end,
9 refused by name (8 interlaced, 1 FMO), nothing unaccounted.
fix(h264): reference index spans its whole 8x8, and numbering precedes markingAhmet Kaan Gümüş · 4b8dc73
fix(h264): reference index spans its whole 8x8, and numbering precedes marking

Two more inter-only defects, both found against the JVT reference decoder
traces that ship with the vectors:

- ref_idx_lX covers a whole macroblock partition. Writing it over only
  the first sub-macroblock partition left the rest of an 8x8 marked
  "list unused", so the mvd contexts of 9.3.3.1.1.7 read absMvdComp 0
  for a neighbour that had one, and CABAC desynchronised.
- clause 8.2.4.1 (FrameNumWrap, PicNum) ran only when a slice built a
  reference list. An intra slice builds none, and the picture being
  stored had no FrameNumWrap of its own, so the sliding window of
  8.2.5.3 compared stale numbers and evicted the wrong reference.
  Numbering now runs at the head of `store`, the one point every
  picture passes through.

JVT full-sequence sweep: 18 vectors bit-exact end to end before, 25 now,
of the 26 that are in scope.
fix(h264): unavailable neighbours carry reference index -1, not 0Ahmet Kaan Gümüş · 276058c
fix(h264): unavailable neighbours carry reference index -1, not 0

Two derivation defects that only inter coding can reach:

- Nb::default() derived Default, so an unavailable neighbouring partition
  reported refIdxLXN 0 instead of the -1 that clause 8.4.1.3.2 assigns.
  Every median prediction with a missing neighbour then saw a phantom
  match on reference picture 0 and took the wrong branch of 8.4.1.3.1.
  Picture-edge macroblocks came out wrong in most inter frames.
- coded_block_flag (9.3.3.1.1.9): an unavailable neighbour counts as set
  only when the current macroblock is intra. The chroma DC block of an
  inter macroblock at the left picture edge read the opposite value and
  desynchronised the arithmetic decoder.

JVT full-sequence sweep: 4 vectors bit-exact end to end before, 18 now.

Adds the full-sequence conformance test that found them, plus an
env-gated macroblock trace (EC_H264_TRACE) and deblocking bypass
(EC_H264_NO_DEBLOCK) that split reconstruction defects from filter
defects; both resolve their environment once so the decode loop stays
allocation free.
feat(h264): inter prediction, decoded picture buffer, display-order outputAhmet Kaan Gümüş · cd996f4
feat(h264): inter prediction, decoded picture buffer, display-order output

P and B slices under both entropy coders, with the clause 8.2 decoded
picture buffer behind them.

- inter.rs: quarter-sample luma interpolation (8.4.2.2.1), eighth-sample
  chroma (8.4.2.2.2) and the weighted combination of 8.4.2.3. Plane
  borders are replicated once per picture, which turns the per-sample
  Clip3 of Equations 8-239/8-240 into a single clamp of the block origin;
  the unit test checks every fractional position, inside the picture and
  far outside it, against the spec's clipped definition written out
  separately.
- mv.rs: macroblock and sub-macroblock partitioning (Tables 7-13, 7-14,
  7-17, 7-18), neighbouring motion data (8.4.1.3.2) and motion vector
  prediction (8.4.1.3) including the directional segmentation shortcuts.
- dpb.rs: picture order count types 0, 1 and 2, sliding-window and
  adaptive (MMCO 1..6, long-term references included) marking, reference
  list initialisation and modification, frame_num gap handling per
  8.2.5.2, and the output bumping of C.4.5.3.
- decoder.rs: P/B macroblock decode, P_Skip, B_Skip and both direct modes
  (spatial and temporal), constrained intra prediction, the inter scaling
  lists, and boundary strength derivation per 8.7.2.1 so deblocking now
  varies across an edge.
- Output is display order by default; OutputOrder::Decode is the escape
  hatch for a caller that reorders itself. Timestamps travel with the
  picture, not the packet.

The tC0 table rows for bS 1 and 2 were transcribed but unexercised by an
intra-only decoder, and both were wrong: whole-row shifts. Re-derived
from Table 8-17; inter edges reach them now.

CABAC initialisation gains the cabac_init_idc columns of Tables 9-13 to
9-21 (ctxIdx 11..59 and the idc columns of 70..275, 399..401), extracted
from the spec text by column alignment.
feat(h264): CABAC entropy decoding for I slicesAhmet Kaan Gümüş · 7cdaf34
feat(h264): CABAC entropy decoding for I slices

Clause 9.3, transcribed from Rec. ITU-T H.264 (V15):

- arithmetic decoding engine (9.3.3.2) with the spec's exact integer steps —
  DecodeDecision over rangeTabLPS, DecodeBypass, DecodeTerminate, RenormD;
- context variable initialisation (9.3.1.1) from SliceQPY, and the engine
  restart after I_PCM samples (9.3.1.2);
- binarizations: the I-slice mb_type tree (Table 9-36), TU, FL and the UEG0
  suffix of coeff_abs_level_minus1 (9.3.2.1 to 9.3.2.7);
- context selection including the neighbour-derived increments of 9.3.3.1.1
  for mb_type, intra_chroma_pred_mode, coded_block_pattern, mb_qp_delta and
  coded_block_flag, plus the significance-map positions of 9.3.3.1.3;
- the CABAC slice-data loop: cabac_alignment_one_bit, then a macroblock and an
  end_of_slice_flag per iteration.

The picture state grows the two neighbour facts CABAC needs and CAVLC did not:
the coded block pattern per macroblock, and the DC coded_block_flags. The
macroblock loop is otherwise untouched — parse and reconstruction stay fused.

Only the values an I slice of a frame-coded 4:2:0 8-bit stream reads are
transcribed. The cabac_init_idc columns, the field-coded significance
contexts and the 8x8 transform block categories belong to slices this decoder
still refuses by name; a later release adds them against its own oracle rather
than shipping numbers no test can reach. Inter slices under CABAC keep the
existing inter-slice refusal, and transform_size_8x8_flag is now refused as a
decoded bin rather than a raw one.
refactor(h264): entropy seat between the macroblock loop and CAVLCAhmet Kaan Gümüş · 6480b8e
refactor(h264): entropy seat between the macroblock loop and CAVLC

The slice-data syntax reader becomes an enum seam (`Entropy`) covering every
element the macroblock loop reads: mb_type, the intra prediction modes,
coded_block_pattern, mb_qp_delta, the residual blocks, the I_PCM samples and
the end-of-slice test. CABAC (clause 9.3) codes all of those differently, so
the seam has to sit there rather than around residual_block alone; the
parse-and-reconstruct loop stays fused.

Enum dispatch, not a generic: the variant is constant for a whole slice, so
the branches predict perfectly and the macroblock loop is monomorphised once.

The neighbour derivations now hand out the raw (left, above) pair instead of
a CAVLC nC, because CABAC reduces the same pair a different way.

CAVLC ns/MB, median of three runs, before -> after:
BA1_Sony_D 1331 -> 1328, CI_MW_D 1137 -> 1126, NL1_Sony_D 948 -> 933.
feat(h264): registry Decoder entry, avcC extradata, mechanism-named refusalsAhmet Kaan Gümüş · 19f3903
feat(h264): registry Decoder entry, avcC extradata, mechanism-named refusals

The NAL-level Decoder is what a bitstream tool wants; a demuxer wants
packets. H264Decoder implements ec_core::registry::Decoder over the same
decode core and adds the two things a container brings with it: parameter
sets carried out of band in an avcC record (14496-15 clause 5.3.3.1), and
NAL units framed by a length prefix instead of Annex B start codes. The
framing is decided once, by whether extradata held an avcC, and the SPS
inside it publishes the picture size before the first packet arrives.

Every refusal's why-text now names the syntax element that fired and the
machinery it would need, not just "not implemented" — the conformance
suite proves each one against a stream that really uses the feature, so
the text is the capability statement a caller reads.
feat(h264): CAVLC intra decoder, bit-exact on 18 JVT streamsAhmet Kaan Gümüş · f985e44
feat(h264): CAVLC intra decoder, bit-exact on 18 JVT streams

I-slice scope: I_4x4 / I_16x16 / I_PCM, full CAVLC residual decode,
all intra prediction modes, 4x4 inverse transform + DC Hadamard,
dequant with scaling-list support, and the complete in-loop deblocking
filter. Everything outside scope (CABAC, FMO, interlace, non-I slices,
8x8 transform, 4:2:2/4:4:4, >8-bit) refuses with a named Unsupported
error backed by tests on real conformance streams - never wrong pixels.

Perf-first layout: padded planes sized for future inter overreach;
per-MB state in flat struct-of-arrays (nz counts, intra modes, QP,
slice ids) with no per-MB heap objects; a register-cached BitCursor for
slice data; residual parse fused with reconstruction so empty blocks
cost one coeff_token read; wide i16x16 SIMD for horizontal deblock
edges (a gather/scatter vertical variant measured slower and stayed
scalar). Steady-state decode loop is zero-alloc, proven by a counting
allocator in the conformance harness.

Conformance: first IDR bit-exact vs the JVT reference YUV and ffmpeg on
18 CAVLC streams incl. multi-slice and I_PCM; 6 CABAC/FMO/interlaced
streams verified to refuse by name; deterministic corrupt-input sweep
(truncations + 2000 single-byte mutations) never panics.

Measured on this machine, single thread, deblock included: 1324 ns/MB
(193 Mpx/s) on BA1_Sony_D at idle; 1007 ns/MB (254 Mpx/s) on the
no-deblock NL1_Sony_D even under background load.