| 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_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 | |
| 278 | fn 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] |
| 287 | fn pin_loud_reds_on_an_ok_but_short_write() { |
| 288 | |
| 289 | |
| 290 | |
| 291 | |
| 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 | |
| 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] |
| 313 | fn pin_loud_reports_what_landed_under_a_size_cap() { |
| 314 | |
| 315 | |
| 316 | |
| 317 | |
| 318 | use std::process::Command; |
| 319 | let Ok(exe) = std::env::current_exe() else { |
| 320 | return; |
| 321 | }; |
| 322 | |
| 323 | |
| 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 | |
| 347 | |
| 348 | |
| 349 | #[test] |
| 350 | fn 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 | |
| 365 | fn 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 | |
| 403 | |
| 404 | |
| 405 | |
| 406 | |
| 407 | |
| 408 | |
| 409 | |
| 410 | fn 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 | |
| 423 | |
| 424 | |
| 425 | |
| 426 | |
| 427 | |
| 428 | |
| 429 | |
| 430 | |
| 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 | |
| 436 | |
| 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", ¶ms]) |
| 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 | |
| 470 | |
| 471 | |
| 472 | |
| 473 | |
| 474 | |
| 475 | |
| 476 | |
| 477 | |
| 478 | |
| 479 | |
| 480 | |
| 481 | |
| 482 | |
| 483 | |
| 484 | |
| 485 | |
| 486 | |
| 487 | #[test] |
| 488 | fn 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 | |
| 518 | |
| 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 | |
| 571 | |
| 572 | |
| 573 | |
| 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 | |
| 652 | |
| 653 | |
| 654 | |
| 655 | |
| 656 | |
| 657 | |
| 658 | |
| 659 | |
| 660 | |
| 661 | const EXTRAP_LIMIT: f64 = 0.20; |
| 662 | let x265_qps = [22, 26, 30, 34]; |
| 663 | let probe_qp = 26; |
| 664 | |
| 665 | |
| 666 | let probe_ours = ours(probe_qp); |
| 667 | let probe_x265 = x265(probe_qp); |
| 668 | |
| 669 | |
| 670 | |
| 671 | |
| 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 | |
| 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 | |
| 720 | |
| 721 | |
| 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 | |
| 772 | |
| 773 | |
| 774 | |
| 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 | |
| 788 | |
| 789 | |
| 790 | |
| 791 | spread *= 0.5; |
| 792 | eprintln!( |
| 793 | "alignment round {}: ladder spread -> {spread:.2} of the anchor's", |
| 794 | round + 1 |
| 795 | ); |
| 796 | } |
| 797 | |
| 798 | |
| 799 | |
| 800 | |
| 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 | |
| 833 | |
| 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 | |
| 844 | |
| 845 | |
| 846 | fn 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 | |
| 868 | |
| 869 | |
| 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 | |
| 879 | |
| 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 | |
| 885 | |
| 886 | |
| 887 | |
| 888 | |
| 889 | |
| 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 | } |