forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust376.5 MiB7eb6d34Tahinli9 hours ago4054 commits

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