forge
Explore
Log in

Don't you dare go Hollow

Commits

Commits on 8a5feaaf4eec5ffa092cf5d42e7919f05c221426Filtered to crates/ec-h265/src/encoder.rsClear filter

2026-09-06

feat(h265): default 4x4 transform skip to the per-block RD decisionAhmet Kaan Gümüş · c7b6783
feat(h265): default 4x4 transform skip to the per-block RD decision

Measured over the four-QP ladder against x265 at matched features, BD-PSNR
all-plane: screen capture A -0.438 -> +0.918, B +0.561 -> +0.781, C +0.099 ->
+0.008, film +0.468 -> +0.460. The tool costs a second quantise-and-reconstruct
pass per committed 4x4 luma block (ladder 111s -> 290s on screen capture A,
427s -> 494s on film); TransformSkip::Off buys that back.

The pinned encode hashes move with the default.
feat(h265): decide transform skip per 4x4 luma block by rate-distortionAhmet Kaan Gümüş · a9d41bf
feat(h265): decide transform skip per 4x4 luma block by rate-distortion

Unconditional 4x4 transform skip is worth +1.8 dB BD-PSNR-YUV on one
screen-capture clip and -0.34 dB on another, so the tool wants a per-block
decision, not a switch. TransformSkip::Rd codes the committed 4x4 luma block
both ways and keeps the cheaper one.

The writer emitted the transform_skip_flag only when it was set, which was
consistent only because every 4x4 skipped; the decoder reads a bin for every
4x4 once the PPS enables the tool. encode_residual now takes Option<bool>:
None when the PPS left the tool off, Some(v) for the flag to write.

2026-08-28

perf(h265): estimated per-context fracbits table replaces exact CABAC replay in RDOQ trial costingAhmet Kaan Gümüş · 50e18de
perf(h265): estimated per-context fracbits table replaces exact CABAC replay in RDOQ trial costing

RDOQ's per-candidate rate was priced by re-simulating the exact adaptive
CABAC coder for every trial (encode_subblock measured 26% self time, cost
structural to exact counting since range/low/context state carries forward).
Adds an x265/HM-`entropyBits`-style estimated fractional-bit table
(ENTROPY_BITS[64], entropy of the current CDF/probability state via the
CABAC probability-state geometric model, alpha=0.9493) and a CabacEncoder
`estimating` mode that looks it up instead of replaying range/renorm
arithmetic. Only RDOQ's dedicated counting instrument (`rdoq_enc`) ever
estimates; the committing encoder always writes exact bits, so streams stay
conformant.

Measured: ec-bench h265 640x360x10f encode ~2953ms -> ~1833ms (1.61x, 4-run
median each). bd_psnr_vs_x265 (synthetic clip): BD-PSNR-YUV +7.880 -> +7.948
dB vs x265 (a gain, not a loss), wall time 28.85s -> 20.70s. Both comfortably
clear the repo's adopt bar (speedup >=1.15x, BD loss <=0.05 dB) with room to
spare, so `EncoderConfig::rdoq_estimate` defaults on; `false` keeps the
exact-replay path for A/B. rdoq_cache_hash's pinned bytes re-pinned to the
new default's output.

2026-08-26

feat(h265): in-loop deblocking filter, on by defaultAhmet Kaan Gümüş · 96b7b12
feat(h265): in-loop deblocking filter, on by default

Spec 8.7.2, written from the text. An intra-only stream simplifies it
twice over: intra prediction reads unfiltered reconstruction, so the
filter is a post-pass over the finished picture and the picture-hash SEI
stays honest; and every edge has bS = 2, so the whole strength
derivation reduces to finding the transform-block boundaries.

TuMap carries one byte per 4x4 unit -- log2 of the transform covering
it. Transform blocks of side S are aligned to multiples of S, so an edge
at x is a boundary exactly when x % S == 0, and no edge list is needed.
Each wavefront worker publishes its band; the encoder stitches them,
filters every vertical edge, then every horizontal one over the result.

Writing the filter exposed an encoder bug: the RQT split trial marks
four child transform blocks, and when the nosplit trial won nothing
rewrote those cells, so the map reported a boundary inside a 32x32
transform. Reconstruction and coefficients were restored between trials;
the side map was not. The nosplit branch now marks its own transform,
and tu_log2 rides the CU-depth meta snapshot.

