use super::*; use super::tests::*; /// lane-ab128: the 128 root's four AB shapes -- `PARTITION_HORZ_A` (two /// 64x64 on top, one 128x64 below), `_HORZ_B`, `_VERT_A`, `_VERT_B`. /// Five passes over the same `testsrc2` clip /// `a_128_root_horz_and_vert_halves_decode_exact_through_both_decoders` /// uses: each shape forced at every root ([`force_b128_ab`]), so every /// context and every visit order the shape reads is exercised rather than /// the handful the RD would pick, and then an UNFORCED pass whose /// per-shape count is REPORTED (it is the number the gate rows are read /// against). /// /// Each pass is sample-exact against the encoder's own reconstruction /// through `decode_stream` AND through ffmpeg; a writer/reader mismatch /// surfaces here as a refusal or a pixel miss, never in the BD gate. RED /// before this lane by construction: `write_sb128_root` could only name /// NONE / HORZ / VERT / SPLIT, so all four counts were 0. /// /// Runs only inside `superblock_size_global_suite`. pub(super) fn a_128_root_ab_shapes_decode_exact_through_both_decoders() { let _knobs = crate::speed::knob_write(); force_sb128(true); let dir = std::env::temp_dir().join(format!("ec-av1-ab128-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); let clip = dir.join("testsrc2-1280x768.y4m"); let ok = ec_testkit::ffmpeg() .args(["-v", "error", "-y", "-f", "lavfi"]) .args(["-i", "testsrc2=size=1280x768:rate=24"]) .args(["-frames:v", "12", "-pix_fmt", "yuv420p"]) .arg(&clip) .status() .expect("ffmpeg failed to run") .success(); assert!(ok, "ffmpeg could not write the synthetic clip"); let (width, height) = (1280usize, 768usize); let pictures = crate::probe::source(clip.to_str().unwrap(), "0", "null", width, height, 12); let names = ["HORZ_A", "HORZ_B", "VERT_A", "VERT_B"]; let mut unforced = [0usize; 4]; for force in [4u8, 5, 6, 7, 0] { force_b128_ab(force); let label = if force == 0 { "unforced" } else { names[usize::from(force) - 4] }; let _ = take_b128_ab_hits(); let _ = crate::tile::take_sb128_ab_hits(); let encoded = encode_sequence(&pictures, 150, 0.5).unwrap(); let won = take_b128_ab_hits(); let coded = crate::tile::take_sb128_ab_hits(); eprintln!( "{label}: search won {won:?} AB roots, writer coded {coded:?} \ (HORZ_A/HORZ_B/VERT_A/VERT_B)" ); if force == 0 { // The unforced counts are REPORTED, not asserted: a zero here // would be an RD result, not a defect (the four forced passes // already prove the writer and the reader agree on the shape). unforced = won; } else { let i = usize::from(force) - 4; assert!( coded[i] > 0, "no {label} root was coded with {label} forced" ); } let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder"); assert_eq!(decoded.len(), encoded.frames.len(), "{label}: frame count"); for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() { for (plane, got, want) in [ ("luma", &dec.y, &frame.reconstruction.y), ("U", &dec.u, &frame.reconstruction.u), ("V", &dec.v, &frame.reconstruction.v), ] { let differ = got.iter().zip(want.iter()).filter(|(a, b)| a != b).count(); assert_eq!( differ, 0, "{label} frame {i}: {plane} -- {differ} samples differ" ); assert_eq!( got.len(), want.len(), "{label} frame {i}: {plane} is {} samples, the reconstruction's is {}", got.len(), want.len() ); } } let ff = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len()); assert_eq!( encoded.frames.len(), ff.len(), "{label}: frame count: ours vs ffmpeg" ); for (i, (frame, dec)) in encoded.frames.iter().zip(&ff).enumerate() { assert_eq!( dec.y, frame.reconstruction.y, "{label} frame {i}: ffmpeg luma" ); assert_eq!(dec.u, frame.reconstruction.u, "{label} frame {i}: ffmpeg U"); assert_eq!(dec.v, frame.reconstruction.v, "{label} frame {i}: ffmpeg V"); } } force_b128_ab(0); eprintln!( "unforced on testsrc2 over 12 frames: {} HORZ_A + {} HORZ_B + {} VERT_A + {} VERT_B", unforced[0], unforced[1], unforced[2], unforced[3], ); } #[test] fn every_frame_of_a_sequence_decodes_through_our_own_decoder() { let _knobs = crate::speed::knob_read(); let fctx = &crate::decode::FrameCtx::for_encoder(); // 256x128, not the 128x64 this started at: once a leaf could search // its second reference (lane-av1comp4) the small card's every // eligible block went to a compound winner, which commits its flat // transform, and the split below stopped firing on content that // still splits at every larger size ([[gate-blind-to-feature]] -- // the guard is right, the fixture had shrunk under it). let (width, height) = (256usize, 128usize); let pictures: Vec = (0..5) .map(|i| panned_test_card(width, height, i * 3)) .collect(); let _ = take_inter_tx_split_hits(); let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap(); let raw = take_inter_tx_split_hits(); // Summed over the four block classes the census keys on (leaf/32x32 x // single/compound): this assert is about the split firing at all. let split = [ raw.iter().step_by(2).sum::(), raw.iter().skip(1).step_by(2).sum::(), ]; eprintln!("inter var-tx: {} blocks flat, {} split", split[0], split[1]); // [[gate-blind-to-feature]]: with inter `TxMode::Select` on, this // content splits -- a green round trip in which the split never fires // would prove only the flat path. if tx_select() && tx_select_inter() { assert!(split[1] > 0, "the inter var-tx split never fired"); } let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder"); assert_eq!(decoded.len(), encoded.frames.len(), "frame count"); for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() { let recon = &frame.reconstruction; for (plane, got, want, stride) in [ ("luma", &dec.y, &recon.y, width), ("U", &dec.u, &recon.u, width / 2), ("V", &dec.v, &recon.v, width / 2), ] { assert_eq!(got.len(), want.len(), "frame {i}: {plane} size"); if let Some(at) = got.iter().zip(want).position(|(a, b)| a != b) { panic!( "frame {i}: {plane} differs first at ({}, {}): decoded {} vs \ reconstruction {} ({} of {} samples differ)", at % stride, at / stride, got[at], want[at], got.iter().zip(want).filter(|(a, b)| a != b).count(), got.len(), ); } } } } /// The rate term the mode search ranks every decision by has to be the /// rate the writer then spends. The search prices a block's coefficients /// through `tile::coeff_bits` -- the writer's own symbol chain, but /// against the default CDFs a tile starts from and the contexts of a /// block whose neighbours coded nothing -- while the tile writer codes /// them against a state that has been adapting all frame (the /// price-the-narrowing class). This measures that drift: the sum of what /// the search paid for the coefficients it kept, against the bytes the /// writer actually emitted for the whole tile (which also carries the /// partition/mode/skip/mv syntax the sum leaves out, so the writer is /// expected to be the larger of the two). #[test] fn predicted_coeff_bits_track_the_tile_the_writer_wrote() { let _knobs = crate::speed::knob_read(); let fctx = &crate::decode::FrameCtx::for_encoder(); let (width, height) = (256usize, 128usize); let pictures: Vec = (0..5) .map(|i| panned_test_card(width, height, i * 2)) .collect(); let _ = take_predicted_bits(); let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap(); let predicted = take_predicted_bits(); assert_eq!(predicted.len(), encoded.frames.len()); eprintln!("frame predicted bits written bits drift"); // Split by sign: a NEGATIVE drift is the search OVER-pricing (the // defect this gate exists to catch), a positive one is the written // side carrying syntax the coefficient sum leaves out -- and since // lane-av1mv an extra reference's `NEWMV` puts a whole MV residual // on that side, so the two directions no longer share a bound. let mut worst_over: f64 = 0.0; let mut worst_under: f64 = 0.0; // The census is per CODED frame, so it is zipped in coding order -- // which is not display order under a pyramid. let coded: Vec<&Encoded> = encoded .coding_order .iter() .map(|&i| &encoded.frames[i]) .collect(); for (i, (frame, &bits)) in coded.into_iter().zip(&predicted).enumerate() { let written = frame.tile.len() as f64 * 8.0; let drift = (written - bits) / written; worst_over = worst_over.max(-drift); // lane-av1pyrdef: a pyramid LEAF codes almost no coefficients at // all (150-250 bits of tile, nearly all of it partition/mode/mv // syntax the coefficient sum never counts), so its ratio measures // that floor rather than any drift. Frames under 512 written bits // are left out of the under-price bound for that reason; the // over-price bound -- the defect direction, where the search pays // MORE than the writer -- still covers every frame. if written >= 512.0 { worst_under = worst_under.max(drift); } eprintln!( "{i:5} {bits:14.0} {written:12.0} {:+6.2}%", drift * 100.0 ); } // Measured 2026-09-06 on this sequence: -13.5% at the key frame, // -8.1%, -3.8%, -2.1%, +1.8% down the inter frames. The search // over-prices every frame but the last (its sum EXCLUDES the // partition/mode/skip/mv syntax the written side carries, so the true // coefficient over-price is larger still): the writer's CDFs adapt to // the content while the search's stay at the defaults. The bound is // set just above the worst measured point -- a widening drift is the // thing this gate exists to catch. assert!( worst_over <= 0.16, "the search's rate term OVER-priced by {:.2}% against the bits the writer spent", worst_over * 100.0 ); // Measured 2026-09-06 with the extra-reference `NEWMV` in: +18.9% at // the worst inter frame, where nearly every block now codes an MV // residual and a reference the coefficient sum never counts. Re-measured // at +29.6% once the encoder's grid published compound blocks properly // (compound share 8.8% -> 11.5%): a compound block carries a second // reference tree, a compound mode symbol and -- for the half-new modes // -- an MV residual, none of which the coefficient sum counts. // lane-av1txbits: pricing against the tables the frame's writer really // starts from collapses the over-price above to nothing, so the whole // remaining gap is the syntax the coefficient sum leaves out. That is // the default on a non-screen frame since lane-av1price2 (this // fixture is one), and it reads +32.6% here. // lane-av1obmc: every eligible single-reference inter block now also // carries a `motion_mode` symbol the coefficient sum never counts, // and an OBMC block carries the more expensive of the two values -- // re-measured at +35.0% here with `EC_AV1_OBMC=1`. Like // `EC_AV1_PRICE_FRAME_CDFS=1` before it, that knob changes encoder // decisions, so this bound and the byte pins above FAIL BY DESIGN // under it; the default path (no motion_mode syntax at all) is the // one they are measured on. // lane-av1pyrdef: `encode_sequence` codes this fixture under the // coding pyramid now, so the five frames are a key frame, a hidden // ALTREF at q-16 and three leaves at q+8: +2.6% / +6.9% (the two // frames over the 512-bit floor) and +44.7 / +74.4 / +74.4 on the // near-empty leaves below it. Both bounds stand where they were. // lane-av1rejudge: local warp is ON by default now, so every eligible // single-reference block carries that same `motion_mode` symbol (a // 3-value alphabet where a warp sample exists) on the DEFAULT path -- // +34.9% here, one point past the OBMC reading above. The bound moves // with it; `EC_AV1_WARP=0` restores the +32.6% no-motion_mode number. // lane-av1cfl: a `UV_CFL_PRED` block carries a `cfl_alpha_signs` // symbol and one or two magnitude symbols, none of which the // coefficient sum counts either -- +36.9% here against the same // fixture's +34.9% with `EC_AV1_CFL=0`. // ... and a directional block whose `angle_delta_y` is no longer // always ZERO codes a costlier symbol off the same CDF -- +39.1%. assert!( worst_under <= 0.40, "the writer spent {:.2}% more than the search priced -- more than \ the mode/mv syntax outside the coefficient sum explains", worst_under * 100.0 ); } /// The census behind step (1) of the pricer lane: for every transform /// block the writer really codes, what the search priced those levels at /// against what the writer spent on them, split by table set and non-zero /// count. One average hides the interesting part -- the classes the /// estimate is systematically wrong about (all-zero blocks, the /// one-coefficient blocks the inter search lives on) -- so the split is /// printed and only the total is asserted on. #[test] fn pricer_error_census_by_block_class() { let _knobs = crate::speed::knob_read(); let fctx = &crate::decode::FrameCtx::for_encoder(); let (width, height) = (256usize, 128usize); let pictures: Vec = (0..5) .map(|i| panned_test_card(width, height, i * 2)) .collect(); crate::tile::pricer_census_on(); let _ = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap(); let rows = crate::tile::take_pricer_census(); assert!(!rows.is_empty(), "the census saw no transform block"); println!("| set | nz | blocks | priced bits | written bits | error |"); println!("|---|---|---|---|---|---|"); let (mut priced_all, mut written_all) = (0.0, 0.0); for ((set, bucket), (blocks, priced, written)) in &rows { priced_all += priced; written_all += written; println!( "| {set} | {} | {blocks} | {priced:.0} | {written:.0} | {:+.1}% |", crate::tile::census_bucket_label(*bucket), if *written > 0.0 { (priced - written) / written * 100.0 } else { 0.0 } ); } println!( "| ALL | | {} | {priced_all:.0} | {written_all:.0} | {:+.1}% |", rows.values().map(|r| r.0).sum::(), (priced_all - written_all) / written_all * 100.0 ); assert!(written_all > 0.0); } /// Low motion has to actually buy something: at least one inter frame of /// a panning sequence has to cost fewer bytes than the key frame that /// starts it, and the inter-block share it prints has to be non-zero -- /// a search that never picks an inter mode would still pass a rate gate /// on a picture with no motion in it (the class this repo calls /// gate-blind-to-feature), so the share is printed even though it is not /// asserted on beyond being reachable at all. #[test] fn low_motion_makes_an_inter_frame_smaller_than_the_key_frame() { let _knobs = crate::speed::knob_read(); let fctx = &crate::decode::FrameCtx::for_encoder(); let (width, height) = (256usize, 128usize); let pictures: Vec = (0..5) .map(|i| panned_test_card(width, height, i * 2)) .collect(); let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap(); let key_bytes = encoded.frames[0].stream.len(); eprintln!("frame bytes inter share"); for (i, frame) in encoded.frames.iter().enumerate() { eprintln!( "{i:5} {:5} {:11.2}", frame.stream.len(), frame.inter_block_share ); } assert!( encoded.frames[1..] .iter() .any(|f| f.stream.len() < key_bytes), "no inter frame of a panning sequence beat the key frame's {key_bytes} bytes" ); assert!( encoded.frames[1..] .iter() .any(|f| f.inter_block_share > 0.0), "no inter frame coded a single inter block -- the search never fired" ); } /// `frames` consecutive pictures out of a real clip, scaled to a whole /// number of 32x32 blocks. Generalizes [`clip_frame`]/[`clip_frame_pair`] /// to an arbitrary count for the fixture regression gate below. pub(super) fn clip_frames( clip: &str, skip: &str, width: usize, height: usize, frames: usize, ) -> Vec { clip_frames_vf( clip, skip, &format!("scale={width}:{height}"), width, height, frames, ) } /// [`clip_frames`] with the filter chain spelled out, so a caller can ask /// for a native-resolution CROP instead of a downscale (the downscale is /// what destroys a screen capture's exact repeats -- class /// `gate-recipe-confound`). `width`/`height` must be what `vf` produces. pub(super) fn clip_frames_vf( clip: &str, skip: &str, vf: &str, width: usize, height: usize, frames: usize, ) -> Vec { // ONE definition of the gate's loader recipe, shared with // `examples/enc_probe` so the instrument cannot arm a different source // than the gate it reports on (class `instrument disagrees with the // gate`; lane-probe). crate::probe::source(clip, skip, vf, width, height, frames) } // ----------------------------------------------------------------------- // The encoder's standing BD-rate baseline against libaom and rav1e. // Every PSNR below is measured on FFMPEG-DECODED pixels, never on an // encoder's own reconstruction ([[shared-oracle-blindness]]): our decoder // agreeing with our encoder proves nothing about the bitstream. // ----------------------------------------------------------------------- /// All-plane PSNR of a decoded picture against its source, on the same /// 8-bit scale [`psnr`] uses. pub(super) fn psnr_all(decoded: &Picture, source: &Picture) -> f64 { let cat = |p: &Picture| { let mut v = Vec::with_capacity(p.y.len() + p.u.len() + p.v.len()); v.extend_from_slice(&p.y); v.extend_from_slice(&p.u); v.extend_from_slice(&p.v); v }; psnr(&cat(decoded), &cat(source)) } /// The pictures back as the planar 8-bit bytes an encoder reads. pub(super) fn raw_yuv420p(source: &[Picture]) -> Vec { let mut raw = Vec::new(); for p in source { for plane in [&p.y, &p.u, &p.v] { raw.extend(plane.iter().map(|&s| s as u8)); } } raw } /// A (all-plane PSNR, log10 bytes) ladder from another AV1 encoder driven /// through ffmpeg: one point per entry of `points`, each a quality flag /// set. Returns the ladder ordered by fidelity and the total encode wall /// clock. The stream is decoded back through [`ffmpeg_decode_sequence`], /// so both curves are measured by the same decoder. pub(super) fn external_ladder( source: &[Picture], width: usize, height: usize, encoder: &str, points: &[Vec], ) -> (Vec<(f64, f64)>, f64) { // [[pid-keyed-temp-path]]: parallel test binaries must not share a name. let dir = std::env::temp_dir(); let raw_path = dir.join(format!("ec-av1-bd-{}-{encoder}.yuv", std::process::id())); std::fs::write(&raw_path, raw_yuv420p(source)).expect("raw source"); let mut ladder = Vec::new(); let mut wall = 0.0; for (i, params) in points.iter().enumerate() { let obu = dir.join(format!( "ec-av1-bd-{}-{encoder}-{i}.obu", std::process::id() )); let start = std::time::Instant::now(); let out = ec_testkit::ffmpeg() .args(["-v", "error", "-y", "-f", "rawvideo", "-pix_fmt", "yuv420p"]) .args(["-s", &format!("{width}x{height}"), "-r", "24", "-i"]) .arg(&raw_path) .args(["-an", "-threads", "1"]) .args(["-g", &source.len().to_string(), "-c:v", encoder]) .args(params) .args(["-f", "obu"]) .arg(&obu).output() .expect("ffmpeg failed to run"); wall += start.elapsed().as_secs_f64(); assert!( out.status.success(), "{encoder} {params:?}: {}", String::from_utf8_lossy(&out.stderr) ); let stream = std::fs::read(&obu).expect("reference stream"); let decoded = ffmpeg_decode_sequence(&stream, width, height, source.len()); // lane-dkey: every reference point must also decode through OUR // decoder, sample-exact against ffmpeg's decode of the same bytes. // A BD table computed off streams we cannot read is a table about // an encoder we cannot check; this is the assertion that would // have caught the `force_integer_mv` defect (its stream decoded to // 25 dB garbage while this gate stayed green) and the crf-5 key // frame desync. A failure names the encoder, the point's flags and // the first differing frame/plane/sample. // lane-dpm1: a failing reference point is COLLECTED, not panicked // on, so one run still prints the whole BD table and names every // bad point instead of stopping at the first. The collection is // asserted empty by [`assert_ladder_decodes`] at the end of each // gate. match crate::stream::decode_stream(&stream) { Ok(ours) if ours.len() != decoded.len() => note_ladder_failure(format!( "{encoder} {params:?}: our decoder returned {} shown frames, ffmpeg {}", ours.len(), decoded.len(), )), Ok(ours) => { for (f, (o, d)) in ours.iter().zip(&decoded).enumerate() { if let Some((plane, s, got, want)) = first_plane_mismatch(o, d) { note_ladder_failure(format!( "{encoder} {params:?} frame {f} plane {plane} sample {s}: our \ decoder decoded {got}, ffmpeg {want}" )); break; } } } Err(e) => note_ladder_failure(format!( "{encoder} {params:?}: our decoder refused the stream ({e})" )), } let mean: f64 = decoded .iter() .zip(source) .map(|(d, s)| psnr_all(d, s)) .sum::() / source.len() as f64; ladder.push((mean, (stream.len() as f64).log10())); let _ = std::fs::remove_file(&obu); } let _ = std::fs::remove_file(&raw_path); ladder.sort_by(|a, b| a.0.total_cmp(&b.0)); (ladder, wall) } /// Every reference ladder point that did not decode sample-exactly /// through our own decoder, collected across a whole gate run so the BD /// table still prints and EVERY bad point is named /// (`encoder params frame plane sample`) instead of only the first. static LADDER_FAILURES: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); pub(super) fn note_ladder_failure(msg: String) { eprintln!("LADDER DECODE FAILURE: {msg}"); LADDER_FAILURES.lock().expect("ladder failures").push(msg); } /// Fail the gate at its END on everything [`external_ladder`] collected. pub(super) fn assert_ladder_decodes() { let failures = std::mem::take(&mut *LADDER_FAILURES.lock().expect("ladder failures")); assert!( failures.is_empty(), "{} reference ladder point(s) did not decode exactly through our decoder:\n{}", failures.len(), failures.join("\n"), ); } /// First differing sample between two pictures, as /// `(plane, index, left, right)` -- so a gate failure names the plane and /// the sample instead of just "differs". A length difference counts as a /// mismatch of that plane at the first index past the shorter one. pub(super) fn first_plane_mismatch(a: &Picture, b: &Picture) -> Option<(&'static str, usize, i64, i64)> { for (plane, l, r) in [("Y", &a.y, &b.y), ("U", &a.u, &b.u), ("V", &a.v, &b.v)] { if let Some(i) = l.iter().zip(r.iter()).position(|(x, y)| x != y) { return Some((plane, i, i64::from(l[i]), i64::from(r[i]))); } if l.len() != r.len() { return Some((plane, l.len().min(r.len()), l.len() as i64, r.len() as i64)); } } None } /// The same ladder for this encoder, at four `base_q_idx` points. The PSNR /// comes from ffmpeg's decode of our own stream, and at EVERY point the /// stream is decoded twice -- by ffmpeg and by our own /// [`crate::stream::decode_stream`] -- and all three pictures (encoder /// reconstruction, ffmpeg's decode, our decode) are asserted sample-exact /// in Y, U and V over every shown frame in display order. That is itself /// a gate: it proves the bitstream says what the encoder thinks, in the /// only two decoders that read it. pub(super) fn our_ladder( name: &str, source: &[Picture], width: usize, height: usize, fctx: &crate::decode::FrameCtx, ) -> (Vec<(f64, f64)>, f64) { let mut ladder = Vec::new(); let mut wall = 0.0; for &q in &[150u8, 120, 90, 60] { let start = std::time::Instant::now(); // lane-rdoq: the deadzone was fitted WITHOUT the RDOQ pass, so // the gate has to be able to re-sweep it. 0.5 is the shipped one // (`crate::encoder::DEADZONE`). let deadzone = std::env::var("EC_AV1_DEADZONE") .ok() .and_then(|v| v.parse().ok()) .unwrap_or(0.5); let encoded = encode_sequence_with_ctx(source, q, deadzone, fctx).unwrap(); wall += start.elapsed().as_secs_f64(); let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, source.len()); let ours = crate::stream::decode_stream(&encoded.stream).expect("our decoder"); assert_eq!( ours.len(), source.len(), "{name} q={q}: our decoder's display-order frame count" ); for (i, (d, e)) in decoded.iter().zip(&encoded.frames).enumerate() { if let Some((plane, s, got, want)) = first_plane_mismatch(d, &e.reconstruction) { panic!( "{name} q={q} frame {i} plane {plane} sample {s}: ffmpeg decoded \ {got}, the encoder reconstructed {want}" ); } } for (i, (o, e)) in ours.iter().zip(&encoded.frames).enumerate() { if let Some((plane, s, got, want)) = first_plane_mismatch(o, &e.reconstruction) { panic!( "{name} q={q} frame {i} plane {plane} sample {s}: our decoder decoded \ {got}, the encoder reconstructed {want}" ); } } let per_frame: Vec = decoded .iter() .zip(source) .map(|(d, s)| psnr_all(d, s)) .collect(); // lane-txrd: does a tool's loss start at the FIRST inter frame // (a local mispricing) or grow down the GOP (propagation into // the reference chain)? One line per q point answers it. if crate::envflags::env_flag!("EC_AV1_FRAME_PSNR") { let row: Vec = per_frame.iter().map(|p| format!("{p:.2}")).collect(); eprintln!("{name}: q={q} per-frame PSNR {}", row.join(" ")); // lane-txrd: per PLANE, because an all-plane mean hides a // collapse in one of them (class `metric blind to a plane`). let plane = |pick: fn(&Picture) -> &Vec| -> String { let v: Vec = decoded .iter() .zip(source) .map(|(d, s)| format!("{:.2}", psnr(pick(d), pick(s)))) .collect(); v.join(" ") }; eprintln!("{name}: q={q} Y {}", plane(|p| &p.y)); eprintln!("{name}: q={q} U {}", plane(|p| &p.u)); eprintln!("{name}: q={q} V {}", plane(|p| &p.v)); } let mean: f64 = per_frame.iter().sum::() / source.len() as f64; ladder.push((mean, (encoded.stream.len() as f64).log10())); } // What this clip asked for and what the content gate left it coding // under: a screen clip requests a pyramid and codes flat, and that // difference is what keeps its row identical to the flat baseline // (class `gate-blind-to-feature`). eprintln!( "{name}: sequence, pyramid requested {:?} effective {:?}", crate::encoder::Pyramid::from_env(), last_sequence_pyramid(), ); ladder.sort_by(|a, b| a.0.total_cmp(&b.0)); (ladder, wall) } /// [`our_ladder`] through the streaming facade — the surface the editor's /// export drives (`EC_AV1_GATE_FACADE=1`). With a [`crate::encoder::Pyramid`] /// each stream is also reordered (hidden `ALTREF` first, /// `show_existing_frame` last per group) and each level is coded at its /// own quantizer offset; without one it is the flat ladder, which /// `encoder::tests::the_facade_codes_the_same_bytes_as_encode_sequence` /// pins byte-identical to [`our_ladder`]'s, so this arm must print the /// same BD numbers. Returns the ladder, the wall, per pyramid level over /// the whole ladder how many frames and how many bytes it spent, and the /// pyramid the streams were EFFECTIVELY coded under — the content gate in /// `Av1Encoder::encode_frames` drops a screen-content clip back to the /// flat path, so a requested pyramid can come back `None` here. pub(super) fn our_ladder_facade( name: &str, source: &[Picture], width: usize, height: usize, pyramid: Option, ) -> ( Vec<(f64, f64)>, f64, [usize; 4], [usize; 4], Option, ) { use crate::encoder::{Av1Encoder, Colour, EncoderConfig, Level}; let slot = |l: Level| match l { Level::Key => 0, Level::Arf => 1, Level::Leaf => 2, Level::ShowExisting => 3, }; let mut ladder = Vec::new(); let mut wall = 0.0; let mut effective = None; let (mut counts, mut bytes) = ([0usize; 4], [0usize; 4]); for &q in &[150u8, 120, 90, 60] { let config = EncoderConfig { width, height, base_q_idx: q, gop: source.len(), colour: Colour::Unspecified, tile_cols_log2: 0, tile_rows_log2: 0, }; let start = std::time::Instant::now(); let mut enc = match pyramid { None => Av1Encoder::new(config).unwrap(), Some(p) => Av1Encoder::with_pyramid(config, p).unwrap(), }; let mut packets = Vec::new(); for picture in source { packets.extend(enc.encode_frames(picture).unwrap()); } packets.extend(enc.flush().unwrap()); wall += start.elapsed().as_secs_f64(); effective = enc.pyramid(); let mut stream = Vec::new(); for p in &packets { counts[slot(p.level)] += 1; bytes[slot(p.level)] += p.data.len(); stream.extend_from_slice(&p.data); } // [[gate-blind-to-hidden-frames]]: a reordered stream is only // correct if the DISPLAY-order output still has one frame per // source picture, in the right order -- checked against our own // decoder as well as ffmpeg's, both below. let ours = crate::stream::decode_stream(&stream).expect("our decoder"); assert_eq!( ours.len(), source.len(), "{name} q={q}: our display-order count" ); let decoded = ffmpeg_decode_sequence(&stream, width, height, source.len()); for (i, (d, o)) in decoded.iter().zip(&ours).enumerate() { if let Some((plane, s, got, want)) = first_plane_mismatch(d, o) { panic!( "{name} q={q} display frame {i} plane {plane} sample {s}: ffmpeg \ decoded {got}, our decoder decoded {want}" ); } } let mean: f64 = decoded .iter() .zip(source) .map(|(d, s)| psnr_all(d, s)) .sum::() / source.len() as f64; ladder.push((mean, (stream.len() as f64).log10())); } ladder.sort_by(|a, b| a.0.total_cmp(&b.0)); (ladder, wall, counts, bytes, effective) } /// Byte-exactness gate for encoder work that is meant to change only /// how long the encoder takes. /// /// The BD gate above measures quality, which a speed lane can move by a /// hair without failing anything; this pins the streams themselves. /// Re-measured on the lane-av1lr merge with main d5fc99e0 (per-64x64 /// `cdef_idx` literals and per-unit loop restoration syntax are new bits /// in the tile) and again on lane-av1mv's merge of it: an extra /// reference's `NEWMV` is a coded-bits change too, judged by the BD gate /// above, not by this pin. Re-pinned on lane-av1price2: the search now /// prices coefficients against the tables the frame's writer really /// starts from on every non-screen frame (`tile::arm_pricing_cdfs`), a /// decision change the BD gate judges. Re-pinned again on /// lane-av1skipctx: the search now prices `txb_skip`/`dc_sign` at the /// real neighbour contexts ([`Plane::coef_ctx`]) instead of zero, which /// is the same kind of decision change. Re-pinned on lane-av1lambda: /// [`LAMBDA_SCALE`] moved 0.1 -> 0.05, so every RD decision in the /// search moved with it. Re-pinned on lane-av1rejudge: local warp is on /// by default ([`warp_on`], a sequence/frame header bit and a new /// motion_mode symbol on eligible blocks) and /// [`LEAF_SECOND_NEW_MARGIN`] moved 0.8 -> 1.2. Re-pinned on lane-av1tpl: /// every inter frame's superblocks now code at their own lambda /// ([`TPL_STRENGTH`]), so every RD decision in an inter frame moved. /// Re-pinned on lane-av1resweep: [`LAMBDA_SCALE`] moved 0.05 -> 0.0275 /// and the two var-tx depth searches ([`tx32_depth_search`], /// [`compound_var_tx`]) are on by default, all three re-judged on the /// native gate's real film rows. /// Re-pinned on lane-av1cfl: the chroma search offers `UV_CFL_PRED`, so /// every block whose chroma takes it codes a different mode symbol, two /// alpha symbols and different chroma coefficients. `EC_AV1_CFL=0` /// restores the previous streams. Re-pinned again in the same lane once /// directional luma winners searched their `angle_delta_y` /// (`EC_AV1_ANGLE=0` restores that half). #[test] fn the_encoders_own_streams_are_byte_identical_to_their_pins() { // These are DEFAULT-PRESET pins: a speed preset switches search levers // off, so it legitimately moves every byte. Encode at speed 0 whatever // `EC_AV1_SPEED` says (write guard: the preset is process-global). let _knobs = crate::speed::knob_write(); let was = crate::speed::speed(); crate::speed::set_speed(0); // lane-av1clipprobe: the bare `clip.exists()` -> SKIP had no env escape, // so a tree with no root `fixtures/` reported this gate green having // compared nothing at all. let clip = ec_testkit::fixture("open/sintel_trailer-1080p.mp4"); let source = clip_frames(clip.to_str().unwrap(), "20", 640, 384, 4); // FNV-1a over the stream: a witness that every coded bit is where it // was, which a byte count alone is not. let fnv = |b: &[u8]| { b.iter().fold(0xcbf2_9ce4_8422_2325u64, |h, &v| { (h ^ u64::from(v)).wrapping_mul(0x0000_0100_0000_01b3) }) }; // Re-taken on lane-av1pyrdef: `encode_sequence` codes this (non-screen) // clip under the coding pyramid now -- one hidden ALTREF per mini-GOP // of 4, its leaves at q+8 and a `show_existing_frame` header per // group. 7299 -> 8194 bytes at q=150 and 26804 -> 28285 at q=60 over // four frames; four pictures is one short mini-GOP, which is the // shape that pays least (the ARF's own quality has no later group to // carry it), so this is not the BD gate's number. // Re-taken again on lane-av1cfl: the chroma search offers // `UV_CFL_PRED` and directional luma winners search `angle_delta_y`, // so every block taking either codes different syntax and different // coefficients -- 8194 -> 7321 at q=150 and 28285 -> 27285 at q=60. // `EC_AV1_CFL=0` / `EC_AV1_ANGLE=0` restore each half. // Re-taken on lane-pyr3: the mini-GOP of the default pyramid is 16 // pictures at `q-24` / `q+16` now (the sweep in [`Pyramid::default`]), // so these four pictures code as one truncated group -- a hidden // ALTREF at `q-24` and three leaves at `q+16` -- instead of one // mini-GOP of 4 at `q-16` / `q+8`: 7373 -> 8076 at q=150 and // 27074 -> 27585 at q=60. `EC_AV1_PYRAMID=4:-16:8` restores these. // Re-taken on lane-fintra: the sequence header sets // `enable_filter_intra`, so every DC_PRED intra block of at most // 32x32 without a luma palette carries a `use_filter_intra` flag and // the blocks that take one code a filter-intra mode, a different // prediction and different coefficients -- 7321 -> 7373 at q=150 and // 27285 -> 27074 at q=60. `EC_AV1_FILTER_INTRA=0` restores these. // Re-taken on lane-b64 (64x64 skip root), at the lane-pyr4 merge // (default pyramid `8:-32:16`, one truncated group of 8 with its // hidden ALTREF at `q-32`), and at the lane-tx64 merge: the 64x64 // root can code a REAL residual now (one TX_64X64 luma transform and // two TX_32X32 chroma ones). `EC_AV1_B64RES=0` restores 8446 / 28548; // `EC_AV1_B64=0` gives the pre-root bytes under this pyramid. // Re-taken on lane-keyq: the pyramid codes its KEY FRAME at // `base_q - 48` now ([`crate::encoder::Pyramid::key_q_offset`]), and // one of these four pictures is the key -- 8590 -> 9778 at q=150 and // 28535 -> 35450 at q=60. `EC_AV1_PYRAMID=8:-32:16:-8:0` restores these. // Re-taken on lane-arfq: the leaves are coded 12 quantizer steps above // base now, not 16 ([`crate::encoder::Pyramid::leaf_q_offset`]) -- 9778 // -> 9835 at q=150 and 35450 -> 35798 at q=60. // `EC_AV1_PYRAMID=8:-32:16:-8:-48` restores these. // Re-taken at the lane-b64b merge, the lane-rdoq merge (`EC_AV1_RDOQ=0` // gave 9808 / 35791) and the lane-i64 merge: the KEY frame -- one of // these four pictures -- offers every superblock a 64x64 intra root // now. `EC_AV1_I64=0` restores 8557 / 33345. // Re-taken on lane-pricer: the inter RD search prices a single // reference through the tree and the neighbour contexts the writer // really codes it with, so every inter picture's reference decisions // move -- 8562 -> 8535 at q=150 and 33357 -> 33221 at q=60. // Re-taken on lane-ctx: the RD pricer reads the writer's own contexts // for `skip`/`is_inter` and for the whole compound reference tree, so // every inter block's cost -- and with it the skip and reference // decisions -- moved: 8535 -> 8311 bytes at q=150 and 33221 -> 33087 // at q=60. Re-taken on lane-ctx2: a single-reference candidate now // pays the `comp_mode = 0` symbol the writer codes ahead of it, so // single and compound are priced against the same syntax -- 8311 -> // 8325 bytes at q=150 and 33087 -> 33014 at q=60. // Re-taken on lane-newmv: the motion search charges its own rate term // at half the block RD lambda ([`crate::motion::MV_SEARCH_LAMBDA`]) // and each subpel stage re-runs from its own winner // ([`crate::motion::MV_SUBPEL_ITERS`]), so every inter block's vector // -- and with it its residual -- moved: 8325 -> 8288 bytes at q=150 // and 33014 -> 33090 at q=60. // Re-taken on lane-dq: preset 0 codes a per-superblock `delta_qindex` // from libaom's objective tpl mapping, so every inter picture's // quantizer grid -- and every decision priced against it -- moved // (8325 -> 8419 / 33014 -> 33029 on its own base); re-taken once more // at the merge of both lanes. // Re-taken on lane-arfq: the top ARF of a mini-GOP codes its // per-superblock `delta_qindex` at 1.5x the preset's strength // ([`crate::speed::DQ_LEVEL_K`]), so the hidden frames' quantizer // grids -- and every decision priced against them -- moved: // 8252 -> 8269 bytes at q=150 and 33053 -> 33044 at q=60. // Re-taken on lane-arfpred: the top ARF is coded from a temporally // FILTERED source ([`crate::speed::ARF_TF`]), so every hidden frame's // pixels -- and the leaves that predict from them -- moved: // 8269 -> 8218 bytes at q=150 and 33044 -> 33017 at q=60. // NOT re-taken on lane-b128: [`SB128_DEFAULT`] stayed off there, so // the shipped stream did not move. // Re-taken on lane-b128m, which flips [`SB128_DEFAULT`] on: every // picture is coded in 128x128 superblocks now, the inter ones // offering the 128 root's own `PARTITION_NONE` block -- 8327 bytes at // q=150 and 33194 at q=60. `EC_AV1_SB128=0` restores 8252 / 33053. // Re-taken at the merge of lane-b128m onto main (128 superblocks on // by default, on top of the ARF temporal filter). // Re-taken on lane-b128r: the 128 root now offers the COMPOUND // candidates the 64 root already did ([`b128_compound`]), so every // inter frame that carries `reference_select` codes different blocks // -- 8354 -> 8364 bytes at q=150 and 33222 -> 33257 at q=60. // `EC_AV1_B128COMP=0` restores 8354 / 33222 exactly. // Re-taken on lane-arftf: that filter's strength swept on the deciding // gate lands at 2, not 3 ([`crate::speed::ARF_TF`]), so the filtered // anchors' pixels moved once more: 8218 -> 8307 bytes at q=150 and // 33017 at q=60 (the same LENGTH, different bytes). // Re-taken at the merge of lane-arftf (ARF filter strength 2) and // lane-rlclamp onto the 128 compound default. // Re-taken on lane-b128hv: the 128 root now also offers PARTITION_HORZ // and PARTITION_VERT ([`b128_rect`]), two 128x64 / 64x128 skip blocks, // so every inter frame whose RD takes one codes a different partition // -- 8290 -> 8291 bytes at q=150. The q=60 pin does NOT move: at that // quantizer the rect cut never wins its own comparison on this clip. // `EC_AV1_B128HV=0` restores 8290 exactly. let pins: [(u8, usize, u64); 2] = [ (150, 8291, 0x1f00bb0eb099a27f), (60, 33227, 0x57ee6b1f8eacd881), ]; let coded: Vec<(u8, usize, u64)> = pins .iter() .map(|&(q, _, _)| { let e = encode_sequence(&source, q, 0.5).unwrap(); (q, e.stream.len(), fnv(&e.stream)) }) .collect(); crate::speed::set_speed(was); for (&(q, bytes, hash), &got) in pins.iter().zip(&coded) { assert_eq!(got, (q, bytes, hash), "q={q}: the encoder's stream moved"); } } /// A ladder is only a ladder if both axes rise together. pub(super) fn assert_monotone(name: &str, ladder: &[(f64, f64)]) { assert_eq!(ladder.len(), 4, "{name}: wanted four quality points"); for w in ladder.windows(2) { assert!( w[1].0 > w[0].0 && w[1].1 > w[0].1, "{name}: not monotone, {ladder:?}" ); } } /// Which var-tx depth this clip's INTER blocks resolved to (lane-av1tx2, /// split by block class in lane-av1txdepth): depth 0 is one transform over /// the whole block, 1 its four halves; the classes are the 16x16/8x8 /// leaves and the 32x32 root, each single-reference or compound. A class /// with no counts at all never reached `commit_inter_luma` -- which is /// what its knob being off looks like (class `gate-blind-to-feature`). pub(super) fn print_inter_tx_census(name: &str) { let splits = take_inter_tx_split_hits(); let total: usize = splits.iter().sum(); let row = |label: &str, base: usize| { let (n0, n1) = (splits[base], splits[base + 1]); format!( "{label} 0={n0} 1={n1} ({:.1}% split)", 100.0 * n1 as f64 / (n0 + n1).max(1) as f64 ) }; eprintln!( "{name}: inter var-tx depths of {total} blocks -- {} | {} | {} | {}", row("leaf single", 0), row("leaf compound", 2), row("32x32 single", 4), row("32x32 compound", 6), ); // lane-txrd: which types the two searches actually COMMITTED over // this row's four encodes -- the gate could not say whether a type // search fired at all (class `gate-blind-to-feature`). const NAMES: [&str; 16] = [ "IDTX", "DCT_DCT", "ADST_ADST", "ADST_DCT", "DCT_ADST", "V_DCT", "H_DCT", "FLIPADST_DCT", "DCT_FLIPADST", "FLIPADST_FLIPADST", "ADST_FLIPADST", "FLIPADST_ADST", "V_ADST", "H_ADST", "V_FLIPADST", "H_FLIPADST", ]; let name_of = |t: usize| NAMES[t]; for (label, hits) in [ ("inter", take_inter_tx_type_hits()), ("intra", take_tx_type_hits()), ] { let total: usize = hits.iter().sum(); let live: Vec = hits .iter() .enumerate() .filter(|&(_, &n)| n > 0) .map(|(t, &n)| { format!( "{}={n} ({:.1}%)", name_of(t), 100.0 * n as f64 / total.max(1) as f64 ) }) .collect(); eprintln!( "{name}: {label} tx_type of {total} units -- {}", live.join(" ") ); } let t = take_txrd_stats(); if t[0] > 0 { eprintln!( "{name}: txrd flat decisions={} chosen sse={} bits={:.0} | DCT_DCT sse={} \ bits={:.0} (dsse {:+.2}%, dbits {:+.2}%)", t[0], t[1], t[3] as f64 / 64.0, t[2], t[4] as f64 / 64.0, 100.0 * (t[1] as f64 - t[2] as f64) / t[2].max(1) as f64, 100.0 * (t[3] as f64 - t[4] as f64) / t[4].max(1) as f64, ); eprintln!( "{name}: txrd DCT_DCT re-predicted HERE sse={} bits={:.0} (vs the passed-in \ flat: dsse {:+.2}%, dbits {:+.2}%)", t[5], t[6] as f64 / 64.0, 100.0 * (t[5] as f64 - t[2] as f64) / t[2].max(1) as f64, 100.0 * (t[6] as f64 - t[4] as f64) / t[4].max(1) as f64, ); } } /// The video stream's coded size, from ffprobe. pub(super) fn probe_dims(clip: &str) -> Option<(usize, usize)> { crate::probe::dims(clip) } /// `EC_AV1_NATIVE_CROP=x`: the native gate's window at a /// size of the reader's choosing instead of [`crate::probe::gate_crop`]'s /// superblock-aligned one, still centred and still even for 4:2:0. /// /// WHY IT EXISTS (lane-sse): `gate_crop` rounds DOWN to whole 128-wide /// superblocks by design, so no default gate row has a block the frame /// edge cuts through -- while every arbitrary export size does (3840x1608 /// is 25.1 superblock rows, 1920x1080 is 8.4). `EC_AV1_NATIVE_CROP= /// 1920x1080` is the straddling arm the edge-clipped distortion score is /// read on. pub(super) fn native_crop_override(clip: &str) -> Option<(String, usize, usize)> { let spec = std::env::var("EC_AV1_NATIVE_CROP").ok()?; let (w, h) = spec .split_once('x') .expect("EC_AV1_NATIVE_CROP is x"); let (cw, ch): (usize, usize) = ( w.parse().expect("crop width"), h.parse().expect("crop height"), ); let (nw, nh) = crate::probe::dims(clip)?; assert!(cw <= nw && ch <= nh, "{cw}x{ch} does not fit in {nw}x{nh}"); let (x, y) = (((nw - cw) / 2) & !1, ((nh - ch) / 2) & !1); Some((format!("crop={cw}:{ch}:{x}:{y}"), cw, ch)) } /// The probe arms the gate's source (lane-probe, class `instrument /// disagrees with the gate`). `examples/enc_probe` built its own ffmpeg /// command line and had no `-ss`, so it read film B from frame 0 -- a /// black leader -- and coded 59 kB where the gate's own ladder point /// coded 89 kB of the same title; every census taken through it was /// probe-relative. Both now call [`crate::probe::source`]; this pins that /// the shared loader honours the seek (arming the probe's way and the /// gate's way gives byte-identical streams, and dropping the seek does /// not), on a synthetic clip whose content moves over time. #[test] fn the_probe_arms_the_gates_source() { let _knobs = crate::speed::knob_write(); let dir = std::env::temp_dir().join(format!("ec-av1-probe-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); let clip = dir.join("testsrc2.y4m"); // 384x202: neither side is a multiple of 128, so the gate's centre // window is a real derivation and not the frame itself -- exactly the // shape film B has (3840x1608, never 3840x2160). let ok = ec_testkit::ffmpeg() .args([ "-v", "error", "-y", "-f", "lavfi", "-i", "testsrc2=size=384x202:rate=10", ]) .args(["-frames:v", "20", "-pix_fmt", "yuv420p"]) .arg(&clip) .status() .expect("ffmpeg failed to run") .success(); assert!(ok, "ffmpeg could not write the synthetic clip"); let path = clip.to_str().unwrap(); // The window: superblock-aligned, centred, even offsets. let (vf, w, h) = crate::probe::gate_crop(path); assert_eq!((vf.as_str(), w, h), ("crop=384:128:0:36", 384, 128)); let (seek, q) = ("00:00:01", 150u8); let gate = clip_frames_vf(path, seek, &vf, w, h, 6); let probe = crate::probe::source(path, seek, &vf, w, h, 6); assert!( gate.iter() .zip(&probe) .all(|(a, b)| a.y == b.y && a.u == b.u && a.v == b.v), "the probe's source differs from the gate's at the same window" ); let bytes = |src: &[Picture]| { encode_sequence_with_ctx(src, q, 0.5, &crate::decode::FrameCtx::for_encoder()) .unwrap() .stream }; assert_eq!( bytes(&gate), bytes(&probe), "probe and gate code different bytes" ); // The two witnesses that both halves of the arming reach ffmpeg: the // seek, and the crop's own offset (the film-B defect in miniature -- // the probe was reading `crop=..:568` of a 1608-high frame). let unseeked = crate::probe::source(path, "0", &vf, w, h, 6); assert_ne!( bytes(&gate), bytes(&unseeked), "seeked and unseeked arming coded the same bytes -- the seek is inert" ); let offset = crate::probe::source(path, seek, "crop=384:128:0:0", w, h, 6); assert_ne!( bytes(&gate), bytes(&offset), "centred and top-aligned windows coded the same bytes -- the crop is inert" ); std::fs::remove_dir_all(&dir).ok(); } /// lane-refs: THE FRAME FILTER REACHES THE PIXELS. `mc::predict` used to /// hardwire the REGULAR kernel, so the encoder could not have coded a /// SMOOTH or SHARP frame even if the header had said so -- the search, /// the trials, the recon and the frame header now all read /// `FrameCtx::interp_filter`. Each of the three kernels codes its own /// distinct stream (a filter that never reached the prediction would code /// the same bytes as REGULAR, class `symbol consumption gap`), and ffmpeg /// reconstructs every frame of each of them exactly, which is what proves /// the header and the prediction agree. #[test] fn each_frame_interpolation_filter_codes_its_own_stream_ffmpeg_decodes_exactly() { let _knobs = crate::speed::knob_write(); let (width, height) = (256usize, 128usize); // A HALF-PEL pan: an integer-pel one reads no filter tap at all, so // all three kernels would code the same bytes and the test would pass // on a wiring that does nothing (class `fixture proves the symbol, not // the signal`). `panned_test_card` shifts by whole pixels, so the // search finds the sub-pel positions off the reconstruction instead: // three frames of a slow diagonal pan. let pictures: Vec = (0..3) .map(|i| panned_test_card(width, height, i * 3)) .collect(); let mut streams = Vec::new(); for filter in [ ec_av1_syntax::InterpolationFilter::Eighttap, ec_av1_syntax::InterpolationFilter::EighttapSmooth, ec_av1_syntax::InterpolationFilter::EighttapSharp, ] { set_frame_interp(Some(filter)); let fctx = &crate::decode::FrameCtx::for_encoder(); let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx) .unwrap_or_else(|e| panic!("{filter:?}: {e}")); let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, 3); assert_eq!(decoded.len(), 3, "{filter:?}: decoded frame count"); for (i, (frame, decoded)) in encoded.frames.iter().zip(&decoded).enumerate() { assert_eq!( decoded.y, frame.reconstruction.y, "{filter:?} frame {i}: luma" ); assert_eq!(decoded.u, frame.reconstruction.u, "{filter:?} frame {i}: U"); assert_eq!(decoded.v, frame.reconstruction.v, "{filter:?} frame {i}: V"); } streams.push((filter, encoded.stream)); } set_frame_interp(None); for (i, (fa, a)) in streams.iter().enumerate() { for (fb, b) in &streams[i + 1..] { assert_ne!(a, b, "{fa:?} and {fb:?} coded the same bytes"); } } } /// lane-hpmv: THE EIGHTH-PEL VECTOR REACHES THE STREAM. With /// `allow_high_precision_mv` off the writer refuses an odd eighth-pel /// residual outright (`round_to_valid_mv` rounds it away first), so the /// finest vector the encoder could commit to was a quarter pel. With the /// header bit on, the writer codes an `mv_hp`/`mv_class0_hp` symbol per /// non-zero component and the search's fourth stage refines to the /// eighth: this asserts ZERO hp symbols in the off arm, non-zero in the /// on arm, and -- the part that makes it a signal rather than a symbol /// count (class `fixture proves the symbol, not the signal`) -- that some /// of them come out ZERO, i.e. name a vector the off arm cannot code at /// all. Both streams are decoded by ffmpeg AND by this crate's own /// decoder and asserted sample-exact against the encoder's own /// reconstruction, which is what proves the header bit and the symbols /// agree. #[test] fn a_high_precision_frame_codes_eighth_pel_motion_vectors_both_decoders_read() { let _knobs = crate::speed::knob_write(); let (width, height) = (256usize, 128usize); let pictures: Vec = (0..3) .map(|i| panned_test_card(width, height, i * 3)) .collect(); let mut arms = Vec::new(); for hp in [false, true] { set_high_precision_mv(Some(hp)); let _ = crate::tile::take_hp_symbols(); let fctx = &crate::decode::FrameCtx::for_encoder(); let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx) .unwrap_or_else(|e| panic!("hp={hp}: {e}")); let (symbols, eighth) = crate::tile::take_hp_symbols(); let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len()); let ours = crate::stream::decode_stream(&encoded.stream).expect("our decoder"); assert_eq!(decoded.len(), pictures.len(), "hp={hp}: ffmpeg frame count"); assert_eq!( ours.len(), pictures.len(), "hp={hp}: our decoder frame count" ); for (i, e) in encoded.frames.iter().enumerate() { for (who, got) in [("ffmpeg", &decoded[i]), ("our decoder", &ours[i])] { if let Some((plane, s, got, want)) = first_plane_mismatch(got, &e.reconstruction) { panic!( "hp={hp} frame {i} plane {plane} sample {s}: {who} decoded {got}, \ the encoder reconstructed {want}" ); } } } arms.push((symbols, eighth, encoded.stream)); } set_high_precision_mv(None); let (off, on) = (&arms[0], &arms[1]); assert_eq!( off.0, 0, "a frame without the header bit codes no hp symbol" ); assert!( on.0 > 0, "a high-precision frame codes hp symbols (got {})", on.0 ); assert!( on.1 > 0, "a high-precision frame codes eighth-pel vectors ({} hp symbols, none of them zero)", on.0 ); assert_ne!(off.2, on.2, "the two arms coded the same bytes"); println!( "hp witness: off {} hp symbols / {} B, on {} hp symbols ({} eighth-pel) / {} B", off.0, off.2.len(), on.0, on.1, on.2.len() ); }