forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB00a6ca0Tahinli3 months ago1913 commits

encode.rs858 lines, 33.3 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_RDOQ_ESTIMATE") {
452 cfg.rdoq_estimate = v != "0";
453 }
454 if let Ok(v) = std::env::var("EC_H265_TSKIP") {
455 cfg.transform_skip = if v != "0" {
456 TransformSkip::AlwaysFor4x4
457 } else {
458 TransformSkip::Off
459 };
460 }
461 if let Ok(v) = std::env::var("EC_H265_NXN") {
462 cfg.intra_nxn = v != "0";
463 }
464 if let Ok(v) = std::env::var("EC_H265_CTB") {
465 cfg.ctb_size = v.parse().expect("EC_H265_CTB must be 32 or 64");
466 }
467 if let Ok(v) = std::env::var("EC_H265_CU64") {
468 cfg.cu64 = v != "0";
469 }
470 if let Ok(v) = std::env::var("EC_H265_DEBLOCK") {
471 cfg.deblock = v != "0";
472 }
473 if let Ok(v) = std::env::var("EC_H265_RQT") {
474 cfg.rqt = v != "0";
475 }
476 if let Ok(k) = std::env::var("EC_H265_RDO_CANDIDATES") {
477 cfg.rdo_candidates = k.parse().expect("EC_H265_RDO_CANDIDATES must be a number");
478 }
479 let enc = Encoder::new(cfg).expect("encoder");
480 let (mut stream, mut sum_recon) = (Vec::new(), 0.0);
481 for (y, u, v) in &sources {
482 let coded = enc
483 .encode_idr_planes(y, w, u, w / 2, v, w / 2)
484 .expect("encode");
485 stream.extend_from_slice(&coded.au);
486 let recon = coded.recon.as_ref().expect("reconstruction");
487 let (ry, _ru, _rv) = planes_of(recon);
488 sum_recon += psnr(y, &ry);
489 }
490 // Measured the same way x265 is: on what a decoder shows, not on the
491 // encoder's own reconstruction. The two are printed together because a
492 // gap between them is a bug in one of the halves, not a rate-quality
493 // result.
494 let decoded = ffmpeg_decode(&stream, w, h).expect("ffmpeg decodes our stream");
495 assert_eq!(decoded.len(), sources.len(), "our encoder dropped pictures");
496 let n = sources.len() as f64;
497 let sum: f64 = sources
498 .iter()
499 .zip(&decoded)
500 .map(|((y, _, _), (dy, _, _))| psnr(y, dy))
501 .sum();
502 let sum_yuv: f64 = sources
503 .iter()
504 .zip(&decoded)
505 .map(|(s, d)| psnr_yuv(s, d))
506 .sum();
507 let (sum_u, sum_v) = (
508 sources
509 .iter()
510 .zip(&decoded)
511 .map(|(s, d)| psnr(&s.1, &d.1))
512 .sum::<f64>(),
513 sources
514 .iter()
515 .zip(&decoded)
516 .map(|(s, d)| psnr(&s.2, &d.2))
517 .sum::<f64>(),
518 );
519 eprintln!(
520 " ours qp {qp}: u {:.2} dB v {:.2} dB",
521 sum_u / n,
522 sum_v / n
523 );
524 let (decoded_psnr, recon_psnr) = (sum / n, sum_recon / n);
525 assert!(
526 (decoded_psnr - recon_psnr).abs() < 0.05,
527 "qp {qp}: our reconstruction reads {recon_psnr:.2} dB but our own \
528 stream decodes to {decoded_psnr:.2} dB"
529 );
530 ((stream.len() * 8) as f64, decoded_psnr, sum_yuv / n)
531 };
532 let x265 = |qp: i32| {
533 let stream = x265_encode_qp(&sources, w, h, qp).expect("x265 encodes");
534 let decoded = ffmpeg_decode(&stream, w, h).expect("ffmpeg decodes x265's own stream");
535 assert_eq!(
536 decoded.len(),
537 sources.len(),
538 "x265 returned {} pictures for {} sources",
539 decoded.len(),
540 sources.len()
541 );
542 let n = sources.len() as f64;
543 let sum: f64 = sources
544 .iter()
545 .zip(&decoded)
546 .map(|((y, _, _), (dy, _, _))| psnr(y, dy))
547 .sum();
548 let sum_yuv: f64 = sources
549 .iter()
550 .zip(&decoded)
551 .map(|(s, d)| psnr_yuv(s, d))
552 .sum();
553 eprintln!(
554 " x265 qp {qp}: u {:.2} dB v {:.2} dB",
555 sources
556 .iter()
557 .zip(&decoded)
558 .map(|(s, d)| psnr(&s.1, &d.1))
559 .sum::<f64>()
560 / n,
561 sources
562 .iter()
563 .zip(&decoded)
564 .map(|(s, d)| psnr(&s.2, &d.2))
565 .sum::<f64>()
566 / n
567 );
568 ((stream.len() * 8) as f64, sum / n, sum_yuv / n)
569 };
570
571 // x265 stays anchored at QP 22/26/30/34. Our ladder is shifted by a QP
572 // delta measured from a single probe encode, not a constant: both sides
573 // are encoded at QP 26, the bit ratio is converted to a QP shift (≈6 QP
574 // per factor of 2 in bits), and our four QPs run at 22/26/30/34 plus that
575 // shift. If the extrapolation share still exceeds 20% after measuring, the
576 // shift is re-estimated from the geometric-mean bit ratio of the two full
577 // curves and the ladder is rebuilt; once the rates match and the curves
578 // still do not meet, our ladder is drawn in towards its own centre until
579 // its bitrate range fits inside the anchor's — at most 8 alignment rounds
580 // before the existing panic fires.
581 const EXTRAP_LIMIT: f64 = 0.20;
582 let x265_qps = [22, 26, 30, 34];
583 let probe_qp = 26;
584
585 // Probe both encoders at QP 26 to measure the bit ratio.
586 let probe_ours = ours(probe_qp);
587 let probe_x265 = x265(probe_qp);
588 // A sample window with nothing in it (a film's black head, a fade) codes
589 // to a handful of bits and decodes back to the source exactly, so every
590 // point on both curves sits at the PSNR cap and the BD number is a flat
591 // +0.000 that looks like a measurement. Refuse it by name.
592 const FLAT_WINDOW_DB: f64 = 90.0;
593 assert!(
594 probe_x265.1 < FLAT_WINDOW_DB && probe_ours.1 < FLAT_WINDOW_DB,
595 "the sample window is flat — both encoders reach the PSNR cap on it \
596 (ours {:.2} dB, x265 {:.2} dB at qp {probe_qp}); this is a black head \
597 or a fade, not content: pass EC_H265_CLIP_SKIP to sample past it",
598 probe_ours.1,
599 probe_x265.1,
600 );
601 let mut shift = (6.0 * (probe_ours.0 / probe_x265.0).log2()).round() as i32;
602 eprintln!(
603 "ladder shift {shift:+} (probe q{probe_qp}: ours {:.1} Mbit vs x265 {:.1} Mbit)",
604 probe_ours.0 / 1e6,
605 probe_x265.0 / 1e6,
606 );
607
608 let curve = |v: &[(f64, f64, f64)], luma: bool| -> Vec<(f64, f64)> {
609 v.iter()
610 .map(|&(b, p, y)| (b, if luma { p } else { y }))
611 .collect()
612 };
613
614 // x265 ladder is fixed; reuse the probe for its QP-26 point.
615 let theirs: Vec<(f64, f64, f64)> = x265_qps
616 .iter()
617 .map(|&q| if q == probe_qp { probe_x265 } else { x265(q) })
618 .collect();
619
620 let gm = |v: &[(f64, f64, f64)]| (v[0].0 * v[1].0 * v[2].0 * v[3].0).powf(0.25);
621 let qps_str = |qs: &[i32; 4]| {
622 qs.iter()
623 .map(|q| q.to_string())
624 .collect::<Vec<_>>()
625 .join("/")
626 };
627
628 #[allow(unused_assignments)]
629 let (
630 mut bd,
631 mut bd_yuv,
632 mut cand_extrap,
633 mut anc_extrap,
634 mut cand_extrap_yuv,
635 mut anc_extrap_yuv,
636 ) = (0.0_f64, 0.0, 0.0, 0.0, 0.0, 0.0);
637 let mut mine: Vec<(f64, f64, f64)>;
638 let mut our_qps: [i32; 4];
639 // How wide our QP ladder is against the anchor's, as a fraction of its
640 // spacing: one encoder can answer a QP step with far more bitrate than the
641 // other, and a BD number needs both curves over the same range.
642 let mut spread = 1.0_f64;
643
644 for round in 0..=8u32 {
645 our_qps = x265_qps.map(|q| {
646 let centre = f64::from(probe_qp + shift);
647 let offset = f64::from(q - probe_qp) * spread;
648 ((centre + offset).round() as i32).clamp(1, 45)
649 });
650 let mut distinct = our_qps;
651 distinct.sort_unstable();
652 let collapsed = distinct.windows(2).any(|w| w[0] == w[1]);
653 assert!(
654 !collapsed,
655 "our QP ladder collapsed to {:?}: the shift has pushed it into the \
656 qp floor, so two points share an x and the cubic has no unique fit",
657 our_qps,
658 );
659 mine = our_qps
660 .iter()
661 .map(|&q| if q == probe_qp { probe_ours } else { ours(q) })
662 .collect();
663 for (i, &qp) in our_qps.iter().enumerate() {
664 let (ob, op, oy) = mine[i];
665 eprintln!("qp {qp}: ours {ob:.0} bits {op:.2} dB ({oy:.2} yuv)");
666 }
667 for (i, &qp) in x265_qps.iter().enumerate() {
668 let (xb, xp, xy) = theirs[i];
669 eprintln!("qp {qp}: x265 {xb:.0} bits {xp:.2} dB ({xy:.2} yuv)");
670 }
671 (bd, cand_extrap, anc_extrap) = bd_psnr_delta(&curve(&mine, true), &curve(&theirs, true));
672 (bd_yuv, cand_extrap_yuv, anc_extrap_yuv) =
673 bd_psnr_delta(&curve(&mine, false), &curve(&theirs, false));
674 eprintln!(
675 "BD-PSNR ours (q{}) vs x265 (q{}): {bd:+.3} dB",
676 qps_str(&our_qps),
677 qps_str(&x265_qps),
678 );
679 eprintln!(
680 "BD-PSNR-YUV ours (q{}) vs x265 (q{}): {bd_yuv:+.3} dB",
681 qps_str(&our_qps),
682 qps_str(&x265_qps),
683 );
684 let aligned = cand_extrap <= EXTRAP_LIMIT
685 && anc_extrap <= EXTRAP_LIMIT
686 && cand_extrap_yuv <= EXTRAP_LIMIT
687 && anc_extrap_yuv <= EXTRAP_LIMIT;
688 if aligned || round == 8 {
689 break;
690 }
691 // Re-estimate the shift from the geometric-mean bit ratio of the two
692 // full curves, then rebuild the ladder. A single-QP correction is
693 // ignored: it is within the rounding of the estimate and only makes the
694 // ladder oscillate between two neighbouring shifts.
695 let delta = (6.0 * (gm(&mine) / gm(&theirs)).log2()).round() as i32;
696 if delta.abs() > 1 {
697 shift += delta;
698 eprintln!(
699 "alignment round {}: shift {delta:+} -> {shift:+} \
700 (gm ours {:.1} Mbit vs x265 {:.1} Mbit)",
701 round + 1,
702 gm(&mine) / 1e6,
703 gm(&theirs) / 1e6,
704 );
705 continue;
706 }
707 // The rates match and the curves still do not overlap, so our ladder
708 // spans a much wider bitrate range than the anchor's: their union is
709 // then mostly outside what x265 measured and the cubic through its four
710 // points extrapolates over most of it. Draw our ladder in.
711 spread *= 0.5;
712 eprintln!(
713 "alignment round {}: ladder spread -> {spread:.2} of the anchor's",
714 round + 1
715 );
716 }
717
718 // A BD number over a range where the two QP ladders do not overlap is not a
719 // measurement — the cubic is extrapolating, not interpolating. Fail loudly
720 // with the side that is out of range instead of reporting a meaningless gap.
721 let out_of_range = |c: f64, a: f64| {
722 let mut parts = Vec::new();
723 if c > EXTRAP_LIMIT {
724 parts.push(format!("ours {:.0}%", c * 100.0));
725 }
726 if a > EXTRAP_LIMIT {
727 parts.push(format!("x265 {:.0}%", a * 100.0));
728 }
729 parts
730 };
731 let luma_oor = out_of_range(cand_extrap, anc_extrap);
732 let yuv_oor = out_of_range(cand_extrap_yuv, anc_extrap_yuv);
733 if !luma_oor.is_empty() {
734 panic!(
735 "BD-PSNR luma: the two QP ladders do not overlap — {} of the \
736 integration range is extrapolated (limit {:.0}%); widen the QP \
737 sweep until the curves meet",
738 luma_oor.join(", "),
739 EXTRAP_LIMIT * 100.0
740 );
741 }
742 if !yuv_oor.is_empty() {
743 panic!(
744 "BD-PSNR-YUV: the two QP ladders do not overlap — {} of the \
745 integration range is extrapolated (limit {:.0}%); widen the QP \
746 sweep until the curves meet",
747 yuv_oor.join(", "),
748 EXTRAP_LIMIT * 100.0
749 );
750 }
751
752 // The floor is calibrated on the synthetic clip; a clip of the user's is a
753 // measurement, not a gate, because its content is not pinned.
754 if std::env::var_os("EC_H265_CLIP").is_none() {
755 assert!(
756 bd > BD_PSNR_VS_X265_FLOOR,
757 "BD-PSNR against x265 fell to {bd:+.3} dB, past the \
758 {BD_PSNR_VS_X265_FLOOR:+.3} dB floor"
759 );
760 }
761}
762
763/// Decode `want` pictures from a media file as tightly packed I420 triples.
764/// `EC_H265_CLIP_SKIP` passes over that many pictures before sampling (film
765/// heads are titles and fades).
766fn clip_sources(path: &std::ffi::OsStr, want: usize) -> (usize, usize, Vec<Planes>) {
767 let dims = std::process::Command::new("ffprobe")
768 .args([
769 "-v",
770 "error",
771 "-select_streams",
772 "v:0",
773 "-show_entries",
774 "stream=width,height",
775 "-of",
776 "csv=p=0",
777 ])
778 .arg(path)
779 .output()
780 .expect("ffprobe");
781 assert!(
782 dims.status.success(),
783 "ffprobe failed: {}",
784 String::from_utf8_lossy(&dims.stderr)
785 );
786 let csv = String::from_utf8_lossy(&dims.stdout);
787 // ffprobe prints one comma-separated line per stream, and recent builds
788 // end it with a trailing separator, so the fields are taken by position
789 // rather than by splitting the line in two.
790 let mut fields = csv.lines().next().unwrap_or_default().split(',');
791 let (w, h) = (|| {
792 Some((
793 fields.next()?.trim().parse::<usize>().ok()?,
794 fields.next()?.trim().parse::<usize>().ok()?,
795 ))
796 })()
797 .unwrap_or_else(|| panic!("ffprobe returned dimensions, got {csv:?}"));
798 // Pictures to pass over before sampling: the head of a film is titles and
799 // fades, which are not what a codec is measured on.
800 let skip: usize = std::env::var("EC_H265_CLIP_SKIP")
801 .ok()
802 .and_then(|v| v.parse().ok())
803 .unwrap_or(0);
804 // Trim on ffmpeg's side, not ours. Asking for the whole file and slicing
805 // afterwards buffers the entire decoded clip in memory: a 1080p feature is
806 // hundreds of gigabytes of raw I420, which the kernel answers with the OOM
807 // killer. `select` drops the skipped pictures inside ffmpeg and
808 // `-frames:v` stops the decode once `want` have come out, so what reaches
809 // this process is exactly `want` frames.
810 let raw = std::process::Command::new("ffmpeg")
811 .args(["-v", "error", "-i"])
812 .arg(path)
813 .args([
814 "-vf",
815 &format!("select=gte(n\\,{skip})"),
816 "-fps_mode",
817 "passthrough",
818 "-frames:v",
819 &want.to_string(),
820 "-f",
821 "rawvideo",
822 "-pix_fmt",
823 "yuv420p",
824 "pipe:1",
825 ])
826 .output()
827 .expect("ffmpeg raw extract");
828 assert!(
829 raw.status.success(),
830 "ffmpeg failed: {}",
831 String::from_utf8_lossy(&raw.stderr)
832 );
833 let frame = w * h * 3 / 2;
834 assert!(
835 raw.stdout.len().is_multiple_of(frame) && raw.stdout.len() / frame >= want,
836 "clip {} yielded {} bytes after skipping {skip}, need {want}x{frame}",
837 path.to_string_lossy(),
838 raw.stdout.len()
839 );
840 let sources: Vec<Planes> = raw
841 .stdout
842 .chunks(frame)
843 .take(want)
844 .map(|f| {
845 let (y, rest) = f.split_at(w * h);
846 let (u, v) = rest.split_at(w / 2 * h / 2);
847 (y.to_vec(), u.to_vec(), v.to_vec())
848 })
849 .collect();
850 eprintln!(
851 "{}: {}x{}, {} pictures (skipped {skip})",
852 path.to_string_lossy(),
853 w,
854 h,
855 sources.len()
856 );
857 (w, h, sources)
858}