Merge branch 'lane-av1mv' (8f1e2498): NEWMV against GOLDEN/ALTREF with stack-seeded starts and a swept early-out
Browse files at this commit2 changed files +366 -66
- crates/ec-av1/src/encode.rs +199 -46
- crates/ec-av1/src/motion.rs +167 -20
crates/ec-av1/src/encode.rsmodified+199 -46
| @@ -165,6 +165,31 @@ fn split_inter_8() -> bool { | |||
| 165 | /// NEARESTMV candidate it always had. | 165 | /// NEARESTMV candidate it always had. |
| 166 | const LEAF_NEW_MV: bool = true; | 166 | const LEAF_NEW_MV: bool = true; |
| 167 | 167 | ||
| 168 | +/// Whether GOLDEN/ALTREF get a `NEWMV` search of their own. Measured on the | ||
| 169 | +/// BD gate: with the early-out below at its swept margin, -1.7/-2.5/-0.0 | ||
| 170 | +/// points vs libaom and -1.6/-2.3/-0.0 vs rav1e for 4%/4%/0.3% more motion | ||
| 171 | +/// searches (the census `bd_rate_vs_libaom_and_rav1e` prints). | ||
| 172 | +const EXTRA_REF_NEW_MV: bool = true; | ||
| 173 | + | ||
| 174 | +/// How much cheaper an extra reference's `NEARESTMV` has to be than LAST's | ||
| 175 | +/// own best vector before that reference's `NEWMV` search is skipped: a | ||
| 176 | +/// factor on the search cost scale, `1.0` meaning "as good or better". | ||
| 177 | +/// Swept on the BD gate over 0.15/0.25/0.35/0.5/0.8/1.0/1.5 and off (`0.0`, | ||
| 178 | +/// never skip): the whole BD gain survives down to 0.35 (+124.8/+150.4/+80.9 | ||
| 179 | +/// vs libaom, against +124.9/+150.3/+81.0 with no early-out at all) while the | ||
| 180 | +/// extra searches drop from +27% to +4% of the base count -- and on screen | ||
| 181 | +/// capture, where an extra reference's NEWMV wins nothing, it skips 99.7% of | ||
| 182 | +/// them. Below 0.35 the gain starts eroding (0.15: +125.3/+151.7). | ||
| 183 | +const EXTRA_NEW_SKIP_MARGIN: f64 = 0.35; | ||
| 184 | + | ||
| 185 | +/// [`EXTRA_NEW_SKIP_MARGIN`], swept by `EC_AV1_MV_SKIP_MARGIN`. | ||
| 186 | +fn extra_new_skip_margin() -> f64 { | ||
| 187 | + match std::env::var("EC_AV1_MV_SKIP_MARGIN").ok() { | ||
| 188 | + Some(v) if cfg!(test) => v.parse().unwrap_or(EXTRA_NEW_SKIP_MARGIN), | ||
| 189 | + _ => EXTRA_NEW_SKIP_MARGIN, | ||
| 190 | + } | ||
| 191 | +} | ||
| 192 | + | ||
| 168 | /// [`LEAF_NEW_MV`], or what `EC_AV1_LEAF_NEWMV` names in a test build. | 193 | /// [`LEAF_NEW_MV`], or what `EC_AV1_LEAF_NEWMV` names in a test build. |
| 169 | fn leaf_new_mv() -> bool { | 194 | fn leaf_new_mv() -> bool { |
| 170 | match std::env::var("EC_AV1_LEAF_NEWMV").ok() { | 195 | match std::env::var("EC_AV1_LEAF_NEWMV").ok() { |
| @@ -2337,6 +2362,7 @@ fn code_square_inter( | |||
| 2337 | let mut best = (inter_cost, None); | 2362 | let mut best = (inter_cost, None); |
| 2338 | if leaf_new_mv() { | 2363 | if leaf_new_mv() { |
| 2339 | let source_block = luma.source_block(x, y, side); | 2364 | let source_block = luma.source_block(x, y, side); |
| 2365 | + let (seeds, seed_n) = mv_seeds(stack); | ||
| 2340 | let found = motion::search( | 2366 | let found = motion::search( |
| 2341 | ref_luma.0, | 2367 | ref_luma.0, |
| 2342 | ref_luma.1, | 2368 | ref_luma.1, |
| @@ -2348,6 +2374,7 @@ fn code_square_inter( | |||
| 2348 | side, | 2374 | side, |
| 2349 | side, | 2375 | side, |
| 2350 | stack.pred_mv, | 2376 | stack.pred_mv, |
| 2377 | + &seeds[..seed_n], | ||
| 2351 | search.lambda, fctx, | 2378 | search.lambda, fctx, |
| 2352 | ); | 2379 | ); |
| 2353 | let new_mv = round_to_valid_mv(found.mv, stack.pred_mv); | 2380 | let new_mv = round_to_valid_mv(found.mv, stack.pred_mv); |
| @@ -3447,6 +3474,68 @@ fn mv_component_bits(diff: i32) -> Option<f64> { | |||
| 3447 | Some(bits) | 3474 | Some(bits) |
| 3448 | } | 3475 | } |
| 3449 | 3476 | ||
| 3477 | +/// Whether an extra reference (GOLDEN/ALTREF) is offered a `NEWMV` of its | ||
| 3478 | +/// own -- a second motion search per block against that reference's picture, | ||
| 3479 | +/// priced off that reference's own stack. `EC_AV1_MV_EXTRA_NEW=0` turns it | ||
| 3480 | +/// off in a test build (what the lane measured both arms with). | ||
| 3481 | +fn extra_ref_new_mv() -> bool { | ||
| 3482 | + match std::env::var("EC_AV1_MV_EXTRA_NEW").ok() { | ||
| 3483 | + Some(v) if cfg!(test) => v != "0", | ||
| 3484 | + _ => EXTRA_REF_NEW_MV, | ||
| 3485 | + } | ||
| 3486 | +} | ||
| 3487 | + | ||
| 3488 | +/// [`tile::write_drl_idx`]'s cost against one stack: one `drl_mode` symbol | ||
| 3489 | +/// per entry past `start`, `1` to advance and `0` to stop, at most two. | ||
| 3490 | +fn drl_bits_for(stack: &MvStack, start: usize, target: usize) -> f64 { | ||
| 3491 | + let mut bits = 0.0; | ||
| 3492 | + let mut idx = start; | ||
| 3493 | + while idx < start + 2 && stack.entries.len() > idx + 1 { | ||
| 3494 | + let advance = idx < target; | ||
| 3495 | + bits += symbol_bits(&cdf::DRL_MODE[stack.drl_ctx[idx]], usize::from(advance)); | ||
| 3496 | + if !advance { | ||
| 3497 | + break; | ||
| 3498 | + } | ||
| 3499 | + idx += 1; | ||
| 3500 | + } | ||
| 3501 | + bits | ||
| 3502 | +} | ||
| 3503 | + | ||
| 3504 | +/// The cheapest `(bits, drl index)` the `NEWMV` syntax can name `mv` with off | ||
| 3505 | +/// `stack`: each DRL entry is a different `PredMv` (spec 7.10.2.10 | ||
| 3506 | +/// `assign_mv`), so the same vector costs a different residual from each. | ||
| 3507 | +fn best_new_mv_syntax(stack: &MvStack, mv: (i32, i32)) -> Option<(f64, u8)> { | ||
| 3508 | + let mut best: Option<(f64, u8)> = None; | ||
| 3509 | + for idx in 0..3usize { | ||
| 3510 | + if idx > 0 && stack.entries.len() <= idx { | ||
| 3511 | + break; | ||
| 3512 | + } | ||
| 3513 | + let base = stack.entries.get(idx).map_or(stack.pred_mv, |e| e.mv); | ||
| 3514 | + if let Some(b) = mv_residual_bits(mv, base) { | ||
| 3515 | + let total = b + drl_bits_for(stack, 0, idx); | ||
| 3516 | + if best.is_none_or(|(t, _)| total < t) { | ||
| 3517 | + best = Some((total, idx as u8)); | ||
| 3518 | + } | ||
| 3519 | + } | ||
| 3520 | + } | ||
| 3521 | + best | ||
| 3522 | +} | ||
| 3523 | + | ||
| 3524 | +/// The starting points [`motion::search`] gets besides `stack.pred_mv`: the | ||
| 3525 | +/// zero vector and the stack's own candidates. A neighbour block's vector is | ||
| 3526 | +/// where this block's motion most often already is, which is what pays for | ||
| 3527 | +/// the extra starting points (measured on the BD gate: -0.9/-0.8/-0.0 points | ||
| 3528 | +/// vs libaom for 0.2 s off a 6 s ladder). | ||
| 3529 | +fn mv_seeds(stack: &MvStack) -> ([(i32, i32); 4], usize) { | ||
| 3530 | + let mut seeds = [(0, 0); 4]; | ||
| 3531 | + let mut n = 1; | ||
| 3532 | + for e in stack.entries.iter().take(3) { | ||
| 3533 | + seeds[n] = e.mv; | ||
| 3534 | + n += 1; | ||
| 3535 | + } | ||
| 3536 | + (seeds, n) | ||
| 3537 | +} | ||
| 3538 | + | ||
| 3450 | /// What [`crate::tile::write_mv`] (private to that module) would spend | 3539 | /// What [`crate::tile::write_mv`] (private to that module) would spend |
| 3451 | /// coding `mv` as a residual against `pred`: the joint symbol naming which | 3540 | /// coding `mv` as a residual against `pred`: the joint symbol naming which |
| 3452 | /// components differ, then each differing component. `None` under the same | 3541 | /// components differ, then each differing component. `None` under the same |
| @@ -3740,19 +3829,7 @@ fn search_inter_block( | |||
| 3740 | // past `start`, `1` to advance and `0` to stop, at most two. A `target` | 3829 | // past `start`, `1` to advance and `0` to stop, at most two. A `target` |
| 3741 | // the loop cannot reach is never offered below -- every candidate's | 3830 | // the loop cannot reach is never offered below -- every candidate's |
| 3742 | // index is one this same loop walks to. | 3831 | // index is one this same loop walks to. |
| 3743 | - let drl_bits = |start: usize, target: usize| { | 3832 | + let drl_bits = |start: usize, target: usize| drl_bits_for(stack, start, target); |
| 3744 | - let mut bits = 0.0; | ||
| 3745 | - let mut idx = start; | ||
| 3746 | - while idx < start + 2 && stack.entries.len() > idx + 1 { | ||
| 3747 | - let advance = idx < target; | ||
| 3748 | - bits += symbol_bits(&cdf::DRL_MODE[stack.drl_ctx[idx]], usize::from(advance)); | ||
| 3749 | - if !advance { | ||
| 3750 | - break; | ||
| 3751 | - } | ||
| 3752 | - idx += 1; | ||
| 3753 | - } | ||
| 3754 | - bits | ||
| 3755 | - }; | ||
| 3756 | let last_ref_bits = single_ref_bits(crate::mvstack::LAST_FRAME); | 3833 | let last_ref_bits = single_ref_bits(crate::mvstack::LAST_FRAME); |
| 3757 | let mut cands: Vec<((i32, i32), f64, InterInfo)> = vec![ | 3834 | let mut cands: Vec<((i32, i32), f64, InterInfo)> = vec![ |
| 3758 | ( | 3835 | ( |
| @@ -3797,6 +3874,7 @@ fn search_inter_block( | |||
| 3797 | } | 3874 | } |
| 3798 | 3875 | ||
| 3799 | let source_block = luma.source_block(x, y, BLOCK); | 3876 | let source_block = luma.source_block(x, y, BLOCK); |
| 3877 | + let (seeds, seed_n) = mv_seeds(stack); | ||
| 3800 | #[cfg(test)] | 3878 | #[cfg(test)] |
| 3801 | let t = std::time::Instant::now(); | 3879 | let t = std::time::Instant::now(); |
| 3802 | let found = motion::search( | 3880 | let found = motion::search( |
| @@ -3810,6 +3888,7 @@ fn search_inter_block( | |||
| 3810 | BLOCK, | 3888 | BLOCK, |
| 3811 | BLOCK, | 3889 | BLOCK, |
| 3812 | stack.pred_mv, | 3890 | stack.pred_mv, |
| 3891 | + &seeds[..seed_n], | ||
| 3813 | search.lambda, fctx, | 3892 | search.lambda, fctx, |
| 3814 | ); | 3893 | ); |
| 3815 | #[cfg(test)] | 3894 | #[cfg(test)] |
| @@ -3818,20 +3897,7 @@ fn search_inter_block( | |||
| 3818 | // Each DRL entry is a different `PredMv` (spec 7.10.2.10 `assign_mv`), so | 3897 | // Each DRL entry is a different `PredMv` (spec 7.10.2.10 `assign_mv`), so |
| 3819 | // the same vector costs a different residual from each: take the index | 3898 | // the same vector costs a different residual from each: take the index |
| 3820 | // whose residual plus DRL bits is cheapest, not entry 0 by default. | 3899 | // whose residual plus DRL bits is cheapest, not entry 0 by default. |
| 3821 | - let mut best_new: Option<(f64, u8)> = None; | 3900 | + if let Some((bits, ref_mv_idx)) = best_new_mv_syntax(stack, mv) { |
| 3822 | - for idx in 0..3usize { | ||
| 3823 | - if idx > 0 && stack.entries.len() <= idx { | ||
| 3824 | - break; | ||
| 3825 | - } | ||
| 3826 | - let base = stack.entries.get(idx).map_or(stack.pred_mv, |e| e.mv); | ||
| 3827 | - if let Some(b) = mv_residual_bits(mv, base) { | ||
| 3828 | - let total = b + drl_bits(0, idx); | ||
| 3829 | - if best_new.is_none_or(|(t, _)| total < t) { | ||
| 3830 | - best_new = Some((total, idx as u8)); | ||
| 3831 | - } | ||
| 3832 | - } | ||
| 3833 | - } | ||
| 3834 | - if let Some((bits, ref_mv_idx)) = best_new { | ||
| 3835 | cands.push(( | 3901 | cands.push(( |
| 3836 | mv, | 3902 | mv, |
| 3837 | last_ref_bits + symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 0) + bits, | 3903 | last_ref_bits + symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 0) + bits, |
| @@ -3844,7 +3910,7 @@ fn search_inter_block( | |||
| 3844 | )); | 3910 | )); |
| 3845 | } | 3911 | } |
| 3846 | 3912 | ||
| 3847 | - for &(ref_frame, _, gstack) in extra { | 3913 | + for &(ref_frame, g, gstack) in extra { |
| 3848 | let g_ref_bits = single_ref_bits(ref_frame); | 3914 | let g_ref_bits = single_ref_bits(ref_frame); |
| 3849 | let g_not_new = symbol_bits(&cdf::NEW_MV[gstack.new_mv_ctx], 1); | 3915 | let g_not_new = symbol_bits(&cdf::NEW_MV[gstack.new_mv_ctx], 1); |
| 3850 | cands.push(( | 3916 | cands.push(( |
| @@ -3870,6 +3936,67 @@ fn search_inter_block( | |||
| 3870 | ref_mv_idx: 0, | 3936 | ref_mv_idx: 0, |
| 3871 | }, | 3937 | }, |
| 3872 | )); | 3938 | )); |
| 3939 | + // A motion search of this reference's own: without it, GOLDEN/ALTREF | ||
| 3940 | + // can only be coded at a vector some neighbour already found, which | ||
| 3941 | + // is why they carried a third of the inter blocks at their two | ||
| 3942 | + // search-free modes alone. | ||
| 3943 | + // The search is skipped when this reference's own NEARESTMV already | ||
| 3944 | + // prices out `margin` times better than LAST's best vector does -- | ||
| 3945 | + // one candidate evaluation (`motion::cost_at`) standing in for a | ||
| 3946 | + // whole search of ~50. | ||
| 3947 | + let margin = extra_new_skip_margin(); | ||
| 3948 | + let skip_search = extra_ref_new_mv() | ||
| 3949 | + && margin > 0.0 | ||
| 3950 | + && motion::cost_at( | ||
| 3951 | + &g.y, | ||
| 3952 | + g.width, | ||
| 3953 | + luma.true_width, | ||
| 3954 | + luma.true_height, | ||
| 3955 | + &source_block, | ||
| 3956 | + x, | ||
| 3957 | + y, | ||
| 3958 | + BLOCK, | ||
| 3959 | + BLOCK, | ||
| 3960 | + gstack.nearest_mv, | ||
| 3961 | + gstack.pred_mv, | ||
| 3962 | + search.lambda, | ||
| 3963 | + fctx, | ||
| 3964 | + ) * margin | ||
| 3965 | + <= found.cost; | ||
| 3966 | + if extra_ref_new_mv() && !skip_search { | ||
| 3967 | + let (gseeds, gn) = mv_seeds(gstack); | ||
| 3968 | + #[cfg(test)] | ||
| 3969 | + let t = std::time::Instant::now(); | ||
| 3970 | + let gfound = motion::search( | ||
| 3971 | + &g.y, | ||
| 3972 | + g.width, | ||
| 3973 | + luma.true_width, | ||
| 3974 | + luma.true_height, | ||
| 3975 | + &source_block, | ||
| 3976 | + x, | ||
| 3977 | + y, | ||
| 3978 | + BLOCK, | ||
| 3979 | + BLOCK, | ||
| 3980 | + gstack.pred_mv, | ||
| 3981 | + &gseeds[..gn], | ||
| 3982 | + search.lambda, fctx, | ||
| 3983 | + ); | ||
| 3984 | + #[cfg(test)] | ||
| 3985 | + stage_add(0, t.elapsed()); | ||
| 3986 | + let gmv = round_to_valid_mv(gfound.mv, gstack.pred_mv); | ||
| 3987 | + if let Some((bits, ref_mv_idx)) = best_new_mv_syntax(gstack, gmv) { | ||
| 3988 | + cands.push(( | ||
| 3989 | + gmv, | ||
| 3990 | + g_ref_bits + symbol_bits(&cdf::NEW_MV[gstack.new_mv_ctx], 0) + bits, | ||
| 3991 | + InterInfo { | ||
| 3992 | + ref_frame, | ||
| 3993 | + mode: InterMode::NewMv, | ||
| 3994 | + mv: gmv, | ||
| 3995 | + ref_mv_idx, | ||
| 3996 | + }, | ||
| 3997 | + )); | ||
| 3998 | + } | ||
| 3999 | + } | ||
| 3873 | } | 4000 | } |
| 3874 | 4001 | ||
| 3875 | // One trial set per distinct (reference, vector) pair: sort, cheapest | 4002 | // One trial set per distinct (reference, vector) pair: sort, cheapest |
| @@ -6701,11 +6828,18 @@ mod tests { | |||
| 6701 | assert_eq!(predicted.len(), encoded.frames.len()); | 6828 | assert_eq!(predicted.len(), encoded.frames.len()); |
| 6702 | 6829 | ||
| 6703 | eprintln!("frame predicted bits written bits drift"); | 6830 | eprintln!("frame predicted bits written bits drift"); |
| 6704 | - let mut worst: f64 = 0.0; | 6831 | + // Split by sign: a NEGATIVE drift is the search OVER-pricing (the |
| 6832 | + // defect this gate exists to catch), a positive one is the written | ||
| 6833 | + // side carrying syntax the coefficient sum leaves out -- and since | ||
| 6834 | + // lane-av1mv an extra reference's `NEWMV` puts a whole MV residual | ||
| 6835 | + // on that side, so the two directions no longer share a bound. | ||
| 6836 | + let mut worst_over: f64 = 0.0; | ||
| 6837 | + let mut worst_under: f64 = 0.0; | ||
| 6705 | for (i, (frame, &bits)) in encoded.frames.iter().zip(&predicted).enumerate() { | 6838 | for (i, (frame, &bits)) in encoded.frames.iter().zip(&predicted).enumerate() { |
| 6706 | let written = frame.tile.len() as f64 * 8.0; | 6839 | let written = frame.tile.len() as f64 * 8.0; |
| 6707 | let drift = (written - bits) / written; | 6840 | let drift = (written - bits) / written; |
| 6708 | - worst = worst.max(drift.abs()); | 6841 | + worst_over = worst_over.max(-drift); |
| 6842 | + worst_under = worst_under.max(drift); | ||
| 6709 | eprintln!("{i:5} {bits:14.0} {written:12.0} {:+6.2}%", drift * 100.0); | 6843 | eprintln!("{i:5} {bits:14.0} {written:12.0} {:+6.2}%", drift * 100.0); |
| 6710 | } | 6844 | } |
| 6711 | // Measured 2026-09-06 on this sequence: -13.5% at the key frame, | 6845 | // Measured 2026-09-06 on this sequence: -13.5% at the key frame, |
| @@ -6717,9 +6851,18 @@ mod tests { | |||
| 6717 | // set just above the worst measured point -- a widening drift is the | 6851 | // set just above the worst measured point -- a widening drift is the |
| 6718 | // thing this gate exists to catch. | 6852 | // thing this gate exists to catch. |
| 6719 | assert!( | 6853 | assert!( |
| 6720 | - worst <= 0.16, | 6854 | + worst_over <= 0.16, |
| 6721 | - "the search's rate term drifted {:.2}% from the bits the writer spent", | 6855 | + "the search's rate term OVER-priced by {:.2}% against the bits the writer spent", |
| 6722 | - worst * 100.0 | 6856 | + worst_over * 100.0 |
| 6857 | + ); | ||
| 6858 | + // Measured 2026-09-06 with the extra-reference `NEWMV` in: +18.9% at | ||
| 6859 | + // the worst inter frame, where nearly every block now codes an MV | ||
| 6860 | + // residual and a reference the coefficient sum never counts. | ||
| 6861 | + assert!( | ||
| 6862 | + worst_under <= 0.22, | ||
| 6863 | + "the writer spent {:.2}% more than the search priced -- more than \ | ||
| 6864 | + the mode/mv syntax outside the coefficient sum explains", | ||
| 6865 | + worst_under * 100.0 | ||
| 6723 | ); | 6866 | ); |
| 6724 | } | 6867 | } |
| 6725 | 6868 | ||
| @@ -7482,18 +7625,11 @@ mod tests { | |||
| 7482 | /// | 7625 | /// |
| 7483 | /// The BD gate above measures quality, which a speed lane can move by a | 7626 | /// The BD gate above measures quality, which a speed lane can move by a |
| 7484 | /// hair without failing anything; this pins the streams themselves. | 7627 | /// hair without failing anything; this pins the streams themselves. |
| 7485 | - /// Re-measured on the lane-av1lr merge with main d5fc99e0: the per-64x64 | 7628 | + /// Re-measured on the lane-av1lr merge with main d5fc99e0 (per-64x64 |
| 7486 | - /// `cdef_idx` literals and the per-unit loop restoration syntax are new | 7629 | + /// `cdef_idx` literals and per-unit loop restoration syntax are new bits |
| 7487 | - /// bits in the tile, so the streams move (q=150 7416 -> 7458 bytes, | 7630 | + /// in the tile) and again on lane-av1mv's merge of it: an extra |
| 7488 | - /// q=60 27927 -> 27807 -- the low-rate frame pays for the syntax, the | 7631 | + /// reference's `NEWMV` is a coded-bits change too, judged by the BD gate |
| 7489 | - /// high-rate one more than earns it back). | 7632 | + /// above, not by this pin. |
| 7490 | - /// | ||
| 7491 | - /// Every number below was measured 2026-09-06: first on lane-av1fwd | ||
| 7492 | - /// (whose three speed steps left them identical to `a6649c4e`'s), then | ||
| 7493 | - /// re-measured on the lane-av1lr merge, which legitimately moves them -- | ||
| 7494 | - /// per-64x64 `cdef_idx` literals and the per-unit loop restoration | ||
| 7495 | - /// syntax are new bits in the tile, and both streams came out SMALLER | ||
| 7496 | - /// (7823 -> 7796, 28189 -> 28182 bytes) for it. | ||
| 7497 | #[test] | 7633 | #[test] |
| 7498 | fn the_encoders_own_streams_are_byte_identical_to_their_pins() { | 7634 | fn the_encoders_own_streams_are_byte_identical_to_their_pins() { |
| 7499 | if !have_ffmpeg() { | 7635 | if !have_ffmpeg() { |
| @@ -7515,7 +7651,7 @@ mod tests { | |||
| 7515 | }) | 7651 | }) |
| 7516 | }; | 7652 | }; |
| 7517 | let pins: [(u8, usize, u64); 2] = | 7653 | let pins: [(u8, usize, u64); 2] = |
| 7518 | - [(150, 7458, 0x7eb2_33c6_bd96_3baf), (60, 27807, 0xeee0_f1e5_e099_46bd)]; | 7654 | + [(150, 7444, 0x76eb980832d719f1), (60, 27692, 0x8c88f7e73455d439)]; |
| 7519 | for (q, bytes, hash) in pins { | 7655 | for (q, bytes, hash) in pins { |
| 7520 | let encoded = encode_sequence(&source, q, 0.5).unwrap(); | 7656 | let encoded = encode_sequence(&source, q, 0.5).unwrap(); |
| 7521 | assert_eq!( | 7657 | assert_eq!( |
| @@ -7679,6 +7815,7 @@ mod tests { | |||
| 7679 | let _ = crate::tile::take_inter_mode_hits(); | 7815 | let _ = crate::tile::take_inter_mode_hits(); |
| 7680 | let _ = crate::tile::take_drl_hits(); | 7816 | let _ = crate::tile::take_drl_hits(); |
| 7681 | let _ = crate::tile::take_ref_hits(); | 7817 | let _ = crate::tile::take_ref_hits(); |
| 7818 | + let _ = crate::motion::take_census(); | ||
| 7682 | let (ours, ours_wall) = our_ladder(&source, width, height, fctx); | 7819 | let (ours, ours_wall) = our_ladder(&source, width, height, fctx); |
| 7683 | // How often the inter split actually fired over this clip's four | 7820 | // How often the inter split actually fired over this clip's four |
| 7684 | // encodes, against the whole 32x32 that was the only outcome | 7821 | // encodes, against the whole 32x32 that was the only outcome |
| @@ -7700,6 +7837,22 @@ mod tests { | |||
| 7700 | 100.0 * global as f64 / modes_total as f64, | 7837 | 100.0 * global as f64 / modes_total as f64, |
| 7701 | 100.0 * new as f64 / modes_total as f64, | 7838 | 100.0 * new as f64 / modes_total as f64, |
| 7702 | ); | 7839 | ); |
| 7840 | + // Where the wall-owning stage actually goes: how many candidate | ||
| 7841 | + // evaluations (one `mc::predict` + SAD each) a search spends, how | ||
| 7842 | + // many of them are subpel, and how often the winner is the seed | ||
| 7843 | + // it started from -- the census the seeded search is judged by. | ||
| 7844 | + let [calls, evals, subpel, rounds, near_pred, unmoved] = crate::motion::take_census(); | ||
| 7845 | + let per = |n: u64| n as f64 / calls.max(1) as f64; | ||
| 7846 | + eprintln!( | ||
| 7847 | + "{name}: motion search {calls} calls, {evals} candidate evals ({:.1}/call, \ | ||
| 7848 | + {:.1}% of them subpel), {rounds} integer rounds ({:.2}/call); winner within \ | ||
| 7849 | + +-1 pel of pred_mv {:.1}%, winner = starting seed {:.1}%", | ||
| 7850 | + per(evals), | ||
| 7851 | + 100.0 * subpel as f64 / evals.max(1) as f64, | ||
| 7852 | + per(rounds), | ||
| 7853 | + 100.0 * near_pred as f64 / calls.max(1) as f64, | ||
| 7854 | + 100.0 * unmoved as f64 / calls.max(1) as f64, | ||
| 7855 | + ); | ||
| 7703 | eprintln!( | 7856 | eprintln!( |
| 7704 | "{name}: references LAST {} GOLDEN {} (LAST2 {} LAST3 {} BWD {} ALT2 {} ALT {})", | 7857 | "{name}: references LAST {} GOLDEN {} (LAST2 {} LAST3 {} BWD {} ALT2 {} ALT {})", |
| 7705 | refs[0], refs[3], refs[1], refs[2], refs[4], refs[5], refs[6] | 7858 | refs[0], refs[3], refs[1], refs[2], refs[4], refs[5], refs[6] |
crates/ec-av1/src/motion.rsmodified+167 -20
| @@ -55,6 +55,56 @@ const SEARCH_INITIAL_STEP_PEL: i32 = 8; | |||
| 55 | /// cost function. | 55 | /// cost function. |
| 56 | const SEARCH_MIN_STEP_PEL: i32 = 1; | 56 | const SEARCH_MIN_STEP_PEL: i32 = 1; |
| 57 | 57 | ||
| 58 | +/// [`SEARCH_INITIAL_STEP_PEL`], swept by `EC_AV1_MV_STEP` in a test build. | ||
| 59 | +/// Swept 1/2/4/8 on the BD gate with the stack seeds below in place: the | ||
| 60 | +/// narrow seeded shape a predictor-seeded search is supposed to allow costs | ||
| 61 | +/// far more rate than it saves wall (step 1 +145.2/+219.4/+81.1 vs libaom, | ||
| 62 | +/// step 2 +134.2/+196.1/+81.1, step 4 +126.0/+161.2/+81.1 against 8's | ||
| 63 | +/// +125.6/+152.1/+80.9) for 0.2 s of a 6 s ladder -- the wide log stage is | ||
| 64 | +/// what finds the 2160p clip's motion, and the search is not the wall. | ||
| 65 | +fn seeded_step() -> i32 { | ||
| 66 | + static STEP: std::sync::OnceLock<i32> = std::sync::OnceLock::new(); | ||
| 67 | + *STEP.get_or_init(|| match std::env::var("EC_AV1_MV_STEP").ok() { | ||
| 68 | + Some(v) if cfg!(test) => v.parse().unwrap_or(SEARCH_INITIAL_STEP_PEL), | ||
| 69 | + _ => SEARCH_INITIAL_STEP_PEL, | ||
| 70 | + }) | ||
| 71 | +} | ||
| 72 | + | ||
| 73 | +/// Whether [`search`] starts from the best of the MV-stack's own candidates | ||
| 74 | +/// (libaom's shape) as well as `pred_mv`. `EC_AV1_MV_SEEDED=0` restores the | ||
| 75 | +/// `pred_mv`-only start in a test build (what the lane measured both arms | ||
| 76 | +/// with). | ||
| 77 | +fn seeded() -> bool { | ||
| 78 | + // Read once: this is on the per-block search path, and `std::env::var` | ||
| 79 | + // allocates and locks. | ||
| 80 | + static SEEDED: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); | ||
| 81 | + *SEEDED.get_or_init(|| match std::env::var("EC_AV1_MV_SEEDED").ok() { | ||
| 82 | + Some(v) if cfg!(test) => v != "0", | ||
| 83 | + _ => true, | ||
| 84 | + }) | ||
| 85 | +} | ||
| 86 | + | ||
| 87 | +/// How the search spends itself since the last [`take_census`]: 0 calls, | ||
| 88 | +/// 1 total candidate evaluations (one `predict` + SAD each), 2 of which in | ||
| 89 | +/// the two subpel stages, 3 integer-stage rounds, 4 calls whose winner is | ||
| 90 | +/// within one whole sample of `pred_mv`, 5 calls whose winner is the | ||
| 91 | +/// starting centre itself. A gate prints these rather than assume where the | ||
| 92 | +/// wall-owning stage goes (gate-blind-to-feature). | ||
| 93 | +static CENSUS: [std::sync::atomic::AtomicU64; 6] = [ | ||
| 94 | + std::sync::atomic::AtomicU64::new(0), | ||
| 95 | + std::sync::atomic::AtomicU64::new(0), | ||
| 96 | + std::sync::atomic::AtomicU64::new(0), | ||
| 97 | + std::sync::atomic::AtomicU64::new(0), | ||
| 98 | + std::sync::atomic::AtomicU64::new(0), | ||
| 99 | + std::sync::atomic::AtomicU64::new(0), | ||
| 100 | +]; | ||
| 101 | + | ||
| 102 | +/// Takes (and clears) the census. | ||
| 103 | +#[cfg(test)] | ||
| 104 | +pub(crate) fn take_census() -> [u64; 6] { | ||
| 105 | + [0, 1, 2, 3, 4, 5].map(|i| CENSUS[i].swap(0, std::sync::atomic::Ordering::Relaxed)) | ||
| 106 | +} | ||
| 107 | + | ||
| 58 | /// The eight offsets, at `step` in each axis, a diamond/log search round | 108 | /// The eight offsets, at `step` in each axis, a diamond/log search round |
| 59 | /// checks around its current centre (the ninth point, no offset, is the | 109 | /// checks around its current centre (the ninth point, no offset, is the |
| 60 | /// centre itself and is already priced). | 110 | /// centre itself and is already priced). |
| @@ -158,6 +208,72 @@ pub struct MotionSearch { | |||
| 158 | pub cost: f64, | 208 | pub cost: f64, |
| 159 | } | 209 | } |
| 160 | 210 | ||
| 211 | +/// One candidate's `SAD + lambda * mv_bits(mv - pred_mv)`, predicted into the | ||
| 212 | +/// caller's `dst16` scratch (`block_w * block_h`) so a whole search allocates | ||
| 213 | +/// once. | ||
| 214 | +#[allow(clippy::too_many_arguments)] | ||
| 215 | +fn cost_of_mv( | ||
| 216 | + reference: &[u16], | ||
| 217 | + stride: usize, | ||
| 218 | + ref_width: usize, | ||
| 219 | + ref_height: usize, | ||
| 220 | + source: &[u8], | ||
| 221 | + block_x: usize, | ||
| 222 | + block_y: usize, | ||
| 223 | + block_w: usize, | ||
| 224 | + block_h: usize, | ||
| 225 | + mv: (i32, i32), | ||
| 226 | + pred_mv: (i32, i32), | ||
| 227 | + lambda: f64, | ||
| 228 | + dst16: &mut [u16], | ||
| 229 | + fctx: &crate::decode::FrameCtx, | ||
| 230 | +) -> f64 { | ||
| 231 | + let x_q4 = (block_x as i32) * 16 + mv.1 * Q4_PER_Q3; | ||
| 232 | + let y_q4 = (block_y as i32) * 16 + mv.0 * Q4_PER_Q3; | ||
| 233 | + predict( | ||
| 234 | + reference, stride, ref_width, ref_height, x_q4, y_q4, block_w, block_h, dst16, fctx, | ||
| 235 | + ); | ||
| 236 | + // lane-av1speed: accumulated as an integer (a block is at most | ||
| 237 | + // 32x32 samples of at most 255 each, nowhere near `u32`, and an | ||
| 238 | + // integer sum this small is exact in `f64` whatever order it is | ||
| 239 | + // summed in) instead of one `f64` conversion and dependent add per | ||
| 240 | + // sample. Same value, several times the throughput. | ||
| 241 | + let sad: u32 = source | ||
| 242 | + .iter() | ||
| 243 | + .zip(dst16.iter()) | ||
| 244 | + .map(|(&a, &b)| (i32::from(a) - i32::from(b)).unsigned_abs()) | ||
| 245 | + .sum(); | ||
| 246 | + let diff = (mv.0 - pred_mv.0, mv.1 - pred_mv.1); | ||
| 247 | + f64::from(sad) + lambda * mv_bits(diff) | ||
| 248 | +} | ||
| 249 | + | ||
| 250 | +/// [`cost_of_mv`] for one vector, on its own scratch -- what a caller uses to | ||
| 251 | +/// price a single candidate (an extra reference's `NEARESTMV`, say) on the | ||
| 252 | +/// same scale [`search`] reports its own cost on, for one evaluation instead | ||
| 253 | +/// of a whole search. | ||
| 254 | +#[allow(clippy::too_many_arguments)] | ||
| 255 | +pub(crate) fn cost_at( | ||
| 256 | + reference: &[u16], | ||
| 257 | + stride: usize, | ||
| 258 | + ref_width: usize, | ||
| 259 | + ref_height: usize, | ||
| 260 | + source: &[u8], | ||
| 261 | + block_x: usize, | ||
| 262 | + block_y: usize, | ||
| 263 | + block_w: usize, | ||
| 264 | + block_h: usize, | ||
| 265 | + mv: (i32, i32), | ||
| 266 | + pred_mv: (i32, i32), | ||
| 267 | + lambda: f64, | ||
| 268 | + fctx: &crate::decode::FrameCtx, | ||
| 269 | +) -> f64 { | ||
| 270 | + let mut dst16 = vec![0u16; block_w * block_h]; | ||
| 271 | + cost_of_mv( | ||
| 272 | + reference, stride, ref_width, ref_height, source, block_x, block_y, block_w, block_h, mv, | ||
| 273 | + pred_mv, lambda, &mut dst16, fctx, | ||
| 274 | + ) | ||
| 275 | +} | ||
| 276 | + | ||
| 161 | /// Searches one `block_w * block_h` block, at `(block_x, block_y)` in the | 277 | /// Searches one `block_w * block_h` block, at `(block_x, block_y)` in the |
| 162 | /// current picture's plane, against `reference` for the motion vector that | 278 | /// current picture's plane, against `reference` for the motion vector that |
| 163 | /// minimises `SAD + lambda * mv_bits(mv - pred_mv)`. | 279 | /// minimises `SAD + lambda * mv_bits(mv - pred_mv)`. |
| @@ -200,11 +316,14 @@ pub(crate) fn search( | |||
| 200 | block_w: usize, | 316 | block_w: usize, |
| 201 | block_h: usize, | 317 | block_h: usize, |
| 202 | pred_mv: (i32, i32), | 318 | pred_mv: (i32, i32), |
| 319 | + seeds: &[(i32, i32)], | ||
| 203 | lambda: f64, fctx: &crate::decode::FrameCtx, | 320 | lambda: f64, fctx: &crate::decode::FrameCtx, |
| 204 | ) -> MotionSearch { | 321 | ) -> MotionSearch { |
| 205 | let (result, _trace) = search_traced( | 322 | let (result, _trace) = search_traced( |
| 206 | reference, stride, ref_width, ref_height, source, block_x, block_y, block_w, block_h, | 323 | reference, stride, ref_width, ref_height, source, block_x, block_y, block_w, block_h, |
| 207 | - pred_mv, lambda, fctx, | 324 | + pred_mv, |
| 325 | + if seeded() { seeds } else { &[] }, | ||
| 326 | + lambda, fctx, | ||
| 208 | ); | 327 | ); |
| 209 | result | 328 | result |
| 210 | } | 329 | } |
| @@ -224,6 +343,7 @@ fn search_traced( | |||
| 224 | block_w: usize, | 343 | block_w: usize, |
| 225 | block_h: usize, | 344 | block_h: usize, |
| 226 | pred_mv: (i32, i32), | 345 | pred_mv: (i32, i32), |
| 346 | + seeds: &[(i32, i32)], | ||
| 227 | lambda: f64, fctx: &crate::decode::FrameCtx, | 347 | lambda: f64, fctx: &crate::decode::FrameCtx, |
| 228 | ) -> (MotionSearch, Vec<f64>) { | 348 | ) -> (MotionSearch, Vec<f64>) { |
| 229 | search_traced_from_step( | 349 | search_traced_from_step( |
| @@ -237,8 +357,13 @@ fn search_traced( | |||
| 237 | block_w, | 357 | block_w, |
| 238 | block_h, | 358 | block_h, |
| 239 | pred_mv, | 359 | pred_mv, |
| 360 | + seeds, | ||
| 240 | lambda, | 361 | lambda, |
| 241 | - SEARCH_INITIAL_STEP_PEL, fctx, | 362 | + if seeded() { |
| 363 | + seeded_step() | ||
| 364 | + } else { | ||
| 365 | + SEARCH_INITIAL_STEP_PEL | ||
| 366 | + }, fctx, | ||
| 242 | ) | 367 | ) |
| 243 | } | 368 | } |
| 244 | 369 | ||
| @@ -257,6 +382,7 @@ fn search_traced_from_step( | |||
| 257 | block_w: usize, | 382 | block_w: usize, |
| 258 | block_h: usize, | 383 | block_h: usize, |
| 259 | pred_mv: (i32, i32), | 384 | pred_mv: (i32, i32), |
| 385 | + seeds: &[(i32, i32)], | ||
| 260 | lambda: f64, | 386 | lambda: f64, |
| 261 | initial_step_pel: i32, fctx: &crate::decode::FrameCtx, | 387 | initial_step_pel: i32, fctx: &crate::decode::FrameCtx, |
| 262 | ) -> (MotionSearch, Vec<f64>) { | 388 | ) -> (MotionSearch, Vec<f64>) { |
| @@ -269,30 +395,34 @@ fn search_traced_from_step( | |||
| 269 | // allocate-and-convert per searched block, which profiled as the single | 395 | // allocate-and-convert per searched block, which profiled as the single |
| 270 | // largest symbol in the encoder (30% of `sequence_bench_sanity`). | 396 | // largest symbol in the encoder (30% of `sequence_bench_sanity`). |
| 271 | let mut dst16 = vec![0u16; block_w * block_h]; | 397 | let mut dst16 = vec![0u16; block_w * block_h]; |
| 398 | + let evals = std::cell::Cell::new(0u64); | ||
| 272 | let mut cost_of = |mv: (i32, i32)| -> f64 { | 399 | let mut cost_of = |mv: (i32, i32)| -> f64 { |
| 273 | - let x_q4 = (block_x as i32) * 16 + mv.1 * Q4_PER_Q3; | 400 | + evals.set(evals.get() + 1); |
| 274 | - let y_q4 = (block_y as i32) * 16 + mv.0 * Q4_PER_Q3; | 401 | + cost_of_mv( |
| 275 | - predict( | 402 | + reference, stride, ref_width, ref_height, source, block_x, block_y, block_w, block_h, |
| 276 | - reference, stride, ref_width, ref_height, x_q4, y_q4, block_w, block_h, | 403 | + mv, pred_mv, lambda, &mut dst16, fctx, |
| 277 | - &mut dst16, fctx, | 404 | + ) |
| 278 | - ); | ||
| 279 | - // lane-av1speed: accumulated as an integer (a block is at most | ||
| 280 | - // 32x32 samples of at most 255 each, nowhere near `u32`, and an | ||
| 281 | - // integer sum this small is exact in `f64` whatever order it is | ||
| 282 | - // summed in) instead of one `f64` conversion and dependent add per | ||
| 283 | - // sample. Same value, several times the throughput. | ||
| 284 | - let sad: u32 = source | ||
| 285 | - .iter() | ||
| 286 | - .zip(dst16.iter()) | ||
| 287 | - .map(|(&a, &b)| (i32::from(a) - i32::from(b)).unsigned_abs()) | ||
| 288 | - .sum(); | ||
| 289 | - let diff = (mv.0 - pred_mv.0, mv.1 - pred_mv.1); | ||
| 290 | - f64::from(sad) + lambda * mv_bits(diff) | ||
| 291 | }; | 405 | }; |
| 292 | 406 | ||
| 293 | let mut trace = Vec::new(); | 407 | let mut trace = Vec::new(); |
| 294 | let mut centre = (round_to_pel(pred_mv.0), round_to_pel(pred_mv.1)); | 408 | let mut centre = (round_to_pel(pred_mv.0), round_to_pel(pred_mv.1)); |
| 295 | let mut best_cost = cost_of(centre); | 409 | let mut best_cost = cost_of(centre); |
| 410 | + // The stack's own candidates, whole-pel rounded, as extra starting | ||
| 411 | + // points: a neighbour block's vector is where this block's motion most | ||
| 412 | + // often already is, and starting there is what lets the log stage below | ||
| 413 | + // start from is usually the vector this block wants. | ||
| 414 | + for &seed in seeds { | ||
| 415 | + let candidate = (round_to_pel(seed.0), round_to_pel(seed.1)); | ||
| 416 | + if candidate == centre { | ||
| 417 | + continue; | ||
| 418 | + } | ||
| 419 | + let cost = cost_of(candidate); | ||
| 420 | + if cost < best_cost { | ||
| 421 | + best_cost = cost; | ||
| 422 | + centre = candidate; | ||
| 423 | + } | ||
| 424 | + } | ||
| 425 | + let start_centre = centre; | ||
| 296 | trace.push(best_cost); | 426 | trace.push(best_cost); |
| 297 | 427 | ||
| 298 | // Stage 1: log/diamond search over whole-pel steps, halving the step | 428 | // Stage 1: log/diamond search over whole-pel steps, halving the step |
| @@ -317,6 +447,7 @@ fn search_traced_from_step( | |||
| 317 | } | 447 | } |
| 318 | let moved = best_in_round < best_cost; | 448 | let moved = best_in_round < best_cost; |
| 319 | best_cost = best_in_round; | 449 | best_cost = best_in_round; |
| 450 | + CENSUS[3].fetch_add(1, std::sync::atomic::Ordering::Relaxed); | ||
| 320 | trace.push(best_cost); | 451 | trace.push(best_cost); |
| 321 | if !moved { | 452 | if !moved { |
| 322 | break; | 453 | break; |
| @@ -328,6 +459,7 @@ fn search_traced_from_step( | |||
| 328 | // Stages 2 and 3: one ±1-step refinement each at half-pel then | 459 | // Stages 2 and 3: one ±1-step refinement each at half-pel then |
| 329 | // quarter-pel, through the same cost function (so the refinement is | 460 | // quarter-pel, through the same cost function (so the refinement is |
| 330 | // costed at the precision it commits to, not the integer-pel SAD alone). | 461 | // costed at the precision it commits to, not the integer-pel SAD alone). |
| 462 | + let integer_evals = evals.get(); | ||
| 331 | for step in [HALF_PEL_Q3, QUARTER_PEL_Q3] { | 463 | for step in [HALF_PEL_Q3, QUARTER_PEL_Q3] { |
| 332 | let round_centre = centre; | 464 | let round_centre = centre; |
| 333 | for (dr, dc) in neighbor_offsets(step) { | 465 | for (dr, dc) in neighbor_offsets(step) { |
| @@ -341,6 +473,17 @@ fn search_traced_from_step( | |||
| 341 | trace.push(best_cost); | 473 | trace.push(best_cost); |
| 342 | } | 474 | } |
| 343 | 475 | ||
| 476 | + use std::sync::atomic::Ordering::Relaxed; | ||
| 477 | + CENSUS[0].fetch_add(1, Relaxed); | ||
| 478 | + CENSUS[1].fetch_add(evals.get(), Relaxed); | ||
| 479 | + CENSUS[2].fetch_add(evals.get() - integer_evals, Relaxed); | ||
| 480 | + if (centre.0 - pred_mv.0).abs() <= PEL_Q3 && (centre.1 - pred_mv.1).abs() <= PEL_Q3 { | ||
| 481 | + CENSUS[4].fetch_add(1, Relaxed); | ||
| 482 | + } | ||
| 483 | + if centre == start_centre { | ||
| 484 | + CENSUS[5].fetch_add(1, Relaxed); | ||
| 485 | + } | ||
| 486 | + | ||
| 344 | ( | 487 | ( |
| 345 | MotionSearch { | 488 | MotionSearch { |
| 346 | mv: centre, | 489 | mv: centre, |
| @@ -449,6 +592,7 @@ mod tests { | |||
| 449 | block_w, | 592 | block_w, |
| 450 | block_h, | 593 | block_h, |
| 451 | (0, 0), | 594 | (0, 0), |
| 595 | + &[], | ||
| 452 | 0.1, fctx, | 596 | 0.1, fctx, |
| 453 | ); | 597 | ); |
| 454 | assert_eq!( | 598 | assert_eq!( |
| @@ -498,6 +642,7 @@ mod tests { | |||
| 498 | block_w, | 642 | block_w, |
| 499 | block_h, | 643 | block_h, |
| 500 | (0, 0), | 644 | (0, 0), |
| 645 | + &[], | ||
| 501 | 0.1, fctx, | 646 | 0.1, fctx, |
| 502 | ); | 647 | ); |
| 503 | assert_eq!( | 648 | assert_eq!( |
| @@ -536,6 +681,7 @@ mod tests { | |||
| 536 | block_w, | 681 | block_w, |
| 537 | block_h, | 682 | block_h, |
| 538 | (0, 0), | 683 | (0, 0), |
| 684 | + &[], | ||
| 539 | 0.1, fctx, | 685 | 0.1, fctx, |
| 540 | ); | 686 | ); |
| 541 | assert!(trace.len() > 1, "the search must run more than one round"); | 687 | assert!(trace.len() > 1, "the search must run more than one round"); |
| @@ -605,6 +751,7 @@ mod tests { | |||
| 605 | block_w, | 751 | block_w, |
| 606 | block_h, | 752 | block_h, |
| 607 | (0, 0), | 753 | (0, 0), |
| 754 | + &[], | ||
| 608 | 0.1, | 755 | 0.1, |
| 609 | candidate_step, fctx, | 756 | candidate_step, fctx, |
| 610 | ); | 757 | ); |