Merge branch 'lane-av1-perf2': an opt-in SAD prescreen for the intra mode search
Browse files at this commit1 changed file +213 -6
- crates/ec-av1/src/encode.rs +213 -6
crates/ec-av1/src/encode.rsmodified+213 -6
| @@ -742,17 +742,83 @@ impl Plane<'_> { | ||
| 742 | 742 | } |
| 743 | 743 | } |
| 744 | 744 | |
| 745 | - /// Codes one block under every mode the search offers and commits the one | |
| 746 | - /// whose squared error and estimated rate come out cheapest. | |
| 745 | + /// Codes one block under every mode the search offers (or, when | |
| 746 | + /// [`Search::top_k`] prunes it, the cheapest `top_k` of them by a SAD | |
| 747 | + /// pre-pass plus DC) and commits the one whose squared error and | |
| 748 | + /// estimated rate come out cheapest. | |
| 749 | + /// | |
| 750 | + /// The prediction is built once per mode regardless -- the full RD trial | |
| 751 | + /// needs it too -- so ranking modes by SAD on that same prediction before | |
| 752 | + /// running the expensive part (forward transform, quantize, reconstruct, | |
| 753 | + /// `coeff_bits`) on only the survivors costs nothing extra to predict, | |
| 754 | + /// only to sum. | |
| 747 | 755 | fn search_block( |
| 748 | 756 | &mut self, |
| 749 | 757 | at: At, |
| 750 | 758 | search: &Search, |
| 751 | 759 | mode_bits: &[f64; 13], |
| 752 | 760 | ) -> (Vec<Coeff>, u8, f64) { |
| 761 | + let At { | |
| 762 | + x, y, side, reach, .. | |
| 763 | + } = at; | |
| 764 | + let (above, left, corner) = self.edges(x, y, side, reach); | |
| 765 | + let mut scored: Vec<(f64, u8, Vec<u8>)> = search | |
| 766 | + .modes | |
| 767 | + .iter() | |
| 768 | + .map(|&mode| { | |
| 769 | + let mut prediction = vec![0u8; side * side]; | |
| 770 | + crate::intra::predict( | |
| 771 | + mode, | |
| 772 | + above.as_deref(), | |
| 773 | + left.as_deref(), | |
| 774 | + corner, | |
| 775 | + side, | |
| 776 | + &mut prediction, | |
| 777 | + ); | |
| 778 | + let sad: f64 = (0..side * side) | |
| 779 | + .map(|i| { | |
| 780 | + let (row, col) = (i / side, i % side); | |
| 781 | + f64::from( | |
| 782 | + (i32::from(self.source[(y + row) * self.width + x + col]) | |
| 783 | + - i32::from(prediction[i])) | |
| 784 | + .abs(), | |
| 785 | + ) | |
| 786 | + }) | |
| 787 | + .sum(); | |
| 788 | + ( | |
| 789 | + sad + search.lambda * mode_bits[usize::from(mode)], | |
| 790 | + mode, | |
| 791 | + prediction, | |
| 792 | + ) | |
| 793 | + }) | |
| 794 | + .collect(); | |
| 795 | + if let Some(k) = search.top_k { | |
| 796 | + if k < scored.len() { | |
| 797 | + let dc_pos = scored.iter().position(|&(_, mode, _)| mode == DC_PRED); | |
| 798 | + let dc_entry = dc_pos.map(|i| scored.remove(i)); | |
| 799 | + scored.sort_by(|a, b| a.0.partial_cmp(&b.0).expect("scores are finite")); | |
| 800 | + scored.truncate(if dc_entry.is_some() { | |
| 801 | + k.saturating_sub(1) | |
| 802 | + } else { | |
| 803 | + k | |
| 804 | + }); | |
| 805 | + if let Some(dc_entry) = dc_entry { | |
| 806 | + scored.push(dc_entry); | |
| 807 | + } | |
| 808 | + } | |
| 809 | + } | |
| 753 | 810 | let mut best: Option<(f64, u8, Trial)> = None; |
| 754 | - for &mode in search.modes { | |
| 755 | - let trial = self.trial(at, mode, search.base_q_idx, search.deadzone); | |
| 811 | + for (_, mode, prediction) in scored { | |
| 812 | + let trial = self.code_from_prediction( | |
| 813 | + x, | |
| 814 | + y, | |
| 815 | + side, | |
| 816 | + &prediction, | |
| 817 | + false, | |
| 818 | + search.base_q_idx, | |
| 819 | + search.deadzone, | |
| 820 | + at.set, | |
| 821 | + ); | |
| 756 | 822 | let cost = trial.sse + search.lambda * (trial.bits + mode_bits[usize::from(mode)]); |
| 757 | 823 | if best |
| 758 | 824 | .as_ref() |
| @@ -762,8 +828,8 @@ impl Plane<'_> { | ||
| 762 | 828 | } |
| 763 | 829 | } |
| 764 | 830 | let (cost, mode, trial) = best.expect("the search offers at least one mode"); |
| 765 | - self.commit(at.x, at.y, at.side, &trial); | |
| 766 | - (coeffs(&trial.levels, at.side), mode, cost) | |
| 831 | + self.commit(x, y, side, &trial); | |
| 832 | + (coeffs(&trial.levels, side), mode, cost) | |
| 767 | 833 | } |
| 768 | 834 | } |
| 769 | 835 | |
| @@ -1011,8 +1077,52 @@ struct Search<'a> { | ||
| 1011 | 1077 | deadzone: f64, |
| 1012 | 1078 | lambda: f64, |
| 1013 | 1079 | modes: &'a [u8], |
| 1080 | + /// How many of `modes` the full RD trial (forward transform, quantize, | |
| 1081 | + /// reconstruct, `coeff_bits`) actually runs on, ranked by a cheap SAD | |
| 1082 | + /// pre-pass on the prediction residual alone plus DC (always kept, since | |
| 1083 | + /// libaom's own intra pruning -- `av1/encoder/speed_features.c`'s | |
| 1084 | + /// `intra_pruning_with_hog` -- never prunes it away). `None` runs every | |
| 1085 | + /// mode through full RD, unchanged from before this lever. | |
| 1086 | + top_k: Option<usize>, | |
| 1087 | +} | |
| 1088 | + | |
| 1089 | +/// [`Search::top_k`]'s value: `None` keeps every mode's search unchanged | |
| 1090 | +/// (the default, until a lever's quality gate justifies pruning by default); | |
| 1091 | +/// `EC_AV1_PRUNE_K` sweeps it in a test build without touching callers. | |
| 1092 | +fn prune_top_k() -> Option<usize> { | |
| 1093 | + #[cfg(test)] | |
| 1094 | + { | |
| 1095 | + if let Some(k) = TEST_TOP_K_OVERRIDE.with(|cell| cell.get()) { | |
| 1096 | + return k; | |
| 1097 | + } | |
| 1098 | + } | |
| 1099 | + let swept = std::env::var("EC_AV1_PRUNE_K") | |
| 1100 | + .ok() | |
| 1101 | + .and_then(|v| v.parse::<usize>().ok()); | |
| 1102 | + match swept { | |
| 1103 | + Some(k) if cfg!(test) => Some(k), | |
| 1104 | + _ => PRUNE_TOP_K, | |
| 1105 | + } | |
| 1106 | +} | |
| 1107 | + | |
| 1108 | +/// A per-thread override [`prune_top_k`] checks first, so one test can sweep | |
| 1109 | +/// `top_k` in-process without mutating the environment (forbidden here -- | |
| 1110 | +/// `#![forbid(unsafe_code)]` -- and racy across parallel tests besides). | |
| 1111 | +#[cfg(test)] | |
| 1112 | +thread_local! { | |
| 1113 | + static TEST_TOP_K_OVERRIDE: std::cell::Cell<Option<Option<usize>>> = | |
| 1114 | + const { std::cell::Cell::new(None) }; | |
| 1115 | +} | |
| 1116 | + | |
| 1117 | +#[cfg(test)] | |
| 1118 | +fn set_test_top_k_override(value: Option<usize>) { | |
| 1119 | + TEST_TOP_K_OVERRIDE.with(|cell| cell.set(Some(value))); | |
| 1014 | 1120 | } |
| 1015 | 1121 | |
| 1122 | +/// The default: unpruned, thirteen full trials per block, same as before this | |
| 1123 | +/// lever. Set from the sweep in the lane report if the quality gate clears it. | |
| 1124 | +const PRUNE_TOP_K: Option<usize> = None; | |
| 1125 | + | |
| 1016 | 1126 | /// One mode's coding of one block, before it is committed. |
| 1017 | 1127 | struct Trial { |
| 1018 | 1128 | levels: Vec<i32>, |
| @@ -1161,6 +1271,7 @@ pub(crate) fn encode_key_frame_inner( | ||
| 1161 | 1271 | deadzone, |
| 1162 | 1272 | lambda: lambda_scale() * step * step, |
| 1163 | 1273 | modes, |
| 1274 | + top_k: prune_top_k(), | |
| 1164 | 1275 | }; |
| 1165 | 1276 | |
| 1166 | 1277 | // The block grid this frame is coded over: [`crate::tile::block_grid`]'s |
| @@ -1923,6 +2034,7 @@ pub(crate) fn encode_inter_frame( | ||
| 1923 | 2034 | deadzone, |
| 1924 | 2035 | lambda: lambda_scale() * step * step, |
| 1925 | 2036 | modes: &KEY_FRAME_MODES, |
| 2037 | + top_k: prune_top_k(), | |
| 1926 | 2038 | }; |
| 1927 | 2039 | let mode_bits_table = inter_mode_bits(); |
| 1928 | 2040 | |
| @@ -3571,4 +3683,99 @@ mod tests { | ||
| 3571 | 3683 | ); |
| 3572 | 3684 | } |
| 3573 | 3685 | } |
| 3686 | + | |
| 3687 | + /// The quality gate [`Search::top_k`]'s lever lives or dies by: three real | |
| 3688 | + /// frames (a dark/flat one, a detailed one, a normal film one) at two | |
| 3689 | + /// `base_q_idx` values, encoded with the mode search unpruned (`top_k = | |
| 3690 | + /// None`, the baseline this same build produces without | |
| 3691 | + /// `EC_AV1_PRUNE_K` set) and with it pruned to each of a few `K`, bytes | |
| 3692 | + /// and luma PSNR compared side by side. Not a gate itself -- the numbers | |
| 3693 | + /// go in the lane report, which is where "ship as default" is decided -- | |
| 3694 | + /// so it stays `#[ignore]`, run by hand with real clips on this machine. | |
| 3695 | + /// `cargo test -p ec-av1 --release prune_k_quality_sweep -- --ignored --nocapture`. | |
| 3696 | + #[test] | |
| 3697 | + #[ignore = "needs real clips and ffmpeg; prints numbers for the lane report to judge"] | |
| 3698 | + fn prune_k_quality_sweep() { | |
| 3699 | + if !have_ffmpeg() { | |
| 3700 | + eprintln!("SKIP prune_k_quality_sweep: no ffmpeg"); | |
| 3701 | + return; | |
| 3702 | + } | |
| 3703 | + let (width, height) = (640usize, 352usize); | |
| 3704 | + let frames: &[(&str, &str, &str)] = &[ | |
| 3705 | + // (label, clip, seek) -- a near-black scene, a busy one, and an | |
| 3706 | + // ordinary film frame, each from a different real file. | |
| 3707 | + ( | |
| 3708 | + "dark/flat", | |
| 3709 | + "/home/user/Videos/reela.mp4", | |
| 3710 | + "3", | |
| 3711 | + ), | |
| 3712 | + ( | |
| 3713 | + "detailed", | |
| 3714 | + "/home/user/Downloads/reelb.mkv", | |
| 3715 | + "1200", | |
| 3716 | + ), | |
| 3717 | + ( | |
| 3718 | + "film", | |
| 3719 | + "/home/user/Videos/Films/reelc.mkv", | |
| 3720 | + "600", | |
| 3721 | + ), | |
| 3722 | + ]; | |
| 3723 | + for &(label, clip, skip) in frames { | |
| 3724 | + if !std::path::Path::new(clip).exists() { | |
| 3725 | + eprintln!("SKIP {label}: {clip} not present on this machine"); | |
| 3726 | + continue; | |
| 3727 | + } | |
| 3728 | + let picture = clip_frame(clip, skip, width, height); | |
| 3729 | + for &q in &[60u8, 150] { | |
| 3730 | + // SAFETY (not literally unsafe, just process-global): this is | |
| 3731 | + // a single-threaded #[ignore] probe, run by hand, never | |
| 3732 | + // alongside other tests that read Search::top_k. | |
| 3733 | + set_test_top_k_override(None); | |
| 3734 | + let baseline = encode_key_frame(&picture, q, 0.5).unwrap(); | |
| 3735 | + let baseline_psnr = psnr(&baseline.reconstruction.y, &picture.y); | |
| 3736 | + eprint!( | |
| 3737 | + "{label:9} q={q:3} baseline {:6} bytes {:6.2} dB", | |
| 3738 | + baseline.stream.len(), | |
| 3739 | + baseline_psnr | |
| 3740 | + ); | |
| 3741 | + for &k in &[3usize, 4, 6] { | |
| 3742 | + set_test_top_k_override(Some(k)); | |
| 3743 | + let pruned = encode_key_frame(&picture, q, 0.5).unwrap(); | |
| 3744 | + let pruned_psnr = psnr(&pruned.reconstruction.y, &picture.y); | |
| 3745 | + eprint!( | |
| 3746 | + " K={k} {:6} bytes {:6.2} dB ({:+.3} dB)", | |
| 3747 | + pruned.stream.len(), | |
| 3748 | + pruned_psnr, | |
| 3749 | + pruned_psnr - baseline_psnr | |
| 3750 | + ); | |
| 3751 | + } | |
| 3752 | + eprintln!(); | |
| 3753 | + } | |
| 3754 | + } | |
| 3755 | + set_test_top_k_override(None); | |
| 3756 | + } | |
| 3757 | + | |
| 3758 | + /// The replica-shaped path: 24 frames, 1280x720, one key frame followed | |
| 3759 | + /// by inter frames -- the same GOP shape [`encode_sequence`] gives the | |
| 3760 | + /// facade -- timed end to end, so the edith export-time projection is a | |
| 3761 | + /// real number rather than a guess from the isolated key/inter numbers | |
| 3762 | + /// above. Run with and without `EC_AV1_PRUNE_K` set to compare. | |
| 3763 | + /// `cargo test -p ec-av1 --release sequence_bench_sanity -- --ignored --nocapture`. | |
| 3764 | + #[test] | |
| 3765 | + #[ignore = "a perf probe, not a gate"] | |
| 3766 | + fn sequence_bench_sanity() { | |
| 3767 | + use std::time::Instant; | |
| 3768 | + let (width, height) = (1280usize, 720usize); | |
| 3769 | + let pictures: Vec<Picture> = (0..24) | |
| 3770 | + .map(|i| panned_test_card(width, height, i * 3)) | |
| 3771 | + .collect(); | |
| 3772 | + let t = Instant::now(); | |
| 3773 | + let encoded = encode_sequence(&pictures, 100, 0.5).unwrap(); | |
| 3774 | + let elapsed = t.elapsed(); | |
| 3775 | + let total_bytes: usize = encoded.frames.iter().map(|f| f.stream.len()).sum(); | |
| 3776 | + eprintln!( | |
| 3777 | + "24 frames @ 1280x720: {elapsed:>9.2?} total, {:>9.2?}/frame, {total_bytes} bytes", | |
| 3778 | + elapsed / 24 | |
| 3779 | + ); | |
| 3780 | + } | |
| 3574 | 3781 | } |