diff --git a/crates/ec-av1/src/encode.rs b/crates/ec-av1/src/encode.rs index bdb0b956..a793f3e9 100644 --- a/crates/ec-av1/src/encode.rs +++ b/crates/ec-av1/src/encode.rs @@ -1080,6 +1080,21 @@ fn screen_content(y: &[u8], width: usize, true_width: usize, true_height: usize) on } +/// Whether this SOURCE picture reads as screen content, for a caller that has +/// to decide something BEFORE the frame is coded: [`crate::encoder::Av1Encoder`] +/// gates its coding pyramid on this (a desktop capture keeps the flat +/// one-in-one-out structure the BD gate measured it on, camera material takes +/// the mini-GOP). The key frame runs the same detector again when it builds +/// its header -- that is the run the [`SCREEN_FRAMES`] histogram is meant to +/// count, so this probe undoes its own tick and leaves the gate prints +/// reading one detection per coded frame. +pub(crate) fn picture_is_screen(picture: &Picture) -> bool { + let y: Vec = picture.y.iter().map(|&v| v as u8).collect(); + let on = screen_content(&y, picture.width, picture.width, picture.height); + SCREEN_FRAMES[usize::from(on)].fetch_sub(1, std::sync::atomic::Ordering::Relaxed); + on +} + /// The sequence and frame headers a picture of this size is coded under: one /// tile, one transform size per block, no in-loop filter parameters yet /// (`crate::encode::pick_and_apply_filters` fills the deblocking levels and @@ -12345,15 +12360,18 @@ mod tests { /// own quantizer offset; without one it is the flat ladder, which /// `encoder::tests::the_facade_codes_the_same_bytes_as_encode_sequence` /// pins byte-identical to [`our_ladder`]'s, so this arm must print the - /// same BD numbers. Returns the ladder, the wall, and — per pyramid level - /// over the whole ladder — how many frames and how many bytes it spent. + /// same BD numbers. Returns the ladder, the wall, per pyramid level over + /// the whole ladder how many frames and how many bytes it spent, and the + /// pyramid the streams were EFFECTIVELY coded under — the content gate in + /// `Av1Encoder::encode_frames` drops a screen-content clip back to the + /// flat path, so a requested pyramid can come back `None` here. fn our_ladder_facade( name: &str, source: &[Picture], width: usize, height: usize, pyramid: Option, - ) -> (Vec<(f64, f64)>, f64, [usize; 4], [usize; 4]) { + ) -> (Vec<(f64, f64)>, f64, [usize; 4], [usize; 4], Option) { use crate::encoder::{Av1Encoder, Colour, EncoderConfig, Level}; let slot = |l: Level| match l { Level::Key => 0, @@ -12363,6 +12381,7 @@ mod tests { }; let mut ladder = Vec::new(); let mut wall = 0.0; + let mut effective = None; let (mut counts, mut bytes) = ([0usize; 4], [0usize; 4]); for &q in &[150u8, 120, 90, 60] { let config = EncoderConfig { @@ -12385,6 +12404,7 @@ mod tests { } packets.extend(enc.flush().unwrap()); wall += start.elapsed().as_secs_f64(); + effective = enc.pyramid(); let mut stream = Vec::new(); for p in &packets { counts[slot(p.level)] += 1; @@ -12415,7 +12435,7 @@ mod tests { ladder.push((mean, (stream.len() as f64).log10())); } ladder.sort_by(|a, b| a.0.total_cmp(&b.0)); - (ladder, wall, counts, bytes) + (ladder, wall, counts, bytes, effective) } /// Byte-exactness gate for encoder work that is meant to change only @@ -12759,10 +12779,11 @@ mod tests { let (ours, ours_wall) = match (facade, pyramid_env) { (false, None) => our_ladder(name, &source, width, height, fctx), (_, pyramid) => { - let (ladder, wall, counts, bytes) = + let (ladder, wall, counts, bytes, effective) = our_ladder_facade(name, &source, width, height, pyramid); eprintln!( - "{name}: facade, pyramid {pyramid:?} -- frames key {} arf {} leaf {} \ + "{name}: facade, 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], @@ -13268,10 +13289,11 @@ mod tests { let (ours, ours_wall) = match pyramid_from_env() { None => our_ladder(name, &source, cw, ch, fctx), Some(pyramid) => { - let (ladder, wall, counts, bytes) = + let (ladder, wall, counts, bytes, effective) = our_ladder_facade(name, &source, cw, ch, Some(pyramid)); eprintln!( - "{name}: pyramid {pyramid:?} -- frames key {} arf {} leaf {} \ + "{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], diff --git a/crates/ec-av1/src/encoder.rs b/crates/ec-av1/src/encoder.rs index 52125ab0..f961c1bb 100644 --- a/crates/ec-av1/src/encoder.rs +++ b/crates/ec-av1/src/encoder.rs @@ -669,6 +669,16 @@ impl Av1Encoder { Ok(encoder) } + /// The [`Pyramid`] this stream is actually coding under: what + /// [`Av1Encoder::with_pyramid`] asked for, or `None` once the content gate + /// in [`Av1Encoder::encode_frames`] has dropped a screen-content stream + /// back to the flat path. Meaningful after the first picture has been + /// handed in. + #[must_use] + pub fn pyramid(&self) -> Option { + self.pyramid + } + /// The coded (padded-to-64) frame size every picture in this stream is /// coded at — what a decoder allocates and what `ffprobe` reports. #[must_use] @@ -741,6 +751,24 @@ impl Av1Encoder { ), )); } + // THE CONTENT GATE (lane-av1pyrgate): the pyramid is for camera + // material. A desktop capture is the one content class every pyramid + // sweep measured WORSE under it, and it is exactly the class the + // screen detector separates (`encode::screen_content`: 0/48 frames on + // both real films, 48/48 on the OBS capture), so a stream whose first + // picture reads as screen content drops back to the flat path and + // codes byte for byte what it coded before the pyramid existed. + // + // Decided ONCE, on the first picture, not per mini-GOP: the flat path + // keeps its references in `reference`/`golden`/`prev2` and the pyramid + // path in `dpb`, so a switch after the first frame would read slots + // the other path never filled. Per-GOP re-decision needs the two + // reference sets kept in step first; the gate's own recipe codes one + // GOP per stream, where the two are the same decision. + if self.pyramid.is_some() && self.next_index == 0 && crate::encode::picture_is_screen(picture) + { + self.pyramid = None; + } let Some(pyramid) = self.pyramid else { // The delay queue: the pictures behind this one are the // lookahead window the one at its head is coded with, which is @@ -1250,6 +1278,48 @@ mod tests { } } + /// THE CONTENT GATE (lane-av1pyrgate): the coding pyramid is asked for by + /// the caller but applied only to camera material. Over screen content + /// the encoder must drop back to the flat path and code byte for byte + /// what a flat encoder codes — that is what keeps the BD gate's screen + /// row identical to the flat baseline — and over non-screen content the + /// same request must still reorder (class `gate-blind-to-feature`: a gate + /// that only checked the screen half would pass with the pyramid deleted). + #[test] + fn the_content_gate_keeps_screen_streams_flat() { + let frames = 8usize; + let pictures: Vec = (0..frames).map(|t| test_card(64, 64, t)).collect(); + let config = EncoderConfig { + width: 64, + height: 64, + base_q_idx: 120, + gop: frames, + colour: Colour::Unspecified, + tile_cols_log2: 0, + tile_rows_log2: 0, + }; + crate::encode::force_screen(Some(true)); + let mut flat = Av1Encoder::new(config).unwrap(); + let flat_packets = encode_all(&mut flat, &pictures); + let mut gated = Av1Encoder::with_pyramid(config, Pyramid::default()).unwrap(); + let gated_packets = encode_all(&mut gated, &pictures); + assert_eq!(gated.pyramid(), None, "the gate left a screen stream on the pyramid"); + assert_eq!( + concat(&gated_packets), + concat(&flat_packets), + "a screen stream's bytes are not the flat path's" + ); + crate::encode::force_screen(Some(false)); + let mut kept = Av1Encoder::with_pyramid(config, Pyramid::default()).unwrap(); + let kept_packets = encode_all(&mut kept, &pictures); + assert_eq!(kept.pyramid(), Some(Pyramid::default()), "the gate ate a film stream"); + assert!( + kept_packets.iter().any(|p| p.level == Level::Arf), + "a non-screen stream coded no hidden frame" + ); + crate::encode::force_screen(None); + } + /// A key frame every `gop` pictures, inter otherwise — checked against /// what the facade itself reports, and (below) against what `ffprobe` /// reads back out of the coded bytes. @@ -1752,6 +1822,11 @@ mod tests { mini_gop: 4, ..Pyramid::default() }; + // The content gate ([`Av1Encoder::encode_frames`]) would drop a + // screen-content stream to the flat path, and a synthetic test card + // is exactly the few-colour picture the detector fires on: this gate + // is about the reordering, so it asks for camera content explicitly. + crate::encode::force_screen(Some(false)); let mut enc = Av1Encoder::with_pyramid(config, pyramid).unwrap(); let sources: Vec = (0..9).map(|t| test_card(width, height, t * 3)).collect(); let _ = crate::encode::take_ref_frame_hits();