Commits
Commits on
154aa4b22d236cbe404ea14544439cf8e82d33ab2026-08-25
feat(av1): a DC level per superblock, with the real sign contextAhmet Kaan Gümüş · 154aa4b
feat(av1): a DC level per superblock, with the real sign context The tile writer carried one level for the whole frame, which meant every block saw the same DC sign context and the context derivation was never observed: a frame of one sign reaches two of the three contexts and never the one where the neighbours cancel. Levels now arrive one per superblock, and the sign context is read off the blocks above and to the left the way a decoder reads it -- each 4x4 unit of a coded neighbour voting its sign, the left column dropped at the start of every superblock row. The gate decodes two 128x128 grids whose levels differ in sign and checks every sample of every block. Its expectation is derived rather than pinned this time: a block's grey is the DC prediction from its reconstructed neighbours plus its own residual, so the test also holds the prediction propagating across the frame, which the single-block frames could not.
Merge branch 'lane-av1-coeff': DC coefficient coding in the AV1 tileAhmet Kaan Gümüş · f830031Browse files
feat(av1): code a DC coefficient in the key frame tileAhmet Kaan Gümüş · c68b3bd
feat(av1): code a DC coefficient in the key frame tile The tile writer could only say "this block is skipped". It now carries a single luma DC coefficient through the full coefficient syntax: the all-zero flag, the end-of-block position, the base level, the base-range tail for levels above two, and the sign with its neighbour-derived context. Chroma stays all-zero, so the two chroma flags sit immediately after the luma block and a desync in it lands on them first. The q-context CDFs this crate carries are the ones for base_q_idx 61..=120, so the writer refuses a base_q_idx outside that band rather than coding against tables the decoder will not be using. Levels are bounded at +/-14, which is what the base syntax reaches before the Golomb tail. The gate decodes each level -14..=14 through ffmpeg and asserts the whole 64x64 luma plane lands on a pinned value, chroma is untouched at 128, the sequence is monotone in the level, and the sign moves the picture the way it should. The pinned values come from the decoder, not from a derivation: there is no inverse transform in this crate yet to derive them with.
test(bd): refuse a sample window with nothing in itAhmet Kaan Gümüş · 7642b35
test(bd): refuse a sample window with nothing in it A clip-driven BD run whose sample window is a film's black head codes to almost no bits and decodes back to the source exactly, so every point on both curves sits at the 99 dB PSNR cap, the two cubics coincide, and the gate prints +0.000 dB. That is not a measurement, and it read as one: an ablation re-measure reported the same +0.000 for both arms of the knob. Both BD gates now refuse such a window by name and say which variable samples past it. The h265 gate also fails with "ladder collapsed" when its QP shift clamps two ladder points onto the same QP, instead of the "singular BD-PSNR fit" assert deep inside the cubic solver.
feat(av1): first frame that a real decoder decodesAhmet Kaan Gümüş · 304ec65
feat(av1): first frame that a real decoder decodes A tile payload writer for the one block coding the encoder can produce so far: a key frame whose every superblock is one skipped 64x64 DC-predicted block. Four symbols per superblock — the partition, the skip flag and the two intra modes — with the frame header turning off everything that would add syntax the writer does not code yet (CDEF, loop restoration, filter intra, screen content tools, transform size selection, CDF adaptation). The default CDF tables of spec section 9.4 arrive with it, in the same orientation the symbol coder reads: the partition, skip, key-frame luma mode and CFL-free chroma mode tables, which is what this syntax touches. Gated end to end rather than by roundtrip: the stream is handed to ffmpeg and every sample of the decoded frame must be 128, which is what a DC prediction with no neighbours and no residual produces. Any desync between our arithmetic coder and dav1d's shows up as a decode failure or a sample that is not mid-grey, with no metric in between to hide it. Frames that are not a whole number of superblocks are refused by name: a partial superblock forces the partition syntax down the block tree.
Merge branch 'lane-h265-chroma': RDOQ, +0.114 dB film / +0.122 dB screenAhmet Kaan Gümüş · d951540Browse files
feat(h265): rate-distortion quantisationAhmet Kaan Gümüş · 21ef192
feat(h265): rate-distortion quantisation
Every non-zero level up to 2 is offered its lower magnitudes and zero, and
the alternative is kept when the rate the CABAC coder actually charges for
it, priced against the transform-domain error the change costs, comes out
cheaper. The rate comes from the coder itself: a counting CabacEncoder is
restored to a fixed base state per trial and asked to code the block, so
the price includes the significance map and the greater-than-one flags
rather than a model of them. Distortion is converted from the coefficient
domain to sample squared error by (n * n) / 128^2, which is what this
transform's scaling leaves for a block of side n. A whole-block-zero trial
follows, since the cbf flag alone can be the cheaper coding.
With a downward-only search the quantiser feeding it must not already
round down, so the RDOQ path quantises with a round-to-nearest offset
(dead zone 2) instead of the intra default of 3; the search then decides
what to drop. All four constants were swept against the clip gate:
luma dead zone 1/2 +0.360, 1/3 +0.315, 1/4 +0.118 (film BD-PSNR-YUV)
chroma dead zone kept at 1/2: 1/3 and 1/4 climb on luma (+0.568/+0.585)
while all-plane BD-PSNR falls (+0.169/+0.128)
max level 1 -> +0.244, 2 -> +0.276, 3 -> +0.277
lambda 1.0 -> +0.276, 1.25 -> +0.294, 1.5 -> +0.293 on film,
but -0.392/-0.408/-0.441 on screen capture
Measured on the real clips, default on:
1080p film +0.246 -> +0.360 dB BD-PSNR vs x265
2560x1440 screen capture -0.479 -> -0.357 dB
Bit exactness is gated separately: rdoq_decodes_bit_exactly encodes three
frame shapes at QP 27, asserts the bitstream differs from the plain path,
and decodes each with ffmpeg against the kept reconstruction with zero
sample mismatches.
The synthetic fallback clip in the BD gate needed its ladder alignment
extended for this: our curve now spans a much wider bitrate range than
x265's over the same QP spacing, so after the geometric-mean rates match,
the ladder is drawn in towards its own centre until both curves cover the
same range. Single-QP shift corrections are ignored, which only made the
alignment oscillate between neighbouring shifts.feat(av1): symbol coder for tile payloadsAhmet Kaan Gümüş · a580965
feat(av1): symbol coder for tile payloads AV1 specifies only the decoding process for its multi-symbol arithmetic coder, so the writer is derived as the inverse of section 8.2: it narrows the same interval decode_symbol tracks and flushes the shortest prefix that pins the interval down whatever bytes follow. CDF adaptation follows section 8.3.2, and CDFs are stored in the specification's own orientation (cumulative, 1 << 15 total, counter in the last entry) so the code reads against the spec text rather than against a decoder's internal complement. Covers the adaptive multi-symbol write, the fixed-CDF write, and L(n) literals; the flush handles carry propagation through the precarry buffer. Gated by a decoder written separately from the section 8.2 pseudocode: alphabets of 2..=16 symbols roundtrip over 4000 adaptive symbols each, 2000 mixed-width literals roundtrip, a 3000-item interleaving of both roundtrips, and a 1-in-256 stream is asserted to cost under a quarter bit per symbol so a backwards interval narrowing cannot pass. This is the primitive every AV1 tile payload is written through; the OBU writers so far cover only the headers around it.
feat(h265): sign data hiding, correct and shipped offAhmet Kaan Gümüş · 0877a36
feat(h265): sign data hiding, correct and shipped off Implements sign_data_hiding_enabled_flag per 7.3.8.11: for each 4x4 sub-block whose first and last significant scan positions are more than three apart, the sign at the first position is not coded and the decoder infers it from the parity of the sub-block's summed absolute levels. The encoder nudges one already-non-zero level by one when the parity comes out wrong, picking the coefficient whose ideal (pre-rounding) level sits closest to the nudge. Proven bit-exact: sign_hiding_decodes_bit_exactly encodes 64x64, 130x66 and 352x288 with hiding on and off, asserts the streams differ, and decodes both through ffmpeg with zero sample mismatches. Shipped off. On the clip gate it loses: -0.033 dB BD-PSNR on a 2560x1440 screen capture (-0.479 -> -0.512 vs x265) and -0.043 dB on 1080p film (+0.246 -> +0.203). Hiding is mandatory for a qualifying sub-block, so every one of them pays whether its cheapest nudge is cheap or not, and levels straight off the quantiser's rounding make that nudge expensive. A rate bias on the nudge picker was swept at +-0.25 and +-0.5 units of squared level error per bit and lost in both directions, so the picker is distortion-only. Worth re-measuring once RDOQ lands, which is where this pays for other encoders.
feat(h265): four 4x4 intra partitions in an 8x8 CU (PART_NxN), on by defaultAhmet Kaan Gümüş · 089675b
feat(h265): four 4x4 intra partitions in an 8x8 CU (PART_NxN), on by default An 8x8 coding unit may now split into four 4x4 intra partitions: the CTU encoder codes both and keeps whichever wins the rate-distortion trial, rolling back the CABAC state, the reconstruction and the mode metadata together when 2Nx2N wins. Syntax order follows the standard: the single `part_mode` bin, then four `prev_intra_luma_pred_flag` bins, then the four remainders, then the chroma mode; the transform split at depth 0 is inferred from IntraSplitFlag, `cbf_cb`/`cbf_cr` stay at depth 0, and the chroma residual rides on the last partition. Measured against x265 with self-aligning QP ladders: a 2560x1440 screen capture goes from -2.619 dB BD-PSNR to -0.479 dB (-2.502 to -0.542 YUV), and 1080p film moves +0.007 dB. It never loses, so it defaults on. The conformance test encodes the grainy natural frame rather than the synthetic one -- the synthetic frame is flat enough that the quadtree never keeps an 8x8 coding unit, so PART_NxN could not fire and the decode proved nothing.
fix(h265): bound the clip gate's decode to the pictures it samplesAhmet Kaan Gümüş · 6e90b9d
fix(h265): bound the clip gate's decode to the pictures it samples `clip_sources` asked ffmpeg for the whole file as raw I420 and sliced the result afterwards. A 1080p feature is hundreds of gigabytes that way: a run on a full film grew the test binary to 29 GB of anon RSS and was killed by the kernel OOM killer, with the machine swapping hard. Short captures fit, so the gate had only ever been run on content that hid it. Trim inside ffmpeg instead -- `select=gte(n,SKIP)` drops the skipped pictures and `-frames:v WANT` stops the decode once enough have come out, so the process holds exactly the frames it measures. The same film run now finishes in 10 s inside an 8 GB cap, and the numbers on the short capture are unchanged.
feat(av1): write the key-frame header OBUAhmet Kaan Gümüş · e203345
feat(av1): write the key-frame header OBU The inverse of `ec_av1_syntax`'s `parse_uncompressed_header`, for the subset a stateless encoder emits: a shown key frame in a sequence with no decoder model, no frame id numbers and no still-picture shortcut. It covers tile info (uniform spacing), quantization, segmentation, delta q and delta lf, loop filter, CDEF, loop restoration, transform mode and the reduced transform set, plus `frame_obu` to carry the header and a tile group in one OBU. Two of the codings are not the value they look like and are spelled out here: the restoration type is remapped (None 0, Switchable 1, Wiener 2, Sgrproj 3, not the enum's discriminant) and a CDEF secondary strength of 4 is coded as 3. Everything outside the subset is refused by name rather than written wrong: a superres denominator other than 8, film grain synthesis, frame id numbers, decoder model timing, `show_existing_frame`, any non-key or hidden frame, and non-uniform tile spacing. The tests parse back every stream they write through `Av1Parser` and compare the whole `FrameHeader`, including the derived fields the format never codes (the header's own bit length, the tile start ramps, the segmentation id range), across a one-tile frame, a four-tile-column frame, a segmented frame with delta q and delta lf, and a frame using loop restoration.
Merge branch 'lane-h265-chroma': chroma mode search, measured and left offAhmet Kaan Gümüş · 9d66338Browse files
feat(h265): chroma prediction mode search, measured and left offAhmet Kaan Gümüş · fea923b
feat(h265): chroma prediction mode search, measured and left off Chroma was always coded in the derived mode: `intra_chroma_pred_mode` was a hardcoded 0 bin. The syntax offers five modes — planar, vertical, horizontal and DC, each swapped for angular 34 when it collides with the luma mode, plus derived — and nothing had ever measured what the other four are worth. `choose_chroma_mode` now codes all five into a counting CABAC snapshot, both planes and their residuals, and keeps the lowest `SSD + lambda * bits`. It is off by default, because measured against x265 on four real clips it is a wash (BD-PSNR luma / all-plane, derived -> search): | clip | derived | search | |------|---------|--------| | 4K film | -0.685 / -0.703 | -0.757 / -0.606 | | 1138x640 web | -0.507 / -0.556 | -0.584 / -0.505 | | 1440p screen capture | -2.465 / -2.360 | -2.617 / -2.460 | | 1080p phone | -0.366 / -0.387 | -0.477 / -0.384 | Luma falls on every clip — the extra chroma bits come out of the same budget at a fixed QP — while all-plane gains 0.10 dB and 0.05 dB on the two camera clips, is flat on the third and loses 0.10 dB on the screen capture, for 10-15% more encode time. Average +0.01 dB all-plane is not a default. The lambda is not the cause: `chroma_rd_weight` swept at 0.25/0.5/1.0/2.0 leaves the screen capture losing at every weight, and 1.0 is the best weight wherever the search wins at all. Correctness is gated on its own: `chroma_mode_search_decodes_bit_exactly` asserts the stream differs from the derived-only one (so the explicit modes really fired) and that ffmpeg decodes it sample-for-sample. EC_H265_CHROMA_RD and EC_H265_CHROMA_W in the BD gate re-run both sweeps.
Merge branch 'lane-h265-rdo': five intra candidates reach the rate-distortion trialAhmet Kaan Gümüş · 966bf25Browse files
perf(h265): give five intra candidates the rate-distortion trialAhmet Kaan Gümüş · b24f633
perf(h265): give five intra candidates the rate-distortion trial The luma mode search screened 35 intra modes with SATD and handed only two survivors to the full rate-distortion trial. That count was never measured; it was the number the search was written with. Swept against x265 at matched features on four real clips (BD-PSNR luma / all-plane, 24 pictures after 1500, ladders auto-aligned, 0% extrapolation): | k | 4K film | 1138x640 web | 1440p screen capture | 1080p phone | |---|---------|--------------|----------------------|-------------| | 1 | -0.840 / -0.815 | -0.728 / -0.733 | | | | 2 | -0.731 / -0.730 | -0.603 / -0.632 | -2.521 / -2.420 | -0.435 / -0.444 | | 3 | -0.703 / -0.709 | -0.556 / -0.596 | -2.493 / -2.402 | -0.401 / -0.416 | | 4 | -0.693 / -0.705 | -0.530 / -0.574 | | | | 5 | -0.685 / -0.703 | -0.507 / -0.556 | -2.465 / -2.360 | -0.366 / -0.387 | | 8 | -0.684 / -0.710 | -0.471 / -0.525 | -2.453 / -2.368 | -0.340 / -0.361 | Every clip improves monotonically to five. Eight buys +0.001 dB on the film clip and takes its all-plane figure backwards, for another 20% of wall time, so the knee is where the default now sits: film 38s -> 49s for the whole four-QP ladder, web clip 8s -> 11s. The synthetic floor moves with it (+2.456 -> +2.507 luma, +3.158 -> +3.238 all-plane) and EC_H265_RDO_CANDIDATES in the gate test re-runs the sweep.
perf(h264): choose the Intra_8x8 luma mode by rate-distortionAhmet Kaan Gümüş · ccc4650
perf(h264): choose the Intra_8x8 luma mode by rate-distortion The Intra_8x8 chooser scored the nine prediction modes on SATD of the prediction residual plus a mode-bit term. That is a decision taken before the quantiser has a say: it never sees which mode's residual survives quantisation cheaply. Same class as the intra chroma chooser fixed in 98d01b7, and the last SATD-only intra site. Every allowed mode is now predicted, coded at the real QP and scored as SSD + lambda * bits, with the rate read from the CABAC coder's own 8x8 price (residual_block_8x8_cost — Luma8x8 has no coded_block_flag of its own, the CBP carries it, so the cbf-indexed cost path panics on it). BD-PSNR against x264 at matched features, 8x8 transform on, GOP 10, 24 consecutive pictures, luma / all-plane YUV: 3840x1608 film +0.475 / -0.068 -> +0.512 / -0.035 1138x640 web clip +0.040 / -0.031 -> +0.076 / +0.003 854x480 web clip +0.070 / +0.047 -> +0.132 / +0.108 2560x1440 screen -0.206 / -0.199 -> -0.215 / -0.207 Three clips of four gain on both metrics; the screen capture loses 0.008 dB. Encode time on the 854x480 clip goes from 12 s to 13 s. The path only runs when the 8x8 transform is enabled, which is still opt-in, so no default stream byte moves; the byte-identity conformance tests confirm it.
2026-08-24
feat(ec-av1): OBU header/framing writer + sequence-header writerAhmet Kaan Gümüş · 4cb83b2
feat(ec-av1): OBU header/framing writer + sequence-header writer Bit-exact inverse writers of the parsers in ec-av1-syntax: obu.rs: - obu_type_code: ObuType -> 4-bit code (inverse of ObuType::from_code) - write_obu_header: writes OBU header (spec 5.3.2), forbidden/reserved bits 0 - wrap_obu: frames payload as low-overhead OBU (header + leb128 size + payload) - temporal_delimiter: the two-byte 0x12 0x00 temporal-unit marker sequence.rs: - write_sequence_header: full sequence-header payload (spec 5.5.1) - write_color_config: color_config() inverse (spec 5.5.2) - sequence_header_obu: wraps the payload as a SequenceHeader OBU Supported subset only (unsupported configs return Error::unsupported): - reduced_still_picture_header == false (still-image header not implemented) - no timing_info - no decoder_model_info - exactly one operating point Roundtrip tests: write -> parse back -> assert equality for both OBU headers (plain + extension) and sequence headers; wrapped OBU leb128 size asserted to match payload length; temporal delimiter asserted to be [0x12, 0x00]. Gates: cargo test --release -p ec-av1 (13 passed), cargo clippy --release -p ec-av1 --all-targets (clean), cargo fmt.
Merge branch 'lane-h265-gate': BD-PSNR against x265 with self-aligning laddersAhmet Kaan Gümüş · addbfd0
Merge branch 'lane-h265-gate': BD-PSNR against x265 with self-aligning ladders Adds the ec-h265 gate: BD-PSNR and BD-PSNR-YUV against x265 at matched features, both sides decoded through ffmpeg, with the QP ladders aligned from a probe encode so the Bjontegaard integral interpolates. The extrapolation share of each curve is measured and a run above 20% fails with a named message instead of reporting a cubic guess.
test(h265-gate): align the QP ladders from a probe encodeAhmet Kaan Gümüş · 8b6026d
test(h265-gate): align the QP ladders from a probe encode A fixed QP offset assumed our encoder is always leaner than x265 at matched QP. That holds on the smooth synthetic clip (probe shift -6, reproducing the hand-picked 16/20/24/28) but not on real content: on a 3840x1608 film and a 1138x640 web clip the probe measures a shift of 0, and the hand-picked ladder put 51% and 72% of the integration range outside the measured bitrate span, so the guard fired and the BD number would have been a cubic guess. The ladder is now derived: both sides encode once at QP 26, the bit ratio becomes a QP shift at ~6 QP per factor of two in bits, and x265's 22/26/30/34 plus that shift is our sweep. If the extrapolation share still exceeds 20%, the shift is re-estimated from the geometric-mean bit ratio of the two full curves, at most twice, before the existing panic fires. The probe encodes are reused as the QP-26 rungs, so the alignment costs no extra encode. With the ladders aligned, the real gap is visible: -0.731 dB luma / -0.730 dB YUV on the film, -0.603 dB / -0.632 dB on the web clip, 0% extrapolation on every curve. The synthetic floor stays at +2.306 dB and gates only the pinned clip; a media file is measured, not gated. Two comments corrected while here: ffmpeg's `-qp` does reach libx265 (`qp=N` and `rc=cqp:qp=N` are byte-identical, so the prefix is dropped), and the shallow all-intra rate-quality slope is content behaviour, not a rate-control misconfiguration.
feat(ec-av1): bit-primitive writers (leb128/uvlc/le/su/ns/delta_q/trailing_bits) with roundtrip testsAhmet Kaan Gümüş · d869345Browse files
perf(h264): choose the intra chroma mode by rate-distortionAhmet Kaan Gümüş · 495e450
perf(h264): choose the intra chroma mode by rate-distortion The chooser scored the four chroma prediction modes on SATD of the prediction plus the bits naming the mode, deciding before the quantiser had a say. Every available mode now goes through the real chroma coding path and is scored on reconstructed SSD plus what its levels and its name actually cost, which is the same measurement the rest of the macroblock decisions already make. Measured with bd_psnr_vs_x264 against x264 -preset medium, BD-PSNR-YUV, GOP 10, 24 consecutive pictures: 3840x1608 film -0.500 -> -0.443 dB, 2560x1440 screen capture -0.220 -> -0.146 dB, its second scene -0.571 -> -0.538 dB, a 1080p phone clip -1.122 -> -1.084 dB, a 720p web clip -0.606 -> -0.572 dB. Five clips of five improve; luma is unmoved (film -0.065 -> -0.070 dB) and encode time does not change measurably, since only intra macroblocks pay and only four chroma trials each.
fix(h265-gate): offset QP ladders so BD-PSNR is a measurement, not a guessAhmet Kaan Gümüş · 4ae6e08
fix(h265-gate): offset QP ladders so BD-PSNR is a measurement, not a guess The gate reported BD-PSNR -38.258 dB with 50% extrapolation on our side — the two rate-quality curves did not overlap. Root cause was misdiagnosed as ffmpeg -qp not reaching x265 rate control; in fact -qp and rc=cqp:qp=N produce byte-identical output. x265 at CQP on this smooth synthetic clip genuinely has a shallow rate-quality slope (29% bitrate drop across 12 QP). The fix: pass rc=cqp:qp=N inside the x265 param string (explicit, not relying on ffmpeg flag translation) and offset the QP ladders so the bitrate ranges overlap. Our sweep drops to 16/20/24/28; x265 stays at 22/26/30/34. At matched bitrate our PSNR is higher on this clip. Measured table (352x288, 24 pictures, Clip::render_smooth): qp 16: ours 809632 bits 53.63 dB qp 20: ours 577872 bits 51.26 dB qp 24: ours 433584 bits 48.84 dB qp 28: ours 316664 bits 45.86 dB qp 22: x265 835424 bits 51.50 dB qp 26: x265 745104 bits 49.19 dB qp 30: x265 674088 bits 46.37 dB qp 34: x265 596808 bits 42.97 dB cubic extrapolation: candidate 0% anchor 0% BD-PSNR: +2.456 dB luma / +3.158 dB YUV Guard: bd_psnr_delta now returns (bd, cand_extrap, anc_extrap); the test panics with a named message when either curve is extrapolated over more than 20% of the integration range. Floor recalibrated: BD_PSNR_VS_X265_FLOOR = 2.306 (measured 2.456 - 0.15).
perf(h264): give the chroma DC block a zero testAhmet Kaan Gümüş · 59070a1
perf(h264): give the chroma DC block a zero test Every other block in this encoder is asked whether coding it pays: luma 4x4 and 8x8, the chroma AC group, the macroblock's shape and skip flag. The chroma DC block was the exception — whatever the quantiser produced was coded, however little it bought. It gets the same test now. With only DC in a block the inverse transform gives every one of its sixteen samples the same (dc + 32) >> 6, so the squared error of zeroing the block is exact from the AC residual that is already reconstructed at that point: one sum per block, no second trial. BD-PSNR-YUV against x264 (GOP 10, QP 22/26/30/34, Preset::Balanced), test off -> on: film -0.504 -> -0.500, screen capture -0.227 -> -0.220, phone -0.300 -> -0.297, handheld -0.886 -> -0.884. The multiplier's ladder is in the comment on CHROMA_DC_LAMBDA; the peak is flat between 0.5 and 0.75 and turns sharply worse above 1.
ec-h265: add bd_psnr_vs_x265 gate against x265Ahmet Kaan Gümüş · 15b6d35
ec-h265: add bd_psnr_vs_x265 gate against x265 BD-PSNR of this encoder against x265 at matched features (intra-only, no B frames, in-loop filters off, AQ/psy/RDOQ off, QP 22/26/30/34) on the synthetic 352x288 24-picture clip, both sides decoded through ffmpeg. Measured: BD-PSNR luma -38.258 dB, BD-PSNR-YUV -31.656 dB. Floor calibrated at measured - 0.15 = -38.41 dB. The gap is wide because this encoder spends 40-70% fewer bits than x265 at every QP, so its rate-quality curve sits below x265's and the union-range cubic integral extrapolates; the convention is documented in bd_psnr_delta.
Merge branch 'lane-mkv-gate': the gate opens Matroska tooAhmet Kaan Gümüş · 832b640
Merge branch 'lane-mkv-gate': the gate opens Matroska too The BD-PSNR gate demuxed only through ec-mp4, so every .mkv in the user's library was refused before a single picture was measured. Probe the container by its bytes instead — ftyp at offset 4 for MP4, EBML magic for Matroska — and refuse a non-H.264 video track by naming its codec.
perf(h264): choose chroma_qp_index_offset from the sourceAhmet Kaan Gümüş · eb83b6f
perf(h264): choose chroma_qp_index_offset from the source The offset was a hardcoded 0 in the PPS. Sweeping it showed the optimum is not a constant: a film clip is best at 0 and loses 0.16 dB at -2, while every screen capture and phone clip gains, one of them by 0.23 dB. What separates them is how textured the chroma planes are relative to luma — flat chroma is what wants the extra chroma bits, because its few edges are all the eye has to read there, and film's chroma carries as much detail as its luma, where the same bits buy more. So measure it: mean absolute sample gradient of the chroma planes over that of luma, taken on the first source picture, and code at -2 below half. The offset now reaches the PPS, the encoder's own chroma QP derivation and the deblocking parameters of every slice it writes, so reconstruction still matches a decode exactly. BD-PSNR-YUV against x264 (GOP 10, QP 22/26/30/34, Preset::Balanced) over nine clips, before -> after: -0.504 -> -0.504 (film, keeps 0), -0.406 -> -0.227, -0.495 -> -0.268, -0.601 -> -0.570, -0.639 -> -0.575, -0.931 -> -0.886, -0.510 -> -0.491, -0.352 -> -0.340, -0.376 -> -0.300. The rule reproduces each clip's own swept optimum.
ec-h264: probe container by bytes, accept Matroska alongside MP4Ahmet Kaan Gümüş · d5e9b8f
ec-h264: probe container by bytes, accept Matroska alongside MP4 Factor both demux call sites in tests/encode.rs onto one helper, open_h264_source, that reads 12 bytes from the file head and dispatches to ec_mp4::Mp4Demuxer (ftyp at offset 4) or ec_matroska::MatroskaDemuxer (EBML magic 1A 45 DF A3) — never by extension. A non-H.264 video track (AV1, HEVC) is refused with a message naming the codec, not a demuxer panic. Add ec-matroska as a dev-dependency. BD-PSNR ours vs x264 over q22/26/30/34: -0.732 dB (FMA 01, 1280x720, H.264-in-Matroska, 24 pictures). AV1 .mkv refusal confirmed: 'video track is Av1, not H.264 — this gate measures H.264 only'.
perf(h264): decide the P shape and skip flag on coded costAhmet Kaan Gümüş · 6897ed7
perf(h264): decide the P shape and skip flag on coded cost
The motion search ranked its shapes by an SATD total plus a guessed
signalling charge, and the macroblock took that ranking as final. That
total is a prediction-domain estimate: it never sees the residual the
shape causes, so a split that looks cheaper to predict can cost more to
code than the 16x16 it displaced, and the encoder had no way to notice.
Intra against inter was already decided by coding both branches and
comparing squared error plus lambda times real bits. This extends the
same treatment to the inter side: choose_inter now returns every shape
it costed, most promising first, with P_Skip appended when the search
did not already prefer it, and the macroblock codes the list and keeps
the smallest coded cost.
BD-PSNR-YUV against x264 at GOP 10 over QP 22/26/30/34, Balanced:
film 3840x1608 screen 2560x1440
1 candidate -0.580 -0.474
2 -0.521 -0.459
3 -0.513 -0.447
5 -0.504 -0.406
monotone with no turnover, so the whole list is coded. Luma-only moves
-0.121 to -0.079 and -0.190 to -0.128. The film clip's comparison run
goes from 46s to 64s: a P macroblock is now coded up to five times and
every loser's reconstruction and entropy writer is thrown away, which
is why the list is Balanced-only and Fast still codes the SATD winner
alone.
This is the step the x264 feature ladder localised: subme 4 reads
-0.290 and subme 6 reads -0.581 on the film clip, the difference being
exactly that x264 stops estimating the mode decision and codes it.perf(h264): search the diagonals tooAhmet Kaan Gümüş · cdfa038
perf(h264): search the diagonals too The whole-sample motion search stepped on a cross, so it could only walk along an axis. A macroblock moving diagonally has to be reached in two steps through a point that is worse than either -- and a step search stops at the first point it cannot improve on, so it never took the first step. Step on a square instead. Worth 0.032 dB BD-PSNR-YUV on the film clip and 0.041 on the screen capture, for twice the candidates in the stage that reads the reference in place and never interpolates. The opening step size was swept alongside at 4, 8 and 16 whole samples and stays at four; wider is not a wider search, it only starts the walk further from the seeds, which are already the answer most of the time.
feat(h264): let the inter decision see chromaAhmet Kaan Gümüş · 5f9d4c9
feat(h264): let the inter decision see chroma Every decision in the P path was made on luma alone: the motion search, the partition shape, the skip flag. Chroma was then coded against whatever vector came out, having never been asked about. Add the two chroma planes to the cost of the candidates that survive to the shape decision -- one motion compensation and one SATD per candidate, which the search proper could not afford but a handful of finalists can. Weight swept at 0, 0.25, 0.5, 1 and 2 on two contents, read on BD-PSNR-YUV; half is the optimum. Worth 0.041 dB on the film clip and nothing on the screen capture, which is small enough to be the useful part of the result: our chroma trails by 0.5-0.9 dB per plane at every QP, and this rules out the vector as the reason. Weighting chroma higher does lift chroma PSNR, monotonically, and past a half it spends more bits than the chroma is worth.
test(h264): report chroma per plane, and stop dropping the first x264 paramAhmet Kaan Gümüş · 8adad23
test(h264): report chroma per plane, and stop dropping the first x264 param The gate compared two encoders on a pooled all-plane number without ever saying which plane either one was losing. Print U and V separately per QP for both sides; on the film clip they say our chroma trails x264 by 0.48-0.90 dB uniformly across QP while we spend more bits, which is a prediction deficit rather than a starved one. EC_H264_X264_PARAMS was spliced in with a colon of its own, so a value written with a leading colon produced "::subme=1" -- and ffmpeg drops the token that follows an empty one. The parameter silently did not apply and the sweep read as "this x264 feature is worth nothing". Trim the colons off the value instead. Corrected attribution of x264's lead on the film clip, as BD-PSNR-YUV: its RD mode decision is worth 0.739 dB, its trellis quantisation 0.206, and the two are additive -- with both stripped we lead by 0.278 dB.
feat(h264): measure all three planes, and a chroma coded_block_pattern testAhmet Kaan Gümüş · 49e08f5
feat(h264): measure all three planes, and a chroma coded_block_pattern test The rate-quality gate measured PSNR on the luma plane alone, so any decision that could trade chroma bits for luma bits read as a pure gain. It now also reports an all-plane PSNR, pooled by sample count the way x264 reports it -- luma 6, each chroma plane 1 for 4:2:0 -- as BD-PSNR-YUV beside the luma number. Chroma gets the group test luma already has: cbp_chroma is 0, 1 (DC) or 2 (DC and AC), so one surviving AC block takes the pattern to 2 and makes the other seven each spend a coded_block_flag saying they are empty. The eight AC blocks are pooled, coding them is compared against zeroing them all, and the pattern step is charged CBP_CHROMA_BIT. Swept at 0, 4, 8, 16, 32 and 64 bits the charge reads -0.688/-0.681/-0.659/ -0.653/-0.670/-0.742 dB all-plane BD on a 3840x1608 film clip and -0.537/ -0.527/-0.530/-0.517/-0.524/-0.522 on a 2560x1440 screen capture; both turn over at sixteen. Read on luma alone the same sweep climbs monotonically to +0.079 dB at 64, which is the encoder buying luma by throwing chroma away. On the all-plane number the gap to x264 is -0.65 dB on the film clip against -0.18 luma, and -0.52 against -0.23 on the screen capture: chroma is the larger half of what is left, and nothing in this lane had been able to see it.
feat(h264): decide the coded_block_pattern group by rate-distortionAhmet Kaan Gümüş · 835b128
feat(h264): decide the coded_block_pattern group by rate-distortion Our residual luma still ran 10 to 17 per cent over x264's at a PSNR above x264's: blocks coded that x264 declines to code. The per-block zero test decides one block at a time, so a block surviving alone in its 8x8 group drags a coded_block_pattern bit behind it uncounted. x264 settles that with `decimate`, a count of how tightly the levels cluster at the front of the scan. Ported exactly, its optimum runs monotonically opposite on the two real clips -- camera grain wants it off, screen capture wants it harder than x264 sets it -- so it is a heuristic standing in for a test the encoder can run. Run the test instead: code the group only when its blocks buy more squared error than their levels plus the pattern bit are worth. That test needs the rate to be right. On the per-block estimate it reproduced the same content split; against CABAC's own cost for the same levels -- already in the encoder for RDOQ, in 256ths of a bit -- screen capture develops an interior optimum it never had. Both lambda and the pattern charge are swept, tables in their doc comments. BD-PSNR against x264 at matched features, consecutive pictures, at the balanced preset: 3840x1608 film -0.329 -> -0.321 dB, 2560x1440 screen capture -0.310 -> -0.252 dB. The same test on the 8x8 transform path is worth nothing across its sweep and is not kept; the negative result is recorded where the constant lives. The transform_8x8 flag gate pins the delta between two arms and drops from 0.255 to 0.230 dB because the flag-off arm is the path that improved -- the absolute synthetic comparison against x264 moves from -4.060 to -3.969 dB -- so it is re-pinned with that written beside it.
feat(h264): search each inter partition against its own predictorAhmet Kaan Gümüş · 1db6da0
feat(h264): search each inter partition against its own predictor A split macroblock's partitions were all searched against the whole macroblock's motion predictor, so the mvd the search costed was not the mvd the stream would carry: 8.4.1.3 gives 16x8 and 8x16 partitions directional shortcuts and 8x8 sub-partitions the median of their own neighbourhood. Partitions whose real predictor sat close by looked expensive and the search declined them. Derive the predictor inside the search loop instead. The neighbourhood comes from the picture, then the entries falling inside this macroblock on already-chosen partitions are filled from the vectors this loop has picked -- what the encoder will do when it codes them. That predictor also seeds the search. Both shape-signalling charges are re-swept on the new path. The quarters' twelve bits survive; the halves' six do not, and become three, with the sweep tables in their doc comments. BD-PSNR against x264 at matched features, consecutive pictures, at the balanced preset: 3840x1608 film -0.377 -> -0.329 dB, 2560x1440 screen capture -0.353 -> -0.310 dB.
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.
perf(h264): search every partition, and document the split gateAhmet Kaan Gümüş · 338bd3f
perf(h264): search every partition, and document the split gate The bit account points at the motion field, so the search's two stopping rules were measured rather than assumed. The early exit that accepted a seed costing under half a level a sample is monotonically harmful -- 0/0.25/0.5/1.0 read -0.586/-0.587/-0.593/-0.617 dB BD-PSNR against x264 on the film clip and -0.466/-0.470/-0.468/-0.476 on the screen capture -- and removing it does not move the suite's wall clock, so it is gone. The gate on searching the 16x8 and 8x16 halves reads identically at four settings on both clips: real content clears it everywhere. It stays as a guard for flat content and is documented as one.
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.
h264: record the mode-decision lambda sweep, which changes nothingAhmet Kaan Gümüş · 6deb39c
h264: record the mode-decision lambda sweep, which changes nothing The RD multiplier ladder had never been swept as a scale. It is now, on both real clips at the settled quantisation constants, and it sits on the crossing: film wants 0.7 (0.022 dB), screen capture wants 1.0 and loses 0.055 for the same move. Nothing landed; the table is in the lane report so the constant is not swept a third time.
h264: price the 8x8 inter blocks on their own bins tooAhmet Kaan Gümüş · fad4297
h264: price the 8x8 inter blocks on their own bins too residual_block_8x8_cost costs the cat-5 bins the writer writes, and the 8x8 path quantises, searches and zero-tests through it the way the 4x4 luma path does. quant_8x8 grew the same offset-naming sibling the 4x4 quantiser has, so the search picks the rounding that feeds it. Swept again rather than inherited: 8x8 answers like 4x4 luma, not like chroma, and keeps round-to-nearest. Measured as BD-PSNR of the opt-in transform_8x8 flag against flag-off, which is what isolates this path: film +0.535 -> +0.619, screen capture +0.042 -> +0.067. No default stream byte moves -- the flag is still off by default.
h264: price inter chroma AC levels the same wayAhmet Kaan Gümüş · e21a764
h264: price inter chroma AC levels the same way The RDOQ decision built for inter luma now also runs on the chroma AC blocks: rdoq_4x4 takes the block category and the DC-skipping flag, and block_ssd reconstructs through the AC-only unzigzag and dequant when it is set. The rounding that feeds the search had to be swept again rather than inherited. Luma wanted the wider 1/2 rounding once a search could take levels back down; chroma is monotonically worse for every widening and keeps the 1/6 inter dead zone it already had, taking only the pruning half. BD-PSNR against x264 on two real clips: film -0.628 -> -0.593, screen capture -0.471 -> -0.468; the synthetic gate is unchanged at -4.073 because its chroma planes are flat.
h264: choose inter luma levels against the CABAC coder's own priceAhmet Kaan Gümüş · 47083d3
h264: choose inter luma levels against the CABAC coder's own price Rate-distortion quantisation for inter luma 4x4: each level is offered the cheaper magnitudes below it, and takes one when the squared error it gives up costs less than the bits it saves. The rate is exact. `CabacEnc::residual_block_cost` runs the same bins `residual_block` writes -- one body behind a `BinSink` the writer and the price share -- against a copy of the context state, charging each bin -log2(p) for its state and moving the state as the coder would. Over 400 random blocks it predicts 2649288/256 bits where the coder then spends 2650112/256, an error of 0.03%, which is asserted rather than assumed: a wrong price is invisible in the stream and shows up only as lost dB. An exact rate on its own was worth almost nothing (film -0.728 -> -0.732, screen capture -0.500 -> -0.449). The half that pays is the dead zone: a search that can only walk levels down cannot see a level the quantiser's 1/6 dead zone already threw away, so it was choosing among the survivors of the decision it was meant to replace. Quantising the searched path at 1/2 and letting the search take the levels back down is worth 0.102 dB on the film clip and 0.301 on the synthetic gate. Deciding the whole-block zero on exact bits too adds 0.142 dB there. BD-PSNR against x264 at matched features: film 3840x1608 -0.728 -> -0.628, screen capture 2560x1440 -0.500 -> -0.471, synthetic -4.523 -> -4.073, the floor moved to -4.15. Bounding the search to levels of 2 or less keeps it free (synthetic run 1.08 s before, 1.09 s after; unbounded it was 3.53 s). Intra stays out: its reconstruction is what the next block in the macroblock predicts from. Inter chroma AC and the 8x8 path are not covered yet.
h264: withdraw the propagation explanation from the RD quantisation noteAhmet Kaan Gümüş · c844bb5
h264: withdraw the propagation explanation from the RD quantisation note The addendum blamed the superset-measures-worse result on a reference picture's quality being worth more than the local metric can see. x264 reports mbtree=0 rc=cqp in the streams this test compares against, so it takes its 0.2 dB with no propagation term either, and the explanation does not hold. The measurement stands; the cause is named as unsettled, with the two remaining suspects and the experiment that separates them.
h264: record what coefficient-level RD quantisation measuredAhmet Kaan Gümüş · cf13a82
h264: record what coefficient-level RD quantisation measured x264's trellis is worth 0.193 dB on the film clip and 0.208 on the screen capture, re-measured against `trellis=0` now that the mode decision has changed. A coefficient-level walk-back, with a scan-position-aware bit estimate and the finished macroblocks picked on exact coded bits, buys about 0.02 of that, so it is not landed: it doubles the inter coding work for a fiftieth of the distance. Two results worth keeping. A superset of candidates chosen on exact local cost measured 0.05 dB worse than a pair of them, which is local rate-distortion being myopic about a reference picture the next nine predict from. And the generator walks levels on an estimate rather than against the CABAC context that will actually code them, which is where x264's version gets its order of magnitude.
h264: decide intra against inter on real coded costAhmet Kaan Gümüş · dbbd3cc
h264: decide intra against inter on real coded cost The comparison was a prediction-domain SATD, discounted by a fixed 3/4 for the Intra_4x4 that usually follows, against a coded inter cost, with the intra side's signalling paid for by a guessed twelve bits. Both branches are now coded for real and the one with the smaller squared error plus lambda times its actual bits is kept -- the decision x264 makes from subme 6 up, and the mode half of the 0.83 dB the ablation in the lane report put behind its refinement. BD-PSNR against x264 at GOP 10 over QP 22/26/30/34: the film clip goes -1.043 to -0.728, the screen capture -1.064 to -0.500, and the bit premium falls with the distance rather than being traded for it (the screen capture spends +17.2% over x264 at QP 22 where it spent +34.4%). The synthetic clip loses 0.074 dB; it prefers a heavier rate term in that decision, which the two real clips do not, so the standard multiplier goes in unscaled and its floor moves -4.5 to -4.6. Each P macroblock is coded twice and the loser's reconstruction and entropy writer are thrown away: one measurement run went 28.8 s to 30.8 s wall. Intra_4x4 in P pictures was re-swept under the new decision and stays on everywhere; the two constants of the old decision are deleted rather than re-swept, because nothing reads them any more.