forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

encode.rs938 lines, 36.7 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_ffmpeg() -> bool {
270 std::process::Command::new("ffmpeg")
271 .arg("-version")
272 .stdout(std::process::Stdio::null())
273 .stderr(std::process::Stdio::null())
274 .status()
275 .is_ok_and(|s| s.success())
276}
277
278fn have_x265() -> bool {
279 std::process::Command::new("ffmpeg")
280 .args(["-v", "error", "-hide_banner", "-encoders"])
281 .output()
282 .is_ok_and(|o| o.status.success() && String::from_utf8_lossy(&o.stdout).contains("libx265"))
283}
284
285#[cfg(unix)]
286#[test]
287fn pin_loud_reds_on_an_ok_but_short_write() {
288 // The shape the two sites above left open: a write that reports success and
289 // leaves a file of a different length. A symlink to /dev/null accepts every
290 // byte and stores none, so `fs::write` returns Ok and the file is 0 bytes --
291 // a stream path, silently empty.
292 let dir = std::env::temp_dir().join(format!("ec-h265-pinloud-{}", std::process::id()));
293 std::fs::create_dir_all(&dir).expect("scratch dir");
294 let path = dir.join("ok-but-short.265");
295 let _ = std::fs::remove_file(&path);
296 std::os::unix::fs::symlink("/dev/null", &path).expect("symlink to /dev/null");
297 let why = pin_loud("ok_but_short", &path, &[7u8; 1234]).unwrap_err();
298 assert!(why.contains(&path.display().to_string()), "{why}");
299 assert!(why.contains("file holds 0 of 1234 bytes"), "{why}");
300 std::fs::remove_file(&path).ok();
301
302 // The control: the same call on a real file succeeds and leaves every byte.
303 let good = dir.join("whole.265");
304 let bytes = vec![7u8; 1234];
305 pin_loud("control", &good, &bytes).expect("a whole write is not short");
306 assert_eq!(std::fs::read(&good).expect("read back"), bytes);
307 std::fs::remove_file(&good).ok();
308 std::fs::remove_dir_all(&dir).ok();
309}
310
311#[cfg(unix)]
312#[test]
313fn pin_loud_reports_what_landed_under_a_size_cap() {
314 // The Err arm, driven for real: `ulimit -f` caps the file, the kernel stores
315 // everything up to the cap and only then returns EFBIG. The line must carry
316 // the bytes that actually LANDED (512 of a 1 KiB-block cap), not the count
317 // the writer confirmed, which is zero.
318 use std::process::Command;
319 let Ok(exe) = std::env::current_exe() else {
320 return;
321 };
322 // SIGXFSZ's default action would kill the child before it can print;
323 // `trap '' XFSZ` sets SIG_IGN, which survives the exec.
324 let script = format!(
325 "ulimit -f 1; trap '' XFSZ; exec {} --exact encode::pin_loud_cap_child --nocapture",
326 exe.display()
327 );
328 let out = Command::new("sh")
329 .args(["-c", &script])
330 .env("EC_PINLOUD_CHILD", "1")
331 .output()
332 .expect("run the capped child");
333 let text = format!(
334 "{}{}",
335 String::from_utf8_lossy(&out.stdout),
336 String::from_utf8_lossy(&out.stderr)
337 );
338 assert!(!out.status.success(), "the capped write must fail: {text}");
339 assert!(text.contains("file holds 512 of 4096 bytes"), "{text}");
340 assert!(
341 text.contains("EFBIG") || text.contains("File too large"),
342 "{text}"
343 );
344}
345
346/// Child of [`pin_loud_reports_what_landed_under_a_size_cap`]: runs under
347/// `ulimit -f 1` (a 1 KiB block cap) and pins 4096 bytes, so the write fails
348/// partway. Inert unless the parent set `EC_PINLOUD_CHILD`.
349#[test]
350fn pin_loud_cap_child() {
351 if std::env::var_os("EC_PINLOUD_CHILD").is_none() {
352 return;
353 }
354 let dir = std::env::temp_dir().join(format!("ec-h265-pinloud-cap-{}", std::process::id()));
355 std::fs::create_dir_all(&dir).expect("scratch dir");
356 let path = dir.join("capped.265");
357 let why =
358 pin_loud("capped", &path, &[7u8; 4096]).expect_err("4096 bytes cannot fit a 1 KiB cap");
359 std::fs::remove_file(&path).ok();
360 std::fs::remove_dir_all(&dir).ok();
361 panic!("{why}");
362}
363
364/// Decode an Annex-B stream with ffmpeg, returning one I420 triple per picture.
365fn ffmpeg_decode(stream: &[u8], w: usize, h: usize) -> Option<Vec<Planes>> {
366 let dir = std::env::temp_dir().join(format!("ec-h265-enc-{}", std::process::id()));
367 std::fs::create_dir_all(&dir).ok()?;
368 let path = dir.join(format!("s{}.265", stream.len()));
369 pin_or_bail("ffmpeg_decode", &path, stream)?;
370 let out = std::process::Command::new("ffmpeg")
371 .args(["-v", "error"])
372 .arg("-i")
373 .arg(&path)
374 .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "pipe:1"])
375 .output()
376 .ok()?;
377 let _ = std::fs::remove_file(&path);
378 if !out.status.success() {
379 eprintln!("ffmpeg failed: {}", String::from_utf8_lossy(&out.stderr));
380 return None;
381 }
382 let frame = w * h * 3 / 2;
383 if frame == 0 || out.stdout.len() % frame != 0 {
384 eprintln!(
385 "ffmpeg returned {} bytes, not a whole number of {frame}-byte frames",
386 out.stdout.len()
387 );
388 return None;
389 }
390 Some(
391 out.stdout
392 .chunks(frame)
393 .map(|f| {
394 let (y, rest) = f.split_at(w * h);
395 let (u, v) = rest.split_at(w / 2 * h / 2);
396 (y.to_vec(), u.to_vec(), v.to_vec())
397 })
398 .collect(),
399 )
400}
401
402/// Encode raw I420 pictures with x265 at constant QP, matched to what this
403/// encoder actually does: intra-only (keyint 1), no B pictures, no scene cut
404/// or lookahead, in-loop filters (SAO, deblock) off, adaptive quantisation off,
405/// psychovisual RD and RDOQ off, RDOQ itself off, the shallowest intra TU
406/// depth x265 allows (1, the closest it has to our
407/// `max_transform_hierarchy_depth_intra=0`), and ipratio/pbratio/qcomp 1.0 so
408/// constant-QP codes I pictures at the QP asked for. Returns the Annex-B
409/// stream.
410fn x265_encode_qp(sources: &[Planes], w: usize, h: usize, qp: i32) -> Option<Vec<u8>> {
411 let dir = std::env::temp_dir().join(format!("ec-h265-x265-{}", std::process::id()));
412 std::fs::create_dir_all(&dir).ok()?;
413 let raw = dir.join(format!("in-q{qp}.yuv"));
414 let out = dir.join(format!("out-q{qp}.265"));
415 let mut buf = Vec::with_capacity(sources.len() * w * h * 3 / 2);
416 for (y, u, v) in sources {
417 buf.extend_from_slice(y);
418 buf.extend_from_slice(u);
419 buf.extend_from_slice(v);
420 }
421 pin_or_bail("x265_encode_qp", &raw, &buf)?;
422 // The param list is the h264 gate's x264 list translated to x265's option
423 // names: psychovisual (psy-rd, psy-rdoq) and adaptive (aq-mode) tools off,
424 // plus the in-loop filters x265 adds and x264 does not have (no-sao,
425 // no-deblock), plus RDOQ off (rdoq-level=0) so the quantiser spends bits
426 // the same way ours does. The quantiser goes inside the param string as
427 // `qp=N`; `-x265-params qp=22` and `-x265-params rc=cqp:qp=22` produce
428 // byte-identical streams, so the `rc=cqp:` prefix is unnecessary.
429 // EC_H265_X265_PARAMS appends to attribute a single feature the same way
430 // EC_H264_X264_PARAMS does.
431 let params = format!(
432 "qp={qp}:keyint=1:bframes=0:scenecut=0:rc-lookahead=0:no-sao:{deblock}\
433 aq-mode=0:psy-rd=0:psy-rdoq=0:rdoq-level=0:tu-intra-depth=1:ipratio=1.0:\
434 pbratio=1.0:qcomp=1.0:chroma-qp-offset=0{extra}",
435 // x265 deblocks by default; `no-deblock` matches an encoder that does
436 // not, and EC_H265_X265_DEBLOCK=1 drops it so both sides filter.
437 deblock = if std::env::var("EC_H265_X265_DEBLOCK").is_ok_and(|v| v != "0") {
438 ""
439 } else {
440 "no-deblock:"
441 },
442 extra = match std::env::var("EC_H265_X265_PARAMS") {
443 Ok(extra) if !extra.trim().trim_matches(':').is_empty() =>
444 format!(":{}", extra.trim().trim_matches(':')),
445 _ => String::new(),
446 }
447 );
448 let status = std::process::Command::new("ffmpeg")
449 .args(["-v", "error", "-y"])
450 .args(["-f", "rawvideo", "-pix_fmt", "yuv420p"])
451 .args(["-s", &format!("{w}x{h}"), "-r", "1"])
452 .arg("-i")
453 .arg(&raw)
454 .args(["-c:v", "libx265", "-preset", "medium"])
455 .args(["-x265-params", &params])
456 .args(["-f", "hevc"])
457 .arg(&out)
458 .status()
459 .ok()?;
460 let _ = std::fs::remove_file(&raw);
461 if !status.success() {
462 return None;
463 }
464 let stream = std::fs::read(&out).ok();
465 let _ = std::fs::remove_file(&out);
466 stream
467}
468
469/// BD-PSNR of this encoder against x265 at matched features. x265 is anchored
470/// at QP 22/26/30/34; our ladder is shifted by a QP delta measured from a
471/// probe encode at QP 26 (both sides), so the bitrate ranges overlap and the
472/// cubic fit interpolates instead of extrapolating — regardless of whether
473/// our encoder is leaner or fatter than x265 at matched QP on the content at
474/// hand. Runs on the synthetic clip by default, so the number cannot rot
475/// behind an `#[ignore]`; point `EC_H265_CLIP` at a media file to measure the
476/// same thing on real content.
477///
478/// Both curves are (bits, luma PSNR against the same source pictures), and
479/// both are measured on ffmpeg's decode of the stream rather than on an
480/// encoder's own reconstruction, so the two halves are read the same way.
481/// BD-PSNR-YUV pools all three planes by sample count (luma weighted 6, each
482/// chroma 1 for 4:2:0), the way x265 reports it.
483///
484/// cargo test --release -p ec-h265 --test encode bd_psnr_vs_x265 -- --nocapture
485/// EC_H265_CLIP=<file> cargo test --release -p ec-h265 --test encode \
486/// bd_psnr_vs_x265 -- --nocapture
487#[test]
488fn bd_psnr_vs_x265() {
489 if !have_ffmpeg() || !have_x265() {
490 eprintln!(
491 "SKIP bd_psnr_vs_x265: no ffmpeg with libx265 on PATH. \
492 Install one, then: cargo test --release -p ec-h265 --test encode \
493 bd_psnr_vs_x265 -- --nocapture"
494 );
495 return;
496 }
497 let (w, h, sources) = match std::env::var_os("EC_H265_CLIP") {
498 Some(path) => clip_sources(&path, 24),
499 None => {
500 let (w, h, frames) = (352, 288, 24);
501 let mut clip = Clip::new(w, h);
502 let mut sources = Vec::with_capacity(frames);
503 for t in 0..frames {
504 clip.render_smooth(t);
505 sources.push((clip.y.clone(), clip.u.clone(), clip.v.clone()));
506 }
507 eprintln!("synthetic clip: {w}x{h}, {frames} pictures");
508 (w, h, sources)
509 }
510 };
511
512 let ours = |qp: i32| {
513 let mut cfg = EncoderConfig::new(w as u32, h as u32);
514 cfg.rate_control = RateControl::ConstantQp(qp);
515 cfg.keep_recon = true;
516 cfg.threads = 0;
517 // Ablation knob: how many SATD survivors reach the full rate-distortion
518 // trial in the luma mode search. The shipped default is 5.
519 if let Ok(v) = std::env::var("EC_H265_CHROMA_RD") {
520 cfg.chroma_mode_search = v != "0";
521 }
522 if let Ok(w) = std::env::var("EC_H265_CHROMA_W") {
523 cfg.chroma_rd_weight = w.parse().expect("EC_H265_CHROMA_W must be a number");
524 }
525 if let Ok(v) = std::env::var("EC_H265_SDH") {
526 cfg.sign_hiding = v != "0";
527 }
528 if let Ok(v) = std::env::var("EC_H265_RDOQ") {
529 cfg.rdoq = v != "0";
530 }
531 if let Ok(v) = std::env::var("EC_H265_RDOQ_ESTIMATE") {
532 cfg.rdoq_estimate = v != "0";
533 }
534 if let Ok(v) = std::env::var("EC_H265_TSKIP") {
535 cfg.transform_skip = match v.as_str() {
536 "0" => TransformSkip::Off,
537 "always" => TransformSkip::AlwaysFor4x4,
538 _ => TransformSkip::Rd,
539 };
540 }
541 if let Ok(v) = std::env::var("EC_H265_NXN") {
542 cfg.intra_nxn = v != "0";
543 }
544 if let Ok(v) = std::env::var("EC_H265_CTB") {
545 cfg.ctb_size = v.parse().expect("EC_H265_CTB must be 32 or 64");
546 }
547 if let Ok(v) = std::env::var("EC_H265_CU64") {
548 cfg.cu64 = v != "0";
549 }
550 if let Ok(v) = std::env::var("EC_H265_DEBLOCK") {
551 cfg.deblock = v != "0";
552 }
553 if let Ok(v) = std::env::var("EC_H265_RQT") {
554 cfg.rqt = v != "0";
555 }
556 if let Ok(k) = std::env::var("EC_H265_RDO_CANDIDATES") {
557 cfg.rdo_candidates = k.parse().expect("EC_H265_RDO_CANDIDATES must be a number");
558 }
559 let enc = Encoder::new(cfg).expect("encoder");
560 let (mut stream, mut sum_recon) = (Vec::new(), 0.0);
561 for (y, u, v) in &sources {
562 let coded = enc
563 .encode_idr_planes(y, w, u, w / 2, v, w / 2)
564 .expect("encode");
565 stream.extend_from_slice(&coded.au);
566 let recon = coded.recon.as_ref().expect("reconstruction");
567 let (ry, _ru, _rv) = planes_of(recon);
568 sum_recon += psnr(y, &ry);
569 }
570 // Measured the same way x265 is: on what a decoder shows, not on the
571 // encoder's own reconstruction. The two are printed together because a
572 // gap between them is a bug in one of the halves, not a rate-quality
573 // result.
574 let decoded = ffmpeg_decode(&stream, w, h).expect("ffmpeg decodes our stream");
575 assert_eq!(decoded.len(), sources.len(), "our encoder dropped pictures");
576 let n = sources.len() as f64;
577 let sum: f64 = sources
578 .iter()
579 .zip(&decoded)
580 .map(|((y, _, _), (dy, _, _))| psnr(y, dy))
581 .sum();
582 let sum_yuv: f64 = sources
583 .iter()
584 .zip(&decoded)
585 .map(|(s, d)| psnr_yuv(s, d))
586 .sum();
587 let (sum_u, sum_v) = (
588 sources
589 .iter()
590 .zip(&decoded)
591 .map(|(s, d)| psnr(&s.1, &d.1))
592 .sum::<f64>(),
593 sources
594 .iter()
595 .zip(&decoded)
596 .map(|(s, d)| psnr(&s.2, &d.2))
597 .sum::<f64>(),
598 );
599 eprintln!(
600 " ours qp {qp}: u {:.2} dB v {:.2} dB",
601 sum_u / n,
602 sum_v / n
603 );
604 let (decoded_psnr, recon_psnr) = (sum / n, sum_recon / n);
605 assert!(
606 (decoded_psnr - recon_psnr).abs() < 0.05,
607 "qp {qp}: our reconstruction reads {recon_psnr:.2} dB but our own \
608 stream decodes to {decoded_psnr:.2} dB"
609 );
610 ((stream.len() * 8) as f64, decoded_psnr, sum_yuv / n)
611 };
612 let x265 = |qp: i32| {
613 let stream = x265_encode_qp(&sources, w, h, qp).expect("x265 encodes");
614 let decoded = ffmpeg_decode(&stream, w, h).expect("ffmpeg decodes x265's own stream");
615 assert_eq!(
616 decoded.len(),
617 sources.len(),
618 "x265 returned {} pictures for {} sources",
619 decoded.len(),
620 sources.len()
621 );
622 let n = sources.len() as f64;
623 let sum: f64 = sources
624 .iter()
625 .zip(&decoded)
626 .map(|((y, _, _), (dy, _, _))| psnr(y, dy))
627 .sum();
628 let sum_yuv: f64 = sources
629 .iter()
630 .zip(&decoded)
631 .map(|(s, d)| psnr_yuv(s, d))
632 .sum();
633 eprintln!(
634 " x265 qp {qp}: u {:.2} dB v {:.2} dB",
635 sources
636 .iter()
637 .zip(&decoded)
638 .map(|(s, d)| psnr(&s.1, &d.1))
639 .sum::<f64>()
640 / n,
641 sources
642 .iter()
643 .zip(&decoded)
644 .map(|(s, d)| psnr(&s.2, &d.2))
645 .sum::<f64>()
646 / n
647 );
648 ((stream.len() * 8) as f64, sum / n, sum_yuv / n)
649 };
650
651 // x265 stays anchored at QP 22/26/30/34. Our ladder is shifted by a QP
652 // delta measured from a single probe encode, not a constant: both sides
653 // are encoded at QP 26, the bit ratio is converted to a QP shift (≈6 QP
654 // per factor of 2 in bits), and our four QPs run at 22/26/30/34 plus that
655 // shift. If the extrapolation share still exceeds 20% after measuring, the
656 // shift is re-estimated from the geometric-mean bit ratio of the two full
657 // curves and the ladder is rebuilt; once the rates match and the curves
658 // still do not meet, our ladder is drawn in towards its own centre until
659 // its bitrate range fits inside the anchor's — at most 8 alignment rounds
660 // before the existing panic fires.
661 const EXTRAP_LIMIT: f64 = 0.20;
662 let x265_qps = [22, 26, 30, 34];
663 let probe_qp = 26;
664
665 // Probe both encoders at QP 26 to measure the bit ratio.
666 let probe_ours = ours(probe_qp);
667 let probe_x265 = x265(probe_qp);
668 // A sample window with nothing in it (a film's black head, a fade) codes
669 // to a handful of bits and decodes back to the source exactly, so every
670 // point on both curves sits at the PSNR cap and the BD number is a flat
671 // +0.000 that looks like a measurement. Refuse it by name.
672 const FLAT_WINDOW_DB: f64 = 90.0;
673 assert!(
674 probe_x265.1 < FLAT_WINDOW_DB && probe_ours.1 < FLAT_WINDOW_DB,
675 "the sample window is flat — both encoders reach the PSNR cap on it \
676 (ours {:.2} dB, x265 {:.2} dB at qp {probe_qp}); this is a black head \
677 or a fade, not content: pass EC_H265_CLIP_SKIP to sample past it",
678 probe_ours.1,
679 probe_x265.1,
680 );
681 let mut shift = (6.0 * (probe_ours.0 / probe_x265.0).log2()).round() as i32;
682 eprintln!(
683 "ladder shift {shift:+} (probe q{probe_qp}: ours {:.1} Mbit vs x265 {:.1} Mbit)",
684 probe_ours.0 / 1e6,
685 probe_x265.0 / 1e6,
686 );
687
688 let curve = |v: &[(f64, f64, f64)], luma: bool| -> Vec<(f64, f64)> {
689 v.iter()
690 .map(|&(b, p, y)| (b, if luma { p } else { y }))
691 .collect()
692 };
693
694 // x265 ladder is fixed; reuse the probe for its QP-26 point.
695 let theirs: Vec<(f64, f64, f64)> = x265_qps
696 .iter()
697 .map(|&q| if q == probe_qp { probe_x265 } else { x265(q) })
698 .collect();
699
700 let gm = |v: &[(f64, f64, f64)]| (v[0].0 * v[1].0 * v[2].0 * v[3].0).powf(0.25);
701 let qps_str = |qs: &[i32; 4]| {
702 qs.iter()
703 .map(|q| q.to_string())
704 .collect::<Vec<_>>()
705 .join("/")
706 };
707
708 #[allow(unused_assignments)]
709 let (
710 mut bd,
711 mut bd_yuv,
712 mut cand_extrap,
713 mut anc_extrap,
714 mut cand_extrap_yuv,
715 mut anc_extrap_yuv,
716 ) = (0.0_f64, 0.0, 0.0, 0.0, 0.0, 0.0);
717 let mut mine: Vec<(f64, f64, f64)>;
718 let mut our_qps: [i32; 4];
719 // How wide our QP ladder is against the anchor's, as a fraction of its
720 // spacing: one encoder can answer a QP step with far more bitrate than the
721 // other, and a BD number needs both curves over the same range.
722 let mut spread = 1.0_f64;
723
724 for round in 0..=8u32 {
725 our_qps = x265_qps.map(|q| {
726 let centre = f64::from(probe_qp + shift);
727 let offset = f64::from(q - probe_qp) * spread;
728 ((centre + offset).round() as i32).clamp(1, 45)
729 });
730 let mut distinct = our_qps;
731 distinct.sort_unstable();
732 let collapsed = distinct.windows(2).any(|w| w[0] == w[1]);
733 assert!(
734 !collapsed,
735 "our QP ladder collapsed to {:?}: the shift has pushed it into the \
736 qp floor, so two points share an x and the cubic has no unique fit",
737 our_qps,
738 );
739 mine = our_qps
740 .iter()
741 .map(|&q| if q == probe_qp { probe_ours } else { ours(q) })
742 .collect();
743 for (i, &qp) in our_qps.iter().enumerate() {
744 let (ob, op, oy) = mine[i];
745 eprintln!("qp {qp}: ours {ob:.0} bits {op:.2} dB ({oy:.2} yuv)");
746 }
747 for (i, &qp) in x265_qps.iter().enumerate() {
748 let (xb, xp, xy) = theirs[i];
749 eprintln!("qp {qp}: x265 {xb:.0} bits {xp:.2} dB ({xy:.2} yuv)");
750 }
751 (bd, cand_extrap, anc_extrap) = bd_psnr_delta(&curve(&mine, true), &curve(&theirs, true));
752 (bd_yuv, cand_extrap_yuv, anc_extrap_yuv) =
753 bd_psnr_delta(&curve(&mine, false), &curve(&theirs, false));
754 eprintln!(
755 "BD-PSNR ours (q{}) vs x265 (q{}): {bd:+.3} dB",
756 qps_str(&our_qps),
757 qps_str(&x265_qps),
758 );
759 eprintln!(
760 "BD-PSNR-YUV ours (q{}) vs x265 (q{}): {bd_yuv:+.3} dB",
761 qps_str(&our_qps),
762 qps_str(&x265_qps),
763 );
764 let aligned = cand_extrap <= EXTRAP_LIMIT
765 && anc_extrap <= EXTRAP_LIMIT
766 && cand_extrap_yuv <= EXTRAP_LIMIT
767 && anc_extrap_yuv <= EXTRAP_LIMIT;
768 if aligned || round == 8 {
769 break;
770 }
771 // Re-estimate the shift from the geometric-mean bit ratio of the two
772 // full curves, then rebuild the ladder. A single-QP correction is
773 // ignored: it is within the rounding of the estimate and only makes the
774 // ladder oscillate between two neighbouring shifts.
775 let delta = (6.0 * (gm(&mine) / gm(&theirs)).log2()).round() as i32;
776 if delta.abs() > 1 {
777 shift += delta;
778 eprintln!(
779 "alignment round {}: shift {delta:+} -> {shift:+} \
780 (gm ours {:.1} Mbit vs x265 {:.1} Mbit)",
781 round + 1,
782 gm(&mine) / 1e6,
783 gm(&theirs) / 1e6,
784 );
785 continue;
786 }
787 // The rates match and the curves still do not overlap, so our ladder
788 // spans a much wider bitrate range than the anchor's: their union is
789 // then mostly outside what x265 measured and the cubic through its four
790 // points extrapolates over most of it. Draw our ladder in.
791 spread *= 0.5;
792 eprintln!(
793 "alignment round {}: ladder spread -> {spread:.2} of the anchor's",
794 round + 1
795 );
796 }
797
798 // A BD number over a range where the two QP ladders do not overlap is not a
799 // measurement — the cubic is extrapolating, not interpolating. Fail loudly
800 // with the side that is out of range instead of reporting a meaningless gap.
801 let out_of_range = |c: f64, a: f64| {
802 let mut parts = Vec::new();
803 if c > EXTRAP_LIMIT {
804 parts.push(format!("ours {:.0}%", c * 100.0));
805 }
806 if a > EXTRAP_LIMIT {
807 parts.push(format!("x265 {:.0}%", a * 100.0));
808 }
809 parts
810 };
811 let luma_oor = out_of_range(cand_extrap, anc_extrap);
812 let yuv_oor = out_of_range(cand_extrap_yuv, anc_extrap_yuv);
813 if !luma_oor.is_empty() {
814 panic!(
815 "BD-PSNR luma: the two QP ladders do not overlap — {} of the \
816 integration range is extrapolated (limit {:.0}%); widen the QP \
817 sweep until the curves meet",
818 luma_oor.join(", "),
819 EXTRAP_LIMIT * 100.0
820 );
821 }
822 if !yuv_oor.is_empty() {
823 panic!(
824 "BD-PSNR-YUV: the two QP ladders do not overlap — {} of the \
825 integration range is extrapolated (limit {:.0}%); widen the QP \
826 sweep until the curves meet",
827 yuv_oor.join(", "),
828 EXTRAP_LIMIT * 100.0
829 );
830 }
831
832 // The floor is calibrated on the synthetic clip; a clip of the user's is a
833 // measurement, not a gate, because its content is not pinned.
834 if std::env::var_os("EC_H265_CLIP").is_none() {
835 assert!(
836 bd > BD_PSNR_VS_X265_FLOOR,
837 "BD-PSNR against x265 fell to {bd:+.3} dB, past the \
838 {BD_PSNR_VS_X265_FLOOR:+.3} dB floor"
839 );
840 }
841}
842
843/// Decode `want` pictures from a media file as tightly packed I420 triples.
844/// `EC_H265_CLIP_SKIP` passes over that many pictures before sampling (film
845/// heads are titles and fades).
846fn clip_sources(path: &std::ffi::OsStr, want: usize) -> (usize, usize, Vec<Planes>) {
847 let dims = std::process::Command::new("ffprobe")
848 .args([
849 "-v",
850 "error",
851 "-select_streams",
852 "v:0",
853 "-show_entries",
854 "stream=width,height",
855 "-of",
856 "csv=p=0",
857 ])
858 .arg(path)
859 .output()
860 .expect("ffprobe");
861 assert!(
862 dims.status.success(),
863 "ffprobe failed: {}",
864 String::from_utf8_lossy(&dims.stderr)
865 );
866 let csv = String::from_utf8_lossy(&dims.stdout);
867 // ffprobe prints one comma-separated line per stream, and recent builds
868 // end it with a trailing separator, so the fields are taken by position
869 // rather than by splitting the line in two.
870 let mut fields = csv.lines().next().unwrap_or_default().split(',');
871 let (w, h) = (|| {
872 Some((
873 fields.next()?.trim().parse::<usize>().ok()?,
874 fields.next()?.trim().parse::<usize>().ok()?,
875 ))
876 })()
877 .unwrap_or_else(|| panic!("ffprobe returned dimensions, got {csv:?}"));
878 // Pictures to pass over before sampling: the head of a film is titles and
879 // fades, which are not what a codec is measured on.
880 let skip: usize = std::env::var("EC_H265_CLIP_SKIP")
881 .ok()
882 .and_then(|v| v.parse().ok())
883 .unwrap_or(0);
884 // Trim on ffmpeg's side, not ours. Asking for the whole file and slicing
885 // afterwards buffers the entire decoded clip in memory: a 1080p feature is
886 // hundreds of gigabytes of raw I420, which the kernel answers with the OOM
887 // killer. `select` drops the skipped pictures inside ffmpeg and
888 // `-frames:v` stops the decode once `want` have come out, so what reaches
889 // this process is exactly `want` frames.
890 let raw = std::process::Command::new("ffmpeg")
891 .args(["-v", "error", "-i"])
892 .arg(path)
893 .args([
894 "-vf",
895 &format!("select=gte(n\\,{skip})"),
896 "-fps_mode",
897 "passthrough",
898 "-frames:v",
899 &want.to_string(),
900 "-f",
901 "rawvideo",
902 "-pix_fmt",
903 "yuv420p",
904 "pipe:1",
905 ])
906 .output()
907 .expect("ffmpeg raw extract");
908 assert!(
909 raw.status.success(),
910 "ffmpeg failed: {}",
911 String::from_utf8_lossy(&raw.stderr)
912 );
913 let frame = w * h * 3 / 2;
914 assert!(
915 raw.stdout.len().is_multiple_of(frame) && raw.stdout.len() / frame >= want,
916 "clip {} yielded {} bytes after skipping {skip}, need {want}x{frame}",
917 path.to_string_lossy(),
918 raw.stdout.len()
919 );
920 let sources: Vec<Planes> = raw
921 .stdout
922 .chunks(frame)
923 .take(want)
924 .map(|f| {
925 let (y, rest) = f.split_at(w * h);
926 let (u, v) = rest.split_at(w / 2 * h / 2);
927 (y.to_vec(), u.to_vec(), v.to_vec())
928 })
929 .collect();
930 eprintln!(
931 "{}: {}x{}, {} pictures (skipped {skip})",
932 path.to_string_lossy(),
933 w,
934 h,
935 sources.len()
936 );
937 (w, h, sources)
938}