| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | use ec_core::frame::VideoFrame; |
| 10 | use ec_h265::encoder::{Encoder, EncoderConfig, RateControl, TransformSkip}; |
| 11 | |
| 12 | |
| 13 | type Planes = (Vec<u8>, Vec<u8>, Vec<u8>); |
| 14 | |
| 15 | |
| 16 | |
| 17 | |
| 18 | |
| 19 | |
| 20 | |
| 21 | |
| 22 | |
| 23 | |
| 24 | |
| 25 | |
| 26 | |
| 27 | |
| 28 | |
| 29 | |
| 30 | |
| 31 | |
| 32 | |
| 33 | |
| 34 | |
| 35 | |
| 36 | |
| 37 | |
| 38 | |
| 39 | |
| 40 | |
| 41 | const BD_PSNR_VS_X265_FLOOR: f64 = 2.357; |
| 42 | |
| 43 | |
| 44 | |
| 45 | |
| 46 | |
| 47 | |
| 48 | struct Clip { |
| 49 | w: usize, |
| 50 | h: usize, |
| 51 | y: Vec<u8>, |
| 52 | u: Vec<u8>, |
| 53 | v: Vec<u8>, |
| 54 | } |
| 55 | |
| 56 | impl Clip { |
| 57 | fn new(w: usize, h: usize) -> Clip { |
| 58 | Clip { |
| 59 | w, |
| 60 | h, |
| 61 | y: vec![0; w * h], |
| 62 | u: vec![0; w / 2 * h / 2], |
| 63 | v: vec![0; w / 2 * h / 2], |
| 64 | } |
| 65 | } |
| 66 | |
| 67 | |
| 68 | |
| 69 | |
| 70 | |
| 71 | fn render_smooth(&mut self, t: usize) { |
| 72 | let (w, h) = (self.w, self.h); |
| 73 | let ft = t as f64; |
| 74 | for y in 0..h { |
| 75 | for x in 0..w { |
| 76 | let (fx, fy) = (x as f64, y as f64); |
| 77 | let ramp = (fx + fy * 0.5 - ft * 1.5) * 0.35; |
| 78 | let texture = if y > h / 3 && y < 2 * h / 3 { |
| 79 | 18.0 * ((fx * 0.19 + ft * 0.9).sin() + (fy * 0.11).cos()) |
| 80 | } else { |
| 81 | 0.0 |
| 82 | }; |
| 83 | let box_x = ((ft * 2.7) as usize) % (w.saturating_sub(48).max(1)); |
| 84 | let inside = x >= box_x && x < box_x + 48 && y >= h / 5 && y < h / 5 + 36; |
| 85 | let v = if inside { |
| 86 | 196.0 - texture * 0.5 |
| 87 | } else { |
| 88 | 40.0 + (ramp % 90.0).abs() + texture |
| 89 | }; |
| 90 | self.y[y * w + x] = v.clamp(0.0, 255.0) as u8; |
| 91 | } |
| 92 | } |
| 93 | for y in 0..h / 2 { |
| 94 | for x in 0..w / 2 { |
| 95 | let (fx, fy) = (x as f64, y as f64); |
| 96 | self.u[y * (w / 2) + x] = |
| 97 | (118.0 + 12.0 * ((fx * 0.05 + ft * 0.3).sin())).clamp(0.0, 255.0) as u8; |
| 98 | self.v[y * (w / 2) + x] = |
| 99 | (134.0 + 10.0 * ((fy * 0.04 - ft * 0.25).cos())).clamp(0.0, 255.0) as u8; |
| 100 | } |
| 101 | } |
| 102 | } |
| 103 | } |
| 104 | |
| 105 | |
| 106 | fn planes_of(frame: &VideoFrame) -> Planes { |
| 107 | let (w, h) = (frame.width as usize, frame.height as usize); |
| 108 | let mut out = Vec::new(); |
| 109 | for (i, (pw, ph)) in [(w, h), (w / 2, h / 2), (w / 2, h / 2)] |
| 110 | .into_iter() |
| 111 | .enumerate() |
| 112 | { |
| 113 | let plane = &frame.planes[i]; |
| 114 | let mut buf = Vec::with_capacity(pw * ph); |
| 115 | for row in 0..ph { |
| 116 | buf.extend_from_slice(&plane.data[row * plane.stride..row * plane.stride + pw]); |
| 117 | } |
| 118 | out.push(buf); |
| 119 | } |
| 120 | let v = out.pop().unwrap(); |
| 121 | let u = out.pop().unwrap(); |
| 122 | let y = out.pop().unwrap(); |
| 123 | (y, u, v) |
| 124 | } |
| 125 | |
| 126 | |
| 127 | fn plane_mse(a: &[u8], b: &[u8]) -> f64 { |
| 128 | a.iter() |
| 129 | .zip(b) |
| 130 | .map(|(&x, &y)| { |
| 131 | let d = f64::from(x) - f64::from(y); |
| 132 | d * d |
| 133 | }) |
| 134 | .sum::<f64>() |
| 135 | / a.len() as f64 |
| 136 | } |
| 137 | |
| 138 | |
| 139 | |
| 140 | |
| 141 | |
| 142 | fn psnr_yuv(a: &Planes, b: &Planes) -> f64 { |
| 143 | let (n_y, n_c) = (a.0.len() as f64, a.1.len() as f64); |
| 144 | let sse = |
| 145 | plane_mse(&a.0, &b.0) * n_y + plane_mse(&a.1, &b.1) * n_c + plane_mse(&a.2, &b.2) * n_c; |
| 146 | let mse = sse / (n_y + 2.0 * n_c); |
| 147 | if mse == 0.0 { |
| 148 | 99.0 |
| 149 | } else { |
| 150 | 10.0 * (255.0 * 255.0 / mse).log10() |
| 151 | } |
| 152 | } |
| 153 | |
| 154 | fn psnr(a: &[u8], b: &[u8]) -> f64 { |
| 155 | let mse: f64 = a |
| 156 | .iter() |
| 157 | .zip(b) |
| 158 | .map(|(&x, &y)| { |
| 159 | let d = f64::from(x) - f64::from(y); |
| 160 | d * d |
| 161 | }) |
| 162 | .sum::<f64>() |
| 163 | / a.len() as f64; |
| 164 | if mse == 0.0 { |
| 165 | 99.0 |
| 166 | } else { |
| 167 | 10.0 * (255.0 * 255.0 / mse).log10() |
| 168 | } |
| 169 | } |
| 170 | |
| 171 | #[allow(clippy::needless_range_loop)] |
| 172 | fn cubic_fit(xs: [f64; 4], ys: [f64; 4]) -> [f64; 4] { |
| 173 | let mut a = [[0.0; 5]; 4]; |
| 174 | for i in 0..4 { |
| 175 | a[i] = [1.0, xs[i], xs[i] * xs[i], xs[i] * xs[i] * xs[i], ys[i]]; |
| 176 | } |
| 177 | for col in 0..4 { |
| 178 | let mut pivot = col; |
| 179 | for row in col + 1..4 { |
| 180 | if a[row][col].abs() > a[pivot][col].abs() { |
| 181 | pivot = row; |
| 182 | } |
| 183 | } |
| 184 | a.swap(col, pivot); |
| 185 | let div = a[col][col]; |
| 186 | assert!(div.abs() > 1e-12, "singular BD-PSNR fit"); |
| 187 | for j in col..5 { |
| 188 | a[col][j] /= div; |
| 189 | } |
| 190 | for row in 0..4 { |
| 191 | if row == col { |
| 192 | continue; |
| 193 | } |
| 194 | let f = a[row][col]; |
| 195 | for j in col..5 { |
| 196 | a[row][j] -= f * a[col][j]; |
| 197 | } |
| 198 | } |
| 199 | } |
| 200 | [a[0][4], a[1][4], a[2][4], a[3][4]] |
| 201 | } |
| 202 | |
| 203 | fn cubic_integral(c: [f64; 4], x: f64) -> f64 { |
| 204 | c[0] * x + c[1] * x * x / 2.0 + c[2] * x * x * x / 3.0 + c[3] * x * x * x * x / 4.0 |
| 205 | } |
| 206 | |
| 207 | |
| 208 | |
| 209 | |
| 210 | |
| 211 | |
| 212 | |
| 213 | |
| 214 | |
| 215 | |
| 216 | |
| 217 | |
| 218 | |
| 219 | |
| 220 | |
| 221 | |
| 222 | |
| 223 | |
| 224 | |
| 225 | |
| 226 | fn bd_psnr_delta(candidate: &[(f64, f64)], anchor: &[(f64, f64)]) -> (f64, f64, f64) { |
| 227 | let xs_candidate = std::array::from_fn(|i| candidate[i].0.ln()); |
| 228 | let ys_candidate = std::array::from_fn(|i| candidate[i].1); |
| 229 | let xs_anchor = std::array::from_fn(|i| anchor[i].0.ln()); |
| 230 | let ys_anchor = std::array::from_fn(|i| anchor[i].1); |
| 231 | |
| 232 | let lo = xs_candidate |
| 233 | .iter() |
| 234 | .copied() |
| 235 | .fold(f64::INFINITY, f64::min) |
| 236 | .min(xs_anchor.iter().copied().fold(f64::INFINITY, f64::min)); |
| 237 | let hi = xs_candidate |
| 238 | .iter() |
| 239 | .copied() |
| 240 | .fold(f64::NEG_INFINITY, f64::max) |
| 241 | .max(xs_anchor.iter().copied().fold(f64::NEG_INFINITY, f64::max)); |
| 242 | let c_candidate = cubic_fit(xs_candidate, ys_candidate); |
| 243 | let c_anchor = cubic_fit(xs_anchor, ys_anchor); |
| 244 | let (cand_lo, cand_hi) = ( |
| 245 | xs_candidate.iter().copied().fold(f64::INFINITY, f64::min), |
| 246 | xs_candidate |
| 247 | .iter() |
| 248 | .copied() |
| 249 | .fold(f64::NEG_INFINITY, f64::max), |
| 250 | ); |
| 251 | let (anc_lo, anc_hi) = ( |
| 252 | xs_anchor.iter().copied().fold(f64::INFINITY, f64::min), |
| 253 | xs_anchor.iter().copied().fold(f64::NEG_INFINITY, f64::max), |
| 254 | ); |
| 255 | let cand_extrap = ((lo - cand_lo).max(0.0) + (hi - cand_hi).max(0.0)) / (cand_hi - cand_lo); |
| 256 | let anc_extrap = ((lo - anc_lo).max(0.0) + (hi - anc_hi).max(0.0)) / (anc_hi - anc_lo); |
| 257 | eprintln!( |
| 258 | " cubic extrapolation: candidate {cand_extrap:.0}% anchor {anc_extrap:.0}% of measured range" |
| 259 | ); |
| 260 | let bd = (cubic_integral(c_candidate, hi) |
| 261 | - cubic_integral(c_candidate, lo) |
| 262 | - cubic_integral(c_anchor, hi) |
| 263 | + cubic_integral(c_anchor, lo)) |
| 264 | / (hi - lo); |
| 265 | (bd, cand_extrap, anc_extrap) |
| 266 | } |
| 267 | |
| 268 | fn have_ffmpeg() -> bool { |
| 269 | std::process::Command::new("ffmpeg") |
| 270 | .arg("-version") |
| 271 | .stdout(std::process::Stdio::null()) |
| 272 | .stderr(std::process::Stdio::null()) |
| 273 | .status() |
| 274 | .is_ok_and(|s| s.success()) |
| 275 | } |
| 276 | |
| 277 | fn have_x265() -> bool { |
| 278 | std::process::Command::new("ffmpeg") |
| 279 | .args(["-v", "error", "-hide_banner", "-encoders"]) |
| 280 | .output() |
| 281 | .is_ok_and(|o| o.status.success() && String::from_utf8_lossy(&o.stdout).contains("libx265")) |
| 282 | } |
| 283 | |
| 284 | |
| 285 | fn ffmpeg_decode(stream: &[u8], w: usize, h: usize) -> Option<Vec<Planes>> { |
| 286 | let dir = std::env::temp_dir().join(format!("ec-h265-enc-{}", std::process::id())); |
| 287 | std::fs::create_dir_all(&dir).ok()?; |
| 288 | let path = dir.join(format!("s{}.265", stream.len())); |
| 289 | std::fs::write(&path, stream).ok()?; |
| 290 | let out = std::process::Command::new("ffmpeg") |
| 291 | .args(["-v", "error"]) |
| 292 | .arg("-i") |
| 293 | .arg(&path) |
| 294 | .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "pipe:1"]) |
| 295 | .output() |
| 296 | .ok()?; |
| 297 | let _ = std::fs::remove_file(&path); |
| 298 | if !out.status.success() { |
| 299 | eprintln!("ffmpeg failed: {}", String::from_utf8_lossy(&out.stderr)); |
| 300 | return None; |
| 301 | } |
| 302 | let frame = w * h * 3 / 2; |
| 303 | if frame == 0 || out.stdout.len() % frame != 0 { |
| 304 | eprintln!( |
| 305 | "ffmpeg returned {} bytes, not a whole number of {frame}-byte frames", |
| 306 | out.stdout.len() |
| 307 | ); |
| 308 | return None; |
| 309 | } |
| 310 | Some( |
| 311 | out.stdout |
| 312 | .chunks(frame) |
| 313 | .map(|f| { |
| 314 | let (y, rest) = f.split_at(w * h); |
| 315 | let (u, v) = rest.split_at(w / 2 * h / 2); |
| 316 | (y.to_vec(), u.to_vec(), v.to_vec()) |
| 317 | }) |
| 318 | .collect(), |
| 319 | ) |
| 320 | } |
| 321 | |
| 322 | |
| 323 | |
| 324 | |
| 325 | |
| 326 | |
| 327 | |
| 328 | |
| 329 | |
| 330 | fn x265_encode_qp(sources: &[Planes], w: usize, h: usize, qp: i32) -> Option<Vec<u8>> { |
| 331 | let dir = std::env::temp_dir().join(format!("ec-h265-x265-{}", std::process::id())); |
| 332 | std::fs::create_dir_all(&dir).ok()?; |
| 333 | let raw = dir.join(format!("in-q{qp}.yuv")); |
| 334 | let out = dir.join(format!("out-q{qp}.265")); |
| 335 | let mut buf = Vec::with_capacity(sources.len() * w * h * 3 / 2); |
| 336 | for (y, u, v) in sources { |
| 337 | buf.extend_from_slice(y); |
| 338 | buf.extend_from_slice(u); |
| 339 | buf.extend_from_slice(v); |
| 340 | } |
| 341 | std::fs::write(&raw, &buf).ok()?; |
| 342 | |
| 343 | |
| 344 | |
| 345 | |
| 346 | |
| 347 | |
| 348 | |
| 349 | |
| 350 | |
| 351 | let params = format!( |
| 352 | "qp={qp}:keyint=1:bframes=0:scenecut=0:rc-lookahead=0:no-sao:{deblock}\ |
| 353 | aq-mode=0:psy-rd=0:psy-rdoq=0:rdoq-level=0:tu-intra-depth=1:ipratio=1.0:\ |
| 354 | pbratio=1.0:qcomp=1.0:chroma-qp-offset=0{extra}", |
| 355 | |
| 356 | |
| 357 | deblock = if std::env::var("EC_H265_X265_DEBLOCK").is_ok_and(|v| v != "0") { |
| 358 | "" |
| 359 | } else { |
| 360 | "no-deblock:" |
| 361 | }, |
| 362 | extra = match std::env::var("EC_H265_X265_PARAMS") { |
| 363 | Ok(extra) if !extra.trim().trim_matches(':').is_empty() => |
| 364 | format!(":{}", extra.trim().trim_matches(':')), |
| 365 | _ => String::new(), |
| 366 | } |
| 367 | ); |
| 368 | let status = std::process::Command::new("ffmpeg") |
| 369 | .args(["-v", "error", "-y"]) |
| 370 | .args(["-f", "rawvideo", "-pix_fmt", "yuv420p"]) |
| 371 | .args(["-s", &format!("{w}x{h}"), "-r", "1"]) |
| 372 | .arg("-i") |
| 373 | .arg(&raw) |
| 374 | .args(["-c:v", "libx265", "-preset", "medium"]) |
| 375 | .args(["-x265-params", ¶ms]) |
| 376 | .args(["-f", "hevc"]) |
| 377 | .arg(&out) |
| 378 | .status() |
| 379 | .ok()?; |
| 380 | let _ = std::fs::remove_file(&raw); |
| 381 | if !status.success() { |
| 382 | return None; |
| 383 | } |
| 384 | let stream = std::fs::read(&out).ok(); |
| 385 | let _ = std::fs::remove_file(&out); |
| 386 | stream |
| 387 | } |
| 388 | |
| 389 | |
| 390 | |
| 391 | |
| 392 | |
| 393 | |
| 394 | |
| 395 | |
| 396 | |
| 397 | |
| 398 | |
| 399 | |
| 400 | |
| 401 | |
| 402 | |
| 403 | |
| 404 | |
| 405 | |
| 406 | |
| 407 | #[test] |
| 408 | fn bd_psnr_vs_x265() { |
| 409 | if !have_ffmpeg() || !have_x265() { |
| 410 | eprintln!( |
| 411 | "SKIP bd_psnr_vs_x265: no ffmpeg with libx265 on PATH. \ |
| 412 | Install one, then: cargo test --release -p ec-h265 --test encode \ |
| 413 | bd_psnr_vs_x265 -- --nocapture" |
| 414 | ); |
| 415 | return; |
| 416 | } |
| 417 | let (w, h, sources) = match std::env::var_os("EC_H265_CLIP") { |
| 418 | Some(path) => clip_sources(&path, 24), |
| 419 | None => { |
| 420 | let (w, h, frames) = (352, 288, 24); |
| 421 | let mut clip = Clip::new(w, h); |
| 422 | let mut sources = Vec::with_capacity(frames); |
| 423 | for t in 0..frames { |
| 424 | clip.render_smooth(t); |
| 425 | sources.push((clip.y.clone(), clip.u.clone(), clip.v.clone())); |
| 426 | } |
| 427 | eprintln!("synthetic clip: {w}x{h}, {frames} pictures"); |
| 428 | (w, h, sources) |
| 429 | } |
| 430 | }; |
| 431 | |
| 432 | let ours = |qp: i32| { |
| 433 | let mut cfg = EncoderConfig::new(w as u32, h as u32); |
| 434 | cfg.rate_control = RateControl::ConstantQp(qp); |
| 435 | cfg.keep_recon = true; |
| 436 | cfg.threads = 0; |
| 437 | |
| 438 | |
| 439 | if let Ok(v) = std::env::var("EC_H265_CHROMA_RD") { |
| 440 | cfg.chroma_mode_search = v != "0"; |
| 441 | } |
| 442 | if let Ok(w) = std::env::var("EC_H265_CHROMA_W") { |
| 443 | cfg.chroma_rd_weight = w.parse().expect("EC_H265_CHROMA_W must be a number"); |
| 444 | } |
| 445 | if let Ok(v) = std::env::var("EC_H265_SDH") { |
| 446 | cfg.sign_hiding = v != "0"; |
| 447 | } |
| 448 | if let Ok(v) = std::env::var("EC_H265_RDOQ") { |
| 449 | cfg.rdoq = v != "0"; |
| 450 | } |
| 451 | if let Ok(v) = std::env::var("EC_H265_RDOQ_ESTIMATE") { |
| 452 | cfg.rdoq_estimate = v != "0"; |
| 453 | } |
| 454 | if let Ok(v) = std::env::var("EC_H265_TSKIP") { |
| 455 | cfg.transform_skip = if v != "0" { |
| 456 | TransformSkip::AlwaysFor4x4 |
| 457 | } else { |
| 458 | TransformSkip::Off |
| 459 | }; |
| 460 | } |
| 461 | if let Ok(v) = std::env::var("EC_H265_NXN") { |
| 462 | cfg.intra_nxn = v != "0"; |
| 463 | } |
| 464 | if let Ok(v) = std::env::var("EC_H265_CTB") { |
| 465 | cfg.ctb_size = v.parse().expect("EC_H265_CTB must be 32 or 64"); |
| 466 | } |
| 467 | if let Ok(v) = std::env::var("EC_H265_CU64") { |
| 468 | cfg.cu64 = v != "0"; |
| 469 | } |
| 470 | if let Ok(v) = std::env::var("EC_H265_DEBLOCK") { |
| 471 | cfg.deblock = v != "0"; |
| 472 | } |
| 473 | if let Ok(v) = std::env::var("EC_H265_RQT") { |
| 474 | cfg.rqt = v != "0"; |
| 475 | } |
| 476 | if let Ok(k) = std::env::var("EC_H265_RDO_CANDIDATES") { |
| 477 | cfg.rdo_candidates = k.parse().expect("EC_H265_RDO_CANDIDATES must be a number"); |
| 478 | } |
| 479 | let enc = Encoder::new(cfg).expect("encoder"); |
| 480 | let (mut stream, mut sum_recon) = (Vec::new(), 0.0); |
| 481 | for (y, u, v) in &sources { |
| 482 | let coded = enc |
| 483 | .encode_idr_planes(y, w, u, w / 2, v, w / 2) |
| 484 | .expect("encode"); |
| 485 | stream.extend_from_slice(&coded.au); |
| 486 | let recon = coded.recon.as_ref().expect("reconstruction"); |
| 487 | let (ry, _ru, _rv) = planes_of(recon); |
| 488 | sum_recon += psnr(y, &ry); |
| 489 | } |
| 490 | |
| 491 | |
| 492 | |
| 493 | |
| 494 | let decoded = ffmpeg_decode(&stream, w, h).expect("ffmpeg decodes our stream"); |
| 495 | assert_eq!(decoded.len(), sources.len(), "our encoder dropped pictures"); |
| 496 | let n = sources.len() as f64; |
| 497 | let sum: f64 = sources |
| 498 | .iter() |
| 499 | .zip(&decoded) |
| 500 | .map(|((y, _, _), (dy, _, _))| psnr(y, dy)) |
| 501 | .sum(); |
| 502 | let sum_yuv: f64 = sources |
| 503 | .iter() |
| 504 | .zip(&decoded) |
| 505 | .map(|(s, d)| psnr_yuv(s, d)) |
| 506 | .sum(); |
| 507 | let (sum_u, sum_v) = ( |
| 508 | sources |
| 509 | .iter() |
| 510 | .zip(&decoded) |
| 511 | .map(|(s, d)| psnr(&s.1, &d.1)) |
| 512 | .sum::<f64>(), |
| 513 | sources |
| 514 | .iter() |
| 515 | .zip(&decoded) |
| 516 | .map(|(s, d)| psnr(&s.2, &d.2)) |
| 517 | .sum::<f64>(), |
| 518 | ); |
| 519 | eprintln!( |
| 520 | " ours qp {qp}: u {:.2} dB v {:.2} dB", |
| 521 | sum_u / n, |
| 522 | sum_v / n |
| 523 | ); |
| 524 | let (decoded_psnr, recon_psnr) = (sum / n, sum_recon / n); |
| 525 | assert!( |
| 526 | (decoded_psnr - recon_psnr).abs() < 0.05, |
| 527 | "qp {qp}: our reconstruction reads {recon_psnr:.2} dB but our own \ |
| 528 | stream decodes to {decoded_psnr:.2} dB" |
| 529 | ); |
| 530 | ((stream.len() * 8) as f64, decoded_psnr, sum_yuv / n) |
| 531 | }; |
| 532 | let x265 = |qp: i32| { |
| 533 | let stream = x265_encode_qp(&sources, w, h, qp).expect("x265 encodes"); |
| 534 | let decoded = ffmpeg_decode(&stream, w, h).expect("ffmpeg decodes x265's own stream"); |
| 535 | assert_eq!( |
| 536 | decoded.len(), |
| 537 | sources.len(), |
| 538 | "x265 returned {} pictures for {} sources", |
| 539 | decoded.len(), |
| 540 | sources.len() |
| 541 | ); |
| 542 | let n = sources.len() as f64; |
| 543 | let sum: f64 = sources |
| 544 | .iter() |
| 545 | .zip(&decoded) |
| 546 | .map(|((y, _, _), (dy, _, _))| psnr(y, dy)) |
| 547 | .sum(); |
| 548 | let sum_yuv: f64 = sources |
| 549 | .iter() |
| 550 | .zip(&decoded) |
| 551 | .map(|(s, d)| psnr_yuv(s, d)) |
| 552 | .sum(); |
| 553 | eprintln!( |
| 554 | " x265 qp {qp}: u {:.2} dB v {:.2} dB", |
| 555 | sources |
| 556 | .iter() |
| 557 | .zip(&decoded) |
| 558 | .map(|(s, d)| psnr(&s.1, &d.1)) |
| 559 | .sum::<f64>() |
| 560 | / n, |
| 561 | sources |
| 562 | .iter() |
| 563 | .zip(&decoded) |
| 564 | .map(|(s, d)| psnr(&s.2, &d.2)) |
| 565 | .sum::<f64>() |
| 566 | / n |
| 567 | ); |
| 568 | ((stream.len() * 8) as f64, sum / n, sum_yuv / n) |
| 569 | }; |
| 570 | |
| 571 | |
| 572 | |
| 573 | |
| 574 | |
| 575 | |
| 576 | |
| 577 | |
| 578 | |
| 579 | |
| 580 | |
| 581 | const EXTRAP_LIMIT: f64 = 0.20; |
| 582 | let x265_qps = [22, 26, 30, 34]; |
| 583 | let probe_qp = 26; |
| 584 | |
| 585 | |
| 586 | let probe_ours = ours(probe_qp); |
| 587 | let probe_x265 = x265(probe_qp); |
| 588 | |
| 589 | |
| 590 | |
| 591 | |
| 592 | const FLAT_WINDOW_DB: f64 = 90.0; |
| 593 | assert!( |
| 594 | probe_x265.1 < FLAT_WINDOW_DB && probe_ours.1 < FLAT_WINDOW_DB, |
| 595 | "the sample window is flat — both encoders reach the PSNR cap on it \ |
| 596 | (ours {:.2} dB, x265 {:.2} dB at qp {probe_qp}); this is a black head \ |
| 597 | or a fade, not content: pass EC_H265_CLIP_SKIP to sample past it", |
| 598 | probe_ours.1, |
| 599 | probe_x265.1, |
| 600 | ); |
| 601 | let mut shift = (6.0 * (probe_ours.0 / probe_x265.0).log2()).round() as i32; |
| 602 | eprintln!( |
| 603 | "ladder shift {shift:+} (probe q{probe_qp}: ours {:.1} Mbit vs x265 {:.1} Mbit)", |
| 604 | probe_ours.0 / 1e6, |
| 605 | probe_x265.0 / 1e6, |
| 606 | ); |
| 607 | |
| 608 | let curve = |v: &[(f64, f64, f64)], luma: bool| -> Vec<(f64, f64)> { |
| 609 | v.iter() |
| 610 | .map(|&(b, p, y)| (b, if luma { p } else { y })) |
| 611 | .collect() |
| 612 | }; |
| 613 | |
| 614 | |
| 615 | let theirs: Vec<(f64, f64, f64)> = x265_qps |
| 616 | .iter() |
| 617 | .map(|&q| if q == probe_qp { probe_x265 } else { x265(q) }) |
| 618 | .collect(); |
| 619 | |
| 620 | let gm = |v: &[(f64, f64, f64)]| (v[0].0 * v[1].0 * v[2].0 * v[3].0).powf(0.25); |
| 621 | let qps_str = |qs: &[i32; 4]| { |
| 622 | qs.iter() |
| 623 | .map(|q| q.to_string()) |
| 624 | .collect::<Vec<_>>() |
| 625 | .join("/") |
| 626 | }; |
| 627 | |
| 628 | #[allow(unused_assignments)] |
| 629 | let ( |
| 630 | mut bd, |
| 631 | mut bd_yuv, |
| 632 | mut cand_extrap, |
| 633 | mut anc_extrap, |
| 634 | mut cand_extrap_yuv, |
| 635 | mut anc_extrap_yuv, |
| 636 | ) = (0.0_f64, 0.0, 0.0, 0.0, 0.0, 0.0); |
| 637 | let mut mine: Vec<(f64, f64, f64)>; |
| 638 | let mut our_qps: [i32; 4]; |
| 639 | |
| 640 | |
| 641 | |
| 642 | let mut spread = 1.0_f64; |
| 643 | |
| 644 | for round in 0..=8u32 { |
| 645 | our_qps = x265_qps.map(|q| { |
| 646 | let centre = f64::from(probe_qp + shift); |
| 647 | let offset = f64::from(q - probe_qp) * spread; |
| 648 | ((centre + offset).round() as i32).clamp(1, 45) |
| 649 | }); |
| 650 | let mut distinct = our_qps; |
| 651 | distinct.sort_unstable(); |
| 652 | let collapsed = distinct.windows(2).any(|w| w[0] == w[1]); |
| 653 | assert!( |
| 654 | !collapsed, |
| 655 | "our QP ladder collapsed to {:?}: the shift has pushed it into the \ |
| 656 | qp floor, so two points share an x and the cubic has no unique fit", |
| 657 | our_qps, |
| 658 | ); |
| 659 | mine = our_qps |
| 660 | .iter() |
| 661 | .map(|&q| if q == probe_qp { probe_ours } else { ours(q) }) |
| 662 | .collect(); |
| 663 | for (i, &qp) in our_qps.iter().enumerate() { |
| 664 | let (ob, op, oy) = mine[i]; |
| 665 | eprintln!("qp {qp}: ours {ob:.0} bits {op:.2} dB ({oy:.2} yuv)"); |
| 666 | } |
| 667 | for (i, &qp) in x265_qps.iter().enumerate() { |
| 668 | let (xb, xp, xy) = theirs[i]; |
| 669 | eprintln!("qp {qp}: x265 {xb:.0} bits {xp:.2} dB ({xy:.2} yuv)"); |
| 670 | } |
| 671 | (bd, cand_extrap, anc_extrap) = bd_psnr_delta(&curve(&mine, true), &curve(&theirs, true)); |
| 672 | (bd_yuv, cand_extrap_yuv, anc_extrap_yuv) = |
| 673 | bd_psnr_delta(&curve(&mine, false), &curve(&theirs, false)); |
| 674 | eprintln!( |
| 675 | "BD-PSNR ours (q{}) vs x265 (q{}): {bd:+.3} dB", |
| 676 | qps_str(&our_qps), |
| 677 | qps_str(&x265_qps), |
| 678 | ); |
| 679 | eprintln!( |
| 680 | "BD-PSNR-YUV ours (q{}) vs x265 (q{}): {bd_yuv:+.3} dB", |
| 681 | qps_str(&our_qps), |
| 682 | qps_str(&x265_qps), |
| 683 | ); |
| 684 | let aligned = cand_extrap <= EXTRAP_LIMIT |
| 685 | && anc_extrap <= EXTRAP_LIMIT |
| 686 | && cand_extrap_yuv <= EXTRAP_LIMIT |
| 687 | && anc_extrap_yuv <= EXTRAP_LIMIT; |
| 688 | if aligned || round == 8 { |
| 689 | break; |
| 690 | } |
| 691 | |
| 692 | |
| 693 | |
| 694 | |
| 695 | let delta = (6.0 * (gm(&mine) / gm(&theirs)).log2()).round() as i32; |
| 696 | if delta.abs() > 1 { |
| 697 | shift += delta; |
| 698 | eprintln!( |
| 699 | "alignment round {}: shift {delta:+} -> {shift:+} \ |
| 700 | (gm ours {:.1} Mbit vs x265 {:.1} Mbit)", |
| 701 | round + 1, |
| 702 | gm(&mine) / 1e6, |
| 703 | gm(&theirs) / 1e6, |
| 704 | ); |
| 705 | continue; |
| 706 | } |
| 707 | |
| 708 | |
| 709 | |
| 710 | |
| 711 | spread *= 0.5; |
| 712 | eprintln!( |
| 713 | "alignment round {}: ladder spread -> {spread:.2} of the anchor's", |
| 714 | round + 1 |
| 715 | ); |
| 716 | } |
| 717 | |
| 718 | |
| 719 | |
| 720 | |
| 721 | let out_of_range = |c: f64, a: f64| { |
| 722 | let mut parts = Vec::new(); |
| 723 | if c > EXTRAP_LIMIT { |
| 724 | parts.push(format!("ours {:.0}%", c * 100.0)); |
| 725 | } |
| 726 | if a > EXTRAP_LIMIT { |
| 727 | parts.push(format!("x265 {:.0}%", a * 100.0)); |
| 728 | } |
| 729 | parts |
| 730 | }; |
| 731 | let luma_oor = out_of_range(cand_extrap, anc_extrap); |
| 732 | let yuv_oor = out_of_range(cand_extrap_yuv, anc_extrap_yuv); |
| 733 | if !luma_oor.is_empty() { |
| 734 | panic!( |
| 735 | "BD-PSNR luma: the two QP ladders do not overlap — {} of the \ |
| 736 | integration range is extrapolated (limit {:.0}%); widen the QP \ |
| 737 | sweep until the curves meet", |
| 738 | luma_oor.join(", "), |
| 739 | EXTRAP_LIMIT * 100.0 |
| 740 | ); |
| 741 | } |
| 742 | if !yuv_oor.is_empty() { |
| 743 | panic!( |
| 744 | "BD-PSNR-YUV: the two QP ladders do not overlap — {} of the \ |
| 745 | integration range is extrapolated (limit {:.0}%); widen the QP \ |
| 746 | sweep until the curves meet", |
| 747 | yuv_oor.join(", "), |
| 748 | EXTRAP_LIMIT * 100.0 |
| 749 | ); |
| 750 | } |
| 751 | |
| 752 | |
| 753 | |
| 754 | if std::env::var_os("EC_H265_CLIP").is_none() { |
| 755 | assert!( |
| 756 | bd > BD_PSNR_VS_X265_FLOOR, |
| 757 | "BD-PSNR against x265 fell to {bd:+.3} dB, past the \ |
| 758 | {BD_PSNR_VS_X265_FLOOR:+.3} dB floor" |
| 759 | ); |
| 760 | } |
| 761 | } |
| 762 | |
| 763 | |
| 764 | |
| 765 | |
| 766 | fn clip_sources(path: &std::ffi::OsStr, want: usize) -> (usize, usize, Vec<Planes>) { |
| 767 | let dims = std::process::Command::new("ffprobe") |
| 768 | .args([ |
| 769 | "-v", |
| 770 | "error", |
| 771 | "-select_streams", |
| 772 | "v:0", |
| 773 | "-show_entries", |
| 774 | "stream=width,height", |
| 775 | "-of", |
| 776 | "csv=p=0", |
| 777 | ]) |
| 778 | .arg(path) |
| 779 | .output() |
| 780 | .expect("ffprobe"); |
| 781 | assert!( |
| 782 | dims.status.success(), |
| 783 | "ffprobe failed: {}", |
| 784 | String::from_utf8_lossy(&dims.stderr) |
| 785 | ); |
| 786 | let csv = String::from_utf8_lossy(&dims.stdout); |
| 787 | |
| 788 | |
| 789 | |
| 790 | let mut fields = csv.lines().next().unwrap_or_default().split(','); |
| 791 | let (w, h) = (|| { |
| 792 | Some(( |
| 793 | fields.next()?.trim().parse::<usize>().ok()?, |
| 794 | fields.next()?.trim().parse::<usize>().ok()?, |
| 795 | )) |
| 796 | })() |
| 797 | .unwrap_or_else(|| panic!("ffprobe returned dimensions, got {csv:?}")); |
| 798 | |
| 799 | |
| 800 | let skip: usize = std::env::var("EC_H265_CLIP_SKIP") |
| 801 | .ok() |
| 802 | .and_then(|v| v.parse().ok()) |
| 803 | .unwrap_or(0); |
| 804 | |
| 805 | |
| 806 | |
| 807 | |
| 808 | |
| 809 | |
| 810 | let raw = std::process::Command::new("ffmpeg") |
| 811 | .args(["-v", "error", "-i"]) |
| 812 | .arg(path) |
| 813 | .args([ |
| 814 | "-vf", |
| 815 | &format!("select=gte(n\\,{skip})"), |
| 816 | "-fps_mode", |
| 817 | "passthrough", |
| 818 | "-frames:v", |
| 819 | &want.to_string(), |
| 820 | "-f", |
| 821 | "rawvideo", |
| 822 | "-pix_fmt", |
| 823 | "yuv420p", |
| 824 | "pipe:1", |
| 825 | ]) |
| 826 | .output() |
| 827 | .expect("ffmpeg raw extract"); |
| 828 | assert!( |
| 829 | raw.status.success(), |
| 830 | "ffmpeg failed: {}", |
| 831 | String::from_utf8_lossy(&raw.stderr) |
| 832 | ); |
| 833 | let frame = w * h * 3 / 2; |
| 834 | assert!( |
| 835 | raw.stdout.len().is_multiple_of(frame) && raw.stdout.len() / frame >= want, |
| 836 | "clip {} yielded {} bytes after skipping {skip}, need {want}x{frame}", |
| 837 | path.to_string_lossy(), |
| 838 | raw.stdout.len() |
| 839 | ); |
| 840 | let sources: Vec<Planes> = raw |
| 841 | .stdout |
| 842 | .chunks(frame) |
| 843 | .take(want) |
| 844 | .map(|f| { |
| 845 | let (y, rest) = f.split_at(w * h); |
| 846 | let (u, v) = rest.split_at(w / 2 * h / 2); |
| 847 | (y.to_vec(), u.to_vec(), v.to_vec()) |
| 848 | }) |
| 849 | .collect(); |
| 850 | eprintln!( |
| 851 | "{}: {}x{}, {} pictures (skipped {skip})", |
| 852 | path.to_string_lossy(), |
| 853 | w, |
| 854 | h, |
| 855 | sources.len() |
| 856 | ); |
| 857 | (w, h, sources) |
| 858 | } |