diff --git a/crates/ec-av1/src/encode.rs b/crates/ec-av1/src/encode.rs index 7dbcb05c..b669169c 100644 --- a/crates/ec-av1/src/encode.rs +++ b/crates/ec-av1/src/encode.rs @@ -960,6 +960,23 @@ thread_local! { static SCREEN_FORCE: std::cell::Cell> = const { std::cell::Cell::new(None) }; } +thread_local! { + /// What the last [`encode_sequence_with_ctx`] call on this thread coded + /// under, AFTER the content gate: the pyramid, or `None` for a stream + /// that stayed flat. Read by the BD gates, which print the requested and + /// the effective pyramid side by side -- a screen clip requests one and + /// codes flat, and that difference is the gate (class + /// `gate-blind-to-feature`). + static LAST_SEQ_PYRAMID: std::cell::Cell> = + const { std::cell::Cell::new(None) }; +} + +/// The pyramid the last sequence coded on this thread was EFFECTIVELY under. +#[allow(dead_code)] // read only from the `#[cfg(test)]` gates +pub(crate) fn last_sequence_pyramid() -> Option { + LAST_SEQ_PYRAMID.with(std::cell::Cell::get) +} + #[cfg(test)] pub(crate) fn force_screen(value: Option) { SCREEN_FORCE.with(|c| c.set(value)); @@ -9012,6 +9029,42 @@ pub(crate) fn encode_sequence_with_ctx( }; first.check_even()?; let render = (first.width, first.height); + // THE CODING PYRAMID (lane-av1pyrdef): a sequence of camera material is + // coded as mini-GOPs -- a hidden ALTREF ahead of its display position, + // the leaves that predict backward off it, and a `show_existing_frame` + // header that re-outputs it -- unless `EC_AV1_PYRAMID` turns it off for + // an A/B. Screen content stays flat (the content gate in + // `Av1Encoder::encode_frames`, whose detector this asks first so the + // whole sequence path is decided in one place), and so does a run that + // asks for a quantizer rounding offset the facade does not carry: the + // facade codes at `encoder::DEADZONE` (0.5), so any other deadzone -- + // the ablations' -- must keep the flat path rather than be silently + // ignored. + // + // The reordering itself is NOT reimplemented here: it is the facade's + // own driver ([`crate::encoder::Av1Encoder::encode_sequence_pyramid`]), + // called with this sequence's shape, so the two paths cannot drift. + let pyramid = crate::encoder::Pyramid::from_env() + .filter(|_| !rest.is_empty() && (deadzone - 0.5).abs() < f64::EPSILON) + .filter(|_| !picture_is_screen(first)); + LAST_SEQ_PYRAMID.with(|c| c.set(pyramid)); + if let Some(pyramid) = pyramid { + for picture in rest { + picture.check_even()?; + if (picture.width, picture.height) != render { + return Err(Error::unsupported( + "AV1 encode", + "every picture in a sequence must be the same size as the first", + )); + } + } + return crate::encoder::Av1Encoder::encode_sequence_pyramid( + pictures, + base_q_idx, + pyramid, + armed_tiles(), + ); + } // The key frame and every inter frame after it are coded at the same // padded size, so the reference each inter frame predicts from -- the // previous frame's own uncropped reconstruction, at the size a decoder's @@ -12326,33 +12379,19 @@ mod tests { / source.len() as f64; ladder.push((mean, (encoded.stream.len() as f64).log10())); } + // What this clip asked for and what the content gate left it coding + // under: a screen clip requests a pyramid and codes flat, and that + // difference is what keeps its row identical to the flat baseline + // (class `gate-blind-to-feature`). + eprintln!( + "{name}: sequence, pyramid requested {:?} effective {:?}", + crate::encoder::Pyramid::from_env(), + last_sequence_pyramid(), + ); ladder.sort_by(|a, b| a.0.total_cmp(&b.0)); (ladder, wall) } - /// The [`crate::encoder::Pyramid`] this run's ladder is coded under, from - /// `EC_AV1_PYRAMID=[::]`. Unset - /// keeps the flat one-key-then-all-inter ladder the baseline was measured - /// on, so the gate's default recipe is unchanged. - /// - /// RE-SWEPT on lane-av1pyrgate under the content gate (see - /// [`crate::encoder::Pyramid`]'s own table): with the screen capture - /// coding flat by construction, `4:-16:8` takes film A +62.8/+32.5 -> - /// +54.1/+24.2 and film B +86.3/+50.5 -> +82.6/+47.4, and the screen row - /// is unchanged to the byte. The gate ladder still defaults to flat -- - /// the sequence path this arm is pinned against codes no pyramid. - fn pyramid_from_env() -> Option { - let spec = std::env::var("EC_AV1_PYRAMID").ok()?; - let mut f = spec.split(':'); - let mini_gop = f.next()?.parse().ok()?; - let d = crate::encoder::Pyramid::default(); - Some(crate::encoder::Pyramid { - mini_gop, - arf_q_offset: f.next().and_then(|v| v.parse().ok()).unwrap_or(d.arf_q_offset), - leaf_q_offset: f.next().and_then(|v| v.parse().ok()).unwrap_or(d.leaf_q_offset), - }) - } - /// [`our_ladder`] through the streaming facade — the surface the editor's /// export drives (`EC_AV1_GATE_FACADE=1`). With a [`crate::encoder::Pyramid`] /// each stream is also reordered (hidden `ALTREF` first, @@ -12778,14 +12817,16 @@ mod tests { let _ = crate::tile::take_compound_size_hits(); let _ = crate::tile::take_compound_leaf_mode_hits(); let _ = crate::motion::take_census(); - let pyramid_env = pyramid_from_env(); // The entry-surface arm: run the SAME ladder through the // streaming facade the editor's export calls, which must print - // the same BD numbers as the sequence path. + // the same BD numbers as the sequence path -- byte for byte the + // same stream now that both drive one mini-GOP driver + // (lane-av1pyrdef). let facade = std::env::var_os("EC_AV1_GATE_FACADE").is_some(); - let (ours, ours_wall) = match (facade, pyramid_env) { - (false, None) => our_ladder(name, &source, width, height, fctx), - (_, pyramid) => { + let (ours, ours_wall) = match facade { + false => our_ladder(name, &source, width, height, fctx), + true => { + let pyramid = crate::encoder::Pyramid::from_env(); let (ladder, wall, counts, bytes, effective) = our_ladder_facade(name, &source, width, height, pyramid); eprintln!( @@ -13293,21 +13334,10 @@ mod tests { let _ = crate::tile::take_palette_uv_hits(); let _ = crate::tile::take_intrabc_hits(); let _ = take_intrabc_search(); - let (ours, ours_wall) = match pyramid_from_env() { - None => our_ladder(name, &source, cw, ch, fctx), - Some(pyramid) => { - let (ladder, wall, counts, bytes, effective) = - our_ladder_facade(name, &source, cw, ch, Some(pyramid)); - eprintln!( - "{name}: pyramid requested {pyramid:?} effective {effective:?} \ - -- frames key {} arf {} leaf {} \ - show_existing {}; bytes key {} arf {} leaf {} show_existing {}", - counts[0], counts[1], counts[2], counts[3], - bytes[0], bytes[1], bytes[2], bytes[3], - ); - (ladder, wall) - } - }; + // The sequence path itself codes the pyramid now + // (lane-av1pyrdef), and prints what it requested and what the + // content gate left effective. + let (ours, ours_wall) = our_ladder(name, &source, cw, ch, fctx); // gate-blind-to-feature: what the screen tools actually did at // native resolution, over this clip's four encodes. let screen_on = SCREEN_FRAMES[1].load(std::sync::atomic::Ordering::Relaxed); diff --git a/crates/ec-av1/src/encoder.rs b/crates/ec-av1/src/encoder.rs index 2b411293..67ed6726 100644 --- a/crates/ec-av1/src/encoder.rs +++ b/crates/ec-av1/src/encoder.rs @@ -356,6 +356,33 @@ pub struct Pyramid { pub leaf_q_offset: i16, } +impl Pyramid { + /// The pyramid a run asks for through the environment: + /// `EC_AV1_PYRAMID=[::]`, with + /// `0` (or anything that is not a mini-GOP of at least 2, e.g. `flat`) + /// meaning the flat one-picture-one-frame path. UNSET is + /// [`Pyramid::default`]: the pyramid is what + /// [`crate::encode::encode_sequence`], the BD gate and `ec-bench` code + /// under unless a run turns it off for an A/B. + #[must_use] + pub fn from_env() -> Option { + let d = Self::default(); + let Some(spec) = std::env::var("EC_AV1_PYRAMID").ok() else { + return Some(d); + }; + let mut f = spec.split(':'); + let mini_gop: usize = f.next().and_then(|v| v.parse().ok()).unwrap_or(0); + if mini_gop < 2 { + return None; + } + Some(Self { + mini_gop, + arf_q_offset: f.next().and_then(|v| v.parse().ok()).unwrap_or(d.arf_q_offset), + leaf_q_offset: f.next().and_then(|v| v.parse().ok()).unwrap_or(d.leaf_q_offset), + }) + } +} + impl Default for Pyramid { /// The best point of the offset sweep run through the BD gate's own /// `EC_AV1_PYRAMID=[::]` knob @@ -580,6 +607,11 @@ pub struct Av1Encoder { anchor: usize, /// Coding-order position of the next packet — a packet's `dts`. next_dts: u64, + /// Set by [`Av1Encoder::encode_sequence_pyramid`]: every coded frame's + /// own cropped [`Encoded`] (its display position and its reconstruction), + /// which is what [`crate::encode::EncodedSequence`] carries and a packet + /// does not. `None` for every other caller, which pays nothing for it. + collected: Option>, } /// One decoded-picture-buffer slot: what a `refresh_frame_flags` bit stores @@ -645,6 +677,7 @@ impl Av1Encoder { held: std::collections::VecDeque::new(), anchor: 0, next_dts: 0, + collected: None, }) } @@ -931,6 +964,65 @@ impl Av1Encoder { Ok(self.packet(cropped.stream, is_key, order, level)) } + /// THE SHARED MINI-GOP DRIVER: codes a whole sequence — one key frame + /// then all inter, which is [`crate::encode::encode_sequence`]'s only + /// shape — through this very facade, under `pyramid`, and hands back what + /// that path returns. The two are byte-identical BY CONSTRUCTION rather + /// than by a mirrored second implementation: there is one reordering, + /// one DPB/slot policy and one set of per-level quantizer offsets, here + /// (`encoder::tests::the_facade_codes_the_same_bytes_as_encode_sequence` + /// still pins it, now over a pyramid sequence too). + /// + /// The content gate lives in [`Av1Encoder::encode_frames`] and applies + /// unchanged, so a screen-content clip handed in here codes flat. + /// + /// `EncodedSequence::frames` comes back in DISPLAY order, one entry per + /// source picture — the order the flat path's coding order happens to be, + /// and the order every reader of it (the BD gate's sample-exactness + /// assertions against a decoder's output) needs. `stream` stays in coding + /// order, which is the order a decoder reads. + /// + /// # Errors + /// As [`Av1Encoder::encode_frames`]. + pub(crate) fn encode_sequence_pyramid( + pictures: &[Picture], + base_q_idx: u8, + pyramid: Pyramid, + tiles: (u32, u32), + ) -> Result { + let first = pictures.first().ok_or_else(|| { + Error::unsupported("AV1 encode", "a sequence needs at least one picture") + })?; + let config = EncoderConfig { + width: first.width, + height: first.height, + base_q_idx, + // One key frame, at picture 0, and inter for the rest. + gop: pictures.len().max(1), + // `encode_sequence` writes an unspecified colour config. + colour: Colour::Unspecified, + tile_cols_log2: tiles.0, + tile_rows_log2: tiles.1, + }; + let mut encoder = Self::with_pyramid(config, pyramid)?; + encoder.collected = Some(Vec::with_capacity(pictures.len())); + let mut stream = Vec::new(); + for picture in pictures { + for packet in encoder.encode_frames(picture)? { + stream.extend_from_slice(&packet.data); + } + } + for packet in encoder.flush()? { + stream.extend_from_slice(&packet.data); + } + let mut collected = encoder.collected.take().expect("collecting"); + collected.sort_by_key(|(order, _)| *order); + Ok(crate::encode::EncodedSequence { + stream, + frames: collected.into_iter().map(|(_, encoded)| encoded).collect(), + }) + } + /// Stamps a packet with its display and coding positions and advances the /// coding-order clock. fn packet(&mut self, data: Vec, key: bool, order: u64, level: Level) -> Packet { @@ -983,6 +1075,9 @@ impl Av1Encoder { if let Some(rate_loop) = self.rate_loop.as_mut() { rate_loop.update(Level::Key, cropped.stream.len()); } + if let Some(collected) = self.collected.as_mut() { + collected.push((order, cropped.clone())); + } Ok(self.packet(cropped.stream, true, order, Level::Key)) } @@ -1091,6 +1186,9 @@ impl Av1Encoder { if let Some(rate_loop) = self.rate_loop.as_mut() { rate_loop.update(level, cropped.stream.len()); } + if let Some(collected) = self.collected.as_mut() { + collected.push((order, cropped.clone())); + } Ok(self.packet(cropped.stream, false, order, level)) } @@ -1263,54 +1361,106 @@ mod tests { assert!(enc.flush().unwrap().is_empty(), "nothing is held twice"); } - /// THE ENTRY-SURFACE GATE (lane-av1facade): the streaming facade — what - /// the editor's export drives — codes byte for byte what - /// [`crate::encode::encode_sequence`] codes, which is the path the BD - /// gate measures. It did not before: the facade passed no lookahead, so - /// every inter frame missed the per-superblock temporal lambda map - /// (lane-av1tpl) the gate's numbers were measured with. + /// A screen-like card: hard-edged 4-pixel bands of two flat luma values + /// with a moving block over the lower half — few colours per 16x16 block + /// at high variance, which is exactly what + /// [`crate::encode::picture_is_screen`] separates. Used unforced, so the + /// gate below runs the real detector rather than an override. + fn screen_card(width: usize, height: usize, shift: usize) -> Picture { + let mut picture = Picture::grey(width, height); + for y in 0..height { + for x in 0..width { + let band = if (x / 4).is_multiple_of(2) { 40 } else { 200 }; + let over = y >= height / 2 && (x + shift) % width < width / 3; + picture.y[y * width + x] = if over { 128 } else { band }; + } + } + picture + } + + /// THE ENTRY-SURFACE GATE (lane-av1facade, extended to the pyramid on + /// lane-av1pyrdef): the streaming facade — what the editor's export + /// drives — codes byte for byte what [`crate::encode::encode_sequence`] + /// codes, which is the path the BD gate measures. Both now drive ONE + /// mini-GOP driver ([`Av1Encoder::encode_sequence_pyramid`]), so the + /// identity is by construction; this pins it anyway, over both content + /// classes the content gate splits: + /// + /// * film-like (the gate's own clip when the fixture is there, a + /// multi-tone moving card otherwise): the pyramid is EFFECTIVE, the + /// stream is reordered (a hidden `ALTREF` per mini-GOP), and the two + /// paths' whole streams are identical; + /// * screen-like: the content gate drops BOTH paths back to flat, one + /// packet per picture, identical frame by frame as well as whole. /// - /// Runs on the gate's own clip at the gate's own size when the fixture is - /// there, and on a synthetic card otherwise — never skipped, since a - /// skipped identity gate is the defect it is meant to catch. + /// Never skipped, since a skipped identity gate is the defect it is meant + /// to catch. #[test] fn the_facade_codes_the_same_bytes_as_encode_sequence() { let frames = 12usize; - let pictures = h264_clip_frames(640, 384, frames).unwrap_or_else(|| { + let film = h264_clip_frames(640, 384, frames).unwrap_or_else(|| { eprintln!("no h264 clip: the facade identity gate runs on a synthetic card"); (0..frames).map(|t| test_card(64, 64, t)).collect() }); - let (width, height) = (pictures[0].width, pictures[0].height); - for q in [150u8, 60] { - let config = EncoderConfig { - width, - height, - base_q_idx: q, - // One key frame then all inter, which is `encode_sequence`'s - // only shape, and the gate's recipe. - gop: frames, - // `encode_sequence` writes an unspecified colour config. - colour: Colour::Unspecified, - tile_cols_log2: 0, - tile_rows_log2: 0, - }; - let mut enc = Av1Encoder::new(config).unwrap(); - let packets = encode_all(&mut enc, &pictures); - let sequence = crate::encode::encode_sequence(&pictures, q, DEADZONE).unwrap(); - assert_eq!(packets.len(), frames, "q={q}: one packet per picture"); - for (i, (packet, coded)) in packets.iter().zip(&sequence.frames).enumerate() { - let cropped = crate::encode::crop_encoded(coded, width, height); + let screen: Vec = (0..frames).map(|t| screen_card(64, 64, t)).collect(); + let pyramid = Pyramid::from_env().expect("the pyramid is this build's default"); + for (content, pictures, is_screen) in + [("film", &film, false), ("screen", &screen, true)] + { + let (width, height) = (pictures[0].width, pictures[0].height); + for q in [150u8, 60] { + let config = EncoderConfig { + width, + height, + base_q_idx: q, + // One key frame then all inter, which is + // `encode_sequence`'s only shape, and the gate's recipe. + gop: frames, + // `encode_sequence` writes an unspecified colour config. + colour: Colour::Unspecified, + tile_cols_log2: 0, + tile_rows_log2: 0, + }; + let mut enc = Av1Encoder::with_pyramid(config, pyramid).unwrap(); + let mut packets = Vec::new(); + for picture in pictures { + packets.extend(enc.encode_frames(picture).unwrap()); + } + packets.extend(enc.flush().unwrap()); + assert_eq!( + enc.pyramid().is_none(), + is_screen, + "{content} q={q}: the content gate read this clip the other way round" + ); + let sequence = crate::encode::encode_sequence(pictures, q, DEADZONE).unwrap(); + assert_eq!( + (packets.iter().map(|p| p.data.len()).sum::(), concat(&packets)), + (sequence.stream.len(), sequence.stream.clone()), + "{content} q={q}: the facade's stream is not the sequence path's" + ); assert_eq!( - (packet.data.len(), packet.data.clone()), - (cropped.stream.len(), cropped.stream.clone()), - "q={q} frame {i}: the facade's bytes are not the sequence path's" + sequence.frames.len(), + frames, + "{content} q={q}: one entry per picture, in display order" ); + if is_screen { + assert_eq!(packets.len(), frames, "{content} q={q}: one packet per picture"); + for (i, (packet, coded)) in packets.iter().zip(&sequence.frames).enumerate() { + let cropped = crate::encode::crop_encoded(coded, width, height); + assert_eq!( + (packet.data.len(), packet.data.clone()), + (cropped.stream.len(), cropped.stream.clone()), + "{content} q={q} frame {i}: the facade's bytes are not the \ + sequence path's" + ); + } + } else { + assert!( + packets.iter().any(|p| p.level == Level::Arf), + "{content} q={q}: a non-screen stream coded no hidden frame" + ); + } } - assert_eq!( - concat(&packets), - sequence.stream, - "q={q}: whole stream" - ); } } diff --git a/tools/ec-bench/src/main.rs b/tools/ec-bench/src/main.rs index ca2dabce..e13417e0 100644 --- a/tools/ec-bench/src/main.rs +++ b/tools/ec-bench/src/main.rs @@ -368,19 +368,13 @@ fn bench_av1_encode(rows: &mut Vec) { tile_cols_log2, tile_rows_log2, }; - // `EC_AV1_PYRAMID=[::]` benches the - // encoder's coding pyramid (hidden ALTREF + show_existing_frame) instead - // of the flat one-picture-one-packet stream, the same knob shape as - // `EC_H265_RDOQ_ESTIMATE`. Unset keeps the flat default. - let pyramid = std::env::var("EC_AV1_PYRAMID").ok().and_then(|spec| { - let mut f = spec.split(':'); - let d = Pyramid::default(); - Some(Pyramid { - mini_gop: f.next()?.parse().ok()?, - arf_q_offset: f.next().and_then(|v| v.parse().ok()).unwrap_or(d.arf_q_offset), - leaf_q_offset: f.next().and_then(|v| v.parse().ok()).unwrap_or(d.leaf_q_offset), - }) - }); + // The encoder's coding pyramid (hidden ALTREF + show_existing_frame) is + // the default, as it is in `encode_sequence`; `EC_AV1_PYRAMID=0` benches + // the flat one-picture-one-packet stream instead, and + // `EC_AV1_PYRAMID=[::]` another + // shape of it. The `hidden` column below is how many frames of the row + // were coded ahead of their display position. + let pyramid = Pyramid::from_env(); let mut enc = match pyramid { None => Av1Encoder::new(cfg).expect("av1 encoder"), Some(p) => Av1Encoder::with_pyramid(cfg, p).expect("av1 encoder"),