use super::*; fn test_card(width: usize, height: usize, shift: usize) -> Picture { let mut picture = Picture::grey(width, height); for y in 0..height { for x in 0..width { let sx = (x + shift) % width; picture.y[y * width + x] = ((sx * 3 + y * 5) % 256) as u16; } } for y in 0..height / 2 { for x in 0..width / 2 { let i = y * (width / 2) + x; picture.u[i] = ((100 + shift * 4) % 256) as u16; picture.v[i] = ((200 + 256 - shift * 2 % 256) % 256) as u16; } } picture } fn encode_all(enc: &mut Av1Encoder, pictures: &[Picture]) -> Vec { let mut packets = Vec::with_capacity(pictures.len()); for (i, picture) in pictures.iter().enumerate() { packets.extend( enc.encode_frames(picture) .unwrap_or_else(|e| panic!("picture {i}: {e}")), ); } packets.extend(enc.flush().unwrap_or_else(|e| panic!("flush: {e}"))); packets } #[test] fn the_rate_loop_prices_the_frames_the_pyramid_codes() { let pictures: Vec = (0..48).map(|i| test_card(64, 64, i)).collect(); let quarters = Pyramid { quarter_q_offset: Some(-20), ..Pyramid::default() }; let two_level = Pyramid { mid_q_offset: None, ..Pyramid::default() }; for (gop, pyramid) in [ (48, Pyramid::default()), (12, Pyramid::default()), (48, quarters), (48, two_level), ] { let config = EncoderConfig { width: 64, height: 64, base_q_idx: 100, gop, colour: Colour::Bt709Limited, tile_cols_log2: 0, tile_rows_log2: 0, }; let rate = RateTarget::BytesPerFrame(2_000); let mut enc = Av1Encoder::with_pyramid_and_rate_target(config, pyramid, rate).unwrap(); let packets = encode_all(&mut enc, &pictures[..gop]); let coded = |level: Level| packets.iter().filter(|p| p.level == level).count(); let (hidden, leaves) = gop_shape(pyramid, gop); let hidden_frames: usize = hidden.iter().map(|&(_, n)| n).sum(); assert_eq!( (hidden_frames, leaves, 1), (coded(Level::Arf), coded(Level::Leaf), coded(Level::Key)), "gop {gop} {pyramid:?}: shape {hidden:?} + {leaves} leaves" ); assert_eq!( hidden_frames + leaves + 1, gop, "gop {gop}: every picture is coded exactly once" ); let target_bytes = 2_000.0; let loop_ = RateLoop::new(target_bytes, 100.0, Some(pyramid), gop); let planned = loop_.target[0] + loop_.target[2] * (leaves as f64 + hidden .iter() .map(|&(o, n)| n as f64 * loop_.weight(o)) .sum::()); assert!( (planned - target_bytes * gop as f64).abs() < 1.0, "gop {gop}: plan {planned:.0} bytes against a {:.0} byte run", target_bytes * gop as f64 ); } } #[test] fn a_bound_level_hands_its_unspent_bytes_to_the_others() { let pyramid = Pyramid::default(); let (gop, target_bytes) = (48usize, 2_000.0); let (hidden, leaves) = gop_shape(pyramid, gop); let run_bytes = target_bytes * gop as f64; let mut rl = RateLoop::new(target_bytes, 100.0, Some(pyramid), gop); let scale0 = rl.target[2]; let hidden_weight: f64 = hidden.iter().map(|&(o, n)| n as f64 * rl.weight(o)).sum(); let key_bytes = rl.target[0].round(); rl.update(Level::Key, 0, 100, key_bytes as usize); let (offset, n0) = hidden[0]; let arf_bytes = (0.5 * scale0 * rl.weight(offset)).round(); rl.update(Level::Arf, offset, 0, arf_bytes as usize); let want = (run_bytes - key_bytes - arf_bytes * n0 as f64) / (leaves as f64 + hidden_weight - n0 as f64 * rl.weight(offset)); assert!( want < scale0 * RateLoop::REPLAN_CLAMP, "this arm must not reach the windup bound: {want:.1} vs {:.1}", scale0 * RateLoop::REPLAN_CLAMP ); assert!( (rl.target[2] - want).abs() < 1e-6, "leaf target {:.3} is not the exact remainder {want:.3} (naive division would \ give {:.3})", rl.target[2], (run_bytes - key_bytes - arf_bytes) / (leaves as f64 + hidden_weight - rl.weight(offset)) ); let mut rl = RateLoop::new(target_bytes, 100.0, Some(pyramid), gop); rl.update(Level::Key, 0, 100, key_bytes as usize); for &(offset, n) in &hidden { for _ in 0..n { rl.update(Level::Arf, offset, 0, 1); } } assert!( rl.target[2] <= scale0 * RateLoop::REPLAN_CLAMP + 1e-9, "the re-plan is unbounded: leaf target {:.1} past {:.1}", rl.target[2], scale0 * RateLoop::REPLAN_CLAMP ); let mut rl = RateLoop::new(target_bytes, 100.0, Some(pyramid), gop); rl.update(Level::Key, 0, 100, key_bytes as usize); for &(offset, n) in &hidden { for _ in 0..n { rl.update(Level::Arf, offset, 0, 40 * key_bytes as usize); } } assert!( rl.target[2] >= scale0 * RateLoop::REPLAN_FLOOR - 1e-9, "the re-plan froze the loop: leaf target {:.1} under {:.1}", rl.target[2], scale0 * RateLoop::REPLAN_FLOOR ); } #[test] fn the_mini_gop_layout_leaves_no_short_tail() { let groups = |remaining: usize, mini_gop: usize, absorb: bool| { let (mut left, mut out) = (remaining, Vec::new()); while left > 0 { let g = group_target(left, mini_gop, absorb).min(left); assert!(g > 0); out.push(g); left -= g; } out }; assert_eq!(groups(47, 8, true), vec![8, 8, 8, 8, 8, 7]); assert_eq!(groups(47, 8, false), vec![8, 8, 8, 8, 8, 7]); assert_eq!(groups(11, 8, false), vec![8, 3]); assert_eq!(groups(11, 8, true), vec![11]); assert_eq!(groups(3, 8, true), vec![3]); for mini_gop in 2..=16 { for remaining in 1..=64 { for g in groups(remaining, mini_gop, true) { assert!(g * 2 <= 3 * mini_gop, "{remaining}/{mini_gop}: long {g}"); assert!( g * 2 >= mini_gop || remaining < mini_gop, "{remaining}/{mini_gop}: short tail {g}" ); } } } } fn concat(packets: &[Packet]) -> Vec { packets.iter().flat_map(|p| p.data.clone()).collect() } #[test] fn one_in_one_out_delayed_by_the_lookahead_depth() { let config = EncoderConfig { width: 64, height: 64, base_q_idx: 100, gop: 2, colour: Colour::Bt709Limited, tile_cols_log2: 0, tile_rows_log2: 0, }; let delay = crate::encode::tpl_depth() as u64 - 1; let pictures = delay + 5; let mut enc = Av1Encoder::new(config).unwrap(); for t in 0..pictures { let packet = enc.encode(&test_card(64, 64, t as usize)).unwrap(); if t < delay { assert!(packet.is_none(), "call {t} holds its picture back"); continue; } let packet = packet.expect("a packet once the queue is full"); assert!(!packet.data.is_empty(), "picture {t}: empty packet"); assert_eq!(packet.order, t - delay, "picture {t}: order"); } let tail = enc.flush().unwrap(); assert_eq!(tail.len() as u64, delay, "flush yields the whole queue"); for (i, p) in tail.iter().enumerate() { assert_eq!( p.order, pictures - delay + i as u64, "flushed packet {i}: order" ); assert!(!p.data.is_empty(), "flushed packet {i}: empty"); } assert!(enc.flush().unwrap().is_empty(), "nothing is held twice"); } fn screen_card(width: usize, height: usize, shift: usize) -> Picture { let mut picture = Picture::grey(width, height); for y in 0..height { for x in 0..width { let band = if (x / 4).is_multiple_of(2) { 40 } else { 200 }; let over = y >= height / 2 && (x + shift) % width < width / 3; picture.y[y * width + x] = if over { 128 } else { band }; } } picture } #[test] fn the_facade_codes_the_same_bytes_as_encode_sequence() { let frames = 12usize; let film = h264_clip_frames(640, 384, frames).unwrap_or_else(|| { eprintln!(" ...so the film arm runs on a synthetic card, not real film"); (0..frames).map(|t| test_card(64, 64, t)).collect() }); let screen: Vec = (0..frames).map(|t| screen_card(64, 64, t)).collect(); let pyramid = Pyramid::default(); for (content, pictures, is_screen) in [("film", &film, false), ("screen", &screen, true)] { let (width, height) = (pictures[0].width, pictures[0].height); for q in [150u8, 60] { let config = EncoderConfig { width, height, base_q_idx: q, gop: frames, colour: Colour::Unspecified, tile_cols_log2: 0, tile_rows_log2: 0, }; let mut enc = Av1Encoder::with_pyramid(config, pyramid).unwrap(); let mut packets = Vec::new(); for picture in pictures { packets.extend(enc.encode_frames(picture).unwrap()); } packets.extend(enc.flush().unwrap()); assert_eq!( enc.pyramid().is_none(), is_screen, "{content} q={q}: the content gate read this clip the other way round" ); let sequence = crate::encode::encode_sequence(pictures, q, DEADZONE).unwrap(); assert_eq!( ( packets.iter().map(|p| p.data.len()).sum::(), concat(&packets) ), (sequence.stream.len(), sequence.stream.clone()), "{content} q={q}: the facade's stream is not the sequence path's" ); assert_eq!( sequence.frames.len(), frames, "{content} q={q}: one entry per picture, in display order" ); if is_screen { assert_eq!( packets.len(), frames, "{content} q={q}: one packet per picture" ); for (i, (packet, coded)) in packets.iter().zip(&sequence.frames).enumerate() { let cropped = crate::encode::crop_encoded(coded, width, height); assert_eq!( (packet.data.len(), packet.data.clone()), (cropped.stream.len(), cropped.stream.clone()), "{content} q={q} frame {i}: the facade's bytes are not the \ sequence path's" ); } } else { assert!( packets.iter().any(|p| p.level == Level::Arf), "{content} q={q}: a non-screen stream coded no hidden frame" ); } } } } #[test] fn gop_cadence_is_honored() { let config = EncoderConfig { width: 64, height: 64, base_q_idx: 100, gop: 3, colour: Colour::Unspecified, tile_cols_log2: 0, tile_rows_log2: 0, }; let mut enc = Av1Encoder::new(config).unwrap(); let pictures: Vec = (0..7).map(|t| test_card(64, 64, t)).collect(); let keys: Vec = encode_all(&mut enc, &pictures) .iter() .map(|p| p.key) .collect(); assert_eq!(keys, vec![true, false, false, true, false, false, true]); } fn ffprobe_frames(stream: &[u8]) -> Vec<(bool, u32, u32)> { let path = std::env::temp_dir().join(format!( "ec-av1-facade-probe-{}-{}.obu", std::process::id(), std::ptr::addr_of!(stream) as usize )); std::fs::write(&path, stream).expect("writing the probe stream"); let out = ec_testkit::ffprobe() .args([ "-v", "error", "-f", "obu", "-select_streams", "v:0", "-show_entries", "frame=key_frame,width,height", "-of", "csv=p=0", ]) .arg(&path) .output() .expect("ffprobe failed to run"); let _ = std::fs::remove_file(&path); assert!( out.status.success(), "ffprobe refused the stream: {}", String::from_utf8_lossy(&out.stderr) ); String::from_utf8_lossy(&out.stdout) .lines() .map(|line| { let mut f = line.trim().split(','); let key: u32 = f.next().unwrap().parse().unwrap(); let width: u32 = f.next().unwrap().parse().unwrap(); let height: u32 = f.next().unwrap().parse().unwrap(); (key == 1, width, height) }) .collect() } fn ffprobe_colour(stream: &[u8]) -> String { let path = std::env::temp_dir().join(format!( "ec-av1-facade-colour-probe-{}-{}.obu", std::process::id(), std::ptr::addr_of!(stream) as usize )); std::fs::write(&path, stream).expect("writing the probe stream"); let out = ec_testkit::ffprobe() .args([ "-v", "error", "-f", "obu", "-select_streams", "v:0", "-show_entries", "stream=color_primaries,color_transfer,color_space,color_range", "-of", "csv=p=0", ]) .arg(&path) .output() .expect("ffprobe failed to run"); let _ = std::fs::remove_file(&path); assert!( out.status.success(), "ffprobe refused the stream: {}", String::from_utf8_lossy(&out.stderr) ); String::from_utf8_lossy(&out.stdout).trim().to_string() } #[test] fn thirty_pictures_at_gop_fifteen_decode_to_two_key_frames() { let (width, height) = (96usize, 96usize); let config = EncoderConfig { width, height, base_q_idx: 120, gop: 15, colour: Colour::Bt709Limited, tile_cols_log2: 0, tile_rows_log2: 0, }; let mut enc = Av1Encoder::new(config).unwrap(); assert_eq!(enc.display_size(), (width, height)); let (coded_w, coded_h) = enc.coded_size(); assert_eq!( (coded_w, coded_h), ( width.next_multiple_of(SUPERBLOCK), height.next_multiple_of(SUPERBLOCK) ) ); let pictures: Vec = (0..30).map(|t| test_card(width, height, t)).collect(); let packets: Vec = encode_all(&mut enc, &pictures); let expect_key: Vec = (0..30).map(|t| t % 15 == 0).collect(); assert_eq!( packets.iter().map(|p| p.key).collect::>(), expect_key, "facade's own key/inter flags" ); let stream = concat(&packets); let frames = ffprobe_frames(&stream); assert_eq!(frames.len(), 30, "ffprobe frame count"); for (t, (key, w, h)) in frames.iter().enumerate() { assert_eq!(*key, expect_key[t], "picture {t}: ffprobe key_frame flag"); assert_eq!( (*w, *h), (width as u32, height as u32), "picture {t}: ffprobe reports the true (display) size, not the padded coded one" ); } } #[test] fn bt709_limited_colour_is_reported_by_ffprobe() { let config = EncoderConfig { width: 64, height: 64, base_q_idx: 100, gop: 4, colour: Colour::Bt709Limited, tile_cols_log2: 0, tile_rows_log2: 0, }; let mut enc = Av1Encoder::new(config).unwrap(); let packets = encode_all(&mut enc, &[test_card(64, 64, 0)]); let colour = ffprobe_colour(&packets[0].data); assert_eq!(colour, "tv,bt709,bt709,bt709", "ffprobe colour fields"); } #[test] fn bt601_limited_colour_is_reported_by_ffprobe() { let config = EncoderConfig { width: 64, height: 64, base_q_idx: 100, gop: 4, colour: Colour::Bt601Limited, tile_cols_log2: 0, tile_rows_log2: 0, }; let mut enc = Av1Encoder::new(config).unwrap(); let packets = encode_all(&mut enc, &[test_card(64, 64, 0)]); let colour = ffprobe_colour(&packets[0].data); assert_eq!( colour, "tv,smpte170m,smpte170m,smpte170m", "ffprobe colour fields" ); } #[test] fn geometry_mismatch_is_refused() { let config = EncoderConfig { width: 64, height: 64, base_q_idx: 100, gop: 4, colour: Colour::Bt709Limited, tile_cols_log2: 0, tile_rows_log2: 0, }; let mut enc = Av1Encoder::new(config).unwrap(); let err = enc.encode(&Picture::grey(32, 32)).unwrap_err(); assert!(err.to_string().contains("64x64"), "{err}"); } #[test] fn zero_gop_is_refused() { let config = EncoderConfig { width: 64, height: 64, base_q_idx: 100, gop: 0, colour: Colour::Bt709Limited, tile_cols_log2: 0, tile_rows_log2: 0, }; let err = Av1Encoder::new(config).unwrap_err(); assert!(err.to_string().contains("gop"), "{err}"); } fn h264_clip_frames(width: usize, height: usize, frames: usize) -> Option> { h264_clip_frames_at(20, width, height, frames) } fn h264_clip_frames_at( start: u32, width: usize, height: usize, frames: usize, ) -> Option> { let clip = ec_testkit::fixture("open/sintel_trailer-1080p.mp4"); let out = ec_testkit::ffmpeg() .args([ "-v", "error", "-ss", &start.to_string(), "-i", clip.to_str().unwrap(), ]) .args(["-frames:v", &frames.to_string()]) .args(["-vf", &format!("scale={width}:{height}")]) .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"]) .output() .expect("ffmpeg failed to run"); assert!( out.status.success(), "{}", String::from_utf8_lossy(&out.stderr) ); let (luma, chroma) = (width * height, width * height / 4); let frame_len = luma + 2 * chroma; assert_eq!( out.stdout.len(), frame_len * frames, "expected {frames} 4:2:0 frames" ); Some( (0..frames) .map(|i| { let bytes = &out.stdout[i * frame_len..][..frame_len]; Picture { width, height, y: bytes[..luma].iter().map(|&v| u16::from(v)).collect(), u: bytes[luma..luma + chroma] .iter() .map(|&v| u16::from(v)) .collect(), v: bytes[luma + chroma..] .iter() .map(|&v| u16::from(v)) .collect(), } }) .collect(), ) } #[test] fn bytes_per_frame_target_settles_within_20_percent() { let Some(pictures) = h264_clip_frames(640, 384, 24) else { return; }; let target_bytes = 4_000u32; let config = EncoderConfig { width: 640, height: 384, base_q_idx: 100, gop: 24, colour: Colour::Bt709Limited, tile_cols_log2: 0, tile_rows_log2: 0, }; let mut enc = Av1Encoder::with_rate_target(config, RateTarget::BytesPerFrame(target_bytes)).unwrap(); let sizes: Vec = encode_all(&mut enc, &pictures) .iter() .map(|p| p.data.len()) .collect(); let settled = &sizes[5..]; let mean = settled.iter().sum::() as f64 / settled.len() as f64; let low = f64::from(target_bytes) * 0.8; let high = f64::from(target_bytes) * 1.2; assert!( mean >= low && mean <= high, "settled mean {mean:.0} bytes/frame outside ±20% of {target_bytes} ({low:.0}..{high:.0}); sizes={sizes:?}" ); } struct ArmResult { targets: [f64; 3], coded: usize, bytes: [usize; 4], count: [usize; 4], } impl ArmResult { fn take(&mut self, packets: Vec) { for packet in packets { self.coded += packet.data.len(); let i = match packet.level { Level::Key => 0, Level::Arf => 1, Level::Leaf => 2, Level::ShowExisting => 3, }; self.bytes[i] += packet.data.len(); self.count[i] += 1; } } } #[test] fn the_pyramid_constructors_fit_on_a_tight_stack() { const STACK: usize = 1024 * 1024; let stack: usize = STACK; let config = EncoderConfig { width: 640, height: 384, base_q_idx: 100, gop: 48, colour: Colour::Bt709Limited, tile_cols_log2: 0, tile_rows_log2: 0, }; let rate = RateTarget::Bitrate { bits_per_second: 1_536_000, frames_per_second: 24.0, }; let handle = std::thread::Builder::new() .stack_size(stack) .spawn(move || { let flat = Av1Encoder::with_rate_target(config, rate) .expect("with_rate_target") .rate_loop .is_some(); let pyr = Av1Encoder::with_pyramid_and_rate_target(config, Pyramid::default(), rate) .expect("with_pyramid_and_rate_target") .pyramid .is_some(); (flat, pyr) }) .expect("spawn tight-stack thread"); let (flat, pyr) = handle .join() .unwrap_or_else(|_| panic!("the encoder constructors overflowed a {stack}-byte stack")); assert!(flat, "with_rate_target lost its rate loop"); assert!(pyr, "with_pyramid_and_rate_target lost its pyramid"); eprintln!( "TIGHTSTACK {stack} bytes: Av1Encoder={} bytes, both constructors returned", std::mem::size_of::() ); } const CLEAN_START: u32 = 23; #[test] fn bitrate_target_lands_within_5_percent_over_48_frames() { let (width, height, frames) = (640usize, 384usize, 48usize); let Some(pictures) = h264_clip_frames_at(CLEAN_START, width, height, frames) else { return; }; let fps = 24.0; let pictures = std::sync::Arc::new(pictures); for bits_per_second in [384_000u32, 768_000, 1_536_000, 2_000_000] { let config = EncoderConfig { width, height, base_q_idx: 100, gop: frames, colour: Colour::Bt709Limited, tile_cols_log2: 0, tile_rows_log2: 0, }; let rate = RateTarget::Bitrate { bits_per_second, frames_per_second: fps, }; for pyramid in [None, Some(Pyramid::default())] { let arm = format!("{bits_per_second} bps pyramid {}", pyramid.is_some()); let pictures = std::sync::Arc::clone(&pictures); let (tx, rx) = std::sync::mpsc::channel::>(); let worker = std::thread::spawn(move || { let mut enc = match pyramid { None => Av1Encoder::with_rate_target(config, rate).unwrap(), Some(p) => Av1Encoder::with_pyramid_and_rate_target(config, p, rate).unwrap(), }; let targets = enc.rate_loop.as_ref().unwrap().target; let mut out = ArmResult { targets, coded: 0, bytes: [0; 4], count: [0; 4], }; for picture in pictures.iter() { out.take(enc.encode_frames(picture).unwrap()); if tx.send(None).is_err() { return; } } out.take(enc.flush().unwrap()); let _ = tx.send(Some(out)); }); let out = loop { match rx.recv() { Ok(Some(out)) => break out, Ok(None) => {} Err(_) => { worker.join().expect("encode worker panicked"); panic!("AV1 encode worker for {arm} died without a result"); } } }; let ArmResult { targets, coded, bytes, count, } = out; let seconds = frames as f64 / fps; let achieved = coded as f64 * 8.0 / seconds; let error = achieved / f64::from(bits_per_second) - 1.0; let per = |i: usize| match count[i] { 0 => "-".to_string(), n => format!("{n}x{}", bytes[i] / n), }; eprintln!( "bitrate {bits_per_second} bps, pyramid {}: {coded} bytes over {seconds:.2}s \ = {achieved:.0} bps ({:+.1}%) | targets {:.0}/{:.0}/{:.0} \ coded key {} arf {} leaf {}", pyramid.is_some(), 100.0 * error, targets[0], targets[1], targets[2], per(0), per(1), per(2), ); assert!( error.abs() <= 0.05, "achieved {achieved:.0} bps is {:+.1}% off the {bits_per_second} bps target \ (pyramid {})", 100.0 * error, pyramid.is_some(), ); } } } #[test] fn bytes_per_frame_controller_never_oscillates_past_its_clamp() { let Some(pictures) = h264_clip_frames(640, 384, 24) else { return; }; let config = EncoderConfig { width: 640, height: 384, base_q_idx: 100, gop: 24, colour: Colour::Bt709Limited, tile_cols_log2: 0, tile_rows_log2: 0, }; let mut enc = Av1Encoder::with_rate_target(config, RateTarget::BytesPerFrame(4_000)).unwrap(); let mut prev_q = enc.rate_loop.as_ref().unwrap().q_idx(Level::Leaf); let mut seeded = false; let mut seed_frame = None; for (frame, picture) in pictures.iter().enumerate() { enc.encode_frames(picture).unwrap(); let q = enc.rate_loop.as_ref().unwrap().q_idx(Level::Leaf); let step = (i32::from(q) - i32::from(prev_q)).abs(); if step > 0 && !seeded { seeded = true; seed_frame = Some(frame); } else { assert!( f64::from(step) <= RateLoop::STEP_CLAMP + 1.0, "frame {frame}: q stepped from {prev_q} to {q}, past the {} clamp", RateLoop::STEP_CLAMP ); } prev_q = q; } assert!( seed_frame.is_some(), "the controller never steered at all -- the bound below is vacuous" ); } fn psnr(a: &[u16], b: &[u16]) -> f64 { let squared: f64 = a .iter() .zip(b) .map(|(&x, &y)| { let d = f64::from(x) - f64::from(y); d * d }) .sum(); if squared == 0.0 { return f64::INFINITY; } 10.0 * (255.0 * 255.0 * a.len() as f64 / squared).log10() } fn ffmpeg_decode_planes( stream: &[u8], width: usize, height: usize, ) -> Vec<(Vec, Vec, Vec)> { let path = std::env::temp_dir().join(format!( "ec-av1-facade-rate-decode-{}-{}.obu", std::process::id(), std::ptr::addr_of!(stream) as usize )); std::fs::write(&path, stream).expect("writing the decode probe stream"); let out = ec_testkit::ffmpeg() .args(["-v", "error", "-f", "obu", "-i"]) .arg(&path) .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"]) .output() .expect("ffmpeg failed to run"); let _ = std::fs::remove_file(&path); assert!( out.status.success(), "{}", String::from_utf8_lossy(&out.stderr) ); let (luma, chroma) = (width * height, width * height / 4); let frame_len = luma + 2 * chroma; out.stdout .chunks_exact(frame_len) .map(|f| { ( f[..luma].to_vec(), f[luma..luma + chroma].to_vec(), f[luma + chroma..].to_vec(), ) }) .collect() } fn ffmpeg_decode_luma(stream: &[u8], width: usize, height: usize) -> Vec> { ffmpeg_decode_planes(stream, width, height) .into_iter() .map(|(y, _, _)| y) .collect() } #[test] fn a_palette_block_cut_by_the_frame_edge_decodes_exactly_through_ffmpeg() { const NAME: &str = "a_palette_block_cut_by_the_frame_edge_decodes_exactly_through_ffmpeg"; let (width, height) = (384usize, 152usize); let card = |shift: usize| -> Picture { let mut picture = Picture::grey(width, height); for y in 0..height { for x in 0..width { let cell = ((x + shift) / 8 + y / 8) % 2; picture.y[y * width + x] = if cell == 0 { 40 } else { 200 }; } } picture }; let sources: Vec = (0..2).map(|t| card(t * 16)).collect(); let config = EncoderConfig { width, height, base_q_idx: 60, gop: 2, colour: Colour::Bt709Limited, tile_cols_log2: 0, tile_rows_log2: 0, }; let mut enc = Av1Encoder::new(config).unwrap(); crate::tile::reset_palette_cut_maps_written(); let mut stream = Vec::new(); for packet in encode_all(&mut enc, &sources) { stream.extend_from_slice(&packet.data); } eprintln!( "{NAME}: {} cut colour-index maps written", crate::tile::palette_cut_maps_written() ); assert!( crate::tile::palette_cut_maps_written() > 0, "{NAME}: no palette block is cut by the frame edge here -- the gate would pass blind" ); let ours = crate::stream::decode_stream(&stream).expect("our decoder"); assert_eq!(ours.len(), sources.len(), "{NAME}: our decoder's frames"); let theirs = ffmpeg_decode_planes(&stream, width, height); assert_eq!(theirs.len(), sources.len(), "{NAME}: ffmpeg's frames"); for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() { for (plane, got, want) in [("luma", &a.y, &b.0), ("U", &a.u, &b.1), ("V", &a.v, &b.2)] { let got: Vec = got.iter().map(|&v| v as u8).collect(); if let Some(at) = got.iter().zip(want).position(|(x, y)| x != y) { let w = if plane == "luma" { width } else { width / 2 }; panic!( "{NAME}: frame {i} {plane} differs first at ({}, {}): ours {} vs ffmpeg {}", at % w, at / w, got[at], want[at], ); } assert_eq!( got.len(), want.len(), "{NAME}: frame {i} {plane} is {} samples, ffmpeg's is {}", got.len(), want.len() ); } } } #[test] fn a_pyramid_stream_decodes_in_display_order_through_both_decoders() { pyramid_round_trip( Pyramid { mini_gop: 4, mid_q_offset: None, ..Pyramid::default() }, 2, ); } #[test] fn a_three_level_pyramid_stream_decodes_in_display_order() { pyramid_round_trip( Pyramid { mini_gop: 8, mid_q_offset: Some(-8), ..Pyramid::default() }, 2, ); } #[test] fn a_four_level_pyramid_stream_decodes_in_display_order() { pyramid_round_trip( Pyramid { mini_gop: 8, mid_q_offset: Some(-8), quarter_q_offset: Some(4), ..Pyramid::default() }, 4, ); } #[test] fn the_key_q_offset_reaches_the_key_frame() { let key_bytes = |offset: i16| { let config = EncoderConfig { width: 128, height: 128, base_q_idx: 120, gop: 32, colour: Colour::Bt709Limited, tile_cols_log2: 0, tile_rows_log2: 0, }; let pyramid = Pyramid { key_q_offset: offset, ..Pyramid::default() }; let mut enc = Av1Encoder::with_pyramid(config, pyramid).unwrap(); let packets = enc.encode_frames(&test_card(128, 128, 0)).unwrap(); let key = packets .iter() .find(|p| p.level == Level::Key) .expect("key frame"); key.data.len() }; let (base, finer) = (key_bytes(0), key_bytes(-48)); eprintln!("key at base q {base} bytes, at base q - 48 {finer} bytes"); assert!( finer > base, "key_q_offset -48 did not reach the key frame ({finer} <= {base})" ); } fn pyramid_round_trip(pyramid: Pyramid, hidden: usize) { let (width, height) = (128usize, 128usize); let config = EncoderConfig { width, height, base_q_idx: 120, gop: 32, colour: Colour::Bt709Limited, tile_cols_log2: 0, tile_rows_log2: 0, }; let mut enc = Av1Encoder::with_pyramid(config, pyramid).unwrap(); let sources: Vec = (0..9).map(|t| test_card(width, height, t * 3)).collect(); let _ = crate::encode::take_ref_frame_hits(); let mut packets = Vec::new(); for picture in &sources { packets.extend(enc.encode_frames(picture).unwrap()); } packets.extend(enc.flush().unwrap()); let coded: Vec = packets .iter() .filter(|p| p.level != Level::ShowExisting) .map(|p| p.order) .collect(); let mut sorted = coded.clone(); sorted.sort_unstable(); assert_eq!( sorted, (0..9).collect::>(), "one packet per picture" ); assert_ne!(coded, sorted, "the pyramid never reordered anything"); let shown = packets .iter() .filter(|p| p.level == Level::ShowExisting) .count(); assert_eq!(shown, hidden, "one show_existing_frame per hidden frame"); for (i, p) in packets.iter().enumerate() { assert_eq!(p.dts, i as u64, "packet {i}: dts is the coding position"); } let hist = |l: Level| packets.iter().filter(|p| p.level == l).count(); eprintln!( "pyramid levels: key {} arf {} leaf {} show_existing {}", hist(Level::Key), hist(Level::Arf), hist(Level::Leaf), hist(Level::ShowExisting), ); assert_eq!(hist(Level::Arf), hidden, "hidden frames"); let refs = crate::encode::take_ref_frame_hits(); eprintln!( "blocks per reference: LAST {} GOLDEN {} ALTREF {}", refs[crate::mvstack::LAST_FRAME as usize], refs[crate::mvstack::GOLDEN_FRAME as usize], refs[crate::mvstack::ALTREF_FRAME as usize], ); assert!( refs[crate::mvstack::ALTREF_FRAME as usize] > 0, "no block predicted off the hidden ALTREF" ); let stream = concat(&packets); let ours = crate::stream::decode_stream(&stream).expect("our decoder"); assert_eq!( ours.len(), sources.len(), "our decoder's display-order count" ); let theirs = ffmpeg_decode_luma(&stream, width, height); assert_eq!(theirs.len(), sources.len(), "ffmpeg's display-order count"); for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() { let got: Vec = a.y.iter().map(|&v| v as u8).collect(); assert_eq!(got.len(), b.len(), "frame {i}: luma size"); if let Some(at) = got.iter().zip(b).position(|(x, y)| x != y) { panic!( "display frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}", at % width, at / width, got[at], b[at], ); } } } #[test] fn a_static_clip_codes_64x64_roots_and_decodes_sample_exact() { let (width, height) = (256usize, 128usize); let still = test_card(width, height, 0); let sources: Vec = (0..3).map(|_| still.clone()).collect(); let config = EncoderConfig { width, height, base_q_idx: 120, gop: 8, colour: Colour::Bt709Limited, tile_cols_log2: 0, tile_rows_log2: 0, }; let mut enc = Av1Encoder::new(config).unwrap(); let mut stream = Vec::new(); let _ = crate::encode::take_b64_root_hits(); for packet in encode_all(&mut enc, &sources) { stream.extend_from_slice(&packet.data); } let roots = crate::encode::take_b64_root_hits(); assert!( roots > 0, "a static clip coded no 64x64 root at all (of 16 inter superblocks)" ); eprintln!("64x64 roots on a static clip: {roots} of 16 inter superblocks"); let ours = crate::stream::decode_stream(&stream).expect("our decoder"); assert_eq!(ours.len(), sources.len(), "our decoder's frames"); let theirs = ffmpeg_decode_luma(&stream, width, height); assert_eq!(theirs.len(), sources.len(), "ffmpeg's frames"); for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() { let got: Vec = a.y.iter().map(|&v| v as u8).collect(); if let Some(at) = got.iter().zip(b).position(|(x, y)| x != y) { panic!( "frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}", at % width, at / width, got[at], b[at], ); } assert_eq!( got.len(), b.len(), "frame {i}: luma is {} samples, ffmpeg's is {}", got.len(), b.len() ); } } #[test] fn a_dc_stepped_clip_codes_a_64x64_residual_and_decodes_sample_exact() { let (width, height) = (256usize, 128usize); let still = test_card(width, height, 0); let sources: Vec = (0..3) .map(|t| { let mut p = still.clone(); let step = (t * 6) as u16; for v in &mut p.y { *v = (*v + step).min(255); } p }) .collect(); let config = EncoderConfig { width, height, base_q_idx: 120, gop: 8, colour: Colour::Bt709Limited, tile_cols_log2: 0, tile_rows_log2: 0, }; let mut enc = Av1Encoder::new(config).unwrap(); let mut stream = Vec::new(); let _ = crate::encode::take_b64_residual_hits(); for packet in encode_all(&mut enc, &sources) { stream.extend_from_slice(&packet.data); } let residuals = crate::encode::take_b64_residual_hits(); assert!( residuals > 0, "a DC-stepped clip coded no 64x64 root with a residual at all" ); eprintln!("64x64 roots with a residual: {residuals} of 16 inter superblocks"); let ours = crate::stream::decode_stream(&stream).expect("our decoder"); assert_eq!(ours.len(), sources.len(), "our decoder's frames"); let theirs = ffmpeg_decode_luma(&stream, width, height); assert_eq!(theirs.len(), sources.len(), "ffmpeg's frames"); for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() { let got: Vec = a.y.iter().map(|&v| v as u8).collect(); if let Some(at) = got.iter().zip(b).position(|(x, y)| x != y) { panic!( "frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}", at % width, at / width, got[at], b[at], ); } assert_eq!( got.len(), b.len(), "frame {i}: luma is {} samples, ffmpeg's is {}", got.len(), b.len() ); } } #[test] fn a_non_superblock_aligned_clip_codes_edge_64x64_roots_and_decodes_sample_exact() { let (width, height) = (232usize, 168usize); let still = test_card(width, height, 0); let sources: Vec = (0..3).map(|_| still.clone()).collect(); let config = EncoderConfig { width, height, base_q_idx: 120, gop: 8, colour: Colour::Bt709Limited, tile_cols_log2: 0, tile_rows_log2: 0, }; let mut enc = Av1Encoder::new(config).unwrap(); let mut stream = Vec::new(); let _ = crate::encode::take_b64_edge_hits(); for packet in encode_all(&mut enc, &sources) { stream.extend_from_slice(&packet.data); } let edges = crate::encode::take_b64_edge_hits(); assert!( edges > 0, "no 64x64 root was taken at a superblock the frame edge cuts" ); eprintln!("edge 64x64 roots: {edges}"); let ours = crate::stream::decode_stream(&stream).expect("our decoder"); assert_eq!(ours.len(), sources.len(), "our decoder's frames"); let theirs = ffmpeg_decode_luma(&stream, width, height); assert_eq!(theirs.len(), sources.len(), "ffmpeg's frames"); for (i, (ours_i, theirs_i)) in ours.iter().zip(&theirs).enumerate() { let got: Vec = ours_i.y.iter().map(|&v| v as u8).collect(); if let Some(at) = got.iter().zip(theirs_i).position(|(x, y)| x != y) { panic!( "frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}", at % width, at / width, got[at], theirs_i[at], ); } assert_eq!( got.len(), theirs_i.len(), "frame {i}: luma is {} samples, ffmpeg's is {}", got.len(), theirs_i.len() ); } } #[test] fn a_1080p_shaped_clip_straddles_at_every_block_size_and_decodes_sample_exact() { let (width, height) = (384usize, 216usize); let sources: Vec = (0..3).map(|i| test_card(width, height, i)).collect(); let config = EncoderConfig { width, height, base_q_idx: 120, gop: 8, colour: Colour::Bt709Limited, tile_cols_log2: 0, tile_rows_log2: 0, }; let mut enc = Av1Encoder::new(config).unwrap(); let mut stream = Vec::new(); for packet in encode_all(&mut enc, &sources) { stream.extend_from_slice(&packet.data); } let ours = crate::stream::decode_stream(&stream).expect("our decoder"); assert_eq!(ours.len(), sources.len(), "our decoder's frames"); let theirs = ffmpeg_decode_luma(&stream, width, height); assert_eq!(theirs.len(), sources.len(), "ffmpeg's frames"); for (i, (ours_i, theirs_i)) in ours.iter().zip(&theirs).enumerate() { let got: Vec = ours_i.y.iter().map(|&v| v as u8).collect(); if let Some(at) = got.iter().zip(theirs_i).position(|(x, y)| x != y) { panic!( "frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}", at % width, at / width, got[at], theirs_i[at], ); } assert_eq!( got.len(), theirs_i.len(), "frame {i}: luma is {} samples, ffmpeg's is {}", got.len(), theirs_i.len() ); } } #[test] fn a_high_frequency_clip_splits_the_64x64_roots_luma_and_decodes_sample_exact() { let (width, height) = (256usize, 128usize); let still = test_card(width, height, 0); let sources: Vec = (0..4) .map(|t| { let mut p = still.clone(); for (i, v) in p.y.iter_mut().enumerate() { let checker = ((i % width) / 4 + (i / width) / 4) % 2; let bump = (t * 5 * (checker + 1)) as u16; *v = (*v + bump).min(255); } p }) .collect(); let config = EncoderConfig { width, height, base_q_idx: 90, gop: 8, colour: Colour::Bt709Limited, tile_cols_log2: 0, tile_rows_log2: 0, }; let mut enc = Av1Encoder::new(config).unwrap(); let mut stream = Vec::new(); let _ = crate::encode::take_b64_var_tx_hits(); for packet in encode_all(&mut enc, &sources) { stream.extend_from_slice(&packet.data); } let split = crate::encode::take_b64_var_tx_hits(); assert!(split > 0, "no 64x64 root split its luma transform at all"); eprintln!("64x64 roots with a SPLIT luma transform: {split}"); let ours = crate::stream::decode_stream(&stream).expect("our decoder"); assert_eq!(ours.len(), sources.len(), "our decoder's frames"); let theirs = ffmpeg_decode_luma(&stream, width, height); assert_eq!(theirs.len(), sources.len(), "ffmpeg's frames"); for (i, (ours_i, theirs_i)) in ours.iter().zip(&theirs).enumerate() { let got: Vec = ours_i.y.iter().map(|&v| v as u8).collect(); if let Some(at) = got.iter().zip(theirs_i).position(|(x, y)| x != y) { panic!( "frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}", at % width, at / width, got[at], theirs_i[at], ); } assert_eq!( got.len(), theirs_i.len(), "frame {i}: luma is {} samples, ffmpeg's is {}", got.len(), theirs_i.len() ); } } #[test] fn a_crossfade_clip_codes_a_compound_64x64_root_and_decodes_sample_exact() { let (width, height) = (256usize, 128usize); let (a, b) = (test_card(width, height, 0), test_card(width, height, 24)); let sources: Vec = (0..9) .map(|t| { let mut p = a.clone(); let w = t as u32; for (v, &other) in p.y.iter_mut().zip(&b.y) { *v = ((u32::from(*v) * (8 - w) + u32::from(other) * w) / 8) as u16; } p }) .collect(); let config = EncoderConfig { width, height, base_q_idx: 120, gop: 9, colour: Colour::Bt709Limited, tile_cols_log2: 0, tile_rows_log2: 0, }; let mut enc = Av1Encoder::new(config).unwrap(); let mut stream = Vec::new(); let _ = crate::encode::take_b64_compound_hits(); for packet in encode_all(&mut enc, &sources) { stream.extend_from_slice(&packet.data); } let compound = crate::encode::take_b64_compound_hits(); assert!( compound > 0, "a crossfade clip coded no COMPOUND 64x64 root at all" ); eprintln!("compound 64x64 roots on a crossfade clip: {compound}"); let ours = crate::stream::decode_stream(&stream).expect("our decoder"); assert_eq!(ours.len(), sources.len(), "our decoder's frames"); let theirs = ffmpeg_decode_luma(&stream, width, height); assert_eq!(theirs.len(), sources.len(), "ffmpeg's frames"); for (i, (ours_i, theirs_i)) in ours.iter().zip(&theirs).enumerate() { let got: Vec = ours_i.y.iter().map(|&v| v as u8).collect(); if let Some(at) = got.iter().zip(theirs_i).position(|(x, y)| x != y) { panic!( "frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}", at % width, at / width, got[at], theirs_i[at], ); } assert_eq!( got.len(), theirs_i.len(), "frame {i}: luma is {} samples, ffmpeg's is {}", got.len(), theirs_i.len() ); } } #[test] fn every_tile_layout_decodes_sample_exact_through_both_decoders() { let (width, height) = (640usize, 384usize); let sources: Vec = (0..4).map(|t| test_card(width, height, t * 3)).collect(); let mut sizes = Vec::new(); for (cols_log2, rows_log2) in [(0u32, 0u32), (1, 0), (0, 1), (1, 1), (2, 1)] { let config = EncoderConfig { width, height, base_q_idx: 120, gop: 4, colour: Colour::Bt709Limited, tile_cols_log2: cols_log2, tile_rows_log2: rows_log2, }; let layout = format!("{}x{} tiles", 1 << cols_log2, 1 << rows_log2); let grid = crate::tile::TileLayout::new( (width as u32).div_ceil(4), (height as u32).div_ceil(4), cols_log2, rows_log2, ); let (want_cols, want_rows) = (grid.cols(), grid.rows()); let mut enc = Av1Encoder::new(config).unwrap(); let mut stream = Vec::new(); for packet in encode_all(&mut enc, &sources) { stream.extend_from_slice(&packet.data); } sizes.push((layout.clone(), stream.len())); let mut parser = ec_av1_syntax::Av1Parser::new(); let mut frames = 0usize; let mut offset = 0usize; while offset < stream.len() { let obus = parser.parse_temporal_unit(&stream[offset..]).unwrap(); let unit: usize = obus.iter().map(|o| o.total_size).sum(); for obu in &obus { if let ec_av1_syntax::ObuKind::Frame(parsed, tiles) = &obu.kind { assert_eq!( (parsed.tile_info.cols, parsed.tile_info.rows), (want_cols, want_rows), "{layout}: the header's own tile grid" ); assert_eq!( tiles.len(), (want_cols * want_rows) as usize, "{layout}: tile payloads located in the tile group" ); frames += 1; } } offset += unit; } assert_eq!(frames, sources.len(), "{layout}: coded frames"); let ours = crate::stream::decode_stream(&stream).expect("our decoder"); assert_eq!(ours.len(), sources.len(), "{layout}: our decoder's frames"); let theirs = ffmpeg_decode_luma(&stream, width, height); assert_eq!(theirs.len(), sources.len(), "{layout}: ffmpeg's frames"); for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() { let got: Vec = a.y.iter().map(|&v| v as u8).collect(); assert_eq!(got.len(), b.len(), "{layout} frame {i}: luma size"); if let Some(at) = got.iter().zip(b).position(|(x, y)| x != y) { panic!( "{layout} frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}", at % width, at / width, got[at], b[at], ); } } } let base = sizes[0].1 as f64; for (layout, bytes) in &sizes { eprintln!( "{layout}: {bytes} bytes ({:+.2}% vs one tile)", (*bytes as f64 / base - 1.0) * 100.0 ); } } #[test] fn a_moving_detail_clip_codes_two_delta_q_levels_both_decoders_read_exactly() { let (width, height) = (640usize, 384usize); let sources: Vec = (0..4) .map(|t| { let mut p = test_card(width, height, t * 3); let x0 = 32 + t * 32; for y in 128..256 { for x in x0..x0 + 128 { p.y[y * width + x] = if (x / 2 + y / 3) % 2 == 0 { 40 } else { 210 }; } } p }) .collect(); let config = EncoderConfig { width, height, base_q_idx: 120, gop: 4, colour: Colour::Bt709Limited, tile_cols_log2: 0, tile_rows_log2: 0, }; let mut enc = Av1Encoder::new(config).unwrap(); let mut stream = Vec::new(); for packet in encode_all(&mut enc, &sources) { stream.extend_from_slice(&packet.data); } let ours = crate::stream::decode_stream(&stream).expect("our decoder"); assert_eq!(ours.len(), sources.len(), "our decoder's frames"); { let theirs = ffmpeg_decode_luma(&stream, width, height); assert_eq!(theirs.len(), sources.len(), "ffmpeg's frames"); for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() { let got: Vec = a.y.iter().map(|&v| v as u8).collect(); if let Some(at) = got.iter().zip(b).position(|(x, y)| x != y) { panic!( "frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}", at % width, at / width, got[at], b[at], ); } assert_eq!( got.len(), b.len(), "frame {i}: luma is {} samples, ffmpeg's is {}", got.len(), b.len() ); } } } #[test] fn an_edge_clip_codes_every_reduced_set_tx_type_both_decoders_read_exactly() { let (width, height) = (320usize, 192usize); let sources: Vec = (0..2) .map(|t| { let mut p = test_card(width, height, t * 3); for y in 0..height { for x in 0..width { let v = match ((x + t * 4) / 16 % 2, y / 16 % 2) { (0, 0) => 16u16, (1, 0) => 235, (0, 1) => (x % 64 * 3) as u16, _ => (y % 64 * 3) as u16, }; p.y[y * width + x] = v; } } p }) .collect(); let config = EncoderConfig { width, height, base_q_idx: 90, gop: 2, colour: Colour::Bt709Limited, tile_cols_log2: 0, tile_rows_log2: 0, }; let mut enc = Av1Encoder::new(config).unwrap(); let _ = crate::encode::take_tx_type_hits(); let mut stream = Vec::new(); for packet in encode_all(&mut enc, &sources) { stream.extend_from_slice(&packet.data); } let hits = crate::encode::take_tx_type_hits(); if crate::speed::at(&crate::speed::TX_TYPE_SEARCH) { let non_dct: usize = hits.iter().sum::() - hits[crate::transform::TxType::DctDct as usize]; assert!( non_dct > 0, "every luma transform unit took DCT_DCT: {hits:?}" ); } if crate::speed::at(&crate::speed::TX_TYPE_SEARCH) && crate::speed::speed() == 0 { for (name, ty) in [ ("DCT_DCT", crate::transform::TxType::DctDct), ("ADST_ADST", crate::transform::TxType::AdstAdst), ("ADST_DCT", crate::transform::TxType::AdstDct), ("DCT_ADST", crate::transform::TxType::DctAdst), ("IDTX", crate::transform::TxType::Idtx), ] { assert!( hits[ty as usize] > 0, "no luma transform unit took {name}: {hits:?}" ); } } let ours = crate::stream::decode_stream(&stream).expect("our decoder"); assert_eq!(ours.len(), sources.len(), "our decoder's frames"); { let theirs = ffmpeg_decode_luma(&stream, width, height); assert_eq!(theirs.len(), sources.len(), "ffmpeg's frames"); for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() { let got: Vec = a.y.iter().map(|&v| v as u8).collect(); if let Some(at) = got.iter().zip(b).position(|(x, y)| x != y) { panic!( "frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}", at % width, at / width, got[at], b[at], ); } assert_eq!( got.len(), b.len(), "frame {i}: luma is {} samples, ffmpeg's is {}", got.len(), b.len() ); } } eprintln!("tx_type witness: hits {hits:?}, {} bytes", stream.len()); } #[test] fn tile_bytes_do_not_depend_on_the_thread_count() { let (width, height) = (320usize, 192usize); let sources: Vec = (0..3).map(|t| test_card(width, height, t * 3)).collect(); let coded = |threads: usize, cols_log2: u32, rows_log2: u32| { crate::par::set_tile_threads(threads); let config = EncoderConfig { width, height, base_q_idx: 120, gop: 3, colour: Colour::Bt709Limited, tile_cols_log2: cols_log2, tile_rows_log2: rows_log2, }; let mut enc = Av1Encoder::new(config).unwrap(); let mut stream = Vec::new(); for packet in encode_all(&mut enc, &sources) { stream.extend_from_slice(&packet.data); } stream }; for (cols_log2, rows_log2) in [(1u32, 0u32), (0, 1), (1, 1), (2, 1)] { let one = coded(1, cols_log2, rows_log2); let four = coded(4, cols_log2, rows_log2); assert_eq!( one, four, "{}x{} tiles: {} bytes at one thread, {} at four", 1 << cols_log2, 1 << rows_log2, one.len(), four.len() ); } crate::par::set_tile_threads(1); } #[test] fn filter_stage_bytes_do_not_depend_on_the_thread_count() { let (width, height) = (384usize, 288usize); let sources: Vec = (0..4).map(|t| test_card(width, height, t * 3)).collect(); let coded = |threads: usize| { crate::par::set_tile_threads(threads); let config = EncoderConfig { width, height, base_q_idx: 120, gop: 2, colour: Colour::Bt709Limited, tile_cols_log2: 0, tile_rows_log2: 0, }; let mut enc = Av1Encoder::new(config).unwrap(); let mut stream = Vec::new(); for packet in encode_all(&mut enc, &sources) { stream.extend_from_slice(&packet.data); } stream }; let one = coded(1); for threads in [2usize, 4, 8] { assert_eq!( one, coded(threads), "the filter stage moved at {threads} threads" ); } crate::par::set_tile_threads(1); } #[test] fn filter_replay_codes_the_same_stream_as_a_full_decode() { let run = |width: usize, height: usize, off: bool| { let sources: Vec = (0..4).map(|t| test_card(width, height, t * 3)).collect(); crate::decode::set_filter_replay_disabled(off); let config = EncoderConfig { width, height, base_q_idx: 120, gop: 2, colour: Colour::Bt709Limited, tile_cols_log2: 0, tile_rows_log2: 0, }; let mut enc = Av1Encoder::new(config).unwrap(); let mut stream = Vec::new(); for packet in encode_all(&mut enc, &sources) { stream.extend_from_slice(&packet.data); } crate::decode::set_filter_replay_disabled(false); stream }; for (width, height) in [(320usize, 160usize), (320, 192)] { let replayed = run(width, height, false); let decoded = run(width, height, true); assert_eq!( replayed, decoded, "{width}x{height}: the filter replay is not the decode it stands in for \ ({} bytes replayed, {} decoded)", replayed.len(), decoded.len(), ); } } #[test] fn filter_replay_final_matches_the_capture_decode() { let run = |sources: &[Picture], width: usize, height: usize, tiles: (u32, u32)| { let config = EncoderConfig { width, height, base_q_idx: 120, gop: 2, colour: Colour::Bt709Limited, tile_cols_log2: tiles.0, tile_rows_log2: tiles.1, }; let mut enc = Av1Encoder::new(config).unwrap(); for packet in encode_all(&mut enc, sources) { assert!(!packet.data.is_empty()); } }; crate::decode::set_verify_final_replay(true); for (width, height) in [(320usize, 160usize), (320, 192)] { let sources: Vec = (0..4).map(|t| test_card(width, height, t * 3)).collect(); run(&sources, width, height, (0, 0)); } if let Some(sources) = h264_clip_frames(640, 384, 3) { run(&sources, 640, 384, (0, 0)); run(&sources, 640, 384, (1, 1)); } crate::decode::set_verify_final_replay(false); } #[test] fn a_1080p_multi_tile_stream_decodes_sample_exact_through_both_decoders() { let (width, height) = (1920usize, 1080usize); let Some(sources) = h264_clip_frames(width, height, 3) else { return; }; for (cols_log2, rows_log2) in [(1u32, 0u32), (1, 1), (2, 1)] { let config = EncoderConfig { width, height, base_q_idx: 120, gop: 3, colour: Colour::Bt709Limited, tile_cols_log2: cols_log2, tile_rows_log2: rows_log2, }; let layout = format!("{}x{} tiles", 1 << cols_log2, 1 << rows_log2); let mut enc = Av1Encoder::new(config).unwrap(); let mut stream = Vec::new(); for packet in encode_all(&mut enc, &sources) { stream.extend_from_slice(&packet.data); } let ours = crate::stream::decode_stream(&stream).expect("our decoder"); assert_eq!(ours.len(), sources.len(), "{layout}: our decoder's frames"); let theirs = ffmpeg_decode_luma(&stream, width, height); assert_eq!(theirs.len(), sources.len(), "{layout}: ffmpeg's frames"); for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() { let got: Vec = a.y.iter().map(|&v| v as u8).collect(); if let Some(at) = got.iter().zip(b).position(|(x, y)| x != y) { panic!( "1080p {layout} frame {i}: luma differs first at ({}, {})", at % width, at / width ); } assert_eq!( got.len(), b.len(), "1080p {layout} frame {i}: luma is {} samples, ffmpeg's is {}", got.len(), b.len() ); } eprintln!("1080p {layout}: {} bytes, sample-exact", stream.len()); } } #[test] fn quality_target_is_monotone_in_bytes_and_psnr() { let (width, height) = (640, 384); let Some(pictures) = h264_clip_frames(width, height, 8) else { return; }; let mut prev_bytes = 0usize; let mut prev_psnr = 0.0f64; for quality in [20u8, 50, 80] { let config = EncoderConfig { width, height, base_q_idx: 100, gop: 8, colour: Colour::Bt709Limited, tile_cols_log2: 0, tile_rows_log2: 0, }; let mut enc = Av1Encoder::with_rate_target(config, RateTarget::Quality(quality)).unwrap(); let mut stream = Vec::new(); let mut total_bytes = 0usize; for packet in encode_all(&mut enc, &pictures) { total_bytes += packet.data.len(); stream.extend_from_slice(&packet.data); } let decoded = ffmpeg_decode_luma(&stream, width, height); assert_eq!( decoded.len(), pictures.len(), "quality {quality}: dav1d frame count" ); let mean_psnr: f64 = decoded .iter() .zip(&pictures) .map(|(d, p)| { let d16: Vec = d.iter().map(|&v| u16::from(v)).collect(); psnr(&d16, &p.y) }) .sum::() / decoded.len() as f64; assert!( total_bytes >= prev_bytes, "quality {quality}: {total_bytes} bytes not >= previous {prev_bytes}" ); assert!( mean_psnr >= prev_psnr - 0.01, "quality {quality}: {mean_psnr:.2} dB not >= previous {prev_psnr:.2} dB" ); prev_bytes = total_bytes; prev_psnr = mean_psnr; } }