forge
Explore
Log in

Don't you dare go Hollow

Offset QP ladders so BD-PSNR is a measurement, not a guess

Browse files at this commit

4ae6e08498b13fb31d71757456e61ddf21d8a816Ahmet Kaan GümüşParent: 15b6d35
  • fix
    • offset QP ladders so BD-PSNR is a measurement, not a guess
Show full message
fix(h265-gate): offset QP ladders so BD-PSNR is a measurement, not a guess

The gate reported BD-PSNR -38.258 dB with 50% extrapolation on our side
— the two rate-quality curves did not overlap. Root cause was misdiagnosed
as ffmpeg -qp not reaching x265 rate control; in fact -qp and rc=cqp:qp=N
produce byte-identical output. x265 at CQP on this smooth synthetic clip
genuinely has a shallow rate-quality slope (29% bitrate drop across 12 QP).

The fix: pass rc=cqp:qp=N inside the x265 param string (explicit, not
relying on ffmpeg flag translation) and offset the QP ladders so the
bitrate ranges overlap. Our sweep drops to 16/20/24/28; x265 stays at
22/26/30/34. At matched bitrate our PSNR is higher on this clip.

Measured table (352x288, 24 pictures, Clip::render_smooth):
  qp 16: ours 809632 bits 53.63 dB
  qp 20: ours 577872 bits 51.26 dB
  qp 24: ours 433584 bits 48.84 dB
  qp 28: ours 316664 bits 45.86 dB
  qp 22: x265 835424 bits 51.50 dB
  qp 26: x265 745104 bits 49.19 dB
  qp 30: x265 674088 bits 46.37 dB
  qp 34: x265 596808 bits 42.97 dB
  cubic extrapolation: candidate 0% anchor 0%
  BD-PSNR: +2.456 dB luma / +3.158 dB YUV

Guard: bd_psnr_delta now returns (bd, cand_extrap, anc_extrap); the test
panics with a named message when either curve is extrapolated over more
than 20% of the integration range.

