| 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, RateControlMode, |
| 19 | }; |
| 20 | use ec_va::Display; |
| 21 | |
| 22 | |
| 23 | |
| 24 | const FRAMES: usize = 24; |
| 25 | |
| 26 | fn bitstreams() -> PathBuf { |
| 27 | Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/bitstreams") |
| 28 | } |
| 29 | |
| 30 | fn display() -> Option<Arc<Display>> { |
| 31 | match Display::open() { |
| 32 | Ok(display) => Some(display), |
| 33 | Err(e) => { |
| 34 | eprintln!("skipped: no VA display ({e})"); |
| 35 | None |
| 36 | } |
| 37 | } |
| 38 | } |
| 39 | |
| 40 | fn fixtures(pattern: &str) -> Vec<PathBuf> { |
| 41 | let Ok(dir) = std::fs::read_dir(bitstreams()) else { |
| 42 | return Vec::new(); |
| 43 | }; |
| 44 | let mut out: Vec<PathBuf> = dir |
| 45 | .flatten() |
| 46 | .map(|e| e.path()) |
| 47 | .filter(|p| { |
| 48 | p.file_name() |
| 49 | .and_then(|n| n.to_str()) |
| 50 | .is_some_and(|n| n.ends_with(pattern)) |
| 51 | }) |
| 52 | .collect(); |
| 53 | out.sort(); |
| 54 | out |
| 55 | } |
| 56 | |
| 57 | |
| 58 | struct Reference { |
| 59 | child: std::process::Child, |
| 60 | frame_bytes: usize, |
| 61 | ten_bit: bool, |
| 62 | } |
| 63 | |
| 64 | impl Reference { |
| 65 | fn open(path: &Path, width: u32, height: u32, ten_bit: bool) -> Option<Reference> { |
| 66 | let pix = if ten_bit { "yuv420p10le" } else { "yuv420p" }; |
| 67 | let child = Command::new("ffmpeg") |
| 68 | .args(["-nostdin", "-v", "error", "-i"]) |
| 69 | .arg(path) |
| 70 | |
| 71 | |
| 72 | |
| 73 | |
| 74 | .args([ |
| 75 | "-map", |
| 76 | "0:v:0", |
| 77 | "-fps_mode", |
| 78 | "passthrough", |
| 79 | "-pix_fmt", |
| 80 | pix, |
| 81 | "-f", |
| 82 | "rawvideo", |
| 83 | "-", |
| 84 | ]) |
| 85 | .stdout(Stdio::piped()) |
| 86 | .stderr(Stdio::null()) |
| 87 | .spawn() |
| 88 | .ok()?; |
| 89 | let samples = (width as usize * height as usize * 3).div_ceil(2); |
| 90 | Some(Reference { |
| 91 | child, |
| 92 | frame_bytes: if ten_bit { samples * 2 } else { samples }, |
| 93 | ten_bit, |
| 94 | }) |
| 95 | } |
| 96 | |
| 97 | |
| 98 | |
| 99 | |
| 100 | |
| 101 | |
| 102 | fn next(&mut self, width: u32, height: u32) -> Option<Planes> { |
| 103 | let stdout = self.child.stdout.as_mut()?; |
| 104 | let mut buf = vec![0u8; self.frame_bytes]; |
| 105 | stdout.read_exact(&mut buf).ok()?; |
| 106 | let (w, h) = (width as usize, height as usize); |
| 107 | let (cw, ch) = (w.div_ceil(2), h.div_ceil(2)); |
| 108 | let (y_len, c_len) = (w * h, cw * ch); |
| 109 | if self.ten_bit { |
| 110 | let read = |slice: &[u8]| -> Vec<u16> { |
| 111 | slice |
| 112 | .chunks_exact(2) |
| 113 | .map(|p| u16::from_le_bytes([p[0], p[1]])) |
| 114 | .collect() |
| 115 | }; |
| 116 | Some(Planes { |
| 117 | y: read(&buf[..y_len * 2]), |
| 118 | u: read(&buf[y_len * 2..(y_len + c_len) * 2]), |
| 119 | v: read(&buf[(y_len + c_len) * 2..(y_len + 2 * c_len) * 2]), |
| 120 | peak: 1023.0, |
| 121 | }) |
| 122 | } else { |
| 123 | let read = |slice: &[u8]| -> Vec<u16> { slice.iter().map(|&v| u16::from(v)).collect() }; |
| 124 | Some(Planes { |
| 125 | y: read(&buf[..y_len]), |
| 126 | u: read(&buf[y_len..y_len + c_len]), |
| 127 | v: read(&buf[y_len + c_len..y_len + 2 * c_len]), |
| 128 | peak: 255.0, |
| 129 | }) |
| 130 | } |
| 131 | } |
| 132 | } |
| 133 | |
| 134 | impl Drop for Reference { |
| 135 | fn drop(&mut self) { |
| 136 | let _ = self.child.kill(); |
| 137 | let _ = self.child.wait(); |
| 138 | } |
| 139 | } |
| 140 | |
| 141 | |
| 142 | struct Planes { |
| 143 | y: Vec<u16>, |
| 144 | u: Vec<u16>, |
| 145 | v: Vec<u16>, |
| 146 | peak: f64, |
| 147 | } |
| 148 | |
| 149 | impl Planes { |
| 150 | fn from_8bit(f: &I420) -> Planes { |
| 151 | let read = |v: &[u8]| -> Vec<u16> { v.iter().map(|&s| u16::from(s)).collect() }; |
| 152 | Planes { |
| 153 | y: read(&f.y), |
| 154 | u: read(&f.u), |
| 155 | v: read(&f.v), |
| 156 | peak: 255.0, |
| 157 | } |
| 158 | } |
| 159 | |
| 160 | fn from_16bit(f: &ec_hw::I420_16) -> Planes { |
| 161 | Planes { |
| 162 | y: f.y.clone(), |
| 163 | u: f.u.clone(), |
| 164 | v: f.v.clone(), |
| 165 | peak: 1023.0, |
| 166 | } |
| 167 | } |
| 168 | } |
| 169 | |
| 170 | |
| 171 | |
| 172 | fn psnr(a: &Planes, b: &Planes) -> f64 { |
| 173 | let mut sum = 0f64; |
| 174 | let mut n = 0usize; |
| 175 | for (x, y) in [(&a.y, &b.y), (&a.u, &b.u), (&a.v, &b.v)] { |
| 176 | for (p, q) in x.iter().zip(y.iter()) { |
| 177 | let d = f64::from(*p) - f64::from(*q); |
| 178 | sum += d * d; |
| 179 | } |
| 180 | n += x.len().min(y.len()); |
| 181 | } |
| 182 | if n == 0 { |
| 183 | return 0.0; |
| 184 | } |
| 185 | let mse = sum / n as f64; |
| 186 | if mse == 0.0 { |
| 187 | return f64::INFINITY; |
| 188 | } |
| 189 | 10.0 * (a.peak * a.peak / mse).log10() |
| 190 | } |
| 191 | |
| 192 | |
| 193 | |
| 194 | |
| 195 | |
| 196 | fn decode_stream( |
| 197 | decoder: &mut Decoder, |
| 198 | codec: Codec, |
| 199 | data: &[u8], |
| 200 | limit: usize, |
| 201 | mut on_frame: impl FnMut(Frame), |
| 202 | ) -> Result<usize, ec_hw::Error> { |
| 203 | let mut count = 0usize; |
| 204 | let units: Vec<&[u8]> = match codec { |
| 205 | Codec::H264 | Codec::H265 => split_access_units(data, codec), |
| 206 | Codec::Vp9 | Codec::Av1 => split_ivf(data), |
| 207 | }; |
| 208 | for (i, unit) in units.iter().enumerate() { |
| 209 | decoder.decode(unit, i as i64)?; |
| 210 | while let Some(frame) = decoder.next_frame() { |
| 211 | count += 1; |
| 212 | on_frame(frame); |
| 213 | if count >= limit { |
| 214 | return Ok(count); |
| 215 | } |
| 216 | } |
| 217 | } |
| 218 | decoder.flush()?; |
| 219 | while let Some(frame) = decoder.next_frame() { |
| 220 | count += 1; |
| 221 | on_frame(frame); |
| 222 | if count >= limit { |
| 223 | break; |
| 224 | } |
| 225 | } |
| 226 | Ok(count) |
| 227 | } |
| 228 | |
| 229 | |
| 230 | |
| 231 | |
| 232 | fn split_access_units(data: &[u8], codec: Codec) -> Vec<&[u8]> { |
| 233 | let mut starts: Vec<usize> = Vec::new(); |
| 234 | let mut seen_slice = false; |
| 235 | let mut i = 0usize; |
| 236 | while i + 3 < data.len() { |
| 237 | if data[i] != 0 || data[i + 1] != 0 || data[i + 2] != 1 { |
| 238 | i += 1; |
| 239 | continue; |
| 240 | } |
| 241 | let nal = i + 3; |
| 242 | let (is_vcl, first_slice) = match codec { |
| 243 | Codec::H264 => { |
| 244 | let t = data[nal] & 0x1f; |
| 245 | let first = data.get(nal + 1).is_some_and(|&b| b & 0x80 != 0); |
| 246 | ((1..=5).contains(&t), first) |
| 247 | } |
| 248 | _ => { |
| 249 | let t = (data[nal] >> 1) & 0x3f; |
| 250 | let first = data.get(nal + 2).is_some_and(|&b| b & 0x80 != 0); |
| 251 | (t <= 31, first) |
| 252 | } |
| 253 | }; |
| 254 | if is_vcl { |
| 255 | if seen_slice && first_slice { |
| 256 | starts.push(i); |
| 257 | seen_slice = false; |
| 258 | } |
| 259 | if first_slice { |
| 260 | seen_slice = true; |
| 261 | } |
| 262 | } |
| 263 | i = nal + 1; |
| 264 | } |
| 265 | let mut out = Vec::new(); |
| 266 | let mut prev = 0usize; |
| 267 | for &start in &starts { |
| 268 | out.push(&data[prev..start]); |
| 269 | prev = start; |
| 270 | } |
| 271 | if prev < data.len() { |
| 272 | out.push(&data[prev..]); |
| 273 | } |
| 274 | out |
| 275 | } |
| 276 | |
| 277 | |
| 278 | fn split_ivf(data: &[u8]) -> Vec<&[u8]> { |
| 279 | let mut out = Vec::new(); |
| 280 | if data.len() < 32 || &data[..4] != b"DKIF" { |
| 281 | return out; |
| 282 | } |
| 283 | let header = u16::from_le_bytes([data[6], data[7]]) as usize; |
| 284 | let mut pos = header.max(32); |
| 285 | while pos + 12 <= data.len() { |
| 286 | let size = |
| 287 | u32::from_le_bytes([data[pos], data[pos + 1], data[pos + 2], data[pos + 3]]) as usize; |
| 288 | pos += 12; |
| 289 | if pos + size > data.len() { |
| 290 | break; |
| 291 | } |
| 292 | out.push(&data[pos..pos + size]); |
| 293 | pos += size; |
| 294 | } |
| 295 | out |
| 296 | } |
| 297 | |
| 298 | |
| 299 | fn compare_against_ffmpeg(files: &[PathBuf], codec: Codec, ten_bit: bool) { |
| 300 | let Some(display) = display() else { return }; |
| 301 | if files.is_empty() { |
| 302 | eprintln!("skipped: no fixtures — run scripts/gen-bitstream-fixtures.sh"); |
| 303 | return; |
| 304 | } |
| 305 | let mut table = Vec::new(); |
| 306 | for path in files { |
| 307 | let data = std::fs::read(path).expect("fixture is readable"); |
| 308 | let mut decoder = Decoder::new(&display, codec).expect("decoder opens"); |
| 309 | let mut reference: Option<Reference> = None; |
| 310 | let mut worst = f64::INFINITY; |
| 311 | let mut identical = 0usize; |
| 312 | let mut compared = 0usize; |
| 313 | let mut mismatched_size = false; |
| 314 | |
| 315 | let result = decode_stream(&mut decoder, codec, &data, FRAMES, |frame| { |
| 316 | let (w, h) = frame.display_size; |
| 317 | let reference = reference |
| 318 | .get_or_insert_with(|| Reference::open(path, w, h, ten_bit).expect("ffmpeg runs")); |
| 319 | let Some(want) = reference.next(w, h) else { |
| 320 | return; |
| 321 | }; |
| 322 | let got = if ten_bit { |
| 323 | Planes::from_16bit(&frame.to_i420_16().expect("readback")) |
| 324 | } else { |
| 325 | Planes::from_8bit(&frame.to_i420().expect("readback")) |
| 326 | }; |
| 327 | if got.y.len() != want.y.len() { |
| 328 | mismatched_size = true; |
| 329 | return; |
| 330 | } |
| 331 | let db = psnr(&got, &want); |
| 332 | if std::env::var_os("EC_HW_DEBUG").is_some() { |
| 333 | eprintln!(" frame {compared}: {db:.1} dB (ts {})", frame.timestamp); |
| 334 | } |
| 335 | if db.is_infinite() { |
| 336 | identical += 1; |
| 337 | } |
| 338 | worst = worst.min(db); |
| 339 | compared += 1; |
| 340 | }); |
| 341 | let decoded = result.expect("decode succeeds"); |
| 342 | assert!( |
| 343 | !mismatched_size, |
| 344 | "{}: frame size disagrees with ffmpeg", |
| 345 | path.display() |
| 346 | ); |
| 347 | assert!(compared > 0, "{}: nothing decoded", path.display()); |
| 348 | table.push(format!( |
| 349 | "{:<40} {decoded:>3} frames, {identical:>3}/{compared} identical, worst {}", |
| 350 | path.file_name().unwrap_or_default().to_string_lossy(), |
| 351 | if worst.is_infinite() { |
| 352 | "exact".to_string() |
| 353 | } else { |
| 354 | format!("{worst:.1} dB") |
| 355 | } |
| 356 | )); |
| 357 | assert!( |
| 358 | worst >= 40.0, |
| 359 | "{}: worst frame PSNR {worst:.1} dB against ffmpeg", |
| 360 | path.display() |
| 361 | ); |
| 362 | } |
| 363 | for row in table { |
| 364 | println!("{row}"); |
| 365 | } |
| 366 | } |
| 367 | |
| 368 | |
| 369 | |
| 370 | fn profile_420(pattern: &str, codec: &str) -> Vec<PathBuf> { |
| 371 | fixtures(pattern) |
| 372 | .into_iter() |
| 373 | .filter(|p| { |
| 374 | let name = p.to_string_lossy().to_string(); |
| 375 | name.contains(codec) && !name.contains("444") && !name.contains("monochrome") |
| 376 | }) |
| 377 | .collect() |
| 378 | } |
| 379 | |
| 380 | fn eight_bit(pattern: &str, codec: &str) -> Vec<PathBuf> { |
| 381 | profile_420(pattern, codec) |
| 382 | .into_iter() |
| 383 | .filter(|p| !p.to_string_lossy().contains("10bit")) |
| 384 | .collect() |
| 385 | } |
| 386 | |
| 387 | fn ten_bit(pattern: &str, codec: &str) -> Vec<PathBuf> { |
| 388 | profile_420(pattern, codec) |
| 389 | .into_iter() |
| 390 | .filter(|p| p.to_string_lossy().contains("10bit")) |
| 391 | .collect() |
| 392 | } |
| 393 | |
| 394 | #[test] |
| 395 | fn h264_matches_ffmpeg() { |
| 396 | compare_against_ffmpeg(&fixtures(".264"), Codec::H264, false); |
| 397 | } |
| 398 | |
| 399 | #[test] |
| 400 | fn hevc_8bit_matches_ffmpeg() { |
| 401 | compare_against_ffmpeg(&eight_bit(".265", "hevc"), Codec::H265, false); |
| 402 | } |
| 403 | |
| 404 | |
| 405 | |
| 406 | |
| 407 | #[test] |
| 408 | fn hevc_10bit_decodes_to_p010() { |
| 409 | let files = ten_bit(".265", "hevc"); |
| 410 | if files.is_empty() { |
| 411 | eprintln!("skipped: no 10-bit HEVC fixtures"); |
| 412 | return; |
| 413 | } |
| 414 | let Some(display) = display() else { return }; |
| 415 | let data = std::fs::read(&files[0]).expect("fixture is readable"); |
| 416 | let mut decoder = Decoder::new(&display, Codec::H265).expect("decoder opens"); |
| 417 | let mut depth = 0u8; |
| 418 | decode_stream(&mut decoder, Codec::H265, &data, 1, |frame| { |
| 419 | depth = frame.bit_depth; |
| 420 | }) |
| 421 | .expect("decode succeeds"); |
| 422 | assert_eq!(depth, 10, "a Main10 stream decoded at {depth} bits"); |
| 423 | let info = decoder.stream_info().expect("the session exists"); |
| 424 | assert_eq!(info.bit_depth, 10); |
| 425 | assert_eq!(info.profile, ec_va::caps::Profile::HEVCMain10); |
| 426 | |
| 427 | compare_against_ffmpeg(&files, Codec::H265, true); |
| 428 | } |
| 429 | |
| 430 | #[test] |
| 431 | fn vp9_matches_ffmpeg() { |
| 432 | compare_against_ffmpeg(&eight_bit(".ivf", "vp9"), Codec::Vp9, false); |
| 433 | } |
| 434 | |
| 435 | #[test] |
| 436 | fn vp9_10bit_matches_ffmpeg() { |
| 437 | compare_against_ffmpeg(&ten_bit(".ivf", "vp9"), Codec::Vp9, true); |
| 438 | } |
| 439 | |
| 440 | #[test] |
| 441 | fn av1_matches_ffmpeg() { |
| 442 | compare_against_ffmpeg(&eight_bit(".ivf", "av1"), Codec::Av1, false); |
| 443 | } |
| 444 | |
| 445 | #[test] |
| 446 | fn av1_10bit_matches_ffmpeg() { |
| 447 | compare_against_ffmpeg(&ten_bit(".ivf", "av1"), Codec::Av1, true); |
| 448 | } |
| 449 | |
| 450 | |
| 451 | |
| 452 | |
| 453 | |
| 454 | #[test] |
| 455 | fn unsupported_profiles_are_refused_with_a_reason() { |
| 456 | let Some(display) = display() else { return }; |
| 457 | let caps = ec_va::CapReport::probe(&display).expect("caps probe"); |
| 458 | for (file, codec, absent) in [ |
| 459 | ( |
| 460 | "vp9-profile1-444.ivf", |
| 461 | Codec::Vp9, |
| 462 | ec_va::caps::Profile::VP9Profile1, |
| 463 | ), |
| 464 | ( |
| 465 | "av1-profile1-444.ivf", |
| 466 | Codec::Av1, |
| 467 | ec_va::caps::Profile::AV1Profile1, |
| 468 | ), |
| 469 | ] { |
| 470 | let path = bitstreams().join(file); |
| 471 | if !path.exists() { |
| 472 | eprintln!("skipped: no {file}"); |
| 473 | continue; |
| 474 | } |
| 475 | assert!( |
| 476 | !caps.supports(absent, ec_va::caps::Entrypoint::VLD), |
| 477 | "{absent:?} is in fact supported — the refusal below would be a bug" |
| 478 | ); |
| 479 | let data = std::fs::read(&path).expect("fixture is readable"); |
| 480 | let mut decoder = Decoder::new(&display, codec).expect("decoder opens"); |
| 481 | let err = decode_stream(&mut decoder, codec, &data, 1, |_| {}) |
| 482 | .expect_err("a 4:4:4 stream must be refused"); |
| 483 | let message = err.to_string(); |
| 484 | assert!( |
| 485 | matches!(err, ec_hw::Error::Unsupported { .. }), |
| 486 | "{file}: expected a typed refusal, got {message}" |
| 487 | ); |
| 488 | println!("{file}: {message}"); |
| 489 | } |
| 490 | } |
| 491 | |
| 492 | |
| 493 | |
| 494 | |
| 495 | |
| 496 | |
| 497 | |
| 498 | fn source_frame(width: u32, height: u32, t: u32) -> I420 { |
| 499 | let (w, h) = (width as usize, height as usize); |
| 500 | let (cw, ch) = (w.div_ceil(2), h.div_ceil(2)); |
| 501 | let mut f = I420 { |
| 502 | y: vec![0; w * h], |
| 503 | u: vec![128; cw * ch], |
| 504 | v: vec![128; cw * ch], |
| 505 | width, |
| 506 | height, |
| 507 | }; |
| 508 | for y in 0..h { |
| 509 | for x in 0..w { |
| 510 | f.y[y * w + x] = ((x * 200 / w) + (y * 55 / h)) as u8; |
| 511 | } |
| 512 | } |
| 513 | let (bx, by) = ((t as usize * 7) % (w - 64), (t as usize * 5) % (h - 64)); |
| 514 | for y in by..by + 64 { |
| 515 | for x in bx..bx + 64 { |
| 516 | f.y[y * w + x] = 235; |
| 517 | } |
| 518 | } |
| 519 | for y in by / 2..(by + 64) / 2 { |
| 520 | for x in bx / 2..(bx + 64) / 2 { |
| 521 | f.u[y * cw + x] = 90; |
| 522 | f.v[y * cw + x] = 240; |
| 523 | } |
| 524 | } |
| 525 | f |
| 526 | } |
| 527 | |
| 528 | |
| 529 | fn encode_stream( |
| 530 | display: &Arc<Display>, |
| 531 | codec: EncCodec, |
| 532 | width: u32, |
| 533 | height: u32, |
| 534 | frames: u32, |
| 535 | allow_av1: bool, |
| 536 | ) -> Result<Vec<u8>, ec_hw::Error> { |
| 537 | let mut config = EncoderConfig::new(codec, width, height); |
| 538 | config.gop_size = 30; |
| 539 | config.framerate = (30, 1); |
| 540 | config.rate_control = RateControlMode::ConstantQp { qp: 26 }; |
| 541 | config.allow_av1 = allow_av1; |
| 542 | let mut encoder = Encoder::new(display, config)?; |
| 543 | let mut out = Vec::new(); |
| 544 | for t in 0..frames { |
| 545 | let coded = encoder.encode( |
| 546 | &source_frame(width, height, t), |
| 547 | FrameMetadata { |
| 548 | timestamp: i64::from(t), |
| 549 | force_keyframe: false, |
| 550 | }, |
| 551 | )?; |
| 552 | assert_eq!(coded.is_keyframe, t == 0, "GOP structure at frame {t}"); |
| 553 | out.extend_from_slice(&coded.data); |
| 554 | } |
| 555 | Ok(out) |
| 556 | } |
| 557 | |
| 558 | |
| 559 | fn round_trip(codec: EncCodec, width: u32, height: u32, min_db: f64) { |
| 560 | let Some(display) = display() else { return }; |
| 561 | let frames = 12u32; |
| 562 | let stream = match encode_stream(&display, codec, width, height, frames, false) { |
| 563 | Ok(stream) => stream, |
| 564 | Err(e) => panic!("{codec:?} encode failed: {e}"), |
| 565 | }; |
| 566 | assert!( |
| 567 | stream.len() > 1000, |
| 568 | "{codec:?}: {} bytes is not a stream", |
| 569 | stream.len() |
| 570 | ); |
| 571 | |
| 572 | let dir = std::env::temp_dir().join(format!("ec-hw-{codec:?}-{width}x{height}")); |
| 573 | std::fs::create_dir_all(&dir).expect("temp dir"); |
| 574 | let path = dir.join(match codec { |
| 575 | EncCodec::H264 => "out.264", |
| 576 | EncCodec::H265 => "out.265", |
| 577 | EncCodec::Av1 => "out.obu", |
| 578 | }); |
| 579 | std::fs::write(&path, &stream).expect("write bitstream"); |
| 580 | |
| 581 | |
| 582 | |
| 583 | let probe = Command::new("ffprobe") |
| 584 | .args([ |
| 585 | "-v", |
| 586 | "error", |
| 587 | "-select_streams", |
| 588 | "v:0", |
| 589 | "-show_entries", |
| 590 | "stream=width,height", |
| 591 | "-of", |
| 592 | "csv=p=0", |
| 593 | ]) |
| 594 | .arg(&path) |
| 595 | .output() |
| 596 | .expect("ffprobe runs"); |
| 597 | let dims = String::from_utf8_lossy(&probe.stdout).trim().to_string(); |
| 598 | assert_eq!( |
| 599 | dims, |
| 600 | format!("{width},{height}"), |
| 601 | "{codec:?}: ffprobe sees {dims}" |
| 602 | ); |
| 603 | |
| 604 | let mut reference = Reference::open(&path, width, height, false).expect("ffmpeg runs"); |
| 605 | let mut worst = f64::INFINITY; |
| 606 | let mut compared = 0u32; |
| 607 | for t in 0..frames { |
| 608 | let Some(got) = reference.next(width, height) else { |
| 609 | break; |
| 610 | }; |
| 611 | let want = Planes::from_8bit(&source_frame(width, height, t)); |
| 612 | let db = psnr(&got, &want); |
| 613 | worst = worst.min(db); |
| 614 | compared += 1; |
| 615 | } |
| 616 | assert_eq!( |
| 617 | compared, frames, |
| 618 | "{codec:?}: ffmpeg decoded {compared} of {frames}" |
| 619 | ); |
| 620 | println!( |
| 621 | "{codec:?} {width}x{height}: {compared} frames, {} bytes, worst {worst:.1} dB vs source", |
| 622 | stream.len() |
| 623 | ); |
| 624 | assert!( |
| 625 | worst >= min_db, |
| 626 | "{codec:?}: worst frame {worst:.1} dB against the source" |
| 627 | ); |
| 628 | } |
| 629 | |
| 630 | #[test] |
| 631 | fn h264_encode_round_trips_through_ffmpeg() { |
| 632 | round_trip(EncCodec::H264, 640, 480, 30.0); |
| 633 | } |
| 634 | |
| 635 | #[test] |
| 636 | fn hevc_encode_round_trips_through_ffmpeg() { |
| 637 | round_trip(EncCodec::H265, 640, 480, 30.0); |
| 638 | } |
| 639 | |
| 640 | |
| 641 | |
| 642 | #[test] |
| 643 | fn hevc_encode_honours_the_conformance_window() { |
| 644 | round_trip(EncCodec::H265, 1916, 1080, 30.0); |
| 645 | } |
| 646 | |
| 647 | |
| 648 | #[test] |
| 649 | fn our_encoder_and_our_decoder_agree() { |
| 650 | let Some(display) = display() else { return }; |
| 651 | for (enc, dec) in [(EncCodec::H264, Codec::H264), (EncCodec::H265, Codec::H265)] { |
| 652 | let stream = encode_stream(&display, enc, 640, 480, 12, false).expect("encode"); |
| 653 | let mut decoder = Decoder::new(&display, dec).expect("decoder opens"); |
| 654 | let mut worst = f64::INFINITY; |
| 655 | let mut count = 0u32; |
| 656 | decode_stream(&mut decoder, dec, &stream, 12, |frame| { |
| 657 | let got = Planes::from_8bit(&frame.to_i420().expect("readback")); |
| 658 | let want = Planes::from_8bit(&source_frame(640, 480, count)); |
| 659 | worst = worst.min(psnr(&got, &want)); |
| 660 | count += 1; |
| 661 | }) |
| 662 | .expect("decode"); |
| 663 | assert_eq!(count, 12, "{enc:?}: decoded {count} of 12 frames"); |
| 664 | println!("{enc:?} -> our decoder: {count} frames, worst {worst:.1} dB vs source"); |
| 665 | assert!(worst >= 30.0, "{enc:?}: worst {worst:.1} dB"); |
| 666 | } |
| 667 | } |
| 668 | |
| 669 | |
| 670 | |
| 671 | |
| 672 | |
| 673 | |
| 674 | |
| 675 | |
| 676 | |
| 677 | #[test] |
| 678 | fn encode_frame_zero_copy_matches_the_cpu_path() { |
| 679 | let Some(display) = display() else { return }; |
| 680 | let (width, height) = (1920u32, 1080u32); |
| 681 | let Some(path) = fixtures(".264") |
| 682 | .into_iter() |
| 683 | .find(|p| p.file_name().and_then(|n| n.to_str()) == Some("h264-1080p-23.976-8bit.264")) |
| 684 | else { |
| 685 | eprintln!("skipped: no h264-1080p fixture — run scripts/gen-bitstream-fixtures.sh"); |
| 686 | return; |
| 687 | }; |
| 688 | let data = std::fs::read(&path).expect("fixture is readable"); |
| 689 | let frames = 10usize; |
| 690 | |
| 691 | for (target, dec_codec) in [(EncCodec::H264, Codec::H264), (EncCodec::H265, Codec::H265)] { |
| 692 | let mut cfg = EncoderConfig::new(target, width, height); |
| 693 | cfg.gop_size = 30; |
| 694 | cfg.rate_control = RateControlMode::ConstantQp { qp: 22 }; |
| 695 | let mut zero_copy = Encoder::new(&display, cfg).expect("zero-copy encoder opens"); |
| 696 | let mut cpu_path = Encoder::new(&display, cfg).expect("cpu-path encoder opens"); |
| 697 | let mut zc_stream = Vec::new(); |
| 698 | let mut cpu_stream = Vec::new(); |
| 699 | let mut count = 0i64; |
| 700 | |
| 701 | let mut decoder = Decoder::new(&display, Codec::H264).expect("decoder opens"); |
| 702 | decode_stream(&mut decoder, Codec::H264, &data, frames, |frame| { |
| 703 | let meta = FrameMetadata { |
| 704 | timestamp: count, |
| 705 | force_keyframe: false, |
| 706 | }; |
| 707 | |
| 708 | |
| 709 | let zc = zero_copy |
| 710 | .encode_frame(&frame, meta) |
| 711 | .expect("encode_frame (zero copy)"); |
| 712 | zc_stream.extend_from_slice(&zc.data); |
| 713 | let i420 = frame.to_i420().expect("readback for the CPU-path baseline"); |
| 714 | let cpu = cpu_path.encode(&i420, meta).expect("encode (CPU path)"); |
| 715 | cpu_stream.extend_from_slice(&cpu.data); |
| 716 | count += 1; |
| 717 | }) |
| 718 | .expect("decode"); |
| 719 | assert_eq!( |
| 720 | count as usize, frames, |
| 721 | "{target:?}: decoded {count} of {frames}" |
| 722 | ); |
| 723 | |
| 724 | let ext = match target { |
| 725 | EncCodec::H264 => "264", |
| 726 | EncCodec::H265 => "265", |
| 727 | EncCodec::Av1 => unreachable!("AV1 is not in this test's target list"), |
| 728 | }; |
| 729 | let dir = std::env::temp_dir().join("ec-hw-encode-frame-zero-copy"); |
| 730 | std::fs::create_dir_all(&dir).expect("temp dir"); |
| 731 | for (name, bytes) in [("zc", &zc_stream), ("cpu", &cpu_stream)] { |
| 732 | std::fs::write(dir.join(format!("{name}.{ext}")), bytes).expect("write bitstream"); |
| 733 | } |
| 734 | |
| 735 | let mut zc_decoder = Decoder::new(&display, dec_codec).expect("zc decoder opens"); |
| 736 | let mut cpu_decoder = Decoder::new(&display, dec_codec).expect("cpu decoder opens"); |
| 737 | let mut zc_frames = Vec::new(); |
| 738 | let mut cpu_frames = Vec::new(); |
| 739 | decode_stream(&mut zc_decoder, dec_codec, &zc_stream, frames, |f| { |
| 740 | zc_frames.push(Planes::from_8bit(&f.to_i420().expect("readback"))) |
| 741 | }) |
| 742 | .expect("decode zero-copy stream"); |
| 743 | decode_stream(&mut cpu_decoder, dec_codec, &cpu_stream, frames, |f| { |
| 744 | cpu_frames.push(Planes::from_8bit(&f.to_i420().expect("readback"))) |
| 745 | }) |
| 746 | .expect("decode CPU-path stream"); |
| 747 | assert_eq!( |
| 748 | zc_frames.len(), |
| 749 | frames, |
| 750 | "{target:?}: zero-copy stream frame count" |
| 751 | ); |
| 752 | assert_eq!( |
| 753 | cpu_frames.len(), |
| 754 | frames, |
| 755 | "{target:?}: CPU-path stream frame count" |
| 756 | ); |
| 757 | |
| 758 | let worst = zc_frames |
| 759 | .iter() |
| 760 | .zip(&cpu_frames) |
| 761 | .map(|(a, b)| psnr(a, b)) |
| 762 | .fold(f64::INFINITY, f64::min); |
| 763 | println!("{target:?} encode_frame vs CPU path: worst {worst:.1} dB"); |
| 764 | assert!( |
| 765 | worst >= 35.0, |
| 766 | "{target:?}: worst {worst:.1} dB vs the CPU path" |
| 767 | ); |
| 768 | } |
| 769 | } |
| 770 | |
| 771 | |
| 772 | |
| 773 | |
| 774 | |
| 775 | |
| 776 | #[test] |
| 777 | fn colour_description_reaches_the_vui() { |
| 778 | let Some(display) = display() else { return }; |
| 779 | let (width, height) = (640u32, 480u32); |
| 780 | let dir = std::env::temp_dir().join("ec-hw-colour-vui"); |
| 781 | std::fs::create_dir_all(&dir).expect("temp dir"); |
| 782 | |
| 783 | let encode_one = |colour: Option<(u8, u8, u8, bool)>, name: &str| -> (PathBuf, Vec<u8>) { |
| 784 | let mut cfg = EncoderConfig::new(EncCodec::H265, width, height); |
| 785 | cfg.rate_control = RateControlMode::ConstantQp { qp: 26 }; |
| 786 | if let Some((primaries, transfer, matrix, full_range)) = colour { |
| 787 | cfg = cfg.colour(primaries, transfer, matrix, full_range); |
| 788 | } |
| 789 | let mut enc = Encoder::new(&display, cfg).expect("encoder opens"); |
| 790 | let coded = enc |
| 791 | .encode( |
| 792 | &source_frame(width, height, 0), |
| 793 | FrameMetadata { |
| 794 | timestamp: 0, |
| 795 | force_keyframe: true, |
| 796 | }, |
| 797 | ) |
| 798 | .expect("encode"); |
| 799 | let path = dir.join(name); |
| 800 | std::fs::write(&path, &coded.data).expect("write bitstream"); |
| 801 | (path, coded.data) |
| 802 | }; |
| 803 | let probe = |path: &Path| -> String { |
| 804 | let out = Command::new("ffprobe") |
| 805 | .args([ |
| 806 | "-v", |
| 807 | "error", |
| 808 | "-select_streams", |
| 809 | "v:0", |
| 810 | "-show_entries", |
| 811 | "stream=color_primaries,color_transfer,color_space", |
| 812 | "-of", |
| 813 | "csv=p=0", |
| 814 | ]) |
| 815 | .arg(path) |
| 816 | .output() |
| 817 | .expect("ffprobe runs"); |
| 818 | String::from_utf8_lossy(&out.stdout).trim().to_string() |
| 819 | }; |
| 820 | |
| 821 | |
| 822 | let (default_path, default_bytes) = encode_one(None, "default-a.265"); |
| 823 | let (_, default_bytes2) = encode_one(None, "default-b.265"); |
| 824 | assert_eq!( |
| 825 | default_bytes, default_bytes2, |
| 826 | "no colour set: two encodes of the same picture must be byte-identical" |
| 827 | ); |
| 828 | let default_probe = probe(&default_path); |
| 829 | println!("no colour set: ffprobe sees `{default_probe}`"); |
| 830 | assert!( |
| 831 | !default_probe.contains("bt2020"), |
| 832 | "no colour set should not read back as BT.2020: `{default_probe}`" |
| 833 | ); |
| 834 | |
| 835 | |
| 836 | let (bt2020_path, _) = encode_one(Some((9, 16, 9, false)), "bt2020.265"); |
| 837 | |
| 838 | |
| 839 | let got = probe(&bt2020_path); |
| 840 | assert_eq!( |
| 841 | got, "bt2020nc,smpte2084,bt2020", |
| 842 | "ffprobe on the BT.2020 stream" |
| 843 | ); |
| 844 | } |
| 845 | |
| 846 | |
| 847 | |
| 848 | |
| 849 | |
| 850 | |
| 851 | |
| 852 | |
| 853 | |
| 854 | |
| 855 | |
| 856 | |
| 857 | |
| 858 | |
| 859 | |
| 860 | |
| 861 | |
| 862 | #[test] |
| 863 | fn av1_encode_is_opt_in() { |
| 864 | let Some(display) = display() else { return }; |
| 865 | let refused = Encoder::new(&display, EncoderConfig::new(EncCodec::Av1, 320, 128)); |
| 866 | assert!( |
| 867 | matches!(refused, Err(ec_hw::Error::Unsupported { .. })), |
| 868 | "AV1 encoding must be refused without the explicit opt-in" |
| 869 | ); |
| 870 | |
| 871 | |
| 872 | let mut config = EncoderConfig::new(EncCodec::Av1, 320, 128); |
| 873 | config.allow_av1 = true; |
| 874 | match Encoder::new(&display, config) { |
| 875 | Ok(encoder) => println!( |
| 876 | "AV1 encode: opt-in encoder built at {:?}, submission deliberately not run", |
| 877 | encoder.coded_size() |
| 878 | ), |
| 879 | Err(e) => println!("AV1 encode: refused by the driver, typed error: {e}"), |
| 880 | } |
| 881 | } |
| 882 | |
| 883 | |
| 884 | |
| 885 | |
| 886 | |
| 887 | |
| 888 | |
| 889 | |
| 890 | |
| 891 | |
| 892 | |
| 893 | |
| 894 | #[test] |
| 895 | fn h264_frame_num_gaps_are_synthesised() { |
| 896 | let Some(display) = display() else { return }; |
| 897 | let path = bitstreams().join("h264-1080p-23.976-8bit.264"); |
| 898 | if !path.exists() { |
| 899 | eprintln!("skipped: no H.264 fixture"); |
| 900 | return; |
| 901 | } |
| 902 | let data = std::fs::read(&path).expect("fixture is readable"); |
| 903 | let units = split_access_units(&data, Codec::H264); |
| 904 | assert!( |
| 905 | units.len() > 8, |
| 906 | "fixture is too short to drop a picture from" |
| 907 | ); |
| 908 | |
| 909 | |
| 910 | let mut kept: Vec<&[u8]> = Vec::new(); |
| 911 | for (i, unit) in units.iter().enumerate() { |
| 912 | if (3..=5).contains(&i) { |
| 913 | continue; |
| 914 | } |
| 915 | kept.push(unit); |
| 916 | } |
| 917 | |
| 918 | let mut decoder = Decoder::new(&display, Codec::H264).expect("decoder opens"); |
| 919 | let mut frames = 0usize; |
| 920 | for (i, unit) in kept.iter().enumerate().take(20) { |
| 921 | if let Err(e) = decoder.decode(unit, i as i64) { |
| 922 | panic!( |
| 923 | "unit {i} failed after {} gap frames: {e}", |
| 924 | decoder.gap_frames_synthesized() |
| 925 | ); |
| 926 | } |
| 927 | while let Some(frame) = decoder.next_frame() { |
| 928 | |
| 929 | let planes = frame.to_i420().expect("readback"); |
| 930 | assert_eq!(planes.y.len(), 1920 * 1080); |
| 931 | frames += 1; |
| 932 | } |
| 933 | } |
| 934 | decoder.flush().expect("flush"); |
| 935 | while decoder.next_frame().is_some() { |
| 936 | frames += 1; |
| 937 | } |
| 938 | let synthesised = decoder.gap_frames_synthesized(); |
| 939 | println!("frame_num gap: {frames} frames decoded, {synthesised} pictures inferred"); |
| 940 | assert!(synthesised > 0, "the gap was not detected"); |
| 941 | assert!(frames >= 10, "only {frames} frames survived the gap"); |
| 942 | } |
| 943 | |
| 944 | |
| 945 | fn rss_kb() -> u64 { |
| 946 | let status = std::fs::read_to_string("/proc/self/status").unwrap_or_default(); |
| 947 | status |
| 948 | .lines() |
| 949 | .find_map(|line| line.strip_prefix("VmRSS:")) |
| 950 | .and_then(|v| v.split_whitespace().next().map(|n| n.to_string())) |
| 951 | .and_then(|n| n.parse().ok()) |
| 952 | .unwrap_or(0) |
| 953 | } |
| 954 | |
| 955 | |
| 956 | |
| 957 | |
| 958 | |
| 959 | |
| 960 | #[test] |
| 961 | fn long_decode_does_not_grow_the_resident_set() { |
| 962 | |
| 963 | |
| 964 | |
| 965 | |
| 966 | if std::env::var_os("EC_HW_RSS_CHILD").is_none() { |
| 967 | let status = Command::new(std::env::current_exe().expect("test binary path")) |
| 968 | .args(["--exact", "long_decode_does_not_grow_the_resident_set"]) |
| 969 | .env("EC_HW_RSS_CHILD", "1") |
| 970 | .status() |
| 971 | .expect("re-run this test in its own process"); |
| 972 | assert!(status.success(), "isolated RSS run failed"); |
| 973 | return; |
| 974 | } |
| 975 | let Some(display) = display() else { return }; |
| 976 | let path = bitstreams().join("h264-1080p-23.976-8bit.264"); |
| 977 | if !path.exists() { |
| 978 | eprintln!("skipped: no H.264 fixture"); |
| 979 | return; |
| 980 | } |
| 981 | let data = std::fs::read(&path).expect("fixture is readable"); |
| 982 | let units = split_access_units(&data, Codec::H264); |
| 983 | let mut decoder = Decoder::new(&display, Codec::H264).expect("decoder opens"); |
| 984 | |
| 985 | |
| 986 | |
| 987 | let mut decoded = 0usize; |
| 988 | let mut baseline = 0u64; |
| 989 | let mut readback_ms = 0f64; |
| 990 | let mut pending: Vec<Frame> = Vec::new(); |
| 991 | let target = 719usize; |
| 992 | 'outer: for pass in 0..16 { |
| 993 | if pass > 0 { |
| 994 | decoder.reset(); |
| 995 | } |
| 996 | for (i, unit) in units.iter().enumerate() { |
| 997 | decoder.decode(unit, i as i64).expect("decode"); |
| 998 | while let Some(frame) = decoder.next_frame() { |
| 999 | |
| 1000 | |
| 1001 | |
| 1002 | pending.push(frame); |
| 1003 | if pending.len() < 4 { |
| 1004 | continue; |
| 1005 | } |
| 1006 | let start = std::time::Instant::now(); |
| 1007 | for frame in pending.drain(..) { |
| 1008 | let planes = frame.to_i420().expect("readback"); |
| 1009 | std::hint::black_box(&planes); |
| 1010 | decoded += 1; |
| 1011 | } |
| 1012 | readback_ms += start.elapsed().as_secs_f64() * 1000.0; |
| 1013 | if decoded == 60 { |
| 1014 | baseline = rss_kb(); |
| 1015 | } |
| 1016 | if decoded >= target { |
| 1017 | break 'outer; |
| 1018 | } |
| 1019 | } |
| 1020 | } |
| 1021 | } |
| 1022 | decoder.flush().expect("flush"); |
| 1023 | let end = rss_kb(); |
| 1024 | let delta_mb = (end.saturating_sub(baseline)) as f64 / 1024.0; |
| 1025 | println!( |
| 1026 | "{decoded} frames decoded and read back: RSS {baseline} -> {end} kB (delta {delta_mb:.1} MB), \ |
| 1027 | decode and read back {:.2} ms/frame at 1920x1080", |
| 1028 | readback_ms / decoded as f64 |
| 1029 | ); |
| 1030 | assert!(decoded >= target, "only {decoded} frames decoded"); |
| 1031 | assert!( |
| 1032 | delta_mb < 50.0, |
| 1033 | "resident set grew {delta_mb:.1} MB over {decoded} frames" |
| 1034 | ); |
| 1035 | } |
| 1036 | |
| 1037 | |
| 1038 | |
| 1039 | |
| 1040 | |
| 1041 | #[test] |
| 1042 | fn frames_export_as_dma_buf() { |
| 1043 | let Some(display) = display() else { return }; |
| 1044 | let path = bitstreams().join("h264-1080p-23.976-8bit.264"); |
| 1045 | if !path.exists() { |
| 1046 | eprintln!("skipped: no H.264 fixture"); |
| 1047 | return; |
| 1048 | } |
| 1049 | let data = std::fs::read(&path).expect("fixture is readable"); |
| 1050 | let mut decoder = Decoder::new(&display, Codec::H264).expect("decoder opens"); |
| 1051 | let mut exported = 0usize; |
| 1052 | decode_stream(&mut decoder, Codec::H264, &data, 2, |frame| { |
| 1053 | let prime = frame.export_prime().expect("export"); |
| 1054 | assert_eq!(prime.fourcc, ec_va::sys::VA_FOURCC_NV12); |
| 1055 | assert_eq!((prime.width, prime.height), frame.coded_size); |
| 1056 | assert!(!prime.objects.is_empty(), "no DRM objects exported"); |
| 1057 | assert!(!prime.layers.is_empty(), "no layers exported"); |
| 1058 | let planes: usize = prime.layers.iter().map(|l| l.planes.len()).sum(); |
| 1059 | assert!( |
| 1060 | planes >= 2, |
| 1061 | "NV12 needs a luma and a chroma plane, got {planes}" |
| 1062 | ); |
| 1063 | exported += 1; |
| 1064 | }) |
| 1065 | .expect("decode"); |
| 1066 | assert!(exported >= 1, "nothing was exported"); |
| 1067 | println!("DRM PRIME export: {exported} frames"); |
| 1068 | } |
| 1069 | |
| 1070 | |
| 1071 | |
| 1072 | |
| 1073 | |
| 1074 | |
| 1075 | |
| 1076 | |
| 1077 | |
| 1078 | fn elementary(path: &Path, codec: Codec, frames: usize) -> Option<Vec<u8>> { |
| 1079 | let args: &[&str] = match codec { |
| 1080 | Codec::H264 => &["-bsf:v", "h264_mp4toannexb", "-f", "h264"], |
| 1081 | Codec::H265 => &["-bsf:v", "hevc_mp4toannexb", "-f", "hevc"], |
| 1082 | Codec::Vp9 | Codec::Av1 => &["-f", "ivf"], |
| 1083 | }; |
| 1084 | let out = Command::new("ffmpeg") |
| 1085 | .args(["-nostdin", "-v", "error", "-i"]) |
| 1086 | .arg(path) |
| 1087 | .args(["-map", "0:v:0", "-c:v", "copy"]) |
| 1088 | |
| 1089 | |
| 1090 | .args(["-frames:v", &(frames + 16).to_string()]) |
| 1091 | .args(args) |
| 1092 | .arg("-") |
| 1093 | .stderr(Stdio::null()) |
| 1094 | .output() |
| 1095 | .ok()?; |
| 1096 | (!out.stdout.is_empty()).then_some(out.stdout) |
| 1097 | } |
| 1098 | |
| 1099 | |
| 1100 | |
| 1101 | |
| 1102 | |
| 1103 | |
| 1104 | |
| 1105 | #[test] |
| 1106 | fn real_library_spot_check() { |
| 1107 | let Some(display) = display() else { return }; |
| 1108 | let manifest = |
| 1109 | Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/real-library-manifest.tsv"); |
| 1110 | let Ok(text) = std::fs::read_to_string(&manifest) else { |
| 1111 | eprintln!( |
| 1112 | "skipped: no fixtures/real-library-manifest.tsv — run scripts/scan-real-library.sh" |
| 1113 | ); |
| 1114 | return; |
| 1115 | }; |
| 1116 | |
| 1117 | |
| 1118 | let mut wanted: Vec<(String, Codec, bool)> = Vec::new(); |
| 1119 | let mut seen: Vec<(String, u8)> = Vec::new(); |
| 1120 | for line in text.lines().skip(1) { |
| 1121 | let f: Vec<&str> = line.split('\t').collect(); |
| 1122 | if f.len() < 7 { |
| 1123 | continue; |
| 1124 | } |
| 1125 | let (path, vcodec, depth) = (f[0].to_string(), f[2], f[6].parse::<u8>().unwrap_or(8)); |
| 1126 | let codec = match vcodec { |
| 1127 | "h264" => Codec::H264, |
| 1128 | "hevc" => Codec::H265, |
| 1129 | "vp9" => Codec::Vp9, |
| 1130 | "av1" => Codec::Av1, |
| 1131 | _ => continue, |
| 1132 | }; |
| 1133 | let key = (vcodec.to_string(), depth); |
| 1134 | if seen.iter().filter(|k| **k == key).count() >= 2 || wanted.len() >= 5 { |
| 1135 | continue; |
| 1136 | } |
| 1137 | if !Path::new(&path).exists() { |
| 1138 | continue; |
| 1139 | } |
| 1140 | seen.push(key); |
| 1141 | wanted.push((path, codec, depth > 8)); |
| 1142 | } |
| 1143 | if wanted.is_empty() { |
| 1144 | eprintln!("skipped: no files from the manifest are present"); |
| 1145 | return; |
| 1146 | } |
| 1147 | |
| 1148 | |
| 1149 | let limit: usize = std::env::var("EC_HW_SWEEP_FRAMES") |
| 1150 | .ok() |
| 1151 | .and_then(|v| v.parse().ok()) |
| 1152 | .unwrap_or(500); |
| 1153 | let mut table = Vec::new(); |
| 1154 | for (path, codec, ten_bit) in &wanted { |
| 1155 | let path = Path::new(path); |
| 1156 | let Some(data) = elementary(path, *codec, limit) else { |
| 1157 | table.push(format!("{:<52} SKIP (no elementary stream)", short(path))); |
| 1158 | continue; |
| 1159 | }; |
| 1160 | let mut decoder = Decoder::new(&display, *codec).expect("decoder opens"); |
| 1161 | let mut reference: Option<Reference> = None; |
| 1162 | let mut worst = f64::INFINITY; |
| 1163 | let mut compared = 0usize; |
| 1164 | let mut failed: Option<String> = None; |
| 1165 | let result = decode_stream(&mut decoder, *codec, &data, limit, |frame| { |
| 1166 | let (w, h) = frame.display_size; |
| 1167 | let reference = reference |
| 1168 | .get_or_insert_with(|| Reference::open(path, w, h, *ten_bit).expect("ffmpeg runs")); |
| 1169 | let Some(want) = reference.next(w, h) else { |
| 1170 | return; |
| 1171 | }; |
| 1172 | let got = if *ten_bit { |
| 1173 | Planes::from_16bit(&frame.to_i420_16().expect("readback")) |
| 1174 | } else { |
| 1175 | Planes::from_8bit(&frame.to_i420().expect("readback")) |
| 1176 | }; |
| 1177 | if got.y.len() != want.y.len() { |
| 1178 | failed = Some("frame size disagrees with ffmpeg".to_string()); |
| 1179 | return; |
| 1180 | } |
| 1181 | let db = psnr(&got, &want); |
| 1182 | if std::env::var_os("EC_HW_DEBUG").is_some() { |
| 1183 | eprintln!(" {} frame {compared}: {db:.1} dB", short(path)); |
| 1184 | } |
| 1185 | worst = worst.min(db); |
| 1186 | compared += 1; |
| 1187 | }); |
| 1188 | match result { |
| 1189 | Ok(decoded) => table.push(format!( |
| 1190 | "{:<52} {decoded:>4} frames, {compared} compared, worst {}", |
| 1191 | short(path), |
| 1192 | if worst.is_infinite() { |
| 1193 | "exact".to_string() |
| 1194 | } else { |
| 1195 | format!("{worst:.1} dB") |
| 1196 | } |
| 1197 | )), |
| 1198 | Err(e) => failed = Some(e.to_string()), |
| 1199 | } |
| 1200 | if let Some(reason) = failed { |
| 1201 | table.push(format!("{:<52} FAIL {reason}", short(path))); |
| 1202 | } |
| 1203 | assert!(compared > 0, "{}: nothing decoded", short(path)); |
| 1204 | assert!( |
| 1205 | worst >= 40.0, |
| 1206 | "{}: worst frame {worst:.1} dB against ffmpeg", |
| 1207 | short(path) |
| 1208 | ); |
| 1209 | } |
| 1210 | for row in table { |
| 1211 | println!("{row}"); |
| 1212 | } |
| 1213 | } |
| 1214 | |
| 1215 | |
| 1216 | fn short(path: &Path) -> String { |
| 1217 | path.file_name() |
| 1218 | .map(|n| n.to_string_lossy().to_string()) |
| 1219 | .unwrap_or_default() |
| 1220 | } |
| 1221 | |
| 1222 | |
| 1223 | fn plane_psnr(a: &[u16], b: &[u16], peak: f64) -> f64 { |
| 1224 | let n = a.len().min(b.len()); |
| 1225 | let mse: f64 = a[..n] |
| 1226 | .iter() |
| 1227 | .zip(&b[..n]) |
| 1228 | .map(|(&p, &q)| { |
| 1229 | let d = f64::from(p) - f64::from(q); |
| 1230 | d * d |
| 1231 | }) |
| 1232 | .sum::<f64>() |
| 1233 | / n as f64; |
| 1234 | if mse == 0.0 { |
| 1235 | f64::INFINITY |
| 1236 | } else { |
| 1237 | 10.0 * (peak * peak / mse).log10() |
| 1238 | } |
| 1239 | } |
| 1240 | |
| 1241 | |
| 1242 | |
| 1243 | |
| 1244 | |
| 1245 | |
| 1246 | |
| 1247 | |
| 1248 | |
| 1249 | |
| 1250 | #[test] |
| 1251 | fn ten_bit_4k_chroma_is_not_grey() { |
| 1252 | let Some(display) = display() else { return }; |
| 1253 | let path = Path::new( |
| 1254 | "/home/user/Downloads/reeld\ |
| 1255 | /reeld.mkv", |
| 1256 | ); |
| 1257 | if !path.exists() { |
| 1258 | eprintln!("skipped: film not present"); |
| 1259 | return; |
| 1260 | } |
| 1261 | let frames = 3usize; |
| 1262 | let Some(data) = elementary(path, Codec::H265, frames) else { |
| 1263 | eprintln!("skipped: no elementary stream"); |
| 1264 | return; |
| 1265 | }; |
| 1266 | let mut decoder = Decoder::new(&display, Codec::H265).expect("decoder opens"); |
| 1267 | let mut ref10: Option<Reference> = None; |
| 1268 | let mut ref8: Option<Reference> = None; |
| 1269 | let mut compared = 0usize; |
| 1270 | decode_stream(&mut decoder, Codec::H265, &data, frames, |frame| { |
| 1271 | let (w, h) = frame.display_size; |
| 1272 | let ref10 = |
| 1273 | ref10.get_or_insert_with(|| Reference::open(path, w, h, true).expect("ffmpeg runs")); |
| 1274 | let want10 = ref10.next(w, h).expect("ffmpeg has a frame"); |
| 1275 | let got16 = Planes::from_16bit(&frame.to_i420_16().expect("readback")); |
| 1276 | let y_db = plane_psnr(&got16.y, &want10.y, 1023.0); |
| 1277 | let uv_db = plane_psnr( |
| 1278 | &[got16.u.as_slice(), got16.v.as_slice()].concat(), |
| 1279 | &[want10.u.as_slice(), want10.v.as_slice()].concat(), |
| 1280 | 1023.0, |
| 1281 | ); |
| 1282 | println!("frame {compared} to_i420_16 vs yuv420p10le: Y {y_db:.1} dB, UV {uv_db:.1} dB"); |
| 1283 | assert!( |
| 1284 | y_db >= 50.0, |
| 1285 | "frame {compared}: Y PSNR collapsed to {y_db:.1} dB" |
| 1286 | ); |
| 1287 | assert!( |
| 1288 | uv_db >= 50.0, |
| 1289 | "frame {compared}: chroma PSNR collapsed to {uv_db:.1} dB (grey frame)" |
| 1290 | ); |
| 1291 | |
| 1292 | let ref8 = |
| 1293 | ref8.get_or_insert_with(|| Reference::open(path, w, h, false).expect("ffmpeg runs")); |
| 1294 | let want8 = ref8.next(w, h).expect("ffmpeg has a frame"); |
| 1295 | let got8 = Planes::from_8bit(&frame.to_i420().expect("readback")); |
| 1296 | let y_db8 = plane_psnr(&got8.y, &want8.y, 255.0); |
| 1297 | let uv_db8 = plane_psnr( |
| 1298 | &[got8.u.as_slice(), got8.v.as_slice()].concat(), |
| 1299 | &[want8.u.as_slice(), want8.v.as_slice()].concat(), |
| 1300 | 255.0, |
| 1301 | ); |
| 1302 | println!("frame {compared} to_i420 vs yuv420p: Y {y_db8:.1} dB, UV {uv_db8:.1} dB"); |
| 1303 | |
| 1304 | |
| 1305 | |
| 1306 | assert!( |
| 1307 | y_db8 >= 30.0, |
| 1308 | "frame {compared}: 8-bit Y PSNR {y_db8:.1} dB" |
| 1309 | ); |
| 1310 | assert!( |
| 1311 | uv_db8 >= 30.0, |
| 1312 | "frame {compared}: 8-bit chroma PSNR collapsed to {uv_db8:.1} dB (grey frame)" |
| 1313 | ); |
| 1314 | compared += 1; |
| 1315 | }) |
| 1316 | .expect("decode"); |
| 1317 | assert_eq!(compared, frames, "not all frames were compared"); |
| 1318 | } |
| 1319 | |
| 1320 | |
| 1321 | |
| 1322 | |
| 1323 | |
| 1324 | |
| 1325 | |
| 1326 | |
| 1327 | #[test] |
| 1328 | fn hdr_film_light_level_sei_is_exposed() { |
| 1329 | let Some(display) = display() else { return }; |
| 1330 | let path = Path::new( |
| 1331 | "/home/user/Downloads/reeld\ |
| 1332 | /reeld.mkv", |
| 1333 | ); |
| 1334 | if !path.exists() { |
| 1335 | eprintln!("skipped: film not present"); |
| 1336 | return; |
| 1337 | } |
| 1338 | let frames = 2usize; |
| 1339 | let Some(data) = elementary(path, Codec::H265, frames) else { |
| 1340 | eprintln!("skipped: no elementary stream"); |
| 1341 | return; |
| 1342 | }; |
| 1343 | let mut decoder = Decoder::new(&display, Codec::H265).expect("decoder opens"); |
| 1344 | let mut seen = 0usize; |
| 1345 | decode_stream(&mut decoder, Codec::H265, &data, frames, |frame| { |
| 1346 | seen += 1; |
| 1347 | let colour = frame |
| 1348 | .colour() |
| 1349 | .expect("HEVC decoder resolves colour metadata"); |
| 1350 | assert_eq!( |
| 1351 | colour.description.codes(), |
| 1352 | (9, 16, 9), |
| 1353 | "primaries/transfer/matrix (BT.2020 / PQ / BT.2020 NCL)" |
| 1354 | ); |
| 1355 | assert_eq!(colour.light.max_cll, Some(1230.0), "MaxCLL"); |
| 1356 | assert_eq!(colour.light.max_fall, Some(419.0), "MaxFALL"); |
| 1357 | assert!( |
| 1358 | colour.light.mastering_max.is_some(), |
| 1359 | "mastering display peak missing" |
| 1360 | ); |
| 1361 | }) |
| 1362 | .expect("decode"); |
| 1363 | assert_eq!(seen, frames, "not all frames were compared"); |
| 1364 | } |
| 1365 | |
| 1366 | |
| 1367 | |
| 1368 | #[test] |
| 1369 | fn sdr_h264_colour_never_panics() { |
| 1370 | let Some(display) = display() else { return }; |
| 1371 | let paths = fixtures(".264"); |
| 1372 | if paths.is_empty() { |
| 1373 | eprintln!("skipped: no H.264 fixtures generated"); |
| 1374 | return; |
| 1375 | } |
| 1376 | let path = &paths[0]; |
| 1377 | let Some(data) = std::fs::read(path).ok() else { |
| 1378 | eprintln!("skipped: fixture unreadable"); |
| 1379 | return; |
| 1380 | }; |
| 1381 | let mut decoder = Decoder::new(&display, Codec::H264).expect("decoder opens"); |
| 1382 | let mut seen = 0usize; |
| 1383 | decode_stream(&mut decoder, Codec::H264, &data, 2, |frame| { |
| 1384 | seen += 1; |
| 1385 | |
| 1386 | if let Some(colour) = frame.colour() { |
| 1387 | assert_eq!(colour.light.max_cll, None); |
| 1388 | } |
| 1389 | }) |
| 1390 | .expect("decode"); |
| 1391 | assert!(seen > 0, "{}: nothing decoded", short(path)); |
| 1392 | } |
| 1393 | |
| 1394 | |
| 1395 | |
| 1396 | |
| 1397 | |
| 1398 | |
| 1399 | |
| 1400 | |
| 1401 | |
| 1402 | #[test] |
| 1403 | fn ten_bit_4k_frame_path_is_realtime() { |
| 1404 | let Some(display) = display() else { return }; |
| 1405 | let path = Path::new( |
| 1406 | "/home/user/Downloads/reeld\ |
| 1407 | /reeld.mkv", |
| 1408 | ); |
| 1409 | if !path.exists() { |
| 1410 | eprintln!("skipped: film not present"); |
| 1411 | return; |
| 1412 | } |
| 1413 | let limit = 120usize; |
| 1414 | let Some(data) = elementary(path, Codec::H265, limit) else { |
| 1415 | eprintln!("skipped: no elementary stream"); |
| 1416 | return; |
| 1417 | }; |
| 1418 | let units = split_access_units(&data, Codec::H265); |
| 1419 | assert!( |
| 1420 | units.len() > limit, |
| 1421 | "film clip too short for {limit} frames" |
| 1422 | ); |
| 1423 | |
| 1424 | #[derive(Clone, Copy)] |
| 1425 | enum Op { |
| 1426 | DecodeOnly, |
| 1427 | ToI420, |
| 1428 | ToI420_16, |
| 1429 | ExportPrime, |
| 1430 | } |
| 1431 | fn apply(op: Op, frame: Frame) { |
| 1432 | match op { |
| 1433 | Op::DecodeOnly => drop(frame), |
| 1434 | Op::ToI420 => { |
| 1435 | frame.to_i420().expect("readback"); |
| 1436 | } |
| 1437 | Op::ToI420_16 => { |
| 1438 | frame.to_i420_16().expect("readback"); |
| 1439 | } |
| 1440 | Op::ExportPrime => { |
| 1441 | frame.export_prime().expect("export"); |
| 1442 | } |
| 1443 | } |
| 1444 | } |
| 1445 | |
| 1446 | println!( |
| 1447 | "{:<22} {:>10} {:>10} {:>10}", |
| 1448 | "stage", "median ms", "min ms", "max ms" |
| 1449 | ); |
| 1450 | let mut got_to_i420_16 = None; |
| 1451 | for (name, op) in [ |
| 1452 | ("decode-only", Op::DecodeOnly), |
| 1453 | ("decode+to_i420", Op::ToI420), |
| 1454 | ("decode+to_i420_16", Op::ToI420_16), |
| 1455 | ("decode+export_prime", Op::ExportPrime), |
| 1456 | ] { |
| 1457 | let mut decoder = Decoder::new(&display, Codec::H265).expect("decoder opens"); |
| 1458 | let mut durations: Vec<Duration> = Vec::new(); |
| 1459 | |
| 1460 | |
| 1461 | |
| 1462 | let mut pending: Vec<Frame> = Vec::new(); |
| 1463 | let mut t_prev = Instant::now(); |
| 1464 | 'outer: for (i, unit) in units.iter().enumerate() { |
| 1465 | decoder.decode(unit, i as i64).expect("decode"); |
| 1466 | while let Some(frame) = decoder.next_frame() { |
| 1467 | pending.push(frame); |
| 1468 | if pending.len() < 4 { |
| 1469 | continue; |
| 1470 | } |
| 1471 | for frame in pending.drain(..) { |
| 1472 | apply(op, frame); |
| 1473 | let now = Instant::now(); |
| 1474 | durations.push(now.duration_since(t_prev)); |
| 1475 | t_prev = now; |
| 1476 | } |
| 1477 | if durations.len() >= limit { |
| 1478 | break 'outer; |
| 1479 | } |
| 1480 | } |
| 1481 | } |
| 1482 | decoder.flush().expect("flush"); |
| 1483 | while durations.len() < limit { |
| 1484 | let Some(frame) = decoder.next_frame() else { |
| 1485 | break; |
| 1486 | }; |
| 1487 | apply(op, frame); |
| 1488 | let now = Instant::now(); |
| 1489 | durations.push(now.duration_since(t_prev)); |
| 1490 | t_prev = now; |
| 1491 | } |
| 1492 | assert!( |
| 1493 | durations.len() >= 24, |
| 1494 | "{name}: only {} frames decoded", |
| 1495 | durations.len() |
| 1496 | ); |
| 1497 | durations.sort(); |
| 1498 | let ms = |d: Duration| d.as_secs_f64() * 1000.0; |
| 1499 | let median = ms(durations[durations.len() / 2]); |
| 1500 | let min = ms(durations[0]); |
| 1501 | let max = ms(durations[durations.len() - 1]); |
| 1502 | println!("{name:<22} {median:>10.2} {min:>10.2} {max:>10.2}"); |
| 1503 | if name == "decode+to_i420_16" { |
| 1504 | got_to_i420_16 = Some(median); |
| 1505 | } |
| 1506 | } |
| 1507 | let got = got_to_i420_16.expect("to_i420_16 phase ran"); |
| 1508 | println!("target: decode+to_i420_16 <= 39.00 ms/frame median (24 fps budget); got {got:.2}"); |
| 1509 | } |
| 1510 | |
| 1511 | const REELD: &str = "/home/user/Downloads/reeld\ |
| 1512 | /reeld.mkv"; |
| 1513 | |
| 1514 | |
| 1515 | |
| 1516 | |
| 1517 | |
| 1518 | |
| 1519 | #[test] |
| 1520 | fn encode_frame_accepts_p010_via_vpp() { |
| 1521 | let Some(display) = display() else { return }; |
| 1522 | let path = Path::new(REELD); |
| 1523 | if !path.exists() { |
| 1524 | eprintln!("skipped: film not present"); |
| 1525 | return; |
| 1526 | } |
| 1527 | let frames = 10usize; |
| 1528 | let Some(data) = elementary(path, Codec::H265, frames) else { |
| 1529 | eprintln!("skipped: no elementary stream"); |
| 1530 | return; |
| 1531 | }; |
| 1532 | |
| 1533 | |
| 1534 | |
| 1535 | |
| 1536 | |
| 1537 | |
| 1538 | |
| 1539 | |
| 1540 | |
| 1541 | let (mut w, mut h) = (0u32, 0u32); |
| 1542 | for (target, dec_codec) in [(EncCodec::H264, Codec::H264), (EncCodec::H265, Codec::H265)] { |
| 1543 | let mut decoder = Decoder::new(&display, Codec::H265).expect("decoder opens"); |
| 1544 | let mut zc_stream = Vec::new(); |
| 1545 | let mut cpu_stream = Vec::new(); |
| 1546 | let mut count = 0i64; |
| 1547 | let mut zero_copy: Option<Encoder> = None; |
| 1548 | let mut cpu_path: Option<Encoder> = None; |
| 1549 | let refused = false; |
| 1550 | |
| 1551 | decode_stream(&mut decoder, Codec::H265, &data, frames, |frame| { |
| 1552 | if refused { |
| 1553 | return; |
| 1554 | } |
| 1555 | (w, h) = frame.display_size; |
| 1556 | let zero_copy = zero_copy.get_or_insert_with(|| { |
| 1557 | let mut cfg = EncoderConfig::new(target, w, h); |
| 1558 | cfg.gop_size = 30; |
| 1559 | cfg.rate_control = RateControlMode::ConstantQp { qp: 22 }; |
| 1560 | Encoder::new(&display, cfg).expect("zero-copy encoder opens") |
| 1561 | }); |
| 1562 | let cpu_path = cpu_path.get_or_insert_with(|| { |
| 1563 | let mut cfg = EncoderConfig::new(target, w, h); |
| 1564 | cfg.gop_size = 30; |
| 1565 | cfg.rate_control = RateControlMode::ConstantQp { qp: 22 }; |
| 1566 | Encoder::new(&display, cfg).expect("cpu-path encoder opens") |
| 1567 | }); |
| 1568 | let meta = FrameMetadata { |
| 1569 | timestamp: count, |
| 1570 | force_keyframe: false, |
| 1571 | }; |
| 1572 | let zc = zero_copy |
| 1573 | .encode_frame(&frame, meta) |
| 1574 | .expect("encode_frame (zero copy, P010 via VPP, size mismatch routed through VPP)"); |
| 1575 | zc_stream.extend_from_slice(&zc.data); |
| 1576 | let i420 = frame.to_i420().expect("readback for the CPU-path baseline"); |
| 1577 | let cpu = cpu_path.encode(&i420, meta).expect("encode (CPU path)"); |
| 1578 | cpu_stream.extend_from_slice(&cpu.data); |
| 1579 | count += 1; |
| 1580 | }) |
| 1581 | .expect("decode"); |
| 1582 | if refused { |
| 1583 | continue; |
| 1584 | } |
| 1585 | assert_eq!( |
| 1586 | count as usize, frames, |
| 1587 | "{target:?}: decoded {count} of {frames}" |
| 1588 | ); |
| 1589 | |
| 1590 | let mut zc_decoder = Decoder::new(&display, dec_codec).expect("zc decoder opens"); |
| 1591 | let mut cpu_decoder = Decoder::new(&display, dec_codec).expect("cpu decoder opens"); |
| 1592 | let mut zc_frames = Vec::new(); |
| 1593 | let mut cpu_frames = Vec::new(); |
| 1594 | decode_stream(&mut zc_decoder, dec_codec, &zc_stream, frames, |f| { |
| 1595 | zc_frames.push(f.to_i420().expect("readback")) |
| 1596 | }) |
| 1597 | .expect("decode zero-copy stream"); |
| 1598 | decode_stream(&mut cpu_decoder, dec_codec, &cpu_stream, frames, |f| { |
| 1599 | cpu_frames.push(f.to_i420().expect("readback")) |
| 1600 | }) |
| 1601 | .expect("decode CPU-path stream"); |
| 1602 | assert_eq!(zc_frames.len(), frames, "{target:?}: zero-copy frame count"); |
| 1603 | assert_eq!(cpu_frames.len(), frames, "{target:?}: CPU-path frame count"); |
| 1604 | |
| 1605 | let widen = |v: &[u8]| -> Vec<u16> { v.iter().map(|&s| u16::from(s)).collect() }; |
| 1606 | let mut worst_y = f64::INFINITY; |
| 1607 | let mut worst_uv = f64::INFINITY; |
| 1608 | for (a, b) in zc_frames.iter().zip(&cpu_frames) { |
| 1609 | let y_db = plane_psnr(&widen(&a.y), &widen(&b.y), 255.0); |
| 1610 | let uv_db = plane_psnr( |
| 1611 | &[widen(&a.u), widen(&a.v)].concat(), |
| 1612 | &[widen(&b.u), widen(&b.v)].concat(), |
| 1613 | 255.0, |
| 1614 | ); |
| 1615 | worst_y = worst_y.min(y_db); |
| 1616 | worst_uv = worst_uv.min(uv_db); |
| 1617 | } |
| 1618 | println!("{target:?} encode_frame (P010 via VPP) vs CPU path: worst Y {worst_y:.1} dB, worst UV {worst_uv:.1} dB"); |
| 1619 | assert!(worst_y >= 40.0, "{target:?}: worst Y {worst_y:.1} dB vs the CPU path"); |
| 1620 | assert!(worst_uv >= 40.0, "{target:?}: worst UV {worst_uv:.1} dB vs the CPU path"); |
| 1621 | |
| 1622 | |
| 1623 | |
| 1624 | |
| 1625 | |
| 1626 | let dir = std::env::temp_dir().join(format!("ec-hw-vpp-region-{target:?}")); |
| 1627 | std::fs::create_dir_all(&dir).expect("temp dir"); |
| 1628 | let path = dir.join(match target { |
| 1629 | EncCodec::H264 => "out.264", |
| 1630 | EncCodec::H265 => "out.265", |
| 1631 | EncCodec::Av1 => "out.obu", |
| 1632 | }); |
| 1633 | std::fs::write(&path, &zc_stream).expect("write bitstream"); |
| 1634 | let probe = Command::new("ffprobe") |
| 1635 | .args([ |
| 1636 | "-v", |
| 1637 | "error", |
| 1638 | "-select_streams", |
| 1639 | "v:0", |
| 1640 | "-show_entries", |
| 1641 | "stream=width,height", |
| 1642 | "-of", |
| 1643 | "csv=p=0", |
| 1644 | ]) |
| 1645 | .arg(&path) |
| 1646 | .output() |
| 1647 | .expect("ffprobe runs"); |
| 1648 | let dims = String::from_utf8_lossy(&probe.stdout).trim().to_string(); |
| 1649 | assert_eq!(dims, format!("{w},{h}"), "{target:?}: ffprobe sees {dims}"); |
| 1650 | } |
| 1651 | } |
| 1652 | |
| 1653 | |
| 1654 | |
| 1655 | |
| 1656 | |
| 1657 | |
| 1658 | |
| 1659 | |
| 1660 | |
| 1661 | |
| 1662 | #[test] |
| 1663 | fn p010_zero_copy_encode_is_realtime() { |
| 1664 | let Some(display) = display() else { return }; |
| 1665 | let path = Path::new(REELD); |
| 1666 | if !path.exists() { |
| 1667 | eprintln!("skipped: film not present"); |
| 1668 | return; |
| 1669 | } |
| 1670 | let limit = 60usize; |
| 1671 | let Some(data) = elementary(path, Codec::H265, limit) else { |
| 1672 | eprintln!("skipped: no elementary stream"); |
| 1673 | return; |
| 1674 | }; |
| 1675 | let units = split_access_units(&data, Codec::H265); |
| 1676 | assert!(units.len() > limit, "film clip too short for {limit} frames"); |
| 1677 | |
| 1678 | println!("{:<28} {:>10} {:>10} {:>10}", "stage", "median ms", "min ms", "max ms"); |
| 1679 | |
| 1680 | let mut rows: Vec<(EncCodec, f64, f64)> = Vec::new(); |
| 1681 | let run_target = |target: EncCodec| -> (f64, f64) { |
| 1682 | let mut zc_median = None; |
| 1683 | let mut cpu_median = None; |
| 1684 | for (label, zero_copy) in [("decode+encode_frame", true), ("decode+to_i420+encode", false)] { |
| 1685 | let name = format!("{target:?} {label}"); |
| 1686 | let mut decoder = Decoder::new(&display, Codec::H265).expect("decoder opens"); |
| 1687 | let mut encoder: Option<Encoder> = None; |
| 1688 | let mut durations: Vec<Duration> = Vec::new(); |
| 1689 | let mut count = 0i64; |
| 1690 | 'outer: for (i, unit) in units.iter().enumerate() { |
| 1691 | decoder.decode(unit, i as i64).expect("decode"); |
| 1692 | while let Some(frame) = decoder.next_frame() { |
| 1693 | let (w, h) = frame.display_size; |
| 1694 | let encoder = encoder.get_or_insert_with(|| { |
| 1695 | let mut cfg = EncoderConfig::new(target, w, h); |
| 1696 | cfg.gop_size = 30; |
| 1697 | cfg.rate_control = RateControlMode::ConstantQp { qp: 22 }; |
| 1698 | Encoder::new(&display, cfg).expect("encoder opens") |
| 1699 | }); |
| 1700 | let meta = FrameMetadata { |
| 1701 | timestamp: count, |
| 1702 | force_keyframe: false, |
| 1703 | }; |
| 1704 | let t0 = Instant::now(); |
| 1705 | if zero_copy { |
| 1706 | encoder.encode_frame(&frame, meta).expect("encode_frame"); |
| 1707 | } else { |
| 1708 | let i420 = frame.to_i420().expect("readback"); |
| 1709 | encoder.encode(&i420, meta).expect("encode"); |
| 1710 | } |
| 1711 | durations.push(t0.elapsed()); |
| 1712 | count += 1; |
| 1713 | if durations.len() >= limit { |
| 1714 | break 'outer; |
| 1715 | } |
| 1716 | } |
| 1717 | } |
| 1718 | assert!( |
| 1719 | durations.len() >= limit, |
| 1720 | "{name}: only {} of {limit} frames encoded", |
| 1721 | durations.len() |
| 1722 | ); |
| 1723 | durations.sort(); |
| 1724 | let ms = |d: Duration| d.as_secs_f64() * 1000.0; |
| 1725 | let median = ms(durations[durations.len() / 2]); |
| 1726 | let min = ms(durations[0]); |
| 1727 | let max = ms(durations[durations.len() - 1]); |
| 1728 | println!("{name:<28} {median:>10.2} {min:>10.2} {max:>10.2}"); |
| 1729 | if zero_copy { |
| 1730 | zc_median = Some(median); |
| 1731 | } else { |
| 1732 | cpu_median = Some(median); |
| 1733 | } |
| 1734 | } |
| 1735 | ( |
| 1736 | zc_median.expect("zero-copy phase ran"), |
| 1737 | cpu_median.expect("CPU-path phase ran"), |
| 1738 | ) |
| 1739 | }; |
| 1740 | for target in [EncCodec::H264, EncCodec::H265] { |
| 1741 | let (mut zc, mut cpu) = run_target(target); |
| 1742 | |
| 1743 | |
| 1744 | |
| 1745 | |
| 1746 | if zc > 20.0 && zc < 30.0 { |
| 1747 | let (zc2, cpu2) = run_target(target); |
| 1748 | if zc2 < zc { |
| 1749 | zc = zc2; |
| 1750 | cpu = cpu2; |
| 1751 | } |
| 1752 | } |
| 1753 | rows.push((target, zc, cpu)); |
| 1754 | } |
| 1755 | for (target, zc, cpu) in rows { |
| 1756 | println!( |
| 1757 | "target: {target:?} decode+encode_frame <= 20.00 ms/frame median; got {zc:.2} (CPU path {cpu:.2})" |
| 1758 | ); |
| 1759 | assert!( |
| 1760 | zc <= 20.0, |
| 1761 | "{target:?}: decode+encode_frame median {zc:.2} ms/frame exceeds the 20 ms budget (CPU path: {cpu:.2} ms)" |
| 1762 | ); |
| 1763 | } |
| 1764 | } |
| 1765 | |
| 1766 | |
| 1767 | |
| 1768 | |
| 1769 | |
| 1770 | |
| 1771 | |
| 1772 | |
| 1773 | #[test] |
| 1774 | fn hevc_seek_matches_linear_mkv() { |
| 1775 | let Some(display) = display() else { return }; |
| 1776 | let path = bitstreams().join("test_hevc.mkv"); |
| 1777 | let Some(data) = elementary(&path, Codec::H265, 45) else { |
| 1778 | eprintln!("skipped: no test_hevc.mkv fixture"); |
| 1779 | return; |
| 1780 | }; |
| 1781 | let units = split_access_units(&data, Codec::H265); |
| 1782 | |
| 1783 | |
| 1784 | |
| 1785 | |
| 1786 | const TARGET: usize = 30; |
| 1787 | let mut decoder = Decoder::new(&display, Codec::H265).expect("decoder opens"); |
| 1788 | let mut linear_frame_30 = None; |
| 1789 | let mut index = 0usize; |
| 1790 | decode_stream(&mut decoder, Codec::H265, &data, 45, |frame| { |
| 1791 | if index == TARGET { |
| 1792 | linear_frame_30 = Some(frame.to_i420().expect("readback")); |
| 1793 | } |
| 1794 | index += 1; |
| 1795 | }) |
| 1796 | .expect("linear decode"); |
| 1797 | let linear_frame_30 = linear_frame_30.expect("linear decode reached frame 30"); |
| 1798 | |
| 1799 | |
| 1800 | |
| 1801 | |
| 1802 | let cra_at = units |
| 1803 | .iter() |
| 1804 | .position(|au| starts_with_cra(au)) |
| 1805 | .expect("a CRA access unit exists"); |
| 1806 | |
| 1807 | |
| 1808 | |
| 1809 | |
| 1810 | |
| 1811 | let mut seek_decoder = Decoder::new(&display, Codec::H265).expect("decoder opens"); |
| 1812 | seek_decoder |
| 1813 | .decode(units[0], 0) |
| 1814 | .expect("prime parameter sets"); |
| 1815 | seek_decoder.reset(); |
| 1816 | let mut seeked_frame = None; |
| 1817 | for (i, unit) in units[cra_at..].iter().enumerate() { |
| 1818 | seek_decoder.decode(unit, i as i64).expect("seek decode"); |
| 1819 | if let Some(frame) = seek_decoder.next_frame() { |
| 1820 | seeked_frame = Some(frame.to_i420().expect("readback")); |
| 1821 | break; |
| 1822 | } |
| 1823 | } |
| 1824 | if seeked_frame.is_none() { |
| 1825 | seek_decoder.flush().expect("flush"); |
| 1826 | seeked_frame = seek_decoder |
| 1827 | .next_frame() |
| 1828 | .map(|f| f.to_i420().expect("readback")); |
| 1829 | } |
| 1830 | let seeked_frame = seeked_frame.expect("a frame came out after the seek"); |
| 1831 | |
| 1832 | assert_eq!( |
| 1833 | seeked_frame, linear_frame_30, |
| 1834 | "seeking to the CRA before frame 30 handed back a different picture \ |
| 1835 | than a linear decode of frame 30 — RASL pictures were not dropped" |
| 1836 | ); |
| 1837 | } |
| 1838 | |
| 1839 | |
| 1840 | |
| 1841 | |
| 1842 | |
| 1843 | |
| 1844 | |
| 1845 | |
| 1846 | #[test] |
| 1847 | fn h264_seek_matches_linear_open_gop() { |
| 1848 | let Some(display) = display() else { return }; |
| 1849 | let path = bitstreams().join("h264-open-gop.mp4"); |
| 1850 | let Some(data) = elementary(&path, Codec::H264, 60) else { |
| 1851 | eprintln!("skipped: no h264-open-gop.mp4 fixture (run scripts/gen-fixtures.sh)"); |
| 1852 | return; |
| 1853 | }; |
| 1854 | let units = split_access_units(&data, Codec::H264); |
| 1855 | |
| 1856 | |
| 1857 | |
| 1858 | const TARGET: usize = 30; |
| 1859 | let mut decoder = Decoder::new(&display, Codec::H264).expect("decoder opens"); |
| 1860 | let mut linear_frame_30 = None; |
| 1861 | let mut index = 0usize; |
| 1862 | decode_stream(&mut decoder, Codec::H264, &data, 60, |frame| { |
| 1863 | if index == TARGET { |
| 1864 | linear_frame_30 = Some(frame.to_i420().expect("readback")); |
| 1865 | } |
| 1866 | index += 1; |
| 1867 | }) |
| 1868 | .expect("linear decode"); |
| 1869 | let linear_frame_30 = linear_frame_30.expect("linear decode reached frame 30"); |
| 1870 | |
| 1871 | |
| 1872 | |
| 1873 | |
| 1874 | let open_gop_at = units |
| 1875 | .iter() |
| 1876 | .position(|au| is_open_gop_i(au)) |
| 1877 | .expect("an open-GOP I access unit exists"); |
| 1878 | |
| 1879 | |
| 1880 | |
| 1881 | |
| 1882 | |
| 1883 | let mut seek_decoder = Decoder::new(&display, Codec::H264).expect("decoder opens"); |
| 1884 | seek_decoder.decode(units[0], 0).expect("prime parameter sets"); |
| 1885 | seek_decoder.reset(); |
| 1886 | let mut seeked_frame = None; |
| 1887 | for (i, unit) in units[open_gop_at..].iter().enumerate() { |
| 1888 | seek_decoder.decode(unit, i as i64).expect("seek decode"); |
| 1889 | if let Some(frame) = seek_decoder.next_frame() { |
| 1890 | seeked_frame = Some(frame.to_i420().expect("readback")); |
| 1891 | break; |
| 1892 | } |
| 1893 | } |
| 1894 | if seeked_frame.is_none() { |
| 1895 | seek_decoder.flush().expect("flush"); |
| 1896 | seeked_frame = seek_decoder |
| 1897 | .next_frame() |
| 1898 | .map(|f| f.to_i420().expect("readback")); |
| 1899 | } |
| 1900 | let seeked_frame = seeked_frame.expect("a frame came out after the seek"); |
| 1901 | |
| 1902 | assert_eq!( |
| 1903 | seeked_frame, linear_frame_30, |
| 1904 | "seeking to the open-GOP I before frame 30 handed back a different \ |
| 1905 | picture than a linear decode of frame 30 — leading pictures with \ |
| 1906 | missing references were not dropped" |
| 1907 | ); |
| 1908 | } |
| 1909 | |
| 1910 | |
| 1911 | |
| 1912 | |
| 1913 | fn is_open_gop_i(au: &[u8]) -> bool { |
| 1914 | let mut i = 0usize; |
| 1915 | while i + 3 < au.len() { |
| 1916 | if au[i] != 0 || au[i + 1] != 0 || au[i + 2] != 1 { |
| 1917 | i += 1; |
| 1918 | continue; |
| 1919 | } |
| 1920 | let header = au[i + 3]; |
| 1921 | if header & 0x1f != 1 { |
| 1922 | return false; |
| 1923 | } |
| 1924 | let mut r = ec_core::BitReader::new(&au[i + 4..]); |
| 1925 | if r.read_ue().is_err() { |
| 1926 | return false; |
| 1927 | } |
| 1928 | return matches!(r.read_ue(), Ok(code) if code % 5 == 2); |
| 1929 | } |
| 1930 | false |
| 1931 | } |
| 1932 | |
| 1933 | |
| 1934 | |
| 1935 | |
| 1936 | fn starts_with_cra(au: &[u8]) -> bool { |
| 1937 | let mut i = 0usize; |
| 1938 | while i + 3 < au.len() { |
| 1939 | if au[i] == 0 && au[i + 1] == 0 && au[i + 2] == 1 { |
| 1940 | let t = (au[i + 3] >> 1) & 0x3f; |
| 1941 | if t <= 31 { |
| 1942 | return t == 21; |
| 1943 | } |
| 1944 | i += 3; |
| 1945 | continue; |
| 1946 | } |
| 1947 | i += 1; |
| 1948 | } |
| 1949 | false |
| 1950 | } |
| 1951 | |
| 1952 | |
| 1953 | |
| 1954 | fn trace_headers(path: &Path, codec: &str) -> Vec<(String, i64)> { |
| 1955 | let out = Command::new("ffmpeg") |
| 1956 | .args(["-v", "trace", "-hide_banner", "-nostats", "-f", codec, "-i"]) |
| 1957 | .arg(path) |
| 1958 | .args(["-c:v", "copy", "-bsf:v", "trace_headers", "-f", "null", "-"]) |
| 1959 | .output() |
| 1960 | .expect("ffmpeg runs"); |
| 1961 | let text = String::from_utf8_lossy(&out.stderr); |
| 1962 | text.lines() |
| 1963 | .filter_map(|line| { |
| 1964 | |
| 1965 | let (lhs, value) = line.rsplit_once(" = ")?; |
| 1966 | let mut words = lhs.split_whitespace().rev(); |
| 1967 | let _bits = words.next()?; |
| 1968 | let name = words.next()?; |
| 1969 | Some((name.to_string(), value.trim().parse().ok()?)) |
| 1970 | }) |
| 1971 | .collect() |
| 1972 | } |
| 1973 | |
| 1974 | |
| 1975 | |
| 1976 | |
| 1977 | |
| 1978 | fn slice_counters(codec: EncCodec, width: u32, height: u32, frames: u32) -> (PathBuf, Vec<(String, i64)>) { |
| 1979 | let Some(display) = display() else { return (PathBuf::new(), Vec::new()) }; |
| 1980 | let mut config = EncoderConfig::new(codec, width, height); |
| 1981 | config.gop_size = frames * 2; |
| 1982 | config.framerate = (30, 1); |
| 1983 | config.rate_control = RateControlMode::ConstantQp { qp: 30 }; |
| 1984 | let mut encoder = Encoder::new(&display, config).expect("encoder"); |
| 1985 | let mut out = Vec::new(); |
| 1986 | for t in 0..frames { |
| 1987 | let coded = encoder |
| 1988 | .encode(&source_frame(width, height, t), FrameMetadata { timestamp: i64::from(t), force_keyframe: false }) |
| 1989 | .expect("encode"); |
| 1990 | assert_eq!(coded.is_keyframe, t == 0, "one IDR then P-frames at {t}"); |
| 1991 | out.extend_from_slice(&coded.data); |
| 1992 | } |
| 1993 | let dir = std::env::temp_dir().join(format!("ec-hw-counters-{codec:?}")); |
| 1994 | std::fs::create_dir_all(&dir).expect("temp dir"); |
| 1995 | let (name, fmt) = match codec { |
| 1996 | EncCodec::H264 => ("out.264", "h264"), |
| 1997 | EncCodec::H265 => ("out.265", "hevc"), |
| 1998 | EncCodec::Av1 => unreachable!(), |
| 1999 | }; |
| 2000 | let path = dir.join(name); |
| 2001 | std::fs::write(&path, &out).expect("write"); |
| 2002 | let fields = trace_headers(&path, fmt); |
| 2003 | (path, fields) |
| 2004 | } |
| 2005 | |
| 2006 | fn values<'a>(fields: &'a [(String, i64)], name: &str) -> Vec<i64> { |
| 2007 | fields.iter().filter(|(n, _)| n == name).map(|(_, v)| *v).collect() |
| 2008 | } |
| 2009 | |
| 2010 | #[test] |
| 2011 | fn h264_slice_headers_count_frames_for_stateful_decoders() { |
| 2012 | let frames = 64u32; |
| 2013 | let (path, fields) = slice_counters(EncCodec::H264, 640, 360, frames); |
| 2014 | if fields.is_empty() { |
| 2015 | return; |
| 2016 | } |
| 2017 | let frame_num = values(&fields, "frame_num"); |
| 2018 | assert_eq!(frame_num.len(), frames as usize, "one slice per picture in {}", path.display()); |
| 2019 | let log2_max = values(&fields, "log2_max_frame_num_minus4")[0] + 4; |
| 2020 | let max_frame_num = 1i64 << log2_max; |
| 2021 | let expected: Vec<i64> = (0..frames as i64).map(|n| n % max_frame_num).collect(); |
| 2022 | assert_eq!(frame_num, expected, "frame_num steps +1 mod {max_frame_num}"); |
| 2023 | |
| 2024 | |
| 2025 | let poc_type = values(&fields, "pic_order_cnt_type"); |
| 2026 | assert!(!poc_type.is_empty() && poc_type.iter().all(|&t| t == 2), "POC type 2 in the SPS: {poc_type:?}"); |
| 2027 | assert!(values(&fields, "pic_order_cnt_lsb").is_empty(), "no POC lsb under type 2"); |
| 2028 | assert!(values(&fields, "level_idc").iter().all(|&l| l == 30), "640x360@30 is level 3.0"); |
| 2029 | } |
| 2030 | |
| 2031 | #[test] |
| 2032 | fn hevc_slice_headers_count_pocs_for_stateful_decoders() { |
| 2033 | let frames = 64u32; |
| 2034 | let (path, fields) = slice_counters(EncCodec::H265, 640, 360, frames); |
| 2035 | if fields.is_empty() { |
| 2036 | return; |
| 2037 | } |
| 2038 | let lsb = values(&fields, "slice_pic_order_cnt_lsb"); |
| 2039 | assert_eq!(lsb.len(), frames as usize - 1, "every non-IDR slice carries a POC lsb in {}", path.display()); |
| 2040 | let log2_max = values(&fields, "log2_max_pic_order_cnt_lsb_minus4")[0] + 4; |
| 2041 | let max_lsb = 1i64 << log2_max; |
| 2042 | let expected: Vec<i64> = (1..frames as i64).map(|n| n % max_lsb).collect(); |
| 2043 | assert_eq!(lsb, expected, "POC lsb steps +1 mod {max_lsb}"); |
| 2044 | } |