//! Live GPU tests: every one of these talks to the real VA-API driver. //! //! They are not `#[ignore]`d — a hardware crate whose tests do not touch the //! hardware tests nothing — but they *skip* (print and return) when there is no //! //! The oracle is ffmpeg's software decoder: every fixture is decoded here and //! by `ffmpeg -f rawvideo`, and the two are compared frame by frame. use std::io::Read; use std::path::{Path, PathBuf}; use std::process::Stdio; use std::rc::Rc; use ec_hw::{ Codec, Decoder, EncCodec, Encoder, EncoderConfig, Frame, FrameMetadata, I420, I420_16, RateControlMode, }; use ec_va::Display; mod common; use common::display; /// Frames compared per fixture: enough to cover several GOPs and any /// reordering, few enough to keep the suite under a minute. const FRAMES: usize = 24; /// The software reference: ffmpeg decoding the same file to raw planes. struct Reference { child: std::process::Child, frame_bytes: usize, ten_bit: bool, } impl Reference { fn open(path: &Path, width: u32, height: u32, ten_bit: bool) -> Option { let pix = if ten_bit { "yuv420p10le" } else { "yuv420p" }; let child = ec_testkit::ffmpeg() .args(["-nostdin", "-v", "error", "-i"]) .arg(path) // `-fps_mode passthrough`: without it ffmpeg conforms its output to // the container's nominal frame rate, duplicating or dropping // pictures on a film whose real cadence differs — which shows up // here as everything being one frame out from some point onward. .args([ "-map", "0:v:0", "-fps_mode", "passthrough", "-pix_fmt", pix, "-f", "rawvideo", "-", ]) .stdout(Stdio::piped()) .stderr(Stdio::null()) .spawn() .ok()?; let samples = (width as usize * height as usize * 3).div_ceil(2); Some(Reference { child, frame_bytes: if ten_bit { samples * 2 } else { samples }, ten_bit, }) } /// The next reference frame, as samples at the stream's own bit depth. /// /// A 10-bit stream is compared at 10 bits rather than converted down: /// `ffmpeg -pix_fmt yuv420p` on a 10-bit source dithers, which would hide a /// real difference behind a fake 53 dB one (measured, not assumed). fn next(&mut self, width: u32, height: u32) -> Option { let stdout = self.child.stdout.as_mut()?; let mut buf = vec![0u8; self.frame_bytes]; stdout.read_exact(&mut buf).ok()?; let (w, h) = (width as usize, height as usize); let (cw, ch) = (w.div_ceil(2), h.div_ceil(2)); let (y_len, c_len) = (w * h, cw * ch); if self.ten_bit { let read = |slice: &[u8]| -> Vec { slice .as_chunks::<2>() .0 .iter() .map(|p| u16::from_le_bytes(*p)) .collect() }; Some(Planes { y: read(&buf[..y_len * 2]), u: read(&buf[y_len * 2..(y_len + c_len) * 2]), v: read(&buf[(y_len + c_len) * 2..(y_len + 2 * c_len) * 2]), peak: 1023.0, }) } else { let read = |slice: &[u8]| -> Vec { slice.iter().map(|&v| u16::from(v)).collect() }; Some(Planes { y: read(&buf[..y_len]), u: read(&buf[y_len..y_len + c_len]), v: read(&buf[y_len + c_len..y_len + 2 * c_len]), peak: 255.0, }) } } } impl Drop for Reference { fn drop(&mut self) { let _ = self.child.kill(); let _ = self.child.wait(); } } /// Three planes at whatever bit depth the stream carries. struct Planes { y: Vec, u: Vec, v: Vec, peak: f64, } impl Planes { fn from_8bit(f: &I420) -> Planes { let read = |v: &[u8]| -> Vec { v.iter().map(|&s| u16::from(s)).collect() }; Planes { y: read(&f.y), u: read(&f.u), v: read(&f.v), peak: 255.0, } } fn from_16bit(f: &ec_hw::I420_16) -> Planes { Planes { y: f.y.clone(), u: f.u.clone(), v: f.v.clone(), peak: 1023.0, } } } /// Peak signal to noise ratio over the three planes, in dB; `f64::INFINITY` /// when the frames are identical. fn psnr(a: &Planes, b: &Planes) -> f64 { let mut sum = 0f64; let mut n = 0usize; for (x, y) in [(&a.y, &b.y), (&a.u, &b.u), (&a.v, &b.v)] { for (p, q) in x.iter().zip(y.iter()) { let d = f64::from(*p) - f64::from(*q); sum += d * d; } n += x.len().min(y.len()); } if n == 0 { return 0.0; } let mse = sum / n as f64; if mse == 0.0 { return f64::INFINITY; } 10.0 * (a.peak * a.peak / mse).log10() } /// Feed a whole elementary stream to a decoder, collecting frames. /// /// H.264 and HEVC are fed access unit by access unit, which is what a demuxer /// hands over; VP9 and AV1 arrive as IVF frames. fn decode_stream( decoder: &mut Decoder, codec: Codec, data: &[u8], limit: usize, mut on_frame: impl FnMut(Frame), ) -> Result { let mut count = 0usize; let units: Vec<&[u8]> = match codec { Codec::H264 | Codec::H265 => split_access_units(data, codec), Codec::Vp9 | Codec::Av1 => split_ivf(data), }; for (i, unit) in units.iter().enumerate() { decoder.decode(unit, i as i64)?; while let Some(frame) = decoder.next_frame() { count += 1; on_frame(frame); if count >= limit { return Ok(count); } } } decoder.flush()?; while let Some(frame) = decoder.next_frame() { count += 1; on_frame(frame); if count >= limit { break; } } Ok(count) } /// Split an Annex B stream into access units: a new one starts at the first /// VCL NAL of a picture, i.e. at an AUD, a parameter set, or a slice whose /// first-slice flag is set after a previous slice. fn split_access_units(data: &[u8], codec: Codec) -> Vec<&[u8]> { let mut starts: Vec = Vec::new(); let mut seen_slice = false; let mut i = 0usize; while i + 3 < data.len() { if data[i] != 0 || data[i + 1] != 0 || data[i + 2] != 1 { i += 1; continue; } let nal = i + 3; let (is_vcl, first_slice) = match codec { Codec::H264 => { let t = data[nal] & 0x1f; let first = data.get(nal + 1).is_some_and(|&b| b & 0x80 != 0); ((1..=5).contains(&t), first) } _ => { let t = (data[nal] >> 1) & 0x3f; let first = data.get(nal + 2).is_some_and(|&b| b & 0x80 != 0); (t <= 31, first) } }; if is_vcl { if seen_slice && first_slice { starts.push(i); seen_slice = false; } if first_slice { seen_slice = true; } } i = nal + 1; } let mut out = Vec::new(); let mut prev = 0usize; for &start in &starts { out.push(&data[prev..start]); prev = start; } if prev < data.len() { out.push(&data[prev..]); } out } /// Split an IVF file into its frames. fn split_ivf(data: &[u8]) -> Vec<&[u8]> { let mut out = Vec::new(); if data.len() < 32 || &data[..4] != b"DKIF" { return out; } let header = u16::from_le_bytes([data[6], data[7]]) as usize; let mut pos = header.max(32); while pos + 12 <= data.len() { let size = u32::from_le_bytes([data[pos], data[pos + 1], data[pos + 2], data[pos + 3]]) as usize; pos += 12; if pos + size > data.len() { break; } out.push(&data[pos..pos + size]); pos += size; } out } /// Decode every named fixture and compare with ffmpeg, frame by frame. fn compare_against_ffmpeg(files: &[PathBuf], codec: Codec, ten_bit: bool) { let Some(display) = display() else { return }; assert!(!files.is_empty(), "no fixtures: run scripts/fixtures.sh"); let mut table = Vec::new(); for path in files { let data = std::fs::read(path).expect("fixture is readable"); let mut decoder = Decoder::new(&display, codec).expect("decoder opens"); let mut reference: Option = None; let mut worst = f64::INFINITY; let mut identical = 0usize; let mut compared = 0usize; let mut mismatched_size = false; let result = decode_stream(&mut decoder, codec, &data, FRAMES, |frame| { let (w, h) = frame.display_size; let reference = reference .get_or_insert_with(|| Reference::open(path, w, h, ten_bit).expect("ffmpeg runs")); let Some(want) = reference.next(w, h) else { return; }; let got = if ten_bit { Planes::from_16bit(&frame.to_i420_16().expect("readback")) } else { Planes::from_8bit(&frame.to_i420().expect("readback")) }; if got.y.len() != want.y.len() { mismatched_size = true; return; } let db = psnr(&got, &want); if std::env::var_os("EC_HW_DEBUG").is_some() { eprintln!(" frame {compared}: {db:.1} dB (ts {})", frame.timestamp); } if db.is_infinite() { identical += 1; } worst = worst.min(db); compared += 1; }); let decoded = result.expect("decode succeeds"); assert!( !mismatched_size, "{}: frame size disagrees with ffmpeg", path.display() ); assert!(compared > 0, "{}: nothing decoded", path.display()); table.push(format!( "{:<40} {decoded:>3} frames, {identical:>3}/{compared} identical, worst {}", path.file_name().unwrap_or_default().to_string_lossy(), if worst.is_infinite() { "exact".to_string() } else { format!("{worst:.1} dB") } )); assert!( worst >= 40.0, "{}: worst frame PSNR {worst:.1} dB against ffmpeg", path.display() ); } for row in table { println!("{row}"); } } /// The fixture's own name. Never the whole path: a checkout directory called /// `edith_codecs-av1fast` made every `.ivf` — VP9 included — select as an AV1 /// fixture, and the VP9 streams then came back as `obu_forbidden_bit is set`. fn name_of(p: &Path) -> String { p.file_name() .unwrap_or_default() .to_string_lossy() .to_string() } /// The 4:2:0 fixtures of one kind; the 4:4:4 and monochrome ones are the /// profiles this GPU does not decode, and have their own test. fn profile_420(pattern: &str, codec: &str) -> Vec { ec_testkit::fixtures("bitstreams", pattern) .into_iter() .filter(|p| { let name = name_of(p); name.contains(codec) && !name.contains("444") && !name.contains("monochrome") }) .collect() } fn eight_bit(pattern: &str, codec: &str) -> Vec { profile_420(pattern, codec) .into_iter() .filter(|p| !name_of(p).contains("10bit")) .collect() } fn ten_bit(pattern: &str, codec: &str) -> Vec { profile_420(pattern, codec) .into_iter() .filter(|p| name_of(p).contains("10bit")) .collect() } #[test] fn h264_matches_ffmpeg() { compare_against_ffmpeg(&ec_testkit::fixtures("bitstreams", "264"), Codec::H264, false); } #[test] fn hevc_8bit_matches_ffmpeg() { compare_against_ffmpeg(&eight_bit("265", "hevc"), Codec::H265, false); } /// The 10-bit path, which is the RT format defect this crate exists to not /// repeat: a Main10 stream must get a `VA_RT_FORMAT_YUV420_10` context and a /// P010 surface, and the ten bits must survive to the caller. #[test] fn hevc_10bit_decodes_to_p010() { let files = ten_bit("265", "hevc"); assert!(!files.is_empty(), "no 10-bit HEVC fixtures"); let Some(display) = display() else { return }; let data = std::fs::read(&files[0]).expect("fixture is readable"); let mut decoder = Decoder::new(&display, Codec::H265).expect("decoder opens"); let mut depth = 0u8; decode_stream(&mut decoder, Codec::H265, &data, 1, |frame| { depth = frame.bit_depth; }) .expect("decode succeeds"); assert_eq!(depth, 10, "a Main10 stream decoded at {depth} bits"); let info = decoder.stream_info().expect("the session exists"); assert_eq!(info.bit_depth, 10); assert_eq!(info.profile, ec_va::caps::Profile::HEVCMain10); compare_against_ffmpeg(&files, Codec::H265, true); } #[test] fn av1_matches_ffmpeg() { compare_against_ffmpeg(&eight_bit("ivf", "av1"), Codec::Av1, false); } /// A moving synthetic frame: a gradient with a box that travels, so motion /// compensation has something to find and a static-image encoder cannot cheat. fn source_frame(width: u32, height: u32, t: u32) -> I420 { let (w, h) = (width as usize, height as usize); let (cw, ch) = (w.div_ceil(2), h.div_ceil(2)); let mut f = I420 { y: vec![0; w * h], u: vec![128; cw * ch], v: vec![128; cw * ch], width, height, }; for y in 0..h { for x in 0..w { f.y[y * w + x] = ((x * 200 / w) + (y * 55 / h)) as u8; } } let (bx, by) = ((t as usize * 7) % (w - 64), (t as usize * 5) % (h - 64)); for y in by..by + 64 { for x in bx..bx + 64 { f.y[y * w + x] = 235; } } for y in by / 2..(by + 64) / 2 { for x in bx / 2..(bx + 64) / 2 { f.u[y * cw + x] = 90; f.v[y * cw + x] = 240; } } f } /// Encode `frames` synthetic pictures and return the bitstream. fn encode_stream( display: &Rc, codec: EncCodec, width: u32, height: u32, frames: u32, ) -> Result, ec_hw::Error> { let mut config = EncoderConfig::new(codec, width, height); config.gop_size = 30; config.framerate = (30, 1); config.rate_control = RateControlMode::ConstantQp { qp: 26 }; let mut encoder = Encoder::new(display, config)?; let mut out = Vec::new(); for t in 0..frames { let coded = encoder.encode( &source_frame(width, height, t), FrameMetadata { timestamp: i64::from(t), force_keyframe: false, }, )?; assert_eq!(coded.is_keyframe, t == 0, "GOP structure at frame {t}"); out.extend_from_slice(&coded.data); } Ok(out) } /// Decode a bitstream with ffmpeg and compare with the frames that went in. fn round_trip(codec: EncCodec, width: u32, height: u32, min_db: f64) { let Some(display) = display() else { return }; let frames = 12u32; let stream = match encode_stream(&display, codec, width, height, frames) { Ok(stream) => stream, Err(e) => panic!("{codec:?} encode failed: {e}"), }; assert!( stream.len() > 1000, "{codec:?}: {} bytes is not a stream", stream.len() ); let dir = std::env::temp_dir().join(format!("ec-hw-{codec:?}-{width}x{height}")); std::fs::create_dir_all(&dir).expect("temp dir"); let path = dir.join(match codec { EncCodec::H264 => "out.264", EncCodec::H265 => "out.265", EncCodec::Av1 => "out.obu", }); std::fs::write(&path, &stream).expect("write bitstream"); // ffprobe first: the conformance window / frame cropping has to survive, so // a 1916-wide encode comes back 1916 wide and not 1920. let probe = ec_testkit::ffprobe() .args([ "-v", "error", "-select_streams", "v:0", "-show_entries", "stream=width,height", "-of", "csv=p=0", ]) .arg(&path) .output() .expect("ffprobe runs"); let dims = String::from_utf8_lossy(&probe.stdout).trim().to_string(); assert_eq!( dims, format!("{width},{height}"), "{codec:?}: ffprobe sees {dims}" ); let mut reference = Reference::open(&path, width, height, false).expect("ffmpeg runs"); let mut worst = f64::INFINITY; let mut compared = 0u32; for t in 0..frames { let Some(got) = reference.next(width, height) else { break; }; let want = Planes::from_8bit(&source_frame(width, height, t)); let db = psnr(&got, &want); worst = worst.min(db); compared += 1; } assert_eq!( compared, frames, "{codec:?}: ffmpeg decoded {compared} of {frames}" ); println!( "{codec:?} {width}x{height}: {compared} frames, {} bytes, worst {worst:.1} dB vs source", stream.len() ); assert!( worst >= min_db, "{codec:?}: worst frame {worst:.1} dB against the source" ); } #[test] fn h264_encode_round_trips_through_ffmpeg() { round_trip(EncCodec::H264, 640, 480, 30.0); } #[test] fn hevc_encode_round_trips_through_ffmpeg() { round_trip(EncCodec::H265, 640, 480, 30.0); } /// stream is neither flat nor 8-bit content dressed up as 10. fn source_frame_16(width: u32, height: u32, t: u32) -> I420_16 { let (w, h) = (width as usize, height as usize); let (cw, ch) = (w.div_ceil(2), h.div_ceil(2)); let mut f = I420_16 { y: vec![0; w * h], u: vec![512; cw * ch], v: vec![512; cw * ch], width, height, bit_depth: 10, }; for y in 0..h { for x in 0..w { f.y[y * w + x] = (64 + x * 700 / w + y * 176 / h) as u16; } } let (bx, by) = ((t as usize * 7) % (w - 64), (t as usize * 5) % (h - 64)); for y in by..by + 64 { for x in bx..bx + 64 { f.y[y * w + x] = 940; } } for y in by / 2..(by + 64) / 2 { for x in bx / 2..(bx + 64) / 2 { f.u[y * cw + x] = 360; f.v[y * cw + x] = 960; } } f } fn ten_bit_source(dir: &Path, frames: u32) -> (String, PathBuf, Vec) { let y4m = dir.join("source-10bit.y4m"); let (w, h) = (1920u32, 1024u32); let planes: Vec = (0..frames).map(|t| source_frame_16(w, h, t)).collect(); assert!(write_y4m_16(&y4m, &planes, (24, 1)), "write the 10-bit y4m"); ("synthetic 10-bit gradient".into(), y4m, planes) } /// Write 10-bit planes as a y4m so ffmpeg sees the same source the encoder did. fn write_y4m_16(path: &Path, frames: &[I420_16], fps: (u32, u32)) -> bool { use std::io::Write; let Ok(file) = std::fs::File::create(path) else { return false; }; let mut out = std::io::BufWriter::new(file); let (w, h) = (frames[0].width, frames[0].height); if write!( out, "YUV4MPEG2 W{w} H{h} F{}:{} Ip A1:1 C420p10", fps.0, fps.1 ) .and_then(|()| out.write_all(b"\n")) .is_err() { return false; } for f in frames { if out.write_all(b"FRAME\n").is_err() { return false; } for plane in [&f.y, &f.u, &f.v] { let bytes: Vec = plane.iter().flat_map(|s| s.to_le_bytes()).collect(); if out.write_all(&bytes).is_err() { return false; } } } out.flush().is_ok() } /// What ffprobe calls the stream's pixel format — for an AV1 stream that is /// libdav1d reporting the sequence header's `high_bitdepth`, read by a decoder /// that shares no code with the writer above. fn ffprobe_pix_fmt(path: &Path, format: &str) -> Option { let out = ec_testkit::ffprobe() .args([ "-v", "error", "-select_streams", "v:0", "-show_entries", "stream=pix_fmt", "-of", "default=nw=1:nk=1", "-f", format, ]) .arg(path) .output() .ok()?; Some(String::from_utf8_lossy(&out.stdout).trim().to_string()).filter(|s| !s.is_empty()) } /// Encode 10-bit planes and return the bitstream. fn encode_stream_16( display: &Rc, codec: EncCodec, planes: &[I420_16], qp: u32, rate_control: RateControlMode, ) -> Result, ec_hw::Error> { let (width, height) = (planes[0].width, planes[0].height); let mut config = EncoderConfig::new(codec, width, height).ten_bit(); config.gop_size = 60; config.framerate = (24, 1); config.rate_control = match rate_control { RateControlMode::ConstantQp { .. } => RateControlMode::ConstantQp { qp }, other => other, }; let mut encoder = Encoder::new(display, config)?; let mut out = Vec::new(); for (t, frame) in planes.iter().enumerate() { let coded = encoder.encode_16( frame, FrameMetadata { timestamp: t as i64, force_keyframe: false, }, )?; out.extend_from_slice(&coded.data); } Ok(out) } #[test] fn hevc_main10_encode_round_trips() { let Some(display) = display() else { return }; let dir = std::env::temp_dir().join("ec-hw-hevc-10bit"); let _ = std::fs::create_dir_all(&dir); let (_, _, planes) = ten_bit_source(&dir, 10); let (width, height) = (planes[0].width, planes[0].height); let data = match encode_stream_16( &display, EncCodec::H265, &planes, 26, RateControlMode::ConstantQp { qp: 26 }, ) { Ok(data) => data, Err(e) => { eprintln!("skipped: 10-bit HEVC encode unavailable ({e})"); return; } }; let path = dir.join("hw-10bit.hevc"); std::fs::write(&path, &data).expect("write the coded stream"); assert_eq!( ffprobe_pix_fmt(&path, "hevc").as_deref(), Some("yuv420p10le") ); let mut reference = Reference::open(&path, width, height, true).expect("ffmpeg opens the stream"); let mut worst = f64::INFINITY; for (i, source) in planes.iter().enumerate() { let theirs = reference .next(width, height) .unwrap_or_else(|| panic!("ffmpeg has no frame {i}")); let db = psnr(&theirs, &Planes::from_16bit(source)); assert!(db > 30.0, "frame {i}: {db:.2} dB from the 10-bit source"); worst = worst.min(db); } println!( "HEVC Main10 encode {width}x{height}: {} bytes, worst frame {worst:.2} dB", data.len() ); } /// Rate control: does an asked-for bitrate come back? /// /// CQP was the only mode the AV1 path had ever measured, because the config /// was created without a `VAConfigAttribRateControl` at all — a driver /// configured for CQP ignores a bitrate handed to it later. With the attribute /// set, three targets are encoded in each of CBR and VBR on his own 1080p /// content and the delivered rate is compared with the ask; the table is /// printed either way, including the pixel format and the mode, so the row /// says what it exercised. #[test] fn av1_encode_rate_control_lands() { let Some(display) = display() else { return }; let (label, source) = real_clips().remove(0); let dir = std::env::temp_dir().join("ec-hw-av1-rc"); let _ = std::fs::create_dir_all(&dir); let (width, height, frames, fps) = (1920u32, 1080u32, 60u32, 30u32); let y4m = dir.join("rc-source.y4m"); assert!( extract_y4m(&source, &y4m, width, height, frames), "{label}: extraction failed" ); let planes = raw_frames(&y4m, width, height, frames).expect("frames of the trailer"); println!( "AV1 rate control on {label}, {width}x{height} yuv420p, {} frames at {fps} fps:", planes.len() ); // QVBR is quality-defined: `bitrate` is a ceiling it may not exceed, not // a target it must reach, so asking it to land on the number would be // asking for the wrong thing. enum Ask { Within(f64), Ceiling, } for (mode_name, mode, ask) in [ ("CBR", RateControlMode::ConstantBitrate, Ask::Within(0.15)), ("VBR", RateControlMode::VariableBitrate, Ask::Ceiling), ("QVBR", RateControlMode::Qvbr { quality: 100 }, Ask::Ceiling), ] { let mut table: Vec<(u32, f64, f64)> = Vec::new(); for target in [2_000_000u32, 6_000_000, 12_000_000] { let mut config = EncoderConfig::new(EncCodec::Av1, width, height); config.framerate = (fps, 1); config.gop_size = 60; config.bitrate = target; config.rate_control = mode; let mut encoder = match Encoder::new(&display, config) { Ok(encoder) => encoder, Err(e) => { // A mode the driver does not advertise refuses at config // creation; that is the driver's answer, printed as one. eprintln!(" {mode_name}: refused by the driver ({e})"); break; } }; let mut bytes = Vec::new(); for (i, frame) in planes.iter().enumerate() { match encoder.encode( frame, FrameMetadata { timestamp: i as i64, force_keyframe: false, }, ) { Ok(coded) => bytes.extend_from_slice(&coded.data), Err(e) => panic!("{mode_name} at {target} bps: encode failed ({e})"), } } let path = dir.join(format!("{mode_name}-{target}.obu")); std::fs::write(&path, &bytes).expect("write"); let delivered = bytes.len() as f64 * 8.0 * f64::from(fps) / f64::from(planes.len() as u32); let db = ffmpeg_psnr_at(&path, &y4m, fps).unwrap_or(f64::NAN); println!( " {mode_name} target {:>5} kbps -> delivered {:>6.0} kbps ({:+.1}%), {db:.2} dB", target / 1000, delivered / 1000.0, (delivered / f64::from(target) - 1.0) * 100.0 ); table.push((target, delivered, db)); } if table.len() < 3 { continue; } match ask { Ask::Within(tolerance) => { for &(target, delivered, _) in &table { let error = delivered / f64::from(target) - 1.0; assert!( error.abs() <= tolerance, "{mode_name} at {target} bps delivered {delivered:.0} bps ({:+.1}%), \ outside +/-{:.0}%", error * 100.0, tolerance * 100.0 ); } for pair in table.windows(2) { assert!( pair[1].2 > pair[0].2, "{mode_name}: PSNR is not monotone in the target ({:?} then {:?})", pair[0], pair[1] ); } } Ask::Ceiling => { for &(target, delivered, _) in &table { assert!( delivered <= f64::from(target) * (1.0 + f64::from(fps) / planes.len() as f64), "{mode_name} at a {target} bps ceiling delivered {delivered:.0} bps" ); } } } } } /// [`ffmpeg_psnr`] with the rate pinned to `fps` on both inputs. fn ffmpeg_psnr_at(coded: &Path, source: &Path, fps: u32) -> Option { let rate = fps.to_string(); let out = ec_testkit::ffmpeg() .args(["-nostdin", "-v", "info", "-f", "obu", "-r", &rate]) .arg("-i") .arg(coded) .args(["-r", &rate]) .arg("-i") .arg(source) .args(["-lavfi", "psnr", "-f", "null", "-"]) .output() .ok()?; let text = String::from_utf8_lossy(&out.stderr); let field = text.split("average:").nth(1)?; field .split_whitespace() .next()? .parse::() .ok() .filter(|v| v.is_finite()) } /// PSNR of a coded stream against the source, from ffmpeg's own filter. /// A 1920x1080 crop of `frames` pictures, as a y4m file the encoders share. fn extract_y4m(source: &Path, out: &Path, width: u32, height: u32, frames: u32) -> bool { let _ = std::fs::remove_file(out); ec_testkit::ffmpeg() .args(["-nostdin", "-v", "error", "-y", "-ss", "20", "-i"]) .arg(source) .args([ "-frames:v", &frames.to_string(), "-vf", &format!("scale={width}:{height}"), "-pix_fmt", "yuv420p", ]) .arg(out) .status() .is_ok_and(|s| s.success()) } /// The same pictures as planes, for the hardware encoder's own input. fn raw_frames(y4m: &Path, width: u32, height: u32, frames: u32) -> Option> { let out = ec_testkit::ffmpeg() .args(["-nostdin", "-v", "error", "-i"]) .arg(y4m) .args(["-pix_fmt", "yuv420p", "-f", "rawvideo", "-"]) .stderr(Stdio::null()) .output() .ok()?; let (w, h) = (width as usize, height as usize); let (cw, ch) = (w.div_ceil(2), h.div_ceil(2)); let frame_len = w * h + 2 * cw * ch; let mut pictures = Vec::new(); for chunk in out.stdout.chunks_exact(frame_len).take(frames as usize) { let (y, rest) = chunk.split_at(w * h); let (u, v) = rest.split_at(cw * ch); pictures.push(I420 { y: y.to_vec(), u: u.to_vec(), v: v.to_vec(), width, height, }); } (!pictures.is_empty()).then_some(pictures) } fn real_clips() -> Vec<(&'static str, PathBuf)> { vec![ ("sintel 1080p", ec_testkit::fixture("open/sintel_trailer-1080p.mp4")), ("sintel 720p", ec_testkit::fixture("open/sintel_trailer-720p.mp4")), ] }