Merge branch 'lane-av1-mot2': SAD-prescreen the inter path's intra candidates
Browse files at this commit1 changed file +240 -2
- crates/ec-av1/src/encode.rs +240 -2
crates/ec-av1/src/encode.rsmodified+240 -2
| @@ -758,6 +758,48 @@ impl Plane<'_> { | ||
| 758 | 758 | } |
| 759 | 759 | } |
| 760 | 760 | |
| 761 | + /// The SAD-plus-mode-cost score [`Self::search_block`] ranks candidates | |
| 762 | + /// by, exposed so [`search_inter_block`]'s intra-candidate loop can | |
| 763 | + /// prescreen by the identical rule rather than a second one that could | |
| 764 | + /// drift from it. | |
| 765 | + fn intra_scores( | |
| 766 | + &self, | |
| 767 | + at: At, | |
| 768 | + modes: &[u8], | |
| 769 | + mode_bits: &[f64; 13], | |
| 770 | + lambda: f64, | |
| 771 | + ) -> Vec<(f64, u8)> { | |
| 772 | + let At { | |
| 773 | + x, y, side, reach, .. | |
| 774 | + } = at; | |
| 775 | + let (above, left, corner) = self.edges(x, y, side, reach); | |
| 776 | + modes | |
| 777 | + .iter() | |
| 778 | + .map(|&mode| { | |
| 779 | + let mut prediction = vec![0u8; side * side]; | |
| 780 | + crate::intra::predict( | |
| 781 | + mode, | |
| 782 | + above.as_deref(), | |
| 783 | + left.as_deref(), | |
| 784 | + corner, | |
| 785 | + side, | |
| 786 | + &mut prediction, | |
| 787 | + ); | |
| 788 | + let sad: f64 = (0..side * side) | |
| 789 | + .map(|i| { | |
| 790 | + let (row, col) = (i / side, i % side); | |
| 791 | + f64::from( | |
| 792 | + (i32::from(self.source[(y + row) * self.width + x + col]) | |
| 793 | + - i32::from(prediction[i])) | |
| 794 | + .abs(), | |
| 795 | + ) | |
| 796 | + }) | |
| 797 | + .sum(); | |
| 798 | + (sad + lambda * mode_bits[usize::from(mode)], mode) | |
| 799 | + }) | |
| 800 | + .collect() | |
| 801 | + } | |
| 802 | + | |
| 761 | 803 | /// Codes one block under every mode the search offers (or, when |
| 762 | 804 | /// [`Search::top_k`] prunes it, the cheapest `top_k` of them by a SAD |
| 763 | 805 | /// pre-pass plus DC) and commits the one whose squared error and |
| @@ -1074,6 +1116,27 @@ fn restore( | ||
| 1074 | 1116 | chroma[1].restore(x / 2, y / 2, BLOCK / 2, &saved[2]); |
| 1075 | 1117 | } |
| 1076 | 1118 | |
| 1119 | +/// Keeps the DC candidate plus the cheapest `top_k` (or fewer, once DC is set | |
| 1120 | +/// aside) of `scored` (as [`Plane::intra_scores`] built it), in `modes`' own | |
| 1121 | +/// order -- the same DC-always-kept, cheapest-by-SAD rule [`Plane::search_block`] | |
| 1122 | +/// applies, so [`search_inter_block`]'s intra-candidate loop prunes by one | |
| 1123 | +/// rule shared with the key-frame path, not a second one that could diverge. | |
| 1124 | +fn prune_by_sad(modes: &[u8], mut scored: Vec<(f64, u8)>, top_k: usize) -> Vec<u8> { | |
| 1125 | + let dc_pos = scored.iter().position(|&(_, mode)| mode == DC_PRED); | |
| 1126 | + let dc_entry = dc_pos.map(|i| scored.remove(i)); | |
| 1127 | + scored.sort_by(|a, b| a.0.partial_cmp(&b.0).expect("scores are finite")); | |
| 1128 | + scored.truncate(if dc_entry.is_some() { | |
| 1129 | + top_k.saturating_sub(1) | |
| 1130 | + } else { | |
| 1131 | + top_k | |
| 1132 | + }); | |
| 1133 | + if let Some(dc_entry) = dc_entry { | |
| 1134 | + scored.push(dc_entry); | |
| 1135 | + } | |
| 1136 | + let keep: Vec<u8> = scored.into_iter().map(|(_, mode)| mode).collect(); | |
| 1137 | + modes.iter().copied().filter(|m| keep.contains(m)).collect() | |
| 1138 | +} | |
| 1139 | + | |
| 1077 | 1140 | fn mode_bits(above_mode: u8, left_mode: u8) -> [f64; 13] { |
| 1078 | 1141 | let luma = &cdf::KF_Y_MODE[INTRA_MODE_CTX[usize::from(above_mode)]] |
| 1079 | 1142 | [INTRA_MODE_CTX[usize::from(left_mode)]]; |
| @@ -1139,6 +1202,49 @@ fn set_test_top_k_override(value: Option<usize>) { | ||
| 1139 | 1202 | /// lever. Set from the sweep in the lane report if the quality gate clears it. |
| 1140 | 1203 | const PRUNE_TOP_K: Option<usize> = None; |
| 1141 | 1204 | |
| 1205 | +/// [`Search::top_k`] for [`search_inter_block`]'s intra-candidate loop -- | |
| 1206 | +/// kept apart from [`prune_top_k`]/[`PRUNE_TOP_K`] because the two paths' | |
| 1207 | +/// quality gates were measured separately and may land on different | |
| 1208 | +/// defaults; `EC_AV1_PRUNE_K_INTER` sweeps it without touching | |
| 1209 | +/// [`EC_AV1_PRUNE_K`] or the key-frame path. | |
| 1210 | +fn prune_top_k_inter() -> Option<usize> { | |
| 1211 | + #[cfg(test)] | |
| 1212 | + { | |
| 1213 | + if let Some(k) = TEST_TOP_K_OVERRIDE_INTER.with(|cell| cell.get()) { | |
| 1214 | + return k; | |
| 1215 | + } | |
| 1216 | + } | |
| 1217 | + let swept = std::env::var("EC_AV1_PRUNE_K_INTER") | |
| 1218 | + .ok() | |
| 1219 | + .and_then(|v| v.parse::<usize>().ok()); | |
| 1220 | + match swept { | |
| 1221 | + Some(k) if cfg!(test) => Some(k), | |
| 1222 | + _ => INTER_PRUNE_TOP_K, | |
| 1223 | + } | |
| 1224 | +} | |
| 1225 | + | |
| 1226 | +/// A per-thread override [`prune_top_k_inter`] checks first, same reason as | |
| 1227 | +/// [`TEST_TOP_K_OVERRIDE`]. | |
| 1228 | +#[cfg(test)] | |
| 1229 | +thread_local! { | |
| 1230 | + static TEST_TOP_K_OVERRIDE_INTER: std::cell::Cell<Option<Option<usize>>> = | |
| 1231 | + const { std::cell::Cell::new(None) }; | |
| 1232 | +} | |
| 1233 | + | |
| 1234 | +#[cfg(test)] | |
| 1235 | +fn set_test_top_k_override_inter(value: Option<usize>) { | |
| 1236 | + TEST_TOP_K_OVERRIDE_INTER.with(|cell| cell.set(Some(value))); | |
| 1237 | +} | |
| 1238 | + | |
| 1239 | +/// The inter path's default `top_k`: `Some(3)`, from `prune_k_quality_sweep_inter` | |
| 1240 | +/// (three real clips, q 60 and 150) -- every `K` in {3, 4, 6} cleared the | |
| 1241 | +/// same rule the key-frame lever uses (every PSNR delta <0.05dB, bytes | |
| 1242 | +/// within +1%; worst seen was -0.011dB / +0.147% bytes), so the cheapest, | |
| 1243 | +/// `K=3`, ships as default. Unlike the key-frame path (still `None`), an | |
| 1244 | +/// inter block's intra candidates rarely win against NEWMV/NEARESTMV, so | |
| 1245 | +/// pruning them costs less quality here. | |
| 1246 | +const INTER_PRUNE_TOP_K: Option<usize> = Some(3); | |
| 1247 | + | |
| 1142 | 1248 | /// Per-thread nanosecond counters `stage_timing_breakdown_inter` (and |
| 1143 | 1249 | /// [`crate::mc::predict`], through [`stage_add`]) accumulate into, so an |
| 1144 | 1250 | /// inter frame's cost can be attributed to a bucket without changing what |
| @@ -1755,7 +1861,25 @@ fn search_inter_block( | ||
| 1755 | 1861 | search.deadzone, |
| 1756 | 1862 | ); |
| 1757 | 1863 | |
| 1758 | - for &mode in search.modes { | |
| 1864 | + let intra_modes: Vec<u8> = match search.top_k { | |
| 1865 | + Some(k) if k < search.modes.len() => { | |
| 1866 | + let scored = luma.intra_scores( | |
| 1867 | + At { | |
| 1868 | + x, | |
| 1869 | + y, | |
| 1870 | + side: BLOCK, | |
| 1871 | + reach, | |
| 1872 | + set: luma_set, | |
| 1873 | + }, | |
| 1874 | + search.modes, | |
| 1875 | + mode_bits, | |
| 1876 | + search.lambda, | |
| 1877 | + ); | |
| 1878 | + prune_by_sad(search.modes, scored, k) | |
| 1879 | + } | |
| 1880 | + _ => search.modes.to_vec(), | |
| 1881 | + }; | |
| 1882 | + for &mode in &intra_modes { | |
| 1759 | 1883 | let luma_trial = luma.trial( |
| 1760 | 1884 | At { |
| 1761 | 1885 | x, |
| @@ -2102,7 +2226,7 @@ pub(crate) fn encode_inter_frame( | ||
| 2102 | 2226 | deadzone, |
| 2103 | 2227 | lambda: lambda_scale() * step * step, |
| 2104 | 2228 | modes: &KEY_FRAME_MODES, |
| 2105 | - top_k: prune_top_k(), | |
| 2229 | + top_k: prune_top_k_inter(), | |
| 2106 | 2230 | }; |
| 2107 | 2231 | let mode_bits_table = inter_mode_bits(); |
| 2108 | 2232 | |
| @@ -3871,6 +3995,120 @@ mod tests { | ||
| 3871 | 3995 | set_test_top_k_override(None); |
| 3872 | 3996 | } |
| 3873 | 3997 | |
| 3998 | + /// Two consecutive decoded frames from one clip, for an inter-frame | |
| 3999 | + /// sweep -- [`clip_frame`] alone only ever gives one. | |
| 4000 | + fn clip_frame_pair(clip: &str, skip: &str, width: usize, height: usize) -> [Picture; 2] { | |
| 4001 | + let out = Command::new("ffmpeg") | |
| 4002 | + .args(["-v", "error", "-ss", skip, "-i", clip, "-frames:v", "2"]) | |
| 4003 | + .args(["-vf", &format!("scale={width}:{height}")]) | |
| 4004 | + .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"]) | |
| 4005 | + .output() | |
| 4006 | + .expect("ffmpeg failed to run"); | |
| 4007 | + assert!( | |
| 4008 | + out.status.success(), | |
| 4009 | + "ffmpeg: {}", | |
| 4010 | + String::from_utf8_lossy(&out.stderr) | |
| 4011 | + ); | |
| 4012 | + let (luma, chroma) = (width * height, width * height / 4); | |
| 4013 | + let frame_len = luma + 2 * chroma; | |
| 4014 | + assert_eq!(out.stdout.len(), frame_len * 2, "expected two 4:2:0 frames"); | |
| 4015 | + std::array::from_fn(|i| { | |
| 4016 | + let bytes = &out.stdout[i * frame_len..][..frame_len]; | |
| 4017 | + Picture { | |
| 4018 | + width, | |
| 4019 | + height, | |
| 4020 | + y: bytes[..luma].to_vec(), | |
| 4021 | + u: bytes[luma..luma + chroma].to_vec(), | |
| 4022 | + v: bytes[luma + chroma..].to_vec(), | |
| 4023 | + } | |
| 4024 | + }) | |
| 4025 | + } | |
| 4026 | + | |
| 4027 | + /// The quality gate [`INTER_PRUNE_TOP_K`] lives or dies by: the same | |
| 4028 | + /// three real clips as [`prune_k_quality_sweep`], but coding a key frame | |
| 4029 | + /// then one inter frame off it (`search_inter_block`'s own intra | |
| 4030 | + /// candidates are what [`prune_by_sad`] prunes here, not the key-frame | |
| 4031 | + /// loop), at 1280x704 -- a whole number of 64x64 superblocks, so no | |
| 4032 | + /// padding step complicates the comparison. Prints bytes and luma PSNR | |
| 4033 | + /// for the inter frame alone, unpruned vs each `K`. | |
| 4034 | + /// `cargo test -p ec-av1 --release prune_k_quality_sweep_inter -- --ignored --nocapture`. | |
| 4035 | + #[test] | |
| 4036 | + #[ignore = "needs real clips and ffmpeg; prints numbers for the lane report to judge"] | |
| 4037 | + fn prune_k_quality_sweep_inter() { | |
| 4038 | + if !have_ffmpeg() { | |
| 4039 | + eprintln!("SKIP prune_k_quality_sweep_inter: no ffmpeg"); | |
| 4040 | + return; | |
| 4041 | + } | |
| 4042 | + let (width, height) = (1280usize, 704usize); | |
| 4043 | + let frames: &[(&str, &str, &str)] = &[ | |
| 4044 | + ( | |
| 4045 | + "dark/flat", | |
| 4046 | + "/home/user/Videos/reela.mp4", | |
| 4047 | + "3", | |
| 4048 | + ), | |
| 4049 | + ( | |
| 4050 | + "detailed", | |
| 4051 | + "/home/user/Downloads/reelb.mkv", | |
| 4052 | + "1200", | |
| 4053 | + ), | |
| 4054 | + ( | |
| 4055 | + "film", | |
| 4056 | + "/home/user/Videos/Films/reelc.mkv", | |
| 4057 | + "600", | |
| 4058 | + ), | |
| 4059 | + ]; | |
| 4060 | + for &(label, clip, skip) in frames { | |
| 4061 | + if !std::path::Path::new(clip).exists() { | |
| 4062 | + eprintln!("SKIP {label}: {clip} not present on this machine"); | |
| 4063 | + continue; | |
| 4064 | + } | |
| 4065 | + let [key_source, inter_source] = clip_frame_pair(clip, skip, width, height); | |
| 4066 | + for &q in &[60u8, 150] { | |
| 4067 | + // SAFETY (not literally unsafe, just process-global): a | |
| 4068 | + // single-threaded #[ignore] probe, run by hand, never | |
| 4069 | + // alongside other tests that read Search::top_k. | |
| 4070 | + set_test_top_k_override_inter(None); | |
| 4071 | + let key = encode_key_frame(&key_source, q, 0.5).unwrap(); | |
| 4072 | + let baseline = encode_inter_frame( | |
| 4073 | + &inter_source, | |
| 4074 | + &key.reconstruction, | |
| 4075 | + q, | |
| 4076 | + 0.5, | |
| 4077 | + 1, | |
| 4078 | + (width, height), | |
| 4079 | + ) | |
| 4080 | + .unwrap(); | |
| 4081 | + let baseline_psnr = psnr(&baseline.reconstruction.y, &inter_source.y); | |
| 4082 | + eprint!( | |
| 4083 | + "{label:9} q={q:3} baseline {:6} bytes {:6.2} dB", | |
| 4084 | + baseline.stream.len(), | |
| 4085 | + baseline_psnr | |
| 4086 | + ); | |
| 4087 | + for &k in &[3usize, 4, 6] { | |
| 4088 | + set_test_top_k_override_inter(Some(k)); | |
| 4089 | + let pruned = encode_inter_frame( | |
| 4090 | + &inter_source, | |
| 4091 | + &key.reconstruction, | |
| 4092 | + q, | |
| 4093 | + 0.5, | |
| 4094 | + 1, | |
| 4095 | + (width, height), | |
| 4096 | + ) | |
| 4097 | + .unwrap(); | |
| 4098 | + let pruned_psnr = psnr(&pruned.reconstruction.y, &inter_source.y); | |
| 4099 | + eprint!( | |
| 4100 | + " K={k} {:6} bytes {:6.2} dB ({:+.3} dB)", | |
| 4101 | + pruned.stream.len(), | |
| 4102 | + pruned_psnr, | |
| 4103 | + pruned_psnr - baseline_psnr | |
| 4104 | + ); | |
| 4105 | + } | |
| 4106 | + eprintln!(); | |
| 4107 | + } | |
| 4108 | + } | |
| 4109 | + set_test_top_k_override_inter(None); | |
| 4110 | + } | |
| 4111 | + | |
| 3874 | 4112 | /// The replica-shaped path: 24 frames, 1280x720, one key frame followed |
| 3875 | 4113 | /// by inter frames -- the same GOP shape [`encode_sequence`] gives the |
| 3876 | 4114 | /// facade -- timed end to end, so the edith export-time projection is a |