Merge branch 'lane-lookahead' (57b7c510): one mini-GOP of encoder lookahead and a symmetric +-3 ARF filter window; long-GOP film B crosses rav1e speed 6; pins hold at 8291 / 33227
Browse files at this commit4 changed files +471 -10
- crates/ec-av1/src/encode.rs +2 -1
- crates/ec-av1/src/encoder.rs +281 -8
- crates/ec-av1/src/speed.rs +41 -1
- lanes/lookahead.report.md +147 -0
crates/ec-av1/src/encode.rsmodified+2 -1
| @@ -11964,12 +11964,13 @@ pub(crate) struct PyramidFrame { | |||
| 11964 | /// one's (film A 5.9%) with the two past neighbours at strength 30, and the | 11964 | /// one's (film A 5.9%) with the two past neighbours at strength 30, and the |
| 11965 | /// filtered picture is 50.1 dB from the source it replaces -- 4 dB above the | 11965 | /// filtered picture is 50.1 dB from the source it replaces -- 4 dB above the |
| 11966 | /// quality the ARF is coded at, so the substitution itself costs little. | 11966 | /// quality the ARF is coded at, so the substitution itself costs little. |
| 11967 | +// lane-lookahead: the CALLER sizes `window` (`ARF_TF_WIN` past neighbours and | ||
| 11968 | +// `ARF_TF_WIN_FUT` future ones); this takes every picture in it. | ||
| 11967 | pub(crate) fn arf_temporal_filter(src: &Picture, window: &[Picture], strength: f64) -> Picture { | 11969 | pub(crate) fn arf_temporal_filter(src: &Picture, window: &[Picture], strength: f64) -> Picture { |
| 11968 | const SIDE: usize = 16; | 11970 | const SIDE: usize = 16; |
| 11969 | let neighbours: Vec<&Picture> = window | 11971 | let neighbours: Vec<&Picture> = window |
| 11970 | .iter() | 11972 | .iter() |
| 11971 | .filter(|p| p.width == src.width && p.height == src.height) | 11973 | .filter(|p| p.width == src.width && p.height == src.height) |
| 11972 | - .take(crate::encoder::arf_tf_window()) | ||
| 11973 | .collect(); | 11974 | .collect(); |
| 11974 | if neighbours.is_empty() || strength <= 0.0 { | 11975 | if neighbours.is_empty() || strength <= 0.0 { |
| 11975 | return src.clone(); | 11976 | return src.clone(); |
crates/ec-av1/src/encoder.rsmodified+281 -8
| @@ -1238,6 +1238,58 @@ pub(crate) fn arf_tf_window() -> usize { | |||
| 1238 | .unwrap_or_else(|| crate::speed::at(&crate::speed::ARF_TF_WIN)) | 1238 | .unwrap_or_else(|| crate::speed::at(&crate::speed::ARF_TF_WIN)) |
| 1239 | } | 1239 | } |
| 1240 | 1240 | ||
| 1241 | +/// lane-lookahead: how many DISPLAY-FUTURE neighbours the top ARF's filter | ||
| 1242 | +/// takes out of the buffered next group ([`crate::speed::ARF_TF_WIN_FUT`], | ||
| 1243 | +/// `EC_AV1_ARF_TF_WIN_FUT=<n>`). Inert without [`lookahead`]. | ||
| 1244 | +pub(crate) fn arf_tf_window_future() -> usize { | ||
| 1245 | + match ARF_TF_FUT_OVERRIDE.load(std::sync::atomic::Ordering::Relaxed) { | ||
| 1246 | + usize::MAX => {} | ||
| 1247 | + n => return n, | ||
| 1248 | + } | ||
| 1249 | + std::env::var("EC_AV1_ARF_TF_WIN_FUT") | ||
| 1250 | + .ok() | ||
| 1251 | + .and_then(|v| v.parse().ok()) | ||
| 1252 | + .unwrap_or_else(|| crate::speed::at(&crate::speed::ARF_TF_WIN_FUT)) | ||
| 1253 | +} | ||
| 1254 | + | ||
| 1255 | +/// PROCESS-GLOBAL overrides of the two lane-lookahead knobs, the shape | ||
| 1256 | +/// [`set_last2`] has (this crate's tests never call `set_var`); `u8::MAX` / | ||
| 1257 | +/// `usize::MAX` is unset, and a witness holds [`crate::speed::knob_write`] | ||
| 1258 | +/// while it uses them. | ||
| 1259 | +static LOOKAHEAD_OVERRIDE: std::sync::atomic::AtomicU8 = | ||
| 1260 | + std::sync::atomic::AtomicU8::new(u8::MAX); | ||
| 1261 | +static ARF_TF_FUT_OVERRIDE: std::sync::atomic::AtomicUsize = | ||
| 1262 | + std::sync::atomic::AtomicUsize::new(usize::MAX); | ||
| 1263 | + | ||
| 1264 | +/// Sets [`LOOKAHEAD_OVERRIDE`]; `None` clears it. | ||
| 1265 | +#[allow(dead_code)] // set only from the `#[cfg(test)]` witness | ||
| 1266 | +pub(crate) fn set_lookahead(on: Option<bool>) { | ||
| 1267 | + LOOKAHEAD_OVERRIDE.store( | ||
| 1268 | + on.map_or(u8::MAX, u8::from), | ||
| 1269 | + std::sync::atomic::Ordering::Relaxed, | ||
| 1270 | + ); | ||
| 1271 | +} | ||
| 1272 | + | ||
| 1273 | +/// Sets [`ARF_TF_FUT_OVERRIDE`]; `None` clears it. | ||
| 1274 | +#[allow(dead_code)] // set only from the `#[cfg(test)]` witness | ||
| 1275 | +pub(crate) fn set_arf_tf_future(n: Option<usize>) { | ||
| 1276 | + ARF_TF_FUT_OVERRIDE.store(n.unwrap_or(usize::MAX), std::sync::atomic::Ordering::Relaxed); | ||
| 1277 | +} | ||
| 1278 | + | ||
| 1279 | +/// lane-lookahead: whether the pyramid path holds one group of lookahead | ||
| 1280 | +/// ([`crate::speed::LOOKAHEAD`], `EC_AV1_LOOKAHEAD=0|1`). | ||
| 1281 | +fn lookahead() -> bool { | ||
| 1282 | + match LOOKAHEAD_OVERRIDE.load(std::sync::atomic::Ordering::Relaxed) { | ||
| 1283 | + 0 => return false, | ||
| 1284 | + 1 => return true, | ||
| 1285 | + _ => {} | ||
| 1286 | + } | ||
| 1287 | + match std::env::var("EC_AV1_LOOKAHEAD").ok() { | ||
| 1288 | + Some(v) => v != "0", | ||
| 1289 | + None => crate::speed::LOOKAHEAD, | ||
| 1290 | + } | ||
| 1291 | +} | ||
| 1292 | + | ||
| 1241 | fn tpl_pyramid() -> bool { | 1293 | fn tpl_pyramid() -> bool { |
| 1242 | match std::env::var("EC_AV1_TPL_PYRAMID").ok() { | 1294 | match std::env::var("EC_AV1_TPL_PYRAMID").ok() { |
| 1243 | Some(v) => v != "0", | 1295 | Some(v) => v != "0", |
| @@ -1315,6 +1367,11 @@ pub struct Av1Encoder { | |||
| 1315 | dpb: [Option<DpbSlot>; 8], | 1367 | dpb: [Option<DpbSlot>; 8], |
| 1316 | /// Pictures held back waiting for their mini-GOP's hidden frame. | 1368 | /// Pictures held back waiting for their mini-GOP's hidden frame. |
| 1317 | pending: Vec<(u64, Picture)>, | 1369 | pending: Vec<(u64, Picture)>, |
| 1370 | + /// lane-lookahead: the CLOSED group waiting for the next group's sources | ||
| 1371 | + /// before it is coded, so its top ARF -- the group's last picture in | ||
| 1372 | + /// display order -- has display-future neighbours available. Always empty | ||
| 1373 | + /// with [`lookahead`] off. | ||
| 1374 | + ready: Vec<(u64, Picture)>, | ||
| 1318 | /// The flat path's delay queue: pictures whose packets later calls | 1375 | /// The flat path's delay queue: pictures whose packets later calls |
| 1319 | /// return, each coded with the ones behind it as its lookahead window | 1376 | /// return, each coded with the ones behind it as its lookahead window |
| 1320 | /// (lane-av1facade, deepened to [`crate::encode::tpl_depth`] - 1 on | 1377 | /// (lane-av1facade, deepened to [`crate::encode::tpl_depth`] - 1 on |
| @@ -1415,6 +1472,7 @@ impl Av1Encoder { | |||
| 1415 | pyramid: None, | 1472 | pyramid: None, |
| 1416 | dpb: [const { None }; 8], | 1473 | dpb: [const { None }; 8], |
| 1417 | pending: Vec::new(), | 1474 | pending: Vec::new(), |
| 1475 | + ready: Vec::new(), | ||
| 1418 | held: std::collections::VecDeque::new(), | 1476 | held: std::collections::VecDeque::new(), |
| 1419 | anchor: 0, | 1477 | anchor: 0, |
| 1420 | leaf_hist: Vec::new(), | 1478 | leaf_hist: Vec::new(), |
| @@ -1618,7 +1676,7 @@ impl Av1Encoder { | |||
| 1618 | // A key frame closes whatever group is open (there is nothing for | 1676 | // A key frame closes whatever group is open (there is nothing for |
| 1619 | // its leaves to point forward at across the boundary) and then | 1677 | // its leaves to point forward at across the boundary) and then |
| 1620 | // restarts the pyramid from the key itself. | 1678 | // restarts the pyramid from the key itself. |
| 1621 | - let mut packets = self.drain_pending()?; | 1679 | + let mut packets = self.drain_all(Some(picture))?; |
| 1622 | packets.push(self.encode_key(order, picture)?); | 1680 | packets.push(self.encode_key(order, picture)?); |
| 1623 | return Ok(packets); | 1681 | return Ok(packets); |
| 1624 | } | 1682 | } |
| @@ -1655,7 +1713,7 @@ impl Av1Encoder { | |||
| 1655 | } | 1713 | } |
| 1656 | return Ok(packets); | 1714 | return Ok(packets); |
| 1657 | } | 1715 | } |
| 1658 | - self.drain_pending() | 1716 | + self.drain_all(None) |
| 1659 | } | 1717 | } |
| 1660 | 1718 | ||
| 1661 | /// The flat path: one picture and its lookahead (the next source picture, | 1719 | /// The flat path: one picture and its lookahead (the next source picture, |
| @@ -1885,6 +1943,11 @@ impl Av1Encoder { | |||
| 1885 | // from, already padded (lane-arfcen). Empty codes the frame at one | 1943 | // from, already padded (lane-arfcen). Empty codes the frame at one |
| 1886 | // lambda, which is what the whole pyramid path used to do. | 1944 | // lambda, which is what the whole pyramid path used to do. |
| 1887 | lookahead: &[Picture], | 1945 | lookahead: &[Picture], |
| 1946 | + // lane-lookahead: DISPLAY-FUTURE pictures for the SOURCE temporal | ||
| 1947 | + // filter only (the top ARF's, out of the buffered next group), never | ||
| 1948 | + // for the temporal lambda map -- keeping the filter's window and the | ||
| 1949 | + // tpl window separate levers. Empty everywhere else. | ||
| 1950 | + future: &[Picture], | ||
| 1888 | ) -> Result<Packet> { | 1951 | ) -> Result<Packet> { |
| 1889 | let render = (self.config.width, self.config.height); | 1952 | let render = (self.config.width, self.config.height); |
| 1890 | let order_hint = (order & 0x7f) as u32; | 1953 | let order_hint = (order & 0x7f) as u32; |
| @@ -1973,7 +2036,18 @@ impl Av1Encoder { | |||
| 1973 | false => 0.0, | 2036 | false => 0.0, |
| 1974 | }; | 2037 | }; |
| 1975 | let source = match tf > 0.0 { | 2038 | let source = match tf > 0.0 { |
| 1976 | - true => crate::encode::arf_temporal_filter(&source, lookahead, tf), | 2039 | + true => { |
| 2040 | + // lane-lookahead: the filter's window is sized HERE -- up to | ||
| 2041 | + // `ARF_TF_WIN` display-past neighbours (nearest first) and | ||
| 2042 | + // then the display-future ones the caller buffered. | ||
| 2043 | + let window: Vec<Picture> = lookahead | ||
| 2044 | + .iter() | ||
| 2045 | + .take(arf_tf_window()) | ||
| 2046 | + .chain(future.iter()) | ||
| 2047 | + .cloned() | ||
| 2048 | + .collect(); | ||
| 2049 | + crate::encode::arf_temporal_filter(&source, &window, tf) | ||
| 2050 | + } | ||
| 1977 | false => source, | 2051 | false => source, |
| 1978 | }; | 2052 | }; |
| 1979 | let encoded = || -> Result<Encoded> { encode_inter_frame( | 2053 | let encoded = || -> Result<Encoded> { encode_inter_frame( |
| @@ -2029,14 +2103,52 @@ impl Av1Encoder { | |||
| 2029 | Ok(self.packet(cropped.stream, false, order, level)) | 2103 | Ok(self.packet(cropped.stream, false, order, level)) |
| 2030 | } | 2104 | } |
| 2031 | 2105 | ||
| 2032 | - /// Codes the open mini-GOP: its hidden frame first, then its leaves, then | 2106 | + /// Closes the open mini-GOP. With the lookahead off that codes it |
| 2033 | - /// the `show_existing_frame` header that puts the hidden frame back in | 2107 | + /// straight away, which is byte for byte what this encoder did before |
| 2034 | - /// display order. | 2108 | + /// lane-lookahead; with it on the open group takes the `ready` slot and |
| 2109 | + /// the group ALREADY there is coded, with the open one's sources as its | ||
| 2110 | + /// display-future window. | ||
| 2035 | fn drain_pending(&mut self) -> Result<Vec<Packet>> { | 2111 | fn drain_pending(&mut self) -> Result<Vec<Packet>> { |
| 2036 | - if self.pending.is_empty() { | 2112 | + if !lookahead() { |
| 2113 | + let group = std::mem::take(&mut self.pending); | ||
| 2114 | + return self.code_group(group, &[]); | ||
| 2115 | + } | ||
| 2116 | + let group = std::mem::take(&mut self.ready); | ||
| 2117 | + let next = std::mem::take(&mut self.pending); | ||
| 2118 | + let packets = self.code_group(group, &next); | ||
| 2119 | + self.ready = next; | ||
| 2120 | + packets | ||
| 2121 | + } | ||
| 2122 | + | ||
| 2123 | + /// Codes every group still buffered, in coding order -- what a key frame | ||
| 2124 | + /// (`next` is the key picture, the last buffered group's own | ||
| 2125 | + /// display-future) and the end of stream (`None`) both need. The tail | ||
| 2126 | + /// group can be any length, down to the single picture `code_group` | ||
| 2127 | + /// codes as one shown leaf. | ||
| 2128 | + fn drain_all(&mut self, next: Option<&Picture>) -> Result<Vec<Packet>> { | ||
| 2129 | + let tail: Vec<(u64, Picture)> = next | ||
| 2130 | + .filter(|_| lookahead()) | ||
| 2131 | + .map(|p| vec![(self.next_index, p.clone())]) | ||
| 2132 | + .unwrap_or_default(); | ||
| 2133 | + let ready = std::mem::take(&mut self.ready); | ||
| 2134 | + let pending = std::mem::take(&mut self.pending); | ||
| 2135 | + let mut packets = self.code_group(ready, &pending)?; | ||
| 2136 | + packets.extend(self.code_group(pending, &tail)?); | ||
| 2137 | + Ok(packets) | ||
| 2138 | + } | ||
| 2139 | + | ||
| 2140 | + /// Codes one mini-GOP: its hidden frame first, then its leaves, then | ||
| 2141 | + /// the `show_existing_frame` header that puts the hidden frame back in | ||
| 2142 | + /// display order. `future` is the display-future sources the caller has | ||
| 2143 | + /// buffered past this group (lane-lookahead), empty without a lookahead. | ||
| 2144 | + fn code_group( | ||
| 2145 | + &mut self, | ||
| 2146 | + group: Vec<(u64, Picture)>, | ||
| 2147 | + future: &[(u64, Picture)], | ||
| 2148 | + ) -> Result<Vec<Packet>> { | ||
| 2149 | + if group.is_empty() { | ||
| 2037 | return Ok(Vec::new()); | 2150 | return Ok(Vec::new()); |
| 2038 | } | 2151 | } |
| 2039 | - let group: Vec<(u64, Picture)> = std::mem::take(&mut self.pending); | ||
| 2040 | let mut packets = Vec::with_capacity(group.len() + 1); | 2152 | let mut packets = Vec::with_capacity(group.len() + 1); |
| 2041 | // The lookahead window of the group's picture at index `pos`: the | 2153 | // The lookahead window of the group's picture at index `pos`: the |
| 2042 | // display-order successors inside this group, or -- for the group's | 2154 | // display-order successors inside this group, or -- for the group's |
| @@ -2080,10 +2192,21 @@ impl Av1Encoder { | |||
| 2080 | Level::Leaf, | 2192 | Level::Leaf, |
| 2081 | pyramid.leaf_q_offset, | 2193 | pyramid.leaf_q_offset, |
| 2082 | &tpl_window(0, false), | 2194 | &tpl_window(0, false), |
| 2195 | + &[], | ||
| 2083 | )?); | 2196 | )?); |
| 2084 | self.anchor = 1 - self.anchor; | 2197 | self.anchor = 1 - self.anchor; |
| 2085 | return Ok(packets); | 2198 | return Ok(packets); |
| 2086 | } | 2199 | } |
| 2200 | + // lane-lookahead: the display-future half of the top ARF's temporal | ||
| 2201 | + // filter window, padded like the frame itself. Empty when the | ||
| 2202 | + // lookahead is off (`future` is then always empty) or when the filter | ||
| 2203 | + // asks for no future neighbours, which is what keeps the default | ||
| 2204 | + // stream byte-identical. | ||
| 2205 | + let arf_future: Vec<Picture> = future | ||
| 2206 | + .iter() | ||
| 2207 | + .take(arf_tf_window_future()) | ||
| 2208 | + .map(|(_, p)| p.padded_to(SUPERBLOCK)) | ||
| 2209 | + .collect(); | ||
| 2087 | // The group's top level: the last picture, hidden, off the anchor. | 2210 | // The group's top level: the last picture, hidden, off the anchor. |
| 2088 | packets.push(self.encode_pyramid_inter( | 2211 | packets.push(self.encode_pyramid_inter( |
| 2089 | arf_order, | 2212 | arf_order, |
| @@ -2106,6 +2229,10 @@ impl Av1Encoder { | |||
| 2106 | Level::Arf, | 2229 | Level::Arf, |
| 2107 | pyramid.arf_q_offset, | 2230 | pyramid.arf_q_offset, |
| 2108 | &tpl_window(group.len() - 1, true), | 2231 | &tpl_window(group.len() - 1, true), |
| 2232 | + // lane-lookahead: the group's top ARF is its LAST picture in | ||
| 2233 | + // display order, so every picture of the next group is a | ||
| 2234 | + // display-future neighbour of it -- nearest first. | ||
| 2235 | + &arf_future, | ||
| 2109 | )?); | 2236 | )?); |
| 2110 | let leaves = group.len() - 1; | 2237 | let leaves = group.len() - 1; |
| 2111 | // THE THIRD LEVEL: a second hidden frame at the middle of the leaf | 2238 | // THE THIRD LEVEL: a second hidden frame at the middle of the leaf |
| @@ -2140,6 +2267,7 @@ impl Av1Encoder { | |||
| 2140 | Level::Arf, | 2267 | Level::Arf, |
| 2141 | offset, | 2268 | offset, |
| 2142 | &tpl_window(at, false), | 2269 | &tpl_window(at, false), |
| 2270 | + &[], | ||
| 2143 | )?); | 2271 | )?); |
| 2144 | } | 2272 | } |
| 2145 | // THE FOURTH LEVEL: one hidden frame at the middle of each half of | 2273 | // THE FOURTH LEVEL: one hidden frame at the middle of each half of |
| @@ -2177,6 +2305,7 @@ impl Av1Encoder { | |||
| 2177 | Level::Arf, | 2305 | Level::Arf, |
| 2178 | offset, | 2306 | offset, |
| 2179 | &tpl_window(pos, false), | 2307 | &tpl_window(pos, false), |
| 2308 | + &[], | ||
| 2180 | )?); | 2309 | )?); |
| 2181 | } | 2310 | } |
| 2182 | } | 2311 | } |
| @@ -2253,6 +2382,7 @@ impl Av1Encoder { | |||
| 2253 | Level::Leaf, | 2382 | Level::Leaf, |
| 2254 | pyramid.leaf_q_offset, | 2383 | pyramid.leaf_q_offset, |
| 2255 | &tpl_window(i, false), | 2384 | &tpl_window(i, false), |
| 2385 | + &[], | ||
| 2256 | )?); | 2386 | )?); |
| 2257 | } | 2387 | } |
| 2258 | let packet = show_existing(self, next_anchor_slot, arf_order)?; | 2388 | let packet = show_existing(self, next_anchor_slot, arf_order)?; |
| @@ -3515,6 +3645,149 @@ mod tests { | |||
| 3515 | assert_eq!(shown, arfs, "one show_existing_frame per hidden frame"); | 3645 | assert_eq!(shown, arfs, "one show_existing_frame per hidden frame"); |
| 3516 | } | 3646 | } |
| 3517 | 3647 | ||
| 3648 | + /// A picture whose content is a static gradient plus a per-picture | ||
| 3649 | + /// pseudo-random +-2 of noise: motion search matches the neighbours | ||
| 3650 | + /// almost exactly, so the ARF temporal filter's weights are near 1 and | ||
| 3651 | + /// the filter actually changes the source (a moving test card gives every | ||
| 3652 | + /// neighbour a large MSE, weight ~0, and the filter is a no-op that would | ||
| 3653 | + /// make the future-window witness below pass blind). | ||
| 3654 | + fn noisy_card(width: usize, height: usize, t: usize) -> Picture { | ||
| 3655 | + let mut picture = Picture::grey(width, height); | ||
| 3656 | + let mut seed = (t as u64 + 1).wrapping_mul(0x9e37_79b9_7f4a_7c15); | ||
| 3657 | + for y in 0..height { | ||
| 3658 | + for x in 0..width { | ||
| 3659 | + seed = seed.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1); | ||
| 3660 | + let noise = ((seed >> 33) % 5) as i32 - 2; | ||
| 3661 | + let base = 40 + (x + y) as i32 / 2; | ||
| 3662 | + picture.y[y * width + x] = base.saturating_add(noise).clamp(0, 255) as u16; | ||
| 3663 | + } | ||
| 3664 | + } | ||
| 3665 | + for i in 0..(width / 2) * (height / 2) { | ||
| 3666 | + picture.u[i] = 110; | ||
| 3667 | + picture.v[i] = 140; | ||
| 3668 | + } | ||
| 3669 | + picture | ||
| 3670 | + } | ||
| 3671 | + | ||
| 3672 | + /// lane-lookahead's correctness witness. One group of lookahead | ||
| 3673 | + /// (`Av1Encoder::drain_pending` hands the closed group to `ready` and | ||
| 3674 | + /// codes the group before it) must not change WHAT is coded: | ||
| 3675 | + /// | ||
| 3676 | + /// * with the future half of the filter window empty the stream is byte | ||
| 3677 | + /// for byte the one the encoder coded without a lookahead, at every | ||
| 3678 | + /// run length -- 1 picture (no hidden frame at all), 7 (a short group), | ||
| 3679 | + /// 8 (exactly `mini_gop`), 9 (a group plus a tail) and 17 -- and at a | ||
| 3680 | + /// GOP short enough (8) that key frames drain the buffer mid-run; | ||
| 3681 | + /// * every run decodes to exactly its picture count through OUR decoder | ||
| 3682 | + /// and through ffmpeg, sample-exact between the two, so the flush and | ||
| 3683 | + /// the `show_existing_frame` order survive the delay; | ||
| 3684 | + /// * and with ONE future neighbour the top ARF's source filter actually | ||
| 3685 | + /// reads it -- the stream MOVES (class gate-blind-to-feature: a | ||
| 3686 | + /// buffered picture nothing consumes would pass every check above). | ||
| 3687 | + #[test] | ||
| 3688 | + fn the_lookahead_holds_one_group_and_still_codes_every_picture() { | ||
| 3689 | + let _knobs = crate::speed::knob_write(); | ||
| 3690 | + // The preset is PROCESS-GLOBAL and another test may have left it | ||
| 3691 | + // anywhere: at a high one every block of this fixture codes as skip | ||
| 3692 | + // (17 pictures in 493 bytes) and the source filter cannot change a | ||
| 3693 | + // byte, which failed the future-half assertion below in the suite and | ||
| 3694 | + // passed it standalone (class process-global-knob-races-tests). | ||
| 3695 | + let was = crate::speed::speed(); | ||
| 3696 | + crate::speed::set_speed(0); | ||
| 3697 | + crate::encode::force_screen(Some(false)); | ||
| 3698 | + let (width, height) = (128usize, 128usize); | ||
| 3699 | + let run = |n: usize, gop: usize, on: bool, fut: usize| -> (Vec<u8>, Vec<Packet>) { | ||
| 3700 | + set_lookahead(Some(on)); | ||
| 3701 | + set_arf_tf_future(Some(fut)); | ||
| 3702 | + let config = EncoderConfig { | ||
| 3703 | + // FINE (not the 120 the other facade tests use): at a coarse | ||
| 3704 | + // quantizer this fixture's ARF codes almost pure skip (17 | ||
| 3705 | + // pictures in 493 bytes) and a filtered source quantizes back | ||
| 3706 | + // to the same bytes, which made the future-half assertion | ||
| 3707 | + // below depend on where the suite's other tests had left the | ||
| 3708 | + // process-global preset. At q=60 the anchor carries real | ||
| 3709 | + // coefficients and the filter must move them. | ||
| 3710 | + base_q_idx: 60, | ||
| 3711 | + width, | ||
| 3712 | + height, | ||
| 3713 | + gop, | ||
| 3714 | + colour: Colour::Bt709Limited, | ||
| 3715 | + tile_cols_log2: 0, | ||
| 3716 | + tile_rows_log2: 0, | ||
| 3717 | + }; | ||
| 3718 | + let mut enc = Av1Encoder::with_pyramid(config, Pyramid::default()).unwrap(); | ||
| 3719 | + let sources: Vec<Picture> = (0..n).map(|t| noisy_card(width, height, t)).collect(); | ||
| 3720 | + let packets = encode_all(&mut enc, &sources); | ||
| 3721 | + // The content gate is process-global and so is the preset: if | ||
| 3722 | + // either has been flipped under this test the pyramid is gone and | ||
| 3723 | + // there is no ARF to filter, which is a different failure from | ||
| 3724 | + // "the future neighbour changed nothing" (the suite reported the | ||
| 3725 | + // second when it meant the first). | ||
| 3726 | + assert!( | ||
| 3727 | + enc.pyramid().is_some(), | ||
| 3728 | + "{n} pictures at gop {gop}: the content gate dropped the pyramid, so no ARF was coded (speed {})", | ||
| 3729 | + crate::speed::speed(), | ||
| 3730 | + ); | ||
| 3731 | + (concat(&packets), packets) | ||
| 3732 | + }; | ||
| 3733 | + for gop in [32usize, 8] { | ||
| 3734 | + for n in [1usize, 7, 8, 9, 17] { | ||
| 3735 | + let (flat, flat_packets) = run(n, gop, false, 0); | ||
| 3736 | + let (held, packets) = run(n, gop, true, 0); | ||
| 3737 | + assert_eq!( | ||
| 3738 | + flat.len(), | ||
| 3739 | + held.len(), | ||
| 3740 | + "{n} pictures at gop {gop}: the lookahead changed the stream LENGTH" | ||
| 3741 | + ); | ||
| 3742 | + assert!(flat == held, "{n} pictures at gop {gop}: the stream is not byte-identical"); | ||
| 3743 | + assert_eq!( | ||
| 3744 | + packets.iter().map(|p| (p.order, p.key, p.level)).collect::<Vec<_>>(), | ||
| 3745 | + flat_packets.iter().map(|p| (p.order, p.key, p.level)).collect::<Vec<_>>(), | ||
| 3746 | + "{n} pictures at gop {gop}: coding order/levels moved" | ||
| 3747 | + ); | ||
| 3748 | + let ours = crate::stream::decode_stream(&held).expect("our decoder"); | ||
| 3749 | + assert_eq!(ours.len(), n, "{n} pictures at gop {gop}: our decoder's count"); | ||
| 3750 | + if !have_ffmpeg() { | ||
| 3751 | + continue; | ||
| 3752 | + } | ||
| 3753 | + let theirs = ffmpeg_decode_luma(&held, width, height); | ||
| 3754 | + assert_eq!(theirs.len(), n, "{n} pictures at gop {gop}: ffmpeg's count"); | ||
| 3755 | + for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() { | ||
| 3756 | + let got: Vec<u8> = a.y.iter().map(|&v| v as u8).collect(); | ||
| 3757 | + assert!( | ||
| 3758 | + got == *b, | ||
| 3759 | + "{n} pictures at gop {gop}, display frame {i}: ours differs from ffmpeg" | ||
| 3760 | + ); | ||
| 3761 | + } | ||
| 3762 | + } | ||
| 3763 | + } | ||
| 3764 | + // The future half REACHES the filter, and what it produces still | ||
| 3765 | + // decodes exactly. | ||
| 3766 | + let (base, _) = run(17, 32, true, 0); | ||
| 3767 | + let (symmetric, _) = run(17, 32, true, 1); | ||
| 3768 | + set_lookahead(None); | ||
| 3769 | + set_arf_tf_future(None); | ||
| 3770 | + assert!( | ||
| 3771 | + base != symmetric, | ||
| 3772 | + "one display-future neighbour left the top ARF's filter unchanged \ | ||
| 3773 | + ({} B vs {} B, preset {})", | ||
| 3774 | + base.len(), | ||
| 3775 | + symmetric.len(), | ||
| 3776 | + crate::speed::speed() | ||
| 3777 | + ); | ||
| 3778 | + let ours = crate::stream::decode_stream(&symmetric).expect("our decoder"); | ||
| 3779 | + assert_eq!(ours.len(), 17, "the symmetric arm's display-order count"); | ||
| 3780 | + if have_ffmpeg() { | ||
| 3781 | + let theirs = ffmpeg_decode_luma(&symmetric, width, height); | ||
| 3782 | + assert_eq!(theirs.len(), 17, "the symmetric arm's ffmpeg count"); | ||
| 3783 | + for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() { | ||
| 3784 | + let got: Vec<u8> = a.y.iter().map(|&v| v as u8).collect(); | ||
| 3785 | + assert!(got == *b, "symmetric arm, display frame {i}: ours differs from ffmpeg"); | ||
| 3786 | + } | ||
| 3787 | + } | ||
| 3788 | + crate::speed::set_speed(was); | ||
| 3789 | + } | ||
| 3790 | + | ||
| 3518 | fn pyramid_round_trip(pyramid: Pyramid, hidden: usize) { | 3791 | fn pyramid_round_trip(pyramid: Pyramid, hidden: usize) { |
| 3519 | let (width, height) = (128usize, 128usize); | 3792 | let (width, height) = (128usize, 128usize); |
| 3520 | let config = EncoderConfig { | 3793 | let config = EncoderConfig { |
crates/ec-av1/src/speed.rsmodified+41 -1
| @@ -433,7 +433,47 @@ pub(crate) const ARF_TF_MID: [f64; 11] = [0.0; 11]; | |||
| 433 | /// measured with two neighbours on EACH side; four pictures of one-sided | 433 | /// measured with two neighbours on EACH side; four pictures of one-sided |
| 434 | /// past is a different (and worse) window, and the anchor drifts away from | 434 | /// past is a different (and worse) window, and the anchor drifts away from |
| 435 | /// the leaves it has to predict. | 435 | /// the leaves it has to predict. |
| 436 | -pub(crate) const ARF_TF_WIN: [usize; 11] = [2; 11]; | 436 | +/// |
| 437 | +/// lane-lookahead gave the encoder the future half ([`LOOKAHEAD`]) and swept | ||
| 438 | +/// the SYMMETRIC window (this many past neighbours and [`ARF_TF_WIN_FUT`] | ||
| 439 | +/// future ones) on the long-GOP gate at strength 2: | ||
| 440 | +/// | ||
| 441 | +/// | window | film A | film B | | ||
| 442 | +/// |---|---|---| | ||
| 443 | +/// | +-0 (2 past, the control) | +22.0/-8.4 | +76.5/+1.2 | | ||
| 444 | +/// | +-1 | +21.4/-8.8 | +74.3/+0.3 | | ||
| 445 | +/// | +-2 | +21.2/-8.8 | +72.3/-0.9 | | ||
| 446 | +/// | **+-3 (ships)** | **+21.2/-8.8** | **+72.1/-1.2** | | ||
| 447 | +/// | +-4 | +21.5/-8.7 | +72.5/-1.0 | | ||
| 448 | +/// | ||
| 449 | +/// Bracketed on both sides and down on all four columns against the control | ||
| 450 | +/// (film A -0.8/-0.4, film B -4.4/-2.4). The census's shape is confirmed: | ||
| 451 | +/// what a wider window cost past-only, it buys symmetric. | ||
| 452 | +pub(crate) const ARF_TF_WIN: [usize; 11] = [3; 11]; | ||
| 453 | + | ||
| 454 | +/// lane-lookahead: how many DISPLAY-FUTURE neighbours the top ARF's temporal | ||
| 455 | +/// filter averages in, on top of [`ARF_TF_WIN`] past ones. Non-zero needs | ||
| 456 | +/// [`LOOKAHEAD`] -- the future pictures are the next group's sources, which | ||
| 457 | +/// the encoder buffers only with the lookahead on. | ||
| 458 | +/// `EC_AV1_ARF_TF_WIN_FUT=<n>` overrides it. The sweep is [`ARF_TF_WIN`]'s | ||
| 459 | +/// table (the two move together, +-n); strength 3 at +-2 loses to strength 2 | ||
| 460 | +/// (film A +21.5/-8.7, film B +73.1/-0.7 against +21.2/-8.8 and +72.3/-0.9), | ||
| 461 | +/// so [`ARF_TF`] stays where lane-arftf put it. | ||
| 462 | +pub(crate) const ARF_TF_WIN_FUT: [usize; 11] = [3; 11]; | ||
| 463 | + | ||
| 464 | +/// lane-lookahead: whether [`crate::encoder::Av1Encoder`] holds one whole | ||
| 465 | +/// mini-GOP of lookahead -- the next group's sources are buffered before the | ||
| 466 | +/// current group's top ARF is coded, so that ARF has display-FUTURE pictures | ||
| 467 | +/// available. Costs one group of latency (`mini_gop` pictures, 8 by default) | ||
| 468 | +/// and one group of source buffer -- [`crate::encode::Picture`] holds u16 | ||
| 469 | +/// samples, so a 3840x2160 4:2:0 picture is 24.9 MB and the group is 199 MB | ||
| 470 | +/// on top of the group the encoder already buffered -- and nothing else: with | ||
| 471 | +/// [`ARF_TF_WIN_FUT`] at 0 nothing reads the future half and the streams are | ||
| 472 | +/// byte-identical. `EC_AV1_LOOKAHEAD=0|1` overrides it. What it BUYS is | ||
| 473 | +/// [`ARF_TF_WIN_FUT`]: the symmetric filter window is the long-GOP gate's | ||
| 474 | +/// film A -0.8/-0.4 and film B -4.4/-2.4, and the buffer is also what a | ||
| 475 | +/// two-pass-like allocation would need. | ||
| 476 | +pub(crate) const LOOKAHEAD: bool = true; | ||
| 437 | 477 | ||
| 438 | /// lane-arfpred: the qindex below which the ARF temporal filter is OFF -- | 478 | /// lane-arfpred: the qindex below which the ARF temporal filter is OFF -- |
| 439 | /// libaom scales `arnr` strength with the quantizer and stops filtering at | 479 | /// libaom scales `arnr` strength with the quantizer and stops filtering at |
lanes/lookahead.report.mdadded+147 -0
| @@ -0,0 +1,147 @@ | |||
| 1 | +# lane-lookahead — one mini-GOP of lookahead, and the ARF filter's future half | ||
| 2 | + | ||
| 3 | +Worktree `edith_codecs-lookahead`, branch `lane-lookahead` off main `eb2af4ee`. | ||
| 4 | +Deciding gate `encode::tests::bd_rate_film_long_gop` (48 pictures, both film | ||
| 5 | +rows, BD vs libaom `cpu-used 6` / rav1e `speed 6`, lower is better). | ||
| 6 | +**Control RUN, not quoted: film A +22.0 / −8.4, film B +76.5 / +1.2** — the | ||
| 7 | +charter's +22.2/−8.2 and +77.5/+1.7 to within the gate's own noise. | ||
| 8 | + | ||
| 9 | +## 1. The machinery — one group held back | ||
| 10 | + | ||
| 11 | +`Av1Encoder::drain_pending` used to code the group it had just closed. It now | ||
| 12 | +hands that group to a new `ready` slot and codes the group ALREADY there, | ||
| 13 | +passing the just-closed group's sources as its display-FUTURE window; the | ||
| 14 | +group's top ARF is its last picture in display order, so every picture of the | ||
| 15 | +next group is a future neighbour of it. `code_group` (the old `drain_pending` | ||
| 16 | +body) takes the group and that future slice as arguments, and `drain_all` | ||
| 17 | +codes both buffered groups in coding order — what a key frame (the key | ||
| 18 | +picture itself is then the last group's future) and `flush` (nothing behind | ||
| 19 | +it) both need. | ||
| 20 | + | ||
| 21 | +* **Latency**: one `mini_gop`, 8 pictures at the default pyramid, on top of | ||
| 22 | + the group the encoder already buffered. | ||
| 23 | +* **Memory**: `Picture` holds u16 samples, so a 3840x2160 4:2:0 source is | ||
| 24 | + 24.9 MB and the extra group is **199 MB at 4K** (56 MB at 1080p). Nothing | ||
| 25 | + else is retained: `ready` holds sources, not reconstructions. | ||
| 26 | +* Output picture order, timestamps and the `show_existing_frame` headers are | ||
| 27 | + untouched — the packets are the same packets, emitted one group later. | ||
| 28 | + | ||
| 29 | +`speed::LOOKAHEAD` (`EC_AV1_LOOKAHEAD=0|1`) switches it off: the open group is | ||
| 30 | +then coded straight away, which is byte for byte the old encoder. | ||
| 31 | + | ||
| 32 | +### The witness — `encoder::tests::the_lookahead_holds_one_group_and_still_codes_every_picture` | ||
| 33 | + | ||
| 34 | +At 1, 7, 8, 9 and 17 pictures, at GOP 32 (one key) and GOP 8 (keys drain the | ||
| 35 | +buffer mid-run), with a gradient-plus-noise fixture: | ||
| 36 | + | ||
| 37 | +* the stream is **byte-identical** to the same run with the lookahead off, and | ||
| 38 | + the packet (order, key, level) list is identical — the delay changes nothing | ||
| 39 | + about WHAT is coded while the future window is empty; | ||
| 40 | +* every run decodes to **exactly its picture count** through `decode_stream` | ||
| 41 | + AND through ffmpeg, **sample-exact between the two**, so the flush, the | ||
| 42 | + short final group (1 picture = one shown leaf, no hidden frame) and the | ||
| 43 | + display order all survive the delay; | ||
| 44 | +* with ONE future neighbour the stream **MOVES** — the buffered picture is | ||
| 45 | + really consumed ([[gate-blind-to-feature]]: everything above would pass over | ||
| 46 | + a lookahead nothing reads) — and still decodes sample-exact. | ||
| 47 | + | ||
| 48 | +RED first, twice, and both reds were the FIXTURE, not the encoder. In the | ||
| 49 | +split suite (never standalone) the future-half assertion failed with "493 B | ||
| 50 | +both": at the q=120 the other facade tests use, this fixture's ARF codes | ||
| 51 | +almost pure skip, and a filtered source quantizes back to the same bytes — | ||
| 52 | +whether it does depends on where the suite's other tests left the | ||
| 53 | +process-global preset, which is why it passed alone and failed in company | ||
| 54 | +(class `process-global-knob-races-tests`). Pinning `set_speed(0)` under | ||
| 55 | +`knob_write` (the byte pins' shape) did NOT fix it — the added assertion that | ||
| 56 | +`enc.pyramid()` survived the content gate ruled the second suspect out — and | ||
| 57 | +what fixed it is coding the witness at **q=60**, where the anchor carries real | ||
| 58 | +coefficients and a filtered source must move them. Both guards ship. | ||
| 59 | + | ||
| 60 | +The gate is a second witness: `native_bd_arm` asserts our decoder's | ||
| 61 | +display-order count and ffmpeg sample-exactness for every one of its 48-picture | ||
| 62 | +streams, and all six long-GOP arms below ran RC=0. | ||
| 63 | + | ||
| 64 | +## 2. The symmetric filter window — it pays, and it is bracketed | ||
| 65 | + | ||
| 66 | +`speed::ARF_TF_WIN` is the PAST neighbour count, new `speed::ARF_TF_WIN_FUT` | ||
| 67 | +(`EC_AV1_ARF_TF_WIN_FUT=<n>`) the FUTURE one; the caller now sizes the window | ||
| 68 | +and `encode::arf_temporal_filter` takes all of it. The tpl lookahead window is | ||
| 69 | +a separate argument (`encode_pyramid_inter`'s new `future` reaches the source | ||
| 70 | +filter only), so this arm is the filter's window and nothing else. | ||
| 71 | + | ||
| 72 | +Long-GOP gate, strength 2 (lane-arftf's shipped point): | ||
| 73 | + | ||
| 74 | +| window | film A | film B | | ||
| 75 | +|---|---|---| | ||
| 76 | +| ±0 = 2 past (control) | +22.0 / −8.4 | +76.5 / +1.2 | | ||
| 77 | +| ±1 | +21.4 / −8.8 | +74.3 / +0.3 | | ||
| 78 | +| ±2 | +21.2 / −8.8 | +72.3 / −0.9 | | ||
| 79 | +| **±3 (ships)** | **+21.2 / −8.8** | **+72.1 / −1.2** | | ||
| 80 | +| ±4 | +21.5 / −8.7 | +72.5 / −1.0 | | ||
| 81 | + | ||
| 82 | +**Down on all four columns against the control** (film A −0.8/−0.4, film B | ||
| 83 | +−4.4/−2.4), which clears the keep rule outright, and BRACKETED on both sides — | ||
| 84 | +±4 is worse than ±3 on all four, so this is not a result at its own search | ||
| 85 | +edge. `arf_pred_census`'s reading is confirmed: what a wider window cost | ||
| 86 | +past-only (lane-arftf refuted 4 past at +22.8/−7.8, +78.9/+2.8) it buys | ||
| 87 | +symmetric. | ||
| 88 | + | ||
| 89 | +Deviation from the charter, named: ±3 and ±4 were run on top of the chartered | ||
| 90 | +±1/±2 because ±2 was the best point of a range with nothing above it. | ||
| 91 | + | ||
| 92 | +Strength re-swept at ±2, as chartered: | ||
| 93 | + | ||
| 94 | +| arm | film A | film B | | ||
| 95 | +|---|---|---| | ||
| 96 | +| ±2, strength 2 | +21.2 / −8.8 | +72.3 / −0.9 | | ||
| 97 | +| ±2, strength 3 | +21.5 / −8.7 | +73.1 / −0.7 | | ||
| 98 | + | ||
| 99 | +Worse on three columns, so `ARF_TF` stays at 2. | ||
| 100 | + | ||
| 101 | +## 3. Guard rows — `bd_rate_screen_native`, 12 pictures, all five rows | ||
| 102 | + | ||
| 103 | +| clip | control | shipped (lookahead + ±3) | Δ | | ||
| 104 | +|---|---|---|---| | ||
| 105 | +| bars 1080p | −3.5 / −19.0 | −3.4 / −19.0 | +0.1 / 0.0 | | ||
| 106 | +| bars 2160p | +8.6 / −13.7 | +8.6 / −13.7 | 0.0 / 0.0 | | ||
| 107 | +| film A | +17.9 / −6.4 | +17.9 / −6.3 | 0.0 / +0.1 | | ||
| 108 | +| film B | +22.9 / −3.6 | +22.8 / −3.6 | −0.1 / 0.0 | | ||
| 109 | +| screen capture | +14.4 / −33.2 | +14.4 / −33.2 | byte-identical | | ||
| 110 | + | ||
| 111 | +Nothing moves by more than 0.1. Measured fact worth keeping: at 12 pictures | ||
| 112 | +`group_target` absorbs the tail into ONE group of 11, so there is no next | ||
| 113 | +group to buffer and **the 12-frame gate cannot see this lever at all** — a | ||
| 114 | +±2 arm run at that length was byte-identical to its control on every row. The | ||
| 115 | +rows above move only through the wider PAST window (2 → 3). | ||
| 116 | + | ||
| 117 | +## 4. Invariants | ||
| 118 | + | ||
| 119 | +* **Byte pins UNCHANGED**, green at the default and at `EC_AV1_SPEED=6`: | ||
| 120 | + `(150, 8290, 0x92cb11033d1f5813)`, `(60, 33227, 0x57ee6b1f8eacd881)`. Not a | ||
| 121 | + miss — the pin fixture is four pictures through `encode_sequence`, one | ||
| 122 | + truncated group whose ARF has two past neighbours and no next group at all, | ||
| 123 | + so neither the lookahead nor a 3-wide window can reach it. | ||
| 124 | +* `encoder::tests::bitrate_target_lands_within_5_percent_over_48_frames` | ||
| 125 | + green and NOT near its bound any more: pyramid arms −0.1% (768 kbps), +0.0% | ||
| 126 | + (1536 kbps), +0.0% (2 Mbps); flat arms −2.5% / −2.8% / −1.8%. | ||
| 127 | +* Split suite at the shipped default: `--skip stream::` **346 passed / 0 | ||
| 128 | + failed**, `stream:: --skip 10bit` **202 passed / 0 failed**, `10bit` **42 | ||
| 129 | + passed / 0 failed** (590 in all). | ||
| 130 | +* `--ignored --exact | ||
| 131 | + encoder::tests::every_speed_preset_decodes_sample_exact_through_both_decoders` | ||
| 132 | + 1 passed. | ||
| 133 | +* `cargo check --workspace --all-targets -j4`: 0 errors, 0 `ec-av1` warnings. | ||
| 134 | + | ||
| 135 | +## 5. What this lane did NOT do | ||
| 136 | + | ||
| 137 | +* `deferred: the tpl window at the ARF (the charter's task 3) — the buffered | ||
| 138 | + future pictures reach the SOURCE filter only; encode_pyramid_inter still | ||
| 139 | + gets tpl_window(pos, true), the display-past leaves, for its temporal | ||
| 140 | + lambda map — unblocked by a lane with long-GOP arms to spend, and it is now | ||
| 141 | + a one-argument change (pass the same future slice as lookahead).` | ||
| 142 | +* `deferred: two-pass-like allocation over the buffered group (the rate loop | ||
| 143 | + still plans per level from gop_shape, blind to the group it holds) — out of | ||
| 144 | + this charter's scope; the buffer it needs now exists.` | ||
| 145 | +* `deferred: per-block weight refinement in arf_temporal_filter (libaom | ||
| 146 | + weights each 16x16 block against each neighbour separately) — untouched | ||
| 147 | + since lane-arftf.` | ||