forge
Explore
Log in

Don't you dare go Hollow

Decide the P shape and skip flag on coded cost

Browse files at this commit

6897ed71473c3c33bb88f0578eeccaa7b2c64540Ahmet Kaan GümüşParent: cdfa038
  • perf
    • decide the P shape and skip flag on coded cost
Show full message
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.
crates/ec-h264/src/enc/mb.rsmodified+72 -11
@@ -471,7 +471,7 @@ pub(crate) fn encode_mb(pic: &mut Picture, e: &mut MbEnc<'_>, w: &mut EncEntropy
471471 }
472472 }
473473
474- let mut inter: Option<InterChoice> = None;
474+ let mut inter: Option<Vec<InterChoice>> = None;
475475 if e.slice_type == SliceType::P {
476476 inter = Some(choose_inter(pic, e, mb_x, mb_y));
477477 }
@@ -499,7 +499,7 @@ pub(crate) fn encode_mb(pic: &mut Picture, e: &mut MbEnc<'_>, w: &mut EncEntropy
499499 // P macroblock is coded twice, and the loser's reconstruction and entropy
500500 // writer are thrown away.
501501 let intra_cost = intra_pre_cost(pic, e, &nbr, mb_x, mb_y);
502- let Some(choice) = inter else {
502+ let Some(choices) = inter else {
503503 encode_intra_mb(pic, e, w, mb_addr, nbr, intra_cost);
504504 return;
505505 };
@@ -510,14 +510,29 @@ pub(crate) fn encode_mb(pic: &mut Picture, e: &mut MbEnc<'_>, w: &mut EncEntropy
510510 lambda_ssd(e.qp)
511511 };
512512 let before = save_mb_state(pic, e, mb_addr);
513- let mut w_inter = w.clone();
514- let inter_bits = {
515- let start = w_inter.bit_len();
516- encode_inter_mb(pic, e, &mut w_inter, mb_addr, nbr, choice);
517- (w_inter.bit_len() - start) as f64
513+ // The shape and the skip flag are ranked the same way intra and inter are:
514+ // by coding each candidate and measuring it. The SATD total that ordered
515+ // them inside the search is a prediction-domain estimate that never sees
516+ // the residual it causes, which is exactly the step x264 takes between
517+ // subme 4 and subme 6 -- the 0.29 dB the feature ladder localised there.
518+ let rd_cands = if e.preset == Preset::Balanced {
519+ choices.len().min(SHAPE_RD_CANDIDATES)
520+ } else {
521+ 1
518522 };
519- let inter_rd = ssd_mb(pic, e, mb_x, mb_y) as f64 + lambda * inter_bits;
520- let after_inter = save_mb_state(pic, e, mb_addr);
523+ let mut best_inter: Option<(f64, MbState, EncEntropy)> = None;
524+ for &choice in &choices[..rd_cands.max(1)] {
525+ load_mb_state(pic, e, mb_addr, &before);
526+ let mut w_c = w.clone();
527+ let start = w_c.bit_len();
528+ encode_inter_mb(pic, e, &mut w_c, mb_addr, nbr, choice);
529+ let bits = (w_c.bit_len() - start) as f64;
530+ let rd = ssd_mb(pic, e, mb_x, mb_y) as f64 + lambda * bits;
531+ if best_inter.as_ref().is_none_or(|b| rd < b.0) {
532+ best_inter = Some((rd, save_mb_state(pic, e, mb_addr), w_c));
533+ }
534+ }
535+ let (inter_rd, after_inter, w_inter) = best_inter.expect("at least one inter candidate");
521536 load_mb_state(pic, e, mb_addr, &before);
522537
523538 let mut w_intra = w.clone();
@@ -742,7 +757,26 @@ impl PShape {
742757 /// half the bits it spends cost more than the chroma it buys.
743758 const CHROMA_ME_WEIGHT: f64 = 0.5;
744759
760+/// How many inter candidates the macroblock decision codes before choosing,
761+/// most promising first. One is the SATD winner alone, which is what this used
762+/// to do; five is every shape the search costed plus P_Skip. BD-PSNR-YUV
763+/// against x264 at GOP 10 over QP 22/26/30/34, at `Preset::Balanced`:
764+///
765+/// ```text
766+/// film 3840x1608 screen 2560x1440
767+/// 1 candidate -0.580 -0.474
768+/// 2 -0.521 -0.459
769+/// 3 -0.513 -0.447
770+/// 5 -0.504 -0.406
771+/// ```
772+///
773+/// monotone in the count with no turnover, so the decision is taken at the
774+/// full list. The SATD total that used to rank the shapes is a
775+/// prediction-domain estimate that never sees the residual it causes.
776+const SHAPE_RD_CANDIDATES: usize = 5;
777+
745778 /// The inter decision for a P macroblock.
779+#[derive(Clone, Copy)]
746780 struct InterChoice {
747781 shape: PShape,
748782 /// One motion vector per partition.
@@ -754,7 +788,7 @@ struct InterChoice {
754788 }
755789
756790 /// Motion search plus the skip candidate.
757-fn choose_inter(pic: &Picture, e: &MbEnc<'_>, mb_x: usize, mb_y: usize) -> InterChoice {
791+fn choose_inter(pic: &Picture, e: &MbEnc<'_>, mb_x: usize, mb_y: usize) -> Vec<InterChoice> {
758792 let reference = e.reference.expect("a P slice has a reference");
759793 let ctx = MvCtx {
760794 mb_x,
@@ -976,6 +1010,9 @@ fn choose_inter(pic: &Picture, e: &MbEnc<'_>, mb_x: usize, mb_y: usize) -> Inter
9761010 };
9771011
9781012 let mut best = (PShape::Whole, [mv16; 4], cost16);
1013+ // Every shape the search costed, kept so the macroblock decision can rank
1014+ // them on coded cost instead of on this SATD total (see `encode_mb`).
1015+ let mut evaluated = vec![(PShape::Whole, [mv16; 4])];
9791016 // Halves, seeded with the whole-macroblock winner. The predictor used here
9801017 // is the whole-macroblock one rather than each half's own: the real
9811018 // predictors are derived in coding order when the choice is made, and this
@@ -1035,6 +1072,7 @@ fn choose_inter(pic: &Picture, e: &MbEnc<'_>, mb_x: usize, mb_y: usize) -> Inter
10351072 mvs[part] = mv;
10361073 total += cost + chroma_satd(bx * 4, by * 4, w, h, mv);
10371074 }
1075+ evaluated.push((shape, mvs));
10381076 if total < best.2 {
10391077 best = (shape, mvs, total);
10401078 }
@@ -1074,12 +1112,35 @@ fn choose_inter(pic: &Picture, e: &MbEnc<'_>, mb_x: usize, mb_y: usize) -> Inter
10741112 );
10751113 }
10761114 }
1077- InterChoice {
1115+ let winner = InterChoice {
10781116 shape: best.0,
10791117 mv: best.1,
10801118 skip_mv,
10811119 prefer_skip: best.0 == PShape::Whole && skip_cost <= best.2,
1120+ };
1121+ // The SATD winner first, then the shapes it beat, then the skip candidate
1122+ // when the winner is not already it. The caller codes as many of these as
1123+ // its preset allows and keeps the one with the smallest coded cost.
1124+ let mut cands = vec![winner];
1125+ for (shape, mv) in evaluated {
1126+ if shape != winner.shape || winner.prefer_skip {
1127+ cands.push(InterChoice {
1128+ shape,
1129+ mv,
1130+ skip_mv,
1131+ prefer_skip: false,
1132+ });
1133+ }
1134+ }
1135+ if !winner.prefer_skip {
1136+ cands.push(InterChoice {
1137+ shape: PShape::Whole,
1138+ mv: [skip_mv; 4],
1139+ skip_mv,
1140+ prefer_skip: true,
1141+ });
10821142 }
1143+ cands
10831144 }
10841145
10851146 /// Quantise and reconstruct the luma residual of a non-Intra_16x16 macroblock,