| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | use crate::common::{pin_loud, pin_or_bail}; |
| 10 | use ec_core::frame::VideoFrame; |
| 11 | use ec_h265::encoder::{Encoder, EncoderConfig, RateControl, TransformSkip}; |
| 12 | |
| 13 | |
| 14 | type Planes = (Vec<u8>, Vec<u8>, Vec<u8>); |
| 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 | |
| 42 | const BD_PSNR_VS_X265_FLOOR: f64 = 2.357; |
| 43 | |
| 44 | |
| 45 | |
| 46 | |
| 47 | |
| 48 | |
| 49 | struct Clip { |
| 50 | w: usize, |
| 51 | h: usize, |
| 52 | y: Vec<u8>, |
| 53 | u: Vec<u8>, |
| 54 | v: Vec<u8>, |
| 55 | } |
| 56 | |
| 57 | impl 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 | |
| 69 | |
| 70 | |
| 71 | |
| 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 | |
| 107 | fn 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 | |
| 128 | fn 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 | |
| 140 | |
| 141 | |
| 142 | |
| 143 | fn 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 | |
| 155 | fn 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)] |
| 173 | fn 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 | |
| 204 | fn 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 | |
| 209 | |
| 210 | |
| 211 | |
| 212 | |
| 213 | |
| 214 | |
| 215 | |
| 216 | |
| 217 | |
| 218 | |
| 219 | |
| 220 | |
| 221 | |
| 222 | |
| 223 | |
| 224 | |
| 225 | |
| 226 | |
| 227 | fn 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 | |
| 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 | |
| 269 | fn 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] |
| 278 | fn pin_loud_reds_on_an_ok_but_short_write() { |
| 279 | |
| 280 | |
| 281 | |
| 282 | |
| 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 | |
| 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] |
| 304 | fn pin_loud_reports_what_landed_under_a_size_cap() { |
| 305 | |
| 306 | |
| 307 | |
| 308 | |
| 309 | use std::process::Command; |
| 310 | let Ok(exe) = std::env::current_exe() else { |
| 311 | return; |
| 312 | }; |
| 313 | |
| 314 | |
| 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 | |
| 338 | |
| 339 | |
| 340 | #[test] |
| 341 | fn 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 | |
| 356 | fn 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 | |
| 394 | |
| 395 | |
| 396 | |
| 397 | |
| 398 | |
| 399 | |
| 400 | |
| 401 | fn 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 | |
| 414 | |
| 415 | |
| 416 | |
| 417 | |
| 418 | |
| 419 | |
| 420 | |
| 421 | |
| 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 | |
| 427 | |
| 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", ¶ms]) |
| 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 | |
| 461 | |
| 462 | |
| 463 | |
| 464 | |
| 465 | |
| 466 | |
| 467 | |
| 468 | |
| 469 | |
| 470 | |
| 471 | |
| 472 | |
| 473 | |
| 474 | |
| 475 | |
| 476 | |
| 477 | |
| 478 | #[test] |
| 479 | fn 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 | |
| 502 | |
| 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 | |
| 555 | |
| 556 | |
| 557 | |
| 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 | |
| 636 | |
| 637 | |
| 638 | |
| 639 | |
| 640 | |
| 641 | |
| 642 | |
| 643 | |
| 644 | |
| 645 | const EXTRAP_LIMIT: f64 = 0.20; |
| 646 | let x265_qps = [22, 26, 30, 34]; |
| 647 | let probe_qp = 26; |
| 648 | |
| 649 | |
| 650 | let probe_ours = ours(probe_qp); |
| 651 | let probe_x265 = x265(probe_qp); |
| 652 | |
| 653 | |
| 654 | |
| 655 | |
| 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 | |
| 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 | |
| 704 | |
| 705 | |
| 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 | |
| 756 | |
| 757 | |
| 758 | |
| 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 | |
| 772 | |
| 773 | |
| 774 | |
| 775 | spread *= 0.5; |
| 776 | eprintln!( |
| 777 | "alignment round {}: ladder spread -> {spread:.2} of the anchor's", |
| 778 | round + 1 |
| 779 | ); |
| 780 | } |
| 781 | |
| 782 | |
| 783 | |
| 784 | |
| 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 | |
| 817 | |
| 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 | |
| 828 | |
| 829 | |
| 830 | fn 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 | |
| 852 | |
| 853 | |
| 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 | |
| 863 | |
| 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 | |
| 869 | |
| 870 | |
| 871 | |
| 872 | |
| 873 | |
| 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 | } |