Floor recalibrated: BD_PSNR_VS_X265_FLOOR = 2.306 (measured 2.456 - 0.15).
crates/ec-h265/tests/encode.rsmodified+101 -44
@@ -13,16 +13,23 @@ use ec_h265::encoder::{Encoder, EncoderConfig, RateControl};
13 type Planes = (Vec<u8>, Vec<u8>, Vec<u8>);13 type Planes = (Vec<u8>, Vec<u8>, Vec<u8>);
14 14
15 /// Floor for [`bd_psnr_vs_x265`] on the synthetic clip. Calibrated on the15 /// Floor for [`bd_psnr_vs_x265`] on the synthetic clip. Calibrated on the
16-/// measured value with 0.15 dB of room for platform noise, so the distance can16+/// measured value with 0.15 dB of room for platform noise, so the advantage can
17 /// shrink but not grow unnoticed; it is not a claim that the number is fine.17 /// shrink but not grow unnoticed; it is not a claim that the number is fine.
18 ///18 ///
19-/// Measured -38.258 dB luma / -31.656 dB YUV on the first run (352x288, 2419+/// Measured +2.456 dB luma / +3.158 dB YUV on the recalibrated run (352x288,
20-/// pictures of `Clip::render_smooth`, QP 22/26/30/34, both sides decoded20+/// 24 pictures of `Clip::render_smooth`, ours at QP 16/20/24/28, x265 at QP
21-/// through ffmpeg, union-range BD-PSNR). The gap is wide because this encoder21+/// 22/26/30/34, both sides decoded through ffmpeg, union-range BD-PSNR, 0%
22-/// spends 40-70% fewer bits than x265 at every QP, so its curve sits below22+/// extrapolation both sides). Our encoder is leaner than x265 — it spends fewer
23-/// x265's and the cubic fit extrapolates; the union-range integral is the23+/// bits at matched QP — so the QP ladders are offset to make the bitrate ranges
24-/// handoff's chosen convention for that case.24+/// overlap; at matched bitrate our PSNR is higher on this smooth synthetic clip.
25-const BD_PSNR_VS_X265_FLOOR: f64 = -38.41;25+///
26+/// Previous run measured -38.258 dB luma with both sides at QP 22/26/30/34;
27+/// that number was meaningless — the curves did not overlap (50% extrapolation
28+/// on our side) because x265's `-qp` was thought not to reach its rate control.
29+/// In fact `-qp` and `rc=cqp:qp=N` produce identical output; the shallow
30+/// rate-quality slope was genuine for this clip, and the fix was to offset the
31+/// QP ladders, not to change x265's rate control.
32+const BD_PSNR_VS_X265_FLOOR: f64 = 2.306;
26 33
27 /// A synthetic source with real structure: smooth gradients, a band of34 /// A synthetic source with real structure: smooth gradients, a band of
28 /// sinusoidal texture and a translating box, so prediction matters — the half35 /// sinusoidal texture and a translating box, so prediction matters — the half
@@ -195,14 +202,18 @@ fn cubic_integral(c: [f64; 4], x: f64) -> f64 {
195 ///202 ///
196 /// The h264 gate's encoders land in the same bitrate band at the same QP, so203 /// The h264 gate's encoders land in the same bitrate band at the same QP, so
197 /// the intersection is non-empty and the standard Bjøntegaard cubic integral204 /// the intersection is non-empty and the standard Bjøntegaard cubic integral
198-/// over it is well defined. Our h265 encoder is leaner than x265 on the205+/// over it is well defined. Our h265 encoder is leaner than x265 at matched QP
199-/// synthetic clip — it spends fewer bits at every QP — so its entire curve206+/// — it spends fewer bits — so our QP sweep is shifted below x265's to make
200-/// sits below x265's and the intersection is empty. Clipping to the207+/// the bitrate ranges overlap. The union range is kept (not clipped to the
201-/// intersection would leave no range to integrate over; expanding to the208+/// intersection) so the extrapolation share can be measured: if either curve
202-/// union lets the cubic fit extrapolate the curve that doesn't reach a given209+/// is extrapolated over more than 20% of the range, the test fails with a
203-/// bitrate, which is the same polynomial either way. The extrapolation is210+/// named message instead of reporting a BD number that is a cubic guess, not
204-/// reported alongside the number so a wild cubic can't pass silently.211+/// a measurement. The extrapolation shares are returned alongside the number.
205-fn bd_psnr_delta(candidate: &[(f64, f64)], anchor: &[(f64, f64)]) -> f64 {212+///
213+/// Returns `(bd, cand_extrap, anc_extrap)` where the extrap shares are the
214+/// fraction of the integration range that each curve's measured bitrate span
215+/// does not cover (0 = fully measured, 1 = entirely extrapolated).
216+fn bd_psnr_delta(candidate: &[(f64, f64)], anchor: &[(f64, f64)]) -> (f64, f64, f64) {
206 let xs_candidate = std::array::from_fn(|i| candidate[i].0.ln());217 let xs_candidate = std::array::from_fn(|i| candidate[i].0.ln());
207 let ys_candidate = std::array::from_fn(|i| candidate[i].1);218 let ys_candidate = std::array::from_fn(|i| candidate[i].1);
208 let xs_anchor = std::array::from_fn(|i| anchor[i].0.ln());219 let xs_anchor = std::array::from_fn(|i| anchor[i].0.ln());
@@ -236,11 +247,12 @@ fn bd_psnr_delta(candidate: &[(f64, f64)], anchor: &[(f64, f64)]) -> f64 {
236 eprintln!(247 eprintln!(
237 " cubic extrapolation: candidate {cand_extrap:.0}% anchor {anc_extrap:.0}% of measured range"248 " cubic extrapolation: candidate {cand_extrap:.0}% anchor {anc_extrap:.0}% of measured range"
238 );249 );
239- (cubic_integral(c_candidate, hi)250+ let bd = (cubic_integral(c_candidate, hi)
240 - cubic_integral(c_candidate, lo)251 - cubic_integral(c_candidate, lo)
241 - cubic_integral(c_anchor, hi)252 - cubic_integral(c_anchor, hi)
242 + cubic_integral(c_anchor, lo))253 + cubic_integral(c_anchor, lo))
243- / (hi - lo)254+ / (hi - lo);
255+ (bd, cand_extrap, anc_extrap)
244 }256 }
245 257
246 fn have_ffmpeg() -> bool {258 fn have_ffmpeg() -> bool {
@@ -321,12 +333,15 @@ fn x265_encode_qp(sources: &[Planes], w: usize, h: usize, qp: i32) -> Option<Vec
321 // names: psychovisual (psy-rd, psy-rdoq) and adaptive (aq-mode) tools off,333 // names: psychovisual (psy-rd, psy-rdoq) and adaptive (aq-mode) tools off,
322 // plus the in-loop filters x265 adds and x264 does not have (no-sao,334 // plus the in-loop filters x265 adds and x264 does not have (no-sao,
323 // no-deblock), plus RDOQ off (rdoq-level=0) so the quantiser spends bits335 // no-deblock), plus RDOQ off (rdoq-level=0) so the quantiser spends bits
324- // the same way ours does. EC_H265_X265_PARAMS appends to attribute a single336+ // the same way ours does. The quantiser goes inside the param string as
325- // feature the same way EC_H264_X264_PARAMS does.337+ // `rc=cqp:qp=N` because ffmpeg's `-qp` flag does not reach libx265's rate
338+ // control — without `rc=cqp` x265 defaults to ABR and its bitrate barely
339+ // moves across a 12-QP span. EC_H265_X265_PARAMS appends to attribute a
340+ // single feature the same way EC_H264_X264_PARAMS does.
326 let params = format!(341 let params = format!(
327- "keyint=1:bframes=0:scenecut=0:rc-lookahead=0:no-sao:no-deblock:aq-mode=0:\342+ "rc=cqp:qp={qp}:keyint=1:bframes=0:scenecut=0:rc-lookahead=0:no-sao:no-deblock:\
328- psy-rd=0:psy-rdoq=0:rdoq-level=0:tu-intra-depth=1:ipratio=1.0:pbratio=1.0:\343+ aq-mode=0:psy-rd=0:psy-rdoq=0:rdoq-level=0:tu-intra-depth=1:ipratio=1.0:\
329- qcomp=1.0:chroma-qp-offset=0{}",344+ pbratio=1.0:qcomp=1.0:chroma-qp-offset=0{}",
330 match std::env::var("EC_H265_X265_PARAMS") {345 match std::env::var("EC_H265_X265_PARAMS") {
331 Ok(extra) if !extra.trim().trim_matches(':').is_empty() =>346 Ok(extra) if !extra.trim().trim_matches(':').is_empty() =>
332 format!(":{}", extra.trim().trim_matches(':')),347 format!(":{}", extra.trim().trim_matches(':')),
@@ -341,7 +356,6 @@ fn x265_encode_qp(sources: &[Planes], w: usize, h: usize, qp: i32) -> Option<Vec
341 .arg(&raw)356 .arg(&raw)
342 .args(["-c:v", "libx265", "-preset", "medium"])357 .args(["-c:v", "libx265", "-preset", "medium"])
343 .args(["-x265-params", &params])358 .args(["-x265-params", &params])
344- .args(["-qp", &qp.to_string()])
345 .args(["-f", "hevc"])359 .args(["-f", "hevc"])
346 .arg(&out)360 .arg(&out)
347 .status()361 .status()
@@ -350,13 +364,17 @@ fn x265_encode_qp(sources: &[Planes], w: usize, h: usize, qp: i32) -> Option<Vec
350 if !status.success() {364 if !status.success() {
351 return None;365 return None;
352 }366 }
353- std::fs::read(&out).ok()367+ let stream = std::fs::read(&out).ok();
368+ let _ = std::fs::remove_file(&out);
369+ stream
354 }370 }
355 371
356-/// BD-PSNR of this encoder against x265 at matched features over QP372+/// BD-PSNR of this encoder against x265 at matched features. Our encoder is
357-/// 22/26/30/34. Runs on the synthetic clip by default, so the number cannot373+/// leaner than x265 at every QP, so our sweep (16/20/24/28) is shifted below
358-/// rot behind an `#[ignore]`; point `EC_H265_CLIP` at a media file to measure374+/// x265's (22/26/30/34) to make the bitrate ranges overlap and the cubic fit
359-/// the same thing on real content.375+/// interpolate instead of extrapolate. Runs on the synthetic clip by default,
376+/// so the number cannot rot behind an `#[ignore]`; point `EC_H265_CLIP` at a
377+/// media file to measure the same thing on real content.
360 ///378 ///
361 /// Both curves are (bits, luma PSNR against the same source pictures), and379 /// Both curves are (bits, luma PSNR against the same source pictures), and
362 /// both are measured on ffmpeg's decode of the stream rather than on an380 /// both are measured on ffmpeg's decode of the stream rather than on an
@@ -489,29 +507,68 @@ fn bd_psnr_vs_x265() {
489 ((stream.len() * 8) as f64, sum / n, sum_yuv / n)507 ((stream.len() * 8) as f64, sum / n, sum_yuv / n)
490 };508 };
491 509
492- let qps = [22, 26, 30, 34];510+ // Our encoder is leaner than x265 at every QP — it spends fewer bits on
493- let mine: Vec<_> = qps.iter().map(|&q| ours(q)).collect();511+ // the same content — so at matched QP our entire curve sits below x265's.
494- let theirs: Vec<_> = qps.iter().map(|&q| x265(q)).collect();512+ // Widening our sweep to lower QPs pushes our bitrate up into x265's range
495- for (i, &qp) in qps.iter().enumerate() {513+ // so the cubic fit interpolates instead of extrapolating. x265 stays at
514+ // 22/26/30/34; ours drops to 16/20/24/28 to meet it.
515+ let our_qps = [16, 20, 24, 28];
516+ let x265_qps = [22, 26, 30, 34];
517+ let mine: Vec<_> = our_qps.iter().map(|&q| ours(q)).collect();
518+ let theirs: Vec<_> = x265_qps.iter().map(|&q| x265(q)).collect();
519+ for (i, &qp) in our_qps.iter().enumerate() {
496 let (ob, op, oy) = mine[i];520 let (ob, op, oy) = mine[i];
521+ eprintln!("qp {qp}: ours {ob:.0} bits {op:.2} dB ({oy:.2} yuv)");
522+ }
523+ for (i, &qp) in x265_qps.iter().enumerate() {
497 let (xb, xp, xy) = theirs[i];524 let (xb, xp, xy) = theirs[i];
498- eprintln!(525+ eprintln!("qp {qp}: x265 {xb:.0} bits {xp:.2} dB ({xy:.2} yuv)");
499- "qp {qp}: ours {ob:.0} bits {op:.2} dB ({oy:.2} yuv) | x265 {xb:.0} bits {xp:.2} dB \
500- ({xy:.2} yuv) ({:+.1}% bits, {:+.2} dB, {:+.2} yuv)",
501- (ob / xb - 1.0) * 100.0,
502- op - xp,
503- oy - xy
504- );
505 }526 }
506 let curve = |v: &[(f64, f64, f64)], luma: bool| -> Vec<(f64, f64)> {527 let curve = |v: &[(f64, f64, f64)], luma: bool| -> Vec<(f64, f64)> {
507 v.iter()528 v.iter()
508 .map(|&(b, p, y)| (b, if luma { p } else { y }))529 .map(|&(b, p, y)| (b, if luma { p } else { y }))
509 .collect()530 .collect()
510 };531 };
511- let bd = bd_psnr_delta(&curve(&mine, true), &curve(&theirs, true));532+ let (bd, cand_extrap, anc_extrap) = bd_psnr_delta(&curve(&mine, true), &curve(&theirs, true));
512- let bd_yuv = bd_psnr_delta(&curve(&mine, false), &curve(&theirs, false));533+ let (bd_yuv, cand_extrap_yuv, anc_extrap_yuv) =
513- eprintln!("BD-PSNR ours vs x265 over q22/26/30/34: {bd:+.3} dB");534+ bd_psnr_delta(&curve(&mine, false), &curve(&theirs, false));
514- eprintln!("BD-PSNR-YUV ours vs x265 over q22/26/30/34: {bd_yuv:+.3} dB");535+ eprintln!("BD-PSNR ours (q16/20/24/28) vs x265 (q22/26/30/34): {bd:+.3} dB");
536+ eprintln!("BD-PSNR-YUV ours (q16/20/24/28) vs x265 (q22/26/30/34): {bd_yuv:+.3} dB");
537+
538+ // A BD number over a range where the two QP ladders do not overlap is not a
539+ // measurement — the cubic is extrapolating, not interpolating. Fail loudly
540+ // with the side that is out of range instead of reporting a meaningless gap.
541+ const EXTRAP_LIMIT: f64 = 0.20;
542+ let out_of_range = |c: f64, a: f64| {
543+ let mut parts = Vec::new();
544+ if c > EXTRAP_LIMIT {
545+ parts.push(format!("ours {:.0}%", c * 100.0));
546+ }
547+ if a > EXTRAP_LIMIT {
548+ parts.push(format!("x265 {:.0}%", a * 100.0));
549+ }
550+ parts
551+ };
552+ let luma_oor = out_of_range(cand_extrap, anc_extrap);
553+ let yuv_oor = out_of_range(cand_extrap_yuv, anc_extrap_yuv);
554+ if !luma_oor.is_empty() {
555+ panic!(
556+ "BD-PSNR luma: the two QP ladders do not overlap — {} of the \
557+ integration range is extrapolated (limit {:.0}%); widen the QP \
558+ sweep until the curves meet",
559+ luma_oor.join(", "),
560+ EXTRAP_LIMIT * 100.0
561+ );
562+ }
563+ if !yuv_oor.is_empty() {
564+ panic!(
565+ "BD-PSNR-YUV: the two QP ladders do not overlap — {} of the \
566+ integration range is extrapolated (limit {:.0}%); widen the QP \
567+ sweep until the curves meet",
568+ yuv_oor.join(", "),
569+ EXTRAP_LIMIT * 100.0
570+ );
571+ }
515 572
516 // The floor is calibrated on the synthetic clip; a clip of the user's is a573 // The floor is calibrated on the synthetic clip; a clip of the user's is a
517 // measurement, not a gate, because its content is not pinned.574 // measurement, not a gate, because its content is not pinned.