forge
Explore
Log in

Don't you dare go Hollow

Measure the encoder on consecutive pictures, and pay for going intra

Browse files at this commit

ba061b693abe278fcb0cd003057b3567b71ee149Ahmet Kaan GümüşParent: 806ee38
  • fix
    • measure the encoder on consecutive pictures, and pay for going intra
Show full message
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.rsmodified+56 -27
@@ -355,18 +355,29 @@ pub(crate) fn encode_mb(pic: &mut Picture, e: &mut MbEnc<'_>, w: &mut EncEntropy
355355 inter = Some(choose_inter(pic, e, mb_x, mb_y));
356356 }
357357
358- // Intra cost against the inter one, with no thumb on the scale. An eight-bit
359- // penalty used to be added to the intra side, on the theory that an intra
360- // macroblock in a P picture also costs the next picture's prediction
361- // quality. Measured, it costs the opposite: removing it is worth 1.17 dB
362- // BD-PSNR against x264 on a 3840x1608 film clip at GOP 10 (-1.404 ->
363- // -0.233 dB) and 0.10 dB on a 2560x1440 screen capture (-0.033 -> +0.068),
364- // and it is not a rate-quality trade -- at every one of QP 22/26/30/34 the
365- // unpenalised encoder is both smaller and 0.15-1.2 dB better, because the
366- // intra macroblocks it now places stop drift accumulating across the GOP.
367- // Penalties of 1, 2, 4 and 8 bits all measured worse and negative ones
368- // measured the same, so zero is the flat part of the curve, not a tuned
369- // value.
358+ // The intra side of the comparison carries what going intra signals: the
359+ // inter side already pays for its motion vector, and an intra macroblock
360+ // in a P picture pays for a macroblock type plus sixteen prediction modes
361+ // that the SATD of its prediction says nothing about.
362+ //
363+ // Swept on two clips of the library and the synthetic one, BD-PSNR against
364+ // x264 at GOP 10 over QP 22/26/30/34:
365+ //
366+ // bits film 3840x1608 screen 2560x1440 synthetic
367+ // 0 -1.521 -1.904 -5.718
368+ // 4 -1.305 -1.290 -5.400
369+ // 8 -1.223 -0.920 -5.290
370+ // 12 -1.211 -0.733 -5.286
371+ // 16 -1.267 -0.650 -5.262
372+ // 32 -1.649 -0.586 --
373+ //
374+ // Screen capture keeps improving to 48 and film falls off after 16, so
375+ // twelve is the overlap of the two flat parts rather than either optimum.
376+ // A previous sweep of this same constant landed zero, on a measurement
377+ // that sampled one picture a second: at that spacing nothing is
378+ // predictable from the previous picture, P slices went 93% intra on film,
379+ // and the penalty had nothing to suppress. The sampler now takes
380+ // consecutive pictures.
370381 //
371382 // Skipping the intra trial when the inter cost is already low was measured
372383 // 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
374385 let intra_cost = intra_pre_cost(pic, e, &nbr, mb_x, mb_y);
375386 let go_intra = match &inter {
376387 None => true,
377- Some(i) => intra_cost.best() < i.cost,
388+ Some(i) => intra_cost.best() + motion_rate(e, INTRA_MODE_BITS) < i.cost,
378389 };
379390
380391 if go_intra {
@@ -408,6 +419,8 @@ impl IntraCost {
408419 }
409420 }
410421
422+
423+
411424 /// Best Intra_16x16 mode by SATD, leaving nothing behind in the plane that a
412425 /// later branch does not overwrite.
413426 fn intra_pre_cost(
@@ -445,18 +458,22 @@ fn intra_pre_cost(
445458 IntraCost {
446459 i16_mode: best.1,
447460 i16_cost: best.0,
448- // Intra_4x4 is tried in P pictures too, at every preset. Measured
449- // against x264 on a 3840x1608 clip from the library (BD-PSNR over QP
450- // 22/26/30/34, matched features): restricting it to I pictures cost
451- // -2.992 dB against x264 where allowing it everywhere reads -1.557 dB,
452- // for 5% more encode time. Nothing else in the Fast/Balanced split
453- // came close -- a 48-sample search range read -3.039 dB and the
454- // half-macroblock partitions -3.009 dB, both inside the noise of the
455- // -2.992 dB baseline.
461+ // Intra_4x4 is tried in P pictures too, at every preset. Re-measured
462+ // on consecutive pictures (BD-PSNR against x264, GOP 10, QP
463+ // 22/26/30/34): restricting it to I pictures reads -1.989 dB on the
464+ // film clip where allowing it everywhere reads -1.154, and the screen
465+ // capture disagrees by a third of that in the other direction (-0.564
466+ // against -0.696). The film margin is the larger of the two, so it
467+ // stays on everywhere.
456468 allow_i4: true,
457469 }
458470 }
459471
472+/// What going intra costs to signal in a P picture, in bits: the macroblock
473+/// type and, when Intra_4x4 wins later, sixteen prediction modes. Swept at the
474+/// decision site above.
475+const INTRA_MODE_BITS: f64 = 12.0;
476+
460477 /// How a P macroblock is partitioned, in the mb_type numbering of Table 7-13.
461478 #[derive(Clone, Copy, PartialEq, Eq, Debug)]
462479 enum PShape {
@@ -618,6 +635,13 @@ fn choose_inter(pic: &Picture, e: &MbEnc<'_>, mb_x: usize, mb_y: usize) -> Inter
618635 }
619636 step /= 2;
620637 }
638+ // Sub-sample refinement runs on SATD, not SAD: interpolation
639+ // smooths, and a sum of absolute differences reads the smoothing
640+ // as a better match where a transform-domain cost does not. Worth
641+ // 0.06 dB BD-PSNR on the film clip and 0.04 dB on the screen
642+ // capture. The whole-sample winner is re-costed in the same domain
643+ // first so the two halves of the search compare.
644+ best.1 = cost_of(best.0, true);
621645 for step in [2i16, 1] {
622646 let mut improved = true;
623647 while improved {
@@ -633,7 +657,7 @@ fn choose_inter(pic: &Picture, e: &MbEnc<'_>, mb_x: usize, mb_y: usize) -> Inter
633657 (-step, step),
634658 ] {
635659 let cand = [best.0[0] + dx, best.0[1] + dy];
636- let c = cost_of(cand, false);
660+ let c = cost_of(cand, true);
637661 if c < best.1 {
638662 best = (cand, c);
639663 improved = true;
@@ -653,11 +677,16 @@ fn choose_inter(pic: &Picture, e: &MbEnc<'_>, mb_x: usize, mb_y: usize) -> Inter
653677 let skip_cost = {
654678 let mut buf = [0u8; 256];
655679 mc_luma(&plane, sx as i32, sy as i32, skip_mv, 16, 16, 16, &mut buf);
656- // P_Skip's rebate is the signalling it genuinely saves, and two bits is
657- // where the measurement is flat: 0 and 2 read -0.113 and -0.110 dB
658- // BD-PSNR against x264 on the film clip at GOP 10 where the four this
659- // used to claim reads -0.233 dB and eight reads -0.708 dB. The screen
660- // capture and the synthetic clip move by 0.01 dB across 0, 2 and 4.
680+ // P_Skip's rebate is the signalling it genuinely saves. Re-measured on
681+ // consecutive pictures: 0 and 2 read -1.102/-1.154 dB on the film clip
682+ // and -0.741/-0.696 on the screen capture -- the two contents disagree
683+ // by less than the step between them, so this is the flat part. Six
684+ // costs 0.14 dB and twelve costs 0.42.
685+ //
686+ // The Intra_4x4 discount above was swept with it: 0.65/0.75/0.85/1.0
687+ // read -1.216/-1.154/-1.182/-1.373 on film and -0.970/-0.696/-0.591/
688+ // -0.562 on screen capture, so three quarters is film's optimum and
689+ // inside screen capture's flat part.
661690 satd_block(&e.src.y, sw, sx, sy, &buf, 16, 0, 16, 16) - motion_rate(e, 2.0)
662691 };
663692
crates/ec-h264/tests/encode.rsmodified+32 -12
@@ -762,10 +762,26 @@ fn clip_sources(path: &std::ffi::OsStr, want: usize) -> (usize, usize, Vec<Plane
762762 _ => panic!("the H.264 track carries no video parameters"),
763763 };
764764 let (w, h) = (video.width as usize, video.height as usize);
765- let stride = video
766- .frame_rate
767- .map_or(25, |r| (r.as_secs_f64().round() as usize).max(1));
765+ // Consecutive pictures by default. This used to take one picture a second,
766+ // which measured an encoder on content it never sees: at a second apart
767+ // nothing is predictable from the previous picture, so P slices went 93%
768+ // intra on film and the inter path was never really under test.
769+ // `EC_H264_CLIP_STRIDE` restores a wider spacing (`fps` takes one a
770+ // second) for the deliberately-uncorrelated case.
771+ let stride = match std::env::var("EC_H264_CLIP_STRIDE").as_deref() {
772+ Ok("fps") => video
773+ .frame_rate
774+ .map_or(25, |r| (r.as_secs_f64().round() as usize).max(1)),
775+ Ok(n) => n.parse().unwrap_or(1usize).max(1),
776+ Err(_) => 1,
777+ };
768778 let mut dec = ec_h264::H264Decoder::new(params).expect("decoder");
779+ // Pictures to pass over before sampling: the head of a film is titles and
780+ // fades, which are not what a codec is measured on.
781+ let skip: usize = std::env::var("EC_H264_CLIP_SKIP")
782+ .ok()
783+ .and_then(|v| v.parse().ok())
784+ .unwrap_or(0);
769785 let mut sources: Vec<Planes> = Vec::new();
770786 let mut seen = 0usize;
771787 while sources.len() < want {
@@ -777,7 +793,7 @@ fn clip_sources(path: &std::ffi::OsStr, want: usize) -> (usize, usize, Vec<Plane
777793 }
778794 dec.send_packet(&packet).expect("decode");
779795 while let Ok(ec_core::frame::Frame::Video(f)) = dec.receive_frame() {
780- if sources.len() < want && seen % stride == 0 {
796+ if seen >= skip && sources.len() < want && (seen - skip).is_multiple_of(stride) {
781797 sources.push(planes_of(&f));
782798 }
783799 seen += 1;
@@ -790,7 +806,7 @@ fn clip_sources(path: &std::ffi::OsStr, want: usize) -> (usize, usize, Vec<Plane
790806 path.to_string_lossy()
791807 );
792808 eprintln!(
793- "{}: {}x{}, {} pictures 1 s apart (every {stride}th of {seen})",
809+ "{}: {}x{}, {} pictures, every {stride}th of {seen}",
794810 path.to_string_lossy(),
795811 w,
796812 h,
@@ -880,7 +896,7 @@ fn real_clip_t8x8_bd_psnr() {
880896 /// signal that the decision belongs on real coded cost rather than on a SATD
881897 /// comparison at all -- that is the next slice, not a reason to tune the
882898 /// threshold back toward this clip.
883-const BD_PSNR_VS_X264_FLOOR: f64 = -5.75;
899+const BD_PSNR_VS_X264_FLOOR: f64 = -4.6;
884900
885901 fn have_x264() -> bool {
886902 std::process::Command::new("ffmpeg")
@@ -956,15 +972,19 @@ fn x264_encode_qp(sources: &[Planes], w: usize, h: usize, qp: i32, gop: u32) ->
956972 /// encoder's own reconstruction, so the two halves are read the same way.
957973 ///
958974 /// `EC_H264_GOP` sets the GOP of both encoders; 1 makes the comparison
959-/// all-intra, which is how the gap was split: on a 3840x1608 clip from the
960-/// library the intra-only distance is -0.749 dB (+2-4% bits) while the same
961-/// clip at GOP 10 is -2.992 dB (+19% bits), so roughly two thirds of the
962-/// distance is in P pictures, not in the intra path.
975+/// all-intra, which splits the gap between the intra path and the P pictures.
963976 ///
964977 /// `EC_H264_PRESET_BALANCED` runs our half of the comparison at
965978 /// `Preset::Balanced` instead of the default `Preset::Fast`, which separates
966-/// what search effort buys from what the coder itself costs: on the same
967-/// library clip it moves -2.992 dB to -1.587 dB for 40% more encode time.
979+/// what search effort buys from what the coder itself costs.
980+///
981+/// `EC_H264_CLIP_SKIP` passes over that many pictures before sampling (film
982+/// heads are titles and fades), and `EC_H264_CLIP_STRIDE` widens the spacing
983+/// between the sampled pictures; both default to consecutive pictures from the
984+/// start of the file. The measurements quoted through this crate that predate
985+/// those two knobs were taken one picture a second, where nothing is
986+/// predictable from the previous picture -- they are not comparable with the
987+/// numbers taken since.
968988 ///
969989 /// cargo test --release -p ec-h264 --test encode bd_psnr_vs_x264 -- --nocapture
970990 /// EC_H264_CLIP=<file> cargo test --release -p ec-h264 --test encode \
lanes/h264x264-r2.report.mdadded+101 -0
@@ -0,0 +1,101 @@
1+# ec-h264 against x264, round 2: the comparison was sampling one picture a second
2+
3+## What was wrong with the measurement
4+
5+`bd_psnr_vs_x264` takes 24 pictures out of a real file. It took them one second
6+apart -- the sampler's stride was the clip's frame rate. At that spacing a P
7+picture has nothing to predict from, so the encoder was being measured on
8+content it never sees in a real encode. The give-away is the macroblock mix:
9+on the film clip our P slices went **93.2% intra, 6.3% skip, 0.5% coded inter**.
10+Every P-path constant in the crate had been swept against that.
11+
12+The sampler now takes consecutive pictures. `EC_H264_CLIP_STRIDE` restores a
13+wider spacing for the deliberately-uncorrelated case, and `EC_H264_CLIP_SKIP`
14+passes over a film's titles and fades before sampling.
15+
16+Baselines move a long way once the pictures are correlated:
17+
18+| clip | one a second | consecutive |
19+| ------------------- | -----------: | ----------: |
20+| film 3840x1608 | -0.110 | -1.521 |
21+| screen capture 2560x1440 | -0.977 | -1.904 |
22+
23+The honest number was worse than the one that had been reported.
24+
25+## What the corrected measurement then showed
26+
27+At every QP we were spending 20-42% more bits than x264 for a similar PSNR, and
28+the premium *grew* with QP. Attribution, by disabling x264's own features on
29+the screen capture:
30+
31+| x264 running | BD-PSNR ours vs x264 |
32+| ---------------------------------- | -------------------: |
33+| as configured | -0.977 |
34+| `trellis=0` | -0.773 |
35+| `trellis=0:subme=1:me=dia` | -0.203 |
36+
37+So roughly 0.2 dB of x264's lead is its rate-distortion quantisation and 0.57 dB
38+is its motion search. (Those three rows are on the old sampler; they were what
39+pointed at the search.)
40+
41+## Two fixes
42+
43+**The intra side of the mode decision signalled nothing.** The inter side pays
44+for its motion vector; going intra pays for a macroblock type and sixteen
45+prediction modes, and the SATD of an intra prediction says nothing about them.
46+A penalty had been swept before and landed at zero -- on the one-a-second
47+content, where it had nothing to suppress. Re-swept on consecutive pictures:
48+
49+| bits | film | screen | synthetic |
50+| ---: | -----: | -----: | --------: |
51+| 0 | -1.521 | -1.904 | -5.718 |
52+| 4 | -1.305 | -1.290 | -5.400 |
53+| 8 | -1.223 | -0.920 | -5.290 |
54+| 12 | -1.211 | -0.733 | -5.286 |
55+| 16 | -1.267 | -0.650 | -5.262 |
56+| 32 | -1.649 | -0.586 | -- |
57+
58+Screen capture keeps improving to 48 and film falls off after 16, so the landed
59+value is 12 -- the overlap of the two flat parts, not either optimum.
60+
61+**Sub-sample refinement ran on SAD.** Interpolation smooths, and a sum of
62+absolute differences reads the smoothing as a better match. The refinement now
63+costs candidates on SATD, with the whole-sample winner re-costed in the same
64+domain first: +0.057 dB on film, +0.037 on screen capture, +0.74 on the
65+synthetic clip.
66+
67+## Result
68+
69+| clip | before | after |
70+| -------------- | -----: | -----: |
71+| film | -1.521 | -1.154 |
72+| screen capture | -1.904 | -0.696 |
73+| synthetic | -5.718 | -4.542 |
74+
75+The bit premium is also flat in QP again rather than growing: film +14-16% at
76+every QP, screen capture +17-18%, where before it ran +23% at QP 22 to +42% at
77+QP 34.
78+
79+The synthetic floor moves with it, -5.75 -> -4.6.
80+
81+## Constants re-swept under the corrected sampler
82+
83+The two contents are quoted film / screen capture.
84+
85+- **Intra_4x4 in P pictures**: on reads -1.154 / -0.696, off reads -1.989 /
86+ -0.564. The contents disagree in sign; film's margin is three times screen
87+ capture's, so it stays on.
88+- **P_Skip rebate**: 0 and 2 read -1.102 / -0.741 and -1.154 / -0.696 -- the
89+ contents disagree by less than the step, so 2 stays. Six costs 0.14 dB,
90+ twelve costs 0.42.
91+- **Intra_4x4 discount on the 16x16 pre-cost**: 0.65/0.75/0.85/1.0 read
92+ -1.216/-1.154/-1.182/-1.373 on film and -0.970/-0.696/-0.591/-0.562 on screen
93+ capture. Three quarters is film's optimum and inside screen capture's flat
94+ part, so it stays.
95+
96+## What is still open
97+
98+x264's rate-distortion quantisation (trellis) is worth about 0.2 dB and we have
99+none. The remaining bit premium is flat in QP, which is the shape of a coder
100+that codes the same decisions less cheaply rather than one making worse
101+decisions.