forge
Explore
Log in

Don't you dare go Hollow

Rate-distortion quantisation

Browse files at this commit

21ef1929241f6deddec8be5e7ea22533e63224bfAhmet Kaan GümüşParent: 0877a36
  • feat
    • rate-distortion quantisation
Show full message
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.
crates/ec-h265/src/ctu.rsmodified+80 -9
@@ -22,14 +22,32 @@
2222 //! which this encoder spends on the wavefront that makes one `encode` call use
2323 //! every core instead.
2424
25-use crate::cabac::{CabacEncoder, CabacState, ctx};
25+use crate::cabac::{CabacEncoder, CabacState, Contexts, ctx};
2626 use crate::intra::{self, Availability, Refs};
2727 use crate::residual::{self, encode_residual};
2828 use crate::transform::{
29- chroma_qp, dequantize, forward_transform, inverse_transform, quantize, uses_dst,
29+ chroma_qp, dequantize, forward_transform, inverse_transform, quantize, quantize_offset,
30+ uses_dst,
3031 };
3132 use std::sync::atomic::{AtomicU8, Ordering};
3233
34+/// The rounding the rate-distortion level search starts from, as a divisor of
35+/// the quantiser step: 2 is round-to-nearest, against the 3 the plain path
36+/// uses. A search that only takes levels down measures the rounding it was
37+/// handed, so it gets the wider one. Swept on 1080p film at the settled
38+/// lambda: 1/2 +0.360 dB BD-PSNR against x265, 1/3 +0.315, 1/4 +0.118.
39+const RDOQ_DEAD_ZONE: i64 = 2;
40+
41+/// The same rounding for the chroma path, swept on its own because the sparser
42+/// chroma of an intra picture answered differently in ec-h264.
43+///
44+/// Here it does not: coarser chroma rounding reads better and better on luma
45+/// BD-PSNR (1/2 +0.360, 1/6 +0.525, 1/12 +0.568, 1/24 +0.585 dB) while the
46+/// all-plane figure falls the whole way (+0.276, +0.231, +0.169, +0.128). That
47+/// arm is chroma being starved to buy luma bits, which only a luma-only metric
48+/// calls a gain, so chroma keeps luma's rounding.
49+const RDOQ_DEAD_ZONE_C: i64 = 2;
50+
3351 /// `log2` of the smallest coding block this encoder makes: 8x8.
3452 pub const MIN_CB_LOG2: u32 = 3;
3553
@@ -151,6 +169,10 @@ pub struct CtuEncoder<'a> {
151169 /// Whether an 8x8 coding unit may split into four 4x4 intra partitions.
152170 intra_nxn: bool,
153171 sign_hiding: bool,
172+ /// Whether the levels get a rate-distortion search after quantisation.
173+ rdoq: bool,
174+ /// The counting CABAC engine that search prices its trials with.
175+ rdoq_enc: CabacEncoder,
154176 /// `log2` of the smallest coding unit the search will produce.
155177 min_cb_log2: u32,
156178 /// Intra mode per 4x4 block of the band; 255 = not coded yet.
@@ -183,6 +205,7 @@ impl<'a> CtuEncoder<'a> {
183205 chroma_rd_weight: f64,
184206 intra_nxn: bool,
185207 sign_hiding: bool,
208+ rdoq: bool,
186209 min_cb_log2: u32,
187210 ) -> CtuEncoder<'a> {
188211 let band_rows = (height - band_y0).min(ctb_size);
@@ -204,6 +227,8 @@ impl<'a> CtuEncoder<'a> {
204227 chroma_rd_weight,
205228 intra_nxn,
206229 sign_hiding,
230+ rdoq,
231+ rdoq_enc: CabacEncoder::counter(Contexts::new(qp)),
207232 min_cb_log2: min_cb_log2.clamp(MIN_CB_LOG2, 5),
208233 modes: vec![255; (width / 4) * (ctb_size / 4)],
209234 depths: vec![0; (width / 4) * (ctb_size / 4)],
@@ -883,7 +908,30 @@ impl<'a> CtuEncoder<'a> {
883908 }
884909 let dst = uses_dst(n, true);
885910 forward_transform(&self.scratch.residual, &mut self.scratch.coeffs, n, dst);
886- let mut nonzero = quantize(&self.scratch.coeffs, &mut self.scratch.levels, n, self.qp);
911+ let mut nonzero = if self.rdoq {
912+ quantize_offset(
913+ &self.scratch.coeffs,
914+ &mut self.scratch.levels,
915+ n,
916+ self.qp,
917+ RDOQ_DEAD_ZONE,
918+ )
919+ } else {
920+ quantize(&self.scratch.coeffs, &mut self.scratch.levels, n, self.qp)
921+ };
922+ if self.rdoq && nonzero > 0 {
923+ nonzero = residual::rdoq(
924+ &self.scratch.coeffs,
925+ &mut self.scratch.levels,
926+ n,
927+ self.qp,
928+ 0,
929+ intra::scan_index(mode, n.trailing_zeros(), true),
930+ ctx::CBF_LUMA + 1,
931+ self.lambda,
932+ &mut self.rdoq_enc,
933+ );
934+ }
887935 if self.sign_hiding && nonzero > 0 {
888936 nonzero = residual::hide_signs(
889937 &self.scratch.coeffs,
@@ -942,12 +990,35 @@ impl<'a> CtuEncoder<'a> {
942990 }
943991 }
944992 forward_transform(&self.scratch.residual, &mut self.scratch.coeffs, cn, false);
945- let mut nonzero = quantize(
946- &self.scratch.coeffs,
947- &mut self.scratch.levels,
948- cn,
949- self.qp_c,
950- );
993+ let mut nonzero = if self.rdoq {
994+ quantize_offset(
995+ &self.scratch.coeffs,
996+ &mut self.scratch.levels,
997+ cn,
998+ self.qp_c,
999+ RDOQ_DEAD_ZONE_C,
1000+ )
1001+ } else {
1002+ quantize(
1003+ &self.scratch.coeffs,
1004+ &mut self.scratch.levels,
1005+ cn,
1006+ self.qp_c,
1007+ )
1008+ };
1009+ if self.rdoq && nonzero > 0 {
1010+ nonzero = residual::rdoq(
1011+ &self.scratch.coeffs,
1012+ &mut self.scratch.levels,
1013+ cn,
1014+ self.qp_c,
1015+ plane,
1016+ intra::scan_index(pred_mode, cn.trailing_zeros(), false),
1017+ ctx::CBF_CHROMA,
1018+ self.lambda,
1019+ &mut self.rdoq_enc,
1020+ );
1021+ }
9511022 if self.sign_hiding && nonzero > 0 {
9521023 nonzero = residual::hide_signs(
9531024 &self.scratch.coeffs,
crates/ec-h265/src/encoder.rsmodified+13 -0
@@ -144,6 +144,17 @@ pub struct EncoderConfig {
144144 /// cost more than the signs save. Worth re-measuring once RDOQ lands: that
145145 /// is where the gain in other encoders comes from.
146146 pub sign_hiding: bool,
147+
148+ /// Whether quantised levels get a rate-distortion search (RDOQ) that
149+ /// offers each small level the magnitudes below it and takes one when the
150+ /// squared error it gives up costs less than the bits it saves.
151+ ///
152+ /// On: worth +0.122 dB BD-PSNR on a 2560x1440 screen capture (-0.479 ->
153+ /// -0.357 against x265) and +0.114 dB on 1080p film (+0.246 -> +0.360),
154+ /// with the all-plane figures moving the same way. The rate is the CABAC
155+ /// coder's own price for the whole block, so dropping a level is priced
156+ /// with the significance map and last position that follow from it.
157+ pub rdoq: bool,
147158 /// What the samples mean, written into the VUI.
148159 pub video_signal_type: Option<VideoSignalType>,
149160 /// Sample aspect ratio.
@@ -174,6 +185,7 @@ impl EncoderConfig {
174185 min_cu_size: 8,
175186 intra_nxn: true,
176187 sign_hiding: false,
188+ rdoq: true,
177189 video_signal_type: None,
178190 sample_aspect_ratio: None,
179191 timing: None,
@@ -551,6 +563,7 @@ impl Encoder {
551563 self.cfg.chroma_rd_weight,
552564 self.cfg.intra_nxn,
553565 self.cfg.sign_hiding,
566+ self.cfg.rdoq,
554567 self.cfg.min_cu_size.max(8).trailing_zeros(),
555568 );
556569 for col in 0..cols {
crates/ec-h265/src/residual.rsmodified+135 -2
@@ -1,7 +1,7 @@
11 //! `residual_coding()` (7.3.8.11) and the scan orders it walks (6.5.3 - 6.5.5).
22
3-use crate::cabac::{CabacEncoder, ctx};
4-use crate::transform::ideal_level;
3+use crate::cabac::{CabacEncoder, CabacState, ctx};
4+use crate::transform::{coeff_ssd_scale, dequant_level, ideal_level};
55 use std::sync::LazyLock;
66
77 /// Scan orders: `SCANS[log2BlockSize][scanIdx][pos] = (x, y)`.
@@ -195,6 +195,139 @@ pub fn hide_signs(coeffs: &[i32], levels: &mut [i32], n: usize, qp: i32, scan_id
195195 levels[..n * n].iter().filter(|&&l| l != 0).count()
196196 }
197197
198+/// The largest level the rate-distortion search offers a smaller magnitude to.
199+///
200+/// A big level carries real signal and never wins by shrinking, so bounding
201+/// the search is what keeps it affordable: every trial re-codes the whole
202+/// block. Swept on 1080p film, BD-PSNR-YUV against x265: 1 gives +0.244, the 2
203+/// kept here +0.276, and 3 +0.277 for strictly more trials.
204+const RDOQ_MAX_LEVEL: i32 = 2;
205+
206+/// How much of the mode-decision lambda the level search uses. The bits are
207+/// the coder's own count, not an estimate, so the scale starts at 1.
208+///
209+/// The two clips disagree above it and the disagreement is small: on
210+/// BD-PSNR-YUV against x265, 1080p film reads +0.276 at 1.0, +0.294 at 1.25
211+/// and +0.293 at 1.5, while a 2560x1440 screen capture reads -0.392, -0.408
212+/// and -0.441. The crossing sits just above 1.0, and the screen capture is the
213+/// content still behind x265, so it takes the tie.
214+const RDOQ_LAMBDA: f64 = 1.0;
215+
216+/// What one candidate set of levels costs in bits, priced by the CABAC coder
217+/// itself against `base`'s context state.
218+#[allow(clippy::too_many_arguments)]
219+fn levels_bits(
220+ enc: &mut CabacEncoder,
221+ base: &CabacState,
222+ levels: &[i32],
223+ log2_size: u32,
224+ c_idx: usize,
225+ scan_idx: usize,
226+ cbf_ctx: usize,
227+ coded: bool,
228+) -> u64 {
229+ enc.restore(base);
230+ let before = enc.bit_count();
231+ enc.encode_bin(cbf_ctx, u32::from(coded));
232+ if coded {
233+ encode_residual(enc, levels, log2_size, c_idx, scan_idx, false);
234+ }
235+ enc.bit_count() - before
236+}
237+
238+/// Rate-distortion quantisation of one transform block: each small level is
239+/// offered the magnitudes below it, and takes one when the squared error it
240+/// gives up costs less than the bits it saves.
241+///
242+/// The rate is the CABAC coder's own price for the whole block — `enc` is a
243+/// counting engine, and every trial is priced from the same context state — so
244+/// dropping a level is priced together with the significance map and the last
245+/// position that follow from it, which is where most of the saving is. The
246+/// distortion is the transform-domain error scaled back to samples by
247+/// [`coeff_ssd_scale`], so `lambda` is the caller's sample-domain lambda.
248+///
249+/// Returns the number of non-zero levels left.
250+#[allow(clippy::too_many_arguments)]
251+pub fn rdoq(
252+ coeffs: &[i32],
253+ levels: &mut [i32],
254+ n: usize,
255+ qp: i32,
256+ c_idx: usize,
257+ scan_idx: usize,
258+ cbf_ctx: usize,
259+ lambda: f64,
260+ enc: &mut CabacEncoder,
261+) -> usize {
262+ let log2_size = n.trailing_zeros();
263+ let scale = coeff_ssd_scale(n);
264+ let lambda = RDOQ_LAMBDA * lambda;
265+ let base = enc.snapshot();
266+ let err = |level: i32, coeff: i32| {
267+ let d = f64::from(dequant_level(level, n, qp) - coeff);
268+ d * d
269+ };
270+
271+ let mut dist: f64 = (0..n * n).map(|i| err(levels[i], coeffs[i])).sum();
272+ let bits = levels_bits(
273+ enc, &base, levels, log2_size, c_idx, scan_idx, cbf_ctx, true,
274+ );
275+ let mut cost = scale * dist + lambda * bits as f64;
276+
277+ // Highest scanning position first: dropping the last significant level is
278+ // what shortens the significance map and moves the coded last position, so
279+ // it is tried while the levels above it are already gone.
280+ let sub_scan = scan(log2_size - 2, scan_idx);
281+ let pos_scan = scan(2, scan_idx);
282+ let order: Vec<usize> = sub_scan
283+ .iter()
284+ .flat_map(|&(xs, ys)| {
285+ pos_scan.iter().map(move |&(xp, yp)| {
286+ (ys as usize * 4 + yp as usize) * n + xs as usize * 4 + xp as usize
287+ })
288+ })
289+ .collect();
290+ for &i in order.iter().rev() {
291+ let level = levels[i];
292+ if level == 0 || level.abs() > RDOQ_MAX_LEVEL {
293+ continue;
294+ }
295+ let mut tried = level.abs();
296+ for candidate in [level.abs() - 1, 0] {
297+ if candidate == tried {
298+ continue;
299+ }
300+ tried = candidate;
301+ let keep = levels[i];
302+ levels[i] = candidate * level.signum();
303+ let trial_dist = dist - err(keep, coeffs[i]) + err(levels[i], coeffs[i]);
304+ let any = levels[..n * n].iter().any(|&l| l != 0);
305+ let trial_bits =
306+ levels_bits(enc, &base, levels, log2_size, c_idx, scan_idx, cbf_ctx, any);
307+ let trial = scale * trial_dist + lambda * trial_bits as f64;
308+ if trial < cost {
309+ cost = trial;
310+ dist = trial_dist;
311+ } else {
312+ levels[i] = keep;
313+ }
314+ }
315+ }
316+ // And the block as a whole: zeroing it drops the coded-block flag as well
317+ // as every level, which no single-coefficient step can see.
318+ let zero_dist: f64 = (0..n * n).map(|i| err(0, coeffs[i])).sum();
319+ let zero_bits = levels_bits(
320+ enc, &base, levels, log2_size, c_idx, scan_idx, cbf_ctx, false,
321+ );
322+ if scale * zero_dist + lambda * zero_bits as f64 <= cost {
323+ levels[..n * n].fill(0);
324+ enc.restore(&base);
325+ return 0;
326+ }
327+ enc.restore(&base);
328+ levels[..n * n].iter().filter(|&&l| l != 0).count()
329+}
330+
198331 /// Encode one transform block's levels.
199332 ///
200333 /// `levels` is row-major `n x n` with `levels[y * n + x]`, `c_idx` is 0 for luma
crates/ec-h265/src/transform.rsmodified+42 -5
@@ -277,10 +277,27 @@ pub fn inverse_transform(scaled: &[i32], residual: &mut [i32], n: usize, dst_typ
277277 /// encoder in this class uses: it costs a little distortion at the rounding
278278 /// boundary and buys back more in rate.
279279 pub fn quantize(coeffs: &[i32], levels: &mut [i32], n: usize, qp: i32) -> usize {
280+ quantize_offset(coeffs, levels, n, qp, 3)
281+}
282+
283+/// [`quantize`] with the rounding written out: `dead_zone` is the divisor of
284+/// the quantiser step the rounding offset is, so 3 is the intra default and 2
285+/// is round-to-nearest.
286+///
287+/// A rate-distortion search over the levels wants the wider rounding: a search
288+/// that only ever takes levels down measures the rounding it started from, not
289+/// its own decisions.
290+pub fn quantize_offset(
291+ coeffs: &[i32],
292+ levels: &mut [i32],
293+ n: usize,
294+ qp: i32,
295+ dead_zone: i64,
296+) -> usize {
280297 let log2n = n.trailing_zeros() as i32;
281298 let qbits = 21 + qp / 6 - log2n;
282299 let scale = QUANT_SCALE[(qp % 6) as usize] as i64;
283- let offset = (1i64 << qbits) / 3;
300+ let offset = (1i64 << qbits) / dead_zone;
284301 let mut nonzero = 0;
285302 for (i, &c) in coeffs[..n * n].iter().enumerate() {
286303 let magnitude = ((c.unsigned_abs() as i64 * scale + offset) >> qbits) as i32;
@@ -305,15 +322,35 @@ pub fn ideal_level(coeff: i32, n: usize, qp: i32) -> f64 {
305322
306323 /// Scale levels back into coefficients, exactly as clause 8.6.3 specifies.
307324 pub fn dequantize(levels: &[i32], scaled: &mut [i32], n: usize, qp: i32) {
325+ for (i, &level) in levels[..n * n].iter().enumerate() {
326+ scaled[i] = dequant_level(level, n, qp);
327+ }
328+}
329+
330+/// One level scaled back to a coefficient, the per-coefficient half of
331+/// [`dequantize`]. A rate-distortion search over the levels prices one
332+/// coefficient at a time and has no use for the whole block.
333+pub fn dequant_level(level: i32, n: usize, qp: i32) -> i32 {
308334 let log2n = n.trailing_zeros() as i32;
309335 let bd_shift = log2n + 3; // bitDepth + Log2(nTbS) + 10 - 15, 8-bit
310336 let round = 1i64 << (bd_shift - 1);
311337 let scale = (16 * LEVEL_SCALE[(qp % 6) as usize]) as i64;
312338 let shift = qp / 6;
313- for (i, &level) in levels[..n * n].iter().enumerate() {
314- let value = (((level as i64 * scale) << shift) + round) >> bd_shift;
315- scaled[i] = value.clamp(COEFF_MIN as i64, COEFF_MAX as i64) as i32;
316- }
339+ let value = (((level as i64 * scale) << shift) + round) >> bd_shift;
340+ value.clamp(COEFF_MIN as i64, COEFF_MAX as i64) as i32
341+}
342+
343+/// What a squared error in the transform domain is worth as a squared error in
344+/// the sample domain.
345+///
346+/// The forward transform's shifts leave the DC at 128 times the mean residual
347+/// whatever the block size, where an orthonormal transform would leave it at
348+/// `n` times; the transform is otherwise orthogonal, so coefficient error
349+/// energy is `(128 / n)^2` times sample error energy and this undoes it. A
350+/// rate-distortion search over the levels needs it to weigh transform-domain
351+/// error against a lambda calibrated on samples.
352+pub fn coeff_ssd_scale(n: usize) -> f64 {
353+ (n * n) as f64 / (128.0 * 128.0)
317354 }
318355
319356 /// The chroma QP a luma QP maps to for 4:2:0 (Table 8-10), before any offset.
crates/ec-h265/tests/conformance.rsmodified+45 -0
@@ -491,3 +491,48 @@ fn the_batch_helper_codes_every_picture_as_its_own_access_unit() {
491491 // Different pictures, different bitstreams.
492492 assert_ne!(coded[0].au, coded[1].au);
493493 }
494+
495+/// Rate-distortion quantisation changes which levels are coded, so the streams
496+/// it produces are a different set of bins from the plain quantiser's; ffmpeg
497+/// has to read them back to the same samples the encoder reconstructed.
498+#[test]
499+fn rdoq_decodes_bit_exactly() {
500+ if !have_ffmpeg() {
501+ eprintln!("skipping: ffmpeg not installed");
502+ return;
503+ }
504+ for &(w, h) in &[(64u32, 64u32), (130, 66), (352, 288)] {
505+ let (source, coded) = encode_rdoq(w, h, 27, true);
506+ let (_, plain) = encode_rdoq(w, h, 27, false);
507+ let name = format!("rdoq-{w}x{h}");
508+ assert_ne!(
509+ coded.au, plain.au,
510+ "{name}: the level search changed no byte, so it is not running"
511+ );
512+ let path = write_au(&name, &coded);
513+ let decoded = match ffmpeg_decode(&path) {
514+ Ok(bytes) => bytes,
515+ Err(e) => panic!("{name}: ffmpeg failed: {e}"),
516+ };
517+ let recon = planes_of(coded.recon.as_ref().expect("recon kept"));
518+ assert_eq!(decoded.len(), recon.len(), "{name}: size mismatch");
519+ let mismatches = decoded.iter().zip(&recon).filter(|(a, b)| a != b).count();
520+ assert_eq!(mismatches, 0, "{name}: {mismatches} samples differ");
521+ let quality = psnr(&planes_of(&source), &recon);
522+ assert!(quality > 28.0, "{name}: PSNR {quality:.2} dB at QP 27");
523+ }
524+}
525+
526+/// The natural frame coded with the level search on or off, everything else
527+/// left at its default.
528+fn encode_rdoq(width: u32, height: u32, qp: i32, rdoq: bool) -> (VideoFrame, EncodedPicture) {
529+ let mut cfg = EncoderConfig::new(width, height);
530+ cfg.rdoq = rdoq;
531+ cfg.rate_control = RateControl::ConstantQp(qp);
532+ cfg.keep_recon = true;
533+ cfg.picture_hash = true;
534+ let encoder = Encoder::new(cfg).expect("encoder");
535+ let frame = natural_frame(width, height, 0);
536+ let coded = encoder.encode_idr(&frame).expect("encode");
537+ (frame, coded)
538+}
crates/ec-h265/tests/encode.rsmodified+38 -11
@@ -438,6 +438,9 @@ fn bd_psnr_vs_x265() {
438438 if let Ok(v) = std::env::var("EC_H265_SDH") {
439439 cfg.sign_hiding = v != "0";
440440 }
441+ if let Ok(v) = std::env::var("EC_H265_RDOQ") {
442+ cfg.rdoq = v != "0";
443+ }
441444 if let Ok(v) = std::env::var("EC_H265_NXN") {
442445 cfg.intra_nxn = v != "0";
443446 }
@@ -542,7 +545,9 @@ fn bd_psnr_vs_x265() {
542545 // per factor of 2 in bits), and our four QPs run at 22/26/30/34 plus that
543546 // shift. If the extrapolation share still exceeds 20% after measuring, the
544547 // shift is re-estimated from the geometric-mean bit ratio of the two full
545- // curves and the ladder is rebuilt — at most 2 extra alignment rounds
548+ // curves and the ladder is rebuilt; once the rates match and the curves
549+ // still do not meet, our ladder is drawn in towards its own centre until
550+ // its bitrate range fits inside the anchor's — at most 8 alignment rounds
546551 // before the existing panic fires.
547552 const EXTRAP_LIMIT: f64 = 0.20;
548553 let x265_qps = [22, 26, 30, 34];
@@ -589,9 +594,17 @@ fn bd_psnr_vs_x265() {
589594 ) = (0.0_f64, 0.0, 0.0, 0.0, 0.0, 0.0);
590595 let mut mine: Vec<(f64, f64, f64)>;
591596 let mut our_qps: [i32; 4];
597+ // How wide our QP ladder is against the anchor's, as a fraction of its
598+ // spacing: one encoder can answer a QP step with far more bitrate than the
599+ // other, and a BD number needs both curves over the same range.
600+ let mut spread = 1.0_f64;
592601
593- for round in 0..=2u32 {
594- our_qps = x265_qps.map(|q| (q + shift).clamp(1, 45));
602+ for round in 0..=8u32 {
603+ our_qps = x265_qps.map(|q| {
604+ let centre = f64::from(probe_qp + shift);
605+ let offset = f64::from(q - probe_qp) * spread;
606+ ((centre + offset).round() as i32).clamp(1, 45)
607+ });
595608 mine = our_qps
596609 .iter()
597610 .map(|&q| if q == probe_qp { probe_ours } else { ours(q) })
@@ -621,19 +634,33 @@ fn bd_psnr_vs_x265() {
621634 && anc_extrap <= EXTRAP_LIMIT
622635 && cand_extrap_yuv <= EXTRAP_LIMIT
623636 && anc_extrap_yuv <= EXTRAP_LIMIT;
624- if aligned || round == 2 {
637+ if aligned || round == 8 {
625638 break;
626639 }
627640 // Re-estimate the shift from the geometric-mean bit ratio of the two
628- // full curves, then rebuild the ladder.
641+ // full curves, then rebuild the ladder. A single-QP correction is
642+ // ignored: it is within the rounding of the estimate and only makes the
643+ // ladder oscillate between two neighbouring shifts.
629644 let delta = (6.0 * (gm(&mine) / gm(&theirs)).log2()).round() as i32;
630- shift += delta;
645+ if delta.abs() > 1 {
646+ shift += delta;
647+ eprintln!(
648+ "alignment round {}: shift {delta:+} -> {shift:+} \
649+ (gm ours {:.1} Mbit vs x265 {:.1} Mbit)",
650+ round + 1,
651+ gm(&mine) / 1e6,
652+ gm(&theirs) / 1e6,
653+ );
654+ continue;
655+ }
656+ // The rates match and the curves still do not overlap, so our ladder
657+ // spans a much wider bitrate range than the anchor's: their union is
658+ // then mostly outside what x265 measured and the cubic through its four
659+ // points extrapolates over most of it. Draw our ladder in.
660+ spread *= 0.5;
631661 eprintln!(
632- "alignment round {}: shift {delta:+} -> {shift:+} \
633- (gm ours {:.1} Mbit vs x265 {:.1} Mbit)",
634- round + 1,
635- gm(&mine) / 1e6,
636- gm(&theirs) / 1e6,
662+ "alignment round {}: ladder spread -> {spread:.2} of the anchor's",
663+ round + 1
637664 );
638665 }
639666