| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | |
| 13 | |
| 14 | |
| 15 | use std::alloc::System; |
| 16 | use std::sync::Once; |
| 17 | |
| 18 | use tracking_allocator::{AllocationGroupId, AllocationRegistry, AllocationTracker, Allocator}; |
| 19 | use std::cell::Cell; |
| 20 | use std::path::{Path, PathBuf}; |
| 21 | use std::process::Command; |
| 22 | use std::sync::atomic::{AtomicU64, Ordering}; |
| 23 | |
| 24 | use ec_core::registry::{CodecId, CodecParameters, Decoder as _}; |
| 25 | use ec_core::{Buf, Frame, Packet, TimeBase}; |
| 26 | use ec_h264::{Decoder, Error, H264Decoder, NalOutcome}; |
| 27 | |
| 28 | |
| 29 | |
| 30 | |
| 31 | |
| 32 | |
| 33 | struct CountingAlloc; |
| 34 | |
| 35 | static ALLOCS: AtomicU64 = AtomicU64::new(0); |
| 36 | |
| 37 | std::thread_local! { |
| 38 | |
| 39 | |
| 40 | static COUNTING_HERE: Cell<bool> = const { Cell::new(false) }; |
| 41 | } |
| 42 | |
| 43 | fn counting_here() -> bool { |
| 44 | COUNTING_HERE.try_with(Cell::get).unwrap_or(false) |
| 45 | } |
| 46 | |
| 47 | impl AllocationTracker for CountingAlloc { |
| 48 | fn allocated(&self, _addr: usize, _object_size: usize, _wrapped: usize, _g: AllocationGroupId) { |
| 49 | if counting_here() { |
| 50 | ALLOCS.fetch_add(1, Ordering::Relaxed); |
| 51 | } |
| 52 | } |
| 53 | fn deallocated( |
| 54 | &self, |
| 55 | _addr: usize, |
| 56 | _object_size: usize, |
| 57 | _wrapped: usize, |
| 58 | _source: AllocationGroupId, |
| 59 | _current: AllocationGroupId, |
| 60 | ) { |
| 61 | } |
| 62 | } |
| 63 | |
| 64 | #[global_allocator] |
| 65 | static A: Allocator<System> = Allocator::system(); |
| 66 | |
| 67 | |
| 68 | fn install_counter() { |
| 69 | static ONCE: Once = Once::new(); |
| 70 | ONCE.call_once(|| { |
| 71 | let _ = AllocationRegistry::set_global_tracker(CountingAlloc); |
| 72 | AllocationRegistry::enable_tracking(); |
| 73 | }); |
| 74 | } |
| 75 | |
| 76 | |
| 77 | |
| 78 | fn vectors_dir() -> PathBuf { |
| 79 | Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/vectors/h264-jvt") |
| 80 | } |
| 81 | |
| 82 | |
| 83 | |
| 84 | |
| 85 | |
| 86 | |
| 87 | |
| 88 | |
| 89 | |
| 90 | fn require_fixtures(path: &Path, what: &str, generator: &str) -> bool { |
| 91 | if path.exists() { |
| 92 | return true; |
| 93 | } |
| 94 | assert!( |
| 95 | std::env::var_os("EC_REQUIRE_FIXTURES").is_none(), |
| 96 | "{what} missing at {} — this gate would prove nothing. A worktree has no \ |
| 97 | gitignored root `fixtures/`: run scripts/link-fixtures.sh, or generate \ |
| 98 | them with {generator}.", |
| 99 | path.display() |
| 100 | ); |
| 101 | eprintln!( |
| 102 | "SKIP {what} missing at {} — this gate proved nothing; run \ |
| 103 | scripts/link-fixtures.sh, or generate them with {generator} \ |
| 104 | (or set EC_REQUIRE_FIXTURES=1 to make this a failure).", |
| 105 | path.display() |
| 106 | ); |
| 107 | false |
| 108 | } |
| 109 | |
| 110 | |
| 111 | |
| 112 | |
| 113 | |
| 114 | |
| 115 | |
| 116 | |
| 117 | fn all_vectors(base: &Path) -> Vec<String> { |
| 118 | let mut names: Vec<String> = std::fs::read_dir(base) |
| 119 | .into_iter() |
| 120 | .flatten() |
| 121 | .flatten() |
| 122 | .filter(|e| e.path().is_dir()) |
| 123 | .map(|e| e.file_name().to_string_lossy().into_owned()) |
| 124 | .collect(); |
| 125 | names.sort(); |
| 126 | names |
| 127 | } |
| 128 | |
| 129 | fn find_stream(dir: &Path) -> Option<PathBuf> { |
| 130 | let mut fallback = None; |
| 131 | for entry in std::fs::read_dir(dir).ok()? { |
| 132 | let p = entry.ok()?.path(); |
| 133 | let ext = p.extension()?.to_str()?.to_ascii_lowercase(); |
| 134 | if matches!(ext.as_str(), "jsv" | "264" | "avc" | "26l" | "h264" | "jvt") { |
| 135 | return Some(p); |
| 136 | } |
| 137 | if ext == "bit" { |
| 138 | fallback = Some(p); |
| 139 | } |
| 140 | } |
| 141 | fallback |
| 142 | } |
| 143 | |
| 144 | fn find_ref_yuv(dir: &Path) -> Option<PathBuf> { |
| 145 | for entry in std::fs::read_dir(dir).ok()? { |
| 146 | let p = entry.ok()?.path(); |
| 147 | let ext = p.extension()?.to_str()?.to_ascii_lowercase(); |
| 148 | if ext == "yuv" || ext == "qcif" { |
| 149 | return Some(p); |
| 150 | } |
| 151 | } |
| 152 | None |
| 153 | } |
| 154 | |
| 155 | fn ffmpeg_first_frame(stream: &Path) -> Option<Vec<u8>> { |
| 156 | let out = Command::new("ffmpeg") |
| 157 | .args(["-v", "error", "-i"]) |
| 158 | .arg(stream) |
| 159 | .args([ |
| 160 | "-frames:v", |
| 161 | "1", |
| 162 | "-f", |
| 163 | "rawvideo", |
| 164 | "-pix_fmt", |
| 165 | "yuv420p", |
| 166 | "-", |
| 167 | ]) |
| 168 | .output() |
| 169 | .ok()?; |
| 170 | if !out.status.success() || out.stdout.is_empty() { |
| 171 | return None; |
| 172 | } |
| 173 | Some(out.stdout) |
| 174 | } |
| 175 | |
| 176 | |
| 177 | fn decode_first(stream_bytes: &[u8]) -> Result<(Vec<u8>, usize, usize), Error> { |
| 178 | let mut dec = Decoder::new(); |
| 179 | let frame = dec.decode_first_idr(stream_bytes)?; |
| 180 | let (w, h) = (frame.width as usize, frame.height as usize); |
| 181 | let mut out = Vec::with_capacity(w * h * 3 / 2); |
| 182 | let dims = [ |
| 183 | (w, h), |
| 184 | (w.div_ceil(2), h.div_ceil(2)), |
| 185 | (w.div_ceil(2), h.div_ceil(2)), |
| 186 | ]; |
| 187 | for (plane, (pw, ph)) in frame.planes.iter().zip(dims) { |
| 188 | for y in 0..ph { |
| 189 | out.extend_from_slice(plane.row(y, pw).expect("plane row")); |
| 190 | } |
| 191 | } |
| 192 | Ok((out, w, h)) |
| 193 | } |
| 194 | |
| 195 | fn first_diff(a: &[u8], b: &[u8]) -> Option<usize> { |
| 196 | a.iter().zip(b).position(|(x, y)| x != y) |
| 197 | } |
| 198 | |
| 199 | |
| 200 | fn frame_bytes(frame: &ec_core::frame::VideoFrame) -> Vec<u8> { |
| 201 | let (w, h) = (frame.width as usize, frame.height as usize); |
| 202 | let mut out = Vec::with_capacity(w * h * 3 / 2); |
| 203 | let dims = [ |
| 204 | (w, h), |
| 205 | (w.div_ceil(2), h.div_ceil(2)), |
| 206 | (w.div_ceil(2), h.div_ceil(2)), |
| 207 | ]; |
| 208 | for (plane, (pw, ph)) in frame.planes.iter().zip(dims) { |
| 209 | for y in 0..ph { |
| 210 | out.extend_from_slice(plane.row(y, pw).expect("plane row")); |
| 211 | } |
| 212 | } |
| 213 | out |
| 214 | } |
| 215 | |
| 216 | |
| 217 | fn decode_all(bytes: &[u8]) -> Result<Vec<Vec<u8>>, Error> { |
| 218 | let mut dec = Decoder::new(); |
| 219 | let mut frames = Vec::new(); |
| 220 | for nal in ec_h264_syntax::AnnexBIter::new(bytes) { |
| 221 | if dec.push_nal(nal)? == NalOutcome::PictureBoundary { |
| 222 | dec.end_picture()?; |
| 223 | dec.push_nal(nal)?; |
| 224 | } |
| 225 | while let Some(f) = dec.next_frame() { |
| 226 | frames.push(frame_bytes(&f)); |
| 227 | } |
| 228 | } |
| 229 | dec.flush()?; |
| 230 | while let Some(f) = dec.next_frame() { |
| 231 | frames.push(frame_bytes(&f)); |
| 232 | } |
| 233 | Ok(frames) |
| 234 | } |
| 235 | |
| 236 | |
| 237 | fn ffmpeg_all_frames(stream: &Path, frame_len: usize) -> Option<Vec<Vec<u8>>> { |
| 238 | let out = Command::new("ffmpeg") |
| 239 | .args(["-v", "error", "-i"]) |
| 240 | .arg(stream) |
| 241 | .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"]) |
| 242 | .output() |
| 243 | .ok()?; |
| 244 | if !out.status.success() || out.stdout.is_empty() { |
| 245 | return None; |
| 246 | } |
| 247 | Some( |
| 248 | out.stdout |
| 249 | .chunks_exact(frame_len) |
| 250 | .map(<[u8]>::to_vec) |
| 251 | .collect(), |
| 252 | ) |
| 253 | } |
| 254 | |
| 255 | |
| 256 | fn x264_encode_gop( |
| 257 | dir: &Path, |
| 258 | tag: &str, |
| 259 | size: &str, |
| 260 | frames: u32, |
| 261 | extra: &[&str], |
| 262 | ) -> Option<PathBuf> { |
| 263 | let stream = dir.join(format!("{tag}.264")); |
| 264 | let source = format!("testsrc=size={size}:rate=25:duration=4"); |
| 265 | let mut args: Vec<String> = [ |
| 266 | "-hide_banner", |
| 267 | "-loglevel", |
| 268 | "error", |
| 269 | "-y", |
| 270 | "-f", |
| 271 | "lavfi", |
| 272 | "-i", |
| 273 | ] |
| 274 | .iter() |
| 275 | .map(|s| s.to_string()) |
| 276 | .collect(); |
| 277 | args.push(source); |
| 278 | if !extra.contains(&"-pix_fmt") { |
| 279 | args.extend(["-pix_fmt".into(), "yuv420p".into()]); |
| 280 | } |
| 281 | args.extend([ |
| 282 | "-c:v".into(), |
| 283 | "libx264".into(), |
| 284 | "-frames:v".into(), |
| 285 | frames.to_string(), |
| 286 | ]); |
| 287 | args.extend(extra.iter().map(|s| s.to_string())); |
| 288 | args.extend([ |
| 289 | "-f".into(), |
| 290 | "h264".into(), |
| 291 | stream.to_string_lossy().into_owned(), |
| 292 | ]); |
| 293 | let refs: Vec<&str> = args.iter().map(|s| s.as_str()).collect(); |
| 294 | run("ffmpeg", &refs).then_some(stream) |
| 295 | } |
| 296 | |
| 297 | |
| 298 | fn compare_sequence(stream: &Path) -> Result<usize, String> { |
| 299 | let bytes = std::fs::read(stream).map_err(|e| e.to_string())?; |
| 300 | let ours = decode_all(&bytes).map_err(|e| format!("{e}"))?; |
| 301 | let first = ours.first().ok_or("no frames decoded")?; |
| 302 | let theirs = ffmpeg_all_frames(stream, first.len()).ok_or("ffmpeg cannot decode the stream")?; |
| 303 | if ours.len() != theirs.len() { |
| 304 | return Err(format!( |
| 305 | "{} frames decoded, ffmpeg gave {}", |
| 306 | ours.len(), |
| 307 | theirs.len() |
| 308 | )); |
| 309 | } |
| 310 | for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() { |
| 311 | if let Some(pos) = first_diff(a, b) { |
| 312 | return Err(format!( |
| 313 | "frame {i} differs at byte {pos}: ours {} ffmpeg {}", |
| 314 | a[pos], b[pos] |
| 315 | )); |
| 316 | } |
| 317 | assert_eq!( |
| 318 | a.len(), |
| 319 | b.len(), |
| 320 | "frame {i} is {} samples, ffmpeg gave {}", |
| 321 | a.len(), |
| 322 | b.len() |
| 323 | ); |
| 324 | } |
| 325 | Ok(ours.len()) |
| 326 | } |
| 327 | |
| 328 | #[test] |
| 329 | fn jvt_cavlc_first_idr_bit_exact() { |
| 330 | let base = vectors_dir(); |
| 331 | if !require_fixtures( |
| 332 | &base, |
| 333 | "the JVT conformance vectors", |
| 334 | "scripts/fetch-vectors.sh", |
| 335 | ) { |
| 336 | return; |
| 337 | } |
| 338 | let mut passed = Vec::new(); |
| 339 | let mut failed = Vec::new(); |
| 340 | let mut refused = Vec::new(); |
| 341 | for name in all_vectors(&base) { |
| 342 | let name = name.as_str(); |
| 343 | let dir = base.join(name); |
| 344 | let Some(stream) = find_stream(&dir) else { |
| 345 | eprintln!("SKIP {name}: no bitstream file"); |
| 346 | continue; |
| 347 | }; |
| 348 | let bytes = std::fs::read(&stream).unwrap(); |
| 349 | match decode_first(&bytes) { |
| 350 | Ok((ours, w, h)) => { |
| 351 | let frame_len = w * h * 3 / 2; |
| 352 | |
| 353 | let mut ok = true; |
| 354 | if let Some(ref_path) = find_ref_yuv(&dir) { |
| 355 | let reference = std::fs::read(&ref_path).unwrap(); |
| 356 | assert!( |
| 357 | reference.len() >= frame_len, |
| 358 | "{name}: reference YUV shorter than one frame" |
| 359 | ); |
| 360 | if let Some(pos) = first_diff(&ours, &reference[..frame_len]) { |
| 361 | eprintln!( |
| 362 | "FAIL {name}: differs from reference YUV at byte {pos} \ |
| 363 | (plane offset, {w}x{h}): ours {} ref {}", |
| 364 | ours[pos], reference[pos] |
| 365 | ); |
| 366 | ok = false; |
| 367 | } |
| 368 | assert_eq!( |
| 369 | ours.len(), |
| 370 | frame_len, |
| 371 | "{name}: frame is {} samples ({w}x{h}), the reference frame is {frame_len}", |
| 372 | ours.len() |
| 373 | ); |
| 374 | } else { |
| 375 | eprintln!("WARN {name}: no reference YUV, ffmpeg only"); |
| 376 | } |
| 377 | |
| 378 | if let Some(ff) = ffmpeg_first_frame(&stream) { |
| 379 | assert!(ff.len() >= frame_len, "{name}: ffmpeg output short"); |
| 380 | if let Some(pos) = first_diff(&ours, &ff[..frame_len]) { |
| 381 | eprintln!( |
| 382 | "FAIL {name}: differs from ffmpeg at byte {pos}: ours {} ff {}", |
| 383 | ours[pos], ff[pos] |
| 384 | ); |
| 385 | ok = false; |
| 386 | } |
| 387 | assert_eq!( |
| 388 | ours.len(), |
| 389 | frame_len, |
| 390 | "{name}: frame is {} samples ({w}x{h}), the ffmpeg frame is {frame_len}", |
| 391 | ours.len() |
| 392 | ); |
| 393 | } |
| 394 | if ok { |
| 395 | passed.push(name.to_string()); |
| 396 | } else { |
| 397 | failed.push(name.to_string()); |
| 398 | } |
| 399 | } |
| 400 | |
| 401 | |
| 402 | |
| 403 | Err(e @ Error::Unsupported { .. }) => { |
| 404 | eprintln!("REFUSED {name}: {e}"); |
| 405 | refused.push(name.to_string()); |
| 406 | } |
| 407 | Err(e) => { |
| 408 | eprintln!("FAIL {name}: decode error: {e}"); |
| 409 | failed.push(name.to_string()); |
| 410 | } |
| 411 | } |
| 412 | } |
| 413 | eprintln!( |
| 414 | "PASS table ({} bit-exact, {} refused by name): {passed:?}", |
| 415 | passed.len(), |
| 416 | refused.len() |
| 417 | ); |
| 418 | assert!( |
| 419 | failed.is_empty(), |
| 420 | "streams neither bit-exact nor refused by name: {failed:?}" |
| 421 | ); |
| 422 | assert!( |
| 423 | passed.len() >= 5, |
| 424 | "fewer than 5 CAVLC conformance streams verified: {passed:?}" |
| 425 | ); |
| 426 | } |
| 427 | |
| 428 | |
| 429 | |
| 430 | |
| 431 | |
| 432 | |
| 433 | |
| 434 | |
| 435 | #[test] |
| 436 | fn steady_state_decode_loop_zero_alloc() { |
| 437 | install_counter(); |
| 438 | let base = vectors_dir(); |
| 439 | if !require_fixtures( |
| 440 | &base, |
| 441 | "the JVT conformance vectors", |
| 442 | "scripts/fetch-vectors.sh", |
| 443 | ) { |
| 444 | return; |
| 445 | } |
| 446 | |
| 447 | |
| 448 | for name in ["BA1_Sony_D", "CABA1_SVA_B", "CABA3_SVA_B"] { |
| 449 | let Some(stream) = find_stream(&base.join(name)) else { |
| 450 | continue; |
| 451 | }; |
| 452 | let bytes = std::fs::read(stream).unwrap(); |
| 453 | let mut dec = Decoder::new(); |
| 454 | let drive = |dec: &mut Decoder, count: bool| -> usize { |
| 455 | let nals: Vec<&[u8]> = ec_h264_syntax::AnnexBIter::new(&bytes).collect(); |
| 456 | let mut frames = 0usize; |
| 457 | for nal in &nals { |
| 458 | if count { |
| 459 | COUNTING_HERE.with(|c| c.set(true)); |
| 460 | } |
| 461 | let outcome = dec.push_nal(nal); |
| 462 | if count { |
| 463 | COUNTING_HERE.with(|c| c.set(false)); |
| 464 | } |
| 465 | match outcome { |
| 466 | Ok(ec_h264::NalOutcome::PictureBoundary) => { |
| 467 | dec.end_picture().expect("end_picture"); |
| 468 | dec.push_nal(nal).expect("re-push"); |
| 469 | } |
| 470 | Ok(_) => {} |
| 471 | Err(e) => panic!("{name}: {e}"), |
| 472 | } |
| 473 | while dec.next_frame().is_some() { |
| 474 | frames += 1; |
| 475 | } |
| 476 | } |
| 477 | dec.flush().expect("flush"); |
| 478 | while dec.next_frame().is_some() { |
| 479 | frames += 1; |
| 480 | } |
| 481 | frames |
| 482 | }; |
| 483 | |
| 484 | let warm = drive(&mut dec, false); |
| 485 | assert!(warm > 1, "{name}: only {warm} frames decoded"); |
| 486 | dec.reset_pictures(); |
| 487 | |
| 488 | ALLOCS.store(0, Ordering::SeqCst); |
| 489 | let again = drive(&mut dec, true); |
| 490 | let n = ALLOCS.load(Ordering::SeqCst); |
| 491 | assert_eq!( |
| 492 | again, warm, |
| 493 | "{name}: frame count changed on the second pass" |
| 494 | ); |
| 495 | assert_eq!( |
| 496 | n, 0, |
| 497 | "{name}: steady-state slice decode allocated {n} times" |
| 498 | ); |
| 499 | } |
| 500 | |
| 501 | |
| 502 | let bytes = std::fs::read(find_stream(&base.join("BA1_Sony_D")).unwrap()).unwrap(); |
| 503 | let mut dec = Decoder::new(); |
| 504 | let _ = dec.decode_first_idr(&bytes).expect("decode"); |
| 505 | ALLOCS.store(0, Ordering::SeqCst); |
| 506 | COUNTING_HERE.with(|c| c.set(true)); |
| 507 | let frame = dec.frame().expect("frame"); |
| 508 | COUNTING_HERE.with(|c| c.set(false)); |
| 509 | assert!(frame.width > 0); |
| 510 | assert!( |
| 511 | ALLOCS.load(Ordering::SeqCst) > 0, |
| 512 | "allocation counter appears dead" |
| 513 | ); |
| 514 | } |
| 515 | |
| 516 | |
| 517 | |
| 518 | |
| 519 | |
| 520 | |
| 521 | |
| 522 | |
| 523 | #[test] |
| 524 | fn ns_per_macroblock_measurement() { |
| 525 | let base = vectors_dir(); |
| 526 | if !require_fixtures( |
| 527 | &base, |
| 528 | "the JVT conformance vectors", |
| 529 | "scripts/fetch-vectors.sh", |
| 530 | ) { |
| 531 | return; |
| 532 | } |
| 533 | for name in [ |
| 534 | "BA1_Sony_D", |
| 535 | "CI_MW_D", |
| 536 | "NL1_Sony_D", |
| 537 | "CABA1_SVA_B", |
| 538 | "CABA3_SVA_B", |
| 539 | ] { |
| 540 | let Some(stream) = find_stream(&base.join(name)) else { |
| 541 | continue; |
| 542 | }; |
| 543 | let bytes = std::fs::read(stream).unwrap(); |
| 544 | let mut dec = Decoder::new(); |
| 545 | let frame = dec.decode_first_idr(&bytes).expect("warm-up"); |
| 546 | let (w, h) = (frame.width as u64, frame.height as u64); |
| 547 | let mbs = (w.div_ceil(16)) * (h.div_ceil(16)); |
| 548 | let nals: Vec<&[u8]> = ec_h264_syntax::AnnexBIter::new(&bytes).collect(); |
| 549 | |
| 550 | let iters = 200u32; |
| 551 | let start = std::time::Instant::now(); |
| 552 | for _ in 0..iters { |
| 553 | for nal in &nals { |
| 554 | match dec.push_nal(nal) { |
| 555 | Ok(ec_h264::NalOutcome::PictureBoundary) => break, |
| 556 | Ok(_) => {} |
| 557 | Err(e) => panic!("{e}"), |
| 558 | } |
| 559 | } |
| 560 | dec.end_picture().expect("end_picture"); |
| 561 | } |
| 562 | let elapsed = start.elapsed(); |
| 563 | let ns_per_mb = elapsed.as_nanos() as f64 / f64::from(iters) / mbs as f64; |
| 564 | let mpx_s = (w * h) as f64 * f64::from(iters) / elapsed.as_secs_f64() / 1e6; |
| 565 | eprintln!( |
| 566 | "PERF {name}: {w}x{h}, {mbs} MBs, {ns_per_mb:.0} ns/MB, {mpx_s:.1} Mpx/s \ |
| 567 | (intra IDR, single thread, deblock included, output copy excluded)" |
| 568 | ); |
| 569 | } |
| 570 | perf_whole_sequence(); |
| 571 | } |
| 572 | |
| 573 | |
| 574 | |
| 575 | fn perf_whole_sequence() { |
| 576 | let base = vectors_dir(); |
| 577 | for name in ["BA_MW_D", "CABA3_SVA_B", "MR1_BT_A"] { |
| 578 | let Some(stream) = find_stream(&base.join(name)) else { |
| 579 | continue; |
| 580 | }; |
| 581 | let bytes = std::fs::read(stream).unwrap(); |
| 582 | let Ok(warm) = decode_all(&bytes) else { |
| 583 | continue; |
| 584 | }; |
| 585 | if warm.is_empty() { |
| 586 | continue; |
| 587 | } |
| 588 | let frames = warm.len() as f64; |
| 589 | let start = std::time::Instant::now(); |
| 590 | let iters = 5u32; |
| 591 | for _ in 0..iters { |
| 592 | let _ = decode_all(&bytes).expect("decode"); |
| 593 | } |
| 594 | let elapsed = start.elapsed().as_secs_f64() / f64::from(iters); |
| 595 | |
| 596 | let mbs = 99.0 * frames; |
| 597 | eprintln!( |
| 598 | "PERF {name}: {frames} frames, {:.0} ns/MB, {:.1} Mpx/s \ |
| 599 | (full sequence, single thread, deblock and output copy included)", |
| 600 | elapsed * 1e9 / mbs, |
| 601 | 176.0 * 144.0 * frames / elapsed / 1e6 |
| 602 | ); |
| 603 | } |
| 604 | } |
| 605 | |
| 606 | |
| 607 | |
| 608 | |
| 609 | |
| 610 | #[test] |
| 611 | fn corrupt_streams_never_panic() { |
| 612 | let base = vectors_dir(); |
| 613 | if !require_fixtures( |
| 614 | &base, |
| 615 | "the JVT conformance vectors", |
| 616 | "scripts/fetch-vectors.sh", |
| 617 | ) { |
| 618 | return; |
| 619 | } |
| 620 | |
| 621 | |
| 622 | |
| 623 | |
| 624 | |
| 625 | for name in ["BA1_Sony_D", "CABA1_SVA_B", "CABA3_SVA_B", "BA_MW_D"] { |
| 626 | let Some(stream) = find_stream(&base.join(name)) else { |
| 627 | continue; |
| 628 | }; |
| 629 | corrupt_sweep(&std::fs::read(stream).unwrap()); |
| 630 | } |
| 631 | } |
| 632 | |
| 633 | |
| 634 | |
| 635 | fn corrupt_sweep(bytes: &[u8]) { |
| 636 | let bytes = bytes.to_vec(); |
| 637 | |
| 638 | |
| 639 | for len in (0..bytes.len().min(4096)) |
| 640 | .step_by(37) |
| 641 | .chain([bytes.len() / 2]) |
| 642 | { |
| 643 | let mut dec = Decoder::new(); |
| 644 | let _ = dec.decode_first_idr(&bytes[..len]); |
| 645 | |
| 646 | |
| 647 | let _ = decode_all(&bytes[..len]); |
| 648 | } |
| 649 | |
| 650 | |
| 651 | let mut xorshift = 0x243F_6A88u32; |
| 652 | |
| 653 | |
| 654 | let count = if cfg!(debug_assertions) { 400 } else { 2000 }; |
| 655 | let dense = count * 3 / 4; |
| 656 | for i in 0..count { |
| 657 | let mut m = bytes.clone(); |
| 658 | let pos = if i < dense { |
| 659 | i * 4 % m.len().min(6144) |
| 660 | } else { |
| 661 | xorshift ^= xorshift << 13; |
| 662 | xorshift ^= xorshift >> 17; |
| 663 | xorshift ^= xorshift << 5; |
| 664 | (xorshift as usize) % m.len() |
| 665 | }; |
| 666 | m[pos] ^= (0x5Bu8.wrapping_add(i as u8)).max(1); |
| 667 | let mut dec = Decoder::new(); |
| 668 | let _ = dec.decode_first_idr(&m); |
| 669 | if i % 8 == 0 { |
| 670 | |
| 671 | |
| 672 | |
| 673 | let _ = decode_all(&m); |
| 674 | } |
| 675 | } |
| 676 | } |
| 677 | |
| 678 | |
| 679 | |
| 680 | |
| 681 | |
| 682 | |
| 683 | |
| 684 | |
| 685 | |
| 686 | fn run(command: &str, args: &[&str]) -> bool { |
| 687 | Command::new(command) |
| 688 | .args(args) |
| 689 | .stdout(std::process::Stdio::null()) |
| 690 | .stderr(std::process::Stdio::null()) |
| 691 | .status() |
| 692 | .map(|s| s.success()) |
| 693 | .unwrap_or(false) |
| 694 | } |
| 695 | |
| 696 | fn have_ffmpeg() -> bool { |
| 697 | run( |
| 698 | "ffmpeg", |
| 699 | &["-hide_banner", "-loglevel", "error", "-version"], |
| 700 | ) |
| 701 | } |
| 702 | |
| 703 | |
| 704 | fn scratch(tag: &str) -> PathBuf { |
| 705 | let dir = std::env::temp_dir().join(format!("ec-h264-{tag}-{}", std::process::id())); |
| 706 | let _ = std::fs::create_dir_all(&dir); |
| 707 | dir |
| 708 | } |
| 709 | |
| 710 | |
| 711 | fn x264_encode(dir: &Path, tag: &str, size: &str, extra: &[&str]) -> Option<PathBuf> { |
| 712 | let stream = dir.join(format!("{tag}.264")); |
| 713 | let source = format!("testsrc=size={size}:rate=1:duration=1"); |
| 714 | let mut args: Vec<String> = [ |
| 715 | "-hide_banner", |
| 716 | "-loglevel", |
| 717 | "error", |
| 718 | "-y", |
| 719 | "-f", |
| 720 | "lavfi", |
| 721 | "-i", |
| 722 | ] |
| 723 | .iter() |
| 724 | .map(|s| s.to_string()) |
| 725 | .collect(); |
| 726 | args.push(source); |
| 727 | |
| 728 | |
| 729 | if !extra.contains(&"-pix_fmt") { |
| 730 | args.extend(["-pix_fmt".into(), "yuv420p".into()]); |
| 731 | } |
| 732 | args.extend([ |
| 733 | "-c:v".into(), |
| 734 | "libx264".into(), |
| 735 | "-frames:v".into(), |
| 736 | "1".into(), |
| 737 | ]); |
| 738 | args.extend(extra.iter().map(|s| s.to_string())); |
| 739 | args.extend([ |
| 740 | "-f".into(), |
| 741 | "h264".into(), |
| 742 | stream.to_string_lossy().into_owned(), |
| 743 | ]); |
| 744 | let refs: Vec<&str> = args.iter().map(|s| s.as_str()).collect(); |
| 745 | run("ffmpeg", &refs).then_some(stream) |
| 746 | } |
| 747 | |
| 748 | |
| 749 | fn round_trip(dir: &Path, tag: &str, size: &str, extra: &[&str]) -> Result<usize, String> { |
| 750 | let stream = |
| 751 | x264_encode(dir, tag, size, extra).ok_or(format!("{tag}: ffmpeg cannot encode"))?; |
| 752 | let expected = |
| 753 | ffmpeg_first_frame(&stream).ok_or(format!("{tag}: ffmpeg cannot decode its own output"))?; |
| 754 | let (ours, w, h) = |
| 755 | decode_first(&std::fs::read(&stream).unwrap()).map_err(|e| format!("{tag}: {e}"))?; |
| 756 | if ours.len() > expected.len() { |
| 757 | return Err(format!( |
| 758 | "{tag}: {w}x{h} is {} bytes, ffmpeg gave {}", |
| 759 | ours.len(), |
| 760 | expected.len() |
| 761 | )); |
| 762 | } |
| 763 | if ours.len() < expected.len() { |
| 764 | return Err(format!( |
| 765 | "{tag}: {w}x{h} decoded to {} bytes, ffmpeg gave {}", |
| 766 | ours.len(), |
| 767 | expected.len() |
| 768 | )); |
| 769 | } |
| 770 | Ok(ours |
| 771 | .iter() |
| 772 | .zip(&expected[..ours.len()]) |
| 773 | .filter(|(a, b)| a != b) |
| 774 | .count()) |
| 775 | } |
| 776 | |
| 777 | |
| 778 | |
| 779 | |
| 780 | const ENTROPY_MODES: [(&str, &[&str]); 2] = [ |
| 781 | ("cavlc", &["-profile:v", "baseline"]), |
| 782 | ("cabac", &["-profile:v", "main", "-coder", "ac"]), |
| 783 | ]; |
| 784 | |
| 785 | |
| 786 | |
| 787 | |
| 788 | #[test] |
| 789 | fn geometry_and_slice_structure_match_ffmpeg() { |
| 790 | if !have_ffmpeg() { |
| 791 | eprintln!("SKIP: ffmpeg not on PATH"); |
| 792 | return; |
| 793 | } |
| 794 | let dir = scratch("geometry"); |
| 795 | let cases: &[(&str, &str, &[&str])] = &[ |
| 796 | |
| 797 | ("hd", "1920x1080", &["-qp", "26"]), |
| 798 | |
| 799 | ("odd", "1916x1080", &["-qp", "26"]), |
| 800 | |
| 801 | |
| 802 | ( |
| 803 | "slices", |
| 804 | "352x288", |
| 805 | &["-qp", "24", "-x264-params", "slices=4"], |
| 806 | ), |
| 807 | |
| 808 | ( |
| 809 | "nodeblock", |
| 810 | "352x288", |
| 811 | &["-qp", "30", "-x264-params", "no-deblock=1"], |
| 812 | ), |
| 813 | |
| 814 | ( |
| 815 | "chromaqp", |
| 816 | "352x288", |
| 817 | &["-qp", "30", "-x264-params", "chroma_qp_offset=6"], |
| 818 | ), |
| 819 | |
| 820 | ("tiny", "16x16", &["-qp", "20"]), |
| 821 | ]; |
| 822 | let mut table = String::new(); |
| 823 | let mut failures = Vec::new(); |
| 824 | for (mode, profile) in ENTROPY_MODES { |
| 825 | for (tag, size, case) in cases { |
| 826 | let mut extra = profile.to_vec(); |
| 827 | extra.extend_from_slice(case); |
| 828 | let tag = format!("{mode}-{tag}"); |
| 829 | match round_trip(&dir, &tag, size, &extra) { |
| 830 | Ok(0) => table.push_str(&format!("{tag:<16} {size:<10} bit-exact\n")), |
| 831 | Ok(n) => { |
| 832 | table.push_str(&format!("{tag:<16} {size:<10} MISMATCH {n} bytes\n")); |
| 833 | failures.push(format!("{tag}: {n} bytes differ")); |
| 834 | } |
| 835 | Err(e) => { |
| 836 | table.push_str(&format!("{tag:<16} {size:<10} {e}\n")); |
| 837 | failures.push(e); |
| 838 | } |
| 839 | } |
| 840 | } |
| 841 | } |
| 842 | let _ = std::fs::remove_dir_all(&dir); |
| 843 | eprintln!("{table}"); |
| 844 | assert!(failures.is_empty(), "{failures:#?}"); |
| 845 | } |
| 846 | |
| 847 | |
| 848 | |
| 849 | |
| 850 | |
| 851 | |
| 852 | #[test] |
| 853 | fn jvt_scaling_matrices_decode_bit_exact() { |
| 854 | if !have_ffmpeg() { |
| 855 | eprintln!("SKIP: ffmpeg not on PATH"); |
| 856 | return; |
| 857 | } |
| 858 | let dir = scratch("scaling"); |
| 859 | let extra = [ |
| 860 | "-profile:v", |
| 861 | "high", |
| 862 | "-qp", |
| 863 | "26", |
| 864 | "-x264-params", |
| 865 | "cabac=0:8x8dct=0:cqm=jvt", |
| 866 | ]; |
| 867 | let result = round_trip(&dir, "cqm-jvt", "176x144", &extra); |
| 868 | let _ = std::fs::remove_dir_all(&dir); |
| 869 | match result { |
| 870 | Ok(0) => eprintln!("cqm=jvt scaling matrices bit-exact"), |
| 871 | Ok(n) => panic!("cqm=jvt: {n} bytes differ from ffmpeg"), |
| 872 | Err(e) => panic!("{e}"), |
| 873 | } |
| 874 | } |
| 875 | |
| 876 | |
| 877 | |
| 878 | #[test] |
| 879 | fn avcc_extradata_and_length_prefixed_packets() { |
| 880 | if !have_ffmpeg() { |
| 881 | eprintln!("SKIP: ffmpeg not on PATH"); |
| 882 | return; |
| 883 | } |
| 884 | let dir = scratch("avcc"); |
| 885 | let Some(annex_b) = x264_encode( |
| 886 | &dir, |
| 887 | "stream", |
| 888 | "176x144", |
| 889 | &["-profile:v", "baseline", "-qp", "26"], |
| 890 | ) else { |
| 891 | panic!("ffmpeg cannot encode a baseline picture"); |
| 892 | }; |
| 893 | let data = std::fs::read(&annex_b).unwrap(); |
| 894 | let units: Vec<Vec<u8>> = ec_h264_syntax::AnnexBIter::new(&data) |
| 895 | .map(<[u8]>::to_vec) |
| 896 | .collect(); |
| 897 | let sps = units.iter().find(|u| u[0] & 0x1F == 7).expect("an SPS"); |
| 898 | let pps = units.iter().find(|u| u[0] & 0x1F == 8).expect("a PPS"); |
| 899 | |
| 900 | |
| 901 | |
| 902 | let mut avcc = vec![1, sps[1], sps[2], sps[3], 0xFF, 0xE1]; |
| 903 | avcc.extend_from_slice(&(sps.len() as u16).to_be_bytes()); |
| 904 | avcc.extend_from_slice(sps); |
| 905 | avcc.push(1); |
| 906 | avcc.extend_from_slice(&(pps.len() as u16).to_be_bytes()); |
| 907 | avcc.extend_from_slice(pps); |
| 908 | |
| 909 | let mut params = CodecParameters::new(CodecId::H264); |
| 910 | params.extradata = Some(Buf::from_vec(avcc)); |
| 911 | let mut decoder = H264Decoder::new(params).expect("avcC parses"); |
| 912 | assert_eq!( |
| 913 | ( |
| 914 | decoder.codec_parameters().video().unwrap().width, |
| 915 | decoder.codec_parameters().video().unwrap().height |
| 916 | ), |
| 917 | (176, 144), |
| 918 | "the SPS inside the avcC sets the picture size, before any packet" |
| 919 | ); |
| 920 | |
| 921 | |
| 922 | let mut sample = Vec::new(); |
| 923 | for unit in units.iter().filter(|u| matches!(u[0] & 0x1F, 1 | 5)) { |
| 924 | sample.extend_from_slice(&(unit.len() as u32).to_be_bytes()); |
| 925 | sample.extend_from_slice(unit); |
| 926 | } |
| 927 | decoder |
| 928 | .send_packet(&Packet::new(0, TimeBase::new(1, 25), sample).with_pts(7)) |
| 929 | .expect("length prefixed packet decodes"); |
| 930 | let Frame::Video(frame) = decoder.receive_frame().expect("a frame") else { |
| 931 | panic!("video frame expected"); |
| 932 | }; |
| 933 | assert_eq!((frame.width, frame.height), (176, 144)); |
| 934 | assert_eq!( |
| 935 | frame.pts.map(|t| t.ticks), |
| 936 | Some(7), |
| 937 | "packet pts reaches the frame" |
| 938 | ); |
| 939 | |
| 940 | |
| 941 | let (annex_b_frame, _, _) = decode_first(&data).unwrap(); |
| 942 | let mut avcc_frame = Vec::with_capacity(annex_b_frame.len()); |
| 943 | for (index, plane) in frame.planes.iter().enumerate() { |
| 944 | let (w, h) = if index == 0 { (176, 144) } else { (88, 72) }; |
| 945 | for row in 0..h { |
| 946 | avcc_frame.extend_from_slice(plane.row(row, w).expect("plane row")); |
| 947 | } |
| 948 | } |
| 949 | assert_eq!(avcc_frame, annex_b_frame); |
| 950 | let _ = std::fs::remove_dir_all(&dir); |
| 951 | } |
| 952 | |
| 953 | |
| 954 | |
| 955 | |
| 956 | |
| 957 | |
| 958 | |
| 959 | |
| 960 | |
| 961 | #[test] |
| 962 | fn p_only_gop_matches_ffmpeg_every_frame() { |
| 963 | if !have_ffmpeg() { |
| 964 | eprintln!("SKIP: ffmpeg not on PATH"); |
| 965 | return; |
| 966 | } |
| 967 | let dir = scratch("p-gop"); |
| 968 | let mut failures = Vec::new(); |
| 969 | for (mode, profile) in ENTROPY_MODES { |
| 970 | let mut extra = profile.to_vec(); |
| 971 | extra.extend(["-qp", "26", "-x264-params", "bframes=0:weightp=0:ref=1"]); |
| 972 | let tag = format!("{mode}-p"); |
| 973 | match x264_encode_gop(&dir, &tag, "176x144", 12, &extra) { |
| 974 | Some(stream) => match compare_sequence(&stream) { |
| 975 | Ok(n) => eprintln!("{tag}: {n} frames bit-exact"), |
| 976 | Err(e) => failures.push(format!("{tag}: {e}")), |
| 977 | }, |
| 978 | None => failures.push(format!("{tag}: ffmpeg cannot encode")), |
| 979 | } |
| 980 | } |
| 981 | let _ = std::fs::remove_dir_all(&dir); |
| 982 | assert!(failures.is_empty(), "{failures:#?}"); |
| 983 | } |
| 984 | |
| 985 | |
| 986 | |
| 987 | |
| 988 | |
| 989 | |
| 990 | |
| 991 | |
| 992 | #[test] |
| 993 | fn jvt_full_sequence_bit_exact() { |
| 994 | let base = vectors_dir(); |
| 995 | if !require_fixtures( |
| 996 | &base, |
| 997 | "the JVT conformance vectors", |
| 998 | "scripts/fetch-vectors.sh", |
| 999 | ) { |
| 1000 | return; |
| 1001 | } |
| 1002 | let mut table = String::new(); |
| 1003 | let mut passed = 0usize; |
| 1004 | let mut refused = Vec::new(); |
| 1005 | let mut failed = Vec::new(); |
| 1006 | for name in all_vectors(&base) { |
| 1007 | let dir = base.join(&name); |
| 1008 | let Some(stream) = find_stream(&dir) else { |
| 1009 | continue; |
| 1010 | }; |
| 1011 | let bytes = std::fs::read(&stream).unwrap(); |
| 1012 | match decode_all(&bytes) { |
| 1013 | Ok(frames) if frames.is_empty() => { |
| 1014 | failed.push(format!("{name}: decoded no frames")); |
| 1015 | } |
| 1016 | Ok(frames) => { |
| 1017 | let len = frames[0].len(); |
| 1018 | let Some(ref_path) = find_ref_yuv(&dir) else { |
| 1019 | table.push_str(&format!( |
| 1020 | "{name:<16} {:>3} frames, no reference YUV\n", |
| 1021 | frames.len() |
| 1022 | )); |
| 1023 | continue; |
| 1024 | }; |
| 1025 | let reference = std::fs::read(&ref_path).unwrap(); |
| 1026 | let want = reference.len() / len; |
| 1027 | let mut bad = None; |
| 1028 | for (i, f) in frames.iter().enumerate() { |
| 1029 | let Some(chunk) = reference.get(i * len..(i + 1) * len) else { |
| 1030 | break; |
| 1031 | }; |
| 1032 | if let Some(pos) = first_diff(f, chunk) { |
| 1033 | bad = Some((i, pos)); |
| 1034 | break; |
| 1035 | } |
| 1036 | assert_eq!( |
| 1037 | f.len(), |
| 1038 | len, |
| 1039 | "{name}: frame {i} is {} samples, {len} expected", |
| 1040 | f.len() |
| 1041 | ); |
| 1042 | } |
| 1043 | match bad { |
| 1044 | None if frames.len() == want => { |
| 1045 | passed += 1; |
| 1046 | table.push_str(&format!( |
| 1047 | "{name:<16} {:>3}/{want:<3} frames bit-exact\n", |
| 1048 | frames.len() |
| 1049 | )); |
| 1050 | } |
| 1051 | None => { |
| 1052 | failed.push(format!( |
| 1053 | "{name}: {} frames decoded, reference has {want}", |
| 1054 | frames.len() |
| 1055 | )); |
| 1056 | table.push_str(&format!( |
| 1057 | "{name:<16} {:>3}/{want:<3} FRAME COUNT\n", |
| 1058 | frames.len() |
| 1059 | )); |
| 1060 | } |
| 1061 | Some((i, pos)) => { |
| 1062 | failed.push(format!("{name}: frame {i} differs at byte {pos}")); |
| 1063 | table.push_str(&format!( |
| 1064 | "{name:<16} {:>3}/{want:<3} MISMATCH frame {i}\n", |
| 1065 | frames.len() |
| 1066 | )); |
| 1067 | } |
| 1068 | } |
| 1069 | } |
| 1070 | Err(e @ Error::Unsupported { .. }) => { |
| 1071 | refused.push(name.clone()); |
| 1072 | table.push_str(&format!("{name:<16} refused: {e}\n")); |
| 1073 | } |
| 1074 | Err(e) => { |
| 1075 | failed.push(format!("{name}: {e}")); |
| 1076 | table.push_str(&format!("{name:<16} ERROR {e}\n")); |
| 1077 | } |
| 1078 | } |
| 1079 | } |
| 1080 | eprintln!("{table}"); |
| 1081 | eprintln!( |
| 1082 | "full-sequence: {passed} bit-exact, {} refused by name, {} failed", |
| 1083 | refused.len(), |
| 1084 | failed.len() |
| 1085 | ); |
| 1086 | assert!(failed.is_empty(), "{failed:#?}"); |
| 1087 | } |
| 1088 | |
| 1089 | |
| 1090 | fn decode_all_in_decode_order(bytes: &[u8]) -> Result<Vec<Vec<u8>>, Error> { |
| 1091 | let mut dec = Decoder::new(); |
| 1092 | dec.set_output_order(ec_h264::OutputOrder::Decode); |
| 1093 | let mut frames = Vec::new(); |
| 1094 | for nal in ec_h264_syntax::AnnexBIter::new(bytes) { |
| 1095 | if dec.push_nal(nal)? == NalOutcome::PictureBoundary { |
| 1096 | dec.end_picture()?; |
| 1097 | dec.push_nal(nal)?; |
| 1098 | } |
| 1099 | while let Some(f) = dec.next_frame() { |
| 1100 | frames.push(frame_bytes(&f)); |
| 1101 | } |
| 1102 | } |
| 1103 | dec.flush()?; |
| 1104 | while let Some(f) = dec.next_frame() { |
| 1105 | frames.push(frame_bytes(&f)); |
| 1106 | } |
| 1107 | Ok(frames) |
| 1108 | } |
| 1109 | |
| 1110 | |
| 1111 | |
| 1112 | |
| 1113 | |
| 1114 | fn slice_type_counts(bytes: &[u8]) -> [usize; 3] { |
| 1115 | let mut counts = [0usize; 3]; |
| 1116 | for nal in ec_h264_syntax::AnnexBIter::new(bytes) { |
| 1117 | let Some((&header, payload)) = nal.split_first() else { |
| 1118 | continue; |
| 1119 | }; |
| 1120 | if !matches!(header & 0x1F, 1 | 5) { |
| 1121 | continue; |
| 1122 | } |
| 1123 | let mut r = ec_core::BitReader::new(payload); |
| 1124 | if r.read_ue().is_err() { |
| 1125 | continue; |
| 1126 | } |
| 1127 | let Ok(code) = r.read_ue() else { continue }; |
| 1128 | match code % 5 { |
| 1129 | 0 => counts[1] += 1, |
| 1130 | 1 => counts[2] += 1, |
| 1131 | 2 => counts[0] += 1, |
| 1132 | _ => {} |
| 1133 | } |
| 1134 | } |
| 1135 | counts |
| 1136 | } |
| 1137 | |
| 1138 | |
| 1139 | |
| 1140 | |
| 1141 | |
| 1142 | |
| 1143 | |
| 1144 | |
| 1145 | #[test] |
| 1146 | fn b_pictures_match_ffmpeg_every_frame() { |
| 1147 | if !have_ffmpeg() { |
| 1148 | eprintln!("SKIP: ffmpeg not on PATH"); |
| 1149 | return; |
| 1150 | } |
| 1151 | let dir = scratch("b-gop"); |
| 1152 | let cases: &[(&str, &[&str])] = &[ |
| 1153 | ( |
| 1154 | "spatial", |
| 1155 | &[ |
| 1156 | "-x264-params", |
| 1157 | "bframes=3:b-adapt=0:direct=spatial:weightp=0", |
| 1158 | ], |
| 1159 | ), |
| 1160 | ( |
| 1161 | "temporal", |
| 1162 | &[ |
| 1163 | "-x264-params", |
| 1164 | "bframes=3:b-adapt=0:direct=temporal:weightp=0", |
| 1165 | ], |
| 1166 | ), |
| 1167 | |
| 1168 | |
| 1169 | ( |
| 1170 | "pyramid", |
| 1171 | &[ |
| 1172 | "-x264-params", |
| 1173 | "bframes=3:b-adapt=0:b-pyramid=normal:direct=spatial", |
| 1174 | ], |
| 1175 | ), |
| 1176 | |
| 1177 | ( |
| 1178 | "weighted", |
| 1179 | &[ |
| 1180 | "-x264-params", |
| 1181 | "bframes=3:b-adapt=0:weightp=2:weightb=1:direct=spatial", |
| 1182 | ], |
| 1183 | ), |
| 1184 | ]; |
| 1185 | let mut failures = Vec::new(); |
| 1186 | let mut table = String::new(); |
| 1187 | for (mode, profile) in ENTROPY_MODES { |
| 1188 | if mode == "cavlc" { |
| 1189 | continue; |
| 1190 | } |
| 1191 | for (tag, case) in cases { |
| 1192 | for coder in ["ac", "0"] { |
| 1193 | let mut extra = vec!["-profile:v", "main", "-coder", coder, "-qp", "26"]; |
| 1194 | extra.extend_from_slice(case); |
| 1195 | let name = format!("{tag}-{}", if coder == "ac" { "cabac" } else { "cavlc" }); |
| 1196 | match x264_encode_gop(&dir, &name, "176x144", 20, &extra) { |
| 1197 | Some(stream) => { |
| 1198 | let counts = slice_type_counts(&std::fs::read(&stream).unwrap()); |
| 1199 | if counts[2] == 0 { |
| 1200 | failures.push(format!("{name}: encoder produced no B slices")); |
| 1201 | continue; |
| 1202 | } |
| 1203 | match compare_sequence(&stream) { |
| 1204 | Ok(n) => table.push_str(&format!( |
| 1205 | "{name:<18} {n:>3} frames bit-exact ({} B slices)\n", |
| 1206 | counts[2] |
| 1207 | )), |
| 1208 | Err(e) => failures.push(format!("{name}: {e}")), |
| 1209 | } |
| 1210 | } |
| 1211 | None => failures.push(format!("{name}: ffmpeg cannot encode")), |
| 1212 | } |
| 1213 | } |
| 1214 | } |
| 1215 | let _ = profile; |
| 1216 | } |
| 1217 | let _ = std::fs::remove_dir_all(&dir); |
| 1218 | eprintln!("{table}"); |
| 1219 | assert!(failures.is_empty(), "{failures:#?}"); |
| 1220 | } |
| 1221 | |
| 1222 | |
| 1223 | |
| 1224 | |
| 1225 | |
| 1226 | |
| 1227 | |
| 1228 | #[test] |
| 1229 | fn output_is_display_order_and_the_reorder_is_real() { |
| 1230 | if !have_ffmpeg() { |
| 1231 | eprintln!("SKIP: ffmpeg not on PATH"); |
| 1232 | return; |
| 1233 | } |
| 1234 | let dir = scratch("order"); |
| 1235 | let extra = [ |
| 1236 | "-profile:v", |
| 1237 | "main", |
| 1238 | "-coder", |
| 1239 | "ac", |
| 1240 | "-qp", |
| 1241 | "26", |
| 1242 | "-x264-params", |
| 1243 | "bframes=3:b-adapt=0:b-pyramid=normal", |
| 1244 | ]; |
| 1245 | let stream = x264_encode_gop(&dir, "reorder", "176x144", 20, &extra).expect("encode"); |
| 1246 | let bytes = std::fs::read(&stream).unwrap(); |
| 1247 | let counts = slice_type_counts(&bytes); |
| 1248 | assert!(counts[2] > 0, "the encoder produced no B slices to reorder"); |
| 1249 | let display = decode_all(&bytes).expect("display order decode"); |
| 1250 | let decode = decode_all_in_decode_order(&bytes).expect("decode order decode"); |
| 1251 | let ffmpeg = ffmpeg_all_frames(&stream, display[0].len()).expect("ffmpeg"); |
| 1252 | let _ = std::fs::remove_dir_all(&dir); |
| 1253 | |
| 1254 | assert_eq!(display.len(), ffmpeg.len()); |
| 1255 | assert_eq!(decode.len(), display.len()); |
| 1256 | for (i, (a, b)) in display.iter().zip(&ffmpeg).enumerate() { |
| 1257 | assert!( |
| 1258 | first_diff(a, b).is_none(), |
| 1259 | "display-order frame {i} differs from ffmpeg" |
| 1260 | ); |
| 1261 | assert_eq!( |
| 1262 | a.len(), |
| 1263 | b.len(), |
| 1264 | "display-order frame {i} is {} samples, ffmpeg gave {}", |
| 1265 | a.len(), |
| 1266 | b.len() |
| 1267 | ); |
| 1268 | } |
| 1269 | |
| 1270 | |
| 1271 | for (i, f) in decode.iter().enumerate() { |
| 1272 | assert!( |
| 1273 | display.iter().any(|d| d == f), |
| 1274 | "decode-order frame {i} is not in the display-order output" |
| 1275 | ); |
| 1276 | } |
| 1277 | let moved = decode.iter().zip(&display).filter(|(a, b)| a != b).count(); |
| 1278 | assert!( |
| 1279 | moved > 0, |
| 1280 | "decode order and display order are identical: the stream does not \ |
| 1281 | reorder, so this test proves nothing" |
| 1282 | ); |
| 1283 | eprintln!( |
| 1284 | "{} of {} frames move under reordering", |
| 1285 | moved, |
| 1286 | display.len() |
| 1287 | ); |
| 1288 | } |
| 1289 | |
| 1290 | |
| 1291 | |
| 1292 | |
| 1293 | |
| 1294 | |
| 1295 | |
| 1296 | |
| 1297 | #[test] |
| 1298 | fn a_frame_num_gap_keeps_decoding() { |
| 1299 | if !have_ffmpeg() { |
| 1300 | eprintln!("SKIP: ffmpeg not on PATH"); |
| 1301 | return; |
| 1302 | } |
| 1303 | let dir = scratch("gap"); |
| 1304 | let extra = [ |
| 1305 | "-profile:v", |
| 1306 | "baseline", |
| 1307 | "-qp", |
| 1308 | "26", |
| 1309 | "-x264-params", |
| 1310 | "bframes=0:ref=1:keyint=100", |
| 1311 | ]; |
| 1312 | let stream = x264_encode_gop(&dir, "gap", "176x144", 12, &extra).expect("encode"); |
| 1313 | let bytes = std::fs::read(&stream).unwrap(); |
| 1314 | let units: Vec<Vec<u8>> = ec_h264_syntax::AnnexBIter::new(&bytes) |
| 1315 | .map(<[u8]>::to_vec) |
| 1316 | .collect(); |
| 1317 | let _ = std::fs::remove_dir_all(&dir); |
| 1318 | |
| 1319 | |
| 1320 | let mut vcl_seen = 0; |
| 1321 | let mut dec = Decoder::new(); |
| 1322 | let mut frames = 0usize; |
| 1323 | let mut errors = Vec::new(); |
| 1324 | for unit in &units { |
| 1325 | if matches!(unit[0] & 0x1F, 1 | 5) { |
| 1326 | vcl_seen += 1; |
| 1327 | if vcl_seen == 4 { |
| 1328 | continue; |
| 1329 | } |
| 1330 | } |
| 1331 | match dec.push_nal(unit) { |
| 1332 | Ok(NalOutcome::PictureBoundary) => { |
| 1333 | dec.end_picture().expect("end_picture"); |
| 1334 | dec.push_nal(unit).expect("re-push"); |
| 1335 | } |
| 1336 | Ok(_) => {} |
| 1337 | Err(e) => errors.push(format!("{e}")), |
| 1338 | } |
| 1339 | while dec.next_frame().is_some() { |
| 1340 | frames += 1; |
| 1341 | } |
| 1342 | } |
| 1343 | dec.flush().expect("flush"); |
| 1344 | while dec.next_frame().is_some() { |
| 1345 | frames += 1; |
| 1346 | } |
| 1347 | assert!(errors.is_empty(), "decoding stopped at the gap: {errors:?}"); |
| 1348 | |
| 1349 | |
| 1350 | assert!( |
| 1351 | frames >= 11, |
| 1352 | "only {frames} frames survived a single dropped picture" |
| 1353 | ); |
| 1354 | eprintln!("frame_num gap: {frames} frames decoded after dropping one picture"); |
| 1355 | } |
| 1356 | |
| 1357 | |
| 1358 | |
| 1359 | |
| 1360 | #[test] |
| 1361 | fn geometry_with_motion_matches_ffmpeg() { |
| 1362 | if !have_ffmpeg() { |
| 1363 | eprintln!("SKIP: ffmpeg not on PATH"); |
| 1364 | return; |
| 1365 | } |
| 1366 | let dir = scratch("geometry-motion"); |
| 1367 | let cases: &[(&str, &str, &[&str])] = &[ |
| 1368 | ("hd", "1920x1080", &["bframes=2:b-adapt=0"]), |
| 1369 | ("odd", "1916x1078", &["bframes=2:b-adapt=0"]), |
| 1370 | |
| 1371 | |
| 1372 | ("slices", "352x288", &["bframes=2:b-adapt=0:slices=4"]), |
| 1373 | ( |
| 1374 | "nodeblock", |
| 1375 | "352x288", |
| 1376 | &["bframes=2:b-adapt=0:no-deblock=1"], |
| 1377 | ), |
| 1378 | |
| 1379 | |
| 1380 | ("tiny", "16x16", &["bframes=2:b-adapt=0"]), |
| 1381 | |
| 1382 | ( |
| 1383 | "manyref", |
| 1384 | "352x288", |
| 1385 | &["bframes=3:b-adapt=0:ref=5:b-pyramid=normal"], |
| 1386 | ), |
| 1387 | ]; |
| 1388 | let mut table = String::new(); |
| 1389 | let mut failures = Vec::new(); |
| 1390 | for coder in ["ac", "0"] { |
| 1391 | for (tag, size, params) in cases { |
| 1392 | let extra = vec![ |
| 1393 | "-profile:v", |
| 1394 | "main", |
| 1395 | "-coder", |
| 1396 | coder, |
| 1397 | "-qp", |
| 1398 | "26", |
| 1399 | "-x264-params", |
| 1400 | params[0], |
| 1401 | ]; |
| 1402 | let name = format!("{coder}-{tag}"); |
| 1403 | match x264_encode_gop(&dir, &name, size, 10, &extra) { |
| 1404 | Some(stream) => match compare_sequence(&stream) { |
| 1405 | Ok(n) => { |
| 1406 | table.push_str(&format!("{name:<14} {size:<10} {n:>2} frames bit-exact\n")) |
| 1407 | } |
| 1408 | Err(e) => { |
| 1409 | table.push_str(&format!("{name:<14} {size:<10} {e}\n")); |
| 1410 | failures.push(format!("{name}: {e}")); |
| 1411 | } |
| 1412 | }, |
| 1413 | None => failures.push(format!("{name}: ffmpeg cannot encode")), |
| 1414 | } |
| 1415 | } |
| 1416 | } |
| 1417 | let _ = std::fs::remove_dir_all(&dir); |
| 1418 | eprintln!("{table}"); |
| 1419 | assert!(failures.is_empty(), "{failures:#?}"); |
| 1420 | } |
| 1421 | |
| 1422 | |
| 1423 | |
| 1424 | |
| 1425 | |
| 1426 | |
| 1427 | |
| 1428 | |
| 1429 | #[test] |
| 1430 | fn switching_slices_are_refused_by_name() { |
| 1431 | use ec_core::BitWriter; |
| 1432 | |
| 1433 | let mut annexb: Vec<u8> = Vec::new(); |
| 1434 | let mut nal = |kind: u8, ref_idc: u8, payload: &[u8]| { |
| 1435 | annexb.extend_from_slice(&[0, 0, 0, 1]); |
| 1436 | annexb.push((ref_idc << 5) | kind); |
| 1437 | annexb.extend_from_slice(payload); |
| 1438 | }; |
| 1439 | |
| 1440 | let mut w = BitWriter::new(); |
| 1441 | w.write_bits(66, 8); |
| 1442 | w.write_bits(0, 8); |
| 1443 | w.write_bits(30, 8); |
| 1444 | w.write_ue(0); |
| 1445 | w.write_ue(0); |
| 1446 | w.write_ue(2); |
| 1447 | w.write_ue(1); |
| 1448 | w.write_bit(false); |
| 1449 | w.write_ue(10); |
| 1450 | w.write_ue(8); |
| 1451 | w.write_bit(true); |
| 1452 | w.write_bit(true); |
| 1453 | w.write_bit(false); |
| 1454 | w.write_bit(false); |
| 1455 | w.write_bit(true); |
| 1456 | w.align_to_byte(); |
| 1457 | nal(7, 3, w.as_bytes()); |
| 1458 | |
| 1459 | let mut w = BitWriter::new(); |
| 1460 | w.write_ue(0); |
| 1461 | w.write_ue(0); |
| 1462 | w.write_bit(false); |
| 1463 | w.write_bit(false); |
| 1464 | w.write_ue(0); |
| 1465 | w.write_ue(0); |
| 1466 | w.write_ue(0); |
| 1467 | w.write_bit(false); |
| 1468 | w.write_bits(0, 2); |
| 1469 | w.write_se(0); |
| 1470 | w.write_se(0); |
| 1471 | w.write_se(0); |
| 1472 | w.write_bit(false); |
| 1473 | w.write_bit(false); |
| 1474 | w.write_bit(false); |
| 1475 | w.write_bit(true); |
| 1476 | w.align_to_byte(); |
| 1477 | nal(8, 3, w.as_bytes()); |
| 1478 | |
| 1479 | |
| 1480 | let mut w = BitWriter::new(); |
| 1481 | w.write_ue(0); |
| 1482 | w.write_ue(3); |
| 1483 | w.write_ue(0); |
| 1484 | w.write_bits(0, 4); |
| 1485 | w.write_bit(false); |
| 1486 | w.write_bit(false); |
| 1487 | w.write_bit(false); |
| 1488 | w.write_bit(false); |
| 1489 | w.write_se(0); |
| 1490 | w.write_se(0); |
| 1491 | w.write_bit(true); |
| 1492 | w.align_to_byte(); |
| 1493 | nal(1, 2, w.as_bytes()); |
| 1494 | |
| 1495 | let mut dec = Decoder::new(); |
| 1496 | let mut refusal = None; |
| 1497 | for unit in ec_h264_syntax::AnnexBIter::new(&annexb) { |
| 1498 | if let Err(e) = dec.push_nal(unit) { |
| 1499 | refusal = Some(e); |
| 1500 | break; |
| 1501 | } |
| 1502 | } |
| 1503 | match refusal { |
| 1504 | Some(Error::Unsupported { what, why }) => { |
| 1505 | assert!( |
| 1506 | what.contains("SP and SI"), |
| 1507 | "refused as {what} ({why}), expected the switching-slice refusal" |
| 1508 | ); |
| 1509 | } |
| 1510 | other => panic!("expected an SP-slice refusal, got {other:?}"), |
| 1511 | } |
| 1512 | } |
| 1513 | |
| 1514 | |
| 1515 | |
| 1516 | |
| 1517 | |
| 1518 | |
| 1519 | |
| 1520 | |
| 1521 | |
| 1522 | fn compare_sequence_streamed( |
| 1523 | stream: &Path, |
| 1524 | frames_wanted: usize, |
| 1525 | ) -> Result<StreamedResult, String> { |
| 1526 | use std::io::Read; |
| 1527 | |
| 1528 | let bytes = std::fs::read(stream).map_err(|e| e.to_string())?; |
| 1529 | let mut child = Command::new("ffmpeg") |
| 1530 | .args(["-v", "error", "-i"]) |
| 1531 | .arg(stream) |
| 1532 | .args([ |
| 1533 | "-frames:v", |
| 1534 | &frames_wanted.to_string(), |
| 1535 | "-f", |
| 1536 | "rawvideo", |
| 1537 | "-pix_fmt", |
| 1538 | "yuv420p", |
| 1539 | "-", |
| 1540 | ]) |
| 1541 | .stdout(std::process::Stdio::piped()) |
| 1542 | .stderr(std::process::Stdio::null()) |
| 1543 | .spawn() |
| 1544 | .map_err(|e| e.to_string())?; |
| 1545 | let mut out = child.stdout.take().expect("piped stdout"); |
| 1546 | |
| 1547 | let mut dec = Decoder::new(); |
| 1548 | let mut reference = Vec::new(); |
| 1549 | let mut result = StreamedResult::default(); |
| 1550 | let mut oracle_open = true; |
| 1551 | let mut take = |frame: Vec<u8>, result: &mut StreamedResult, reference: &mut Vec<u8>| { |
| 1552 | result.produced += 1; |
| 1553 | if !oracle_open || result.compared >= frames_wanted { |
| 1554 | return; |
| 1555 | } |
| 1556 | reference.resize(frame.len(), 0); |
| 1557 | if out.read_exact(reference).is_err() { |
| 1558 | oracle_open = false; |
| 1559 | return; |
| 1560 | } |
| 1561 | if let Some(pos) = first_diff(&frame, reference) { |
| 1562 | result.diffs.push((result.compared, pos)); |
| 1563 | } |
| 1564 | result.compared += 1; |
| 1565 | }; |
| 1566 | |
| 1567 | for nal in ec_h264_syntax::AnnexBIter::new(&bytes) { |
| 1568 | match dec.push_nal(nal) { |
| 1569 | Ok(NalOutcome::PictureBoundary) => { |
| 1570 | dec.end_picture().map_err(|e| format!("{e}"))?; |
| 1571 | dec.push_nal(nal).map_err(|e| format!("{e}"))?; |
| 1572 | } |
| 1573 | Ok(_) => {} |
| 1574 | Err(e) => return Err(format!("{e}")), |
| 1575 | } |
| 1576 | while let Some(f) = dec.next_frame() { |
| 1577 | take(frame_bytes(&f), &mut result, &mut reference); |
| 1578 | } |
| 1579 | } |
| 1580 | dec.flush().map_err(|e| format!("{e}"))?; |
| 1581 | while let Some(f) = dec.next_frame() { |
| 1582 | take(frame_bytes(&f), &mut result, &mut reference); |
| 1583 | } |
| 1584 | let _ = child.kill(); |
| 1585 | let _ = child.wait(); |
| 1586 | Ok(result) |
| 1587 | } |
| 1588 | |
| 1589 | |
| 1590 | #[derive(Default)] |
| 1591 | struct StreamedResult { |
| 1592 | |
| 1593 | produced: usize, |
| 1594 | |
| 1595 | compared: usize, |
| 1596 | |
| 1597 | diffs: Vec<(usize, usize)>, |
| 1598 | } |
| 1599 | |
| 1600 | |
| 1601 | fn extract_annexb(src: &Path, dst: &Path, frames: usize) -> bool { |
| 1602 | run( |
| 1603 | "ffmpeg", |
| 1604 | &[ |
| 1605 | "-v", |
| 1606 | "error", |
| 1607 | "-y", |
| 1608 | "-i", |
| 1609 | &src.to_string_lossy(), |
| 1610 | "-map", |
| 1611 | "0:v:0", |
| 1612 | "-c", |
| 1613 | "copy", |
| 1614 | "-bsf:v", |
| 1615 | "h264_mp4toannexb", |
| 1616 | "-frames:v", |
| 1617 | &frames.to_string(), |
| 1618 | "-f", |
| 1619 | "h264", |
| 1620 | &dst.to_string_lossy(), |
| 1621 | ], |
| 1622 | ) |
| 1623 | } |
| 1624 | |
| 1625 | |
| 1626 | |
| 1627 | |
| 1628 | |
| 1629 | |
| 1630 | |
| 1631 | |
| 1632 | |
| 1633 | fn compare_container_streamed( |
| 1634 | source: &Path, |
| 1635 | frames_wanted: usize, |
| 1636 | ) -> Result<StreamedResult, String> { |
| 1637 | use ec_core::registry::{Decoder as _, Demuxer as _}; |
| 1638 | use std::io::Read; |
| 1639 | |
| 1640 | let file = std::fs::File::open(source).map_err(|e| e.to_string())?; |
| 1641 | let mut demux = ec_mp4::Mp4Demuxer::new(std::io::BufReader::new(file)) |
| 1642 | .map_err(|e| format!("ec-mp4 open: {e}"))?; |
| 1643 | let (stream_index, params) = demux |
| 1644 | .streams() |
| 1645 | .iter() |
| 1646 | .find(|s| s.params.codec == ec_core::registry::CodecId::H264) |
| 1647 | .map(|s| (s.index, s.params.clone())) |
| 1648 | .ok_or("no H.264 track")?; |
| 1649 | let mut dec = ec_h264::H264Decoder::new(params).map_err(|e| format!("{e}"))?; |
| 1650 | |
| 1651 | let mut child = Command::new("ffmpeg") |
| 1652 | .args(["-v", "error", "-i"]) |
| 1653 | .arg(source) |
| 1654 | .args([ |
| 1655 | "-map", |
| 1656 | "0:v:0", |
| 1657 | "-frames:v", |
| 1658 | &frames_wanted.to_string(), |
| 1659 | "-f", |
| 1660 | "rawvideo", |
| 1661 | "-pix_fmt", |
| 1662 | "yuv420p", |
| 1663 | "-", |
| 1664 | ]) |
| 1665 | .stdout(std::process::Stdio::piped()) |
| 1666 | .stderr(std::process::Stdio::null()) |
| 1667 | .spawn() |
| 1668 | .map_err(|e| e.to_string())?; |
| 1669 | let mut out = child.stdout.take().expect("piped stdout"); |
| 1670 | |
| 1671 | let mut reference = Vec::new(); |
| 1672 | let mut result = StreamedResult::default(); |
| 1673 | let mut oracle_open = true; |
| 1674 | let mut take = |frame: Vec<u8>, result: &mut StreamedResult, reference: &mut Vec<u8>| { |
| 1675 | result.produced += 1; |
| 1676 | if !oracle_open || result.compared >= frames_wanted { |
| 1677 | return; |
| 1678 | } |
| 1679 | reference.resize(frame.len(), 0); |
| 1680 | if out.read_exact(reference).is_err() { |
| 1681 | oracle_open = false; |
| 1682 | return; |
| 1683 | } |
| 1684 | if let Some(pos) = first_diff(&frame, reference) { |
| 1685 | result.diffs.push((result.compared, pos)); |
| 1686 | } |
| 1687 | result.compared += 1; |
| 1688 | }; |
| 1689 | let mut drain = |
| 1690 | |dec: &mut ec_h264::H264Decoder, result: &mut StreamedResult, reference: &mut Vec<u8>| { |
| 1691 | while let Ok(ec_core::frame::Frame::Video(f)) = dec.receive_frame() { |
| 1692 | take(frame_bytes(&f), result, reference); |
| 1693 | } |
| 1694 | }; |
| 1695 | while result.produced < frames_wanted { |
| 1696 | let packet = match demux.next_packet() { |
| 1697 | Ok(p) => p, |
| 1698 | Err(_) => break, |
| 1699 | }; |
| 1700 | if packet.stream != stream_index { |
| 1701 | continue; |
| 1702 | } |
| 1703 | dec.send_packet(&packet).map_err(|e| format!("{e}"))?; |
| 1704 | drain(&mut dec, &mut result, &mut reference); |
| 1705 | } |
| 1706 | dec.flush().map_err(|e| format!("{e}"))?; |
| 1707 | drain(&mut dec, &mut result, &mut reference); |
| 1708 | let _ = child.kill(); |
| 1709 | let _ = child.wait(); |
| 1710 | Ok(result) |
| 1711 | } |
| 1712 | |
| 1713 | |
| 1714 | |
| 1715 | |
| 1716 | |
| 1717 | |
| 1718 | |
| 1719 | |
| 1720 | |
| 1721 | |
| 1722 | |
| 1723 | |
| 1724 | |
| 1725 | |
| 1726 | |
| 1727 | |
| 1728 | |
| 1729 | |
| 1730 | |
| 1731 | |
| 1732 | |
| 1733 | |
| 1734 | |
| 1735 | |
| 1736 | |
| 1737 | |
| 1738 | |
| 1739 | |
| 1740 | |
| 1741 | |
| 1742 | |
| 1743 | |
| 1744 | |
| 1745 | |
| 1746 | #[ignore = "sweeps the PERSONAL media library (~/Videos, ~/Downloads, ~/Music) through the gitignored fixtures/real-library-manifest.tsv; MINUTES of wall time (measured past 840 s on the workstation), so workstation only -- budget an hour, it is not wedged. A runner host has no such library, so the test is either a silent green or a red for the wrong reason. Run it on the workstation with --ignored."] |
| 1747 | #[test] |
| 1748 | fn real_library_streams_match_ffmpeg() { |
| 1749 | if !have_ffmpeg() { |
| 1750 | eprintln!("SKIP: ffmpeg not on PATH"); |
| 1751 | return; |
| 1752 | } |
| 1753 | let manifest = |
| 1754 | Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/real-library-manifest.tsv"); |
| 1755 | let Ok(text) = std::fs::read_to_string(&manifest) else { |
| 1756 | eprintln!("SKIP: {} missing", manifest.display()); |
| 1757 | return; |
| 1758 | }; |
| 1759 | let dir = scratch("real-library"); |
| 1760 | const FRAMES: usize = 500; |
| 1761 | |
| 1762 | const MIN_FRAMES: usize = 100; |
| 1763 | let mut table = String::new(); |
| 1764 | let mut decoded = 0usize; |
| 1765 | let mut refused = 0usize; |
| 1766 | let mut failures = Vec::new(); |
| 1767 | let mut seen_containers = std::collections::BTreeSet::new(); |
| 1768 | |
| 1769 | for line in text.lines().skip(1) { |
| 1770 | let mut f = line.split('\t'); |
| 1771 | let (Some(path), Some(container), Some(vcodec)) = (f.next(), f.next(), f.next()) else { |
| 1772 | continue; |
| 1773 | }; |
| 1774 | if vcodec != "h264" || !Path::new(path).is_file() { |
| 1775 | continue; |
| 1776 | } |
| 1777 | |
| 1778 | |
| 1779 | let width = f.next().unwrap_or("0"); |
| 1780 | let key = (container.to_string(), width.to_string()); |
| 1781 | if !seen_containers.insert(key) { |
| 1782 | continue; |
| 1783 | } |
| 1784 | let name: String = Path::new(path) |
| 1785 | .file_name() |
| 1786 | .map(|n| n.to_string_lossy().chars().take(38).collect()) |
| 1787 | .unwrap_or_default(); |
| 1788 | let annexb = dir.join("stream.264"); |
| 1789 | if !extract_annexb(Path::new(path), &annexb, FRAMES) { |
| 1790 | table.push_str(&format!("{name:<40} {container:<12} not extractable\n")); |
| 1791 | continue; |
| 1792 | } |
| 1793 | match compare_sequence_streamed(&annexb, FRAMES) { |
| 1794 | Ok(r) if !r.diffs.is_empty() => { |
| 1795 | failures.push(format!( |
| 1796 | "{name}: {} of {} frames differ", |
| 1797 | r.diffs.len(), |
| 1798 | r.compared |
| 1799 | )); |
| 1800 | table.push_str(&format!( |
| 1801 | "{name:<40} {container:<12} {width:>5}px MISMATCH {} of {}\n", |
| 1802 | r.diffs.len(), |
| 1803 | r.compared |
| 1804 | )); |
| 1805 | } |
| 1806 | |
| 1807 | |
| 1808 | |
| 1809 | |
| 1810 | Ok(r) if r.compared < r.produced.min(MIN_FRAMES) => { |
| 1811 | match compare_container_streamed(Path::new(path), FRAMES) { |
| 1812 | Ok(c) if !c.diffs.is_empty() => { |
| 1813 | failures.push(format!( |
| 1814 | "{name} (container demux): {} of {} frames differ", |
| 1815 | c.diffs.len(), |
| 1816 | c.compared |
| 1817 | )); |
| 1818 | table.push_str(&format!( |
| 1819 | "{name:<40} {container:<12} {width:>5}px MISMATCH {} of {} \ |
| 1820 | (container demux)\n", |
| 1821 | c.diffs.len(), |
| 1822 | c.compared |
| 1823 | )); |
| 1824 | } |
| 1825 | Ok(c) if c.compared >= MIN_FRAMES => { |
| 1826 | decoded += 1; |
| 1827 | table.push_str(&format!( |
| 1828 | "{name:<40} {container:<12} {width:>5}px {:>4} frames bit-exact \ |
| 1829 | (container demux)\n", |
| 1830 | c.compared |
| 1831 | )); |
| 1832 | } |
| 1833 | Ok(c) => { |
| 1834 | table.push_str(&format!( |
| 1835 | "{name:<40} {container:<12} {width:>5}px oracle short both ways: \ |
| 1836 | ffmpeg gave {} frames, we decoded {}\n", |
| 1837 | c.compared, c.produced |
| 1838 | )); |
| 1839 | } |
| 1840 | Err(e) => { |
| 1841 | table.push_str(&format!( |
| 1842 | "{name:<40} {container:<12} {width:>5}px oracle short, container \ |
| 1843 | demux failed: {e}\n" |
| 1844 | )); |
| 1845 | } |
| 1846 | } |
| 1847 | } |
| 1848 | Ok(r) => { |
| 1849 | decoded += 1; |
| 1850 | table.push_str(&format!( |
| 1851 | "{name:<40} {container:<12} {width:>5}px {:>4} frames bit-exact\n", |
| 1852 | r.compared |
| 1853 | )); |
| 1854 | } |
| 1855 | Err(e) if e.contains("unsupported") => { |
| 1856 | refused += 1; |
| 1857 | table.push_str(&format!( |
| 1858 | "{name:<40} {container:<12} {width:>5}px refused: {e}\n" |
| 1859 | )); |
| 1860 | } |
| 1861 | Err(e) => { |
| 1862 | failures.push(format!("{name}: {e}")); |
| 1863 | table.push_str(&format!( |
| 1864 | "{name:<40} {container:<12} {width:>5}px ERROR {e}\n" |
| 1865 | )); |
| 1866 | } |
| 1867 | } |
| 1868 | } |
| 1869 | let _ = std::fs::remove_dir_all(&dir); |
| 1870 | eprintln!("{table}"); |
| 1871 | eprintln!("real library: {decoded} decoded bit-exact, {refused} refused by name"); |
| 1872 | assert!(failures.is_empty(), "{failures:#?}"); |
| 1873 | assert!( |
| 1874 | decoded >= 3, |
| 1875 | "only {decoded} real files swept end to end; the sweep is the point" |
| 1876 | ); |
| 1877 | } |
| 1878 | |
| 1879 | |
| 1880 | |
| 1881 | |
| 1882 | |
| 1883 | |
| 1884 | |
| 1885 | |
| 1886 | #[test] |
| 1887 | fn packet_entry_surface_reorders_and_carries_timestamps() { |
| 1888 | if !have_ffmpeg() { |
| 1889 | eprintln!("SKIP: ffmpeg not on PATH"); |
| 1890 | return; |
| 1891 | } |
| 1892 | let dir = scratch("entry"); |
| 1893 | let extra = [ |
| 1894 | "-profile:v", |
| 1895 | "main", |
| 1896 | "-coder", |
| 1897 | "ac", |
| 1898 | "-qp", |
| 1899 | "26", |
| 1900 | "-x264-params", |
| 1901 | "bframes=3:b-adapt=0:b-pyramid=normal", |
| 1902 | ]; |
| 1903 | let stream = x264_encode_gop(&dir, "entry", "176x144", 16, &extra).expect("encode"); |
| 1904 | let data = std::fs::read(&stream).unwrap(); |
| 1905 | assert!( |
| 1906 | slice_type_counts(&data)[2] > 0, |
| 1907 | "the encoder produced no B slices" |
| 1908 | ); |
| 1909 | |
| 1910 | |
| 1911 | |
| 1912 | let units: Vec<Vec<u8>> = ec_h264_syntax::AnnexBIter::new(&data) |
| 1913 | .map(<[u8]>::to_vec) |
| 1914 | .collect(); |
| 1915 | let mut access_units: Vec<Vec<u8>> = Vec::new(); |
| 1916 | let mut current: Vec<u8> = Vec::new(); |
| 1917 | let mut current_has_slice = false; |
| 1918 | for unit in &units { |
| 1919 | let is_slice = matches!(unit[0] & 0x1F, 1 | 5); |
| 1920 | if is_slice && current_has_slice { |
| 1921 | access_units.push(std::mem::take(&mut current)); |
| 1922 | current_has_slice = false; |
| 1923 | } |
| 1924 | current_has_slice |= is_slice; |
| 1925 | current.extend_from_slice(&[0, 0, 0, 1]); |
| 1926 | current.extend_from_slice(unit); |
| 1927 | } |
| 1928 | if current_has_slice { |
| 1929 | access_units.push(current); |
| 1930 | } |
| 1931 | |
| 1932 | let time_base = TimeBase::new(1, 25); |
| 1933 | let mut decoder = H264Decoder::new(CodecParameters::new(CodecId::H264)).expect("decoder"); |
| 1934 | let mut out: Vec<(i64, Vec<u8>)> = Vec::new(); |
| 1935 | for (i, au) in access_units.iter().enumerate() { |
| 1936 | let packet = Packet::new(0, time_base, au.clone()).with_pts(i as i64); |
| 1937 | decoder.send_packet(&packet).expect("send_packet"); |
| 1938 | while let Ok(Frame::Video(f)) = decoder.receive_frame() { |
| 1939 | out.push((f.pts.map(|t| t.ticks).unwrap_or(-1), frame_bytes(&f))); |
| 1940 | } |
| 1941 | } |
| 1942 | decoder.flush().expect("flush"); |
| 1943 | while let Ok(Frame::Video(f)) = decoder.receive_frame() { |
| 1944 | out.push((f.pts.map(|t| t.ticks).unwrap_or(-1), frame_bytes(&f))); |
| 1945 | } |
| 1946 | |
| 1947 | let expected = ffmpeg_all_frames(&stream, out[0].1.len()).expect("ffmpeg"); |
| 1948 | let _ = std::fs::remove_dir_all(&dir); |
| 1949 | assert_eq!(out.len(), expected.len(), "frame count"); |
| 1950 | for (i, ((_, ours), theirs)) in out.iter().zip(&expected).enumerate() { |
| 1951 | assert!( |
| 1952 | first_diff(ours, theirs).is_none(), |
| 1953 | "packet-path frame {i} differs from ffmpeg" |
| 1954 | ); |
| 1955 | assert_eq!( |
| 1956 | ours.len(), |
| 1957 | theirs.len(), |
| 1958 | "packet-path frame {i} is {} samples, ffmpeg gave {}", |
| 1959 | ours.len(), |
| 1960 | theirs.len() |
| 1961 | ); |
| 1962 | } |
| 1963 | |
| 1964 | |
| 1965 | |
| 1966 | |
| 1967 | |
| 1968 | let by_decode_order = decode_all_in_decode_order(&data).expect("decode order"); |
| 1969 | assert_eq!(by_decode_order.len(), out.len()); |
| 1970 | for (position, (tag, pixels)) in out.iter().enumerate() { |
| 1971 | let tag = usize::try_from(*tag).expect("a tag was lost"); |
| 1972 | assert!( |
| 1973 | first_diff(pixels, &by_decode_order[tag]).is_none(), |
| 1974 | "output position {position} carries the timestamp of packet {tag}, \ |
| 1975 | but its pixels are a different picture" |
| 1976 | ); |
| 1977 | assert_eq!( |
| 1978 | pixels.len(), |
| 1979 | by_decode_order[tag].len(), |
| 1980 | "output position {position} is {} samples, decode-order frame {tag} is {}", |
| 1981 | pixels.len(), |
| 1982 | by_decode_order[tag].len() |
| 1983 | ); |
| 1984 | } |
| 1985 | let order: Vec<i64> = out.iter().map(|(pts, _)| *pts).collect(); |
| 1986 | assert_ne!( |
| 1987 | order, |
| 1988 | (0..order.len() as i64).collect::<Vec<_>>(), |
| 1989 | "output order equals packet order, so no reordering happened" |
| 1990 | ); |
| 1991 | eprintln!( |
| 1992 | "packet entry surface: {} frames, packets emitted in order {order:?}", |
| 1993 | out.len() |
| 1994 | ); |
| 1995 | } |
| 1996 | |
| 1997 | |
| 1998 | |
| 1999 | |
| 2000 | |
| 2001 | |
| 2002 | |
| 2003 | |
| 2004 | |
| 2005 | #[test] |
| 2006 | fn spatial_direct_over_a_b_reference_matches_ffmpeg() { |
| 2007 | if !have_ffmpeg() { |
| 2008 | eprintln!("SKIP: ffmpeg not on PATH"); |
| 2009 | return; |
| 2010 | } |
| 2011 | let dir = scratch("direct-bref"); |
| 2012 | let mut failures = Vec::new(); |
| 2013 | for (tag, coder) in [("cabac", "ac"), ("cavlc", "0")] { |
| 2014 | let extra = [ |
| 2015 | "-profile:v", |
| 2016 | "high", |
| 2017 | "-coder", |
| 2018 | coder, |
| 2019 | "-qp", |
| 2020 | "24", |
| 2021 | "-bf", |
| 2022 | "3", |
| 2023 | "-refs", |
| 2024 | "4", |
| 2025 | "-x264-params", |
| 2026 | "b-adapt=0:b-pyramid=normal:direct=spatial:8x8dct=1", |
| 2027 | ]; |
| 2028 | match x264_encode_gop(&dir, tag, "352x288", 40, &extra) { |
| 2029 | None => failures.push(format!("{tag}: ffmpeg cannot encode")), |
| 2030 | Some(stream) => match compare_sequence(&stream) { |
| 2031 | Ok(n) => eprintln!("b-pyramid direct {tag}: {n} frames bit-exact"), |
| 2032 | Err(e) => failures.push(format!("{tag}: {e}")), |
| 2033 | }, |
| 2034 | } |
| 2035 | } |
| 2036 | let _ = std::fs::remove_dir_all(&dir); |
| 2037 | assert!(failures.is_empty(), "{failures:#?}"); |
| 2038 | } |
| 2039 | |
| 2040 | |
| 2041 | |
| 2042 | |
| 2043 | |
| 2044 | |
| 2045 | fn pps_enables_8x8(stream: &Path) -> bool { |
| 2046 | let bytes = std::fs::read(stream).unwrap_or_default(); |
| 2047 | let mut rbsp = Vec::new(); |
| 2048 | let mut sps = None; |
| 2049 | for nal in ec_h264_syntax::AnnexBIter::new(&bytes) { |
| 2050 | let Some((&header, payload)) = nal.split_first() else { |
| 2051 | continue; |
| 2052 | }; |
| 2053 | let Ok(h) = ec_h264_syntax::NalHeader::parse(header) else { |
| 2054 | continue; |
| 2055 | }; |
| 2056 | ec_h264_syntax::unescape_rbsp(payload, &mut rbsp); |
| 2057 | match h.unit_type { |
| 2058 | ec_h264_syntax::NalUnitType::Sps => sps = ec_h264_syntax::Sps::parse(&rbsp).ok(), |
| 2059 | ec_h264_syntax::NalUnitType::Pps => { |
| 2060 | if let Ok(p) = ec_h264_syntax::Pps::parse(&rbsp, |_| sps.as_ref()) { |
| 2061 | return p.transform_8x8_mode; |
| 2062 | } |
| 2063 | } |
| 2064 | _ => {} |
| 2065 | } |
| 2066 | } |
| 2067 | false |
| 2068 | } |
| 2069 | |
| 2070 | |
| 2071 | |
| 2072 | |
| 2073 | |
| 2074 | #[test] |
| 2075 | fn high_profile_8x8_inter_sequences_match_ffmpeg() { |
| 2076 | if !have_ffmpeg() { |
| 2077 | eprintln!("SKIP: ffmpeg not on PATH"); |
| 2078 | return; |
| 2079 | } |
| 2080 | let dir = scratch("high8x8-seq"); |
| 2081 | let mut failures = Vec::new(); |
| 2082 | let cases: &[(&str, &[&str])] = &[ |
| 2083 | ( |
| 2084 | "p-cabac", |
| 2085 | &["-profile:v", "high", "-coder", "ac", "-bf", "0"], |
| 2086 | ), |
| 2087 | ( |
| 2088 | "p-cavlc", |
| 2089 | &["-profile:v", "high", "-coder", "0", "-bf", "0"], |
| 2090 | ), |
| 2091 | ( |
| 2092 | "b-cabac", |
| 2093 | &[ |
| 2094 | "-profile:v", |
| 2095 | "high", |
| 2096 | "-coder", |
| 2097 | "ac", |
| 2098 | "-bf", |
| 2099 | "2", |
| 2100 | "-x264-params", |
| 2101 | "b-adapt=0", |
| 2102 | ], |
| 2103 | ), |
| 2104 | ( |
| 2105 | "b-cavlc", |
| 2106 | &[ |
| 2107 | "-profile:v", |
| 2108 | "high", |
| 2109 | "-coder", |
| 2110 | "0", |
| 2111 | "-bf", |
| 2112 | "2", |
| 2113 | "-x264-params", |
| 2114 | "b-adapt=0", |
| 2115 | ], |
| 2116 | ), |
| 2117 | |
| 2118 | |
| 2119 | ( |
| 2120 | "subpart", |
| 2121 | &[ |
| 2122 | "-profile:v", |
| 2123 | "high", |
| 2124 | "-coder", |
| 2125 | "ac", |
| 2126 | "-bf", |
| 2127 | "0", |
| 2128 | "-x264-params", |
| 2129 | "partitions=all:8x8dct=1", |
| 2130 | ], |
| 2131 | ), |
| 2132 | ]; |
| 2133 | for (tag, extra) in cases { |
| 2134 | let mut args = extra.to_vec(); |
| 2135 | args.extend(["-qp", "26"]); |
| 2136 | match x264_encode_gop(&dir, tag, "176x144", 12, &args) { |
| 2137 | None => failures.push(format!("{tag}: ffmpeg cannot encode")), |
| 2138 | Some(stream) => match compare_sequence(&stream) { |
| 2139 | Ok(n) => { |
| 2140 | assert!( |
| 2141 | pps_enables_8x8(&stream), |
| 2142 | "{tag}: encoder did not enable the 8x8 transform" |
| 2143 | ); |
| 2144 | eprintln!("8x8 {tag}: {n} frames bit-exact"); |
| 2145 | } |
| 2146 | Err(e) => failures.push(format!("{tag}: {e}")), |
| 2147 | }, |
| 2148 | } |
| 2149 | } |
| 2150 | let _ = std::fs::remove_dir_all(&dir); |
| 2151 | assert!(failures.is_empty(), "{failures:#?}"); |
| 2152 | } |
| 2153 | |
| 2154 | |
| 2155 | |
| 2156 | |
| 2157 | |
| 2158 | |
| 2159 | |
| 2160 | |
| 2161 | #[test] |
| 2162 | fn h264_seek_matches_linear_open_gop() { |
| 2163 | if !have_ffmpeg() { |
| 2164 | eprintln!("SKIP: ffmpeg not on PATH"); |
| 2165 | return; |
| 2166 | } |
| 2167 | let src = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/video/h264-open-gop.mp4"); |
| 2168 | if !require_fixtures( |
| 2169 | &src, |
| 2170 | "the open-GOP fixture", |
| 2171 | "scripts/gen-fixtures.sh (fixtures/video/h264-open-gop.mp4)", |
| 2172 | ) { |
| 2173 | return; |
| 2174 | } |
| 2175 | let dir = scratch("open-gop"); |
| 2176 | std::fs::create_dir_all(&dir).unwrap(); |
| 2177 | let annexb = dir.join("open-gop.264"); |
| 2178 | assert!(extract_annexb(&src, &annexb, 120), "ffmpeg extraction"); |
| 2179 | let data = std::fs::read(&annexb).unwrap(); |
| 2180 | let _ = std::fs::remove_dir_all(&dir); |
| 2181 | |
| 2182 | |
| 2183 | |
| 2184 | let units: Vec<Vec<u8>> = ec_h264_syntax::AnnexBIter::new(&data) |
| 2185 | .map(<[u8]>::to_vec) |
| 2186 | .collect(); |
| 2187 | let mut access_units: Vec<Vec<u8>> = Vec::new(); |
| 2188 | let mut current: Vec<u8> = Vec::new(); |
| 2189 | let mut current_has_slice = false; |
| 2190 | for unit in &units { |
| 2191 | let is_slice = matches!(unit[0] & 0x1F, 1 | 5); |
| 2192 | if is_slice && current_has_slice { |
| 2193 | access_units.push(std::mem::take(&mut current)); |
| 2194 | current_has_slice = false; |
| 2195 | } |
| 2196 | current_has_slice |= is_slice; |
| 2197 | current.extend_from_slice(&[0, 0, 0, 1]); |
| 2198 | current.extend_from_slice(unit); |
| 2199 | } |
| 2200 | if current_has_slice { |
| 2201 | access_units.push(current); |
| 2202 | } |
| 2203 | |
| 2204 | |
| 2205 | |
| 2206 | const TARGET: usize = 30; |
| 2207 | let mut dec = Decoder::new(); |
| 2208 | let mut linear_frame_30 = None; |
| 2209 | let mut index = 0usize; |
| 2210 | for nal in ec_h264_syntax::AnnexBIter::new(&data) { |
| 2211 | if dec.push_nal(nal).expect("push_nal") == NalOutcome::PictureBoundary { |
| 2212 | dec.end_picture().expect("end_picture"); |
| 2213 | dec.push_nal(nal).expect("re-push"); |
| 2214 | } |
| 2215 | while let Some(f) = dec.next_frame() { |
| 2216 | if index == TARGET { |
| 2217 | linear_frame_30 = Some(frame_bytes(&f)); |
| 2218 | } |
| 2219 | index += 1; |
| 2220 | } |
| 2221 | } |
| 2222 | dec.flush().expect("flush"); |
| 2223 | while let Some(f) = dec.next_frame() { |
| 2224 | if index == TARGET { |
| 2225 | linear_frame_30 = Some(frame_bytes(&f)); |
| 2226 | } |
| 2227 | index += 1; |
| 2228 | } |
| 2229 | let linear_frame_30 = linear_frame_30.expect("linear decode reached frame 30"); |
| 2230 | |
| 2231 | |
| 2232 | |
| 2233 | let is_open_gop_i = |au: &[u8]| -> bool { |
| 2234 | let Some((&header, payload)) = au.get(4).zip(au.get(5..)) else { |
| 2235 | return false; |
| 2236 | }; |
| 2237 | if header & 0x1F != 1 { |
| 2238 | return false; |
| 2239 | } |
| 2240 | let mut r = ec_core::BitReader::new(payload); |
| 2241 | if r.read_ue().is_err() { |
| 2242 | return false; |
| 2243 | } |
| 2244 | matches!(r.read_ue(), Ok(code) if code % 5 == 2) |
| 2245 | }; |
| 2246 | let cra_at = access_units |
| 2247 | .iter() |
| 2248 | .position(|au| is_open_gop_i(au)) |
| 2249 | .expect("an open-GOP I access unit exists"); |
| 2250 | |
| 2251 | |
| 2252 | |
| 2253 | |
| 2254 | let mut seek_dec = Decoder::new(); |
| 2255 | for nal in ec_h264_syntax::AnnexBIter::new(&access_units[0]) { |
| 2256 | seek_dec.push_nal(nal).expect("prime parameter sets"); |
| 2257 | } |
| 2258 | seek_dec.end_picture().expect("end priming IDR"); |
| 2259 | seek_dec.reset_pictures(); |
| 2260 | |
| 2261 | let mut seeked_frame = None; |
| 2262 | 'outer: for au in &access_units[cra_at..] { |
| 2263 | for nal in ec_h264_syntax::AnnexBIter::new(au) { |
| 2264 | if seek_dec.push_nal(nal).expect("seek decode") == NalOutcome::PictureBoundary { |
| 2265 | seek_dec.end_picture().expect("end_picture"); |
| 2266 | seek_dec.push_nal(nal).expect("re-push"); |
| 2267 | } |
| 2268 | } |
| 2269 | if let Some(f) = seek_dec.next_frame() { |
| 2270 | seeked_frame = Some(frame_bytes(&f)); |
| 2271 | break 'outer; |
| 2272 | } |
| 2273 | } |
| 2274 | if seeked_frame.is_none() { |
| 2275 | seek_dec.flush().expect("flush"); |
| 2276 | seeked_frame = seek_dec.next_frame().map(|f| frame_bytes(&f)); |
| 2277 | } |
| 2278 | let seeked_frame = seeked_frame.expect("a frame came out after the seek"); |
| 2279 | |
| 2280 | assert_eq!( |
| 2281 | seeked_frame, linear_frame_30, |
| 2282 | "seeking to the open-GOP I before frame 30 handed back a different \ |
| 2283 | picture than a linear decode of frame 30 — leading pictures with \ |
| 2284 | missing references were not dropped" |
| 2285 | ); |
| 2286 | } |