| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | use std::io::Read; |
| 12 | use std::path::{Path, PathBuf}; |
| 13 | use std::process::{Command, Stdio}; |
| 14 | use std::sync::Arc; |
| 15 | use std::time::{Duration, Instant}; |
| 16 | |
| 17 | use ec_hw::{ |
| 18 | Codec, Decoder, EncCodec, Encoder, EncoderConfig, Frame, FrameMetadata, I420, I420_16, |
| 19 | RateControlMode, |
| 20 | }; |
| 21 | use ec_va::Display; |
| 22 | |
| 23 | |
| 24 | |
| 25 | const FRAMES: usize = 24; |
| 26 | |
| 27 | fn bitstreams() -> PathBuf { |
| 28 | Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/bitstreams") |
| 29 | } |
| 30 | |
| 31 | fn display() -> Option<Arc<Display>> { |
| 32 | match Display::open() { |
| 33 | Ok(display) => Some(display), |
| 34 | Err(e) => { |
| 35 | eprintln!("skipped: no VA display ({e})"); |
| 36 | None |
| 37 | } |
| 38 | } |
| 39 | } |
| 40 | |
| 41 | fn fixtures(pattern: &str) -> Vec<PathBuf> { |
| 42 | let Ok(dir) = std::fs::read_dir(bitstreams()) else { |
| 43 | return Vec::new(); |
| 44 | }; |
| 45 | let mut out: Vec<PathBuf> = dir |
| 46 | .flatten() |
| 47 | .map(|e| e.path()) |
| 48 | .filter(|p| { |
| 49 | p.file_name() |
| 50 | .and_then(|n| n.to_str()) |
| 51 | .is_some_and(|n| n.ends_with(pattern)) |
| 52 | }) |
| 53 | .collect(); |
| 54 | out.sort(); |
| 55 | out |
| 56 | } |
| 57 | |
| 58 | |
| 59 | struct Reference { |
| 60 | child: std::process::Child, |
| 61 | frame_bytes: usize, |
| 62 | ten_bit: bool, |
| 63 | } |
| 64 | |
| 65 | impl Reference { |
| 66 | fn open(path: &Path, width: u32, height: u32, ten_bit: bool) -> Option<Reference> { |
| 67 | let pix = if ten_bit { "yuv420p10le" } else { "yuv420p" }; |
| 68 | let child = Command::new("ffmpeg") |
| 69 | .args(["-nostdin", "-v", "error", "-i"]) |
| 70 | .arg(path) |
| 71 | |
| 72 | |
| 73 | |
| 74 | |
| 75 | .args([ |
| 76 | "-map", |
| 77 | "0:v:0", |
| 78 | "-fps_mode", |
| 79 | "passthrough", |
| 80 | "-pix_fmt", |
| 81 | pix, |
| 82 | "-f", |
| 83 | "rawvideo", |
| 84 | "-", |
| 85 | ]) |
| 86 | .stdout(Stdio::piped()) |
| 87 | .stderr(Stdio::null()) |
| 88 | .spawn() |
| 89 | .ok()?; |
| 90 | let samples = (width as usize * height as usize * 3).div_ceil(2); |
| 91 | Some(Reference { |
| 92 | child, |
| 93 | frame_bytes: if ten_bit { samples * 2 } else { samples }, |
| 94 | ten_bit, |
| 95 | }) |
| 96 | } |
| 97 | |
| 98 | |
| 99 | |
| 100 | |
| 101 | |
| 102 | |
| 103 | fn next(&mut self, width: u32, height: u32) -> Option<Planes> { |
| 104 | let stdout = self.child.stdout.as_mut()?; |
| 105 | let mut buf = vec![0u8; self.frame_bytes]; |
| 106 | stdout.read_exact(&mut buf).ok()?; |
| 107 | let (w, h) = (width as usize, height as usize); |
| 108 | let (cw, ch) = (w.div_ceil(2), h.div_ceil(2)); |
| 109 | let (y_len, c_len) = (w * h, cw * ch); |
| 110 | if self.ten_bit { |
| 111 | let read = |slice: &[u8]| -> Vec<u16> { |
| 112 | slice |
| 113 | .chunks_exact(2) |
| 114 | .map(|p| u16::from_le_bytes([p[0], p[1]])) |
| 115 | .collect() |
| 116 | }; |
| 117 | Some(Planes { |
| 118 | y: read(&buf[..y_len * 2]), |
| 119 | u: read(&buf[y_len * 2..(y_len + c_len) * 2]), |
| 120 | v: read(&buf[(y_len + c_len) * 2..(y_len + 2 * c_len) * 2]), |
| 121 | peak: 1023.0, |
| 122 | }) |
| 123 | } else { |
| 124 | let read = |slice: &[u8]| -> Vec<u16> { slice.iter().map(|&v| u16::from(v)).collect() }; |
| 125 | Some(Planes { |
| 126 | y: read(&buf[..y_len]), |
| 127 | u: read(&buf[y_len..y_len + c_len]), |
| 128 | v: read(&buf[y_len + c_len..y_len + 2 * c_len]), |
| 129 | peak: 255.0, |
| 130 | }) |
| 131 | } |
| 132 | } |
| 133 | } |
| 134 | |
| 135 | impl Drop for Reference { |
| 136 | fn drop(&mut self) { |
| 137 | let _ = self.child.kill(); |
| 138 | let _ = self.child.wait(); |
| 139 | } |
| 140 | } |
| 141 | |
| 142 | |
| 143 | struct Planes { |
| 144 | y: Vec<u16>, |
| 145 | u: Vec<u16>, |
| 146 | v: Vec<u16>, |
| 147 | peak: f64, |
| 148 | } |
| 149 | |
| 150 | impl Planes { |
| 151 | fn from_8bit(f: &I420) -> Planes { |
| 152 | let read = |v: &[u8]| -> Vec<u16> { v.iter().map(|&s| u16::from(s)).collect() }; |
| 153 | Planes { |
| 154 | y: read(&f.y), |
| 155 | u: read(&f.u), |
| 156 | v: read(&f.v), |
| 157 | peak: 255.0, |
| 158 | } |
| 159 | } |
| 160 | |
| 161 | fn from_16bit(f: &ec_hw::I420_16) -> Planes { |
| 162 | Planes { |
| 163 | y: f.y.clone(), |
| 164 | u: f.u.clone(), |
| 165 | v: f.v.clone(), |
| 166 | peak: 1023.0, |
| 167 | } |
| 168 | } |
| 169 | } |
| 170 | |
| 171 | |
| 172 | |
| 173 | fn psnr(a: &Planes, b: &Planes) -> f64 { |
| 174 | let mut sum = 0f64; |
| 175 | let mut n = 0usize; |
| 176 | for (x, y) in [(&a.y, &b.y), (&a.u, &b.u), (&a.v, &b.v)] { |
| 177 | for (p, q) in x.iter().zip(y.iter()) { |
| 178 | let d = f64::from(*p) - f64::from(*q); |
| 179 | sum += d * d; |
| 180 | } |
| 181 | n += x.len().min(y.len()); |
| 182 | } |
| 183 | if n == 0 { |
| 184 | return 0.0; |
| 185 | } |
| 186 | let mse = sum / n as f64; |
| 187 | if mse == 0.0 { |
| 188 | return f64::INFINITY; |
| 189 | } |
| 190 | 10.0 * (a.peak * a.peak / mse).log10() |
| 191 | } |
| 192 | |
| 193 | |
| 194 | |
| 195 | |
| 196 | |
| 197 | fn decode_stream( |
| 198 | decoder: &mut Decoder, |
| 199 | codec: Codec, |
| 200 | data: &[u8], |
| 201 | limit: usize, |
| 202 | mut on_frame: impl FnMut(Frame), |
| 203 | ) -> Result<usize, ec_hw::Error> { |
| 204 | let mut count = 0usize; |
| 205 | let units: Vec<&[u8]> = match codec { |
| 206 | Codec::H264 | Codec::H265 => split_access_units(data, codec), |
| 207 | Codec::Vp9 | Codec::Av1 => split_ivf(data), |
| 208 | }; |
| 209 | for (i, unit) in units.iter().enumerate() { |
| 210 | decoder.decode(unit, i as i64)?; |
| 211 | while let Some(frame) = decoder.next_frame() { |
| 212 | count += 1; |
| 213 | on_frame(frame); |
| 214 | if count >= limit { |
| 215 | return Ok(count); |
| 216 | } |
| 217 | } |
| 218 | } |
| 219 | decoder.flush()?; |
| 220 | while let Some(frame) = decoder.next_frame() { |
| 221 | count += 1; |
| 222 | on_frame(frame); |
| 223 | if count >= limit { |
| 224 | break; |
| 225 | } |
| 226 | } |
| 227 | Ok(count) |
| 228 | } |
| 229 | |
| 230 | |
| 231 | |
| 232 | |
| 233 | fn split_access_units(data: &[u8], codec: Codec) -> Vec<&[u8]> { |
| 234 | let mut starts: Vec<usize> = Vec::new(); |
| 235 | let mut seen_slice = false; |
| 236 | let mut i = 0usize; |
| 237 | while i + 3 < data.len() { |
| 238 | if data[i] != 0 || data[i + 1] != 0 || data[i + 2] != 1 { |
| 239 | i += 1; |
| 240 | continue; |
| 241 | } |
| 242 | let nal = i + 3; |
| 243 | let (is_vcl, first_slice) = match codec { |
| 244 | Codec::H264 => { |
| 245 | let t = data[nal] & 0x1f; |
| 246 | let first = data.get(nal + 1).is_some_and(|&b| b & 0x80 != 0); |
| 247 | ((1..=5).contains(&t), first) |
| 248 | } |
| 249 | _ => { |
| 250 | let t = (data[nal] >> 1) & 0x3f; |
| 251 | let first = data.get(nal + 2).is_some_and(|&b| b & 0x80 != 0); |
| 252 | (t <= 31, first) |
| 253 | } |
| 254 | }; |
| 255 | if is_vcl { |
| 256 | if seen_slice && first_slice { |
| 257 | starts.push(i); |
| 258 | seen_slice = false; |
| 259 | } |
| 260 | if first_slice { |
| 261 | seen_slice = true; |
| 262 | } |
| 263 | } |
| 264 | i = nal + 1; |
| 265 | } |
| 266 | let mut out = Vec::new(); |
| 267 | let mut prev = 0usize; |
| 268 | for &start in &starts { |
| 269 | out.push(&data[prev..start]); |
| 270 | prev = start; |
| 271 | } |
| 272 | if prev < data.len() { |
| 273 | out.push(&data[prev..]); |
| 274 | } |
| 275 | out |
| 276 | } |
| 277 | |
| 278 | |
| 279 | fn split_ivf(data: &[u8]) -> Vec<&[u8]> { |
| 280 | let mut out = Vec::new(); |
| 281 | if data.len() < 32 || &data[..4] != b"DKIF" { |
| 282 | return out; |
| 283 | } |
| 284 | let header = u16::from_le_bytes([data[6], data[7]]) as usize; |
| 285 | let mut pos = header.max(32); |
| 286 | while pos + 12 <= data.len() { |
| 287 | let size = |
| 288 | u32::from_le_bytes([data[pos], data[pos + 1], data[pos + 2], data[pos + 3]]) as usize; |
| 289 | pos += 12; |
| 290 | if pos + size > data.len() { |
| 291 | break; |
| 292 | } |
| 293 | out.push(&data[pos..pos + size]); |
| 294 | pos += size; |
| 295 | } |
| 296 | out |
| 297 | } |
| 298 | |
| 299 | |
| 300 | fn compare_against_ffmpeg(files: &[PathBuf], codec: Codec, ten_bit: bool) { |
| 301 | let Some(display) = display() else { return }; |
| 302 | if files.is_empty() { |
| 303 | eprintln!("skipped: no fixtures — run scripts/gen-bitstream-fixtures.sh"); |
| 304 | return; |
| 305 | } |
| 306 | let mut table = Vec::new(); |
| 307 | for path in files { |
| 308 | let data = std::fs::read(path).expect("fixture is readable"); |
| 309 | let mut decoder = Decoder::new(&display, codec).expect("decoder opens"); |
| 310 | let mut reference: Option<Reference> = None; |
| 311 | let mut worst = f64::INFINITY; |
| 312 | let mut identical = 0usize; |
| 313 | let mut compared = 0usize; |
| 314 | let mut mismatched_size = false; |
| 315 | |
| 316 | let result = decode_stream(&mut decoder, codec, &data, FRAMES, |frame| { |
| 317 | let (w, h) = frame.display_size; |
| 318 | let reference = reference |
| 319 | .get_or_insert_with(|| Reference::open(path, w, h, ten_bit).expect("ffmpeg runs")); |
| 320 | let Some(want) = reference.next(w, h) else { |
| 321 | return; |
| 322 | }; |
| 323 | let got = if ten_bit { |
| 324 | Planes::from_16bit(&frame.to_i420_16().expect("readback")) |
| 325 | } else { |
| 326 | Planes::from_8bit(&frame.to_i420().expect("readback")) |
| 327 | }; |
| 328 | if got.y.len() != want.y.len() { |
| 329 | mismatched_size = true; |
| 330 | return; |
| 331 | } |
| 332 | let db = psnr(&got, &want); |
| 333 | if std::env::var_os("EC_HW_DEBUG").is_some() { |
| 334 | eprintln!(" frame {compared}: {db:.1} dB (ts {})", frame.timestamp); |
| 335 | } |
| 336 | if db.is_infinite() { |
| 337 | identical += 1; |
| 338 | } |
| 339 | worst = worst.min(db); |
| 340 | compared += 1; |
| 341 | }); |
| 342 | let decoded = result.expect("decode succeeds"); |
| 343 | assert!( |
| 344 | !mismatched_size, |
| 345 | "{}: frame size disagrees with ffmpeg", |
| 346 | path.display() |
| 347 | ); |
| 348 | assert!(compared > 0, "{}: nothing decoded", path.display()); |
| 349 | table.push(format!( |
| 350 | "{:<40} {decoded:>3} frames, {identical:>3}/{compared} identical, worst {}", |
| 351 | path.file_name().unwrap_or_default().to_string_lossy(), |
| 352 | if worst.is_infinite() { |
| 353 | "exact".to_string() |
| 354 | } else { |
| 355 | format!("{worst:.1} dB") |
| 356 | } |
| 357 | )); |
| 358 | assert!( |
| 359 | worst >= 40.0, |
| 360 | "{}: worst frame PSNR {worst:.1} dB against ffmpeg", |
| 361 | path.display() |
| 362 | ); |
| 363 | } |
| 364 | for row in table { |
| 365 | println!("{row}"); |
| 366 | } |
| 367 | } |
| 368 | |
| 369 | |
| 370 | |
| 371 | |
| 372 | fn name_of(p: &Path) -> String { |
| 373 | p.file_name() |
| 374 | .unwrap_or_default() |
| 375 | .to_string_lossy() |
| 376 | .to_string() |
| 377 | } |
| 378 | |
| 379 | |
| 380 | |
| 381 | fn profile_420(pattern: &str, codec: &str) -> Vec<PathBuf> { |
| 382 | fixtures(pattern) |
| 383 | .into_iter() |
| 384 | .filter(|p| { |
| 385 | let name = name_of(p); |
| 386 | name.contains(codec) && !name.contains("444") && !name.contains("monochrome") |
| 387 | }) |
| 388 | .collect() |
| 389 | } |
| 390 | |
| 391 | fn eight_bit(pattern: &str, codec: &str) -> Vec<PathBuf> { |
| 392 | profile_420(pattern, codec) |
| 393 | .into_iter() |
| 394 | .filter(|p| !name_of(p).contains("10bit")) |
| 395 | .collect() |
| 396 | } |
| 397 | |
| 398 | fn ten_bit(pattern: &str, codec: &str) -> Vec<PathBuf> { |
| 399 | profile_420(pattern, codec) |
| 400 | .into_iter() |
| 401 | .filter(|p| name_of(p).contains("10bit")) |
| 402 | .collect() |
| 403 | } |
| 404 | |
| 405 | |
| 406 | #[test] |
| 407 | fn fixture_selection_ignores_the_checkout_path() { |
| 408 | for p in eight_bit(".ivf", "av1") { |
| 409 | let name = name_of(&p); |
| 410 | assert!( |
| 411 | name.starts_with("av1") && !name.contains("10bit"), |
| 412 | "{name} is not an 8-bit AV1 fixture" |
| 413 | ); |
| 414 | } |
| 415 | for p in ten_bit(".ivf", "vp9") { |
| 416 | let name = name_of(&p); |
| 417 | assert!( |
| 418 | name.starts_with("vp9") && name.contains("10bit"), |
| 419 | "{name} is not a 10-bit VP9 fixture" |
| 420 | ); |
| 421 | } |
| 422 | } |
| 423 | |
| 424 | #[test] |
| 425 | fn h264_matches_ffmpeg() { |
| 426 | compare_against_ffmpeg(&fixtures(".264"), Codec::H264, false); |
| 427 | } |
| 428 | |
| 429 | #[test] |
| 430 | fn hevc_8bit_matches_ffmpeg() { |
| 431 | compare_against_ffmpeg(&eight_bit(".265", "hevc"), Codec::H265, false); |
| 432 | } |
| 433 | |
| 434 | |
| 435 | |
| 436 | |
| 437 | #[test] |
| 438 | fn hevc_10bit_decodes_to_p010() { |
| 439 | let files = ten_bit(".265", "hevc"); |
| 440 | if files.is_empty() { |
| 441 | eprintln!("skipped: no 10-bit HEVC fixtures"); |
| 442 | return; |
| 443 | } |
| 444 | let Some(display) = display() else { return }; |
| 445 | let data = std::fs::read(&files[0]).expect("fixture is readable"); |
| 446 | let mut decoder = Decoder::new(&display, Codec::H265).expect("decoder opens"); |
| 447 | let mut depth = 0u8; |
| 448 | decode_stream(&mut decoder, Codec::H265, &data, 1, |frame| { |
| 449 | depth = frame.bit_depth; |
| 450 | }) |
| 451 | .expect("decode succeeds"); |
| 452 | assert_eq!(depth, 10, "a Main10 stream decoded at {depth} bits"); |
| 453 | let info = decoder.stream_info().expect("the session exists"); |
| 454 | assert_eq!(info.bit_depth, 10); |
| 455 | assert_eq!(info.profile, ec_va::caps::Profile::HEVCMain10); |
| 456 | |
| 457 | compare_against_ffmpeg(&files, Codec::H265, true); |
| 458 | } |
| 459 | |
| 460 | #[test] |
| 461 | fn vp9_matches_ffmpeg() { |
| 462 | compare_against_ffmpeg(&eight_bit(".ivf", "vp9"), Codec::Vp9, false); |
| 463 | } |
| 464 | |
| 465 | #[test] |
| 466 | fn vp9_10bit_matches_ffmpeg() { |
| 467 | compare_against_ffmpeg(&ten_bit(".ivf", "vp9"), Codec::Vp9, true); |
| 468 | } |
| 469 | |
| 470 | #[test] |
| 471 | fn av1_matches_ffmpeg() { |
| 472 | compare_against_ffmpeg(&eight_bit(".ivf", "av1"), Codec::Av1, false); |
| 473 | } |
| 474 | |
| 475 | #[test] |
| 476 | fn av1_10bit_matches_ffmpeg() { |
| 477 | compare_against_ffmpeg(&ten_bit(".ivf", "av1"), Codec::Av1, true); |
| 478 | } |
| 479 | |
| 480 | |
| 481 | |
| 482 | |
| 483 | |
| 484 | #[test] |
| 485 | fn unsupported_profiles_are_refused_with_a_reason() { |
| 486 | let Some(display) = display() else { return }; |
| 487 | let caps = ec_va::CapReport::probe(&display).expect("caps probe"); |
| 488 | for (file, codec, absent) in [ |
| 489 | ( |
| 490 | "vp9-profile1-444.ivf", |
| 491 | Codec::Vp9, |
| 492 | ec_va::caps::Profile::VP9Profile1, |
| 493 | ), |
| 494 | ( |
| 495 | "av1-profile1-444.ivf", |
| 496 | Codec::Av1, |
| 497 | ec_va::caps::Profile::AV1Profile1, |
| 498 | ), |
| 499 | ] { |
| 500 | let path = bitstreams().join(file); |
| 501 | if !path.exists() { |
| 502 | eprintln!("skipped: no {file}"); |
| 503 | continue; |
| 504 | } |
| 505 | assert!( |
| 506 | !caps.supports(absent, ec_va::caps::Entrypoint::VLD), |
| 507 | "{absent:?} is in fact supported — the refusal below would be a bug" |
| 508 | ); |
| 509 | let data = std::fs::read(&path).expect("fixture is readable"); |
| 510 | let mut decoder = Decoder::new(&display, codec).expect("decoder opens"); |
| 511 | let err = decode_stream(&mut decoder, codec, &data, 1, |_| {}) |
| 512 | .expect_err("a 4:4:4 stream must be refused"); |
| 513 | let message = err.to_string(); |
| 514 | assert!( |
| 515 | matches!(err, ec_hw::Error::Unsupported { .. }), |
| 516 | "{file}: expected a typed refusal, got {message}" |
| 517 | ); |
| 518 | println!("{file}: {message}"); |
| 519 | } |
| 520 | } |
| 521 | |
| 522 | |
| 523 | |
| 524 | |
| 525 | |
| 526 | |
| 527 | |
| 528 | fn source_frame(width: u32, height: u32, t: u32) -> I420 { |
| 529 | let (w, h) = (width as usize, height as usize); |
| 530 | let (cw, ch) = (w.div_ceil(2), h.div_ceil(2)); |
| 531 | let mut f = I420 { |
| 532 | y: vec![0; w * h], |
| 533 | u: vec![128; cw * ch], |
| 534 | v: vec![128; cw * ch], |
| 535 | width, |
| 536 | height, |
| 537 | }; |
| 538 | for y in 0..h { |
| 539 | for x in 0..w { |
| 540 | f.y[y * w + x] = ((x * 200 / w) + (y * 55 / h)) as u8; |
| 541 | } |
| 542 | } |
| 543 | let (bx, by) = ((t as usize * 7) % (w - 64), (t as usize * 5) % (h - 64)); |
| 544 | for y in by..by + 64 { |
| 545 | for x in bx..bx + 64 { |
| 546 | f.y[y * w + x] = 235; |
| 547 | } |
| 548 | } |
| 549 | for y in by / 2..(by + 64) / 2 { |
| 550 | for x in bx / 2..(bx + 64) / 2 { |
| 551 | f.u[y * cw + x] = 90; |
| 552 | f.v[y * cw + x] = 240; |
| 553 | } |
| 554 | } |
| 555 | f |
| 556 | } |
| 557 | |
| 558 | |
| 559 | fn encode_stream( |
| 560 | display: &Arc<Display>, |
| 561 | codec: EncCodec, |
| 562 | width: u32, |
| 563 | height: u32, |
| 564 | frames: u32, |
| 565 | ) -> Result<Vec<u8>, ec_hw::Error> { |
| 566 | let mut config = EncoderConfig::new(codec, width, height); |
| 567 | config.gop_size = 30; |
| 568 | config.framerate = (30, 1); |
| 569 | config.rate_control = RateControlMode::ConstantQp { qp: 26 }; |
| 570 | let mut encoder = Encoder::new(display, config)?; |
| 571 | let mut out = Vec::new(); |
| 572 | for t in 0..frames { |
| 573 | let coded = encoder.encode( |
| 574 | &source_frame(width, height, t), |
| 575 | FrameMetadata { |
| 576 | timestamp: i64::from(t), |
| 577 | force_keyframe: false, |
| 578 | }, |
| 579 | )?; |
| 580 | assert_eq!(coded.is_keyframe, t == 0, "GOP structure at frame {t}"); |
| 581 | out.extend_from_slice(&coded.data); |
| 582 | } |
| 583 | Ok(out) |
| 584 | } |
| 585 | |
| 586 | |
| 587 | fn round_trip(codec: EncCodec, width: u32, height: u32, min_db: f64) { |
| 588 | let Some(display) = display() else { return }; |
| 589 | let frames = 12u32; |
| 590 | let stream = match encode_stream(&display, codec, width, height, frames) { |
| 591 | Ok(stream) => stream, |
| 592 | Err(e) => panic!("{codec:?} encode failed: {e}"), |
| 593 | }; |
| 594 | assert!( |
| 595 | stream.len() > 1000, |
| 596 | "{codec:?}: {} bytes is not a stream", |
| 597 | stream.len() |
| 598 | ); |
| 599 | |
| 600 | let dir = std::env::temp_dir().join(format!("ec-hw-{codec:?}-{width}x{height}")); |
| 601 | std::fs::create_dir_all(&dir).expect("temp dir"); |
| 602 | let path = dir.join(match codec { |
| 603 | EncCodec::H264 => "out.264", |
| 604 | EncCodec::H265 => "out.265", |
| 605 | EncCodec::Av1 => "out.obu", |
| 606 | }); |
| 607 | std::fs::write(&path, &stream).expect("write bitstream"); |
| 608 | |
| 609 | |
| 610 | |
| 611 | let probe = Command::new("ffprobe") |
| 612 | .args([ |
| 613 | "-v", |
| 614 | "error", |
| 615 | "-select_streams", |
| 616 | "v:0", |
| 617 | "-show_entries", |
| 618 | "stream=width,height", |
| 619 | "-of", |
| 620 | "csv=p=0", |
| 621 | ]) |
| 622 | .arg(&path) |
| 623 | .output() |
| 624 | .expect("ffprobe runs"); |
| 625 | let dims = String::from_utf8_lossy(&probe.stdout).trim().to_string(); |
| 626 | assert_eq!( |
| 627 | dims, |
| 628 | format!("{width},{height}"), |
| 629 | "{codec:?}: ffprobe sees {dims}" |
| 630 | ); |
| 631 | |
| 632 | let mut reference = Reference::open(&path, width, height, false).expect("ffmpeg runs"); |
| 633 | let mut worst = f64::INFINITY; |
| 634 | let mut compared = 0u32; |
| 635 | for t in 0..frames { |
| 636 | let Some(got) = reference.next(width, height) else { |
| 637 | break; |
| 638 | }; |
| 639 | let want = Planes::from_8bit(&source_frame(width, height, t)); |
| 640 | let db = psnr(&got, &want); |
| 641 | worst = worst.min(db); |
| 642 | compared += 1; |
| 643 | } |
| 644 | assert_eq!( |
| 645 | compared, frames, |
| 646 | "{codec:?}: ffmpeg decoded {compared} of {frames}" |
| 647 | ); |
| 648 | println!( |
| 649 | "{codec:?} {width}x{height}: {compared} frames, {} bytes, worst {worst:.1} dB vs source", |
| 650 | stream.len() |
| 651 | ); |
| 652 | assert!( |
| 653 | worst >= min_db, |
| 654 | "{codec:?}: worst frame {worst:.1} dB against the source" |
| 655 | ); |
| 656 | } |
| 657 | |
| 658 | #[test] |
| 659 | fn h264_encode_round_trips_through_ffmpeg() { |
| 660 | round_trip(EncCodec::H264, 640, 480, 30.0); |
| 661 | } |
| 662 | |
| 663 | #[test] |
| 664 | fn hevc_encode_round_trips_through_ffmpeg() { |
| 665 | round_trip(EncCodec::H265, 640, 480, 30.0); |
| 666 | } |
| 667 | |
| 668 | |
| 669 | |
| 670 | #[test] |
| 671 | fn hevc_encode_honours_the_conformance_window() { |
| 672 | round_trip(EncCodec::H265, 1916, 1080, 30.0); |
| 673 | } |
| 674 | |
| 675 | |
| 676 | #[test] |
| 677 | fn our_encoder_and_our_decoder_agree() { |
| 678 | let Some(display) = display() else { return }; |
| 679 | for (enc, dec) in [(EncCodec::H264, Codec::H264), (EncCodec::H265, Codec::H265)] { |
| 680 | let stream = encode_stream(&display, enc, 640, 480, 12).expect("encode"); |
| 681 | let mut decoder = Decoder::new(&display, dec).expect("decoder opens"); |
| 682 | let mut worst = f64::INFINITY; |
| 683 | let mut count = 0u32; |
| 684 | decode_stream(&mut decoder, dec, &stream, 12, |frame| { |
| 685 | let got = Planes::from_8bit(&frame.to_i420().expect("readback")); |
| 686 | let want = Planes::from_8bit(&source_frame(640, 480, count)); |
| 687 | worst = worst.min(psnr(&got, &want)); |
| 688 | count += 1; |
| 689 | }) |
| 690 | .expect("decode"); |
| 691 | assert_eq!(count, 12, "{enc:?}: decoded {count} of 12 frames"); |
| 692 | println!("{enc:?} -> our decoder: {count} frames, worst {worst:.1} dB vs source"); |
| 693 | assert!(worst >= 30.0, "{enc:?}: worst {worst:.1} dB"); |
| 694 | } |
| 695 | } |
| 696 | |
| 697 | |
| 698 | |
| 699 | |
| 700 | |
| 701 | |
| 702 | |
| 703 | |
| 704 | |
| 705 | #[test] |
| 706 | fn encode_frame_zero_copy_matches_the_cpu_path() { |
| 707 | let Some(display) = display() else { return }; |
| 708 | let (width, height) = (1920u32, 1080u32); |
| 709 | let Some(path) = fixtures(".264") |
| 710 | .into_iter() |
| 711 | .find(|p| p.file_name().and_then(|n| n.to_str()) == Some("h264-1080p-23.976-8bit.264")) |
| 712 | else { |
| 713 | eprintln!("skipped: no h264-1080p fixture — run scripts/gen-bitstream-fixtures.sh"); |
| 714 | return; |
| 715 | }; |
| 716 | let data = std::fs::read(&path).expect("fixture is readable"); |
| 717 | let frames = 10usize; |
| 718 | |
| 719 | for (target, dec_codec) in [(EncCodec::H264, Codec::H264), (EncCodec::H265, Codec::H265)] { |
| 720 | let mut cfg = EncoderConfig::new(target, width, height); |
| 721 | cfg.gop_size = 30; |
| 722 | cfg.rate_control = RateControlMode::ConstantQp { qp: 22 }; |
| 723 | let mut zero_copy = Encoder::new(&display, cfg).expect("zero-copy encoder opens"); |
| 724 | let mut cpu_path = Encoder::new(&display, cfg).expect("cpu-path encoder opens"); |
| 725 | let mut zc_stream = Vec::new(); |
| 726 | let mut cpu_stream = Vec::new(); |
| 727 | let mut count = 0i64; |
| 728 | |
| 729 | let mut decoder = Decoder::new(&display, Codec::H264).expect("decoder opens"); |
| 730 | decode_stream(&mut decoder, Codec::H264, &data, frames, |frame| { |
| 731 | let meta = FrameMetadata { |
| 732 | timestamp: count, |
| 733 | force_keyframe: false, |
| 734 | }; |
| 735 | |
| 736 | |
| 737 | let zc = zero_copy |
| 738 | .encode_frame(&frame, meta) |
| 739 | .expect("encode_frame (zero copy)"); |
| 740 | zc_stream.extend_from_slice(&zc.data); |
| 741 | let i420 = frame.to_i420().expect("readback for the CPU-path baseline"); |
| 742 | let cpu = cpu_path.encode(&i420, meta).expect("encode (CPU path)"); |
| 743 | cpu_stream.extend_from_slice(&cpu.data); |
| 744 | count += 1; |
| 745 | }) |
| 746 | .expect("decode"); |
| 747 | assert_eq!( |
| 748 | count as usize, frames, |
| 749 | "{target:?}: decoded {count} of {frames}" |
| 750 | ); |
| 751 | |
| 752 | let ext = match target { |
| 753 | EncCodec::H264 => "264", |
| 754 | EncCodec::H265 => "265", |
| 755 | EncCodec::Av1 => unreachable!("AV1 is not in this test's target list"), |
| 756 | }; |
| 757 | let dir = std::env::temp_dir().join("ec-hw-encode-frame-zero-copy"); |
| 758 | std::fs::create_dir_all(&dir).expect("temp dir"); |
| 759 | for (name, bytes) in [("zc", &zc_stream), ("cpu", &cpu_stream)] { |
| 760 | std::fs::write(dir.join(format!("{name}.{ext}")), bytes).expect("write bitstream"); |
| 761 | } |
| 762 | |
| 763 | let mut zc_decoder = Decoder::new(&display, dec_codec).expect("zc decoder opens"); |
| 764 | let mut cpu_decoder = Decoder::new(&display, dec_codec).expect("cpu decoder opens"); |
| 765 | let mut zc_frames = Vec::new(); |
| 766 | let mut cpu_frames = Vec::new(); |
| 767 | decode_stream(&mut zc_decoder, dec_codec, &zc_stream, frames, |f| { |
| 768 | zc_frames.push(Planes::from_8bit(&f.to_i420().expect("readback"))) |
| 769 | }) |
| 770 | .expect("decode zero-copy stream"); |
| 771 | decode_stream(&mut cpu_decoder, dec_codec, &cpu_stream, frames, |f| { |
| 772 | cpu_frames.push(Planes::from_8bit(&f.to_i420().expect("readback"))) |
| 773 | }) |
| 774 | .expect("decode CPU-path stream"); |
| 775 | assert_eq!( |
| 776 | zc_frames.len(), |
| 777 | frames, |
| 778 | "{target:?}: zero-copy stream frame count" |
| 779 | ); |
| 780 | assert_eq!( |
| 781 | cpu_frames.len(), |
| 782 | frames, |
| 783 | "{target:?}: CPU-path stream frame count" |
| 784 | ); |
| 785 | |
| 786 | let worst = zc_frames |
| 787 | .iter() |
| 788 | .zip(&cpu_frames) |
| 789 | .map(|(a, b)| psnr(a, b)) |
| 790 | .fold(f64::INFINITY, f64::min); |
| 791 | println!("{target:?} encode_frame vs CPU path: worst {worst:.1} dB"); |
| 792 | assert!( |
| 793 | worst >= 35.0, |
| 794 | "{target:?}: worst {worst:.1} dB vs the CPU path" |
| 795 | ); |
| 796 | } |
| 797 | } |
| 798 | |
| 799 | |
| 800 | |
| 801 | |
| 802 | |
| 803 | |
| 804 | #[test] |
| 805 | fn colour_description_reaches_the_vui() { |
| 806 | let Some(display) = display() else { return }; |
| 807 | let (width, height) = (640u32, 480u32); |
| 808 | let dir = std::env::temp_dir().join("ec-hw-colour-vui"); |
| 809 | std::fs::create_dir_all(&dir).expect("temp dir"); |
| 810 | |
| 811 | let encode_one = |colour: Option<(u8, u8, u8, bool)>, name: &str| -> (PathBuf, Vec<u8>) { |
| 812 | let mut cfg = EncoderConfig::new(EncCodec::H265, width, height); |
| 813 | cfg.rate_control = RateControlMode::ConstantQp { qp: 26 }; |
| 814 | if let Some((primaries, transfer, matrix, full_range)) = colour { |
| 815 | cfg = cfg.colour(primaries, transfer, matrix, full_range); |
| 816 | } |
| 817 | let mut enc = Encoder::new(&display, cfg).expect("encoder opens"); |
| 818 | let coded = enc |
| 819 | .encode( |
| 820 | &source_frame(width, height, 0), |
| 821 | FrameMetadata { |
| 822 | timestamp: 0, |
| 823 | force_keyframe: true, |
| 824 | }, |
| 825 | ) |
| 826 | .expect("encode"); |
| 827 | let path = dir.join(name); |
| 828 | std::fs::write(&path, &coded.data).expect("write bitstream"); |
| 829 | (path, coded.data) |
| 830 | }; |
| 831 | let probe = |path: &Path| -> String { |
| 832 | let out = Command::new("ffprobe") |
| 833 | .args([ |
| 834 | "-v", |
| 835 | "error", |
| 836 | "-select_streams", |
| 837 | "v:0", |
| 838 | "-show_entries", |
| 839 | "stream=color_primaries,color_transfer,color_space", |
| 840 | "-of", |
| 841 | "csv=p=0", |
| 842 | ]) |
| 843 | .arg(path) |
| 844 | .output() |
| 845 | .expect("ffprobe runs"); |
| 846 | String::from_utf8_lossy(&out.stdout).trim().to_string() |
| 847 | }; |
| 848 | |
| 849 | |
| 850 | let (default_path, default_bytes) = encode_one(None, "default-a.265"); |
| 851 | let (_, default_bytes2) = encode_one(None, "default-b.265"); |
| 852 | assert_eq!( |
| 853 | default_bytes, default_bytes2, |
| 854 | "no colour set: two encodes of the same picture must be byte-identical" |
| 855 | ); |
| 856 | let default_probe = probe(&default_path); |
| 857 | println!("no colour set: ffprobe sees `{default_probe}`"); |
| 858 | assert!( |
| 859 | !default_probe.contains("bt2020"), |
| 860 | "no colour set should not read back as BT.2020: `{default_probe}`" |
| 861 | ); |
| 862 | |
| 863 | |
| 864 | let (bt2020_path, _) = encode_one(Some((9, 16, 9, false)), "bt2020.265"); |
| 865 | |
| 866 | |
| 867 | let got = probe(&bt2020_path); |
| 868 | assert_eq!( |
| 869 | got, "bt2020nc,smpte2084,bt2020", |
| 870 | "ffprobe on the BT.2020 stream" |
| 871 | ); |
| 872 | } |
| 873 | |
| 874 | |
| 875 | |
| 876 | |
| 877 | |
| 878 | |
| 879 | |
| 880 | |
| 881 | |
| 882 | |
| 883 | |
| 884 | |
| 885 | |
| 886 | |
| 887 | |
| 888 | #[test] |
| 889 | fn av1_encode_agrees_between_two_decoders() { |
| 890 | let Some(display) = display() else { return }; |
| 891 | let dir = std::env::temp_dir().join("ec-hw-av1-encode"); |
| 892 | let _ = std::fs::create_dir_all(&dir); |
| 893 | for (width, height, frames) in [(640u32, 384u32, 10u32), (1920, 1080, 10)] { |
| 894 | let data = match encode_stream(&display, EncCodec::Av1, width, height, frames) { |
| 895 | Ok(data) => data, |
| 896 | Err(e) => { |
| 897 | eprintln!("skipped: AV1 encode unavailable ({e})"); |
| 898 | return; |
| 899 | } |
| 900 | }; |
| 901 | let path = dir.join(format!("hw-{width}x{height}.obu")); |
| 902 | std::fs::write(&path, &data).expect("write the coded stream"); |
| 903 | |
| 904 | |
| 905 | let ours = ec_av1::stream::decode_stream(&data) |
| 906 | .unwrap_or_else(|e| panic!("ec-av1 decodes the {width}x{height} hardware stream: {e}")); |
| 907 | assert_eq!( |
| 908 | ours.len(), |
| 909 | frames as usize, |
| 910 | "{width}x{height}: ec-av1 decoded {} of {frames} shown frames", |
| 911 | ours.len() |
| 912 | ); |
| 913 | |
| 914 | |
| 915 | let mut reference = |
| 916 | Reference::open(&path, width, height, false).expect("ffmpeg opens the stream"); |
| 917 | let mut worst = f64::INFINITY; |
| 918 | for (i, picture) in ours.iter().enumerate() { |
| 919 | let theirs = reference |
| 920 | .next(width, height) |
| 921 | .unwrap_or_else(|| panic!("{width}x{height}: ffmpeg has no frame {i}")); |
| 922 | let mine = Planes { |
| 923 | y: picture.y.clone(), |
| 924 | u: picture.u.clone(), |
| 925 | v: picture.v.clone(), |
| 926 | peak: 255.0, |
| 927 | }; |
| 928 | let db = psnr(&mine, &theirs); |
| 929 | assert!( |
| 930 | db.is_infinite(), |
| 931 | "{width}x{height} frame {i}: the two decoders disagree ({db:.2} dB)" |
| 932 | ); |
| 933 | |
| 934 | |
| 935 | let source = Planes::from_8bit(&source_frame(width, height, i as u32)); |
| 936 | let fidelity = psnr(&mine, &source); |
| 937 | assert!( |
| 938 | fidelity > 30.0, |
| 939 | "{width}x{height} frame {i}: coded {fidelity:.2} dB from the source" |
| 940 | ); |
| 941 | worst = worst.min(fidelity); |
| 942 | } |
| 943 | println!( |
| 944 | "AV1 encode {width}x{height}: {frames} frames, {} bytes, ec-av1 and libdav1d agree \ |
| 945 | sample for sample, worst frame {worst:.2} dB from the source", |
| 946 | data.len() |
| 947 | ); |
| 948 | } |
| 949 | } |
| 950 | |
| 951 | |
| 952 | |
| 953 | |
| 954 | |
| 955 | |
| 956 | |
| 957 | |
| 958 | |
| 959 | fn ten_bit_film_clip() -> Option<(PathBuf, String, u32, u32, u32, u32)> { |
| 960 | let manifest = |
| 961 | Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/real-library-manifest.tsv"); |
| 962 | let text = std::fs::read_to_string(manifest).ok()?; |
| 963 | for line in text.lines().skip(1) { |
| 964 | let f: Vec<&str> = line.split('\t').collect(); |
| 965 | if f.len() < 7 || f[2] != "av1" || f[5] != "yuv420p10le" || f[3] != "3840" { |
| 966 | continue; |
| 967 | } |
| 968 | let path = PathBuf::from(f[0]); |
| 969 | if !path.exists() { |
| 970 | continue; |
| 971 | } |
| 972 | let (nw, nh): (u32, u32) = (f[3].parse().ok()?, f[4].parse().ok()?); |
| 973 | let (cw, ch) = (nw.min(1920) / 128 * 128, nh.min(1024) / 128 * 128); |
| 974 | return Some((path, "00:40:00".into(), cw, ch, (nw - cw) / 2 & !1, (nh - ch) / 2 & !1)); |
| 975 | } |
| 976 | None |
| 977 | } |
| 978 | |
| 979 | |
| 980 | |
| 981 | |
| 982 | fn source_frame_16(width: u32, height: u32, t: u32) -> I420_16 { |
| 983 | let (w, h) = (width as usize, height as usize); |
| 984 | let (cw, ch) = (w.div_ceil(2), h.div_ceil(2)); |
| 985 | let mut f = I420_16 { |
| 986 | y: vec![0; w * h], |
| 987 | u: vec![512; cw * ch], |
| 988 | v: vec![512; cw * ch], |
| 989 | width, |
| 990 | height, |
| 991 | bit_depth: 10, |
| 992 | }; |
| 993 | for y in 0..h { |
| 994 | for x in 0..w { |
| 995 | f.y[y * w + x] = (64 + x * 700 / w + y * 176 / h) as u16; |
| 996 | } |
| 997 | } |
| 998 | let (bx, by) = ((t as usize * 7) % (w - 64), (t as usize * 5) % (h - 64)); |
| 999 | for y in by..by + 64 { |
| 1000 | for x in bx..bx + 64 { |
| 1001 | f.y[y * w + x] = 940; |
| 1002 | } |
| 1003 | } |
| 1004 | for y in by / 2..(by + 64) / 2 { |
| 1005 | for x in bx / 2..(bx + 64) / 2 { |
| 1006 | f.u[y * cw + x] = 360; |
| 1007 | f.v[y * cw + x] = 960; |
| 1008 | } |
| 1009 | } |
| 1010 | f |
| 1011 | } |
| 1012 | |
| 1013 | |
| 1014 | fn write_y4m_16(path: &Path, frames: &[I420_16], fps: (u32, u32)) -> bool { |
| 1015 | use std::io::Write; |
| 1016 | let Ok(file) = std::fs::File::create(path) else { |
| 1017 | return false; |
| 1018 | }; |
| 1019 | let mut out = std::io::BufWriter::new(file); |
| 1020 | let (w, h) = (frames[0].width, frames[0].height); |
| 1021 | if write!(out, "YUV4MPEG2 W{w} H{h} F{}:{} Ip A1:1 C420p10\n", fps.0, fps.1).is_err() { |
| 1022 | return false; |
| 1023 | } |
| 1024 | for f in frames { |
| 1025 | if out.write_all(b"FRAME\n").is_err() { |
| 1026 | return false; |
| 1027 | } |
| 1028 | for plane in [&f.y, &f.u, &f.v] { |
| 1029 | let bytes: Vec<u8> = plane.iter().flat_map(|s| s.to_le_bytes()).collect(); |
| 1030 | if out.write_all(&bytes).is_err() { |
| 1031 | return false; |
| 1032 | } |
| 1033 | } |
| 1034 | } |
| 1035 | out.flush().is_ok() |
| 1036 | } |
| 1037 | |
| 1038 | |
| 1039 | |
| 1040 | |
| 1041 | |
| 1042 | fn ten_bit_source(dir: &Path, frames: u32) -> Option<(String, PathBuf, Vec<I420_16>)> { |
| 1043 | let y4m = dir.join("source-10bit.y4m"); |
| 1044 | let _ = std::fs::remove_file(&y4m); |
| 1045 | if let Some((path, seek, cw, ch, x, y)) = ten_bit_film_clip() { |
| 1046 | let ok = Command::new("ffmpeg") |
| 1047 | .args(["-nostdin", "-v", "error", "-y", "-ss", &seek, "-i"]) |
| 1048 | .arg(&path) |
| 1049 | .args([ |
| 1050 | "-frames:v", |
| 1051 | &frames.to_string(), |
| 1052 | "-vf", |
| 1053 | &format!("crop={cw}:{ch}:{x}:{y}"), |
| 1054 | "-pix_fmt", |
| 1055 | "yuv420p10le", |
| 1056 | |
| 1057 | "-strict", |
| 1058 | "-1", |
| 1059 | ]) |
| 1060 | .arg(&y4m) |
| 1061 | .status() |
| 1062 | .is_ok_and(|s| s.success()); |
| 1063 | if ok && let Some(planes) = raw_frames_16(&y4m, cw, ch, frames) { |
| 1064 | return Some(("film B 10-bit native crop".into(), y4m, planes)); |
| 1065 | } |
| 1066 | eprintln!("film B 10-bit extraction failed; falling back to the synthetic gradient"); |
| 1067 | } |
| 1068 | let (w, h) = (1920u32, 1024u32); |
| 1069 | let planes: Vec<I420_16> = (0..frames).map(|t| source_frame_16(w, h, t)).collect(); |
| 1070 | write_y4m_16(&y4m, &planes, (24, 1)).then_some(("synthetic 10-bit gradient".into(), y4m, planes)) |
| 1071 | } |
| 1072 | |
| 1073 | |
| 1074 | fn raw_frames_16(y4m: &Path, width: u32, height: u32, frames: u32) -> Option<Vec<I420_16>> { |
| 1075 | let out = Command::new("ffmpeg") |
| 1076 | .args(["-nostdin", "-v", "error", "-i"]) |
| 1077 | .arg(y4m) |
| 1078 | .args(["-pix_fmt", "yuv420p10le", "-f", "rawvideo", "-"]) |
| 1079 | .stderr(Stdio::null()) |
| 1080 | .output() |
| 1081 | .ok()?; |
| 1082 | let (w, h) = (width as usize, height as usize); |
| 1083 | let (cw, ch) = (w.div_ceil(2), h.div_ceil(2)); |
| 1084 | let frame_len = (w * h + 2 * cw * ch) * 2; |
| 1085 | let read = |s: &[u8]| -> Vec<u16> { |
| 1086 | s.chunks_exact(2).map(|p| u16::from_le_bytes([p[0], p[1]])).collect() |
| 1087 | }; |
| 1088 | let mut pictures = Vec::new(); |
| 1089 | for chunk in out.stdout.chunks_exact(frame_len).take(frames as usize) { |
| 1090 | let (y, rest) = chunk.split_at(w * h * 2); |
| 1091 | let (u, v) = rest.split_at(cw * ch * 2); |
| 1092 | pictures.push(I420_16 { |
| 1093 | y: read(y), |
| 1094 | u: read(u), |
| 1095 | v: read(v), |
| 1096 | width, |
| 1097 | height, |
| 1098 | bit_depth: 10, |
| 1099 | }); |
| 1100 | } |
| 1101 | (!pictures.is_empty()).then_some(pictures) |
| 1102 | } |
| 1103 | |
| 1104 | |
| 1105 | |
| 1106 | |
| 1107 | fn ffprobe_pix_fmt(path: &Path) -> Option<String> { |
| 1108 | let out = Command::new("ffprobe") |
| 1109 | .args([ |
| 1110 | "-v", "error", "-select_streams", "v:0", "-show_entries", |
| 1111 | "stream=pix_fmt", "-of", "default=nw=1:nk=1", "-f", "obu", |
| 1112 | ]) |
| 1113 | .arg(path) |
| 1114 | .output() |
| 1115 | .ok()?; |
| 1116 | Some(String::from_utf8_lossy(&out.stdout).trim().to_string()).filter(|s| !s.is_empty()) |
| 1117 | } |
| 1118 | |
| 1119 | |
| 1120 | fn encode_stream_16( |
| 1121 | display: &Arc<Display>, |
| 1122 | planes: &[I420_16], |
| 1123 | qp: u32, |
| 1124 | rate_control: RateControlMode, |
| 1125 | ) -> Result<Vec<u8>, ec_hw::Error> { |
| 1126 | let (width, height) = (planes[0].width, planes[0].height); |
| 1127 | let mut config = EncoderConfig::new(EncCodec::Av1, width, height).ten_bit(); |
| 1128 | config.gop_size = 60; |
| 1129 | config.framerate = (24, 1); |
| 1130 | config.rate_control = match rate_control { |
| 1131 | RateControlMode::ConstantQp { .. } => RateControlMode::ConstantQp { qp }, |
| 1132 | other => other, |
| 1133 | }; |
| 1134 | let mut encoder = Encoder::new(display, config)?; |
| 1135 | let mut out = Vec::new(); |
| 1136 | for (t, frame) in planes.iter().enumerate() { |
| 1137 | let coded = encoder.encode_16( |
| 1138 | frame, |
| 1139 | FrameMetadata { timestamp: t as i64, force_keyframe: false }, |
| 1140 | )?; |
| 1141 | out.extend_from_slice(&coded.data); |
| 1142 | } |
| 1143 | Ok(out) |
| 1144 | } |
| 1145 | |
| 1146 | |
| 1147 | |
| 1148 | |
| 1149 | |
| 1150 | |
| 1151 | |
| 1152 | |
| 1153 | #[test] |
| 1154 | fn av1_10bit_encode_agrees_between_two_decoders() { |
| 1155 | let Some(display) = display() else { return }; |
| 1156 | let dir = std::env::temp_dir().join("ec-hw-av1-10bit"); |
| 1157 | let _ = std::fs::create_dir_all(&dir); |
| 1158 | let frames = 10u32; |
| 1159 | let Some((label, y4m, planes)) = ten_bit_source(&dir, frames) else { |
| 1160 | eprintln!("skipped: no 10-bit source could be built"); |
| 1161 | return; |
| 1162 | }; |
| 1163 | let _ = y4m; |
| 1164 | let (width, height) = (planes[0].width, planes[0].height); |
| 1165 | let data = match encode_stream_16( |
| 1166 | &display, |
| 1167 | &planes, |
| 1168 | 90, |
| 1169 | RateControlMode::ConstantQp { qp: 90 }, |
| 1170 | ) { |
| 1171 | Ok(data) => data, |
| 1172 | Err(e) => { |
| 1173 | eprintln!("skipped: 10-bit AV1 encode unavailable ({e})"); |
| 1174 | return; |
| 1175 | } |
| 1176 | }; |
| 1177 | let path = dir.join("hw-10bit.obu"); |
| 1178 | std::fs::write(&path, &data).expect("write the coded stream"); |
| 1179 | |
| 1180 | assert_eq!( |
| 1181 | ffprobe_pix_fmt(&path).as_deref(), |
| 1182 | Some("yuv420p10le"), |
| 1183 | "the coded stream's sequence header does not say 10-bit" |
| 1184 | ); |
| 1185 | |
| 1186 | |
| 1187 | |
| 1188 | |
| 1189 | let ten_bit_hevc = EncoderConfig::new(EncCodec::H265, width, height).ten_bit(); |
| 1190 | assert!( |
| 1191 | Encoder::new(&display, ten_bit_hevc).is_err(), |
| 1192 | "a 10-bit HEVC encoder was built out of an 8-bit profile" |
| 1193 | ); |
| 1194 | let mut config = EncoderConfig::new(EncCodec::Av1, width, height).ten_bit(); |
| 1195 | config.rate_control = RateControlMode::ConstantQp { qp: 90 }; |
| 1196 | let mut ten = Encoder::new(&display, config).expect("a 10-bit AV1 encoder"); |
| 1197 | assert!( |
| 1198 | ten.encode(&source_frame(width, height, 0), FrameMetadata::default()).is_err(), |
| 1199 | "8-bit pixels went into a 10-bit encoder" |
| 1200 | ); |
| 1201 | |
| 1202 | let ours = ec_av1::stream::decode_stream(&data) |
| 1203 | .unwrap_or_else(|e| panic!("ec-av1 decodes the 10-bit hardware stream: {e}")); |
| 1204 | assert_eq!(ours.len(), planes.len(), "ec-av1 decoded {} of {frames} frames", ours.len()); |
| 1205 | let peak = ours.iter().flat_map(|p| p.y.iter()).copied().max().unwrap_or(0); |
| 1206 | assert!(peak > 255, "every decoded luma sample fits in 8 bits (peak {peak})"); |
| 1207 | |
| 1208 | let mut reference = |
| 1209 | Reference::open(&path, width, height, true).expect("ffmpeg opens the stream"); |
| 1210 | let mut worst = f64::INFINITY; |
| 1211 | for (i, picture) in ours.iter().enumerate() { |
| 1212 | let theirs = reference |
| 1213 | .next(width, height) |
| 1214 | .unwrap_or_else(|| panic!("ffmpeg has no frame {i}")); |
| 1215 | let mine = Planes { |
| 1216 | y: picture.y.clone(), |
| 1217 | u: picture.u.clone(), |
| 1218 | v: picture.v.clone(), |
| 1219 | peak: 1023.0, |
| 1220 | }; |
| 1221 | let db = psnr(&mine, &theirs); |
| 1222 | assert!(db.is_infinite(), "frame {i}: the two decoders disagree ({db:.2} dB)"); |
| 1223 | let source = Planes::from_16bit(&planes[i]); |
| 1224 | let fidelity = psnr(&mine, &source); |
| 1225 | assert!(fidelity > 30.0, "frame {i}: coded {fidelity:.2} dB from the 10-bit source"); |
| 1226 | worst = worst.min(fidelity); |
| 1227 | } |
| 1228 | println!( |
| 1229 | "AV1 10-bit encode {width}x{height} ({label}): {frames} frames, {} bytes, pix_fmt \ |
| 1230 | yuv420p10le, CQP 90, decoded peak luma {peak}, ec-av1 and libdav1d agree sample for \ |
| 1231 | sample, worst frame {worst:.2} dB from the source (10-bit domain)", |
| 1232 | data.len() |
| 1233 | ); |
| 1234 | } |
| 1235 | |
| 1236 | |
| 1237 | |
| 1238 | |
| 1239 | |
| 1240 | |
| 1241 | |
| 1242 | |
| 1243 | |
| 1244 | |
| 1245 | #[test] |
| 1246 | fn av1_encode_rate_control_lands() { |
| 1247 | let Some(display) = display() else { return }; |
| 1248 | let clips = real_clips(); |
| 1249 | let Some((label, source)) = clips.into_iter().next() else { |
| 1250 | eprintln!("skipped: no real-library manifest"); |
| 1251 | return; |
| 1252 | }; |
| 1253 | let dir = std::env::temp_dir().join("ec-hw-av1-rc"); |
| 1254 | let _ = std::fs::create_dir_all(&dir); |
| 1255 | let (width, height, frames, fps) = (1920u32, 1080u32, 60u32, 30u32); |
| 1256 | let y4m = dir.join("rc-source.y4m"); |
| 1257 | if !extract_y4m(&source, &y4m, width, height, frames) { |
| 1258 | eprintln!("skipped {label}: extraction failed"); |
| 1259 | return; |
| 1260 | } |
| 1261 | let Some(planes) = raw_frames(&y4m, width, height, frames) else { |
| 1262 | eprintln!("skipped {label}: no frames extracted"); |
| 1263 | return; |
| 1264 | }; |
| 1265 | |
| 1266 | println!("AV1 rate control on {label}, {width}x{height} yuv420p, {} frames at {fps} fps:", planes.len()); |
| 1267 | |
| 1268 | |
| 1269 | |
| 1270 | enum Ask { |
| 1271 | Within(f64), |
| 1272 | Ceiling, |
| 1273 | } |
| 1274 | for (mode_name, mode, ask) in [ |
| 1275 | ("CBR", RateControlMode::ConstantBitrate, Ask::Within(0.15)), |
| 1276 | ("VBR", RateControlMode::VariableBitrate, Ask::Within(0.25)), |
| 1277 | ("QVBR", RateControlMode::Qvbr { quality: 100 }, Ask::Ceiling), |
| 1278 | ] { |
| 1279 | let mut table: Vec<(u32, f64, f64)> = Vec::new(); |
| 1280 | for target in [2_000_000u32, 6_000_000, 12_000_000] { |
| 1281 | let mut config = EncoderConfig::new(EncCodec::Av1, width, height); |
| 1282 | config.framerate = (fps, 1); |
| 1283 | config.gop_size = 60; |
| 1284 | config.bitrate = target; |
| 1285 | config.rate_control = mode; |
| 1286 | let mut encoder = match Encoder::new(&display, config) { |
| 1287 | Ok(encoder) => encoder, |
| 1288 | Err(e) => { |
| 1289 | |
| 1290 | |
| 1291 | eprintln!(" {mode_name}: refused by the driver ({e})"); |
| 1292 | break; |
| 1293 | } |
| 1294 | }; |
| 1295 | let mut bytes = Vec::new(); |
| 1296 | for (i, frame) in planes.iter().enumerate() { |
| 1297 | match encoder.encode( |
| 1298 | frame, |
| 1299 | FrameMetadata { timestamp: i as i64, force_keyframe: false }, |
| 1300 | ) { |
| 1301 | Ok(coded) => bytes.extend_from_slice(&coded.data), |
| 1302 | Err(e) => panic!("{mode_name} at {target} bps: encode failed ({e})"), |
| 1303 | } |
| 1304 | } |
| 1305 | let path = dir.join(format!("{mode_name}-{target}.obu")); |
| 1306 | std::fs::write(&path, &bytes).expect("write"); |
| 1307 | let delivered = |
| 1308 | bytes.len() as f64 * 8.0 * f64::from(fps) / f64::from(planes.len() as u32); |
| 1309 | let db = ffmpeg_psnr_at(&path, &y4m, fps).unwrap_or(f64::NAN); |
| 1310 | println!( |
| 1311 | " {mode_name} target {:>5} kbps -> delivered {:>6.0} kbps ({:+.1}%), {db:.2} dB", |
| 1312 | target / 1000, |
| 1313 | delivered / 1000.0, |
| 1314 | (delivered / f64::from(target) - 1.0) * 100.0 |
| 1315 | ); |
| 1316 | table.push((target, delivered, db)); |
| 1317 | } |
| 1318 | if table.len() < 3 { |
| 1319 | continue; |
| 1320 | } |
| 1321 | match ask { |
| 1322 | Ask::Within(tolerance) => { |
| 1323 | for &(target, delivered, _) in &table { |
| 1324 | let error = delivered / f64::from(target) - 1.0; |
| 1325 | assert!( |
| 1326 | error.abs() <= tolerance, |
| 1327 | "{mode_name} at {target} bps delivered {delivered:.0} bps ({:+.1}%), \ |
| 1328 | outside +/-{:.0}%", |
| 1329 | error * 100.0, |
| 1330 | tolerance * 100.0 |
| 1331 | ); |
| 1332 | } |
| 1333 | for pair in table.windows(2) { |
| 1334 | assert!( |
| 1335 | pair[1].2 > pair[0].2, |
| 1336 | "{mode_name}: PSNR is not monotone in the target ({:?} then {:?})", |
| 1337 | pair[0], |
| 1338 | pair[1] |
| 1339 | ); |
| 1340 | } |
| 1341 | } |
| 1342 | Ask::Ceiling => { |
| 1343 | for &(target, delivered, _) in &table { |
| 1344 | assert!( |
| 1345 | delivered <= f64::from(target) * 1.1, |
| 1346 | "{mode_name} at a {target} bps ceiling delivered {delivered:.0} bps" |
| 1347 | ); |
| 1348 | } |
| 1349 | } |
| 1350 | } |
| 1351 | } |
| 1352 | } |
| 1353 | |
| 1354 | |
| 1355 | fn ffmpeg_psnr_at(coded: &Path, source: &Path, fps: u32) -> Option<f64> { |
| 1356 | let rate = fps.to_string(); |
| 1357 | let out = Command::new("ffmpeg") |
| 1358 | .args(["-nostdin", "-v", "info", "-f", "obu", "-r", &rate]) |
| 1359 | .arg("-i") |
| 1360 | .arg(coded) |
| 1361 | .args(["-r", &rate]) |
| 1362 | .arg("-i") |
| 1363 | .arg(source) |
| 1364 | .args(["-lavfi", "psnr", "-f", "null", "-"]) |
| 1365 | .output() |
| 1366 | .ok()?; |
| 1367 | let text = String::from_utf8_lossy(&out.stderr); |
| 1368 | let field = text.split("average:").nth(1)?; |
| 1369 | field.split_whitespace().next()?.parse::<f64>().ok().filter(|v| v.is_finite()) |
| 1370 | } |
| 1371 | |
| 1372 | |
| 1373 | |
| 1374 | |
| 1375 | |
| 1376 | |
| 1377 | |
| 1378 | |
| 1379 | #[test] |
| 1380 | fn av1_10bit_bd_row_vs_software() { |
| 1381 | let Some(display) = display() else { return }; |
| 1382 | let dir = std::env::temp_dir().join("ec-hw-av1-10bit-bd"); |
| 1383 | let _ = std::fs::create_dir_all(&dir); |
| 1384 | let frames = 12u32; |
| 1385 | let Some((label, y4m, planes)) = ten_bit_source(&dir, frames) else { |
| 1386 | eprintln!("skipped: no 10-bit source could be built"); |
| 1387 | return; |
| 1388 | }; |
| 1389 | if !label.starts_with("film") { |
| 1390 | eprintln!("skipped: no 10-bit film in the real-library manifest ({label})"); |
| 1391 | return; |
| 1392 | } |
| 1393 | let (width, height) = (planes[0].width, planes[0].height); |
| 1394 | let coded = planes.len() as u32; |
| 1395 | |
| 1396 | let mut ours = Vec::new(); |
| 1397 | for qp in [180u32, 140, 100, 60] { |
| 1398 | let data = match encode_stream_16( |
| 1399 | &display, |
| 1400 | &planes, |
| 1401 | qp, |
| 1402 | RateControlMode::ConstantQp { qp }, |
| 1403 | ) { |
| 1404 | Ok(data) => data, |
| 1405 | Err(e) => { |
| 1406 | eprintln!("skipped: 10-bit AV1 encode unavailable ({e})"); |
| 1407 | return; |
| 1408 | } |
| 1409 | }; |
| 1410 | let path = dir.join(format!("hw10-{qp}.obu")); |
| 1411 | std::fs::write(&path, &data).expect("write"); |
| 1412 | if let Some(db) = ffmpeg_psnr(&path, &y4m, true) { |
| 1413 | ours.push((data.len() as f64 * 8.0 / f64::from(coded), db)); |
| 1414 | } |
| 1415 | } |
| 1416 | let rav1e: Vec<(f64, f64)> = [180u32, 140, 100, 60] |
| 1417 | .iter() |
| 1418 | .filter_map(|q| { |
| 1419 | software_point( |
| 1420 | &dir, |
| 1421 | &y4m, |
| 1422 | "film-B-10bit", |
| 1423 | "librav1e", |
| 1424 | &[ |
| 1425 | "-pix_fmt", "yuv420p10le", |
| 1426 | "-rav1e-params", &format!("speed=6:quantizer={q}"), |
| 1427 | "-g", "60", |
| 1428 | ], |
| 1429 | *q, |
| 1430 | coded, |
| 1431 | ) |
| 1432 | }) |
| 1433 | .collect(); |
| 1434 | let libaom: Vec<(f64, f64)> = [56u32, 44, 32, 20] |
| 1435 | .iter() |
| 1436 | .filter_map(|crf| { |
| 1437 | software_point( |
| 1438 | &dir, |
| 1439 | &y4m, |
| 1440 | "film-B-10bit", |
| 1441 | "libaom-av1", |
| 1442 | &[ |
| 1443 | "-pix_fmt", "yuv420p10le", |
| 1444 | "-cpu-used", "6", "-crf", &crf.to_string(), "-b:v", "0", "-g", "60", |
| 1445 | ], |
| 1446 | *crf, |
| 1447 | coded, |
| 1448 | ) |
| 1449 | }) |
| 1450 | .collect(); |
| 1451 | |
| 1452 | println!("10-bit BD row: {label}, {width}x{height} yuv420p10le, {coded} frames"); |
| 1453 | for (name, ladder) in [ |
| 1454 | ("hw AV1 10-bit", &ours), |
| 1455 | ("librav1e 10-bit", &rav1e), |
| 1456 | ("libaom 10-bit", &libaom), |
| 1457 | ] { |
| 1458 | println!(" {name}: {ladder:?}"); |
| 1459 | for pair in ladder.windows(2) { |
| 1460 | assert!( |
| 1461 | pair[1].0 > pair[0].0 && pair[1].1 > pair[0].1, |
| 1462 | "{name}: ladder is not monotone at {pair:?}" |
| 1463 | ); |
| 1464 | } |
| 1465 | } |
| 1466 | if ours.len() >= 3 && rav1e.len() >= 3 { |
| 1467 | println!( |
| 1468 | " BD-rate: hw AV1 10-bit vs librav1e speed 6 10-bit: {:+.1}%", |
| 1469 | bd_rate(&rav1e, &ours) * 100.0 |
| 1470 | ); |
| 1471 | } |
| 1472 | if ours.len() >= 3 && libaom.len() >= 3 { |
| 1473 | println!( |
| 1474 | " BD-rate: hw AV1 10-bit vs libaom cpu-used 6 10-bit: {:+.1}%", |
| 1475 | bd_rate(&libaom, &ours) * 100.0 |
| 1476 | ); |
| 1477 | } |
| 1478 | } |
| 1479 | |
| 1480 | |
| 1481 | |
| 1482 | |
| 1483 | |
| 1484 | |
| 1485 | |
| 1486 | |
| 1487 | |
| 1488 | #[test] |
| 1489 | fn av1_encode_bd_row_vs_software() { |
| 1490 | let Some(display) = display() else { return }; |
| 1491 | let clips = real_clips(); |
| 1492 | if clips.is_empty() { |
| 1493 | eprintln!("skipped: no real-library manifest"); |
| 1494 | return; |
| 1495 | } |
| 1496 | |
| 1497 | let same = [(100.0, 30.0), (200.0, 35.0), (400.0, 40.0)]; |
| 1498 | assert!(bd_rate(&same, &same).abs() < 1e-9, "bd_rate is not self-zero"); |
| 1499 | |
| 1500 | let dir = std::env::temp_dir().join("ec-hw-av1-bd"); |
| 1501 | let _ = std::fs::create_dir_all(&dir); |
| 1502 | for (label, source) in clips { |
| 1503 | let y4m = dir.join(format!("{label}.y4m")); |
| 1504 | let (width, height, frames) = (1920u32, 1080u32, 12u32); |
| 1505 | if !extract_y4m(&source, &y4m, width, height, frames) { |
| 1506 | eprintln!("skipped {label}: extraction failed"); |
| 1507 | continue; |
| 1508 | } |
| 1509 | let planes = match raw_frames(&y4m, width, height, frames) { |
| 1510 | Some(planes) => planes, |
| 1511 | None => { |
| 1512 | eprintln!("skipped {label}: no frames extracted"); |
| 1513 | continue; |
| 1514 | } |
| 1515 | }; |
| 1516 | |
| 1517 | let mut ours = Vec::new(); |
| 1518 | |
| 1519 | for qp in [180u32, 140, 100, 60] { |
| 1520 | let mut config = EncoderConfig::new(EncCodec::Av1, width, height); |
| 1521 | config.framerate = (24, 1); |
| 1522 | config.gop_size = 60; |
| 1523 | config.rate_control = RateControlMode::ConstantQp { qp }; |
| 1524 | let mut encoder = match Encoder::new(&display, config) { |
| 1525 | Ok(encoder) => encoder, |
| 1526 | Err(e) => { |
| 1527 | eprintln!("skipped: AV1 encode unavailable ({e})"); |
| 1528 | return; |
| 1529 | } |
| 1530 | }; |
| 1531 | let mut bytes = Vec::new(); |
| 1532 | for (i, frame) in planes.iter().enumerate() { |
| 1533 | let coded = encoder |
| 1534 | .encode( |
| 1535 | frame, |
| 1536 | FrameMetadata { |
| 1537 | timestamp: i as i64, |
| 1538 | force_keyframe: false, |
| 1539 | }, |
| 1540 | ) |
| 1541 | .expect("hardware AV1 encode"); |
| 1542 | bytes.extend_from_slice(&coded.data); |
| 1543 | } |
| 1544 | let path = dir.join(format!("{label}-hw-{qp}.obu")); |
| 1545 | std::fs::write(&path, &bytes).expect("write"); |
| 1546 | if let Some(db) = ffmpeg_psnr(&path, &y4m, true) { |
| 1547 | ours.push((bytes.len() as f64 * 8.0 / f64::from(frames), db)); |
| 1548 | } |
| 1549 | } |
| 1550 | let rav1e: Vec<(f64, f64)> = [180u32, 140, 100, 60] |
| 1551 | .iter() |
| 1552 | .filter_map(|q| { |
| 1553 | software_point( |
| 1554 | &dir, |
| 1555 | &y4m, |
| 1556 | label, |
| 1557 | "librav1e", |
| 1558 | &["-rav1e-params", &format!("speed=6:quantizer={q}"), "-g", "60"], |
| 1559 | *q, |
| 1560 | frames, |
| 1561 | ) |
| 1562 | }) |
| 1563 | .collect(); |
| 1564 | let libaom: Vec<(f64, f64)> = [56u32, 44, 32, 20] |
| 1565 | .iter() |
| 1566 | .filter_map(|crf| { |
| 1567 | software_point( |
| 1568 | &dir, |
| 1569 | &y4m, |
| 1570 | label, |
| 1571 | "libaom-av1", |
| 1572 | &[ |
| 1573 | "-cpu-used", "6", "-crf", &crf.to_string(), "-b:v", "0", "-g", "60", |
| 1574 | ], |
| 1575 | *crf, |
| 1576 | frames, |
| 1577 | ) |
| 1578 | }) |
| 1579 | .collect(); |
| 1580 | |
| 1581 | for (name, ladder) in [("hw AV1", &ours), ("librav1e", &rav1e), ("libaom", &libaom)] { |
| 1582 | println!("{label} {name}: {ladder:?}"); |
| 1583 | for pair in ladder.windows(2) { |
| 1584 | assert!( |
| 1585 | pair[1].0 > pair[0].0 && pair[1].1 > pair[0].1, |
| 1586 | "{label} {name}: ladder is not monotone at {pair:?}" |
| 1587 | ); |
| 1588 | } |
| 1589 | } |
| 1590 | if ours.len() >= 3 && rav1e.len() >= 3 { |
| 1591 | println!( |
| 1592 | "BD-rate row: {label}, hw AV1 vs librav1e speed 6: {:+.1}%", |
| 1593 | bd_rate(&rav1e, &ours) * 100.0 |
| 1594 | ); |
| 1595 | } |
| 1596 | if ours.len() >= 3 && libaom.len() >= 3 { |
| 1597 | println!( |
| 1598 | "BD-rate row: {label}, hw AV1 vs libaom cpu-used 6: {:+.1}%", |
| 1599 | bd_rate(&libaom, &ours) * 100.0 |
| 1600 | ); |
| 1601 | } |
| 1602 | } |
| 1603 | } |
| 1604 | |
| 1605 | |
| 1606 | |
| 1607 | fn software_point( |
| 1608 | dir: &Path, |
| 1609 | y4m: &Path, |
| 1610 | label: &str, |
| 1611 | encoder: &str, |
| 1612 | args: &[&str], |
| 1613 | point: u32, |
| 1614 | frames: u32, |
| 1615 | ) -> Option<(f64, f64)> { |
| 1616 | let out = dir.join(format!("{label}-{encoder}-{point}.ivf")); |
| 1617 | let _ = std::fs::remove_file(&out); |
| 1618 | let status = Command::new("ffmpeg") |
| 1619 | .args(["-nostdin", "-v", "error", "-y", "-i"]) |
| 1620 | .arg(y4m) |
| 1621 | .args(["-c:v", encoder]) |
| 1622 | .args(args) |
| 1623 | .arg(&out) |
| 1624 | .status() |
| 1625 | .ok()?; |
| 1626 | if !status.success() { |
| 1627 | return None; |
| 1628 | } |
| 1629 | let bytes = std::fs::metadata(&out).ok()?.len() as f64; |
| 1630 | let db = ffmpeg_psnr(&out, y4m, false)?; |
| 1631 | Some((bytes * 8.0 / f64::from(frames), db)) |
| 1632 | } |
| 1633 | |
| 1634 | |
| 1635 | fn ffmpeg_psnr(coded: &Path, source: &Path, raw_obu: bool) -> Option<f64> { |
| 1636 | let mut cmd = Command::new("ffmpeg"); |
| 1637 | cmd.args(["-nostdin", "-v", "info"]); |
| 1638 | if raw_obu { |
| 1639 | cmd.args(["-f", "obu"]); |
| 1640 | } |
| 1641 | |
| 1642 | |
| 1643 | |
| 1644 | let out = cmd |
| 1645 | .args(["-r", "24"]) |
| 1646 | .arg("-i") |
| 1647 | .arg(coded) |
| 1648 | .args(["-r", "24"]) |
| 1649 | .arg("-i") |
| 1650 | .arg(source) |
| 1651 | .args(["-lavfi", "psnr", "-f", "null", "-"]) |
| 1652 | .output() |
| 1653 | .ok()?; |
| 1654 | let text = String::from_utf8_lossy(&out.stderr); |
| 1655 | let field = text.split("average:").nth(1)?; |
| 1656 | field |
| 1657 | .split_whitespace() |
| 1658 | .next()? |
| 1659 | .parse::<f64>() |
| 1660 | .ok() |
| 1661 | .filter(|v| v.is_finite()) |
| 1662 | } |
| 1663 | |
| 1664 | |
| 1665 | fn extract_y4m(source: &Path, out: &Path, width: u32, height: u32, frames: u32) -> bool { |
| 1666 | let _ = std::fs::remove_file(out); |
| 1667 | Command::new("ffmpeg") |
| 1668 | .args(["-nostdin", "-v", "error", "-y", "-ss", "60", "-i"]) |
| 1669 | .arg(source) |
| 1670 | .args([ |
| 1671 | "-frames:v", |
| 1672 | &frames.to_string(), |
| 1673 | "-vf", |
| 1674 | &format!("scale={width}:{height}"), |
| 1675 | "-pix_fmt", |
| 1676 | "yuv420p", |
| 1677 | ]) |
| 1678 | .arg(out) |
| 1679 | .status() |
| 1680 | .is_ok_and(|s| s.success()) |
| 1681 | } |
| 1682 | |
| 1683 | |
| 1684 | fn raw_frames(y4m: &Path, width: u32, height: u32, frames: u32) -> Option<Vec<I420>> { |
| 1685 | let out = Command::new("ffmpeg") |
| 1686 | .args(["-nostdin", "-v", "error", "-i"]) |
| 1687 | .arg(y4m) |
| 1688 | .args(["-pix_fmt", "yuv420p", "-f", "rawvideo", "-"]) |
| 1689 | .stderr(Stdio::null()) |
| 1690 | .output() |
| 1691 | .ok()?; |
| 1692 | let (w, h) = (width as usize, height as usize); |
| 1693 | let (cw, ch) = (w.div_ceil(2), h.div_ceil(2)); |
| 1694 | let frame_len = w * h + 2 * cw * ch; |
| 1695 | let mut pictures = Vec::new(); |
| 1696 | for chunk in out.stdout.chunks_exact(frame_len).take(frames as usize) { |
| 1697 | let (y, rest) = chunk.split_at(w * h); |
| 1698 | let (u, v) = rest.split_at(cw * ch); |
| 1699 | pictures.push(I420 { |
| 1700 | y: y.to_vec(), |
| 1701 | u: u.to_vec(), |
| 1702 | v: v.to_vec(), |
| 1703 | width, |
| 1704 | height, |
| 1705 | }); |
| 1706 | } |
| 1707 | (!pictures.is_empty()).then_some(pictures) |
| 1708 | } |
| 1709 | |
| 1710 | |
| 1711 | |
| 1712 | fn real_clips() -> Vec<(&'static str, PathBuf)> { |
| 1713 | let manifest = |
| 1714 | Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/real-library-manifest.tsv"); |
| 1715 | let Ok(text) = std::fs::read_to_string(&manifest) else { |
| 1716 | return Vec::new(); |
| 1717 | }; |
| 1718 | let mut film = None; |
| 1719 | let mut screen = None; |
| 1720 | for line in text.lines().skip(1) { |
| 1721 | let f: Vec<&str> = line.split('\t').collect(); |
| 1722 | if f.len() < 7 || f[2] != "h264" { |
| 1723 | continue; |
| 1724 | } |
| 1725 | let width: u32 = f[3].parse().unwrap_or(0); |
| 1726 | |
| 1727 | let duration: f64 = f.get(8).and_then(|d| d.parse().ok()).unwrap_or(0.0); |
| 1728 | if width < 1280 || duration < 90.0 { |
| 1729 | continue; |
| 1730 | } |
| 1731 | let path = PathBuf::from(f[0]); |
| 1732 | if f[0].contains("/Films/") && film.is_none() { |
| 1733 | film = Some(("film A", path)); |
| 1734 | } else if f[0].contains("/OBS/") && screen.is_none() { |
| 1735 | screen = Some(("screen capture", path)); |
| 1736 | } |
| 1737 | } |
| 1738 | film.into_iter().chain(screen).collect() |
| 1739 | } |
| 1740 | |
| 1741 | |
| 1742 | |
| 1743 | |
| 1744 | |
| 1745 | |
| 1746 | |
| 1747 | |
| 1748 | fn bd_rate(reference: &[(f64, f64)], test: &[(f64, f64)]) -> f64 { |
| 1749 | let low = reference[0].1.max(test[0].1); |
| 1750 | let high = reference[reference.len() - 1].1.min(test[test.len() - 1].1); |
| 1751 | if !(high > low) { |
| 1752 | return f64::NAN; |
| 1753 | } |
| 1754 | |
| 1755 | let at = |ladder: &[(f64, f64)], db: f64| -> f64 { |
| 1756 | for pair in ladder.windows(2) { |
| 1757 | let ((r0, d0), (r1, d1)) = (pair[0], pair[1]); |
| 1758 | if db >= d0 && db <= d1 { |
| 1759 | let t = if (d1 - d0).abs() < f64::EPSILON { |
| 1760 | 0.0 |
| 1761 | } else { |
| 1762 | (db - d0) / (d1 - d0) |
| 1763 | }; |
| 1764 | return r0.log10() + t * (r1.log10() - r0.log10()); |
| 1765 | } |
| 1766 | } |
| 1767 | if db < ladder[0].1 { |
| 1768 | ladder[0].0.log10() |
| 1769 | } else { |
| 1770 | ladder[ladder.len() - 1].0.log10() |
| 1771 | } |
| 1772 | }; |
| 1773 | let steps = 100; |
| 1774 | let mut integral = 0.0; |
| 1775 | for i in 0..steps { |
| 1776 | let a = low + (high - low) * f64::from(i) / f64::from(steps); |
| 1777 | let b = low + (high - low) * f64::from(i + 1) / f64::from(steps); |
| 1778 | let da = at(test, a) - at(reference, a); |
| 1779 | let db = at(test, b) - at(reference, b); |
| 1780 | integral += (da + db) / 2.0 * (b - a); |
| 1781 | } |
| 1782 | 10f64.powf(integral / (high - low)) - 1.0 |
| 1783 | } |
| 1784 | |
| 1785 | |
| 1786 | |
| 1787 | |
| 1788 | #[test] |
| 1789 | fn av1_encode_speed() { |
| 1790 | let Some(display) = display() else { return }; |
| 1791 | for (width, height) in [(1920u32, 1080u32), (3840, 1608)] { |
| 1792 | let frames = 30u32; |
| 1793 | let start = Instant::now(); |
| 1794 | match encode_stream(&display, EncCodec::Av1, width, height, frames) { |
| 1795 | Ok(data) => { |
| 1796 | let secs = start.elapsed().as_secs_f64(); |
| 1797 | println!( |
| 1798 | "AV1 encode {width}x{height}: {:.1} fps ({frames} frames in {secs:.2} s), {} kbit/frame", |
| 1799 | f64::from(frames) / secs, |
| 1800 | data.len() * 8 / frames as usize / 1000 |
| 1801 | ); |
| 1802 | } |
| 1803 | Err(e) => { |
| 1804 | eprintln!("skipped: AV1 encode unavailable ({e})"); |
| 1805 | return; |
| 1806 | } |
| 1807 | } |
| 1808 | } |
| 1809 | |
| 1810 | |
| 1811 | let planes: Vec<I420_16> = (0..30).map(|t| source_frame_16(3840, 1608, t)).collect(); |
| 1812 | let start = Instant::now(); |
| 1813 | match encode_stream_16(&display, &planes, 90, RateControlMode::ConstantQp { qp: 90 }) { |
| 1814 | Ok(data) => { |
| 1815 | let secs = start.elapsed().as_secs_f64(); |
| 1816 | println!( |
| 1817 | "AV1 encode 3840x1608 10-bit: {:.1} fps ({} frames in {secs:.2} s), {} kbit/frame", |
| 1818 | planes.len() as f64 / secs, |
| 1819 | planes.len(), |
| 1820 | data.len() * 8 / planes.len() / 1000 |
| 1821 | ); |
| 1822 | } |
| 1823 | Err(e) => eprintln!("skipped: 10-bit AV1 encode unavailable ({e})"), |
| 1824 | } |
| 1825 | } |
| 1826 | |
| 1827 | |
| 1828 | |
| 1829 | |
| 1830 | |
| 1831 | |
| 1832 | |
| 1833 | |
| 1834 | |
| 1835 | |
| 1836 | |
| 1837 | |
| 1838 | #[test] |
| 1839 | fn h264_frame_num_gaps_are_synthesised() { |
| 1840 | let Some(display) = display() else { return }; |
| 1841 | let path = bitstreams().join("h264-1080p-23.976-8bit.264"); |
| 1842 | if !path.exists() { |
| 1843 | eprintln!("skipped: no H.264 fixture"); |
| 1844 | return; |
| 1845 | } |
| 1846 | let data = std::fs::read(&path).expect("fixture is readable"); |
| 1847 | let units = split_access_units(&data, Codec::H264); |
| 1848 | assert!( |
| 1849 | units.len() > 8, |
| 1850 | "fixture is too short to drop a picture from" |
| 1851 | ); |
| 1852 | |
| 1853 | |
| 1854 | let mut kept: Vec<&[u8]> = Vec::new(); |
| 1855 | for (i, unit) in units.iter().enumerate() { |
| 1856 | if (3..=5).contains(&i) { |
| 1857 | continue; |
| 1858 | } |
| 1859 | kept.push(unit); |
| 1860 | } |
| 1861 | |
| 1862 | let mut decoder = Decoder::new(&display, Codec::H264).expect("decoder opens"); |
| 1863 | let mut frames = 0usize; |
| 1864 | for (i, unit) in kept.iter().enumerate().take(20) { |
| 1865 | if let Err(e) = decoder.decode(unit, i as i64) { |
| 1866 | panic!( |
| 1867 | "unit {i} failed after {} gap frames: {e}", |
| 1868 | decoder.gap_frames_synthesized() |
| 1869 | ); |
| 1870 | } |
| 1871 | while let Some(frame) = decoder.next_frame() { |
| 1872 | |
| 1873 | let planes = frame.to_i420().expect("readback"); |
| 1874 | assert_eq!(planes.y.len(), 1920 * 1080); |
| 1875 | frames += 1; |
| 1876 | } |
| 1877 | } |
| 1878 | decoder.flush().expect("flush"); |
| 1879 | while decoder.next_frame().is_some() { |
| 1880 | frames += 1; |
| 1881 | } |
| 1882 | let synthesised = decoder.gap_frames_synthesized(); |
| 1883 | println!("frame_num gap: {frames} frames decoded, {synthesised} pictures inferred"); |
| 1884 | assert!(synthesised > 0, "the gap was not detected"); |
| 1885 | assert!(frames >= 10, "only {frames} frames survived the gap"); |
| 1886 | } |
| 1887 | |
| 1888 | |
| 1889 | fn rss_kb() -> u64 { |
| 1890 | let status = std::fs::read_to_string("/proc/self/status").unwrap_or_default(); |
| 1891 | status |
| 1892 | .lines() |
| 1893 | .find_map(|line| line.strip_prefix("VmRSS:")) |
| 1894 | .and_then(|v| v.split_whitespace().next().map(|n| n.to_string())) |
| 1895 | .and_then(|n| n.parse().ok()) |
| 1896 | .unwrap_or(0) |
| 1897 | } |
| 1898 | |
| 1899 | |
| 1900 | |
| 1901 | |
| 1902 | |
| 1903 | |
| 1904 | #[test] |
| 1905 | fn long_decode_does_not_grow_the_resident_set() { |
| 1906 | |
| 1907 | |
| 1908 | |
| 1909 | |
| 1910 | if std::env::var_os("EC_HW_RSS_CHILD").is_none() { |
| 1911 | let status = Command::new(std::env::current_exe().expect("test binary path")) |
| 1912 | .args(["--exact", "long_decode_does_not_grow_the_resident_set"]) |
| 1913 | .env("EC_HW_RSS_CHILD", "1") |
| 1914 | .status() |
| 1915 | .expect("re-run this test in its own process"); |
| 1916 | assert!(status.success(), "isolated RSS run failed"); |
| 1917 | return; |
| 1918 | } |
| 1919 | let Some(display) = display() else { return }; |
| 1920 | let path = bitstreams().join("h264-1080p-23.976-8bit.264"); |
| 1921 | if !path.exists() { |
| 1922 | eprintln!("skipped: no H.264 fixture"); |
| 1923 | return; |
| 1924 | } |
| 1925 | let data = std::fs::read(&path).expect("fixture is readable"); |
| 1926 | let units = split_access_units(&data, Codec::H264); |
| 1927 | let mut decoder = Decoder::new(&display, Codec::H264).expect("decoder opens"); |
| 1928 | |
| 1929 | |
| 1930 | |
| 1931 | let mut decoded = 0usize; |
| 1932 | let mut baseline = 0u64; |
| 1933 | let mut readback_ms = 0f64; |
| 1934 | let mut pending: Vec<Frame> = Vec::new(); |
| 1935 | let target = 719usize; |
| 1936 | 'outer: for pass in 0..16 { |
| 1937 | if pass > 0 { |
| 1938 | decoder.reset(); |
| 1939 | } |
| 1940 | for (i, unit) in units.iter().enumerate() { |
| 1941 | decoder.decode(unit, i as i64).expect("decode"); |
| 1942 | while let Some(frame) = decoder.next_frame() { |
| 1943 | |
| 1944 | |
| 1945 | |
| 1946 | pending.push(frame); |
| 1947 | if pending.len() < 4 { |
| 1948 | continue; |
| 1949 | } |
| 1950 | let start = std::time::Instant::now(); |
| 1951 | for frame in pending.drain(..) { |
| 1952 | let planes = frame.to_i420().expect("readback"); |
| 1953 | std::hint::black_box(&planes); |
| 1954 | decoded += 1; |
| 1955 | } |
| 1956 | readback_ms += start.elapsed().as_secs_f64() * 1000.0; |
| 1957 | if decoded == 60 { |
| 1958 | baseline = rss_kb(); |
| 1959 | } |
| 1960 | if decoded >= target { |
| 1961 | break 'outer; |
| 1962 | } |
| 1963 | } |
| 1964 | } |
| 1965 | } |
| 1966 | decoder.flush().expect("flush"); |
| 1967 | let end = rss_kb(); |
| 1968 | let delta_mb = (end.saturating_sub(baseline)) as f64 / 1024.0; |
| 1969 | println!( |
| 1970 | "{decoded} frames decoded and read back: RSS {baseline} -> {end} kB (delta {delta_mb:.1} MB), \ |
| 1971 | decode and read back {:.2} ms/frame at 1920x1080", |
| 1972 | readback_ms / decoded as f64 |
| 1973 | ); |
| 1974 | assert!(decoded >= target, "only {decoded} frames decoded"); |
| 1975 | assert!( |
| 1976 | delta_mb < 50.0, |
| 1977 | "resident set grew {delta_mb:.1} MB over {decoded} frames" |
| 1978 | ); |
| 1979 | } |
| 1980 | |
| 1981 | |
| 1982 | |
| 1983 | |
| 1984 | |
| 1985 | #[test] |
| 1986 | fn frames_export_as_dma_buf() { |
| 1987 | let Some(display) = display() else { return }; |
| 1988 | let path = bitstreams().join("h264-1080p-23.976-8bit.264"); |
| 1989 | if !path.exists() { |
| 1990 | eprintln!("skipped: no H.264 fixture"); |
| 1991 | return; |
| 1992 | } |
| 1993 | let data = std::fs::read(&path).expect("fixture is readable"); |
| 1994 | let mut decoder = Decoder::new(&display, Codec::H264).expect("decoder opens"); |
| 1995 | let mut exported = 0usize; |
| 1996 | decode_stream(&mut decoder, Codec::H264, &data, 2, |frame| { |
| 1997 | let prime = frame.export_prime().expect("export"); |
| 1998 | assert_eq!(prime.fourcc, ec_va::sys::VA_FOURCC_NV12); |
| 1999 | assert_eq!((prime.width, prime.height), frame.coded_size); |
| 2000 | assert!(!prime.objects.is_empty(), "no DRM objects exported"); |
| 2001 | assert!(!prime.layers.is_empty(), "no layers exported"); |
| 2002 | let planes: usize = prime.layers.iter().map(|l| l.planes.len()).sum(); |
| 2003 | assert!( |
| 2004 | planes >= 2, |
| 2005 | "NV12 needs a luma and a chroma plane, got {planes}" |
| 2006 | ); |
| 2007 | exported += 1; |
| 2008 | }) |
| 2009 | .expect("decode"); |
| 2010 | assert!(exported >= 1, "nothing was exported"); |
| 2011 | println!("DRM PRIME export: {exported} frames"); |
| 2012 | } |
| 2013 | |
| 2014 | |
| 2015 | |
| 2016 | |
| 2017 | |
| 2018 | |
| 2019 | |
| 2020 | |
| 2021 | |
| 2022 | fn elementary(path: &Path, codec: Codec, frames: usize) -> Option<Vec<u8>> { |
| 2023 | let args: &[&str] = match codec { |
| 2024 | Codec::H264 => &["-bsf:v", "h264_mp4toannexb", "-f", "h264"], |
| 2025 | Codec::H265 => &["-bsf:v", "hevc_mp4toannexb", "-f", "hevc"], |
| 2026 | Codec::Vp9 | Codec::Av1 => &["-f", "ivf"], |
| 2027 | }; |
| 2028 | let out = Command::new("ffmpeg") |
| 2029 | .args(["-nostdin", "-v", "error", "-i"]) |
| 2030 | .arg(path) |
| 2031 | .args(["-map", "0:v:0", "-c:v", "copy"]) |
| 2032 | |
| 2033 | |
| 2034 | .args(["-frames:v", &(frames + 16).to_string()]) |
| 2035 | .args(args) |
| 2036 | .arg("-") |
| 2037 | .stderr(Stdio::null()) |
| 2038 | .output() |
| 2039 | .ok()?; |
| 2040 | (!out.stdout.is_empty()).then_some(out.stdout) |
| 2041 | } |
| 2042 | |
| 2043 | |
| 2044 | |
| 2045 | |
| 2046 | |
| 2047 | |
| 2048 | |
| 2049 | #[test] |
| 2050 | fn real_library_spot_check() { |
| 2051 | let Some(display) = display() else { return }; |
| 2052 | let manifest = |
| 2053 | Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/real-library-manifest.tsv"); |
| 2054 | let Ok(text) = std::fs::read_to_string(&manifest) else { |
| 2055 | eprintln!( |
| 2056 | "skipped: no fixtures/real-library-manifest.tsv — run scripts/scan-real-library.sh" |
| 2057 | ); |
| 2058 | return; |
| 2059 | }; |
| 2060 | |
| 2061 | |
| 2062 | let mut wanted: Vec<(String, Codec, bool)> = Vec::new(); |
| 2063 | let mut seen: Vec<(String, u8)> = Vec::new(); |
| 2064 | for line in text.lines().skip(1) { |
| 2065 | let f: Vec<&str> = line.split('\t').collect(); |
| 2066 | if f.len() < 7 { |
| 2067 | continue; |
| 2068 | } |
| 2069 | let (path, vcodec, depth) = (f[0].to_string(), f[2], f[6].parse::<u8>().unwrap_or(8)); |
| 2070 | let codec = match vcodec { |
| 2071 | "h264" => Codec::H264, |
| 2072 | "hevc" => Codec::H265, |
| 2073 | "vp9" => Codec::Vp9, |
| 2074 | "av1" => Codec::Av1, |
| 2075 | _ => continue, |
| 2076 | }; |
| 2077 | let key = (vcodec.to_string(), depth); |
| 2078 | if seen.iter().filter(|k| **k == key).count() >= 2 || wanted.len() >= 5 { |
| 2079 | continue; |
| 2080 | } |
| 2081 | if !Path::new(&path).exists() { |
| 2082 | continue; |
| 2083 | } |
| 2084 | seen.push(key); |
| 2085 | wanted.push((path, codec, depth > 8)); |
| 2086 | } |
| 2087 | if wanted.is_empty() { |
| 2088 | eprintln!("skipped: no files from the manifest are present"); |
| 2089 | return; |
| 2090 | } |
| 2091 | |
| 2092 | |
| 2093 | let limit: usize = std::env::var("EC_HW_SWEEP_FRAMES") |
| 2094 | .ok() |
| 2095 | .and_then(|v| v.parse().ok()) |
| 2096 | .unwrap_or(500); |
| 2097 | let mut table = Vec::new(); |
| 2098 | for (path, codec, ten_bit) in &wanted { |
| 2099 | let path = Path::new(path); |
| 2100 | let Some(data) = elementary(path, *codec, limit) else { |
| 2101 | table.push(format!("{:<52} SKIP (no elementary stream)", short(path))); |
| 2102 | continue; |
| 2103 | }; |
| 2104 | let mut decoder = Decoder::new(&display, *codec).expect("decoder opens"); |
| 2105 | let mut reference: Option<Reference> = None; |
| 2106 | let mut worst = f64::INFINITY; |
| 2107 | let mut compared = 0usize; |
| 2108 | let mut failed: Option<String> = None; |
| 2109 | let result = decode_stream(&mut decoder, *codec, &data, limit, |frame| { |
| 2110 | let (w, h) = frame.display_size; |
| 2111 | let reference = reference |
| 2112 | .get_or_insert_with(|| Reference::open(path, w, h, *ten_bit).expect("ffmpeg runs")); |
| 2113 | let Some(want) = reference.next(w, h) else { |
| 2114 | return; |
| 2115 | }; |
| 2116 | let got = if *ten_bit { |
| 2117 | Planes::from_16bit(&frame.to_i420_16().expect("readback")) |
| 2118 | } else { |
| 2119 | Planes::from_8bit(&frame.to_i420().expect("readback")) |
| 2120 | }; |
| 2121 | if got.y.len() != want.y.len() { |
| 2122 | failed = Some("frame size disagrees with ffmpeg".to_string()); |
| 2123 | return; |
| 2124 | } |
| 2125 | let db = psnr(&got, &want); |
| 2126 | if std::env::var_os("EC_HW_DEBUG").is_some() { |
| 2127 | eprintln!(" {} frame {compared}: {db:.1} dB", short(path)); |
| 2128 | } |
| 2129 | worst = worst.min(db); |
| 2130 | compared += 1; |
| 2131 | }); |
| 2132 | match result { |
| 2133 | Ok(decoded) => table.push(format!( |
| 2134 | "{:<52} {decoded:>4} frames, {compared} compared, worst {}", |
| 2135 | short(path), |
| 2136 | if worst.is_infinite() { |
| 2137 | "exact".to_string() |
| 2138 | } else { |
| 2139 | format!("{worst:.1} dB") |
| 2140 | } |
| 2141 | )), |
| 2142 | Err(e) => failed = Some(e.to_string()), |
| 2143 | } |
| 2144 | if let Some(reason) = failed { |
| 2145 | table.push(format!("{:<52} FAIL {reason}", short(path))); |
| 2146 | } |
| 2147 | assert!(compared > 0, "{}: nothing decoded", short(path)); |
| 2148 | assert!( |
| 2149 | worst >= 40.0, |
| 2150 | "{}: worst frame {worst:.1} dB against ffmpeg", |
| 2151 | short(path) |
| 2152 | ); |
| 2153 | } |
| 2154 | for row in table { |
| 2155 | println!("{row}"); |
| 2156 | } |
| 2157 | } |
| 2158 | |
| 2159 | |
| 2160 | fn short(path: &Path) -> String { |
| 2161 | path.file_name() |
| 2162 | .map(|n| n.to_string_lossy().to_string()) |
| 2163 | .unwrap_or_default() |
| 2164 | } |
| 2165 | |
| 2166 | |
| 2167 | fn plane_psnr(a: &[u16], b: &[u16], peak: f64) -> f64 { |
| 2168 | let n = a.len().min(b.len()); |
| 2169 | let mse: f64 = a[..n] |
| 2170 | .iter() |
| 2171 | .zip(&b[..n]) |
| 2172 | .map(|(&p, &q)| { |
| 2173 | let d = f64::from(p) - f64::from(q); |
| 2174 | d * d |
| 2175 | }) |
| 2176 | .sum::<f64>() |
| 2177 | / n as f64; |
| 2178 | if mse == 0.0 { |
| 2179 | f64::INFINITY |
| 2180 | } else { |
| 2181 | 10.0 * (peak * peak / mse).log10() |
| 2182 | } |
| 2183 | } |
| 2184 | |
| 2185 | |
| 2186 | |
| 2187 | |
| 2188 | |
| 2189 | |
| 2190 | |
| 2191 | |
| 2192 | |
| 2193 | |
| 2194 | #[test] |
| 2195 | fn ten_bit_4k_chroma_is_not_grey() { |
| 2196 | let Some(display) = display() else { return }; |
| 2197 | let path = Path::new( |
| 2198 | "/home/user/Downloads/reeld\ |
| 2199 | /reeld.mkv", |
| 2200 | ); |
| 2201 | if !path.exists() { |
| 2202 | eprintln!("skipped: film not present"); |
| 2203 | return; |
| 2204 | } |
| 2205 | let frames = 3usize; |
| 2206 | let Some(data) = elementary(path, Codec::H265, frames) else { |
| 2207 | eprintln!("skipped: no elementary stream"); |
| 2208 | return; |
| 2209 | }; |
| 2210 | let mut decoder = Decoder::new(&display, Codec::H265).expect("decoder opens"); |
| 2211 | let mut ref10: Option<Reference> = None; |
| 2212 | let mut ref8: Option<Reference> = None; |
| 2213 | let mut compared = 0usize; |
| 2214 | decode_stream(&mut decoder, Codec::H265, &data, frames, |frame| { |
| 2215 | let (w, h) = frame.display_size; |
| 2216 | let ref10 = |
| 2217 | ref10.get_or_insert_with(|| Reference::open(path, w, h, true).expect("ffmpeg runs")); |
| 2218 | let want10 = ref10.next(w, h).expect("ffmpeg has a frame"); |
| 2219 | let got16 = Planes::from_16bit(&frame.to_i420_16().expect("readback")); |
| 2220 | let y_db = plane_psnr(&got16.y, &want10.y, 1023.0); |
| 2221 | let uv_db = plane_psnr( |
| 2222 | &[got16.u.as_slice(), got16.v.as_slice()].concat(), |
| 2223 | &[want10.u.as_slice(), want10.v.as_slice()].concat(), |
| 2224 | 1023.0, |
| 2225 | ); |
| 2226 | println!("frame {compared} to_i420_16 vs yuv420p10le: Y {y_db:.1} dB, UV {uv_db:.1} dB"); |
| 2227 | assert!( |
| 2228 | y_db >= 50.0, |
| 2229 | "frame {compared}: Y PSNR collapsed to {y_db:.1} dB" |
| 2230 | ); |
| 2231 | assert!( |
| 2232 | uv_db >= 50.0, |
| 2233 | "frame {compared}: chroma PSNR collapsed to {uv_db:.1} dB (grey frame)" |
| 2234 | ); |
| 2235 | |
| 2236 | let ref8 = |
| 2237 | ref8.get_or_insert_with(|| Reference::open(path, w, h, false).expect("ffmpeg runs")); |
| 2238 | let want8 = ref8.next(w, h).expect("ffmpeg has a frame"); |
| 2239 | let got8 = Planes::from_8bit(&frame.to_i420().expect("readback")); |
| 2240 | let y_db8 = plane_psnr(&got8.y, &want8.y, 255.0); |
| 2241 | let uv_db8 = plane_psnr( |
| 2242 | &[got8.u.as_slice(), got8.v.as_slice()].concat(), |
| 2243 | &[want8.u.as_slice(), want8.v.as_slice()].concat(), |
| 2244 | 255.0, |
| 2245 | ); |
| 2246 | println!("frame {compared} to_i420 vs yuv420p: Y {y_db8:.1} dB, UV {uv_db8:.1} dB"); |
| 2247 | |
| 2248 | |
| 2249 | |
| 2250 | assert!( |
| 2251 | y_db8 >= 30.0, |
| 2252 | "frame {compared}: 8-bit Y PSNR {y_db8:.1} dB" |
| 2253 | ); |
| 2254 | assert!( |
| 2255 | uv_db8 >= 30.0, |
| 2256 | "frame {compared}: 8-bit chroma PSNR collapsed to {uv_db8:.1} dB (grey frame)" |
| 2257 | ); |
| 2258 | compared += 1; |
| 2259 | }) |
| 2260 | .expect("decode"); |
| 2261 | assert_eq!(compared, frames, "not all frames were compared"); |
| 2262 | } |
| 2263 | |
| 2264 | |
| 2265 | |
| 2266 | |
| 2267 | |
| 2268 | |
| 2269 | |
| 2270 | |
| 2271 | #[test] |
| 2272 | fn hdr_film_light_level_sei_is_exposed() { |
| 2273 | let Some(display) = display() else { return }; |
| 2274 | let path = Path::new( |
| 2275 | "/home/user/Downloads/reeld\ |
| 2276 | /reeld.mkv", |
| 2277 | ); |
| 2278 | if !path.exists() { |
| 2279 | eprintln!("skipped: film not present"); |
| 2280 | return; |
| 2281 | } |
| 2282 | let frames = 2usize; |
| 2283 | let Some(data) = elementary(path, Codec::H265, frames) else { |
| 2284 | eprintln!("skipped: no elementary stream"); |
| 2285 | return; |
| 2286 | }; |
| 2287 | let mut decoder = Decoder::new(&display, Codec::H265).expect("decoder opens"); |
| 2288 | let mut seen = 0usize; |
| 2289 | decode_stream(&mut decoder, Codec::H265, &data, frames, |frame| { |
| 2290 | seen += 1; |
| 2291 | let colour = frame |
| 2292 | .colour() |
| 2293 | .expect("HEVC decoder resolves colour metadata"); |
| 2294 | assert_eq!( |
| 2295 | colour.description.codes(), |
| 2296 | (9, 16, 9), |
| 2297 | "primaries/transfer/matrix (BT.2020 / PQ / BT.2020 NCL)" |
| 2298 | ); |
| 2299 | assert_eq!(colour.light.max_cll, Some(1230.0), "MaxCLL"); |
| 2300 | assert_eq!(colour.light.max_fall, Some(419.0), "MaxFALL"); |
| 2301 | assert!( |
| 2302 | colour.light.mastering_max.is_some(), |
| 2303 | "mastering display peak missing" |
| 2304 | ); |
| 2305 | }) |
| 2306 | .expect("decode"); |
| 2307 | assert_eq!(seen, frames, "not all frames were compared"); |
| 2308 | } |
| 2309 | |
| 2310 | |
| 2311 | |
| 2312 | #[test] |
| 2313 | fn sdr_h264_colour_never_panics() { |
| 2314 | let Some(display) = display() else { return }; |
| 2315 | let paths = fixtures(".264"); |
| 2316 | if paths.is_empty() { |
| 2317 | eprintln!("skipped: no H.264 fixtures generated"); |
| 2318 | return; |
| 2319 | } |
| 2320 | let path = &paths[0]; |
| 2321 | let Some(data) = std::fs::read(path).ok() else { |
| 2322 | eprintln!("skipped: fixture unreadable"); |
| 2323 | return; |
| 2324 | }; |
| 2325 | let mut decoder = Decoder::new(&display, Codec::H264).expect("decoder opens"); |
| 2326 | let mut seen = 0usize; |
| 2327 | decode_stream(&mut decoder, Codec::H264, &data, 2, |frame| { |
| 2328 | seen += 1; |
| 2329 | |
| 2330 | if let Some(colour) = frame.colour() { |
| 2331 | assert_eq!(colour.light.max_cll, None); |
| 2332 | } |
| 2333 | }) |
| 2334 | .expect("decode"); |
| 2335 | assert!(seen > 0, "{}: nothing decoded", short(path)); |
| 2336 | } |
| 2337 | |
| 2338 | |
| 2339 | |
| 2340 | |
| 2341 | |
| 2342 | |
| 2343 | |
| 2344 | |
| 2345 | |
| 2346 | #[test] |
| 2347 | fn ten_bit_4k_frame_path_is_realtime() { |
| 2348 | let Some(display) = display() else { return }; |
| 2349 | let path = Path::new( |
| 2350 | "/home/user/Downloads/reeld\ |
| 2351 | /reeld.mkv", |
| 2352 | ); |
| 2353 | if !path.exists() { |
| 2354 | eprintln!("skipped: film not present"); |
| 2355 | return; |
| 2356 | } |
| 2357 | let limit = 120usize; |
| 2358 | let Some(data) = elementary(path, Codec::H265, limit) else { |
| 2359 | eprintln!("skipped: no elementary stream"); |
| 2360 | return; |
| 2361 | }; |
| 2362 | let units = split_access_units(&data, Codec::H265); |
| 2363 | assert!( |
| 2364 | units.len() > limit, |
| 2365 | "film clip too short for {limit} frames" |
| 2366 | ); |
| 2367 | |
| 2368 | #[derive(Clone, Copy)] |
| 2369 | enum Op { |
| 2370 | DecodeOnly, |
| 2371 | ToI420, |
| 2372 | ToI420_16, |
| 2373 | ExportPrime, |
| 2374 | } |
| 2375 | fn apply(op: Op, frame: Frame) { |
| 2376 | match op { |
| 2377 | Op::DecodeOnly => drop(frame), |
| 2378 | Op::ToI420 => { |
| 2379 | frame.to_i420().expect("readback"); |
| 2380 | } |
| 2381 | Op::ToI420_16 => { |
| 2382 | frame.to_i420_16().expect("readback"); |
| 2383 | } |
| 2384 | Op::ExportPrime => { |
| 2385 | frame.export_prime().expect("export"); |
| 2386 | } |
| 2387 | } |
| 2388 | } |
| 2389 | |
| 2390 | println!( |
| 2391 | "{:<22} {:>10} {:>10} {:>10}", |
| 2392 | "stage", "median ms", "min ms", "max ms" |
| 2393 | ); |
| 2394 | let mut got_to_i420_16 = None; |
| 2395 | for (name, op) in [ |
| 2396 | ("decode-only", Op::DecodeOnly), |
| 2397 | ("decode+to_i420", Op::ToI420), |
| 2398 | ("decode+to_i420_16", Op::ToI420_16), |
| 2399 | ("decode+export_prime", Op::ExportPrime), |
| 2400 | ] { |
| 2401 | let mut decoder = Decoder::new(&display, Codec::H265).expect("decoder opens"); |
| 2402 | let mut durations: Vec<Duration> = Vec::new(); |
| 2403 | |
| 2404 | |
| 2405 | |
| 2406 | let mut pending: Vec<Frame> = Vec::new(); |
| 2407 | let mut t_prev = Instant::now(); |
| 2408 | 'outer: for (i, unit) in units.iter().enumerate() { |
| 2409 | decoder.decode(unit, i as i64).expect("decode"); |
| 2410 | while let Some(frame) = decoder.next_frame() { |
| 2411 | pending.push(frame); |
| 2412 | if pending.len() < 4 { |
| 2413 | continue; |
| 2414 | } |
| 2415 | for frame in pending.drain(..) { |
| 2416 | apply(op, frame); |
| 2417 | let now = Instant::now(); |
| 2418 | durations.push(now.duration_since(t_prev)); |
| 2419 | t_prev = now; |
| 2420 | } |
| 2421 | if durations.len() >= limit { |
| 2422 | break 'outer; |
| 2423 | } |
| 2424 | } |
| 2425 | } |
| 2426 | decoder.flush().expect("flush"); |
| 2427 | while durations.len() < limit { |
| 2428 | let Some(frame) = decoder.next_frame() else { |
| 2429 | break; |
| 2430 | }; |
| 2431 | apply(op, frame); |
| 2432 | let now = Instant::now(); |
| 2433 | durations.push(now.duration_since(t_prev)); |
| 2434 | t_prev = now; |
| 2435 | } |
| 2436 | assert!( |
| 2437 | durations.len() >= 24, |
| 2438 | "{name}: only {} frames decoded", |
| 2439 | durations.len() |
| 2440 | ); |
| 2441 | durations.sort(); |
| 2442 | let ms = |d: Duration| d.as_secs_f64() * 1000.0; |
| 2443 | let median = ms(durations[durations.len() / 2]); |
| 2444 | let min = ms(durations[0]); |
| 2445 | let max = ms(durations[durations.len() - 1]); |
| 2446 | println!("{name:<22} {median:>10.2} {min:>10.2} {max:>10.2}"); |
| 2447 | if name == "decode+to_i420_16" { |
| 2448 | got_to_i420_16 = Some(median); |
| 2449 | } |
| 2450 | } |
| 2451 | let got = got_to_i420_16.expect("to_i420_16 phase ran"); |
| 2452 | println!("target: decode+to_i420_16 <= 39.00 ms/frame median (24 fps budget); got {got:.2}"); |
| 2453 | } |
| 2454 | |
| 2455 | const REELD: &str = "/home/user/Downloads/reeld\ |
| 2456 | /reeld.mkv"; |
| 2457 | |
| 2458 | |
| 2459 | |
| 2460 | |
| 2461 | |
| 2462 | |
| 2463 | #[test] |
| 2464 | fn encode_frame_accepts_p010_via_vpp() { |
| 2465 | let Some(display) = display() else { return }; |
| 2466 | let path = Path::new(REELD); |
| 2467 | if !path.exists() { |
| 2468 | eprintln!("skipped: film not present"); |
| 2469 | return; |
| 2470 | } |
| 2471 | let frames = 10usize; |
| 2472 | let Some(data) = elementary(path, Codec::H265, frames) else { |
| 2473 | eprintln!("skipped: no elementary stream"); |
| 2474 | return; |
| 2475 | }; |
| 2476 | |
| 2477 | |
| 2478 | |
| 2479 | |
| 2480 | |
| 2481 | |
| 2482 | |
| 2483 | |
| 2484 | |
| 2485 | let (mut w, mut h) = (0u32, 0u32); |
| 2486 | for (target, dec_codec) in [(EncCodec::H264, Codec::H264), (EncCodec::H265, Codec::H265)] { |
| 2487 | let mut decoder = Decoder::new(&display, Codec::H265).expect("decoder opens"); |
| 2488 | let mut zc_stream = Vec::new(); |
| 2489 | let mut cpu_stream = Vec::new(); |
| 2490 | let mut count = 0i64; |
| 2491 | let mut zero_copy: Option<Encoder> = None; |
| 2492 | let mut cpu_path: Option<Encoder> = None; |
| 2493 | let refused = false; |
| 2494 | |
| 2495 | decode_stream(&mut decoder, Codec::H265, &data, frames, |frame| { |
| 2496 | if refused { |
| 2497 | return; |
| 2498 | } |
| 2499 | (w, h) = frame.display_size; |
| 2500 | let zero_copy = zero_copy.get_or_insert_with(|| { |
| 2501 | let mut cfg = EncoderConfig::new(target, w, h); |
| 2502 | cfg.gop_size = 30; |
| 2503 | cfg.rate_control = RateControlMode::ConstantQp { qp: 22 }; |
| 2504 | Encoder::new(&display, cfg).expect("zero-copy encoder opens") |
| 2505 | }); |
| 2506 | let cpu_path = cpu_path.get_or_insert_with(|| { |
| 2507 | let mut cfg = EncoderConfig::new(target, w, h); |
| 2508 | cfg.gop_size = 30; |
| 2509 | cfg.rate_control = RateControlMode::ConstantQp { qp: 22 }; |
| 2510 | Encoder::new(&display, cfg).expect("cpu-path encoder opens") |
| 2511 | }); |
| 2512 | let meta = FrameMetadata { |
| 2513 | timestamp: count, |
| 2514 | force_keyframe: false, |
| 2515 | }; |
| 2516 | let zc = zero_copy |
| 2517 | .encode_frame(&frame, meta) |
| 2518 | .expect("encode_frame (zero copy, P010 via VPP, size mismatch routed through VPP)"); |
| 2519 | zc_stream.extend_from_slice(&zc.data); |
| 2520 | let i420 = frame.to_i420().expect("readback for the CPU-path baseline"); |
| 2521 | let cpu = cpu_path.encode(&i420, meta).expect("encode (CPU path)"); |
| 2522 | cpu_stream.extend_from_slice(&cpu.data); |
| 2523 | count += 1; |
| 2524 | }) |
| 2525 | .expect("decode"); |
| 2526 | if refused { |
| 2527 | continue; |
| 2528 | } |
| 2529 | assert_eq!( |
| 2530 | count as usize, frames, |
| 2531 | "{target:?}: decoded {count} of {frames}" |
| 2532 | ); |
| 2533 | |
| 2534 | let mut zc_decoder = Decoder::new(&display, dec_codec).expect("zc decoder opens"); |
| 2535 | let mut cpu_decoder = Decoder::new(&display, dec_codec).expect("cpu decoder opens"); |
| 2536 | let mut zc_frames = Vec::new(); |
| 2537 | let mut cpu_frames = Vec::new(); |
| 2538 | decode_stream(&mut zc_decoder, dec_codec, &zc_stream, frames, |f| { |
| 2539 | zc_frames.push(f.to_i420().expect("readback")) |
| 2540 | }) |
| 2541 | .expect("decode zero-copy stream"); |
| 2542 | decode_stream(&mut cpu_decoder, dec_codec, &cpu_stream, frames, |f| { |
| 2543 | cpu_frames.push(f.to_i420().expect("readback")) |
| 2544 | }) |
| 2545 | .expect("decode CPU-path stream"); |
| 2546 | assert_eq!(zc_frames.len(), frames, "{target:?}: zero-copy frame count"); |
| 2547 | assert_eq!(cpu_frames.len(), frames, "{target:?}: CPU-path frame count"); |
| 2548 | |
| 2549 | let widen = |v: &[u8]| -> Vec<u16> { v.iter().map(|&s| u16::from(s)).collect() }; |
| 2550 | let mut worst_y = f64::INFINITY; |
| 2551 | let mut worst_uv = f64::INFINITY; |
| 2552 | for (a, b) in zc_frames.iter().zip(&cpu_frames) { |
| 2553 | let y_db = plane_psnr(&widen(&a.y), &widen(&b.y), 255.0); |
| 2554 | let uv_db = plane_psnr( |
| 2555 | &[widen(&a.u), widen(&a.v)].concat(), |
| 2556 | &[widen(&b.u), widen(&b.v)].concat(), |
| 2557 | 255.0, |
| 2558 | ); |
| 2559 | worst_y = worst_y.min(y_db); |
| 2560 | worst_uv = worst_uv.min(uv_db); |
| 2561 | } |
| 2562 | println!("{target:?} encode_frame (P010 via VPP) vs CPU path: worst Y {worst_y:.1} dB, worst UV {worst_uv:.1} dB"); |
| 2563 | assert!(worst_y >= 40.0, "{target:?}: worst Y {worst_y:.1} dB vs the CPU path"); |
| 2564 | assert!(worst_uv >= 40.0, "{target:?}: worst UV {worst_uv:.1} dB vs the CPU path"); |
| 2565 | |
| 2566 | |
| 2567 | |
| 2568 | |
| 2569 | |
| 2570 | let dir = std::env::temp_dir().join(format!("ec-hw-vpp-region-{target:?}")); |
| 2571 | std::fs::create_dir_all(&dir).expect("temp dir"); |
| 2572 | let path = dir.join(match target { |
| 2573 | EncCodec::H264 => "out.264", |
| 2574 | EncCodec::H265 => "out.265", |
| 2575 | EncCodec::Av1 => "out.obu", |
| 2576 | }); |
| 2577 | std::fs::write(&path, &zc_stream).expect("write bitstream"); |
| 2578 | let probe = Command::new("ffprobe") |
| 2579 | .args([ |
| 2580 | "-v", |
| 2581 | "error", |
| 2582 | "-select_streams", |
| 2583 | "v:0", |
| 2584 | "-show_entries", |
| 2585 | "stream=width,height", |
| 2586 | "-of", |
| 2587 | "csv=p=0", |
| 2588 | ]) |
| 2589 | .arg(&path) |
| 2590 | .output() |
| 2591 | .expect("ffprobe runs"); |
| 2592 | let dims = String::from_utf8_lossy(&probe.stdout).trim().to_string(); |
| 2593 | assert_eq!(dims, format!("{w},{h}"), "{target:?}: ffprobe sees {dims}"); |
| 2594 | } |
| 2595 | } |
| 2596 | |
| 2597 | |
| 2598 | |
| 2599 | |
| 2600 | |
| 2601 | |
| 2602 | |
| 2603 | |
| 2604 | |
| 2605 | |
| 2606 | #[test] |
| 2607 | fn p010_zero_copy_encode_is_realtime() { |
| 2608 | let Some(display) = display() else { return }; |
| 2609 | let path = Path::new(REELD); |
| 2610 | if !path.exists() { |
| 2611 | eprintln!("skipped: film not present"); |
| 2612 | return; |
| 2613 | } |
| 2614 | let limit = 60usize; |
| 2615 | let Some(data) = elementary(path, Codec::H265, limit) else { |
| 2616 | eprintln!("skipped: no elementary stream"); |
| 2617 | return; |
| 2618 | }; |
| 2619 | let units = split_access_units(&data, Codec::H265); |
| 2620 | assert!(units.len() > limit, "film clip too short for {limit} frames"); |
| 2621 | |
| 2622 | println!("{:<28} {:>10} {:>10} {:>10}", "stage", "median ms", "min ms", "max ms"); |
| 2623 | |
| 2624 | let mut rows: Vec<(EncCodec, f64, f64)> = Vec::new(); |
| 2625 | let run_target = |target: EncCodec| -> (f64, f64) { |
| 2626 | let mut zc_median = None; |
| 2627 | let mut cpu_median = None; |
| 2628 | for (label, zero_copy) in [("decode+encode_frame", true), ("decode+to_i420+encode", false)] { |
| 2629 | let name = format!("{target:?} {label}"); |
| 2630 | let mut decoder = Decoder::new(&display, Codec::H265).expect("decoder opens"); |
| 2631 | let mut encoder: Option<Encoder> = None; |
| 2632 | let mut durations: Vec<Duration> = Vec::new(); |
| 2633 | let mut count = 0i64; |
| 2634 | 'outer: for (i, unit) in units.iter().enumerate() { |
| 2635 | decoder.decode(unit, i as i64).expect("decode"); |
| 2636 | while let Some(frame) = decoder.next_frame() { |
| 2637 | let (w, h) = frame.display_size; |
| 2638 | let encoder = encoder.get_or_insert_with(|| { |
| 2639 | let mut cfg = EncoderConfig::new(target, w, h); |
| 2640 | cfg.gop_size = 30; |
| 2641 | cfg.rate_control = RateControlMode::ConstantQp { qp: 22 }; |
| 2642 | Encoder::new(&display, cfg).expect("encoder opens") |
| 2643 | }); |
| 2644 | let meta = FrameMetadata { |
| 2645 | timestamp: count, |
| 2646 | force_keyframe: false, |
| 2647 | }; |
| 2648 | let t0 = Instant::now(); |
| 2649 | if zero_copy { |
| 2650 | encoder.encode_frame(&frame, meta).expect("encode_frame"); |
| 2651 | } else { |
| 2652 | let i420 = frame.to_i420().expect("readback"); |
| 2653 | encoder.encode(&i420, meta).expect("encode"); |
| 2654 | } |
| 2655 | durations.push(t0.elapsed()); |
| 2656 | count += 1; |
| 2657 | if durations.len() >= limit { |
| 2658 | break 'outer; |
| 2659 | } |
| 2660 | } |
| 2661 | } |
| 2662 | assert!( |
| 2663 | durations.len() >= limit, |
| 2664 | "{name}: only {} of {limit} frames encoded", |
| 2665 | durations.len() |
| 2666 | ); |
| 2667 | durations.sort(); |
| 2668 | let ms = |d: Duration| d.as_secs_f64() * 1000.0; |
| 2669 | let median = ms(durations[durations.len() / 2]); |
| 2670 | let min = ms(durations[0]); |
| 2671 | let max = ms(durations[durations.len() - 1]); |
| 2672 | println!("{name:<28} {median:>10.2} {min:>10.2} {max:>10.2}"); |
| 2673 | if zero_copy { |
| 2674 | zc_median = Some(median); |
| 2675 | } else { |
| 2676 | cpu_median = Some(median); |
| 2677 | } |
| 2678 | } |
| 2679 | ( |
| 2680 | zc_median.expect("zero-copy phase ran"), |
| 2681 | cpu_median.expect("CPU-path phase ran"), |
| 2682 | ) |
| 2683 | }; |
| 2684 | for target in [EncCodec::H264, EncCodec::H265] { |
| 2685 | let (mut zc, mut cpu) = run_target(target); |
| 2686 | |
| 2687 | |
| 2688 | |
| 2689 | |
| 2690 | if zc > 20.0 && zc < 30.0 { |
| 2691 | let (zc2, cpu2) = run_target(target); |
| 2692 | if zc2 < zc { |
| 2693 | zc = zc2; |
| 2694 | cpu = cpu2; |
| 2695 | } |
| 2696 | } |
| 2697 | rows.push((target, zc, cpu)); |
| 2698 | } |
| 2699 | for (target, zc, cpu) in rows { |
| 2700 | println!( |
| 2701 | "target: {target:?} decode+encode_frame <= 20.00 ms/frame median; got {zc:.2} (CPU path {cpu:.2})" |
| 2702 | ); |
| 2703 | assert!( |
| 2704 | zc <= 20.0, |
| 2705 | "{target:?}: decode+encode_frame median {zc:.2} ms/frame exceeds the 20 ms budget (CPU path: {cpu:.2} ms)" |
| 2706 | ); |
| 2707 | } |
| 2708 | } |
| 2709 | |
| 2710 | |
| 2711 | |
| 2712 | |
| 2713 | |
| 2714 | |
| 2715 | |
| 2716 | |
| 2717 | #[test] |
| 2718 | fn hevc_seek_matches_linear_mkv() { |
| 2719 | let Some(display) = display() else { return }; |
| 2720 | let path = bitstreams().join("test_hevc.mkv"); |
| 2721 | let Some(data) = elementary(&path, Codec::H265, 45) else { |
| 2722 | eprintln!("skipped: no test_hevc.mkv fixture"); |
| 2723 | return; |
| 2724 | }; |
| 2725 | let units = split_access_units(&data, Codec::H265); |
| 2726 | |
| 2727 | |
| 2728 | |
| 2729 | |
| 2730 | const TARGET: usize = 30; |
| 2731 | let mut decoder = Decoder::new(&display, Codec::H265).expect("decoder opens"); |
| 2732 | let mut linear_frame_30 = None; |
| 2733 | let mut index = 0usize; |
| 2734 | decode_stream(&mut decoder, Codec::H265, &data, 45, |frame| { |
| 2735 | if index == TARGET { |
| 2736 | linear_frame_30 = Some(frame.to_i420().expect("readback")); |
| 2737 | } |
| 2738 | index += 1; |
| 2739 | }) |
| 2740 | .expect("linear decode"); |
| 2741 | let linear_frame_30 = linear_frame_30.expect("linear decode reached frame 30"); |
| 2742 | |
| 2743 | |
| 2744 | |
| 2745 | |
| 2746 | let cra_at = units |
| 2747 | .iter() |
| 2748 | .position(|au| starts_with_cra(au)) |
| 2749 | .expect("a CRA access unit exists"); |
| 2750 | |
| 2751 | |
| 2752 | |
| 2753 | |
| 2754 | |
| 2755 | let mut seek_decoder = Decoder::new(&display, Codec::H265).expect("decoder opens"); |
| 2756 | seek_decoder |
| 2757 | .decode(units[0], 0) |
| 2758 | .expect("prime parameter sets"); |
| 2759 | seek_decoder.reset(); |
| 2760 | let mut seeked_frame = None; |
| 2761 | for (i, unit) in units[cra_at..].iter().enumerate() { |
| 2762 | seek_decoder.decode(unit, i as i64).expect("seek decode"); |
| 2763 | if let Some(frame) = seek_decoder.next_frame() { |
| 2764 | seeked_frame = Some(frame.to_i420().expect("readback")); |
| 2765 | break; |
| 2766 | } |
| 2767 | } |
| 2768 | if seeked_frame.is_none() { |
| 2769 | seek_decoder.flush().expect("flush"); |
| 2770 | seeked_frame = seek_decoder |
| 2771 | .next_frame() |
| 2772 | .map(|f| f.to_i420().expect("readback")); |
| 2773 | } |
| 2774 | let seeked_frame = seeked_frame.expect("a frame came out after the seek"); |
| 2775 | |
| 2776 | assert_eq!( |
| 2777 | seeked_frame, linear_frame_30, |
| 2778 | "seeking to the CRA before frame 30 handed back a different picture \ |
| 2779 | than a linear decode of frame 30 — RASL pictures were not dropped" |
| 2780 | ); |
| 2781 | } |
| 2782 | |
| 2783 | |
| 2784 | |
| 2785 | |
| 2786 | |
| 2787 | |
| 2788 | |
| 2789 | |
| 2790 | #[test] |
| 2791 | fn h264_seek_matches_linear_open_gop() { |
| 2792 | let Some(display) = display() else { return }; |
| 2793 | let path = bitstreams().join("h264-open-gop.mp4"); |
| 2794 | let Some(data) = elementary(&path, Codec::H264, 60) else { |
| 2795 | eprintln!("skipped: no h264-open-gop.mp4 fixture (run scripts/gen-fixtures.sh)"); |
| 2796 | return; |
| 2797 | }; |
| 2798 | let units = split_access_units(&data, Codec::H264); |
| 2799 | |
| 2800 | |
| 2801 | |
| 2802 | const TARGET: usize = 30; |
| 2803 | let mut decoder = Decoder::new(&display, Codec::H264).expect("decoder opens"); |
| 2804 | let mut linear_frame_30 = None; |
| 2805 | let mut index = 0usize; |
| 2806 | decode_stream(&mut decoder, Codec::H264, &data, 60, |frame| { |
| 2807 | if index == TARGET { |
| 2808 | linear_frame_30 = Some(frame.to_i420().expect("readback")); |
| 2809 | } |
| 2810 | index += 1; |
| 2811 | }) |
| 2812 | .expect("linear decode"); |
| 2813 | let linear_frame_30 = linear_frame_30.expect("linear decode reached frame 30"); |
| 2814 | |
| 2815 | |
| 2816 | |
| 2817 | |
| 2818 | let open_gop_at = units |
| 2819 | .iter() |
| 2820 | .position(|au| is_open_gop_i(au)) |
| 2821 | .expect("an open-GOP I access unit exists"); |
| 2822 | |
| 2823 | |
| 2824 | |
| 2825 | |
| 2826 | |
| 2827 | let mut seek_decoder = Decoder::new(&display, Codec::H264).expect("decoder opens"); |
| 2828 | seek_decoder.decode(units[0], 0).expect("prime parameter sets"); |
| 2829 | seek_decoder.reset(); |
| 2830 | let mut seeked_frame = None; |
| 2831 | for (i, unit) in units[open_gop_at..].iter().enumerate() { |
| 2832 | seek_decoder.decode(unit, i as i64).expect("seek decode"); |
| 2833 | if let Some(frame) = seek_decoder.next_frame() { |
| 2834 | seeked_frame = Some(frame.to_i420().expect("readback")); |
| 2835 | break; |
| 2836 | } |
| 2837 | } |
| 2838 | if seeked_frame.is_none() { |
| 2839 | seek_decoder.flush().expect("flush"); |
| 2840 | seeked_frame = seek_decoder |
| 2841 | .next_frame() |
| 2842 | .map(|f| f.to_i420().expect("readback")); |
| 2843 | } |
| 2844 | let seeked_frame = seeked_frame.expect("a frame came out after the seek"); |
| 2845 | |
| 2846 | assert_eq!( |
| 2847 | seeked_frame, linear_frame_30, |
| 2848 | "seeking to the open-GOP I before frame 30 handed back a different \ |
| 2849 | picture than a linear decode of frame 30 — leading pictures with \ |
| 2850 | missing references were not dropped" |
| 2851 | ); |
| 2852 | } |
| 2853 | |
| 2854 | |
| 2855 | |
| 2856 | |
| 2857 | fn is_open_gop_i(au: &[u8]) -> bool { |
| 2858 | let mut i = 0usize; |
| 2859 | while i + 3 < au.len() { |
| 2860 | if au[i] != 0 || au[i + 1] != 0 || au[i + 2] != 1 { |
| 2861 | i += 1; |
| 2862 | continue; |
| 2863 | } |
| 2864 | let header = au[i + 3]; |
| 2865 | if header & 0x1f != 1 { |
| 2866 | return false; |
| 2867 | } |
| 2868 | let mut r = ec_core::BitReader::new(&au[i + 4..]); |
| 2869 | if r.read_ue().is_err() { |
| 2870 | return false; |
| 2871 | } |
| 2872 | return matches!(r.read_ue(), Ok(code) if code % 5 == 2); |
| 2873 | } |
| 2874 | false |
| 2875 | } |
| 2876 | |
| 2877 | |
| 2878 | |
| 2879 | |
| 2880 | fn starts_with_cra(au: &[u8]) -> bool { |
| 2881 | let mut i = 0usize; |
| 2882 | while i + 3 < au.len() { |
| 2883 | if au[i] == 0 && au[i + 1] == 0 && au[i + 2] == 1 { |
| 2884 | let t = (au[i + 3] >> 1) & 0x3f; |
| 2885 | if t <= 31 { |
| 2886 | return t == 21; |
| 2887 | } |
| 2888 | i += 3; |
| 2889 | continue; |
| 2890 | } |
| 2891 | i += 1; |
| 2892 | } |
| 2893 | false |
| 2894 | } |
| 2895 | |
| 2896 | |
| 2897 | |
| 2898 | fn trace_headers(path: &Path, codec: &str) -> Vec<(String, i64)> { |
| 2899 | let out = Command::new("ffmpeg") |
| 2900 | .args(["-v", "trace", "-hide_banner", "-nostats", "-f", codec, "-i"]) |
| 2901 | .arg(path) |
| 2902 | .args(["-c:v", "copy", "-bsf:v", "trace_headers", "-f", "null", "-"]) |
| 2903 | .output() |
| 2904 | .expect("ffmpeg runs"); |
| 2905 | let text = String::from_utf8_lossy(&out.stderr); |
| 2906 | text.lines() |
| 2907 | .filter_map(|line| { |
| 2908 | |
| 2909 | let (lhs, value) = line.rsplit_once(" = ")?; |
| 2910 | let mut words = lhs.split_whitespace().rev(); |
| 2911 | let _bits = words.next()?; |
| 2912 | let name = words.next()?; |
| 2913 | Some((name.to_string(), value.trim().parse().ok()?)) |
| 2914 | }) |
| 2915 | .collect() |
| 2916 | } |
| 2917 | |
| 2918 | |
| 2919 | |
| 2920 | |
| 2921 | |
| 2922 | fn slice_counters(codec: EncCodec, width: u32, height: u32, frames: u32) -> (PathBuf, Vec<(String, i64)>) { |
| 2923 | let Some(display) = display() else { return (PathBuf::new(), Vec::new()) }; |
| 2924 | let mut config = EncoderConfig::new(codec, width, height); |
| 2925 | config.gop_size = frames * 2; |
| 2926 | config.framerate = (30, 1); |
| 2927 | config.rate_control = RateControlMode::ConstantQp { qp: 30 }; |
| 2928 | let mut encoder = Encoder::new(&display, config).expect("encoder"); |
| 2929 | let mut out = Vec::new(); |
| 2930 | for t in 0..frames { |
| 2931 | let coded = encoder |
| 2932 | .encode(&source_frame(width, height, t), FrameMetadata { timestamp: i64::from(t), force_keyframe: false }) |
| 2933 | .expect("encode"); |
| 2934 | assert_eq!(coded.is_keyframe, t == 0, "one IDR then P-frames at {t}"); |
| 2935 | out.extend_from_slice(&coded.data); |
| 2936 | } |
| 2937 | let dir = std::env::temp_dir().join(format!("ec-hw-counters-{codec:?}")); |
| 2938 | std::fs::create_dir_all(&dir).expect("temp dir"); |
| 2939 | let (name, fmt) = match codec { |
| 2940 | EncCodec::H264 => ("out.264", "h264"), |
| 2941 | EncCodec::H265 => ("out.265", "hevc"), |
| 2942 | EncCodec::Av1 => unreachable!(), |
| 2943 | }; |
| 2944 | let path = dir.join(name); |
| 2945 | std::fs::write(&path, &out).expect("write"); |
| 2946 | let fields = trace_headers(&path, fmt); |
| 2947 | (path, fields) |
| 2948 | } |
| 2949 | |
| 2950 | fn values<'a>(fields: &'a [(String, i64)], name: &str) -> Vec<i64> { |
| 2951 | fields.iter().filter(|(n, _)| n == name).map(|(_, v)| *v).collect() |
| 2952 | } |
| 2953 | |
| 2954 | #[test] |
| 2955 | fn h264_slice_headers_count_frames_for_stateful_decoders() { |
| 2956 | let frames = 64u32; |
| 2957 | let (path, fields) = slice_counters(EncCodec::H264, 640, 360, frames); |
| 2958 | if fields.is_empty() { |
| 2959 | return; |
| 2960 | } |
| 2961 | let frame_num = values(&fields, "frame_num"); |
| 2962 | assert_eq!(frame_num.len(), frames as usize, "one slice per picture in {}", path.display()); |
| 2963 | let log2_max = values(&fields, "log2_max_frame_num_minus4")[0] + 4; |
| 2964 | let max_frame_num = 1i64 << log2_max; |
| 2965 | let expected: Vec<i64> = (0..frames as i64).map(|n| n % max_frame_num).collect(); |
| 2966 | assert_eq!(frame_num, expected, "frame_num steps +1 mod {max_frame_num}"); |
| 2967 | |
| 2968 | |
| 2969 | let poc_type = values(&fields, "pic_order_cnt_type"); |
| 2970 | assert!(!poc_type.is_empty() && poc_type.iter().all(|&t| t == 2), "POC type 2 in the SPS: {poc_type:?}"); |
| 2971 | assert!(values(&fields, "pic_order_cnt_lsb").is_empty(), "no POC lsb under type 2"); |
| 2972 | assert!(values(&fields, "level_idc").iter().all(|&l| l == 30), "640x360@30 is level 3.0"); |
| 2973 | } |
| 2974 | |
| 2975 | #[test] |
| 2976 | fn hevc_slice_headers_count_pocs_for_stateful_decoders() { |
| 2977 | let frames = 64u32; |
| 2978 | let (path, fields) = slice_counters(EncCodec::H265, 640, 360, frames); |
| 2979 | if fields.is_empty() { |
| 2980 | return; |
| 2981 | } |
| 2982 | let lsb = values(&fields, "slice_pic_order_cnt_lsb"); |
| 2983 | assert_eq!(lsb.len(), frames as usize - 1, "every non-IDR slice carries a POC lsb in {}", path.display()); |
| 2984 | let log2_max = values(&fields, "log2_max_pic_order_cnt_lsb_minus4")[0] + 4; |
| 2985 | let max_lsb = 1i64 << log2_max; |
| 2986 | let expected: Vec<i64> = (1..frames as i64).map(|n| n % max_lsb).collect(); |
| 2987 | assert_eq!(lsb, expected, "POC lsb steps +1 mod {max_lsb}"); |
| 2988 | } |