forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB214cdf2Tahinli3 months ago821 commits

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