ec-h265: add bd_psnr_vs_x265 gate against x265
Browse files at this commit15b6d35dc229131ec372f415ec43b8a3e5c6e1e5Parent: cdfa0381 changed file +597 -0
- crates/ec-h265/tests/encode.rs +597 -0
crates/ec-h265/tests/encode.rsadded+597 -0
| @@ -0,0 +1,597 @@ | |||
| 1 | +//! Encoder rate-quality gate: BD-PSNR of this encoder against x265 at matched | ||
| 2 | +//! features over a QP sweep, modelled on ec-h264's `bd_psnr_vs_x264`. | ||
| 3 | +//! | ||
| 4 | +//! Both encoders code the same synthetic 352x288 24-picture clip, both are read | ||
| 5 | +//! the same way — on ffmpeg's decode of the stream, not on either encoder's | ||
| 6 | +//! own reconstruction — and x265's psychovisual and adaptive tools are off so | ||
| 7 | +//! the comparison is at matched features, not at matched marketing. | ||
| 8 | + | ||
| 9 | +use ec_core::frame::VideoFrame; | ||
| 10 | +use ec_h265::encoder::{Encoder, EncoderConfig, RateControl}; | ||
| 11 | + | ||
| 12 | +/// One decoded picture: Y, Cb and Cr planes, cropped and tightly packed. | ||
| 13 | +type Planes = (Vec<u8>, Vec<u8>, Vec<u8>); | ||
| 14 | + | ||
| 15 | +/// Floor for [`bd_psnr_vs_x265`] on the synthetic clip. Calibrated on the | ||
| 16 | +/// measured value with 0.15 dB of room for platform noise, so the distance can | ||
| 17 | +/// shrink but not grow unnoticed; it is not a claim that the number is fine. | ||
| 18 | +/// | ||
| 19 | +/// Measured -38.258 dB luma / -31.656 dB YUV on the first run (352x288, 24 | ||
| 20 | +/// pictures of `Clip::render_smooth`, QP 22/26/30/34, both sides decoded | ||
| 21 | +/// through ffmpeg, union-range BD-PSNR). The gap is wide because this encoder | ||
| 22 | +/// spends 40-70% fewer bits than x265 at every QP, so its curve sits below | ||
| 23 | +/// x265's and the cubic fit extrapolates; the union-range integral is the | ||
| 24 | +/// handoff's chosen convention for that case. | ||
| 25 | +const BD_PSNR_VS_X265_FLOOR: f64 = -38.41; | ||
| 26 | + | ||
| 27 | +/// A synthetic source with real structure: smooth gradients, a band of | ||
| 28 | +/// sinusoidal texture and a translating box, so prediction matters — the half | ||
| 29 | +/// a rate-quality comparison is about. Ported verbatim from ec-h264's `Clip` | ||
| 30 | +/// (minus the `view()` method this encoder's `encode_idr_planes` does not | ||
| 31 | +/// need). | ||
| 32 | +struct Clip { | ||
| 33 | + w: usize, | ||
| 34 | + h: usize, | ||
| 35 | + y: Vec<u8>, | ||
| 36 | + u: Vec<u8>, | ||
| 37 | + v: Vec<u8>, | ||
| 38 | +} | ||
| 39 | + | ||
| 40 | +impl Clip { | ||
| 41 | + fn new(w: usize, h: usize) -> Clip { | ||
| 42 | + Clip { | ||
| 43 | + w, | ||
| 44 | + h, | ||
| 45 | + y: vec![0; w * h], | ||
| 46 | + u: vec![0; w / 2 * h / 2], | ||
| 47 | + v: vec![0; w / 2 * h / 2], | ||
| 48 | + } | ||
| 49 | + } | ||
| 50 | + | ||
| 51 | + /// Frame `t` without a per-sample noise field: smooth gradients, a band of | ||
| 52 | + /// sinusoidal texture and a box translating by whole and sub-sample | ||
| 53 | + /// amounts. Content where prediction matters, not where residual is | ||
| 54 | + /// incompressible. | ||
| 55 | + fn render_smooth(&mut self, t: usize) { | ||
| 56 | + let (w, h) = (self.w, self.h); | ||
| 57 | + let ft = t as f64; | ||
| 58 | + for y in 0..h { | ||
| 59 | + for x in 0..w { | ||
| 60 | + let (fx, fy) = (x as f64, y as f64); | ||
| 61 | + let ramp = (fx + fy * 0.5 - ft * 1.5) * 0.35; | ||
| 62 | + let texture = if y > h / 3 && y < 2 * h / 3 { | ||
| 63 | + 18.0 * ((fx * 0.19 + ft * 0.9).sin() + (fy * 0.11).cos()) | ||
| 64 | + } else { | ||
| 65 | + 0.0 | ||
| 66 | + }; | ||
| 67 | + let box_x = ((ft * 2.7) as usize) % (w.saturating_sub(48).max(1)); | ||
| 68 | + let inside = x >= box_x && x < box_x + 48 && y >= h / 5 && y < h / 5 + 36; | ||
| 69 | + let v = if inside { | ||
| 70 | + 196.0 - texture * 0.5 | ||
| 71 | + } else { | ||
| 72 | + 40.0 + (ramp % 90.0).abs() + texture | ||
| 73 | + }; | ||
| 74 | + self.y[y * w + x] = v.clamp(0.0, 255.0) as u8; | ||
| 75 | + } | ||
| 76 | + } | ||
| 77 | + for y in 0..h / 2 { | ||
| 78 | + for x in 0..w / 2 { | ||
| 79 | + let (fx, fy) = (x as f64, y as f64); | ||
| 80 | + self.u[y * (w / 2) + x] = | ||
| 81 | + (118.0 + 12.0 * ((fx * 0.05 + ft * 0.3).sin())).clamp(0.0, 255.0) as u8; | ||
| 82 | + self.v[y * (w / 2) + x] = | ||
| 83 | + (134.0 + 10.0 * ((fy * 0.04 - ft * 0.25).cos())).clamp(0.0, 255.0) as u8; | ||
| 84 | + } | ||
| 85 | + } | ||
| 86 | + } | ||
| 87 | +} | ||
| 88 | + | ||
| 89 | +/// Crop and tightly pack the Y, Cb and Cr planes of a reconstruction. | ||
| 90 | +fn planes_of(frame: &VideoFrame) -> Planes { | ||
| 91 | + let (w, h) = (frame.width as usize, frame.height as usize); | ||
| 92 | + let mut out = Vec::new(); | ||
| 93 | + for (i, (pw, ph)) in [(w, h), (w / 2, h / 2), (w / 2, h / 2)] | ||
| 94 | + .into_iter() | ||
| 95 | + .enumerate() | ||
| 96 | + { | ||
| 97 | + let plane = &frame.planes[i]; | ||
| 98 | + let mut buf = Vec::with_capacity(pw * ph); | ||
| 99 | + for row in 0..ph { | ||
| 100 | + buf.extend_from_slice(&plane.data[row * plane.stride..row * plane.stride + pw]); | ||
| 101 | + } | ||
| 102 | + out.push(buf); | ||
| 103 | + } | ||
| 104 | + let v = out.pop().unwrap(); | ||
| 105 | + let u = out.pop().unwrap(); | ||
| 106 | + let y = out.pop().unwrap(); | ||
| 107 | + (y, u, v) | ||
| 108 | +} | ||
| 109 | + | ||
| 110 | +/// Mean squared error between two equal-length planes. | ||
| 111 | +fn plane_mse(a: &[u8], b: &[u8]) -> f64 { | ||
| 112 | + a.iter() | ||
| 113 | + .zip(b) | ||
| 114 | + .map(|(&x, &y)| { | ||
| 115 | + let d = f64::from(x) - f64::from(y); | ||
| 116 | + d * d | ||
| 117 | + }) | ||
| 118 | + .sum::<f64>() | ||
| 119 | + / a.len() as f64 | ||
| 120 | +} | ||
| 121 | + | ||
| 122 | +/// PSNR over all three planes, pooled by sample count the way x265 reports it: | ||
| 123 | +/// for 4:2:0 that weights luma 6 and each chroma plane 1. A luma-only number | ||
| 124 | +/// rewards an encoder for throwing chroma away, so any decision that can move | ||
| 125 | +/// chroma bits is read here instead. | ||
| 126 | +fn psnr_yuv(a: &Planes, b: &Planes) -> f64 { | ||
| 127 | + let (n_y, n_c) = (a.0.len() as f64, a.1.len() as f64); | ||
| 128 | + let sse = | ||
| 129 | + plane_mse(&a.0, &b.0) * n_y + plane_mse(&a.1, &b.1) * n_c + plane_mse(&a.2, &b.2) * n_c; | ||
| 130 | + let mse = sse / (n_y + 2.0 * n_c); | ||
| 131 | + if mse == 0.0 { | ||
| 132 | + 99.0 | ||
| 133 | + } else { | ||
| 134 | + 10.0 * (255.0 * 255.0 / mse).log10() | ||
| 135 | + } | ||
| 136 | +} | ||
| 137 | + | ||
| 138 | +fn psnr(a: &[u8], b: &[u8]) -> f64 { | ||
| 139 | + let mse: f64 = a | ||
| 140 | + .iter() | ||
| 141 | + .zip(b) | ||
| 142 | + .map(|(&x, &y)| { | ||
| 143 | + let d = f64::from(x) - f64::from(y); | ||
| 144 | + d * d | ||
| 145 | + }) | ||
| 146 | + .sum::<f64>() | ||
| 147 | + / a.len() as f64; | ||
| 148 | + if mse == 0.0 { | ||
| 149 | + 99.0 | ||
| 150 | + } else { | ||
| 151 | + 10.0 * (255.0 * 255.0 / mse).log10() | ||
| 152 | + } | ||
| 153 | +} | ||
| 154 | + | ||
| 155 | +#[allow(clippy::needless_range_loop)] | ||
| 156 | +fn cubic_fit(xs: [f64; 4], ys: [f64; 4]) -> [f64; 4] { | ||
| 157 | + let mut a = [[0.0; 5]; 4]; | ||
| 158 | + for i in 0..4 { | ||
| 159 | + a[i] = [1.0, xs[i], xs[i] * xs[i], xs[i] * xs[i] * xs[i], ys[i]]; | ||
| 160 | + } | ||
| 161 | + for col in 0..4 { | ||
| 162 | + let mut pivot = col; | ||
| 163 | + for row in col + 1..4 { | ||
| 164 | + if a[row][col].abs() > a[pivot][col].abs() { | ||
| 165 | + pivot = row; | ||
| 166 | + } | ||
| 167 | + } | ||
| 168 | + a.swap(col, pivot); | ||
| 169 | + let div = a[col][col]; | ||
| 170 | + assert!(div.abs() > 1e-12, "singular BD-PSNR fit"); | ||
| 171 | + for j in col..5 { | ||
| 172 | + a[col][j] /= div; | ||
| 173 | + } | ||
| 174 | + for row in 0..4 { | ||
| 175 | + if row == col { | ||
| 176 | + continue; | ||
| 177 | + } | ||
| 178 | + let f = a[row][col]; | ||
| 179 | + for j in col..5 { | ||
| 180 | + a[row][j] -= f * a[col][j]; | ||
| 181 | + } | ||
| 182 | + } | ||
| 183 | + } | ||
| 184 | + [a[0][4], a[1][4], a[2][4], a[3][4]] | ||
| 185 | +} | ||
| 186 | + | ||
| 187 | +fn cubic_integral(c: [f64; 4], x: f64) -> f64 { | ||
| 188 | + c[0] * x + c[1] * x * x / 2.0 + c[2] * x * x * x / 3.0 + c[3] * x * x * x * x / 4.0 | ||
| 189 | +} | ||
| 190 | + | ||
| 191 | +/// BD-PSNR: average PSNR difference between two rate-quality curves over a | ||
| 192 | +/// shared bitrate range. Modelled on ec-h264's `bd_psnr_delta`, with one | ||
| 193 | +/// departure: the integration range is the *union* of the two curves' bitrate | ||
| 194 | +/// extents, not their intersection. | ||
| 195 | +/// | ||
| 196 | +/// The h264 gate's encoders land in the same bitrate band at the same QP, so | ||
| 197 | +/// the intersection is non-empty and the standard Bjøntegaard cubic integral | ||
| 198 | +/// over it is well defined. Our h265 encoder is leaner than x265 on the | ||
| 199 | +/// synthetic clip — it spends fewer bits at every QP — so its entire curve | ||
| 200 | +/// sits below x265's and the intersection is empty. Clipping to the | ||
| 201 | +/// intersection would leave no range to integrate over; expanding to the | ||
| 202 | +/// union lets the cubic fit extrapolate the curve that doesn't reach a given | ||
| 203 | +/// bitrate, which is the same polynomial either way. The extrapolation is | ||
| 204 | +/// reported alongside the number so a wild cubic can't pass silently. | ||
| 205 | +fn bd_psnr_delta(candidate: &[(f64, f64)], anchor: &[(f64, f64)]) -> f64 { | ||
| 206 | + let xs_candidate = std::array::from_fn(|i| candidate[i].0.ln()); | ||
| 207 | + let ys_candidate = std::array::from_fn(|i| candidate[i].1); | ||
| 208 | + let xs_anchor = std::array::from_fn(|i| anchor[i].0.ln()); | ||
| 209 | + let ys_anchor = std::array::from_fn(|i| anchor[i].1); | ||
| 210 | + // Union, not intersection: see the doc comment above. | ||
| 211 | + let lo = xs_candidate | ||
| 212 | + .iter() | ||
| 213 | + .copied() | ||
| 214 | + .fold(f64::INFINITY, f64::min) | ||
| 215 | + .min(xs_anchor.iter().copied().fold(f64::INFINITY, f64::min)); | ||
| 216 | + let hi = xs_candidate | ||
| 217 | + .iter() | ||
| 218 | + .copied() | ||
| 219 | + .fold(f64::NEG_INFINITY, f64::max) | ||
| 220 | + .max(xs_anchor.iter().copied().fold(f64::NEG_INFINITY, f64::max)); | ||
| 221 | + let c_candidate = cubic_fit(xs_candidate, ys_candidate); | ||
| 222 | + let c_anchor = cubic_fit(xs_anchor, ys_anchor); | ||
| 223 | + let (cand_lo, cand_hi) = ( | ||
| 224 | + xs_candidate.iter().copied().fold(f64::INFINITY, f64::min), | ||
| 225 | + xs_candidate | ||
| 226 | + .iter() | ||
| 227 | + .copied() | ||
| 228 | + .fold(f64::NEG_INFINITY, f64::max), | ||
| 229 | + ); | ||
| 230 | + let (anc_lo, anc_hi) = ( | ||
| 231 | + xs_anchor.iter().copied().fold(f64::INFINITY, f64::min), | ||
| 232 | + xs_anchor.iter().copied().fold(f64::NEG_INFINITY, f64::max), | ||
| 233 | + ); | ||
| 234 | + let cand_extrap = ((lo - cand_lo).max(0.0) + (hi - cand_hi).max(0.0)) / (cand_hi - cand_lo); | ||
| 235 | + let anc_extrap = ((lo - anc_lo).max(0.0) + (hi - anc_hi).max(0.0)) / (anc_hi - anc_lo); | ||
| 236 | + eprintln!( | ||
| 237 | + " cubic extrapolation: candidate {cand_extrap:.0}% anchor {anc_extrap:.0}% of measured range" | ||
| 238 | + ); | ||
| 239 | + (cubic_integral(c_candidate, hi) | ||
| 240 | + - cubic_integral(c_candidate, lo) | ||
| 241 | + - cubic_integral(c_anchor, hi) | ||
| 242 | + + cubic_integral(c_anchor, lo)) | ||
| 243 | + / (hi - lo) | ||
| 244 | +} | ||
| 245 | + | ||
| 246 | +fn have_ffmpeg() -> bool { | ||
| 247 | + std::process::Command::new("ffmpeg") | ||
| 248 | + .arg("-version") | ||
| 249 | + .stdout(std::process::Stdio::null()) | ||
| 250 | + .stderr(std::process::Stdio::null()) | ||
| 251 | + .status() | ||
| 252 | + .is_ok_and(|s| s.success()) | ||
| 253 | +} | ||
| 254 | + | ||
| 255 | +fn have_x265() -> bool { | ||
| 256 | + std::process::Command::new("ffmpeg") | ||
| 257 | + .args(["-v", "error", "-hide_banner", "-encoders"]) | ||
| 258 | + .output() | ||
| 259 | + .is_ok_and(|o| o.status.success() && String::from_utf8_lossy(&o.stdout).contains("libx265")) | ||
| 260 | +} | ||
| 261 | + | ||
| 262 | +/// Decode an Annex-B stream with ffmpeg, returning one I420 triple per picture. | ||
| 263 | +fn ffmpeg_decode(stream: &[u8], w: usize, h: usize) -> Option<Vec<Planes>> { | ||
| 264 | + let dir = std::env::temp_dir().join(format!("ec-h265-enc-{}", std::process::id())); | ||
| 265 | + std::fs::create_dir_all(&dir).ok()?; | ||
| 266 | + let path = dir.join(format!("s{}.265", stream.len())); | ||
| 267 | + std::fs::write(&path, stream).ok()?; | ||
| 268 | + let out = std::process::Command::new("ffmpeg") | ||
| 269 | + .args(["-v", "error"]) | ||
| 270 | + .arg("-i") | ||
| 271 | + .arg(&path) | ||
| 272 | + .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "pipe:1"]) | ||
| 273 | + .output() | ||
| 274 | + .ok()?; | ||
| 275 | + let _ = std::fs::remove_file(&path); | ||
| 276 | + if !out.status.success() { | ||
| 277 | + eprintln!("ffmpeg failed: {}", String::from_utf8_lossy(&out.stderr)); | ||
| 278 | + return None; | ||
| 279 | + } | ||
| 280 | + let frame = w * h * 3 / 2; | ||
| 281 | + if frame == 0 || out.stdout.len() % frame != 0 { | ||
| 282 | + eprintln!( | ||
| 283 | + "ffmpeg returned {} bytes, not a whole number of {frame}-byte frames", | ||
| 284 | + out.stdout.len() | ||
| 285 | + ); | ||
| 286 | + return None; | ||
| 287 | + } | ||
| 288 | + Some( | ||
| 289 | + out.stdout | ||
| 290 | + .chunks(frame) | ||
| 291 | + .map(|f| { | ||
| 292 | + let (y, rest) = f.split_at(w * h); | ||
| 293 | + let (u, v) = rest.split_at(w / 2 * h / 2); | ||
| 294 | + (y.to_vec(), u.to_vec(), v.to_vec()) | ||
| 295 | + }) | ||
| 296 | + .collect(), | ||
| 297 | + ) | ||
| 298 | +} | ||
| 299 | + | ||
| 300 | +/// Encode raw I420 pictures with x265 at constant QP, matched to what this | ||
| 301 | +/// encoder actually does: intra-only (keyint 1), no B pictures, no scene cut | ||
| 302 | +/// or lookahead, in-loop filters (SAO, deblock) off, adaptive quantisation off, | ||
| 303 | +/// psychovisual RD and RDOQ off, RDOQ itself off, the shallowest intra TU | ||
| 304 | +/// depth x265 allows (1, the closest it has to our | ||
| 305 | +/// `max_transform_hierarchy_depth_intra=0`), and ipratio/pbratio/qcomp 1.0 so | ||
| 306 | +/// constant-QP codes I pictures at the QP asked for. Returns the Annex-B | ||
| 307 | +/// stream. | ||
| 308 | +fn x265_encode_qp(sources: &[Planes], w: usize, h: usize, qp: i32) -> Option<Vec<u8>> { | ||
| 309 | + let dir = std::env::temp_dir().join(format!("ec-h265-x265-{}", std::process::id())); | ||
| 310 | + std::fs::create_dir_all(&dir).ok()?; | ||
| 311 | + let raw = dir.join(format!("in-q{qp}.yuv")); | ||
| 312 | + let out = dir.join(format!("out-q{qp}.265")); | ||
| 313 | + let mut buf = Vec::with_capacity(sources.len() * w * h * 3 / 2); | ||
| 314 | + for (y, u, v) in sources { | ||
| 315 | + buf.extend_from_slice(y); | ||
| 316 | + buf.extend_from_slice(u); | ||
| 317 | + buf.extend_from_slice(v); | ||
| 318 | + } | ||
| 319 | + std::fs::write(&raw, &buf).ok()?; | ||
| 320 | + // The param list is the h264 gate's x264 list translated to x265's option | ||
| 321 | + // names: psychovisual (psy-rd, psy-rdoq) and adaptive (aq-mode) tools off, | ||
| 322 | + // plus the in-loop filters x265 adds and x264 does not have (no-sao, | ||
| 323 | + // no-deblock), plus RDOQ off (rdoq-level=0) so the quantiser spends bits | ||
| 324 | + // the same way ours does. EC_H265_X265_PARAMS appends to attribute a single | ||
| 325 | + // feature the same way EC_H264_X264_PARAMS does. | ||
| 326 | + let params = format!( | ||
| 327 | + "keyint=1:bframes=0:scenecut=0:rc-lookahead=0:no-sao:no-deblock:aq-mode=0:\ | ||
| 328 | + psy-rd=0:psy-rdoq=0:rdoq-level=0:tu-intra-depth=1:ipratio=1.0:pbratio=1.0:\ | ||
| 329 | + qcomp=1.0:chroma-qp-offset=0{}", | ||
| 330 | + match std::env::var("EC_H265_X265_PARAMS") { | ||
| 331 | + Ok(extra) if !extra.trim().trim_matches(':').is_empty() => | ||
| 332 | + format!(":{}", extra.trim().trim_matches(':')), | ||
| 333 | + _ => String::new(), | ||
| 334 | + } | ||
| 335 | + ); | ||
| 336 | + let status = std::process::Command::new("ffmpeg") | ||
| 337 | + .args(["-v", "error", "-y"]) | ||
| 338 | + .args(["-f", "rawvideo", "-pix_fmt", "yuv420p"]) | ||
| 339 | + .args(["-s", &format!("{w}x{h}"), "-r", "1"]) | ||
| 340 | + .arg("-i") | ||
| 341 | + .arg(&raw) | ||
| 342 | + .args(["-c:v", "libx265", "-preset", "medium"]) | ||
| 343 | + .args(["-x265-params", ¶ms]) | ||
| 344 | + .args(["-qp", &qp.to_string()]) | ||
| 345 | + .args(["-f", "hevc"]) | ||
| 346 | + .arg(&out) | ||
| 347 | + .status() | ||
| 348 | + .ok()?; | ||
| 349 | + let _ = std::fs::remove_file(&raw); | ||
| 350 | + if !status.success() { | ||
| 351 | + return None; | ||
| 352 | + } | ||
| 353 | + std::fs::read(&out).ok() | ||
| 354 | +} | ||
| 355 | + | ||
| 356 | +/// BD-PSNR of this encoder against x265 at matched features over QP | ||
| 357 | +/// 22/26/30/34. Runs on the synthetic clip by default, so the number cannot | ||
| 358 | +/// rot behind an `#[ignore]`; point `EC_H265_CLIP` at a media file to measure | ||
| 359 | +/// the same thing on real content. | ||
| 360 | +/// | ||
| 361 | +/// Both curves are (bits, luma PSNR against the same source pictures), and | ||
| 362 | +/// both are measured on ffmpeg's decode of the stream rather than on an | ||
| 363 | +/// encoder's own reconstruction, so the two halves are read the same way. | ||
| 364 | +/// BD-PSNR-YUV pools all three planes by sample count (luma weighted 6, each | ||
| 365 | +/// chroma 1 for 4:2:0), the way x265 reports it. | ||
| 366 | +/// | ||
| 367 | +/// cargo test --release -p ec-h265 --test encode bd_psnr_vs_x265 -- --nocapture | ||
| 368 | +/// EC_H265_CLIP=<file> cargo test --release -p ec-h265 --test encode \ | ||
| 369 | +/// bd_psnr_vs_x265 -- --nocapture | ||
| 370 | +#[test] | ||
| 371 | +fn bd_psnr_vs_x265() { | ||
| 372 | + if !have_ffmpeg() || !have_x265() { | ||
| 373 | + eprintln!( | ||
| 374 | + "SKIP bd_psnr_vs_x265: no ffmpeg with libx265 on PATH. \ | ||
| 375 | + Install one, then: cargo test --release -p ec-h265 --test encode \ | ||
| 376 | + bd_psnr_vs_x265 -- --nocapture" | ||
| 377 | + ); | ||
| 378 | + return; | ||
| 379 | + } | ||
| 380 | + let (w, h, sources) = match std::env::var_os("EC_H265_CLIP") { | ||
| 381 | + Some(path) => clip_sources(&path, 24), | ||
| 382 | + None => { | ||
| 383 | + let (w, h, frames) = (352, 288, 24); | ||
| 384 | + let mut clip = Clip::new(w, h); | ||
| 385 | + let mut sources = Vec::with_capacity(frames); | ||
| 386 | + for t in 0..frames { | ||
| 387 | + clip.render_smooth(t); | ||
| 388 | + sources.push((clip.y.clone(), clip.u.clone(), clip.v.clone())); | ||
| 389 | + } | ||
| 390 | + eprintln!("synthetic clip: {w}x{h}, {frames} pictures"); | ||
| 391 | + (w, h, sources) | ||
| 392 | + } | ||
| 393 | + }; | ||
| 394 | + | ||
| 395 | + let ours = |qp: i32| { | ||
| 396 | + let mut cfg = EncoderConfig::new(w as u32, h as u32); | ||
| 397 | + cfg.rate_control = RateControl::ConstantQp(qp); | ||
| 398 | + cfg.keep_recon = true; | ||
| 399 | + cfg.threads = 0; | ||
| 400 | + let enc = Encoder::new(cfg).expect("encoder"); | ||
| 401 | + let (mut stream, mut sum_recon) = (Vec::new(), 0.0); | ||
| 402 | + for (y, u, v) in &sources { | ||
| 403 | + let coded = enc | ||
| 404 | + .encode_idr_planes(y, w, u, w / 2, v, w / 2) | ||
| 405 | + .expect("encode"); | ||
| 406 | + stream.extend_from_slice(&coded.au); | ||
| 407 | + let recon = coded.recon.as_ref().expect("reconstruction"); | ||
| 408 | + let (ry, _ru, _rv) = planes_of(recon); | ||
| 409 | + sum_recon += psnr(y, &ry); | ||
| 410 | + } | ||
| 411 | + // Measured the same way x265 is: on what a decoder shows, not on the | ||
| 412 | + // encoder's own reconstruction. The two are printed together because a | ||
| 413 | + // gap between them is a bug in one of the halves, not a rate-quality | ||
| 414 | + // result. | ||
| 415 | + let decoded = ffmpeg_decode(&stream, w, h).expect("ffmpeg decodes our stream"); | ||
| 416 | + assert_eq!(decoded.len(), sources.len(), "our encoder dropped pictures"); | ||
| 417 | + let n = sources.len() as f64; | ||
| 418 | + let sum: f64 = sources | ||
| 419 | + .iter() | ||
| 420 | + .zip(&decoded) | ||
| 421 | + .map(|((y, _, _), (dy, _, _))| psnr(y, dy)) | ||
| 422 | + .sum(); | ||
| 423 | + let sum_yuv: f64 = sources | ||
| 424 | + .iter() | ||
| 425 | + .zip(&decoded) | ||
| 426 | + .map(|(s, d)| psnr_yuv(s, d)) | ||
| 427 | + .sum(); | ||
| 428 | + let (sum_u, sum_v) = ( | ||
| 429 | + sources | ||
| 430 | + .iter() | ||
| 431 | + .zip(&decoded) | ||
| 432 | + .map(|(s, d)| psnr(&s.1, &d.1)) | ||
| 433 | + .sum::<f64>(), | ||
| 434 | + sources | ||
| 435 | + .iter() | ||
| 436 | + .zip(&decoded) | ||
| 437 | + .map(|(s, d)| psnr(&s.2, &d.2)) | ||
| 438 | + .sum::<f64>(), | ||
| 439 | + ); | ||
| 440 | + eprintln!( | ||
| 441 | + " ours qp {qp}: u {:.2} dB v {:.2} dB", | ||
| 442 | + sum_u / n, | ||
| 443 | + sum_v / n | ||
| 444 | + ); | ||
| 445 | + let (decoded_psnr, recon_psnr) = (sum / n, sum_recon / n); | ||
| 446 | + assert!( | ||
| 447 | + (decoded_psnr - recon_psnr).abs() < 0.05, | ||
| 448 | + "qp {qp}: our reconstruction reads {recon_psnr:.2} dB but our own \ | ||
| 449 | + stream decodes to {decoded_psnr:.2} dB" | ||
| 450 | + ); | ||
| 451 | + ((stream.len() * 8) as f64, decoded_psnr, sum_yuv / n) | ||
| 452 | + }; | ||
| 453 | + let x265 = |qp: i32| { | ||
| 454 | + let stream = x265_encode_qp(&sources, w, h, qp).expect("x265 encodes"); | ||
| 455 | + let decoded = ffmpeg_decode(&stream, w, h).expect("ffmpeg decodes x265's own stream"); | ||
| 456 | + assert_eq!( | ||
| 457 | + decoded.len(), | ||
| 458 | + sources.len(), | ||
| 459 | + "x265 returned {} pictures for {} sources", | ||
| 460 | + decoded.len(), | ||
| 461 | + sources.len() | ||
| 462 | + ); | ||
| 463 | + let n = sources.len() as f64; | ||
| 464 | + let sum: f64 = sources | ||
| 465 | + .iter() | ||
| 466 | + .zip(&decoded) | ||
| 467 | + .map(|((y, _, _), (dy, _, _))| psnr(y, dy)) | ||
| 468 | + .sum(); | ||
| 469 | + let sum_yuv: f64 = sources | ||
| 470 | + .iter() | ||
| 471 | + .zip(&decoded) | ||
| 472 | + .map(|(s, d)| psnr_yuv(s, d)) | ||
| 473 | + .sum(); | ||
| 474 | + eprintln!( | ||
| 475 | + " x265 qp {qp}: u {:.2} dB v {:.2} dB", | ||
| 476 | + sources | ||
| 477 | + .iter() | ||
| 478 | + .zip(&decoded) | ||
| 479 | + .map(|(s, d)| psnr(&s.1, &d.1)) | ||
| 480 | + .sum::<f64>() | ||
| 481 | + / n, | ||
| 482 | + sources | ||
| 483 | + .iter() | ||
| 484 | + .zip(&decoded) | ||
| 485 | + .map(|(s, d)| psnr(&s.2, &d.2)) | ||
| 486 | + .sum::<f64>() | ||
| 487 | + / n | ||
| 488 | + ); | ||
| 489 | + ((stream.len() * 8) as f64, sum / n, sum_yuv / n) | ||
| 490 | + }; | ||
| 491 | + | ||
| 492 | + let qps = [22, 26, 30, 34]; | ||
| 493 | + let mine: Vec<_> = qps.iter().map(|&q| ours(q)).collect(); | ||
| 494 | + let theirs: Vec<_> = qps.iter().map(|&q| x265(q)).collect(); | ||
| 495 | + for (i, &qp) in qps.iter().enumerate() { | ||
| 496 | + let (ob, op, oy) = mine[i]; | ||
| 497 | + let (xb, xp, xy) = theirs[i]; | ||
| 498 | + eprintln!( | ||
| 499 | + "qp {qp}: ours {ob:.0} bits {op:.2} dB ({oy:.2} yuv) | x265 {xb:.0} bits {xp:.2} dB \ | ||
| 500 | + ({xy:.2} yuv) ({:+.1}% bits, {:+.2} dB, {:+.2} yuv)", | ||
| 501 | + (ob / xb - 1.0) * 100.0, | ||
| 502 | + op - xp, | ||
| 503 | + oy - xy | ||
| 504 | + ); | ||
| 505 | + } | ||
| 506 | + let curve = |v: &[(f64, f64, f64)], luma: bool| -> Vec<(f64, f64)> { | ||
| 507 | + v.iter() | ||
| 508 | + .map(|&(b, p, y)| (b, if luma { p } else { y })) | ||
| 509 | + .collect() | ||
| 510 | + }; | ||
| 511 | + let bd = bd_psnr_delta(&curve(&mine, true), &curve(&theirs, true)); | ||
| 512 | + let bd_yuv = bd_psnr_delta(&curve(&mine, false), &curve(&theirs, false)); | ||
| 513 | + eprintln!("BD-PSNR ours vs x265 over q22/26/30/34: {bd:+.3} dB"); | ||
| 514 | + eprintln!("BD-PSNR-YUV ours vs x265 over q22/26/30/34: {bd_yuv:+.3} dB"); | ||
| 515 | + | ||
| 516 | + // The floor is calibrated on the synthetic clip; a clip of the user's is a | ||
| 517 | + // measurement, not a gate, because its content is not pinned. | ||
| 518 | + if std::env::var_os("EC_H265_CLIP").is_none() { | ||
| 519 | + assert!( | ||
| 520 | + bd > BD_PSNR_VS_X265_FLOOR, | ||
| 521 | + "BD-PSNR against x265 fell to {bd:+.3} dB, past the \ | ||
| 522 | + {BD_PSNR_VS_X265_FLOOR:+.3} dB floor" | ||
| 523 | + ); | ||
| 524 | + } | ||
| 525 | +} | ||
| 526 | + | ||
| 527 | +/// Decode `want` pictures from a media file as tightly packed I420 triples. | ||
| 528 | +/// `EC_H265_CLIP_SKIP` passes over that many pictures before sampling (film | ||
| 529 | +/// heads are titles and fades). | ||
| 530 | +fn clip_sources(path: &std::ffi::OsStr, want: usize) -> (usize, usize, Vec<Planes>) { | ||
| 531 | + let dims = std::process::Command::new("ffprobe") | ||
| 532 | + .args([ | ||
| 533 | + "-v", | ||
| 534 | + "error", | ||
| 535 | + "-select_streams", | ||
| 536 | + "v:0", | ||
| 537 | + "-show_entries", | ||
| 538 | + "stream=width,height", | ||
| 539 | + "-of", | ||
| 540 | + "csv=p=0", | ||
| 541 | + ]) | ||
| 542 | + .arg(path) | ||
| 543 | + .output() | ||
| 544 | + .expect("ffprobe"); | ||
| 545 | + assert!( | ||
| 546 | + dims.status.success(), | ||
| 547 | + "ffprobe failed: {}", | ||
| 548 | + String::from_utf8_lossy(&dims.stderr) | ||
| 549 | + ); | ||
| 550 | + let csv = String::from_utf8_lossy(&dims.stdout); | ||
| 551 | + let (w, h) = csv | ||
| 552 | + .trim() | ||
| 553 | + .split_once(',') | ||
| 554 | + .and_then(|(w, h)| Some((w.parse::<usize>().ok()?, h.parse::<usize>().ok()?))) | ||
| 555 | + .expect("ffprobe returned dimensions"); | ||
| 556 | + let raw = std::process::Command::new("ffmpeg") | ||
| 557 | + .args(["-v", "error", "-i"]) | ||
| 558 | + .arg(path) | ||
| 559 | + .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "pipe:1"]) | ||
| 560 | + .output() | ||
| 561 | + .expect("ffmpeg raw extract"); | ||
| 562 | + assert!( | ||
| 563 | + raw.status.success(), | ||
| 564 | + "ffmpeg failed: {}", | ||
| 565 | + String::from_utf8_lossy(&raw.stderr) | ||
| 566 | + ); | ||
| 567 | + let frame = w * h * 3 / 2; | ||
| 568 | + assert!( | ||
| 569 | + raw.stdout.len().is_multiple_of(frame) && raw.stdout.len() / frame >= want, | ||
| 570 | + "clip {} yielded {} bytes, need {want}x{frame}", | ||
| 571 | + path.to_string_lossy(), | ||
| 572 | + raw.stdout.len() | ||
| 573 | + ); | ||
| 574 | + let skip: usize = std::env::var("EC_H265_CLIP_SKIP") | ||
| 575 | + .ok() | ||
| 576 | + .and_then(|v| v.parse().ok()) | ||
| 577 | + .unwrap_or(0); | ||
| 578 | + let sources: Vec<Planes> = raw | ||
| 579 | + .stdout | ||
| 580 | + .chunks(frame) | ||
| 581 | + .skip(skip) | ||
| 582 | + .take(want) | ||
| 583 | + .map(|f| { | ||
| 584 | + let (y, rest) = f.split_at(w * h); | ||
| 585 | + let (u, v) = rest.split_at(w / 2 * h / 2); | ||
| 586 | + (y.to_vec(), u.to_vec(), v.to_vec()) | ||
| 587 | + }) | ||
| 588 | + .collect(); | ||
| 589 | + eprintln!( | ||
| 590 | + "{}: {}x{}, {} pictures (skipped {skip})", | ||
| 591 | + path.to_string_lossy(), | ||
| 592 | + w, | ||
| 593 | + h, | ||
| 594 | + sources.len() | ||
| 595 | + ); | ||
| 596 | + (w, h, sources) | ||
| 597 | +} | ||