use super::*; use super::tests::*; use crate::intra::{D45_PRED, NON_DIRECTIONAL}; use std::process::Command; /// 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(); if !have_ffmpeg() { eprintln!("SKIP: no ffmpeg"); return; } 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 = Command::new("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); } /// Step (2) of the pricer lane: the same census, but on the REAL clips /// the BD gate scores -- one film clip and the screen capture -- so the /// question the film/screen split raises can be answered from data. Real /// tables (`EC_AV1_PRICE_FRAME_CDFS=1`) make both film clips smaller and /// the screen capture larger, and the census says why: on a screen /// capture the frame's own starting tables are the tables of a frame that /// coded PALETTE and long runs of zero blocks, so they are far from the /// tables the writer ends the frame with; the pricer error does not fall /// the way it does on film. /// /// Not a gate -- it prints. Run it once per mode: /// EC_AV1_PRICE_FRAME_CDFS=0 cargo test -p ec-av1 --release --lib -- \ /// --ignored pricer_error_census_on_clips --nocapture #[test] #[ignore = "reads the real library, needs ffmpeg"] fn pricer_error_census_on_clips() { let _knobs = crate::speed::knob_write(); if !have_ffmpeg() { eprintln!("SKIP pricer_error_census_on_clips: no ffmpeg"); return; } // lane-av1clipprobe: the crate's one fixture root (EC_FIXTURES first), // so this probe reads the same tree the preflight validates. Its // `assert!(!clips.is_empty())` below was already a hard failure, so no // skip shape changes here — only the root does. let fixtures = crate::library_fixture::root(); let mut clips: Vec<(String, std::path::PathBuf)> = Vec::new(); let film = fixtures.join("video/h264-1080p-23.976-8bit.mp4"); if film.exists() { clips.push(("film 1080p".to_string(), film)); } if let Ok(manifest) = std::fs::read_to_string(fixtures.join("real-library-manifest.tsv")) && let Some(p) = manifest .lines() .skip(1) .filter_map(|l| l.split('\t').next()) .find(|p| { p.contains("/OBS/") && p.ends_with(".mkv") && std::path::Path::new(p).exists() }) { clips.push(("screen".to_string(), std::path::PathBuf::from(p))); } assert!(!clips.is_empty(), "no source clip available"); let (width, height, frames) = (640usize, 384usize, 6usize); for (name, path) in &clips { let fctx = &crate::decode::FrameCtx::for_encoder(); let source = clip_frames(path.to_str().unwrap(), "0", width, height, frames); SCREEN_FRAMES.iter().for_each(|c| { c.store(0, std::sync::atomic::Ordering::Relaxed); }); let _ = crate::tile::take_pricing_hits(); crate::tile::pricer_census_on(); let _ = encode_sequence_with_ctx(&source, 100, 0.5, fctx).unwrap(); let rows = crate::tile::take_pricer_census(); let (price_default, price_real) = crate::tile::take_pricing_hits(); let screen_on = SCREEN_FRAMES[1].load(std::sync::atomic::Ordering::Relaxed); println!( "\n## {name} ({frames} frames at {width}x{height}, q=100): screen frames \ {screen_on}, pricer armings default={price_default} real={price_real}" ); 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, "{name}: the census saw no transform block" ); } } /// 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" ); } /// A manual perf probe, not a gate: prints where a key frame's and an /// inter frame's time goes, coarse stage by coarse stage, so a perf lane /// measures before it optimizes rather than guessing. Run with /// `cargo test -p ec-av1 --release stage_timing_breakdown -- --ignored --nocapture`. #[test] #[ignore = "a perf probe, not a gate"] fn stage_timing_breakdown() { let _knobs = crate::speed::knob_read(); let fctx = &crate::decode::FrameCtx::for_encoder(); use std::time::Instant; for &(width, height) in &[(1920usize, 1080usize), (3840, 2160)] { let picture = test_card(width, height); let t = Instant::now(); let dc_only = encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &[DC_PRED], fctx).unwrap(); let dc_only_t = t.elapsed(); let t = Instant::now(); let non_directional = encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &NON_DIRECTIONAL, fctx) .unwrap(); let non_directional_t = t.elapsed(); let t = Instant::now(); let all_modes = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap(); let all_modes_t = t.elapsed(); eprintln!( "\n=== key frame {width}x{height} ===\n\ 1 mode (DC only): {dc_only_t:>9.2?} ({} bytes)\n\ 7 modes (non-directional): {non_directional_t:>9.2?} ({} bytes)\n\ 13 modes (default search): {all_modes_t:>9.2?} ({} bytes)", dc_only.stream.len(), non_directional.stream.len(), all_modes.stream.len(), ); // One inter frame predicting off the key frame's own // reconstruction, the (256, 256)-padded surface encode_sequence // itself would hand encode_inter_frame. let padded_ref = all_modes.reconstruction.padded_to(SUPERBLOCK); let padded_pic = picture.padded_to(SUPERBLOCK); let t = Instant::now(); let inter = encode_inter_frame( &padded_pic, &padded_ref, 100, 0.5, 1, flat_order_hints(1, 0, false), (width, height), None, None, None, None, fctx, None, &[], ) .unwrap(); let inter_t = t.elapsed(); eprintln!( "inter frame vs its own key frame: {inter_t:>9.2?} ({} bytes, inter share \ {:.2})", inter.stream.len(), inter.inter_block_share ); } // Isolated per-call cost of the trial pipeline's own stages, at both // transform sizes the search runs, averaged over enough calls to // rise above `Instant::now`'s own noise. for side in [16usize, 32] { const N: u32 = 20_000; let residual: Vec = (0..side * side) .map(|i| ((i * 37 % 61) as i32) - 30) .collect(); let t = Instant::now(); let mut levels = Vec::new(); for _ in 0..N { levels = forward_and_quantize(&residual, side, 8, 100, 0.5); } let forward_t = t.elapsed() / N; let t = Instant::now(); for _ in 0..N { std::hint::black_box(crate::transform::dequant_and_inverse(&levels, side, 8, 100)); } let inverse_t = t.elapsed() / N; let set = if side == 32 { crate::cdf_state::TxbSet::Luma32 } else { crate::cdf_state::TxbSet::Luma16 }; let t = Instant::now(); for _ in 0..N { std::hint::black_box(crate::tile::coeff_bits(&levels, set, 2, 0, 0)); } let entropy_t = t.elapsed() / N; let above = vec![128u8; side * 2]; let left = vec![128u8; side * 2]; let mut prediction = vec![0u8; side * side]; let t = Instant::now(); for _ in 0..N { intra_predict_u8( D45_PRED, 0, Some(&above), Some(&left), Some(128), side, side, false, false, &mut prediction, fctx, ); } let predict_t = t.elapsed() / N; eprintln!( "\n=== per-call cost at {side}x{side}, averaged over {N} calls ===\n\ predict (1 directional mode): {predict_t:>9.2?}\n\ forward_and_quantize: {forward_t:>9.2?}\n\ dequant_and_inverse: {inverse_t:>9.2?}\n\ coeff_bits: {entropy_t:>9.2?}" ); } } /// Breaks one inter frame's own cost into the four [`STAGE_NS`] buckets /// plus what is left over once buckets 0/2/3 are subtracted. /// /// lane-av1probes: the two search-shaped buckets OVERLAP and the old /// print denied it. Bucket 0 is not "the motion search": `stage_since(0, /// ..)` fires only after `find_best_new_mv` and the global-MV search /// (`encode.rs:11959`, `:12080`), so it is the NEWMV/GLOBAL sub-search /// alone. Bucket 1 is EVERY `crate::mc::predict` call, from the search's /// candidates *and* from a committed inter block's final prediction -- /// and that final prediction runs OUTSIDE any bucket-0 region. So bucket 1 /// is neither inside bucket 0 nor smaller than it, and a print that shows /// it as "motion search (of which interpolation ...)" necessarily shows /// a sub-number bigger than its parent. Measured: bucket 0 = 17.82 ms, /// bucket 1 = 148.63 ms. /// /// Which number is real: BOTH timers are right; only the old ARITHMETIC /// was wrong. Bucket 1 is now printed as its own top-level row, the /// overlap is stated, and the residual is labelled for what it is -- it /// absorbs the committed block's own interpolation, so it is not a pure /// "13-mode intra candidate loop" figure either. /// /// `cargo test -p ec-av1 --release stage_timing_breakdown_inter -- --ignored --nocapture`. #[test] #[ignore = "a perf probe, not a gate"] fn stage_timing_breakdown_inter() { let _knobs = crate::speed::knob_read(); let fctx = &crate::decode::FrameCtx::for_encoder(); use std::time::Instant; let (width, height) = (1280usize, 720); let picture = test_card(width, height); let key = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap(); let padded_ref = key.reconstruction.padded_to(SUPERBLOCK); let padded_pic = picture.padded_to(SUPERBLOCK); stage_reset(); let t = Instant::now(); let inter = encode_inter_frame( &padded_pic, &padded_ref, 100, 0.5, 1, flat_order_hints(1, 0, false), (width, height), None, None, None, None, fctx, None, &[], ) .unwrap(); let total_t = t.elapsed(); let [motion_search, interpolation, transform_quant, entropy] = stage_read(); // Buckets 0 and 2 and 3 are disjoint and additive. Bucket 1 (every // `mc::predict` call) is NOT added: it overlaps bucket 0 wherever a // search candidate calls predict, and it also covers the committed // block's final prediction, which no other bucket times. Adding it // would double-count the overlap; leaving it out puts the committed // prediction (and the intra candidate loop, RD glue, and the symbol // lookups outside `coeff_bits`) into the residual, which is what the // residual has always been. let accounted = motion_search + transform_quant + entropy; let other = total_t.saturating_sub(accounted); let overlap = interpolation.saturating_sub(motion_search); eprintln!( "\n=== inter frame {width}x{height}, one frame ===\n\ total: {total_t:>9.2?} ({} bytes)\n\ NEWMV/GLOBAL sub-search (bucket 0): {motion_search:>9.2?}\n\ transform + quantize (bucket 2): {transform_quant:>9.2?}\n\ coeff_bits, entropy pricing (bucket 3): {entropy:>9.2?}\n\ buckets 0+2+3 accounted: {accounted:>9.2?}\n\ \n\ OVERLAPPING, not additive: every mc::predict call (bucket 1) {interpolation:>9.2?}\n\ \x20 -- of which {overlap:>9.2?} is OUTSIDE bucket 0 (a committed\n\ \x20 inter block's final prediction, which no bucket above times)\n\ \x20 and the rest is the search candidates' interpolation, already\n\ \x20 inside bucket 0. It is deliberately NOT added to the total.\n\ \n\ residual (13-mode intra candidate loop, the committed block's\n\ \x20 interpolation above, NEARESTMV's own predict, RD glue): {other:>9.2?}", inter.stream.len(), ); } /// The quality gate [`Search::top_k`]'s lever lives or dies by: three real /// frames (a dark/flat one, a detailed one, a normal film one) at two /// `base_q_idx` values, encoded with the mode search unpruned (`top_k = /// None`, the baseline this same build produces without /// `EC_AV1_PRUNE_K` set) and with it pruned to each of a few `K`, bytes /// and luma PSNR compared side by side. Not a gate itself -- the numbers /// go in the lane report, which is where "ship as default" is decided -- /// so it stays `#[ignore]`, run by hand with real clips on this machine. /// `cargo test -p ec-av1 --release prune_k_quality_sweep -- --ignored --nocapture`. #[test] // The three clip paths are HARD-CODED ABSOLUTES under /home/user, not // env-driven: off this workstation every row prints `SKIP