forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'lane-h265-gate': BD-PSNR against x265 with self-aligning ladders

Browse files at this commit

addbfd0e0e7c89134f6b0ec4cdc26caf3b75e8baAhmet Kaan GümüşParent: 495e4508b6026d
Adds the ec-h265 gate: BD-PSNR and BD-PSNR-YUV against x265 at matched
features, both sides decoded through ffmpeg, with the QP ladders aligned from
a probe encode so the Bjontegaard integral interpolates. The extrapolation
share of each curve is measured and a run above 20% fails with a named
message instead of reporting a cubic guess.
crates/ec-h265/tests/encode.rsadded+736 -0
@@ -0,0 +1,736 @@
1+//! Encoder rate-quality gate: BD-PSNR of this encoder against x265 at matched
2+//! features over a QP sweep, modelled on ec-h264's `bd_psnr_vs_x264`.
3+//!
4+//! Both encoders code the same synthetic 352x288 24-picture clip, both are read
5+//! the same way — on ffmpeg's decode of the stream, not on either encoder's
6+//! own reconstruction — and x265's psychovisual and adaptive tools are off so
7+//! the comparison is at matched features, not at matched marketing.
8+
9+use ec_core::frame::VideoFrame;
10+use ec_h265::encoder::{Encoder, EncoderConfig, RateControl};
11+
12+/// One decoded picture: Y, Cb and Cr planes, cropped and tightly packed.
13+type Planes = (Vec<u8>, Vec<u8>, Vec<u8>);
14+
15+/// 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 advantage can
17+/// shrink but not grow unnoticed; it is not a claim that the number is fine.
18+///
19+/// Measured +2.456 dB luma / +3.158 dB YUV on the recalibrated run (352x288,
20+/// 24 pictures of `Clip::render_smooth`, x265 at QP 22/26/30/34, our ladder
21+/// auto-shifted from a QP-26 probe to 16/20/24/28, both sides decoded through
22+/// ffmpeg, union-range BD-PSNR, 0% extrapolation both sides). This is a
23+/// smooth-gradient result: it does NOT hold on real content, where our
24+/// encoder is no leaner than x265 at matched QP (the probe measures a shift of
25+/// 0) and the aligned BD is negative. Real-clip numbers, 24 pictures after
26+/// 1500, ladders auto-aligned to 22/26/30/34, 0% extrapolation both sides:
27+/// • 3840x1608 film: -0.731 dB luma / -0.730 dB YUV
28+/// • 1138x640 web clip: -0.603 dB luma / -0.632 dB YUV
29+/// Those two are the real gap to close; the synthetic number only guards
30+/// against regression on a clip whose content is pinned.
31+///
32+/// Previous run measured -38.258 dB luma with both sides at QP 22/26/30/34;
33+/// that number was meaningless because the two curves' bitrate ranges did not
34+/// overlap (50% extrapolation on our side) — a fixed QP offset could not
35+/// bridge encoders whose relative leanness varies with content. The shallow
36+/// all-intra rate-quality slope is genuine content behaviour (x264 forced
37+/// all-intra shows the same shape); the fix is to auto-align the ladders from
38+/// a probe encode, not to change x265's rate control.
39+const BD_PSNR_VS_X265_FLOOR: f64 = 2.306;
40+
41+/// A synthetic source with real structure: smooth gradients, a band of
42+/// sinusoidal texture and a translating box, so prediction matters — the half
43+/// a rate-quality comparison is about. Ported verbatim from ec-h264's `Clip`
44+/// (minus the `view()` method this encoder's `encode_idr_planes` does not
45+/// need).
46+struct Clip {
47+ w: usize,
48+ h: usize,
49+ y: Vec<u8>,
50+ u: Vec<u8>,
51+ v: Vec<u8>,
52+}
53+
54+impl Clip {
55+ fn new(w: usize, h: usize) -> Clip {
56+ Clip {
57+ w,
58+ h,
59+ y: vec![0; w * h],
60+ u: vec![0; w / 2 * h / 2],
61+ v: vec![0; w / 2 * h / 2],
62+ }
63+ }
64+
65+ /// Frame `t` without a per-sample noise field: smooth gradients, a band of
66+ /// sinusoidal texture and a box translating by whole and sub-sample
67+ /// amounts. Content where prediction matters, not where residual is
68+ /// incompressible.
69+ fn render_smooth(&mut self, t: usize) {
70+ let (w, h) = (self.w, self.h);
71+ let ft = t as f64;
72+ for y in 0..h {
73+ for x in 0..w {
74+ let (fx, fy) = (x as f64, y as f64);
75+ let ramp = (fx + fy * 0.5 - ft * 1.5) * 0.35;
76+ let texture = if y > h / 3 && y < 2 * h / 3 {
77+ 18.0 * ((fx * 0.19 + ft * 0.9).sin() + (fy * 0.11).cos())
78+ } else {
79+ 0.0
80+ };
81+ let box_x = ((ft * 2.7) as usize) % (w.saturating_sub(48).max(1));
82+ let inside = x >= box_x && x < box_x + 48 && y >= h / 5 && y < h / 5 + 36;
83+ let v = if inside {
84+ 196.0 - texture * 0.5
85+ } else {
86+ 40.0 + (ramp % 90.0).abs() + texture
87+ };
88+ self.y[y * w + x] = v.clamp(0.0, 255.0) as u8;
89+ }
90+ }
91+ for y in 0..h / 2 {
92+ for x in 0..w / 2 {
93+ let (fx, fy) = (x as f64, y as f64);
94+ self.u[y * (w / 2) + x] =
95+ (118.0 + 12.0 * ((fx * 0.05 + ft * 0.3).sin())).clamp(0.0, 255.0) as u8;
96+ self.v[y * (w / 2) + x] =
97+ (134.0 + 10.0 * ((fy * 0.04 - ft * 0.25).cos())).clamp(0.0, 255.0) as u8;
98+ }
99+ }
100+ }
101+}
102+
103+/// Crop and tightly pack the Y, Cb and Cr planes of a reconstruction.
104+fn planes_of(frame: &VideoFrame) -> Planes {
105+ let (w, h) = (frame.width as usize, frame.height as usize);
106+ let mut out = Vec::new();
107+ for (i, (pw, ph)) in [(w, h), (w / 2, h / 2), (w / 2, h / 2)]
108+ .into_iter()
109+ .enumerate()
110+ {
111+ let plane = &frame.planes[i];
112+ let mut buf = Vec::with_capacity(pw * ph);
113+ for row in 0..ph {
114+ buf.extend_from_slice(&plane.data[row * plane.stride..row * plane.stride + pw]);
115+ }
116+ out.push(buf);
117+ }
118+ let v = out.pop().unwrap();
119+ let u = out.pop().unwrap();
120+ let y = out.pop().unwrap();
121+ (y, u, v)
122+}
123+
124+/// Mean squared error between two equal-length planes.
125+fn plane_mse(a: &[u8], b: &[u8]) -> f64 {
126+ a.iter()
127+ .zip(b)
128+ .map(|(&x, &y)| {
129+ let d = f64::from(x) - f64::from(y);
130+ d * d
131+ })
132+ .sum::<f64>()
133+ / a.len() as f64
134+}
135+
136+/// PSNR over all three planes, pooled by sample count the way x265 reports it:
137+/// for 4:2:0 that weights luma 6 and each chroma plane 1. A luma-only number
138+/// rewards an encoder for throwing chroma away, so any decision that can move
139+/// chroma bits is read here instead.
140+fn psnr_yuv(a: &Planes, b: &Planes) -> f64 {
141+ let (n_y, n_c) = (a.0.len() as f64, a.1.len() as f64);
142+ let sse =
143+ plane_mse(&a.0, &b.0) * n_y + plane_mse(&a.1, &b.1) * n_c + plane_mse(&a.2, &b.2) * n_c;
144+ let mse = sse / (n_y + 2.0 * n_c);
145+ if mse == 0.0 {
146+ 99.0
147+ } else {
148+ 10.0 * (255.0 * 255.0 / mse).log10()
149+ }
150+}
151+
152+fn psnr(a: &[u8], b: &[u8]) -> f64 {
153+ let mse: f64 = a
154+ .iter()
155+ .zip(b)
156+ .map(|(&x, &y)| {
157+ let d = f64::from(x) - f64::from(y);
158+ d * d
159+ })
160+ .sum::<f64>()
161+ / a.len() as f64;
162+ if mse == 0.0 {
163+ 99.0
164+ } else {
165+ 10.0 * (255.0 * 255.0 / mse).log10()
166+ }
167+}
168+
169+#[allow(clippy::needless_range_loop)]
170+fn cubic_fit(xs: [f64; 4], ys: [f64; 4]) -> [f64; 4] {
171+ let mut a = [[0.0; 5]; 4];
172+ for i in 0..4 {
173+ a[i] = [1.0, xs[i], xs[i] * xs[i], xs[i] * xs[i] * xs[i], ys[i]];
174+ }
175+ for col in 0..4 {
176+ let mut pivot = col;
177+ for row in col + 1..4 {
178+ if a[row][col].abs() > a[pivot][col].abs() {
179+ pivot = row;
180+ }
181+ }
182+ a.swap(col, pivot);
183+ let div = a[col][col];
184+ assert!(div.abs() > 1e-12, "singular BD-PSNR fit");
185+ for j in col..5 {
186+ a[col][j] /= div;
187+ }
188+ for row in 0..4 {
189+ if row == col {
190+ continue;
191+ }
192+ let f = a[row][col];
193+ for j in col..5 {
194+ a[row][j] -= f * a[col][j];
195+ }
196+ }
197+ }
198+ [a[0][4], a[1][4], a[2][4], a[3][4]]
199+}
200+
201+fn cubic_integral(c: [f64; 4], x: f64) -> f64 {
202+ c[0] * x + c[1] * x * x / 2.0 + c[2] * x * x * x / 3.0 + c[3] * x * x * x * x / 4.0
203+}
204+
205+/// BD-PSNR: average PSNR difference between two rate-quality curves over a
206+/// shared bitrate range. Modelled on ec-h264's `bd_psnr_delta`, with one
207+/// departure: the integration range is the *union* of the two curves' bitrate
208+/// extents, not their intersection.
209+///
210+/// The h264 gate's encoders land in the same bitrate band at the same QP, so
211+/// the intersection is non-empty and the standard Bjøntegaard cubic integral
212+/// over it is well defined. Our h265 encoder's bitrate at matched QP can be
213+/// leaner or fatter than x265's depending on content, so the QP-ladder shift
214+/// is measured from a probe encode, not fixed — the union range is kept (not
215+/// clipped to the intersection) so the extrapolation share can be measured:
216+/// if either curve is extrapolated over more than 20% of the range, the test
217+/// fails with a named message instead of reporting a BD number that is a cubic
218+/// guess, not a measurement. The extrapolation shares are returned alongside
219+/// the number.
220+///
221+/// Returns `(bd, cand_extrap, anc_extrap)` where the extrap shares are the
222+/// fraction of the integration range that each curve's measured bitrate span
223+/// does not cover (0 = fully measured, 1 = entirely extrapolated).
224+fn bd_psnr_delta(candidate: &[(f64, f64)], anchor: &[(f64, f64)]) -> (f64, f64, f64) {
225+ let xs_candidate = std::array::from_fn(|i| candidate[i].0.ln());
226+ let ys_candidate = std::array::from_fn(|i| candidate[i].1);
227+ let xs_anchor = std::array::from_fn(|i| anchor[i].0.ln());
228+ let ys_anchor = std::array::from_fn(|i| anchor[i].1);
229+ // Union, not intersection: see the doc comment above.
230+ let lo = xs_candidate
231+ .iter()
232+ .copied()
233+ .fold(f64::INFINITY, f64::min)
234+ .min(xs_anchor.iter().copied().fold(f64::INFINITY, f64::min));
235+ let hi = xs_candidate
236+ .iter()
237+ .copied()
238+ .fold(f64::NEG_INFINITY, f64::max)
239+ .max(xs_anchor.iter().copied().fold(f64::NEG_INFINITY, f64::max));
240+ let c_candidate = cubic_fit(xs_candidate, ys_candidate);
241+ let c_anchor = cubic_fit(xs_anchor, ys_anchor);
242+ let (cand_lo, cand_hi) = (
243+ xs_candidate.iter().copied().fold(f64::INFINITY, f64::min),
244+ xs_candidate
245+ .iter()
246+ .copied()
247+ .fold(f64::NEG_INFINITY, f64::max),
248+ );
249+ let (anc_lo, anc_hi) = (
250+ xs_anchor.iter().copied().fold(f64::INFINITY, f64::min),
251+ xs_anchor.iter().copied().fold(f64::NEG_INFINITY, f64::max),
252+ );
253+ let cand_extrap = ((lo - cand_lo).max(0.0) + (hi - cand_hi).max(0.0)) / (cand_hi - cand_lo);
254+ let anc_extrap = ((lo - anc_lo).max(0.0) + (hi - anc_hi).max(0.0)) / (anc_hi - anc_lo);
255+ eprintln!(
256+ " cubic extrapolation: candidate {cand_extrap:.0}% anchor {anc_extrap:.0}% of measured range"
257+ );
258+ let bd = (cubic_integral(c_candidate, hi)
259+ - cubic_integral(c_candidate, lo)
260+ - cubic_integral(c_anchor, hi)
261+ + cubic_integral(c_anchor, lo))
262+ / (hi - lo);
263+ (bd, cand_extrap, anc_extrap)
264+}
265+
266+fn have_ffmpeg() -> bool {
267+ std::process::Command::new("ffmpeg")
268+ .arg("-version")
269+ .stdout(std::process::Stdio::null())
270+ .stderr(std::process::Stdio::null())
271+ .status()
272+ .is_ok_and(|s| s.success())
273+}
274+
275+fn have_x265() -> bool {
276+ std::process::Command::new("ffmpeg")
277+ .args(["-v", "error", "-hide_banner", "-encoders"])
278+ .output()
279+ .is_ok_and(|o| o.status.success() && String::from_utf8_lossy(&o.stdout).contains("libx265"))
280+}
281+
282+/// Decode an Annex-B stream with ffmpeg, returning one I420 triple per picture.
283+fn ffmpeg_decode(stream: &[u8], w: usize, h: usize) -> Option<Vec<Planes>> {
284+ let dir = std::env::temp_dir().join(format!("ec-h265-enc-{}", std::process::id()));
285+ std::fs::create_dir_all(&dir).ok()?;
286+ let path = dir.join(format!("s{}.265", stream.len()));
287+ std::fs::write(&path, stream).ok()?;
288+ let out = std::process::Command::new("ffmpeg")
289+ .args(["-v", "error"])
290+ .arg("-i")
291+ .arg(&path)
292+ .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "pipe:1"])
293+ .output()
294+ .ok()?;
295+ let _ = std::fs::remove_file(&path);
296+ if !out.status.success() {
297+ eprintln!("ffmpeg failed: {}", String::from_utf8_lossy(&out.stderr));
298+ return None;
299+ }
300+ let frame = w * h * 3 / 2;
301+ if frame == 0 || out.stdout.len() % frame != 0 {
302+ eprintln!(
303+ "ffmpeg returned {} bytes, not a whole number of {frame}-byte frames",
304+ out.stdout.len()
305+ );
306+ return None;
307+ }
308+ Some(
309+ out.stdout
310+ .chunks(frame)
311+ .map(|f| {
312+ let (y, rest) = f.split_at(w * h);
313+ let (u, v) = rest.split_at(w / 2 * h / 2);
314+ (y.to_vec(), u.to_vec(), v.to_vec())
315+ })
316+ .collect(),
317+ )
318+}
319+
320+/// Encode raw I420 pictures with x265 at constant QP, matched to what this
321+/// encoder actually does: intra-only (keyint 1), no B pictures, no scene cut
322+/// or lookahead, in-loop filters (SAO, deblock) off, adaptive quantisation off,
323+/// psychovisual RD and RDOQ off, RDOQ itself off, the shallowest intra TU
324+/// depth x265 allows (1, the closest it has to our
325+/// `max_transform_hierarchy_depth_intra=0`), and ipratio/pbratio/qcomp 1.0 so
326+/// constant-QP codes I pictures at the QP asked for. Returns the Annex-B
327+/// stream.
328+fn x265_encode_qp(sources: &[Planes], w: usize, h: usize, qp: i32) -> Option<Vec<u8>> {
329+ let dir = std::env::temp_dir().join(format!("ec-h265-x265-{}", std::process::id()));
330+ std::fs::create_dir_all(&dir).ok()?;
331+ let raw = dir.join(format!("in-q{qp}.yuv"));
332+ let out = dir.join(format!("out-q{qp}.265"));
333+ let mut buf = Vec::with_capacity(sources.len() * w * h * 3 / 2);
334+ for (y, u, v) in sources {
335+ buf.extend_from_slice(y);
336+ buf.extend_from_slice(u);
337+ buf.extend_from_slice(v);
338+ }
339+ std::fs::write(&raw, &buf).ok()?;
340+ // The param list is the h264 gate's x264 list translated to x265's option
341+ // names: psychovisual (psy-rd, psy-rdoq) and adaptive (aq-mode) tools off,
342+ // plus the in-loop filters x265 adds and x264 does not have (no-sao,
343+ // no-deblock), plus RDOQ off (rdoq-level=0) so the quantiser spends bits
344+ // the same way ours does. The quantiser goes inside the param string as
345+ // `qp=N`; `-x265-params qp=22` and `-x265-params rc=cqp:qp=22` produce
346+ // byte-identical streams, so the `rc=cqp:` prefix is unnecessary.
347+ // EC_H265_X265_PARAMS appends to attribute a single feature the same way
348+ // EC_H264_X264_PARAMS does.
349+ let params = format!(
350+ "qp={qp}:keyint=1:bframes=0:scenecut=0:rc-lookahead=0:no-sao:no-deblock:\
351+ aq-mode=0:psy-rd=0:psy-rdoq=0:rdoq-level=0:tu-intra-depth=1:ipratio=1.0:\
352+ pbratio=1.0:qcomp=1.0:chroma-qp-offset=0{}",
353+ match std::env::var("EC_H265_X265_PARAMS") {
354+ Ok(extra) if !extra.trim().trim_matches(':').is_empty() =>
355+ format!(":{}", extra.trim().trim_matches(':')),
356+ _ => String::new(),
357+ }
358+ );
359+ let status = std::process::Command::new("ffmpeg")
360+ .args(["-v", "error", "-y"])
361+ .args(["-f", "rawvideo", "-pix_fmt", "yuv420p"])
362+ .args(["-s", &format!("{w}x{h}"), "-r", "1"])
363+ .arg("-i")
364+ .arg(&raw)
365+ .args(["-c:v", "libx265", "-preset", "medium"])
366+ .args(["-x265-params", &params])
367+ .args(["-f", "hevc"])
368+ .arg(&out)
369+ .status()
370+ .ok()?;
371+ let _ = std::fs::remove_file(&raw);
372+ if !status.success() {
373+ return None;
374+ }
375+ let stream = std::fs::read(&out).ok();
376+ let _ = std::fs::remove_file(&out);
377+ stream
378+}
379+
380+/// BD-PSNR of this encoder against x265 at matched features. x265 is anchored
381+/// at QP 22/26/30/34; our ladder is shifted by a QP delta measured from a
382+/// probe encode at QP 26 (both sides), so the bitrate ranges overlap and the
383+/// cubic fit interpolates instead of extrapolating — regardless of whether
384+/// our encoder is leaner or fatter than x265 at matched QP on the content at
385+/// hand. Runs on the synthetic clip by default, so the number cannot rot
386+/// behind an `#[ignore]`; point `EC_H265_CLIP` at a media file to measure the
387+/// same thing on real content.
388+///
389+/// Both curves are (bits, luma PSNR against the same source pictures), and
390+/// both are measured on ffmpeg's decode of the stream rather than on an
391+/// encoder's own reconstruction, so the two halves are read the same way.
392+/// BD-PSNR-YUV pools all three planes by sample count (luma weighted 6, each
393+/// chroma 1 for 4:2:0), the way x265 reports it.
394+///
395+/// cargo test --release -p ec-h265 --test encode bd_psnr_vs_x265 -- --nocapture
396+/// EC_H265_CLIP=<file> cargo test --release -p ec-h265 --test encode \
397+/// bd_psnr_vs_x265 -- --nocapture
398+#[test]
399+fn bd_psnr_vs_x265() {
400+ if !have_ffmpeg() || !have_x265() {
401+ eprintln!(
402+ "SKIP bd_psnr_vs_x265: no ffmpeg with libx265 on PATH. \
403+ Install one, then: cargo test --release -p ec-h265 --test encode \
404+ bd_psnr_vs_x265 -- --nocapture"
405+ );
406+ return;
407+ }
408+ let (w, h, sources) = match std::env::var_os("EC_H265_CLIP") {
409+ Some(path) => clip_sources(&path, 24),
410+ None => {
411+ let (w, h, frames) = (352, 288, 24);
412+ let mut clip = Clip::new(w, h);
413+ let mut sources = Vec::with_capacity(frames);
414+ for t in 0..frames {
415+ clip.render_smooth(t);
416+ sources.push((clip.y.clone(), clip.u.clone(), clip.v.clone()));
417+ }
418+ eprintln!("synthetic clip: {w}x{h}, {frames} pictures");
419+ (w, h, sources)
420+ }
421+ };
422+
423+ let ours = |qp: i32| {
424+ let mut cfg = EncoderConfig::new(w as u32, h as u32);
425+ cfg.rate_control = RateControl::ConstantQp(qp);
426+ cfg.keep_recon = true;
427+ cfg.threads = 0;
428+ let enc = Encoder::new(cfg).expect("encoder");
429+ let (mut stream, mut sum_recon) = (Vec::new(), 0.0);
430+ for (y, u, v) in &sources {
431+ let coded = enc
432+ .encode_idr_planes(y, w, u, w / 2, v, w / 2)
433+ .expect("encode");
434+ stream.extend_from_slice(&coded.au);
435+ let recon = coded.recon.as_ref().expect("reconstruction");
436+ let (ry, _ru, _rv) = planes_of(recon);
437+ sum_recon += psnr(y, &ry);
438+ }
439+ // Measured the same way x265 is: on what a decoder shows, not on the
440+ // encoder's own reconstruction. The two are printed together because a
441+ // gap between them is a bug in one of the halves, not a rate-quality
442+ // result.
443+ let decoded = ffmpeg_decode(&stream, w, h).expect("ffmpeg decodes our stream");
444+ assert_eq!(decoded.len(), sources.len(), "our encoder dropped pictures");
445+ let n = sources.len() as f64;
446+ let sum: f64 = sources
447+ .iter()
448+ .zip(&decoded)
449+ .map(|((y, _, _), (dy, _, _))| psnr(y, dy))
450+ .sum();
451+ let sum_yuv: f64 = sources
452+ .iter()
453+ .zip(&decoded)
454+ .map(|(s, d)| psnr_yuv(s, d))
455+ .sum();
456+ let (sum_u, sum_v) = (
457+ sources
458+ .iter()
459+ .zip(&decoded)
460+ .map(|(s, d)| psnr(&s.1, &d.1))
461+ .sum::<f64>(),
462+ sources
463+ .iter()
464+ .zip(&decoded)
465+ .map(|(s, d)| psnr(&s.2, &d.2))
466+ .sum::<f64>(),
467+ );
468+ eprintln!(
469+ " ours qp {qp}: u {:.2} dB v {:.2} dB",
470+ sum_u / n,
471+ sum_v / n
472+ );
473+ let (decoded_psnr, recon_psnr) = (sum / n, sum_recon / n);
474+ assert!(
475+ (decoded_psnr - recon_psnr).abs() < 0.05,
476+ "qp {qp}: our reconstruction reads {recon_psnr:.2} dB but our own \
477+ stream decodes to {decoded_psnr:.2} dB"
478+ );
479+ ((stream.len() * 8) as f64, decoded_psnr, sum_yuv / n)
480+ };
481+ let x265 = |qp: i32| {
482+ let stream = x265_encode_qp(&sources, w, h, qp).expect("x265 encodes");
483+ let decoded = ffmpeg_decode(&stream, w, h).expect("ffmpeg decodes x265's own stream");
484+ assert_eq!(
485+ decoded.len(),
486+ sources.len(),
487+ "x265 returned {} pictures for {} sources",
488+ decoded.len(),
489+ sources.len()
490+ );
491+ let n = sources.len() as f64;
492+ let sum: f64 = sources
493+ .iter()
494+ .zip(&decoded)
495+ .map(|((y, _, _), (dy, _, _))| psnr(y, dy))
496+ .sum();
497+ let sum_yuv: f64 = sources
498+ .iter()
499+ .zip(&decoded)
500+ .map(|(s, d)| psnr_yuv(s, d))
501+ .sum();
502+ eprintln!(
503+ " x265 qp {qp}: u {:.2} dB v {:.2} dB",
504+ sources
505+ .iter()
506+ .zip(&decoded)
507+ .map(|(s, d)| psnr(&s.1, &d.1))
508+ .sum::<f64>()
509+ / n,
510+ sources
511+ .iter()
512+ .zip(&decoded)
513+ .map(|(s, d)| psnr(&s.2, &d.2))
514+ .sum::<f64>()
515+ / n
516+ );
517+ ((stream.len() * 8) as f64, sum / n, sum_yuv / n)
518+ };
519+
520+ // x265 stays anchored at QP 22/26/30/34. Our ladder is shifted by a QP
521+ // delta measured from a single probe encode, not a constant: both sides
522+ // are encoded at QP 26, the bit ratio is converted to a QP shift (≈6 QP
523+ // per factor of 2 in bits), and our four QPs run at 22/26/30/34 plus that
524+ // shift. If the extrapolation share still exceeds 20% after measuring, the
525+ // shift is re-estimated from the geometric-mean bit ratio of the two full
526+ // curves and the ladder is rebuilt — at most 2 extra alignment rounds
527+ // before the existing panic fires.
528+ const EXTRAP_LIMIT: f64 = 0.20;
529+ let x265_qps = [22, 26, 30, 34];
530+ let probe_qp = 26;
531+
532+ // Probe both encoders at QP 26 to measure the bit ratio.
533+ let probe_ours = ours(probe_qp);
534+ let probe_x265 = x265(probe_qp);
535+ let mut shift = (6.0 * (probe_ours.0 / probe_x265.0).log2()).round() as i32;
536+ eprintln!(
537+ "ladder shift {shift:+} (probe q{probe_qp}: ours {:.1} Mbit vs x265 {:.1} Mbit)",
538+ probe_ours.0 / 1e6,
539+ probe_x265.0 / 1e6,
540+ );
541+
542+ let curve = |v: &[(f64, f64, f64)], luma: bool| -> Vec<(f64, f64)> {
543+ v.iter()
544+ .map(|&(b, p, y)| (b, if luma { p } else { y }))
545+ .collect()
546+ };
547+
548+ // x265 ladder is fixed; reuse the probe for its QP-26 point.
549+ let theirs: Vec<(f64, f64, f64)> = x265_qps
550+ .iter()
551+ .map(|&q| if q == probe_qp { probe_x265 } else { x265(q) })
552+ .collect();
553+
554+ let gm = |v: &[(f64, f64, f64)]| (v[0].0 * v[1].0 * v[2].0 * v[3].0).powf(0.25);
555+ let qps_str = |qs: &[i32; 4]| {
556+ qs.iter()
557+ .map(|q| q.to_string())
558+ .collect::<Vec<_>>()
559+ .join("/")
560+ };
561+
562+ #[allow(unused_assignments)]
563+ let (
564+ mut bd,
565+ mut bd_yuv,
566+ mut cand_extrap,
567+ mut anc_extrap,
568+ mut cand_extrap_yuv,
569+ mut anc_extrap_yuv,
570+ ) = (0.0_f64, 0.0, 0.0, 0.0, 0.0, 0.0);
571+ let mut mine: Vec<(f64, f64, f64)>;
572+ let mut our_qps: [i32; 4];
573+
574+ for round in 0..=2u32 {
575+ our_qps = x265_qps.map(|q| (q + shift).clamp(1, 45));
576+ mine = our_qps
577+ .iter()
578+ .map(|&q| if q == probe_qp { probe_ours } else { ours(q) })
579+ .collect();
580+ for (i, &qp) in our_qps.iter().enumerate() {
581+ let (ob, op, oy) = mine[i];
582+ eprintln!("qp {qp}: ours {ob:.0} bits {op:.2} dB ({oy:.2} yuv)");
583+ }
584+ for (i, &qp) in x265_qps.iter().enumerate() {
585+ let (xb, xp, xy) = theirs[i];
586+ eprintln!("qp {qp}: x265 {xb:.0} bits {xp:.2} dB ({xy:.2} yuv)");
587+ }
588+ (bd, cand_extrap, anc_extrap) = bd_psnr_delta(&curve(&mine, true), &curve(&theirs, true));
589+ (bd_yuv, cand_extrap_yuv, anc_extrap_yuv) =
590+ bd_psnr_delta(&curve(&mine, false), &curve(&theirs, false));
591+ eprintln!(
592+ "BD-PSNR ours (q{}) vs x265 (q{}): {bd:+.3} dB",
593+ qps_str(&our_qps),
594+ qps_str(&x265_qps),
595+ );
596+ eprintln!(
597+ "BD-PSNR-YUV ours (q{}) vs x265 (q{}): {bd_yuv:+.3} dB",
598+ qps_str(&our_qps),
599+ qps_str(&x265_qps),
600+ );
601+ let aligned = cand_extrap <= EXTRAP_LIMIT
602+ && anc_extrap <= EXTRAP_LIMIT
603+ && cand_extrap_yuv <= EXTRAP_LIMIT
604+ && anc_extrap_yuv <= EXTRAP_LIMIT;
605+ if aligned || round == 2 {
606+ break;
607+ }
608+ // Re-estimate the shift from the geometric-mean bit ratio of the two
609+ // full curves, then rebuild the ladder.
610+ let delta = (6.0 * (gm(&mine) / gm(&theirs)).log2()).round() as i32;
611+ shift += delta;
612+ eprintln!(
613+ "alignment round {}: shift {delta:+} -> {shift:+} \
614+ (gm ours {:.1} Mbit vs x265 {:.1} Mbit)",
615+ round + 1,
616+ gm(&mine) / 1e6,
617+ gm(&theirs) / 1e6,
618+ );
619+ }
620+
621+ // A BD number over a range where the two QP ladders do not overlap is not a
622+ // measurement — the cubic is extrapolating, not interpolating. Fail loudly
623+ // with the side that is out of range instead of reporting a meaningless gap.
624+ let out_of_range = |c: f64, a: f64| {
625+ let mut parts = Vec::new();
626+ if c > EXTRAP_LIMIT {
627+ parts.push(format!("ours {:.0}%", c * 100.0));
628+ }
629+ if a > EXTRAP_LIMIT {
630+ parts.push(format!("x265 {:.0}%", a * 100.0));
631+ }
632+ parts
633+ };
634+ let luma_oor = out_of_range(cand_extrap, anc_extrap);
635+ let yuv_oor = out_of_range(cand_extrap_yuv, anc_extrap_yuv);
636+ if !luma_oor.is_empty() {
637+ panic!(
638+ "BD-PSNR luma: the two QP ladders do not overlap — {} of the \
639+ integration range is extrapolated (limit {:.0}%); widen the QP \
640+ sweep until the curves meet",
641+ luma_oor.join(", "),
642+ EXTRAP_LIMIT * 100.0
643+ );
644+ }
645+ if !yuv_oor.is_empty() {
646+ panic!(
647+ "BD-PSNR-YUV: the two QP ladders do not overlap — {} of the \
648+ integration range is extrapolated (limit {:.0}%); widen the QP \
649+ sweep until the curves meet",
650+ yuv_oor.join(", "),
651+ EXTRAP_LIMIT * 100.0
652+ );
653+ }
654+
655+ // The floor is calibrated on the synthetic clip; a clip of the user's is a
656+ // measurement, not a gate, because its content is not pinned.
657+ if std::env::var_os("EC_H265_CLIP").is_none() {
658+ assert!(
659+ bd > BD_PSNR_VS_X265_FLOOR,
660+ "BD-PSNR against x265 fell to {bd:+.3} dB, past the \
661+ {BD_PSNR_VS_X265_FLOOR:+.3} dB floor"
662+ );
663+ }
664+}
665+
666+/// Decode `want` pictures from a media file as tightly packed I420 triples.
667+/// `EC_H265_CLIP_SKIP` passes over that many pictures before sampling (film
668+/// heads are titles and fades).
669+fn clip_sources(path: &std::ffi::OsStr, want: usize) -> (usize, usize, Vec<Planes>) {
670+ let dims = std::process::Command::new("ffprobe")
671+ .args([
672+ "-v",
673+ "error",
674+ "-select_streams",
675+ "v:0",
676+ "-show_entries",
677+ "stream=width,height",
678+ "-of",
679+ "csv=p=0",
680+ ])
681+ .arg(path)
682+ .output()
683+ .expect("ffprobe");
684+ assert!(
685+ dims.status.success(),
686+ "ffprobe failed: {}",
687+ String::from_utf8_lossy(&dims.stderr)
688+ );
689+ let csv = String::from_utf8_lossy(&dims.stdout);
690+ let (w, h) = csv
691+ .trim()
692+ .split_once(',')
693+ .and_then(|(w, h)| Some((w.parse::<usize>().ok()?, h.parse::<usize>().ok()?)))
694+ .expect("ffprobe returned dimensions");
695+ let raw = std::process::Command::new("ffmpeg")
696+ .args(["-v", "error", "-i"])
697+ .arg(path)
698+ .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "pipe:1"])
699+ .output()
700+ .expect("ffmpeg raw extract");
701+ assert!(
702+ raw.status.success(),
703+ "ffmpeg failed: {}",
704+ String::from_utf8_lossy(&raw.stderr)
705+ );
706+ let frame = w * h * 3 / 2;
707+ assert!(
708+ raw.stdout.len().is_multiple_of(frame) && raw.stdout.len() / frame >= want,
709+ "clip {} yielded {} bytes, need {want}x{frame}",
710+ path.to_string_lossy(),
711+ raw.stdout.len()
712+ );
713+ let skip: usize = std::env::var("EC_H265_CLIP_SKIP")
714+ .ok()
715+ .and_then(|v| v.parse().ok())
716+ .unwrap_or(0);
717+ let sources: Vec<Planes> = raw
718+ .stdout
719+ .chunks(frame)
720+ .skip(skip)
721+ .take(want)
722+ .map(|f| {
723+ let (y, rest) = f.split_at(w * h);
724+ let (u, v) = rest.split_at(w / 2 * h / 2);
725+ (y.to_vec(), u.to_vec(), v.to_vec())
726+ })
727+ .collect();
728+ eprintln!(
729+ "{}: {}x{}, {} pictures (skipped {skip})",
730+ path.to_string_lossy(),
731+ w,
732+ h,
733+ sources.len()
734+ );
735+ (w, h, sources)
736+}