ffmpeg decodes every shape bit-exactly with the filter on. BD-PSNR
against a deblocking x265, our filter off then on: film -0.197 ->
+0.063 dB, screen capture +0.606 -> +0.693, web clip +0.567 -> +0.686,
phone clip +0.113 -> +0.162, synthetic +8.781 -> +8.796. Every clip
improves, so it defaults on.

2026-08-25

feat(h265): a 64x64 coding tree block may stay one coding unitAhmet Kaan Gümüş · 826a8f8
feat(h265): a 64x64 coding tree block may stay one coding unit

HEVC's largest transform is 32x32, so a 64x64 intra coding unit splits its
transform tree without a split_transform_flag -- the split is inferred from
log2TrafoSize > MaxTbLog2SizeY -- and predicts per 32x32 transform block in
z-order, each quadrant marked coded before the next reads its neighbours.
What the coding unit buys is three split flags and three mode signallings,
against one luma direction for the whole 64x64.

On by default; only reachable with ctb_size 64, which is not the default.
Against always splitting a 64x64 tree block it is worth +0.002 dB BD-PSNR on
a film frame and +0.098 dB on a screen capture.
feat(h265): residual quadtree, one split level, on by defaultAhmet Kaan Gümüş · 11904c0
feat(h265): residual quadtree, one split level, on by default

A 2Nx2N intra coding unit may now split its luma transform once into four
half-size children, chosen against the unsplit block by J = SSD + lambda*bits.
Chroma splits with the tree while its own blocks stay 4x4 or larger; at an 8x8
luma tree chroma stays at the parent size and is coded with the last child
(7.3.8.8). The parent luma cbf is the OR of the children's.

Measured against x265 over the four-point ladder it is worth +0.010 dB BD-PSNR
on film and +0.080 dB on screen capture, so it is on by default.

Flipping the default surfaced a transform-skip desync: transform_skip_flag is
read for every 4x4 residual block once the picture parameter set enables skip,
and the encoder decided it from the coding unit's size, so the 4x4 chroma
children of a 16x16 unit were coded with a real transform and no flag. The
decision now travels by the transform block's own size.
feat(h265): transform skip on 4x4 transform unitsAhmet Kaan Gümüş · f5dbd0b
feat(h265): transform skip on 4x4 transform units

A 4x4 transform unit may now code its residual samples directly instead
of transforming them (transform_skip_flag, 7.3.8.11), which is what
screen content wants: sharp edges spread over every basis function, and
the transform costs bits to undo them.

The PPS carries transform_skip_enabled_flag, the flag itself is coded
per 4x4 TU on its own pair of contexts (luma and chroma, init value 139
in Table 9-25), and the residual path swaps the integer transform for a
pair of shifts. Those shifts are the whole feature: the decoder scales
what it reads by tsShift = 5 + Log2(nTbS) and takes the bit-depth shift
of 12 back off, so a coefficient carries the sample scaled by the
difference. Writing the encoder's own shift as tsShift instead was
caught by the decode: 3117 samples of a 64x64 picture differed.

Off by default, so every existing stream stays byte-identical; the BD
gate reaches it through EC_H265_TSKIP.

