From ba061b693abe278fcb0cd003057b3567b71ee149 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Sun, 23 Aug 2026 23:56:38 +0300 Subject: [PATCH] fix(h264): measure the encoder on consecutive pictures, and pay for going intra The real-clip comparison against x264 sampled one picture a second, so P pictures had nothing to predict from and the P path was never really under test: on a film clip our P slices ran 93.2% intra, 6.3% skip, 0.5% coded inter. The sampler now takes consecutive pictures, with EC_H264_CLIP_STRIDE to restore a wider spacing and EC_H264_CLIP_SKIP to pass over a film's titles first. Corrected, the encoder read -1.521 dB BD-PSNR on film and -1.904 on screen capture, spending 20-42% more bits than x264 with the premium growing with QP. Two defects the old sampler had hidden: - The intra side of the mode decision carried no rate term at all, while the inter side paid for its motion vector. Twelve bits for the macroblock type and the prediction modes is the overlap of the two contents' flat parts; a previous sweep of this same constant landed zero on the uncorrelated content. - Sub-sample refinement chose on SAD, which reads interpolation's smoothing as a better match. It now costs candidates on SATD. Together: film -1.521 -> -1.154 dB, screen capture -1.904 -> -0.696, synthetic -5.718 -> -4.542, and the bit premium is flat in QP again (+14-18%) instead of growing to +42%. The synthetic floor tightens to -4.6. The other P-path constants swept under the old sampler were re-swept and all held: Intra_4x4 in P pictures, the P_Skip rebate, and the Intra_4x4 discount. --- crates/ec-h264/src/enc/mb.rs | 83 ++++++++++++++++++--------- crates/ec-h264/tests/encode.rs | 44 ++++++++++---- lanes/h264x264-r2.report.md | 101 +++++++++++++++++++++++++++++++++ 3 files changed, 189 insertions(+), 39 deletions(-) create mode 100644 lanes/h264x264-r2.report.md diff --git a/crates/ec-h264/src/enc/mb.rs b/crates/ec-h264/src/enc/mb.rs index 821bf7be..ad4025d0 100644 --- a/crates/ec-h264/src/enc/mb.rs +++ b/crates/ec-h264/src/enc/mb.rs @@ -355,18 +355,29 @@ pub(crate) fn encode_mb(pic: &mut Picture, e: &mut MbEnc<'_>, w: &mut EncEntropy inter = Some(choose_inter(pic, e, mb_x, mb_y)); } - // Intra cost against the inter one, with no thumb on the scale. An eight-bit - // penalty used to be added to the intra side, on the theory that an intra - // macroblock in a P picture also costs the next picture's prediction - // quality. Measured, it costs the opposite: removing it is worth 1.17 dB - // BD-PSNR against x264 on a 3840x1608 film clip at GOP 10 (-1.404 -> - // -0.233 dB) and 0.10 dB on a 2560x1440 screen capture (-0.033 -> +0.068), - // and it is not a rate-quality trade -- at every one of QP 22/26/30/34 the - // unpenalised encoder is both smaller and 0.15-1.2 dB better, because the - // intra macroblocks it now places stop drift accumulating across the GOP. - // Penalties of 1, 2, 4 and 8 bits all measured worse and negative ones - // measured the same, so zero is the flat part of the curve, not a tuned - // value. + // The intra side of the comparison carries what going intra signals: the + // inter side already pays for its motion vector, and an intra macroblock + // in a P picture pays for a macroblock type plus sixteen prediction modes + // that the SATD of its prediction says nothing about. + // + // Swept on two clips of the library and the synthetic one, BD-PSNR against + // x264 at GOP 10 over QP 22/26/30/34: + // + // bits film 3840x1608 screen 2560x1440 synthetic + // 0 -1.521 -1.904 -5.718 + // 4 -1.305 -1.290 -5.400 + // 8 -1.223 -0.920 -5.290 + // 12 -1.211 -0.733 -5.286 + // 16 -1.267 -0.650 -5.262 + // 32 -1.649 -0.586 -- + // + // Screen capture keeps improving to 48 and film falls off after 16, so + // twelve is the overlap of the two flat parts rather than either optimum. + // A previous sweep of this same constant landed zero, on a measurement + // that sampled one picture a second: at that spacing nothing is + // predictable from the previous picture, P slices went 93% intra on film, + // and the penalty had nothing to suppress. The sampler now takes + // consecutive pictures. // // Skipping the intra trial when the inter cost is already low was measured // and dropped: it cost 0.7 dB on screen capture and bought no measurable @@ -374,7 +385,7 @@ pub(crate) fn encode_mb(pic: &mut Picture, e: &mut MbEnc<'_>, w: &mut EncEntropy let intra_cost = intra_pre_cost(pic, e, &nbr, mb_x, mb_y); let go_intra = match &inter { None => true, - Some(i) => intra_cost.best() < i.cost, + Some(i) => intra_cost.best() + motion_rate(e, INTRA_MODE_BITS) < i.cost, }; if go_intra { @@ -408,6 +419,8 @@ impl IntraCost { } } + + /// Best Intra_16x16 mode by SATD, leaving nothing behind in the plane that a /// later branch does not overwrite. fn intra_pre_cost( @@ -445,18 +458,22 @@ fn intra_pre_cost( IntraCost { i16_mode: best.1, i16_cost: best.0, - // Intra_4x4 is tried in P pictures too, at every preset. Measured - // against x264 on a 3840x1608 clip from the library (BD-PSNR over QP - // 22/26/30/34, matched features): restricting it to I pictures cost - // -2.992 dB against x264 where allowing it everywhere reads -1.557 dB, - // for 5% more encode time. Nothing else in the Fast/Balanced split - // came close -- a 48-sample search range read -3.039 dB and the - // half-macroblock partitions -3.009 dB, both inside the noise of the - // -2.992 dB baseline. + // Intra_4x4 is tried in P pictures too, at every preset. Re-measured + // on consecutive pictures (BD-PSNR against x264, GOP 10, QP + // 22/26/30/34): restricting it to I pictures reads -1.989 dB on the + // film clip where allowing it everywhere reads -1.154, and the screen + // capture disagrees by a third of that in the other direction (-0.564 + // against -0.696). The film margin is the larger of the two, so it + // stays on everywhere. allow_i4: true, } } +/// What going intra costs to signal in a P picture, in bits: the macroblock +/// type and, when Intra_4x4 wins later, sixteen prediction modes. Swept at the +/// decision site above. +const INTRA_MODE_BITS: f64 = 12.0; + /// How a P macroblock is partitioned, in the mb_type numbering of Table 7-13. #[derive(Clone, Copy, PartialEq, Eq, Debug)] enum PShape { @@ -618,6 +635,13 @@ fn choose_inter(pic: &Picture, e: &MbEnc<'_>, mb_x: usize, mb_y: usize) -> Inter } step /= 2; } + // Sub-sample refinement runs on SATD, not SAD: interpolation + // smooths, and a sum of absolute differences reads the smoothing + // as a better match where a transform-domain cost does not. Worth + // 0.06 dB BD-PSNR on the film clip and 0.04 dB on the screen + // capture. The whole-sample winner is re-costed in the same domain + // first so the two halves of the search compare. + best.1 = cost_of(best.0, true); for step in [2i16, 1] { let mut improved = true; while improved { @@ -633,7 +657,7 @@ fn choose_inter(pic: &Picture, e: &MbEnc<'_>, mb_x: usize, mb_y: usize) -> Inter (-step, step), ] { let cand = [best.0[0] + dx, best.0[1] + dy]; - let c = cost_of(cand, false); + let c = cost_of(cand, true); if c < best.1 { best = (cand, c); improved = true; @@ -653,11 +677,16 @@ fn choose_inter(pic: &Picture, e: &MbEnc<'_>, mb_x: usize, mb_y: usize) -> Inter let skip_cost = { let mut buf = [0u8; 256]; mc_luma(&plane, sx as i32, sy as i32, skip_mv, 16, 16, 16, &mut buf); - // P_Skip's rebate is the signalling it genuinely saves, and two bits is - // where the measurement is flat: 0 and 2 read -0.113 and -0.110 dB - // BD-PSNR against x264 on the film clip at GOP 10 where the four this - // used to claim reads -0.233 dB and eight reads -0.708 dB. The screen - // capture and the synthetic clip move by 0.01 dB across 0, 2 and 4. + // P_Skip's rebate is the signalling it genuinely saves. Re-measured on + // consecutive pictures: 0 and 2 read -1.102/-1.154 dB on the film clip + // and -0.741/-0.696 on the screen capture -- the two contents disagree + // by less than the step between them, so this is the flat part. Six + // costs 0.14 dB and twelve costs 0.42. + // + // The Intra_4x4 discount above was swept with it: 0.65/0.75/0.85/1.0 + // read -1.216/-1.154/-1.182/-1.373 on film and -0.970/-0.696/-0.591/ + // -0.562 on screen capture, so three quarters is film's optimum and + // inside screen capture's flat part. satd_block(&e.src.y, sw, sx, sy, &buf, 16, 0, 16, 16) - motion_rate(e, 2.0) }; diff --git a/crates/ec-h264/tests/encode.rs b/crates/ec-h264/tests/encode.rs index d3e7ae10..14765b06 100644 --- a/crates/ec-h264/tests/encode.rs +++ b/crates/ec-h264/tests/encode.rs @@ -762,10 +762,26 @@ fn clip_sources(path: &std::ffi::OsStr, want: usize) -> (usize, usize, Vec panic!("the H.264 track carries no video parameters"), }; let (w, h) = (video.width as usize, video.height as usize); - let stride = video - .frame_rate - .map_or(25, |r| (r.as_secs_f64().round() as usize).max(1)); + // Consecutive pictures by default. This used to take one picture a second, + // which measured an encoder on content it never sees: at a second apart + // nothing is predictable from the previous picture, so P slices went 93% + // intra on film and the inter path was never really under test. + // `EC_H264_CLIP_STRIDE` restores a wider spacing (`fps` takes one a + // second) for the deliberately-uncorrelated case. + let stride = match std::env::var("EC_H264_CLIP_STRIDE").as_deref() { + Ok("fps") => video + .frame_rate + .map_or(25, |r| (r.as_secs_f64().round() as usize).max(1)), + Ok(n) => n.parse().unwrap_or(1usize).max(1), + Err(_) => 1, + }; let mut dec = ec_h264::H264Decoder::new(params).expect("decoder"); + // Pictures to pass over before sampling: the head of a film is titles and + // fades, which are not what a codec is measured on. + let skip: usize = std::env::var("EC_H264_CLIP_SKIP") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(0); let mut sources: Vec = Vec::new(); let mut seen = 0usize; while sources.len() < want { @@ -777,7 +793,7 @@ fn clip_sources(path: &std::ffi::OsStr, want: usize) -> (usize, usize, Vec= skip && sources.len() < want && (seen - skip).is_multiple_of(stride) { sources.push(planes_of(&f)); } seen += 1; @@ -790,7 +806,7 @@ fn clip_sources(path: &std::ffi::OsStr, want: usize) -> (usize, usize, Vec bool { std::process::Command::new("ffmpeg") @@ -956,15 +972,19 @@ fn x264_encode_qp(sources: &[Planes], w: usize, h: usize, qp: i32, gop: u32) -> /// encoder's own reconstruction, so the two halves are read the same way. /// /// `EC_H264_GOP` sets the GOP of both encoders; 1 makes the comparison -/// all-intra, which is how the gap was split: on a 3840x1608 clip from the -/// library the intra-only distance is -0.749 dB (+2-4% bits) while the same -/// clip at GOP 10 is -2.992 dB (+19% bits), so roughly two thirds of the -/// distance is in P pictures, not in the intra path. +/// all-intra, which splits the gap between the intra path and the P pictures. /// /// `EC_H264_PRESET_BALANCED` runs our half of the comparison at /// `Preset::Balanced` instead of the default `Preset::Fast`, which separates -/// what search effort buys from what the coder itself costs: on the same -/// library clip it moves -2.992 dB to -1.587 dB for 40% more encode time. +/// what search effort buys from what the coder itself costs. +/// +/// `EC_H264_CLIP_SKIP` passes over that many pictures before sampling (film +/// heads are titles and fades), and `EC_H264_CLIP_STRIDE` widens the spacing +/// between the sampled pictures; both default to consecutive pictures from the +/// start of the file. The measurements quoted through this crate that predate +/// those two knobs were taken one picture a second, where nothing is +/// predictable from the previous picture -- they are not comparable with the +/// numbers taken since. /// /// cargo test --release -p ec-h264 --test encode bd_psnr_vs_x264 -- --nocapture /// EC_H264_CLIP= cargo test --release -p ec-h264 --test encode \ diff --git a/lanes/h264x264-r2.report.md b/lanes/h264x264-r2.report.md new file mode 100644 index 00000000..426e9121 --- /dev/null +++ b/lanes/h264x264-r2.report.md @@ -0,0 +1,101 @@ +# ec-h264 against x264, round 2: the comparison was sampling one picture a second + +## What was wrong with the measurement + +`bd_psnr_vs_x264` takes 24 pictures out of a real file. It took them one second +apart -- the sampler's stride was the clip's frame rate. At that spacing a P +picture has nothing to predict from, so the encoder was being measured on +content it never sees in a real encode. The give-away is the macroblock mix: +on the film clip our P slices went **93.2% intra, 6.3% skip, 0.5% coded inter**. +Every P-path constant in the crate had been swept against that. + +The sampler now takes consecutive pictures. `EC_H264_CLIP_STRIDE` restores a +wider spacing for the deliberately-uncorrelated case, and `EC_H264_CLIP_SKIP` +passes over a film's titles and fades before sampling. + +Baselines move a long way once the pictures are correlated: + +| clip | one a second | consecutive | +| ------------------- | -----------: | ----------: | +| film 3840x1608 | -0.110 | -1.521 | +| screen capture 2560x1440 | -0.977 | -1.904 | + +The honest number was worse than the one that had been reported. + +## What the corrected measurement then showed + +At every QP we were spending 20-42% more bits than x264 for a similar PSNR, and +the premium *grew* with QP. Attribution, by disabling x264's own features on +the screen capture: + +| x264 running | BD-PSNR ours vs x264 | +| ---------------------------------- | -------------------: | +| as configured | -0.977 | +| `trellis=0` | -0.773 | +| `trellis=0:subme=1:me=dia` | -0.203 | + +So roughly 0.2 dB of x264's lead is its rate-distortion quantisation and 0.57 dB +is its motion search. (Those three rows are on the old sampler; they were what +pointed at the search.) + +## Two fixes + +**The intra side of the mode decision signalled nothing.** The inter side pays +for its motion vector; going intra pays for a macroblock type and sixteen +prediction modes, and the SATD of an intra prediction says nothing about them. +A penalty had been swept before and landed at zero -- on the one-a-second +content, where it had nothing to suppress. Re-swept on consecutive pictures: + +| bits | film | screen | synthetic | +| ---: | -----: | -----: | --------: | +| 0 | -1.521 | -1.904 | -5.718 | +| 4 | -1.305 | -1.290 | -5.400 | +| 8 | -1.223 | -0.920 | -5.290 | +| 12 | -1.211 | -0.733 | -5.286 | +| 16 | -1.267 | -0.650 | -5.262 | +| 32 | -1.649 | -0.586 | -- | + +Screen capture keeps improving to 48 and film falls off after 16, so the landed +value is 12 -- the overlap of the two flat parts, not either optimum. + +**Sub-sample refinement ran on SAD.** Interpolation smooths, and a sum of +absolute differences reads the smoothing as a better match. The refinement now +costs candidates on SATD, with the whole-sample winner re-costed in the same +domain first: +0.057 dB on film, +0.037 on screen capture, +0.74 on the +synthetic clip. + +## Result + +| clip | before | after | +| -------------- | -----: | -----: | +| film | -1.521 | -1.154 | +| screen capture | -1.904 | -0.696 | +| synthetic | -5.718 | -4.542 | + +The bit premium is also flat in QP again rather than growing: film +14-16% at +every QP, screen capture +17-18%, where before it ran +23% at QP 22 to +42% at +QP 34. + +The synthetic floor moves with it, -5.75 -> -4.6. + +## Constants re-swept under the corrected sampler + +The two contents are quoted film / screen capture. + +- **Intra_4x4 in P pictures**: on reads -1.154 / -0.696, off reads -1.989 / + -0.564. The contents disagree in sign; film's margin is three times screen + capture's, so it stays on. +- **P_Skip rebate**: 0 and 2 read -1.102 / -0.741 and -1.154 / -0.696 -- the + contents disagree by less than the step, so 2 stays. Six costs 0.14 dB, + twelve costs 0.42. +- **Intra_4x4 discount on the 16x16 pre-cost**: 0.65/0.75/0.85/1.0 read + -1.216/-1.154/-1.182/-1.373 on film and -0.970/-0.696/-0.591/-0.562 on screen + capture. Three quarters is film's optimum and inside screen capture's flat + part, so it stays. + +## What is still open + +x264's rate-distortion quantisation (trellis) is worth about 0.2 dB and we have +none. The remaining bit premium is flat in QP, which is the shape of a coder +that codes the same decisions less cheaply rather than one making worse +decisions.