#[test] fn every_drl_index_the_new_mv_pricer_offers_is_one_the_writer_can_signal() { for n in 0..=4usize { let mut stack = bare_stack(); for i in 0..n { stack.entries.push(crate::mvstack::StackEntry { mv: (8 * (i as i32 + 1), -8 * (i as i32 + 1)), weight: 1, }); stack.drl_ctx.push(0); } stack.nearest_mv = stack.entries.first().map_or((0, 0), |e| e.mv); stack.near_mv = stack.entries.get(1).map_or((0, 0), |e| e.mv); stack.pred_mv = stack.nearest_mv; for target in 0..n.max(1) { let mv = stack.entries.get(target).map_or(stack.pred_mv, |e| e.mv); let (_, idx) = best_new_mv_syntax(&stack, mv).expect("a zero residual is always codable"); let idx = usize::from(idx); assert_eq!( crate::tile::signalled_drl_idx(n, 0, idx), idx, "NEWMV: a {n}-entry stack cannot signal the offered drl index {idx}", ); } for idx in 1..=2usize { if stack.entries.get(idx).is_some() { assert_eq!( crate::tile::signalled_drl_idx(n, 1, idx), idx, "NEARMV: a {n}-entry stack cannot signal the offered drl index {idx}", ); } } } } pub(super) fn bare_stack() -> crate::mvstack::MvStack { crate::mvstack::MvStack { entries: Default::default(), nearest_mv: (0, 0), near_mv: (0, 0), pred_mv: (0, 0), new_mv_ctx: 0, ref_mv_ctx: 0, zero_mv_ctx: 0, drl_ctx: Default::default(), above_refs: (None, None), left_refs: (None, None), above_nbr: None, left_nbr: None, above_skip: false, left_skip: false, } } #[test] fn the_compound_ref_pricer_pays_the_writers_own_symbol_sequence() { use crate::cdf::{COMP_BWDREF, COMP_MODE, COMP_REF, COMP_REF_TYPE, UNI_COMP_REF}; use crate::encode::symbol_bits as b; use crate::mvstack::{ ALTREF_FRAME, ALTREF2_FRAME, BWDREF_FRAME, GOLDEN_FRAME, LAST_FRAME, LAST2_FRAME, LAST3_FRAME, NeighbourRef, comp_reference_type_ctx, reference_mode_ctx, single_ref_p1_ctx, single_ref_p2_ctx, single_ref_p3_ctx, single_ref_p4_ctx, single_ref_p5_ctx, single_ref_p6_ctx, uni_comp_ref_p1_ctx, }; type Sym = (char, usize, usize, usize); let cases: [((i8, i8), bool, &[Sym]); 7] = [ ( (LAST_FRAME, LAST2_FRAME), true, &[('u', 0, 1, 0), ('u', 1, 7, 0)], ), ( (LAST_FRAME, LAST3_FRAME), true, &[('u', 0, 1, 0), ('u', 1, 7, 1), ('u', 2, 5, 0)], ), ( (LAST_FRAME, GOLDEN_FRAME), true, &[('u', 0, 1, 0), ('u', 1, 7, 1), ('u', 2, 5, 1)], ), ((BWDREF_FRAME, ALTREF_FRAME), true, &[('u', 0, 1, 1)]), ( (LAST_FRAME, ALTREF_FRAME), false, &[('c', 0, 3, 0), ('c', 1, 4, 0), ('b', 0, 2, 1)], ), ( (LAST_FRAME, BWDREF_FRAME), false, &[ ('c', 0, 3, 0), ('c', 1, 4, 0), ('b', 0, 2, 0), ('b', 1, 6, 0), ], ), ( (LAST_FRAME, ALTREF2_FRAME), false, &[ ('c', 0, 3, 0), ('c', 1, 4, 0), ('b', 0, 2, 0), ('b', 1, 6, 1), ], ), ]; let nbr = |ref0, ref1: Option| { Some(NeighbourRef { is_inter: true, ref0, ref1, uni: ref1.is_some_and(|r1| crate::mvstack::is_uni_comp_ref(ref0, r1)), }) }; for (above_nbr, left_nbr, above_refs, left_refs) in [ (None, None, (None, None), (None, None)), ( nbr(LAST_FRAME, None), nbr(ALTREF_FRAME, Some(GOLDEN_FRAME)), (Some(LAST_FRAME), None), (Some(ALTREF_FRAME), Some(GOLDEN_FRAME)), ), ] { let stack = crate::mvstack::MvStack { above_nbr, left_nbr, above_refs, left_refs, ..bare_stack() }; let (a, a1) = above_refs; let (l, l1) = left_refs; let ctx_of = |sel: usize| match sel { 1 => single_ref_p1_ctx(a, a1, l, l1), 2 => single_ref_p2_ctx(a, a1, l, l1), 3 => single_ref_p3_ctx(a, a1, l, l1), 4 => single_ref_p4_ctx(a, a1, l, l1), 5 => single_ref_p5_ctx(a, a1, l, l1), 6 => single_ref_p6_ctx(a, a1, l, l1), _ => uni_comp_ref_p1_ctx(a, a1, l, l1), }; for (pair, unidir, symbols) in cases { let mut want = b(&COMP_MODE[reference_mode_ctx(above_nbr, left_nbr)], 1) + b( &COMP_REF_TYPE[comp_reference_type_ctx(above_nbr, left_nbr)], usize::from(!unidir), ); for &(table, p, sel, v) in symbols { let row = ctx_of(sel); want += match table { 'u' => b(&UNI_COMP_REF[row][p], v), 'c' => b(&COMP_REF[row][p], v), _ => b(&COMP_BWDREF[row][p], v), }; } let got = super::compound_ref_bits(pair, &stack); assert!( (got - want).abs() < 1e-9, "pair {pair:?} above {above_refs:?} left {left_refs:?}: \ priced {got} bits, writer codes {want}" ); } } } #[test] fn the_skip_and_intra_inter_pricers_use_the_writers_own_contexts() { use crate::cdf::{INTRA_INTER, SKIP}; use crate::encode::symbol_bits as b; use crate::mvstack::NeighbourRef; let nbr = |is_inter| NeighbourRef { is_inter, ref0: if is_inter { crate::mvstack::LAST_FRAME } else { 0 }, ref1: None, uni: false, }; for (above, left, above_skip, left_skip) in [ (None, None, false, false), (Some(nbr(true)), Some(nbr(true)), true, false), (Some(nbr(false)), Some(nbr(false)), true, true), (Some(nbr(false)), None, false, true), (None, Some(nbr(true)), true, true), ] { let stack = crate::mvstack::MvStack { above_nbr: above, left_nbr: left, above_skip, left_skip, ..bare_stack() }; let skip_ctx = usize::from(above_skip) + usize::from(left_skip); let ii_ctx = crate::tile::intra_inter_ctx( above.is_some(), left.is_some(), above.is_some_and(|n| n.is_inter), left.is_some_and(|n| n.is_inter), ); for v in [false, true] { let (got, want) = ( super::skip_bits_at(&stack, v), b(&SKIP[skip_ctx], usize::from(v)), ); assert!( (got - want).abs() < 1e-9, "skip {v} at ctx {skip_ctx}: priced {got}, writer codes {want}" ); let (got, want) = ( super::intra_inter_bits_at(&stack, v), b(&INTRA_INTER[ii_ctx], usize::from(v)), ); assert!( (got - want).abs() < 1e-9, "is_inter {v} at ctx {ii_ctx}: priced {got}, writer codes {want}" ); } } } #[test] fn the_single_ref_pricer_pays_the_writers_own_symbol_sequence() { use crate::cdf::SINGLE_REF as SR; use crate::encode::symbol_bits as b; use crate::mvstack::{ ALTREF_FRAME, ALTREF2_FRAME, BWDREF_FRAME, GOLDEN_FRAME, LAST_FRAME, LAST2_FRAME, LAST3_FRAME, MvStack, single_ref_p1_ctx, single_ref_p2_ctx, single_ref_p3_ctx, single_ref_p4_ctx, single_ref_p5_ctx, single_ref_p6_ctx, }; let stack_with = |above_refs, left_refs, above_nbr, left_nbr| MvStack { above_refs, left_refs, above_nbr, left_nbr, ..bare_stack() }; let nbr = |ref0, ref1| { Some(crate::mvstack::NeighbourRef { is_inter: true, ref0, ref1, uni: false, }) }; let cases: [(i8, &[(usize, usize)]); 7] = [ (LAST_FRAME, &[(0, 0), (2, 0), (3, 0)]), (LAST2_FRAME, &[(0, 0), (2, 0), (3, 1)]), (LAST3_FRAME, &[(0, 0), (2, 1), (4, 0)]), (GOLDEN_FRAME, &[(0, 0), (2, 1), (4, 1)]), (BWDREF_FRAME, &[(0, 1), (1, 0), (5, 0)]), (ALTREF2_FRAME, &[(0, 1), (1, 0), (5, 1)]), (ALTREF_FRAME, &[(0, 1), (1, 1)]), ]; for (above_refs, left_refs, above_nbr, left_nbr) in [ ((None, None), (None, None), None, None), ( (Some(LAST_FRAME), None), (Some(ALTREF_FRAME), Some(LAST_FRAME)), nbr(LAST_FRAME, None), nbr(ALTREF_FRAME, Some(LAST_FRAME)), ), ] { let stack = stack_with(above_refs, left_refs, above_nbr, left_nbr); let (a, a1) = above_refs; let (l, l1) = left_refs; let ctx_of = |p: usize| match p { 0 => single_ref_p1_ctx(a, a1, l, l1), 1 => single_ref_p2_ctx(a, a1, l, l1), 2 => single_ref_p3_ctx(a, a1, l, l1), 3 => single_ref_p4_ctx(a, a1, l, l1), 4 => single_ref_p5_ctx(a, a1, l, l1), _ => single_ref_p6_ctx(a, a1, l, l1), }; for (ref_frame, symbols) in cases { let mut want: f64 = symbols.iter().map(|&(p, v)| b(&SR[ctx_of(p)][p], v)).sum(); if super::reference_select() { want += b( &crate::cdf::COMP_MODE[crate::mvstack::reference_mode_ctx(above_nbr, left_nbr)], 0, ); } let got = super::single_ref_bits(ref_frame, &stack); assert!( (got - want).abs() < 1e-9, "ref {ref_frame} above {above_refs:?} left {left_refs:?}: \ priced {got} bits, writer codes {want}" ); } } } #[test] fn a_block_the_frame_edge_cuts_is_scored_over_its_inside_only() { let source = vec![10u8; 64 * 64]; let plane = fresh_plane(&source, 64, 64, 40, 40); let mut reconstruction = vec![10u8; 64 * 64]; reconstruction[50 * 64 + 50] = 200; assert_eq!( plane.block_sse(0, 0, 64, &reconstruction), 0.0, "padding was scored" ); reconstruction[39 * 64 + 39] = 20; assert_eq!( plane.block_sse(0, 0, 64, &reconstruction), 100.0, "inside was not scored" ); let block = vec![200u8; 16 * 16]; assert_eq!( plane.block_sse(48, 0, 16, &block), 0.0, "a block past the edge scored" ); assert_eq!(plane.block_sse(32, 32, 16, &block), (190.0 * 190.0) * 64.0); } #[test] fn the_objective_delta_q_mapping_leans_the_right_way_and_stops_at_libaom_s_clamp() { let (base, res) = (162u8, 4i32); let rf = 2.0; assert!( super::deltaq_libaom(base, 8.0, rf, 1.0, res) < base, "leaned-on SB must go finer" ); assert!( super::deltaq_libaom(base, 0.2, rf, 1.0, res) > base, "idle SB must go coarser" ); assert_eq!( super::deltaq_libaom(base, rf, rf, 1.0, res), base, "the average SB moves 0" ); let max = ((res * 9 - 1) / res) * res; for r in [0.0f64, 0.01, 0.5, 1.0, 3.0, 50.0, 1e6] { for k in [0.5f64, 1.0, 1.5] { let q = i32::from(super::deltaq_libaom(base, r, rf, k, res)); let d = q - i32::from(base); assert_eq!( d % res, 0, "r={r} k={k}: offset {d} is not a whole {res}-step" ); assert!( d.abs() <= max, "r={r} k={k}: offset {d} past libaom's +-{max}" ); } } assert_eq!( i32::from(super::deltaq_libaom(base, 1e9, rf, 1.0, res)) - i32::from(base), -max ); assert_eq!( i32::from(super::deltaq_libaom(base, 0.0, 1e9, 1.0, res)) - i32::from(base), max ); let d = |k: f64| (i32::from(super::deltaq_libaom(base, 8.0, rf, k, res)) - i32::from(base)).abs(); assert!( d(0.5) <= d(1.0) && d(1.0) <= d(1.5), "strength must be monotone: {} {} {}", d(0.5), d(1.0), d(1.5) ); assert!((super::tpl_frame_ratio(&[2.5; 16]) - 2.5).abs() < 1e-9); } #[test] fn tpl_factors_are_flat_on_a_uniform_repeat_and_fall_where_the_window_leans() { let (w, h) = (256usize, 64usize); let uniform: Vec = (0..w * h).map(|i| ((i * 37) % 251) as u8).collect(); let frames: Vec<&[u8]> = vec![&uniform, &uniform, &uniform]; let (f, _) = super::tpl_lambda_factors(&frames, w, h, 1.0); assert_eq!(f.len(), 64, "16x4 cells of 16x16"); for (i, &v) in f.iter().enumerate() { assert!( (v - 1.0).abs() < 1e-6, "cell {i} factor {v}, a flat map must move no lambda" ); } let split: Vec = (0..w * h) .map(|i| { if i % w < w / 2 { ((i * 37) % 251) as u8 } else { 128 } }) .collect(); let frames: Vec<&[u8]> = vec![&split, &split, &split]; let cells_x = w / 16; for k in [0.25f64, 0.5, 1.0, 2.0] { let (f, _) = super::tpl_lambda_factors(&frames, w, h, k); for r in 0..h / 16 { let (lean, idle) = (f[r * cells_x], f[r * cells_x + cells_x - 1]); assert!( lean < 1.0, "k={k} row {r}: leaned-on cell factor {lean} must be < 1" ); assert!( idle > 1.0, "k={k} row {r}: idle cell factor {idle} must be > 1" ); } } } #[test] fn rect_reach_tables_are_indexed_with_a_32_mi_row_stride() { for (bw, bh) in [ (16usize, 8usize), (8, 16), (32, 16), (16, 32), (64, 32), (32, 64), ] { let (bw_log2, bh_log2) = ( (bw / 4).trailing_zeros() as usize, (bh / 4).trailing_zeros() as usize, ); let (rows, cols) = (32 >> bh_log2, 32 >> bw_log2); for (name, table) in [ ("has_tr", rect_reach_tables(bw, bh).0), ("has_bl", rect_reach_tables(bw, bh).1), ] { assert_eq!( table.len() * 8, rows * cols, "{name}_{bw}x{bh}: libaom's table is {rows} rows of {cols} bits" ); let mut seen = vec![0u32; table.len() * 8]; for blk_row in 0..rows { for blk_col in 0..cols { let idx = Reach::rect_table_index(bw_log2, blk_row, blk_col); assert!( idx < seen.len(), "{name}_{bw}x{bh}: index {idx} past the table at ({blk_row},{blk_col})" ); seen[idx] += 1; } } assert!( seen.iter().all(|&n| n == 1), "{name}_{bw}x{bh}: the block walk is not a bijection onto the table's bits \ (row stride is not {cols})" ); } } } use super::*; use crate::intra::{D45_PRED, D135_PRED, KEY_FRAME_MODES}; use crate::probe::run_with_stdin; #[test] fn every_rect_shape_reaches_what_libaom_says_over_the_whole_superblock() { let fctx = &crate::decode::FrameCtx::new(); const SHAPES: [(usize, usize, usize, u32, usize, u32); 14] = [ (4, 8, 64, 9280, 64, 550), (8, 4, 64, 3712, 64, 9630), (8, 16, 16, 2352, 16, 134), (16, 8, 16, 960, 16, 2400), (16, 32, 4, 620, 4, 32), (32, 16, 4, 32, 4, 184), (32, 64, 1, 127, 1, 0), (64, 32, 1, 19, 1, 34), (4, 16, 32, 5472, 32, 14), (16, 4, 32, 960, 32, 6464), (8, 32, 8, 1400, 8, 2), (32, 8, 8, 32, 8, 1136), (16, 64, 2, 382, 2, 0), (64, 16, 2, 4, 2, 84), ]; fn libaom_reach( bw: usize, bh: usize, x: usize, y: usize, width: usize, height: usize, _fctx: &crate::decode::FrameCtx, ) -> (bool, bool) { let (bw_log2, bh_log2) = ((bw / 4).ilog2() as usize, (bh / 4).ilog2() as usize); let (_bw_unit, bh_unit) = (bw / 4, bh / 4); let sb_mi_size = 16usize; let blk_row_in_sb = ((y / 4) & (sb_mi_size - 1)) >> bh_log2; let blk_col_in_sb = ((x / 4) & (sb_mi_size - 1)) >> bw_log2; let this_blk_index = (blk_row_in_sb << (5 - bw_log2)) + blk_col_in_sb; let (tr_table, bl_table) = rect_reach_tables(bw, bh); let bit = |t: &[u8]| (t[this_blk_index / 8] >> (this_blk_index % 8)) & 1 != 0; let top_right = if y == 0 || x + bw >= width { false } else if blk_row_in_sb == 0 { true } else if ((blk_col_in_sb + 1) << bw_log2) >= sb_mi_size { false } else { bit(tr_table) }; let bottom_left = if x == 0 || y + bh >= height { false } else if blk_col_in_sb == 0 { (blk_row_in_sb << bh_log2) + bh_unit < sb_mi_size } else if ((blk_row_in_sb + 1) << bh_log2) >= sb_mi_size { false } else { bit(bl_table) }; (top_right, bottom_left) } for (bw, bh, tr_len, tr_sum, bl_len, bl_sum) in SHAPES { let (tr, bl) = rect_reach_tables(bw, bh); let sum = |t: &[u8]| t.iter().map(|&b| u32::from(b)).sum::(); assert_eq!( (tr.len(), sum(tr), bl.len(), sum(bl)), (tr_len, tr_sum, bl_len, bl_sum), "rect_reach_tables({bw}, {bh}) is not libaom's has_tr_{bw}x{bh}/has_bl_{bw}x{bh}" ); for sb_y in [0usize, 64] { for sb_x in [0usize, 64] { for y in (sb_y..sb_y + 64).step_by(bh) { for x in (sb_x..sb_x + 64).step_by(bw) { let got = Reach::of_rect(bw, bh, x, y, 256, 256, fctx); let want = libaom_reach(bw, bh, x, y, 256, 256, fctx); assert_eq!( (got.above_right, got.below_left), want, "{bw}x{bh} at ({x}, {y})" ); } } } } } } pub(super) fn ffmpeg_decode(stream: &[u8], width: usize, height: usize) -> Picture { let out = run_with_stdin( ec_testkit::ffmpeg().args([ "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-", ]), stream, ); assert!( out.status.success(), "ffmpeg refused the stream: {}", String::from_utf8_lossy(&out.stderr) ); let (luma, chroma) = (width * height, width * height / 4); assert_eq!( out.stdout.len(), luma + 2 * chroma, "expected one 4:2:0 frame" ); Picture { width, height, y: out.stdout[..luma].iter().map(|&v| u16::from(v)).collect(), u: out.stdout[luma..luma + chroma] .iter() .map(|&v| u16::from(v)) .collect(), v: out.stdout[luma + chroma..] .iter() .map(|&v| u16::from(v)) .collect(), } } #[test] fn the_filter_search_picks_real_filters() { let fctx = &crate::decode::FrameCtx::for_encoder(); let pictures: Vec<_> = (0..3).map(|i| panned_test_card(128, 128, i * 3)).collect(); let encoded = encode_sequence_with_ctx(&pictures, 120, 0.5, fctx).unwrap(); let fired = encoded .frames .iter() .filter(|f| f.loop_filter.level[0] > 0 || f.cdef.y_pri_strength[0] > 0) .count(); assert!( fired > 0, "no frame of this sequence chose any in-loop filtering: {:?}", encoded .frames .iter() .map(|f| (f.loop_filter.level, f.cdef.y_pri_strength[0])) .collect::>() ); let decoded = crate::stream::decode_stream(&encoded.stream).unwrap(); assert_eq!(decoded.len(), encoded.frames.len()); for (i, (dec, enc)) in decoded.iter().zip(&encoded.frames).enumerate() { assert_eq!(dec.y, enc.reconstruction.y, "frame {i} luma"); assert_eq!(dec.u, enc.reconstruction.u, "frame {i} U"); assert_eq!(dec.v, enc.reconstruction.v, "frame {i} V"); } } pub(super) fn test_card(width: usize, height: usize) -> Picture { let mut picture = Picture::grey(width, height); for y in 0..height { for x in 0..width { let gradient = x as f64 * 200.0 / width as f64; let ripple = 30.0 * (x as f64 * std::f64::consts::PI / 23.0).sin() * (y as f64 * std::f64::consts::PI / 37.0).cos(); let edge = if x > width * 3 / 7 && y > height / 3 { 40.0 } else { 0.0 }; picture.y[y * width + x] = (20.0 + gradient + ripple + edge).clamp(0.0, 255.0) as u16; } } for y in 0..height / 2 { for x in 0..width / 2 { let i = y * width / 2 + x; picture.u[i] = (100 + (x * 60 / (width / 2))) as u16; picture.v[i] = (200 - (y * 80 / (height / 2))) as u16; } } picture } pub(super) 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() } #[test] fn a_smooth_gradient_key_frame_codes_whole_superblocks_and_decodes_exactly() { let fctx = &crate::decode::FrameCtx::for_encoder(); let (width, height) = (256usize, 192usize); let mut picture = Picture::grey(width, height); for y in 0..height { for x in 0..width { picture.y[y * width + x] = (16 + (x + y) * 200 / (width + height)) as u16; } } for y in 0..height / 2 { for x in 0..width / 2 { picture.u[y * width / 2 + x] = (110 + x * 20 / (width / 2)) as u16; picture.v[y * width / 2 + x] = (130 - y * 20 / (height / 2)) as u16; } } let _ = take_i64_root_hits(); let encoded = encode_key_frame_with_ctx(&picture, 120, 0.5, fctx).unwrap(); let [roots, _offered, _edge] = take_i64_root_hits(); assert_eq!( encoded.modes.len(), 12, "not every superblock was coded as one 64x64 intra block" ); assert!( roots >= 8, "a smooth-gradient key frame coded only {roots} whole 64x64 intra roots of 12" ); eprintln!("whole 64x64 intra roots on a smooth gradient: {roots} of 12"); let ours = crate::stream::decode_stream(&encoded.stream).expect("our decoder"); assert_eq!(ours.len(), 1, "our decoder's frames"); assert_eq!(ours[0].y, encoded.reconstruction.y, "our decoder: luma"); assert_eq!(ours[0].u, encoded.reconstruction.u, "our decoder: U"); assert_eq!(ours[0].v, encoded.reconstruction.v, "our decoder: V"); let decoded = ffmpeg_decode(&encoded.stream, width, height); assert_eq!(decoded.y, encoded.reconstruction.y, "ffmpeg: luma"); assert_eq!(decoded.u, encoded.reconstruction.u, "ffmpeg: U"); assert_eq!(decoded.v, encoded.reconstruction.v, "ffmpeg: V"); } #[test] fn ffmpeg_decodes_exactly_what_the_encoder_reconstructed() { let fctx = &crate::decode::FrameCtx::for_encoder(); for &(width, height) in &[ (64usize, 64usize), (96, 64), (160, 96), (32, 48), (248, 152), ] { let picture = test_card(width, height); let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap(); let decoded = ffmpeg_decode(&encoded.stream, width, height); assert_eq!( decoded.y, encoded.reconstruction.y, "{width}x{height}: luma" ); assert_eq!(decoded.u, encoded.reconstruction.u, "{width}x{height}: U"); assert_eq!(decoded.v, encoded.reconstruction.v, "{width}x{height}: V"); } let (width, height) = (64usize, 64usize); let picture = test_card(width, height); let _ = take_tx_depth_hits(); for &q in &[15u8, 45, 100, 200] { let encoded = encode_key_frame_with_ctx(&picture, q, 0.5, fctx).unwrap(); let decoded = ffmpeg_decode(&encoded.stream, width, height); assert_eq!(decoded.y, encoded.reconstruction.y, "q={q}: luma"); assert_eq!(decoded.u, encoded.reconstruction.u, "q={q}: U"); assert_eq!(decoded.v, encoded.reconstruction.v, "q={q}: V"); } let depths = take_tx_depth_hits(); assert!( depths[1] + depths[2] > 0, "no block split its transform: depths {depths:?}" ); } #[cfg(test)] pub(super) fn screen_card(width: usize, height: usize) -> Picture { const INK: [u16; 4] = [16, 90, 180, 235]; let mut picture = Picture::grey(width, height); for y in 0..height { for x in 0..width { let cell = (x / 24 + y / 24) % 2; let bar = usize::from(y % 24 < 6 && x % 24 >= 3 && x % 24 < 20); picture.y[y * width + x] = INK[cell * 2 + bar]; } } const CHROMA_U: [u16; 4] = [96, 118, 150, 176]; const CHROMA_V: [u16; 4] = [148, 126, 104, 92]; for y in 0..height / 2 { for x in 0..width / 2 { let cell = (x / 12 + 2 * (y / 12)) % 4; picture.u[y * (width / 2) + x] = CHROMA_U[cell]; picture.v[y * (width / 2) + x] = CHROMA_V[cell]; } } picture } #[test] fn a_screen_content_picture_codes_palette_blocks_ffmpeg_decodes_exactly() { let fctx = &crate::decode::FrameCtx::for_encoder(); let (width, height) = (192usize, 96usize); let _ = crate::tile::take_palette_hits(); let picture = screen_card(width, height); let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap(); assert!( encoded.screen, "the detector did not fire on screen content -- no palette syntax was coded at all" ); let hits = crate::tile::take_palette_hits(); assert!(hits[0] > 0, "no block took a palette: {hits:?}"); eprintln!("palette blocks {} sizes {:?}", hits[0], &hits[2..]); let uv_hits = crate::tile::take_palette_uv_hits(); assert!( uv_hits[0] > 0, "no block took a chroma palette: {uv_hits:?}" ); let uv_cached = crate::tile::take_palette_uv_cache_hits(); eprintln!( "chroma palette blocks {} sizes {:?}, {uv_cached} colours from the neighbour cache", uv_hits[0], &uv_hits[2..] ); assert!( uv_cached > 0, "no chroma base colour came out of the neighbour cache -- \ `write_palette_colors_uv`'s cache half is unproven by the oracle below" ); let via_us = crate::stream::decode_stream(&encoded.stream).unwrap(); assert_eq!(via_us[0].y, encoded.reconstruction.y, "our decoder: luma"); assert_eq!(via_us[0].u, encoded.reconstruction.u, "our decoder: U"); assert_eq!(via_us[0].v, encoded.reconstruction.v, "our decoder: V"); let decoded = ffmpeg_decode(&encoded.stream, width, height); assert_eq!(decoded.y, encoded.reconstruction.y, "ffmpeg: luma"); assert_eq!(decoded.u, encoded.reconstruction.u, "ffmpeg: U"); assert_eq!(decoded.v, encoded.reconstruction.v, "ffmpeg: V"); let moved: Vec = (0..4) .map(|f| { let base = screen_card(width, height); let mut out = Picture::grey(width, height); for y in 0..height { for x in 0..width { let sx = (x + f * 7) % width; out.y[y * width + x] = base.y[y * width + sx]; } } for y in 0..height / 2 { for x in 0..width / 2 { let sx = (x + f * 3) % (width / 2); out.u[y * (width / 2) + x] = base.u[y * (width / 2) + sx]; out.v[y * (width / 2) + x] = base.v[y * (width / 2) + sx]; } } out }) .collect(); let _ = crate::tile::take_palette_hits(); let _ = crate::tile::take_palette_uv_hits(); let gop = encode_sequence_with_ctx(&moved, 100, 0.5, fctx).unwrap(); let gop_hits = crate::tile::take_palette_hits(); let gop_uv_hits = crate::tile::take_palette_uv_hits(); let inter_screen = gop.frames.iter().skip(1).filter(|f| f.screen).count(); eprintln!( "GOP: {} frames with screen tools after the key frame, {} palette blocks, \ {} chroma palette blocks", inter_screen, gop_hits[0], gop_uv_hits[0] ); assert!( gop_uv_hits[0] > 0, "no block of the GOP took a chroma palette: {gop_uv_hits:?}" ); assert!( inter_screen > 0, "no inter frame set allow_screen_content_tools" ); let gop_decoded = crate::stream::decode_stream(&gop.stream).unwrap(); assert_eq!( gop_decoded.len(), gop.frames.len(), "our decoder: GOP frame count" ); for (i, (ours, frame)) in gop_decoded.iter().zip(gop.frames.iter()).enumerate() { assert_eq!( ours.y, frame.reconstruction.y, "our decoder: GOP frame {i} luma" ); } { let ff = ffmpeg_decode_sequence(&gop.stream, width, height, moved.len()); assert_eq!(ff.len(), gop.frames.len(), "ffmpeg: GOP frame count"); for (i, (theirs, frame)) in ff.iter().zip(gop.frames.iter()).enumerate() { assert_eq!( theirs.y, frame.reconstruction.y, "ffmpeg: GOP frame {i} luma" ); assert_eq!(theirs.u, frame.reconstruction.u, "ffmpeg: GOP frame {i} U"); assert_eq!(theirs.v, frame.reconstruction.v, "ffmpeg: GOP frame {i} V"); } } let film = encode_key_frame_with_ctx(&test_card(width, height), 100, 0.5, fctx).unwrap(); assert!( !film.screen, "the detector fired on the film-shaped test card" ); } #[test] fn a_nearestmv_block_with_one_nonzero_coefficient_decodes_clean() { let fctx = &crate::decode::FrameCtx::for_encoder(); let (width, height) = (64usize, 64usize); let picture = Picture::grey(width, height); let key = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap(); let (seq, _) = key_frame_headers(width, height, 100).unwrap(); let (_, inter_header) = inter_frame_headers(width, height, 100, 1, 0).unwrap(); let residual_block = BlockCoeffs { luma_tx_types: Vec::new(), angle_delta_y: 0, cfl_alphas: None, filter_intra: None, luma: vec![Coeff { row: 0, col: 0, level: 4, }], u: Vec::new(), v: Vec::new(), mode: 0, uv_mode: 0, skip: false, eight: None, dv: None, palette: None, palette_uv: None, tx_depth: 0, inter: Some(InterInfo { ref1: None, mv1: (0, 0), ref_frame: crate::mvstack::LAST_FRAME, mode: InterMode::NearestMv, mv: (0, 0), ref_mv_idx: 0, }), motion_mode: 0, }; let skipped_block = BlockCoeffs { skip: true, inter: Some(InterInfo { ref1: None, mv1: (0, 0), ref_frame: crate::mvstack::LAST_FRAME, mode: InterMode::NearestMv, mv: (0, 0), ref_mv_idx: 0, }), ..BlockCoeffs::default() }; let blocks = vec![ Quadrant::Whole(residual_block), Quadrant::Whole(skipped_block.clone()), Quadrant::Whole(skipped_block.clone()), Quadrant::Whole(skipped_block), ]; crate::tile::arm_motion_mode(inter_header.is_motion_mode_switchable); crate::tile::arm_warped_motion(inter_header.allow_warped_motion); let tile = crate::tile::sb_coeff_inter_frame_tile( inter_header.mi_cols, inter_header.mi_rows, 100, &blocks, ) .unwrap(); let mut stream = key.stream.clone(); stream.extend_from_slice(&temporal_delimiter()); stream.extend_from_slice(&frame_obu(&seq, &inter_header, &tile).unwrap()); ffmpeg_decode_sequence(&stream, width, height, 2); } pub(super) fn ffprobe_size(stream: &[u8]) -> (u32, u32) { static PROBE_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); let path = std::env::temp_dir().join(format!( "ec-av1-probe-{}-{}.obu", std::process::id(), PROBE_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed) )); let _ = std::fs::remove_file(&path); 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=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) ); let text = String::from_utf8_lossy(&out.stdout); let mut fields = text.trim().split(','); let width: u32 = fields.next().expect("ffprobe width").parse().unwrap(); let height: u32 = fields.next().expect("ffprobe height").parse().unwrap(); (width, height) } #[test] fn the_final_filter_replay_matches_the_capture_decode_at_odd_sizes() { let fctx = &crate::decode::FrameCtx::for_encoder(); crate::decode::set_verify_final_replay(true); for &(width, height) in &[ (64usize, 56usize), (216, 96), (192, 120), (640, 352), (1280, 720), ] { eprintln!("--- {width}x{height}"); let picture = test_card(width, height); let _ = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap(); } crate::decode::set_verify_final_replay(false); } #[test] fn a_frame_round_trips_at_its_own_size() { let fctx = &crate::decode::FrameCtx::for_encoder(); for &(width, height) in &[ (1920usize, 1080usize), (640, 352), (1280, 720), (64, 56), (854, 480), (216, 96), (192, 120), ] { let picture = test_card(width, height); let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap(); assert_eq!( (encoded.reconstruction.width, encoded.reconstruction.height), (width, height), "{width}x{height}: reconstruction is cropped to the picture's own size" ); assert_eq!( ffprobe_size(&encoded.stream), (width as u32, height as u32), "{width}x{height}: ffprobe reports the true (display) size, not the padded one" ); let decoded = ffmpeg_decode(&encoded.stream, width, height); assert_eq!( decoded.y, encoded.reconstruction.y, "{width}x{height}: luma" ); assert_eq!(decoded.u, encoded.reconstruction.u, "{width}x{height}: U"); assert_eq!(decoded.v, encoded.reconstruction.v, "{width}x{height}: V"); } } #[test] fn an_854x480_picture_round_trips_through_its_padding() { let fctx = &crate::decode::FrameCtx::for_encoder(); let (width, height) = (854usize, 480usize); let picture = test_card(width, height); let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap(); let decoded = ffmpeg_decode(&encoded.stream, width, height); assert_eq!(decoded.y, encoded.reconstruction.y, "854x480: luma"); assert_eq!(decoded.u, encoded.reconstruction.u, "854x480: U"); assert_eq!(decoded.v, encoded.reconstruction.v, "854x480: V"); } #[test] fn of_tu_follows_the_block_row_including_under_vert_ab() { let fctx = &crate::decode::FrameCtx::for_encoder(); let plain = Reach::of(8, 0, 8, SUPERBLOCK, SUPERBLOCK, fctx); assert_eq!( Reach::of_tu(8, 8, 4, 0, 4, 4, plain).above_right, plain.above_right, "ordinary table: the top-right TX4 unit takes the block's row" ); let guard = Reach::vert_ab_partition(); let vert = Reach::of(8, 0, 8, SUPERBLOCK, SUPERBLOCK, fctx); assert_eq!( Reach::of_tu(8, 8, 4, 0, 4, 4, vert).above_right, vert.above_right, "vert AB: the unit follows the vert row the block just picked" ); assert_ne!( plain.above_right, vert.above_right, "this position is the cell where the vert tables disagree; pick another if libaom's tables change" ); drop(guard); } #[test] fn reach_matches_libaom_has_top_right_and_has_bottom_left() { let fctx = &crate::decode::FrameCtx::new(); fn libaom_top_right(side: usize, x: usize, y: usize, width: usize, _height: usize) -> bool { if y == 0 || x + side >= width { return false; } let (row, col, per_side) = ( (y % SUPERBLOCK) / side, (x % SUPERBLOCK) / side, SUPERBLOCK / side, ); if row == 0 { return true; } if col + 1 == per_side { return false; } let stride = 128 / side; let index = row * stride + col; let table = if side == BLOCK { [95u8, 87].to_vec() } else { vec![255, 85, 119, 85, 127, 85, 119, 85] }; (table[index / 8] >> (index % 8)) & 1 != 0 } fn libaom_bottom_left( side: usize, x: usize, y: usize, height: usize, _fctx: &crate::decode::FrameCtx, ) -> bool { if x == 0 || y + side >= height { return false; } let (row, col, per_side) = ( (y % SUPERBLOCK) / side, (x % SUPERBLOCK) / side, SUPERBLOCK / side, ); if col == 0 { return row * side + side < SUPERBLOCK; } if row + 1 == per_side { return false; } let stride = 128 / side; let index = row * stride + col; let table = if side == BLOCK { [4u8, 4].to_vec() } else { vec![84, 16, 84, 0, 84, 16, 84, 0] }; (table[index / 8] >> (index % 8)) & 1 != 0 } let (width, height) = (SUPERBLOCK * 3, SUPERBLOCK * 3); for side in [16usize, BLOCK] { for y in (0..height).step_by(side) { for x in (0..width).step_by(side) { let reach = Reach::of(side, x, y, width, height, fctx); assert_eq!( reach.above_right, libaom_top_right(side, x, y, width, height), "side={side} x={x} y={y}: above_right" ); assert_eq!( reach.below_left, libaom_bottom_left(side, x, y, height, fctx), "side={side} x={x} y={y}: below_left" ); } } } } #[test] fn of_tu_matches_libaom_has_top_right_and_has_bottom_left_per_unit() { fn libaom_tr( bw: usize, bh: usize, col_off: usize, row_off: usize, tx: usize, blk: bool, ) -> bool { let (plane_bw_unit, count) = (bw / 4, tx / 4); let (col_off_u, row_off_u) = (col_off / 4, row_off / 4); let _ = bh; if row_off_u > 0 { col_off_u + count < plane_bw_unit } else if col_off_u + count < plane_bw_unit { true } else { blk } } fn libaom_bl( bw: usize, bh: usize, col_off: usize, row_off: usize, tx: usize, blk: bool, ) -> bool { let (plane_bh_unit, count) = (bh / 4, tx / 4); let (col_off_u, row_off_u) = (col_off / 4, row_off / 4); let _ = bw; if col_off_u > 0 { false } else if row_off_u + count < plane_bh_unit { true } else { blk } } for &(bw, bh) in &[ (8, 8), (16, 16), (32, 32), (64, 64), (16, 8), (8, 16), (32, 16), (16, 32), (64, 32), (32, 64), ] { for &tx in &[4usize, 8, 16, 32] { if tx > bw.min(bh) { continue; } for row_off in (0..bh).step_by(tx) { for col_off in (0..bw).step_by(tx) { for &blk in &[ Reach { above_right: false, below_left: false, }, Reach { above_right: true, below_left: true, }, ] { let got = Reach::of_tu(bw, bh, col_off, row_off, tx, tx, blk); assert_eq!( got.above_right, libaom_tr(bw, bh, col_off, row_off, tx, blk.above_right), "above_right bw={bw} bh={bh} tx={tx} row_off={row_off} col_off={col_off} blk={blk:?}" ); assert_eq!( got.below_left, libaom_bl(bw, bh, col_off, row_off, tx, blk.below_left), "below_left bw={bw} bh={bh} tx={tx} row_off={row_off} col_off={col_off} blk={blk:?}" ); } } } } } } #[test] fn vert_ab_partition_flips_below_left_for_the_top_right_8x8() { let fctx = &crate::decode::FrameCtx::for_encoder(); let (width, height) = (SUPERBLOCK * 3, SUPERBLOCK * 3); let (sb_x, sb_y) = (SUPERBLOCK, SUPERBLOCK); let mut flipped = 0; for row in 0..8 { for col in 1..8 { let (x, y) = (sb_x + col * 8, sb_y + row * 8); let raster = Reach::of(8, x, y, width, height, fctx).below_left; let vert = { let _guard = Reach::vert_ab_partition(); Reach::of(8, x, y, width, height, fctx).below_left }; if row % 2 == 0 && col % 2 == 1 { assert!(!raster, "raster below_left at row={row} col={col}"); assert!(vert, "vert below_left at row={row} col={col}"); flipped += 1; } else { assert_eq!(raster, vert, "guard moved row={row} col={col}"); } } } assert_eq!(flipped, 4 * 4, "expected the 16 8x8 TR slots to flip"); assert!(!Reach::of(8, sb_x + 8, sb_y, width, height, fctx).below_left); } #[test] fn odd_dimensions_are_refused() { let fctx = &crate::decode::FrameCtx::for_encoder(); for &(width, height) in &[(1921usize, 1080usize), (1920, 1081), (63, 63)] { let picture = Picture::grey(width, height); let err = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx) .expect_err(&format!("{width}x{height} is odd and must be refused")); assert!( err.to_string().contains("even"), "{width}x{height}: error was {err}" ); } } #[test] fn sequence_round_trips_at_a_non_multiple_size() { let fctx = &crate::decode::FrameCtx::for_encoder(); let (width, height) = (160usize, 96usize); let pictures: Vec = (0..3) .map(|i| panned_test_card(width, height, i * 3)) .collect(); let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap(); assert_eq!(encoded.frames.len(), 3); for (i, frame) in encoded.frames.iter().enumerate() { assert_eq!( (frame.reconstruction.width, frame.reconstruction.height), (width, height), "frame {i}: reconstruction size" ); } assert_eq!( ffprobe_size(&encoded.stream), (width as u32, height as u32), "sequence: ffprobe reports the true (display) size" ); let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, 3); assert_eq!(decoded.len(), 3, "decoded frame count"); for (i, (frame, decoded)) in encoded.frames.iter().zip(&decoded).enumerate() { assert_eq!(decoded.y, frame.reconstruction.y, "frame {i}: luma"); assert_eq!(decoded.u, frame.reconstruction.u, "frame {i}: U"); assert_eq!(decoded.v, frame.reconstruction.v, "frame {i}: V"); } } #[test] fn a_sequence_round_trips_at_the_exactly_half_straddle_size() { let fctx = &crate::decode::FrameCtx::for_encoder(); let (width, height) = (1280usize, 720usize); let pictures: Vec = (0..3) .map(|i| panned_test_card(width, height, i * 3)) .collect(); let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap(); assert_eq!(encoded.frames.len(), 3); for (i, frame) in encoded.frames.iter().enumerate() { assert_eq!( (frame.reconstruction.width, frame.reconstruction.height), (width, height), "frame {i}: reconstruction size" ); } assert_eq!( ffprobe_size(&encoded.stream), (width as u32, height as u32), "ffprobe reports the true (display) 1280x720 size" ); let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, 3); assert_eq!(decoded.len(), 3, "decoded frame count"); for (i, (frame, decoded)) in encoded.frames.iter().zip(&decoded).enumerate() { assert_eq!(decoded.y, frame.reconstruction.y, "frame {i}: luma"); assert_eq!(decoded.u, frame.reconstruction.u, "frame {i}: U"); assert_eq!(decoded.v, frame.reconstruction.v, "frame {i}: V"); } } #[test] fn key_frame_and_inter_frame_both_encode_at_half_straddle_size() { let fctx = &crate::decode::FrameCtx::for_encoder(); let (width, height) = (640usize, 360usize); let picture = Picture::grey(width, height); encode_key_frame_with_ctx(&picture, 100, 0.5, fctx) .expect("key frame now codes the mod-32==8 straddle"); let pictures = vec![picture.clone(), picture]; encode_sequence_with_ctx(&pictures, 100, 0.5, fctx) .expect("inter frame now codes the mod-32==8 straddle too"); } #[test] fn a_640x360_half_straddle_round_trips_through_ffmpeg_across_three_frames() { let fctx = &crate::decode::FrameCtx::for_encoder(); let (width, height) = (640usize, 360usize); for shift in [0i64, 7, 19] { let picture = panned_test_card(width, height, shift); let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap(); let decoded = ffmpeg_decode(&encoded.stream, width, height); assert_eq!(decoded.y, encoded.reconstruction.y, "shift {shift}: luma"); assert_eq!(decoded.u, encoded.reconstruction.u, "shift {shift}: U"); assert_eq!(decoded.v, encoded.reconstruction.v, "shift {shift}: V"); } } #[test] fn a_640x360_half_straddle_sequence_round_trips_through_ffmpeg() { let fctx = &crate::decode::FrameCtx::for_encoder(); let (width, height) = (640usize, 360usize); let pictures: Vec = (0..4) .map(|i| panned_test_card(width, height, i * 3)) .collect(); let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap(); assert_eq!(encoded.frames.len(), 4); let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, 4); assert_eq!(decoded.len(), 4, "decoded frame count"); for (i, (frame, decoded)) in encoded.frames.iter().zip(&decoded).enumerate() { assert_eq!(decoded.y, frame.reconstruction.y, "frame {i}: luma"); assert_eq!(decoded.u, frame.reconstruction.u, "frame {i}: U"); assert_eq!(decoded.v, frame.reconstruction.v, "frame {i}: V"); } } pub(super) fn first_difference(ours: &[u16], theirs: &[u16], width: usize) -> Option { if let Some(i) = ours.iter().zip(theirs).position(|(a, b)| a != b) { let differ = ours.iter().zip(theirs).filter(|(a, b)| a != b).count(); return Some(format!( "{differ} samples differ, first at ({}, {}): ours {} theirs {}", i % width, i / width, ours[i], theirs[i] )); } if ours.len() != theirs.len() { return Some(format!( "no sample in the shared prefix differs, but ours is {} samples and theirs is {}", ours.len(), theirs.len() )); } None } #[test] fn every_mode_decodes_to_what_the_encoder_predicted() { let fctx = &crate::decode::FrameCtx::for_encoder(); for (width, height) in [(128, 96), (160, 96)] { let picture = test_card(width, height); for mode in KEY_FRAME_MODES { let encoded = encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &[mode], fctx).unwrap(); let decoded = ffmpeg_decode(&encoded.stream, width, height); for (plane, ours, theirs, stride) in [ ("luma", &encoded.reconstruction.y, &decoded.y, width), ("U", &encoded.reconstruction.u, &decoded.u, width / 2), ("V", &encoded.reconstruction.v, &decoded.v, width / 2), ] { assert!( first_difference(ours, theirs, stride).is_none(), "{width}x{height} mode {mode}, {plane}: {}", first_difference(ours, theirs, stride).unwrap() ); } } } } pub(super) fn diagonal(width: usize, height: usize, down_right: bool) -> Picture { let mut picture = Picture::grey(width, height); for y in 0..height { for x in 0..width { let along = if down_right { x + height - y } else { x + y }; picture.y[y * width + x] = if (along / 6) % 2 == 0 { 40 } else { 210 }; } } picture } pub(super) fn favourite_mode( picture: &Picture, fctx: &crate::decode::FrameCtx, ) -> (u8, usize, usize) { let encoded = encode_key_frame_with_ctx(picture, 100, 0.5, fctx).unwrap(); let blocks = &encoded.modes[1..]; let mut counts = [0usize; 13]; for &mode in blocks { counts[usize::from(mode)] += 1; } let (mode, count) = counts .iter() .enumerate() .max_by_key(|&(_, count)| *count) .expect("thirteen modes"); (mode as u8, *count, blocks.len()) } #[test] fn the_search_picks_the_diagonal_the_picture_runs() { let fctx = &crate::decode::FrameCtx::for_encoder(); for (down_right, want) in [(true, D135_PRED), (false, D45_PRED)] { let picture = diagonal(160, 96, down_right); let (mode, count, blocks) = favourite_mode(&picture, fctx); assert_eq!( mode, want, "down_right={down_right}: {count} of {blocks} blocks picked mode {mode}" ); } } #[test] fn a_mode_the_encoder_cannot_predict_is_refused() { let fctx = &crate::decode::FrameCtx::for_encoder(); let picture = test_card(64, 64); let message = encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &[13], fctx) .unwrap_err() .to_string(); assert!( message.contains("intra mode 13"), "the refusal must name the mode, got {message}" ); assert!(encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &[], fctx).is_err()); } #[test] fn the_encoded_picture_is_the_one_that_went_in() { let fctx = &crate::decode::FrameCtx::for_encoder(); let picture = test_card(160, 96); let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap(); let luma = psnr(&encoded.reconstruction.y, &picture.y); assert!(luma > 36.0, "luma PSNR {luma} at q 100"); for (plane, (got, want)) in [ (encoded.reconstruction.u.as_slice(), picture.u.as_slice()), (encoded.reconstruction.v.as_slice(), picture.v.as_slice()), ] .iter() .enumerate() { let chroma = psnr(got, want); assert!(chroma > 40.0, "chroma plane {plane} PSNR {chroma} at q 100"); } } #[test] fn fidelity_and_rate_move_with_the_quantizer() { let fctx = &crate::decode::FrameCtx::for_encoder(); let picture = test_card(128, 128); let mut previous: Option<(usize, f64)> = None; for &q in &[70u8, 90, 110] { let encoded = encode_key_frame_with_ctx(&picture, q, 0.5, fctx).unwrap(); let quality = psnr(&encoded.reconstruction.y, &picture.y); if let Some((bytes, better)) = previous { assert!( encoded.stream.len() < bytes, "q {q}: {} bytes", encoded.stream.len() ); assert!(quality < better, "q {q}: PSNR {quality}"); } previous = Some((encoded.stream.len(), quality)); } for &(lo, hi) in &[(20u8, 21u8), (60, 61), (120, 121)] { let lo_bytes = encode_key_frame_with_ctx(&picture, lo, 0.5, fctx) .unwrap() .stream .len(); let hi_bytes = encode_key_frame_with_ctx(&picture, hi, 0.5, fctx) .unwrap() .stream .len(); assert!( hi_bytes as f64 <= lo_bytes as f64 * 1.10, "q {lo}->{hi} crosses a context boundary: {lo_bytes} -> {hi_bytes} bytes" ); } } #[test] fn a_flat_picture_costs_almost_nothing() { let fctx = &crate::decode::FrameCtx::for_encoder(); let mut picture = Picture::grey(128, 128); picture.y.fill(97); let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap(); assert!( encoded.stream.len() < 100, "{} bytes for a flat picture", encoded.stream.len() ); for (i, &s) in encoded.reconstruction.y.iter().enumerate().skip(32 * 128) { assert_eq!(s, 97, "sample {i} of a flat picture"); } } #[test] fn a_picture_off_the_block_grid_encodes_and_a_malformed_one_is_refused() { let fctx = &crate::decode::FrameCtx::for_encoder(); encode_key_frame_with_ctx(&Picture::grey(40, 40), 100, 0.5, fctx) .expect("40x40 cuts a 16x16 leaf on both axes, which is an inferred split"); encode_key_frame_with_ctx(&Picture::grey(36, 40), 100, 0.5, fctx) .expect("36 luma columns still round up to an even MiCols"); let mut short = Picture::grey(64, 64); short.u.truncate(10); assert!(encode_key_frame_with_ctx(&short, 100, 0.5, fctx).is_err()); } #[test] fn a_single_axis_straddle_round_trips_through_ffmpeg() { let fctx = &crate::decode::FrameCtx::for_encoder(); let (width, height) = (40usize, 32usize); let picture = test_card(width, height); let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap(); assert_eq!( (encoded.reconstruction.width, encoded.reconstruction.height), (width, height) ); let decoded = ffmpeg_decode(&encoded.stream, width, height); assert_eq!(decoded.y, encoded.reconstruction.y, "luma"); assert_eq!(decoded.u, encoded.reconstruction.u, "U"); assert_eq!(decoded.v, encoded.reconstruction.v, "V"); } pub(super) fn panned_test_card(width: usize, height: usize, shift: i64) -> Picture { let mut picture = Picture::grey(width, height); for y in 0..height { for x in 0..width { let sx = (x as i64 - shift).rem_euclid(width as i64) as f64; let gradient = sx * 200.0 / width as f64; let ripple = 30.0 * (sx * std::f64::consts::PI / 23.0).sin() * (y as f64 * std::f64::consts::PI / 37.0).cos(); let edge = if sx > (width * 3 / 7) as f64 && y > height / 3 { 40.0 } else { 0.0 }; picture.y[y * width + x] = (20.0 + gradient + ripple + edge).clamp(0.0, 255.0) as u16; } } for y in 0..height / 2 { for x in 0..width / 2 { let sx = (x as i64 - shift / 2).rem_euclid((width / 2) as i64) as usize; let i = y * width / 2 + x; picture.u[i] = (100 + (sx * 60 / (width / 2))) as u16; picture.v[i] = (200 - (y * 80 / (height / 2))) as u16; } } picture } pub(super) fn ffmpeg_decode_sequence( stream: &[u8], width: usize, height: usize, frames: usize, ) -> Vec { let out = run_with_stdin( ec_testkit::ffmpeg().args([ "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-", ]), stream, ); assert!( out.status.success(), "ffmpeg refused the stream: {}", String::from_utf8_lossy(&out.stderr) ); let (luma, chroma) = (width * height, width * height / 4); let frame_bytes = luma + 2 * chroma; assert_eq!( out.stdout.len(), frame_bytes * frames, "expected {frames} 4:2:0 frames, ffmpeg said: {}", String::from_utf8_lossy(&out.stderr) ); (0..frames) .map(|i| { let base = i * frame_bytes; Picture { width, height, y: out.stdout[base..base + luma] .iter() .map(|&v| u16::from(v)) .collect(), u: out.stdout[base + luma..base + luma + chroma] .iter() .map(|&v| u16::from(v)) .collect(), v: out.stdout[base + luma + chroma..base + frame_bytes] .iter() .map(|&v| u16::from(v)) .collect(), } }) .collect() } #[test] fn every_frame_of_a_sequence_decodes_to_what_the_encoder_reconstructed() { let fctx = &crate::decode::FrameCtx::for_encoder(); let (width, height) = (128usize, 64usize); let pictures: Vec = (0..5) .map(|i| panned_test_card(width, height, i * 3)) .collect(); let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap(); assert_eq!(encoded.frames.len(), 5); let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, 5); assert_eq!( encoded.frames.len(), decoded.len(), "frame count: ours vs ffmpeg" ); for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() { assert_eq!(dec.y, frame.reconstruction.y, "frame {i}: luma"); assert_eq!(dec.u, frame.reconstruction.u, "frame {i}: U"); assert_eq!(dec.v, frame.reconstruction.v, "frame {i}: V"); } eprintln!("frame bytes luma PSNR (dB) inter share"); for (i, frame) in encoded.frames.iter().enumerate() { eprintln!( "{i:5} {:5} {:14.2} {:11.2}", frame.stream.len(), psnr(&frame.reconstruction.y, &pictures[i].y), frame.inter_block_share ); } }