Gated by ffmpeg decoding three picture shapes sample for sample against
the encoder's reconstruction, and by a unit round trip over every 8-bit
residual value. Three mutations were checked to fail those: tsShift one
short, the flag never written, and one wrong context init value.
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(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.
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.
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.

2026-08-14

perf(h265): 32x32 coding trees by default, for the wavefront rowsAhmet Kaan Gümüş · 7a75a9b
perf(h265): 32x32 coding trees by default, for the wavefront rows

The wavefront hands one CTB row to a worker, so the tree size sets the
parallelism: 1080 lines are 17 rows at CTB 64 but 34 at 32, and 17 rows
dealt round-robin over twelve workers leaves seven of them holding half
the work of the other five.

Measured at 1080p QP 27: the sizes are identical on one thread (1.80 fps
each) and 9.03 vs 7.92 fps on twelve, for 1.0% more bits and 0.02 dB less
PSNR. Both numbers are now tests: perf.rs measures the two sizes
alternately so a drifting machine load cannot favour whichever ran first,
and conformance.rs bounds the bits and the PSNR against 64. The ffmpeg
bit-exactness oracle now codes shapes at both tree sizes.

The bigger figure that prompted this (3.5 vs 11.8 fps) was an end-to-end
export at QP 40 on real content, not this crate's pure-encode harness.
feat(h265-syntax): the DPB fields a stateless hardware decode needsAhmet Kaan Gümüş · a3e5dd1
feat(h265-syntax): the DPB fields a stateless hardware decode needs

A software decoder derives its reference picture set as it goes; a
stateless one has to hand the driver finished picture lists, so the
parser now keeps what it used to walk past:

- `ShortTermRefPicSet` carries `DeltaPocS0`/`S1` and the used-by-current
  flags, including the inter-set prediction of 7.4.8, and the SPS keeps
  its sets so a slice that names one by index can resolve it.
- `SliceHeader` carries the resolved set, the long-term entries with
  their `DeltaPocMsbCycleLt` accumulation (7-52), the reference list
  modification entries and a parsed `pred_weight_table()` whose chroma
  offsets are derived per 7-56 rather than left as raw deltas.
- `SliceHeader::write_without_alignment` writes a header without its
  closing `byte_alignment()`, which is what a VA-API encoder submits as
  a packed header, and `write` keeps its old behaviour on top of it.

The fuzz suite caught an overflow in the weight derivation on the way
in: both terms come straight off the wire, so 7-56 is evaluated in 64
bits and clamped.
feat(h265-syntax): the fields a VA-API decoder asks for and this encoder does not writeAhmet Kaan Gümüş · 4d59579
feat(h265-syntax): the fields a VA-API decoder asks for and this encoder does not write

An audit of every field in VAPictureParameterBufferHEVC and
VASliceParameterBufferHEVC against what this crate hands back turned up
four the parser walked past: PCM depths and block sizes, explicit tile
column and row geometry, colour_plane_id, and the emulation prevention
byte count of the slice data. All four are carried now, with round-trip
tests, because the consumer is a hardware decode path that cannot
re-parse a header the parser already read.

What is still deliberately absent, and why: reference lists and the
picture buffer (decoder state, not syntax), scaling lists (refused as
Unsupported), and pred_weight_table (walked for length, not modelled -
no HEVC stream this family produces uses weighted prediction).
feat(h265): full-depth quadtree search, VA-API check, parse-side fuzzAhmet Kaan Gümüş · b19a281
feat(h265): full-depth quadtree search, VA-API check, parse-side fuzz

The search goes down to 8x8 by default because on real pictures that is
both better and no slower: measured on a 1080p camera frame at QP 22,
-27% bits and +1.5 dB against stopping at 16x16, at the same wall time.
The 16x16 floor stays available as a setting.

Two defects the earlier tests could not see, both found by pointing the
encoder at real footage:

- stopping the search early skipped split_cu_flag entirely, while the
  sequence still allowed a split. Every picture decoded to noise. The
  flag is written now whatever the search decides.
- a fuzzed SPS could name a 45-bit POC field and take ec-core's bit
  reader past its documented contract. Picture size, POC width and
  long-term set count are validated where they are parsed.

Also: VA-API decode of the encoder's own output is a test (radeonsi, real
GPU), progress counters are one per cache line - twelve workers polling
eight counters per line spend their time invalidating each other - and
waits back off to a sleep instead of spinning on a core someone needs.
feat(h265): wavefront-parallel intra IDR encoderAhmet Kaan Gümüş · fa29faa
feat(h265): wavefront-parallel intra IDR encoder

One encode_idr call uses every core: entropy_coding_sync (WPP) makes each
CTB row a substream, a worker starts a row once the row above is two CTBs
ahead, and the only shared mutable state is one atomic byte per boundary
sample plus a progress counter. No unsafe, no rayon, and the bitstream is
identical whatever the thread count - a test asserts that.

Deblocking and SAO are signalled off. An intra-only stream predicts from
its own reconstruction, so an in-loop filter changes what a decoder shows
without changing what either side predicts from; off, the encoder's
reconstruction is bit-identical to ffmpeg's decode, which the conformance
test checks at four picture shapes including 1916x1080.