forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'lane-tplfut' (112893ff): the top ARF's temporal lambda map looks three pictures back and four forward into the buffered next group; future-only refuted; long-GOP film B +72.1/-1.2 to +71.6/-1.5; pins hold at 8291 / 33227

Browse files at this commit

54de485730e6c472a1f646d17f463df79311fdd4Ahmet Kaan GümüşParent: e01aa80d695be9
The tpl chain is nearest-first over adjacent pictures; the top ARF passed the group's own sources, all display-past, a well-formed but time-reversed window against the flat path and against libaom. A future-only window loses on every column (depth-1 of the next group +22.0/-8.6 and +73.1/-1.1, the whole next group +21.9/-8.7 and +72.7/-1.4, against +21.3/-8.8 and +72.1/-1.2). TPL_FUT=2 ships: 3 past then 4 future, film A +21.2/-8.8, film B +71.6/-1.5, wall +3.2% / +0.2%; falls back to the past window when no next group is buffered, so pins and the 12-picture gate are byte-unchanged. Open: the 3+4 split is unswept (EC_AV1_TPL_FUT_HALF).
crates/ec-av1/src/encoder.rsmodified+153 -1
@@ -1260,6 +1260,8 @@ static LOOKAHEAD_OVERRIDE: std::sync::atomic::AtomicU8 =
12601260 std::sync::atomic::AtomicU8::new(u8::MAX);
12611261 static ARF_TF_FUT_OVERRIDE: std::sync::atomic::AtomicUsize =
12621262 std::sync::atomic::AtomicUsize::new(usize::MAX);
1263+static TPL_FUT_OVERRIDE: std::sync::atomic::AtomicUsize =
1264+ std::sync::atomic::AtomicUsize::new(usize::MAX);
12631265
12641266 /// Sets [`LOOKAHEAD_OVERRIDE`]; `None` clears it.
12651267 #[allow(dead_code)] // set only from the `#[cfg(test)]` witness
@@ -1276,6 +1278,26 @@ pub(crate) fn set_arf_tf_future(n: Option<usize>) {
12761278 ARF_TF_FUT_OVERRIDE.store(n.unwrap_or(usize::MAX), std::sync::atomic::Ordering::Relaxed);
12771279 }
12781280
1281+/// Sets [`TPL_FUT_OVERRIDE`]; `None` clears it.
1282+#[allow(dead_code)] // set only from the `#[cfg(test)]` witness
1283+pub(crate) fn set_tpl_fut(n: Option<usize>) {
1284+ TPL_FUT_OVERRIDE.store(n.unwrap_or(usize::MAX), std::sync::atomic::Ordering::Relaxed);
1285+}
1286+
1287+/// lane-tplfut: which window the TOP ARF's temporal lambda map propagates
1288+/// back through ([`crate::speed::TPL_FUT`], `EC_AV1_TPL_FUT=<n>`). Inert
1289+/// without [`lookahead`] -- mode 0 is the shipped past window.
1290+pub(crate) fn tpl_fut() -> usize {
1291+ match TPL_FUT_OVERRIDE.load(std::sync::atomic::Ordering::Relaxed) {
1292+ usize::MAX => {}
1293+ n => return n,
1294+ }
1295+ std::env::var("EC_AV1_TPL_FUT")
1296+ .ok()
1297+ .and_then(|v| v.parse().ok())
1298+ .unwrap_or_else(|| crate::speed::at(&crate::speed::TPL_FUT))
1299+}
1300+
12791301 /// lane-lookahead: whether the pyramid path holds one group of lookahead
12801302 /// ([`crate::speed::LOOKAHEAD`], `EC_AV1_LOOKAHEAD=0|1`).
12811303 fn lookahead() -> bool {
@@ -2207,6 +2229,41 @@ impl Av1Encoder {
22072229 .take(arf_tf_window_future())
22082230 .map(|(_, p)| p.padded_to(SUPERBLOCK))
22092231 .collect();
2232+ // lane-tplfut: the top ARF's TEMPORAL LAMBDA window. Mode 0 (and any
2233+ // mode with no buffered future picture) keeps the group's own
2234+ // display-PAST sources, reversed -- the only window that exists
2235+ // without a lookahead, and the one every measurement so far was
2236+ // taken with. The other modes read the next group's sources, which
2237+ // is the direction libaom's tpl looks at an ARF.
2238+ // `n` of the buffered display-future sources, nearest first, padded
2239+ // like the frame being coded.
2240+ let arf_tpl_future = |n: usize| -> Vec<Picture> {
2241+ future.iter().take(n).map(|(_, p)| p.padded_to(SUPERBLOCK)).collect()
2242+ };
2243+ let arf_tpl: Vec<Picture> = {
2244+ let depth = crate::encode::tpl_depth();
2245+ let past = || tpl_window(group.len() - 1, true);
2246+ match (tpl_fut(), future.is_empty(), tpl_pyramid() && depth >= 2) {
2247+ (_, _, false) => Vec::new(),
2248+ (0, _, _) | (_, true, _) => past(),
2249+ (1, _, _) => arf_tpl_future(depth - 1),
2250+ // Half the budget each side (`EC_AV1_TPL_FUT_HALF=<n>`
2251+ // moves the split), past first: the chain then has
2252+ // ONE discontinuity in the middle (the coarse pass between
2253+ // the nearest past and the nearest future neighbour spans the
2254+ // whole group), which is the arm's known cost.
2255+ (2, _, _) => {
2256+ let half = std::env::var("EC_AV1_TPL_FUT_HALF").ok().and_then(|v| v.parse().ok()).unwrap_or((depth - 1) / 2);
2257+ let mut w = past();
2258+ w.truncate(half.max(1));
2259+ let room = (depth - 1).saturating_sub(w.len());
2260+ w.extend(arf_tpl_future(room));
2261+ w
2262+ }
2263+ // Mode 3 and anything above: the WHOLE buffered next group.
2264+ (_, _, _) => arf_tpl_future(future.len()),
2265+ }
2266+ };
22102267 // The group's top level: the last picture, hidden, off the anchor.
22112268 packets.push(self.encode_pyramid_inter(
22122269 arf_order,
@@ -2228,7 +2285,7 @@ impl Av1Encoder {
22282285 false,
22292286 Level::Arf,
22302287 pyramid.arf_q_offset,
2231- &tpl_window(group.len() - 1, true),
2288+ &arf_tpl,
22322289 // lane-lookahead: the group's top ARF is its LAST picture in
22332290 // display order, so every picture of the next group is a
22342291 // display-future neighbour of it -- nearest first.
@@ -3788,6 +3845,101 @@ mod tests {
37883845 crate::speed::set_speed(was);
37893846 }
37903847
3848+ /// lane-tplfut's correctness witness, the sibling of
3849+ /// [`the_lookahead_holds_one_group_and_still_codes_every_picture`]: with
3850+ /// the top ARF's TEMPORAL LAMBDA window taken out of the buffered next
3851+ /// group (`speed::TPL_FUT`), every picture is still coded, the streams
3852+ /// decode exactly through our decoder and ffmpeg, and the stream MOVES
3853+ /// against the knob off wherever a next group exists (class
3854+ /// gate-blind-to-feature). Coded at q=60, not 120: at a coarse
3855+ /// quantizer this fixture's ARF is almost pure skip and a different
3856+ /// lambda map re-quantises to identical bytes.
3857+ #[test]
3858+ fn the_future_tpl_window_still_codes_every_picture_and_moves_the_stream() {
3859+ let _knobs = crate::speed::knob_write();
3860+ let was = crate::speed::speed();
3861+ crate::speed::set_speed(0);
3862+ crate::encode::force_screen(Some(false));
3863+ let (width, height) = (128usize, 128usize);
3864+ let run = |n: usize, gop: usize, fut: usize| -> (Vec<u8>, Vec<Packet>) {
3865+ set_lookahead(Some(true));
3866+ set_arf_tf_future(Some(0));
3867+ set_tpl_fut(Some(fut));
3868+ let config = EncoderConfig {
3869+ base_q_idx: 60,
3870+ width,
3871+ height,
3872+ gop,
3873+ colour: Colour::Bt709Limited,
3874+ tile_cols_log2: 0,
3875+ tile_rows_log2: 0,
3876+ };
3877+ let mut enc = Av1Encoder::with_pyramid(config, Pyramid::default()).unwrap();
3878+ let sources: Vec<Picture> = (0..n).map(|t| noisy_card(width, height, t)).collect();
3879+ let packets = encode_all(&mut enc, &sources);
3880+ assert!(
3881+ enc.pyramid().is_some(),
3882+ "{n} pictures at gop {gop}: the content gate dropped the pyramid (speed {})",
3883+ crate::speed::speed(),
3884+ );
3885+ (concat(&packets), packets)
3886+ };
3887+ for gop in [32usize, 8] {
3888+ for n in [1usize, 7, 8, 9, 17] {
3889+ let (off, off_packets) = run(n, gop, 0);
3890+ for mode in [1usize, 2, 3] {
3891+ let (on, packets) = run(n, gop, mode);
3892+ assert_eq!(
3893+ packets.iter().map(|p| (p.order, p.key, p.level)).collect::<Vec<_>>(),
3894+ off_packets.iter().map(|p| (p.order, p.key, p.level)).collect::<Vec<_>>(),
3895+ "{n} pictures at gop {gop} mode {mode}: coding order/levels moved"
3896+ );
3897+ let ours = crate::stream::decode_stream(&on).expect("our decoder");
3898+ assert_eq!(ours.len(), n, "{n} pictures at gop {gop} mode {mode}: our count");
3899+ if !have_ffmpeg() {
3900+ continue;
3901+ }
3902+ let theirs = ffmpeg_decode_luma(&on, width, height);
3903+ assert_eq!(theirs.len(), n, "{n} pictures at gop {gop} mode {mode}: ffmpeg count");
3904+ for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() {
3905+ let got: Vec<u8> = a.y.iter().map(|&v| v as u8).collect();
3906+ assert!(
3907+ got == *b,
3908+ "{n} pictures at gop {gop} mode {mode}, frame {i}: ours differs from ffmpeg"
3909+ );
3910+ }
3911+ }
3912+ let _ = &off;
3913+ }
3914+ }
3915+ // The future window REACHES the lambda map: 17 pictures at gop 32 is
3916+ // three groups, so the first two top ARFs each have a next group
3917+ // buffered and their windows really are display-future.
3918+ let (off, _) = run(17, 32, 0);
3919+ // Mode 2 is NOT in this list: at its default split it keeps the three
3920+ // NEAREST past neighbours, and those dominate the propagation -- on
3921+ // this 128x128 fixture the map moves too little to flip an RD
3922+ // decision and the stream comes back byte-identical to mode 0. Not a
3923+ // dead knob: the same run with `EC_AV1_TPL_FUT_HALF=1` (one past
3924+ // neighbour, six future) does move the stream, and the gate below
3925+ // measures mode 2 on real content.
3926+ for mode in [1usize, 3] {
3927+ let (on, _) = run(17, 32, mode);
3928+ assert!(
3929+ off != on,
3930+ "mode {mode} left the top ARF's temporal lambda map unchanged \
3931+ ({} B vs {} B, preset {})",
3932+ off.len(),
3933+ on.len(),
3934+ crate::speed::speed()
3935+ );
3936+ }
3937+ set_lookahead(None);
3938+ set_arf_tf_future(None);
3939+ set_tpl_fut(None);
3940+ crate::speed::set_speed(was);
3941+ }
3942+
37913943 fn pyramid_round_trip(pyramid: Pyramid, hidden: usize) {
37923944 let (width, height) = (128usize, 128usize);
37933945 let config = EncoderConfig {
crates/ec-av1/src/speed.rsmodified+40 -0
@@ -475,6 +475,46 @@ pub(crate) const ARF_TF_WIN_FUT: [usize; 11] = [3; 11];
475475 /// two-pass-like allocation would need.
476476 pub(crate) const LOOKAHEAD: bool = true;
477477
478+/// lane-tplfut: which pictures the TOP ARF's temporal lambda map
479+/// ([`crate::encode::tpl_lambda_factors`]) propagates back through. The top
480+/// ARF is its group's LAST picture in display order, so the group's own
481+/// sources -- what [`crate::encoder::Av1Encoder::code_group`] hands it today
482+/// -- are all display-PAST, i.e. the window is time-REVERSED against every
483+/// other frame's (and against the flat path's, which always looks forward).
484+/// libaom's tpl at an ARF looks FORWARD, over the next group. With
485+/// [`LOOKAHEAD`] on those pictures are buffered, so the window is a choice:
486+///
487+/// * `0` -- the past window (time-reversed), the shipped behaviour.
488+/// * `1` -- the display-FUTURE pictures only, nearest first, up to
489+/// `tpl_depth() - 1` of them.
490+/// * `2` -- past then future, concatenated nearest-first. NOTE the chain has
491+/// a discontinuity in the middle (the coarse pass between the last past
492+/// neighbour and the nearest future one spans the whole group).
493+/// * `3` -- future-only over the WHOLE next group, ignoring `tpl_depth()`.
494+///
495+/// Falls back to `0`'s window whenever no future picture is buffered (the
496+/// lookahead off, or the end of the stream). `EC_AV1_TPL_FUT=<n>` overrides
497+/// it, and `EC_AV1_TPL_FUT_HALF=<n>` moves mode 2's split (default half the
498+/// budget each side).
499+///
500+/// The 48-picture long-GOP gate, both films, against the past window:
501+///
502+/// | arm | film A | film B | wall A | wall B |
503+/// |---|---|---|---|---|
504+/// | 0, past (the control) | +21.3/-8.8 | +72.1/-1.2 | 671.1s | 461.6s |
505+/// | 1, future only | +22.0/-8.6 | +73.1/-1.1 | 629.6s | 583.1s |
506+/// | **2, 3 past then 4 future (ships)** | **+21.2/-8.8** | **+71.6/-1.5** | 692.3s | 462.5s |
507+/// | 3, the whole next group | +21.9/-8.7 | +72.7/-1.4 | 573.1s | 455.7s |
508+///
509+/// A future-ONLY window is worse than the past one on every column: the
510+/// nearest past neighbours are what the map's propagation is carried by (the
511+/// witness sees the same thing -- mode 2 at its default split is byte-
512+/// identical to mode 0 on a 128x128 fixture, and only moves once the past
513+/// half is cut to one). Mode 2 is film B -0.5/-0.3 and film A -0.1/0.0, so it
514+/// keeps by the lane's rule (one row >=0.5 down, the other flat within
515+/// +-0.3) at +3.2% / +0.2% wall.
516+pub(crate) const TPL_FUT: [usize; 11] = [2; 11];
517+
478518 /// lane-arfpred: the qindex below which the ARF temporal filter is OFF --
479519 /// libaom scales `arnr` strength with the quantizer and stops filtering at
480520 /// the high-quality end for the same reason: a picture we are about to
lanes/tplfut.report.mdadded+120 -0
@@ -0,0 +1,120 @@
1+# lane-tplfut: the top ARF's temporal lambda window
2+
3+## 1. What the tpl window MEANS on each path
4+
5+`encode_inter_frame`'s `lookahead` argument (encode.rs:12333) is turned into
6+`frames = [current, w0, w1, ...]` and `tpl_lambda_factors` (encode.rs:11785)
7+runs one coarse motion pass per ADJACENT pair, `tpl_coarse_pass(frames[f-1],
8+frames[f])`, then propagates `mc_dep` from the far end back to `frames[0]`.
9+So the window is ordered NEAREST-FIRST and the propagation assumes each entry
10+is one display step further from the current frame along a continuous chain.
11+
12+* Flat path (encode.rs:13783): `rest[i+1..].take(tpl_depth()-1)` -- strictly
13+ display-FUTURE, nearest first. Forward in time, like libaom.
14+* Pyramid leaves and the mid/quarter ARFs (`code_group`'s `tpl_window(pos,
15+ false)`): the group's own display-order successors. Also forward.
16+* The TOP ARF: `tpl_window(group.len()-1, true)` = `group[..pos].iter().rev()`
17+ -- the group's own sources, which are all display-PAST of it (the top ARF is
18+ its group's LAST picture). Nearest-first is still an adjacent chain, so the
19+ propagation is well-formed, but it runs BACKWARD in time: the window is
20+ TIME-REVERSED relative to the flat path and to libaom's tpl at an ARF, which
21+ looks forward over the next group. That is the premise this lane tested, and
22+ it is confirmed in code.
23+
24+## 2. The arm
25+
26+`speed::TPL_FUT` / `EC_AV1_TPL_FUT=<n>`, read in `Av1Encoder::code_group`
27+(encoder.rs), applying to the TOP ARF only; falls back to mode 0's window
28+whenever `future` is empty (lookahead off, end of stream). The ARF source
29+filter window (`arf_tf_window_future`) is untouched.
30+
31+* 0 -- the display-past window, the shipped behaviour.
32+* 1 -- future-only, nearest first, up to `tpl_depth()-1`.
33+* 2 -- past then future concatenated nearest-first, half the budget each side
34+ (`EC_AV1_TPL_FUT_HALF=<n>` moves the split; default 3 past + 4 future at
35+ `tpl_depth()=8`). The chain has ONE discontinuity in the middle.
36+* 3 -- future-only over the WHOLE buffered next group, ignoring `tpl_depth`.
37+
38+## 3. Deciding gate: `encode::tests::bd_rate_film_long_gop` (48 pictures)
39+
40+BD-rate vs libaom / vs rav1e, lower better; wall is ours.
41+
42+| arm | film A | film B | wall A | wall B |
43+|---|---|---|---|---|
44+| 0, past (control, reproduced) | +21.3% / -8.8% | +72.1% / -1.2% | 671.1s | 461.6s |
45+| 1, future only | +22.0% / -8.6% | +73.1% / -1.1% | 629.6s | 583.1s |
46+| **2, 3 past + 4 future (SHIPS)** | **+21.2% / -8.8%** | **+71.6% / -1.5%** | 692.3s | 462.5s |
47+| 3, whole next group | +21.9% / -8.7% | +72.7% / -1.4% | 573.1s | 455.7s |
48+
49+The control reproduces the standing table (film A +21.2/-8.8, film B
50++72.1/-1.2 at 152996c8), so the arms are read against a live baseline.
51+
52+A future-ONLY window LOSES on every column of both films (modes 1 and 3): the
53+nearest display-past neighbours are what carries the map's propagation for a
54+frame the whole group predicts from. Mode 2 is film B -0.5 / -0.3 and film A
55+-0.1 / 0.0, i.e. one row >=0.5 down and the other flat within +-0.3 -- the
56+lane's keep rule -- at +3.2% (film A) and +0.2% (film B) wall, well under the
57++15% ceiling. `speed::TPL_FUT` defaults to 2.
58+
59+Honest ceiling: mode 2's win is 0.5 point on a +72 number and the split
60+(3+4) was not swept. `EC_AV1_TPL_FUT_HALF` exists for that sweep.
61+
62+## 4. 12-picture native guard (`bd_rate_screen_native`, all three clips on)
63+
64+STRUCTURALLY BLIND to this lever: `group_target` absorbs the 12-picture tail
65+into ONE group of 11, so no next group is ever buffered and mode 2 falls back
66+to the past window on every ARF. Run only as a no-regression guard:
67+
68+| clip | BD vs libaom | BD vs rav1e |
69+|---|---|---|
70+| bars 1080p | -3.2% | -18.8% |
71+| bars 2160p | +8.4% | -13.9% |
72+| film A | +17.9% | -6.3% |
73+| film B | +22.4% | -3.9% |
74+| screen capture | +14.4% | -33.2% |
75+
76+## 5. Witness
77+
78+`encoder::tests::the_future_tpl_window_still_codes_every_picture_and_moves_the_stream`
79+(sibling of the lane-lookahead one), coded at q=60 -- NOT 120, where this
80+fixture's ARF is almost pure skip and re-quantises to identical bytes. At GOP
81+32 and 8, run lengths 1/7/8/9/17, every mode: coding order and levels
82+unchanged, every picture coded, decoded exact through our decoder AND ffmpeg.
83+Modes 1 and 3 MOVE the stream against mode 0 at 17 pictures.
84+
85+Mode 2 does NOT move it on that 128x128 fixture at its default split: it keeps
86+the three nearest past neighbours, which dominate the propagation, and no RD
87+decision flips. Measured, not assumed -- the same run with
88+`EC_AV1_TPL_FUT_HALF=1` (one past, six future) DOES move the stream, and the
89+long-GOP gate above measures mode 2 moving on real content. The witness names
90+this instead of asserting it.
91+
92+## 6. Other gates
93+
94+* Pins `encode::tests::the_encoders_own_streams_are_byte_identical_to_their_pins`:
95+ PASS at the default AND at `EC_AV1_SPEED=6`, unchanged (its 4-picture
96+ fixture has no next group, so the fallback keeps the past window).
97+* `encoder::tests::every_speed_preset_decodes_sample_exact_through_both_decoders`
98+ (--ignored): PASS.
99+* `encoder::tests::bitrate_target_lands_within_5_percent_over_48_frames`:
100+ PASS. Pyramid arm -1.9% is flat: 384k +1.5%, 768k +0.0%, 1536k +0.0%,
101+ 2000k +0.0%; the flat arm -1.9% / -2.6% / -2.8% / -1.7%.
102+* Suite in three lanes and `cargo check --workspace --all-targets`: see the
103+ suite line at the end of this file.
104+
105+## Deviations
106+
107+* The charter's sub-arm (b) "past (+) future concatenated nearest-first" does
108+ not define the split; half-and-half with an env override is what shipped,
109+ and the split is unswept (named above).
110+* `EC_AV1_TPL_FUT_HALF` is an extra knob the charter did not ask for; it is
111+ what makes the witness's mode-2 inertness a measurement rather than a story.
112+
113+## Suite line
114+
115+`ec-av1` lib suite, three detached lanes off one release binary: 347 passed /
116+0 failed (`--skip stream::`), 202 / 0 (`stream:: --skip 10bit`), 42 / 0
117+(`10bit`) -- 591 passed, 0 failed, 55 ignored.
118+`cargo check --workspace --all-targets -j4`: 0 errors, 0 ec-av1 warnings (the
119+21 ec-opus missing-doc warnings and the ec-vorbis oracle one are pre-existing
120+and untouched).