forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'lane-av1pyr' (a5447b64): two-level frame pyramid (opt-in), target-bitrate rate mode, encode_frames/flush API

Browse files at this commit

7c2597ddd535ac48d91a825d992b2c681795903dAhmet Kaan GümüşParent: e6e02af51ea72d
Pyramid ships OFF: 4:-16:8 measures +131.9/+178.7/+78.4 vs libaom against
flat +121.1/+146.1/+79.3 (hidden frame predicted mini_gop pictures ahead
under the same search range; leaves reach it only via extra-ref modes).
Defect fixed on the way: decode_inter_frame_tile_lr hard-coded
NO_SIGN_BIAS, desyncing the encoder's own filter-search re-decode for any
backward reference (surfaced as a missing-picture refusal).
crates/ec-av1/src/decode.rsmodified+14 -2
@@ -32874,7 +32874,7 @@ pub(crate) fn decode_inter_frame_tile(
32874 data, mi_cols, mi_rows, base_q_idx, frame_width, frame_height, refpix, cdef,32874 data, mi_cols, mi_rows, base_q_idx, frame_width, frame_height, refpix, cdef,
32875 loop_filter, allow_high_precision_mv, force_integer_mv, interp_fixed,32875 loop_filter, allow_high_precision_mv, force_integer_mv, interp_fixed,
32876 enable_dual_filter, reference_select, tx_select,32876 enable_dual_filter, reference_select, tx_select,
32877- &LoopRestorationParams::default(), initial_cdfs, fctx,32877+ &LoopRestorationParams::default(), initial_cdfs, NO_SIGN_BIAS, fctx,
32878 )32878 )
32879 }32879 }
32880 32880
@@ -32899,6 +32899,16 @@ pub(crate) fn decode_inter_frame_tile_lr(
32899 tx_select: bool,32899 tx_select: bool,
32900 lr: &LoopRestorationParams,32900 lr: &LoopRestorationParams,
32901 initial_cdfs: Option<Cdfs>,32901 initial_cdfs: Option<Cdfs>,
32902+ // spec 5.9.2's `ref_frame_sign_bias`, derived by a real decoder from the
32903+ // order hints its DPB slots hold. A raw tile decode cannot derive it (it
32904+ // is handed planes, not slots), and hard-coding `NO_SIGN_BIAS` here
32905+ // desyncs the encoder's own filter-search re-decode of any frame with a
32906+ // BACKWARD reference -- a pyramid leaf reading its group's hidden
32907+ // `ALTREF_FRAME` -- since the writer's MV-stack scans flip borrowed
32908+ // candidates across the bias boundary and this one's did not. Same class
32909+ // as `tx_select`/`initial_cdfs` above: a header-derived value a raw tile
32910+ // decode has to be told.
32911+ sign_bias: crate::mvstack::SignBiasTable,
32902 fctx: &crate::decode::FrameCtx,32912 fctx: &crate::decode::FrameCtx,
32903 ) -> Result<Picture> {32913 ) -> Result<Picture> {
32904 let single_tile = TileInfo {32914 let single_tile = TileInfo {
@@ -32922,7 +32932,7 @@ pub(crate) fn decode_inter_frame_tile_lr(
32922 initial_cdfs,32932 initial_cdfs,
32923 allow_high_precision_mv,32933 allow_high_precision_mv,
32924 force_integer_mv,32934 force_integer_mv,
32925- NO_SIGN_BIAS,32935+ sign_bias,
32926 [ec_av1_syntax::WarpParams::default(); 7],32936 [ec_av1_syntax::WarpParams::default(); 7],
32927 interp_fixed,32937 interp_fixed,
32928 enable_dual_filter,32938 enable_dual_filter,
@@ -37478,6 +37488,7 @@ mod tests {
37478 frame.tx_select,37488 frame.tx_select,
37479 &frame.loop_restoration,37489 &frame.loop_restoration,
37480 Some(frame.start_cdfs.0.clone()),37490 Some(frame.start_cdfs.0.clone()),
37491+ NO_SIGN_BIAS,
37481 fctx,37492 fctx,
37482 )37493 )
37483 .unwrap();37494 .unwrap();
@@ -37796,6 +37807,7 @@ mod tests {
37796 frame.tx_select,37807 frame.tx_select,
37797 &frame.loop_restoration,37808 &frame.loop_restoration,
37798 Some(frame.start_cdfs.0.clone()),37809 Some(frame.start_cdfs.0.clone()),
37810+ NO_SIGN_BIAS,
37799 fctx,37811 fctx,
37800 )37812 )
37801 .unwrap();37813 .unwrap();
crates/ec-av1/src/encode.rsmodified+177 -14
@@ -1933,6 +1933,20 @@ pub(crate) fn take_tx_depth_hits() -> [usize; 3] {
1933 static INTER_TX_SPLIT_HITS: [std::sync::atomic::AtomicUsize; 2] =1933 static INTER_TX_SPLIT_HITS: [std::sync::atomic::AtomicUsize; 2] =
1934 [const { std::sync::atomic::AtomicUsize::new(0) }; 2];1934 [const { std::sync::atomic::AtomicUsize::new(0) }; 2];
1935 1935
1936+/// How many 32x32-and-below inter blocks each reference frame won, indexed by
1937+/// `ref_frame` (`crate::mvstack::LAST_FRAME` = 1 .. `ALTREF_FRAME` = 7), the
1938+/// fire count a gate prints to see an extra reference reach a block at all
1939+/// ([[gate-blind-to-feature]]: a pyramid whose backward `ALTREF` is never
1940+/// chosen is a pyramid that costs bytes and buys nothing).
1941+static REF_FRAME_HITS: [std::sync::atomic::AtomicUsize; 8] =
1942+ [const { std::sync::atomic::AtomicUsize::new(0) }; 8];
1943+
1944+/// Reads [`REF_FRAME_HITS`] and zeroes it.
1945+#[cfg(test)]
1946+pub(crate) fn take_ref_frame_hits() -> [usize; 8] {
1947+ std::array::from_fn(|r| REF_FRAME_HITS[r].swap(0, std::sync::atomic::Ordering::Relaxed))
1948+}
1949+
1936 /// Reads [`INTER_TX_SPLIT_HITS`] and zeroes it.1950 /// Reads [`INTER_TX_SPLIT_HITS`] and zeroes it.
1937 #[cfg(test)]1951 #[cfg(test)]
1938 pub(crate) fn take_inter_tx_split_hits() -> [usize; 2] {1952 pub(crate) fn take_inter_tx_split_hits() -> [usize; 2] {
@@ -4115,6 +4129,33 @@ fn search_inter_block(
4115 )4129 )
4116 }4130 }
4117 4131
4132+/// Where one inter frame sits in a coding-order pyramid: which DPB slots its
4133+/// references name, which slot it refreshes, whether it is shown when it is
4134+/// coded, and the `ref_frame_sign_bias` that follows from all of it. `None`
4135+/// keeps `encode_inter_frame`'s pre-pyramid flat behaviour verbatim (slot
4136+/// 0/2 alternation, every frame shown, every reference in the past).
4137+///
4138+/// The sign bias is carried rather than derived here because only the caller
4139+/// knows what order hint each slot holds; it is armed onto the tile writer
4140+/// ([`crate::tile::arm_sign_bias`]) and set on the encoder's own MV grid, so
4141+/// the writer scans the same stacks the decoder will.
4142+#[derive(Debug, Clone, Copy)]
4143+pub(crate) struct PyramidFrame {
4144+ /// The slot `LAST_FRAME` (and every reference this encoder does not name
4145+ /// apart) reads.
4146+ pub last_slot: u8,
4147+ /// The single slot `refresh_frame_flags` sets.
4148+ pub self_slot: u8,
4149+ /// The slot `ALTREF_FRAME` reads -- a FUTURE frame for a leaf of a
4150+ /// pyramid, which is what makes `sign_bias`'s last entry true.
4151+ pub altref_slot: u8,
4152+ /// `show_frame`: false for a hidden frame, output later by a
4153+ /// `show_existing_frame` header.
4154+ pub show_frame: bool,
4155+ /// This frame's `ref_frame_sign_bias` (spec 5.9.2).
4156+ pub sign_bias: crate::mvstack::SignBiasTable,
4157+}
4158+
4118 /// Encodes one picture as an inter frame predicting from `reference`'s4159 /// Encodes one picture as an inter frame predicting from `reference`'s
4119 /// reconstruction, which the caller decoded (or, for the frame right after4160 /// reconstruction, which the caller decoded (or, for the frame right after
4120 /// the key frame, is the key frame's own reconstruction).4161 /// the key frame, is the key frame's own reconstruction).
@@ -4138,6 +4179,9 @@ pub(crate) fn encode_inter_frame(
4138 // (the encoder alternates 0/2): `ALTREF_FRAME`. `None` for the first two4179 // (the encoder alternates 0/2): `ALTREF_FRAME`. `None` for the first two
4139 // inter frames of a GOP, where the frame two back IS the key frame.4180 // inter frames of a GOP, where the frame two back IS the key frame.
4140 altref: Option<&Picture>, fctx: &crate::decode::FrameCtx,4181 altref: Option<&Picture>, fctx: &crate::decode::FrameCtx,
4182+ // Where this frame sits in the coding-order pyramid; `None` is the flat
4183+ // one-shown-frame-per-picture stream this encoder wrote before.
4184+ pyramid: Option<PyramidFrame>,
4141 ) -> Result<Encoded> {4185 ) -> Result<Encoded> {
4142 picture.check()?;4186 picture.check()?;
4143 if !picture.width.is_multiple_of(SUPERBLOCK) || !picture.height.is_multiple_of(SUPERBLOCK) {4187 if !picture.width.is_multiple_of(SUPERBLOCK) || !picture.height.is_multiple_of(SUPERBLOCK) {
@@ -4164,14 +4208,17 @@ pub(crate) fn encode_inter_frame(
4164 // frame: frame n writes A(n) = 0 for odd n, 2 for even, so A(n) = A(n-2)4208 // frame: frame n writes A(n) = 0 for odd n, 2 for even, so A(n) = A(n-2)
4165 // and the picture this frame names as `ALTREF_FRAME` is the one sitting4209 // and the picture this frame names as `ALTREF_FRAME` is the one sitting
4166 // in the very slot it will overwrite.4210 // in the very slot it will overwrite.
4167- let self_slot = if order_hint % 2 == 1 { 0 } else { 2 };4211+ let self_slot = pyramid.map_or(if order_hint % 2 == 1 { 0 } else { 2 }, |p| p.self_slot);
4168- let last_slot = if order_hint <= 1 {4212+ let last_slot = pyramid.map_or(
4169- LAST_SLOT4213+ if order_hint <= 1 {
4170- } else if (order_hint - 1) % 2 == 1 {4214+ LAST_SLOT
4171- 04215+ } else if (order_hint - 1) % 2 == 1 {
4172- } else {4216+ 0
4173- 24217+ } else {
4174- };4218+ 2
4219+ },
4220+ |p| p.last_slot,
4221+ );
4175 // `render`, not `picture.width`/`picture.height`: `picture` here is4222 // `render`, not `picture.width`/`picture.height`: `picture` here is
4176 // already padded to a whole number of superblocks (`encode_sequence`'s4223 // already padded to a whole number of superblocks (`encode_sequence`'s
4177 // `padded_to(SUPERBLOCK)`), and the header's `mi_cols`/`mi_rows` (and so4224 // `padded_to(SUPERBLOCK)`), and the header's `mi_cols`/`mi_rows` (and so
@@ -4185,10 +4232,20 @@ pub(crate) fn encode_inter_frame(
4185 order_hint,4232 order_hint,
4186 last_slot,4233 last_slot,
4187 self_slot,4234 self_slot,
4188- if altref.is_some() { self_slot } else { GOLDEN_SLOT },4235+ match pyramid {
4236+ Some(p) => p.altref_slot,
4237+ None if altref.is_some() => self_slot,
4238+ None => GOLDEN_SLOT,
4239+ },
4189 )?;4240 )?;
4190 header.render_width = render.0 as u32;4241 header.render_width = render.0 as u32;
4191 header.render_height = render.1 as u32;4242 header.render_height = render.1 as u32;
4243+ let sign_bias = pyramid.map_or(crate::mvstack::NO_SIGN_BIAS, |p| p.sign_bias);
4244+ if let Some(p) = pyramid {
4245+ header.show_frame = p.show_frame;
4246+ header.showable_frame = !p.show_frame;
4247+ header.ref_frame_sign_bias = p.sign_bias;
4248+ }
4192 // `TxMode::Select` here too: an inter block then codes one `txfm_split`4249 // `TxMode::Select` here too: an inter block then codes one `txfm_split`
4193 // flag (kept at zero -- its var-tx tree is not searched yet) and an INTRA4250 // flag (kept at zero -- its var-tx tree is not searched yet) and an INTRA
4194 // block inside this frame codes and searches its own `tx_depth`, the same4251 // block inside this frame codes and searches its own `tx_depth`, the same
@@ -4255,6 +4312,7 @@ pub(crate) fn encode_inter_frame(
4255 // once per frame (lane-av1rd2), not once per block, which is a whole4312 // once per frame (lane-av1rd2), not once per block, which is a whole
4256 // plane's map per 32x32 block and now per leaf too.4313 // plane's map per 32x32 block and now per leaf too.
4257 let mut grid = MiGrid::new(mi_cols, mi_rows);4314 let mut grid = MiGrid::new(mi_cols, mi_rows);
4315+ grid.set_sign_bias(sign_bias);
4258 let mut blocks = vec![Quadrant::Whole(BlockCoeffs::default()); cols * rows];4316 let mut blocks = vec![Quadrant::Whole(BlockCoeffs::default()); cols * rows];
4259 4317
4260 for sb_r in 0..sb_rows {4318 for sb_r in 0..sb_rows {
@@ -4638,6 +4696,12 @@ pub(crate) fn encode_inter_frame(
4638 .filter(|b| b.inter.is_some())4696 .filter(|b| b.inter.is_some())
4639 .count() as f644697 .count() as f64
4640 / modes.len() as f64;4698 / modes.len() as f64;
4699+ for block in blocks.iter().flat_map(Quadrant::blocks) {
4700+ if let Some(info) = block.inter {
4701+ let r = (info.ref_frame as usize).min(7);
4702+ REF_FRAME_HITS[r].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
4703+ }
4704+ }
4641 #[cfg(test)]4705 #[cfg(test)]
4642 record_predicted_bits(crate::tile::predicted_coeff_bits(&blocks, base_q_idx));4706 record_predicted_bits(crate::tile::predicted_coeff_bits(&blocks, base_q_idx));
4643 // This frame's header leaves `disable_frame_end_update_cdf` off, so it4707 // This frame's header leaves `disable_frame_end_update_cdf` off, so it
@@ -4649,6 +4713,7 @@ pub(crate) fn encode_inter_frame(
4649 .cloned()4713 .cloned()
4650 .unwrap_or_else(|| crate::cdf_state::Cdfs::new(crate::tile::q_ctx_of(base_q_idx)));4714 .unwrap_or_else(|| crate::cdf_state::Cdfs::new(crate::tile::q_ctx_of(base_q_idx)));
4651 let start_cdfs = CdfSnapshot(cdfs.clone());4715 let start_cdfs = CdfSnapshot(cdfs.clone());
4716+ crate::tile::arm_sign_bias(sign_bias);
4652 let mut tile = crate::tile::sb_coeff_inter_frame_tile_cdfs(4717 let mut tile = crate::tile::sb_coeff_inter_frame_tile_cdfs(
4653 mi_cols,4718 mi_cols,
4654 mi_rows,4719 mi_rows,
@@ -4738,6 +4803,7 @@ pub(crate) fn encode_inter_frame(
4738 |bits, sb_cols, grid, units| {4803 |bits, sb_cols, grid, units| {
4739 crate::tile::arm_cdef_idx(bits, sb_cols, grid.to_vec());4804 crate::tile::arm_cdef_idx(bits, sb_cols, grid.to_vec());
4740 crate::tile::arm_lr(64, lr_horz, lr_vert, units.to_vec());4805 crate::tile::arm_lr(64, lr_horz, lr_vert, units.to_vec());
4806+ crate::tile::arm_sign_bias(sign_bias);
4741 let mut cdfs = start_cdfs.0.clone();4807 let mut cdfs = start_cdfs.0.clone();
4742 let coded = crate::tile::sb_coeff_inter_frame_tile_cdfs(4808 let coded = crate::tile::sb_coeff_inter_frame_tile_cdfs(
4743 mi_cols,4809 mi_cols,
@@ -4774,6 +4840,7 @@ pub(crate) fn encode_inter_frame(
4774 // so it starts from the same tables the writer did (this4840 // so it starts from the same tables the writer did (this
4775 // frame's `start_cdfs`), not from the defaults.4841 // frame's `start_cdfs`), not from the defaults.
4776 Some(start_cdfs.0.clone()),4842 Some(start_cdfs.0.clone()),
4843+ sign_bias,
4777 fctx,4844 fctx,
4778 )4845 )
4779 },4846 },
@@ -4893,6 +4960,7 @@ pub(crate) fn encode_sequence_with_ctx(
4893 Some(&carried.0),4960 Some(&carried.0),
4894 Some(&golden),4961 Some(&golden),
4895 prev2.as_ref(), fctx,4962 prev2.as_ref(), fctx,
4963+ None,
4896 )?;4964 )?;
4897 stream.extend_from_slice(&inter.stream);4965 stream.extend_from_slice(&inter.stream);
4898 carried = inter.next_cdfs.clone();4966 carried = inter.next_cdfs.clone();
@@ -6948,7 +7016,7 @@ mod tests {
6948 let padded_pic = picture.padded_to(SUPERBLOCK);7016 let padded_pic = picture.padded_to(SUPERBLOCK);
6949 let t = Instant::now();7017 let t = Instant::now();
6950 let inter =7018 let inter =
6951- encode_inter_frame(&padded_pic, &padded_ref, 100, 0.5, 1, (width, height), None, None, None, fctx).unwrap();7019+ encode_inter_frame(&padded_pic, &padded_ref, 100, 0.5, 1, (width, height), None, None, None, fctx, None).unwrap();
6952 let inter_t = t.elapsed();7020 let inter_t = t.elapsed();
6953 eprintln!(7021 eprintln!(
6954 "inter frame vs its own key frame: {inter_t:>9.2?} ({} bytes, inter share \7022 "inter frame vs its own key frame: {inter_t:>9.2?} ({} bytes, inter share \
@@ -7046,7 +7114,7 @@ mod tests {
7046 stage_reset();7114 stage_reset();
7047 let t = Instant::now();7115 let t = Instant::now();
7048 let inter =7116 let inter =
7049- encode_inter_frame(&padded_pic, &padded_ref, 100, 0.5, 1, (width, height), None, None, None, fctx).unwrap();7117+ encode_inter_frame(&padded_pic, &padded_ref, 100, 0.5, 1, (width, height), None, None, None, fctx, None).unwrap();
7050 let total_t = t.elapsed();7118 let total_t = t.elapsed();
7051 let [motion_search, interpolation, transform_quant, entropy] = stage_read();7119 let [motion_search, interpolation, transform_quant, entropy] = stage_read();
7052 let accounted = motion_search + transform_quant + entropy;7120 let accounted = motion_search + transform_quant + entropy;
@@ -7223,7 +7291,7 @@ mod tests {
7223 q,7291 q,
7224 0.5,7292 0.5,
7225 1,7293 1,
7226- (width, height), None, None, None, fctx,7294+ (width, height), None, None, None, fctx, None,
7227 )7295 )
7228 .unwrap();7296 .unwrap();
7229 let baseline_psnr = psnr(&baseline.reconstruction.y, &inter_source.y);7297 let baseline_psnr = psnr(&baseline.reconstruction.y, &inter_source.y);
@@ -7240,7 +7308,7 @@ mod tests {
7240 q,7308 q,
7241 0.5,7309 0.5,
7242 1,7310 1,
7243- (width, height), None, None, None, fctx,7311+ (width, height), None, None, None, fctx, None,
7244 )7312 )
7245 .unwrap();7313 .unwrap();
7246 let pruned_psnr = psnr(&pruned.reconstruction.y, &inter_source.y);7314 let pruned_psnr = psnr(&pruned.reconstruction.y, &inter_source.y);
@@ -7620,6 +7688,88 @@ mod tests {
7620 (ladder, wall)7688 (ladder, wall)
7621 }7689 }
7622 7690
7691+ /// The [`crate::encoder::Pyramid`] this run's ladder is coded under, from
7692+ /// `EC_AV1_PYRAMID=<mini_gop>[:<arf_q_offset>:<leaf_q_offset>]`. Unset
7693+ /// keeps the flat one-key-then-all-inter ladder the baseline was measured
7694+ /// on, so the gate's default recipe is unchanged.
7695+ fn pyramid_from_env() -> Option<crate::encoder::Pyramid> {
7696+ let spec = std::env::var("EC_AV1_PYRAMID").ok()?;
7697+ let mut f = spec.split(':');
7698+ let mini_gop = f.next()?.parse().ok()?;
7699+ let d = crate::encoder::Pyramid::default();
7700+ Some(crate::encoder::Pyramid {
7701+ mini_gop,
7702+ arf_q_offset: f.next().and_then(|v| v.parse().ok()).unwrap_or(d.arf_q_offset),
7703+ leaf_q_offset: f.next().and_then(|v| v.parse().ok()).unwrap_or(d.leaf_q_offset),
7704+ })
7705+ }
7706+
7707+ /// [`our_ladder`] through the streaming facade with a coding pyramid: the
7708+ /// four points are the same `base_q_idx` ladder, but each stream is
7709+ /// reordered (hidden `ALTREF` first, `show_existing_frame` last per
7710+ /// group) and each level is coded at its own quantizer offset. Returns
7711+ /// the ladder, the wall, and — per pyramid level over the whole ladder —
7712+ /// how many frames and how many bytes it spent.
7713+ fn our_ladder_pyramid(
7714+ source: &[Picture],
7715+ width: usize,
7716+ height: usize,
7717+ pyramid: crate::encoder::Pyramid,
7718+ ) -> (Vec<(f64, f64)>, f64, [usize; 4], [usize; 4]) {
7719+ use crate::encoder::{Av1Encoder, Colour, EncoderConfig, Level};
7720+ let slot = |l: Level| match l {
7721+ Level::Key => 0,
7722+ Level::Arf => 1,
7723+ Level::Leaf => 2,
7724+ Level::ShowExisting => 3,
7725+ };
7726+ let mut ladder = Vec::new();
7727+ let mut wall = 0.0;
7728+ let (mut counts, mut bytes) = ([0usize; 4], [0usize; 4]);
7729+ for &q in &[150u8, 120, 90, 60] {
7730+ let config = EncoderConfig {
7731+ width,
7732+ height,
7733+ base_q_idx: q,
7734+ gop: source.len(),
7735+ colour: Colour::Unspecified,
7736+ };
7737+ let start = std::time::Instant::now();
7738+ let mut enc = Av1Encoder::with_pyramid(config, pyramid).unwrap();
7739+ let mut packets = Vec::new();
7740+ for picture in source {
7741+ packets.extend(enc.encode_frames(picture).unwrap());
7742+ }
7743+ packets.extend(enc.flush().unwrap());
7744+ wall += start.elapsed().as_secs_f64();
7745+ let mut stream = Vec::new();
7746+ for p in &packets {
7747+ counts[slot(p.level)] += 1;
7748+ bytes[slot(p.level)] += p.data.len();
7749+ stream.extend_from_slice(&p.data);
7750+ }
7751+ // [[gate-blind-to-hidden-frames]]: a reordered stream is only
7752+ // correct if the DISPLAY-order output still has one frame per
7753+ // source picture, in the right order -- checked against our own
7754+ // decoder as well as ffmpeg's, both below.
7755+ let ours = crate::stream::decode_stream(&stream).expect("our decoder");
7756+ assert_eq!(ours.len(), source.len(), "q={q}: our display-order count");
7757+ let decoded = ffmpeg_decode_sequence(&stream, width, height, source.len());
7758+ for (i, (d, o)) in decoded.iter().zip(&ours).enumerate() {
7759+ assert!(d.y == o.y, "q={q} display frame {i}: ffmpeg differs from our decoder");
7760+ }
7761+ let mean: f64 = decoded
7762+ .iter()
7763+ .zip(source)
7764+ .map(|(d, s)| psnr_all(d, s))
7765+ .sum::<f64>()
7766+ / source.len() as f64;
7767+ ladder.push((mean, (stream.len() as f64).log10()));
7768+ }
7769+ ladder.sort_by(|a, b| a.0.total_cmp(&b.0));
7770+ (ladder, wall, counts, bytes)
7771+ }
7772+
7623 /// Byte-exactness gate for encoder work that is meant to change only7773 /// Byte-exactness gate for encoder work that is meant to change only
7624 /// how long the encoder takes.7774 /// how long the encoder takes.
7625 ///7775 ///
@@ -7816,7 +7966,20 @@ mod tests {
7816 let _ = crate::tile::take_drl_hits();7966 let _ = crate::tile::take_drl_hits();
7817 let _ = crate::tile::take_ref_hits();7967 let _ = crate::tile::take_ref_hits();
7818 let _ = crate::motion::take_census();7968 let _ = crate::motion::take_census();
7819- let (ours, ours_wall) = our_ladder(&source, width, height, fctx);7969+ let (ours, ours_wall) = match pyramid_from_env() {
7970+ None => our_ladder(&source, width, height, fctx),
7971+ Some(pyramid) => {
7972+ let (ladder, wall, counts, bytes) =
7973+ our_ladder_pyramid(&source, width, height, pyramid);
7974+ eprintln!(
7975+ "{name}: pyramid {pyramid:?} -- frames key {} arf {} leaf {} \
7976+ show_existing {}; bytes key {} arf {} leaf {} show_existing {}",
7977+ counts[0], counts[1], counts[2], counts[3],
7978+ bytes[0], bytes[1], bytes[2], bytes[3],
7979+ );
7980+ (ladder, wall)
7981+ }
7982+ };
7820 // How often the inter split actually fired over this clip's four7983 // How often the inter split actually fired over this clip's four
7821 // encodes, against the whole 32x32 that was the only outcome7984 // encodes, against the whole 32x32 that was the only outcome
7822 // before (gate-blind-to-feature).7985 // before (gate-blind-to-feature).
crates/ec-av1/src/encoder.rsmodified+767 -55
@@ -4,7 +4,11 @@
4 //! One picture in, one [`Packet`] out, same contract as the repo's other4 //! One picture in, one [`Packet`] out, same contract as the repo's other
5 //! software encoder shims (`shims/rusty_h264`'s `Encoder::try_encode`,5 //! software encoder shims (`shims/rusty_h264`'s `Encoder::try_encode`,
6 //! "nothing is ever held back"): [`Av1Encoder::encode`] never buffers a6 //! "nothing is ever held back"): [`Av1Encoder::encode`] never buffers a
7-//! picture past its own call, so there is no flush to drain. Internally it7+//! picture past its own call, so there is no flush to drain. That contract
8+//! still holds for every caller that does not opt into a coding pyramid;
9+//! [`Av1Encoder::with_pyramid`] does reorder pictures, and such a stream is
10+//! driven through [`Av1Encoder::encode_frames`] (zero or more packets per
11+//! picture) and [`Av1Encoder::flush`] instead. Internally it
8 //! is [`crate::encode::encode_key_frame_inner`] and12 //! is [`crate::encode::encode_key_frame_inner`] and
9 //! [`crate::encode::encode_inter_frame`] driven by a small state machine —13 //! [`crate::encode::encode_inter_frame`] driven by a small state machine —
10 //! a key frame every `gop` pictures, an inter frame predicting from the14 //! a key frame every `gop` pictures, an inter frame predicting from the
@@ -17,8 +21,8 @@ use ec_av1_syntax::sequence::{ChromaSamplePosition, ColorConfig};
17 use ec_core::{Error, Result};21 use ec_core::{Error, Result};
18 22
19 use crate::encode::{23 use crate::encode::{
20- Encoded, Picture, SUPERBLOCK, crop_encoded, encode_inter_frame, encode_key_frame_inner,24+ Encoded, GOLDEN_SLOT, Picture, SUPERBLOCK, crop_encoded, encode_inter_frame,
21- split_blocks,25+ encode_key_frame_inner, split_blocks,
22 };26 };
23 use crate::intra::KEY_FRAME_MODES;27 use crate::intra::KEY_FRAME_MODES;
24 28
@@ -100,6 +104,46 @@ pub enum RateTarget {
100 /// coded frame near this many bytes, via [`RateLoop`] — see there for104 /// coded frame near this many bytes, via [`RateLoop`] — see there for
101 /// the controller and its windup bound.105 /// the controller and its windup bound.
102 BytesPerFrame(u32),106 BytesPerFrame(u32),
107+ /// A target BITRATE: the same closed loop, with the per-frame byte
108+ /// target derived from `bits_per_second` and `frames_per_second`
109+ /// (`bits_per_second / 8 / frames_per_second`), and — in pyramid mode —
110+ /// split across the levels by their reference weight, since a hidden
111+ /// `ALTREF` and a leaf differ by several times in size and one shared
112+ /// predictor would swing the quantizer every frame.
113+ Bitrate {
114+ /// The stream's target bitrate.
115+ bits_per_second: u32,
116+ /// The frame rate the bitrate is spent at.
117+ frames_per_second: f64,
118+ },
119+}
120+
121+impl RateTarget {
122+ /// Applies this target to `config` and returns the closed loop it needs
123+ /// (`None` for the two open-loop variants). `mini_gop` is `Some` in
124+ /// pyramid mode, which is what makes the loop keep a quantizer per level.
125+ fn into_loop(self, config: &mut EncoderConfig, mini_gop: Option<usize>) -> Option<RateLoop> {
126+ let target_bytes = match self {
127+ RateTarget::QIndex(q) => {
128+ config.base_q_idx = q;
129+ return None;
130+ }
131+ RateTarget::Quality(quality) => {
132+ config.base_q_idx = quality_to_q_idx(quality);
133+ return None;
134+ }
135+ RateTarget::BytesPerFrame(target_bytes) => f64::from(target_bytes),
136+ RateTarget::Bitrate {
137+ bits_per_second,
138+ frames_per_second,
139+ } => f64::from(bits_per_second) / 8.0 / frames_per_second.max(1.0),
140+ };
141+ Some(RateLoop::new(
142+ target_bytes,
143+ f64::from(config.base_q_idx),
144+ mini_gop,
145+ ))
146+ }
103 }147 }
104 148
105 /// `quality`'s mapping to `base_q_idx`, linear across the calibration sweep's149 /// `quality`'s mapping to `base_q_idx`, linear across the calibration sweep's
@@ -112,19 +156,39 @@ fn quality_to_q_idx(quality: u8) -> u8 {
112 (240.0 - quality * 2.0).round() as u8156 (240.0 - quality * 2.0).round() as u8
113 }157 }
114 158
115-/// The closed-loop controller behind [`RateTarget::BytesPerFrame`]: a159+/// How much of a mini-GOP's byte budget the hidden `ALTREF` frame is worth
116-/// proportional step on `base_q_idx`, sized from the calibration sweep's own160+/// relative to one leaf: every leaf of the group predicts off it, so it is
117-/// log-linear slope (bytes roughly halve every ~45 `q_idx` steps there, i.e.161+/// bought at roughly twice a leaf's size (libaom's `gf_group` spends its
118-/// `d(ln bytes)/d(q_idx) ≈ -0.0154`), clamped per frame. Pure proportional —162+/// `ARF` the same way, through a lower quantizer rather than a byte target).
119-/// no accumulated error term — is the windup bound itself163+const ARF_WEIGHT: f64 = 2.0;
120-/// ([[vorbis-rate-loop-windup]]'s class): the only state carried between164+
121-/// frames is `q`, already clamped to `0..=255`, so a quiet lead-in cannot165+/// How much a key frame is worth relative to one leaf, same units.
122-/// build a debt a later transient has to repay; each frame's step is bounded166+const KEY_WEIGHT: f64 = 3.0;
123-/// by `STEP_CLAMP` regardless of history.167+
168+/// The closed-loop controller behind [`RateTarget::BytesPerFrame`] and
169+/// [`RateTarget::Bitrate`]: a proportional step on `base_q_idx`, sized from
170+/// the calibration sweep's own log-linear slope (bytes roughly halve every
171+/// ~45 `q_idx` steps there, i.e. `d(ln bytes)/d(q_idx) ≈ -0.0154`), clamped
172+/// per frame. Pure proportional — no accumulated error term — is the windup
173+/// bound itself ([[vorbis-rate-loop-windup]]'s class): the only state carried
174+/// between frames is `q`, already clamped to `0..=255`, so a quiet lead-in
175+/// cannot build a debt a later transient has to repay; each frame's step is
176+/// bounded by `STEP_CLAMP` regardless of history.
177+///
178+/// In pyramid mode the state is kept PER LEVEL: each frame's size is
179+/// predicted from the previous frame of its own level, against that level's
180+/// own share of the budget, which is the whole "two-pass-free model" this
181+/// encoder carries.
124 #[derive(Debug, Clone, Copy)]182 #[derive(Debug, Clone, Copy)]
125 struct RateLoop {183 struct RateLoop {
126- target_bytes: u32,184+ /// Byte target per level, indexed by [`RateLoop::slot`].
127- q: f64,185+ target: [f64; 3],
186+ /// Quantizer per level, same index.
187+ q: [f64; 3],
188+ /// Whether the three slots are actually distinct (pyramid mode) or all
189+ /// one shared controller (the flat path, unchanged from before levels
190+ /// existed).
191+ per_level: bool,
128 }192 }
129 193
130 impl RateLoop {194 impl RateLoop {
@@ -137,25 +201,54 @@ impl RateLoop {
137 /// convert a bytes ratio into a `q_idx` step.201 /// convert a bytes ratio into a `q_idx` step.
138 const GAIN: f64 = 1.0 / 0.0154;202 const GAIN: f64 = 1.0 / 0.0154;
139 203
140- fn new(target_bytes: u32, start_q: f64) -> Self {204+ fn new(target_bytes: f64, start_q: f64, mini_gop: Option<usize>) -> Self {
205+ let Some(m) = mini_gop.map(|m| m as f64) else {
206+ return Self {
207+ target: [target_bytes; 3],
208+ q: [start_q; 3],
209+ per_level: false,
210+ };
211+ };
212+ // A group of `m` pictures gets `m * target_bytes`, split one
213+ // `ARF_WEIGHT` share to the hidden frame and one each to the `m - 1`
214+ // leaves, so the group's own average is the target exactly.
215+ let share = target_bytes * m / (m - 1.0 + ARF_WEIGHT);
141 Self {216 Self {
142- target_bytes,217+ target: [target_bytes * KEY_WEIGHT, share * ARF_WEIGHT, share],
143- q: start_q,218+ q: [start_q; 3],
219+ per_level: true,
144 }220 }
145 }221 }
146 222
147- fn q_idx(&self) -> u8 {223+ /// Which controller a level uses: one shared slot on the flat path, three
148- self.q.round().clamp(0.0, 255.0) as u8224+ /// separate ones under a pyramid.
225+ fn slot(&self, level: Level) -> usize {
226+ if !self.per_level {
227+ return 0;
228+ }
229+ match level {
230+ Level::Key => 0,
231+ Level::Arf => 1,
232+ // A `show_existing_frame` packet codes no pixels and never
233+ // reaches `update`; it shares the leaf slot so `q_idx` is total.
234+ Level::Leaf | Level::ShowExisting => 2,
235+ }
149 }236 }
150 237
151- /// Steers `q` toward `target_bytes` from this frame's actual coded size.238+ fn q_idx(&self, level: Level) -> u8 {
152- fn update(&mut self, actual_bytes: usize) {239+ self.q[self.slot(level)].round().clamp(0.0, 255.0) as u8
153- if self.target_bytes == 0 || actual_bytes == 0 {240+ }
241+
242+ /// Steers this level's `q` toward its own target from the frame's actual
243+ /// coded size.
244+ fn update(&mut self, level: Level, actual_bytes: usize) {
245+ let slot = self.slot(level);
246+ if self.target[slot] <= 0.0 || actual_bytes == 0 {
154 return;247 return;
155 }248 }
156- let ratio = actual_bytes as f64 / f64::from(self.target_bytes);249+ let ratio = actual_bytes as f64 / self.target[slot];
157 let step = (ratio.ln() * Self::GAIN).clamp(-Self::STEP_CLAMP, Self::STEP_CLAMP);250 let step = (ratio.ln() * Self::GAIN).clamp(-Self::STEP_CLAMP, Self::STEP_CLAMP);
158- self.q = (self.q + step).clamp(0.0, 255.0);251+ self.q[slot] = (self.q[slot] + step).clamp(0.0, 255.0);
159 }252 }
160 }253 }
161 254
@@ -199,13 +292,144 @@ pub struct Packet {
199 pub data: Vec<u8>,292 pub data: Vec<u8>,
200 /// Whether this picture was coded as a key frame.293 /// Whether this picture was coded as a key frame.
201 pub key: bool,294 pub key: bool,
202- /// This picture's position in the stream, in coding (== presentation,295+ /// This picture's position in DISPLAY (presentation) order, starting at
203- /// since this encoder has no B frames) order, starting at 0.296+ /// 0 — a muxer's `pts` in picture units. Without a [`Pyramid`] this is
297+ /// also the coding order and equals `dts`.
204 pub order: u64,298 pub order: u64,
299+ /// This packet's position in CODING (decode) order, starting at 0 — a
300+ /// muxer's `dts` in packet units. With a [`Pyramid`] the hidden frame of
301+ /// each mini-GOP is coded before the leaves it precedes in display order,
302+ /// so `dts` and `order` diverge, and the `show_existing_frame` packet
303+ /// that re-outputs the hidden frame carries the hidden frame's own
304+ /// `order` with its own later `dts`.
305+ pub dts: u64,
306+ /// Which pyramid level this packet is.
307+ pub level: Level,
308+}
309+
310+/// One mini-GOP of a two-level coding pyramid, and the quantizer offsets its
311+/// two levels are coded at. libaom's `gf_group` shape, cut down to the two
312+/// levels this encoder's reference set can carry: the last picture of each
313+/// mini-GOP is coded FIRST, hidden (`show_frame == 0`), as the group's
314+/// `ALTREF_FRAME`, then the pictures before it are coded as shown leaves that
315+/// may predict backward off it, and finally a `show_existing_frame` header
316+/// re-outputs the hidden frame in its own display position.
317+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
318+pub struct Pyramid {
319+ /// Pictures per mini-GOP: the hidden frame is `mini_gop` pictures ahead
320+ /// of the group's anchor, and `mini_gop - 1` leaves sit between them.
321+ /// `1` would leave no leaf at all and is refused.
322+ pub mini_gop: usize,
323+ /// Added to `base_q_idx` for the hidden `ALTREF_FRAME` — negative, since
324+ /// every leaf of the group predicts off it.
325+ pub arf_q_offset: i16,
326+ /// Added to `base_q_idx` for each shown leaf — positive, since nothing
327+ /// predicts off a leaf but the next leaf.
328+ pub leaf_q_offset: i16,
205 }329 }
206 330
331+impl Default for Pyramid {
332+ /// The best point of the offset sweep run through the BD gate's own
333+ /// `EC_AV1_PYRAMID=<mini_gop>[:<arf_q_offset>:<leaf_q_offset>]` knob
334+ /// (`encode::tests::bd_rate_vs_libaom_and_rav1e`, 12 frames of each of
335+ /// the three gate clips, BD-rate vs libaom / vs rav1e, wall = the four
336+ /// encodes of the ladder together).
337+ ///
338+ /// First sweep, before the motion-search lane merged (its extra-reference
339+ /// `NEWMV` is exactly what a pyramid leaf needs to reach its hidden
340+ /// frame), so read it for the OFFSETS, not for the verdict:
341+ ///
342+ /// | mini_gop:arf:leaf | 1080p | 2160p | screen |
343+ /// |---|---|---|---|
344+ /// | flat (no pyramid) | +122.7 / +73.4 | +147.3 / +98.5 | +79.4 / +17.2 |
345+ /// | 4:0:0 | +152.2 / +97.9 | +214.7 / +158.1 | +91.4 / +26.2 |
346+ /// | 4:-16:8 | +139.9 / +87.1 | +201.5 / +143.7 | +78.5 / +19.5 |
347+ /// | 4:-24:12 | +141.3 / +85.0 | +190.0 / +132.9 | +84.5 / +22.8 |
348+ /// | 2:0:0 | +149.3 / +93.1 | +203.0 / +149.4 | +88.3 / +23.6 |
349+ /// | 2:-8:4 | +143.1 / +89.1 | +196.2 / +141.6 | +82.5 / +20.4 |
350+ /// | 2:-16:8 | +137.6 / +84.5 | +187.2 / +130.6 | +84.9 / +23.1 |
351+ ///
352+ /// `0:0` is the worst row at both mini-GOP sizes and `-16/+8` buys 12-16
353+ /// BD points over it, in the direction libaom's `gf_group` spends them
354+ /// (lowest quantizer on the frame everything else predicts from). Those
355+ /// are these defaults.
356+ ///
357+ /// Re-measured after that lane merged (wall ours, 1080p/2160p/screen):
358+ ///
359+ /// | arm | 1080p | 2160p | screen | wall |
360+ /// |---|---|---|---|---|
361+ /// | flat (no pyramid) | +121.1 / +71.8 | +146.1 / +97.5 | +79.3 / +17.2 | 6.3 / 5.8 / 6.2 s |
362+ /// | 4:-16:8 | +131.9 / +81.1 | +178.7 / +123.6 | +78.4 / +19.5 | 6.2 / 5.6 / 5.5 s |
363+ /// | 2:-16:8 | +125.4 / +76.2 | +173.0 / +119.5 | +84.9 / +23.1 | 6.2 / 5.6 / 6.2 s |
364+ ///
365+ /// So the pyramid still does NOT pay, and ships OFF: it wins 0.9 points
366+ /// on screen capture at `4:-16:8` and loses 11 on 1080p and 33 on 2160p.
367+ /// What keeps it from paying, in the order the numbers point at it:
368+ ///
369+ /// * The hidden frame predicts `mini_gop` pictures ahead of its own
370+ /// reference with the SAME forward search a neighbouring frame gets,
371+ /// and it is the largest frame in the group (73.8 kB of the 1080p
372+ /// ladder's 184 kB at `4:-16:8`). On the 2160p clip, whose motion the
373+ /// search only just reaches at distance 1, distance 4 is where it
374+ /// falls off — that clip loses twice what 1080p does, and shrinking
375+ /// the mini-GOP to 2 recovers most of the gap (+178.7 -> +173.0,
376+ /// +131.9 -> +125.4). A distance-scaled search range is the fix, and
377+ /// it lives in the motion-search lane, not here.
378+ /// * The leaves reach the hidden frame through the extra-reference
379+ /// modes only: `ALTREF_FRAME` wins about 13% of blocks
380+ /// (`encode::take_ref_frame_hits`, printed by the round-trip test),
381+ /// up from 4% before the motion lane merged. A compound
382+ /// (`LAST` + `ALTREF`) prediction mode is the other half of what a
383+ /// real B frame buys, and this crate codes no compound blocks at all.
384+ ///
385+ /// Neither is a defect in the pyramid itself: the reordering is exact
386+ /// (`encoder::tests::a_pyramid_stream_decodes_in_display_order_through_both_decoders`
387+ /// checks every shown frame in display order against ffmpeg AND our own
388+ /// decoder, with the hidden frame proven to win blocks), and the
389+ /// quantizer offsets behave. Nothing selects the pyramid but an explicit
390+ /// [`Av1Encoder::with_pyramid`] call (or `EC_AV1_PYRAMID` on the gate and
391+ /// on `ec-bench`); the default one-in-one-out path is byte-identical to
392+ /// before it existed.
393+ fn default() -> Self {
394+ Self {
395+ mini_gop: 4,
396+ arf_q_offset: -16,
397+ leaf_q_offset: 8,
398+ }
399+ }
400+}
401+
402+/// Which level of the pyramid a coded frame sits at, reported on every
403+/// [`Packet`] so a caller (and the BD gate's histogram) can tell them apart
404+/// without parsing the frame headers back out.
405+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
406+pub enum Level {
407+ /// A key frame.
408+ Key,
409+ /// A hidden `ALTREF_FRAME`, coded ahead of its display position.
410+ Arf,
411+ /// A shown leaf.
412+ Leaf,
413+ /// A `show_existing_frame` header re-outputting a hidden frame: no coded
414+ /// pixels at all, four bits of header.
415+ ShowExisting,
416+}
417+
418+/// The DPB slot the group anchors alternate between (see
419+/// [`Av1Encoder::encode_frames`]): the hidden frame of group `g` refreshes
420+/// `ANCHOR_SLOTS[(g + 1) % 2]`, which is the slot the leaves of group `g`
421+/// name as `ALTREF_FRAME` and which group `g + 1` reads as its own anchor.
422+/// Two slots alternate because a group's leaves must still be able to read
423+/// the previous anchor while the new one is already written.
424+const ANCHOR_SLOTS: [u8; 2] = [3, 4];
425+
426+/// The slot the leaf chain refreshes and reads as `LAST_FRAME`.
427+const LEAF_SLOT: u8 = 0;
428+
207 /// The AV1 software encoder: [`EncoderConfig`] in, one [`Packet`] out per429 /// The AV1 software encoder: [`EncoderConfig`] in, one [`Packet`] out per
208-/// [`Av1Encoder::encode`] call.430+/// [`Av1Encoder::encode`] call — or, with a [`Pyramid`] configured, a
431+/// coding-order burst of them per [`Av1Encoder::encode_frames`] call plus a
432+/// [`Av1Encoder::flush`] at the end of the stream.
209 #[derive(Debug)]433 #[derive(Debug)]
210 pub struct Av1Encoder {434 pub struct Av1Encoder {
211 config: EncoderConfig,435 config: EncoderConfig,
@@ -237,6 +461,31 @@ pub struct Av1Encoder {
237 /// The frame two back: `ALTREF_FRAME`, in the slot the next frame is461 /// The frame two back: `ALTREF_FRAME`, in the slot the next frame is
238 /// about to refresh (`encode_inter_frame`'s 0/2 alternation).462 /// about to refresh (`encode_inter_frame`'s 0/2 alternation).
239 prev2: Option<Picture>,463 prev2: Option<Picture>,
464+ /// `Some` puts the encoder in pyramid mode: [`Av1Encoder::encode`] then
465+ /// refuses (a picture no longer maps to one packet) and the state below
466+ /// drives coding order.
467+ pyramid: Option<Pyramid>,
468+ /// The eight DPB slots, modelled exactly as the decoder does (spec 7.20):
469+ /// what picture each holds, the order hint it was coded at, and the CDF
470+ /// tables it stored. Only pyramid mode reads these; the flat path keeps
471+ /// `reference`/`golden`/`prev2` so its bytes are unchanged.
472+ dpb: [Option<DpbSlot>; 8],
473+ /// Pictures held back waiting for their mini-GOP's hidden frame.
474+ pending: Vec<(u64, Picture)>,
475+ /// Which of [`ANCHOR_SLOTS`] the group about to be coded reads as its
476+ /// anchor.
477+ anchor: usize,
478+ /// Coding-order position of the next packet — a packet's `dts`.
479+ next_dts: u64,
480+}
481+
482+/// One decoded-picture-buffer slot: what a `refresh_frame_flags` bit stores
483+/// and what a `ref_frame_idx` entry reads back.
484+#[derive(Debug, Clone)]
485+struct DpbSlot {
486+ picture: Picture,
487+ order_hint: u32,
488+ cdfs: crate::encode::CdfSnapshot,
240 }489 }
241 490
242 /// The encoder stays `Send` now that it owns a `FrameCtx` (whose cells are491 /// The encoder stays `Send` now that it owns a `FrameCtx` (whose cells are
@@ -271,9 +520,37 @@ impl Av1Encoder {
271 next_index: 0,520 next_index: 0,
272 rate_loop: None,521 rate_loop: None,
273 fctx: crate::decode::FrameCtx::new(),522 fctx: crate::decode::FrameCtx::new(),
523+ pyramid: None,
524+ dpb: [const { None }; 8],
525+ pending: Vec::new(),
526+ anchor: 0,
527+ next_dts: 0,
274 })528 })
275 }529 }
276 530
531+ /// [`Av1Encoder::new`] in pyramid mode: pictures are coded out of display
532+ /// order, so a call to [`Av1Encoder::encode_frames`] returns zero, one or
533+ /// several packets and [`Av1Encoder::flush`] drains whatever is still
534+ /// held at the end of the stream. [`Av1Encoder::encode`]'s one-in-one-out
535+ /// contract cannot hold here and it returns an error instead; a caller
536+ /// that wants the old shape simply does not call this constructor.
537+ ///
538+ /// # Errors
539+ /// As [`Av1Encoder::new`], plus a `mini_gop` below 2 (no leaf would be
540+ /// left between the anchor and the hidden frame) or above `config.gop`
541+ /// (the group would straddle a key frame).
542+ pub fn with_pyramid(config: EncoderConfig, pyramid: Pyramid) -> Result<Self> {
543+ if pyramid.mini_gop < 2 {
544+ return Err(Error::unsupported(
545+ "AV1 encode",
546+ "a pyramid mini-GOP is at least 2 pictures",
547+ ));
548+ }
549+ let mut encoder = Self::new(config)?;
550+ encoder.pyramid = Some(pyramid);
551+ Ok(encoder)
552+ }
553+
277 /// [`Av1Encoder::new`], but `rate` picks `base_q_idx` (or steers it,554 /// [`Av1Encoder::new`], but `rate` picks `base_q_idx` (or steers it,
278 /// frame by frame, for [`RateTarget::BytesPerFrame`]) instead of555 /// frame by frame, for [`RateTarget::BytesPerFrame`]) instead of
279 /// `config.base_q_idx` being used as-is.556 /// `config.base_q_idx` being used as-is.
@@ -281,24 +558,31 @@ impl Av1Encoder {
281 /// # Errors558 /// # Errors
282 /// Same as [`Av1Encoder::new`].559 /// Same as [`Av1Encoder::new`].
283 pub fn with_rate_target(mut config: EncoderConfig, rate: RateTarget) -> Result<Self> {560 pub fn with_rate_target(mut config: EncoderConfig, rate: RateTarget) -> Result<Self> {
284- let rate_loop = match rate {561+ let rate_loop = rate.into_loop(&mut config, None);
285- RateTarget::QIndex(q) => {
286- config.base_q_idx = q;
287- None
288- }
289- RateTarget::Quality(quality) => {
290- config.base_q_idx = quality_to_q_idx(quality);
291- None
292- }
293- RateTarget::BytesPerFrame(target_bytes) => {
294- Some(RateLoop::new(target_bytes, f64::from(config.base_q_idx)))
295- }
296- };
297 let mut encoder = Self::new(config)?;562 let mut encoder = Self::new(config)?;
298 encoder.rate_loop = rate_loop;563 encoder.rate_loop = rate_loop;
299 Ok(encoder)564 Ok(encoder)
300 }565 }
301 566
567+ /// [`Av1Encoder::with_pyramid`] and [`Av1Encoder::with_rate_target`] at
568+ /// once: the rate loop then keeps a separate quantizer per pyramid level,
569+ /// predicting each frame's size from the previous frame of its OWN level
570+ /// (a leaf and a hidden `ALTREF` differ by several times in size, so one
571+ /// shared predictor would swing the quantizer every frame).
572+ ///
573+ /// # Errors
574+ /// As both.
575+ pub fn with_pyramid_and_rate_target(
576+ mut config: EncoderConfig,
577+ pyramid: Pyramid,
578+ rate: RateTarget,
579+ ) -> Result<Self> {
580+ let rate_loop = rate.into_loop(&mut config, Some(pyramid.mini_gop));
581+ let mut encoder = Self::with_pyramid(config, pyramid)?;
582+ encoder.rate_loop = rate_loop;
583+ Ok(encoder)
584+ }
585+
302 /// The coded (padded-to-64) frame size every picture in this stream is586 /// The coded (padded-to-64) frame size every picture in this stream is
303 /// coded at — what a decoder allocates and what `ffprobe` reports.587 /// coded at — what a decoder allocates and what `ffprobe` reports.
304 #[must_use]588 #[must_use]
@@ -322,10 +606,32 @@ impl Av1Encoder {
322 ///606 ///
323 /// # Errors607 /// # Errors
324 /// Returns an error when `picture`'s size does not match608 /// Returns an error when `picture`'s size does not match
325- /// [`EncoderConfig::width`]/[`EncoderConfig::height`], or under the same609+ /// [`EncoderConfig::width`]/[`EncoderConfig::height`], when the encoder
326- /// conditions [`crate::encode::encode_key_frame`]/610+ /// was built by [`Av1Encoder::with_pyramid`] (which reorders pictures, so
327- /// [`crate::encode::encode_sequence`] do.611+ /// one call cannot return one packet), or under the same conditions
612+ /// [`crate::encode::encode_key_frame`]/[`crate::encode::encode_sequence`]
613+ /// do.
328 pub fn encode(&mut self, picture: &Picture) -> Result<Packet> {614 pub fn encode(&mut self, picture: &Picture) -> Result<Packet> {
615+ if self.pyramid.is_some() {
616+ return Err(Error::unsupported(
617+ "AV1 encode",
618+ "a pyramid stream reorders pictures -- use encode_frames()/flush()",
619+ ));
620+ }
621+ let mut packets = self.encode_frames(picture)?;
622+ Ok(packets.pop().expect("the flat path emits exactly one packet"))
623+ }
624+
625+ /// Encodes one picture and returns every packet it completed, in coding
626+ /// order. Without a [`Pyramid`] that is always exactly one packet and
627+ /// this is [`Av1Encoder::encode`] with a `Vec` around it; with one it is
628+ /// empty for most pictures and a whole mini-GOP's worth (the hidden
629+ /// frame, its leaves and the `show_existing_frame` that re-outputs it)
630+ /// for the picture that closes a group.
631+ ///
632+ /// # Errors
633+ /// As [`Av1Encoder::encode`], minus the pyramid refusal.
634+ pub fn encode_frames(&mut self, picture: &Picture) -> Result<Vec<Packet>> {
329 if (picture.width, picture.height) != (self.config.width, self.config.height) {635 if (picture.width, picture.height) != (self.config.width, self.config.height) {
330 return Err(Error::unsupported(636 return Err(Error::unsupported(
331 "AV1 encode",637 "AV1 encode",
@@ -335,14 +641,48 @@ impl Av1Encoder {
335 ),641 ),
336 ));642 ));
337 }643 }
644+ let Some(pyramid) = self.pyramid else {
645+ return Ok(vec![self.encode_flat(picture)?]);
646+ };
647+ let order = self.next_index;
648+ self.next_index += 1;
649+ if order.is_multiple_of(self.config.gop as u64) {
650+ // A key frame closes whatever group is open (there is nothing for
651+ // its leaves to point forward at across the boundary) and then
652+ // restarts the pyramid from the key itself.
653+ let mut packets = self.drain_pending()?;
654+ packets.push(self.encode_key(order, picture)?);
655+ return Ok(packets);
656+ }
657+ self.pending.push((order, picture.clone()));
658+ // The group closes on its own size, or early when the next picture
659+ // would be a key frame.
660+ let next_is_key = (order + 1).is_multiple_of(self.config.gop as u64);
661+ if self.pending.len() >= pyramid.mini_gop || next_is_key {
662+ return self.drain_pending();
663+ }
664+ Ok(Vec::new())
665+ }
666+
667+ /// Codes and returns every picture still held back — the tail of a stream
668+ /// whose last mini-GOP never filled up. Empty (and cheap) for a stream
669+ /// with no [`Pyramid`], which never holds a picture at all.
670+ ///
671+ /// # Errors
672+ /// As [`Av1Encoder::encode_frames`].
673+ pub fn flush(&mut self) -> Result<Vec<Packet>> {
674+ self.drain_pending()
675+ }
676+
677+ /// The pre-pyramid path, byte for byte: one picture in, one packet out.
678+ fn encode_flat(&mut self, picture: &Picture) -> Result<Packet> {
338 let render = (self.config.width, self.config.height);679 let render = (self.config.width, self.config.height);
339 let padded = picture.padded_to(SUPERBLOCK);680 let padded = picture.padded_to(SUPERBLOCK);
340- let is_key = self.next_index % self.config.gop as u64 == 0;681+ let is_key = self.next_index.is_multiple_of(self.config.gop as u64);
341 let order = self.next_index;682 let order = self.next_index;
342- let base_q_idx = self683+ let base_q_idx = self.rate_loop.as_ref().map_or(self.config.base_q_idx, |r| {
343- .rate_loop684+ r.q_idx(if is_key { Level::Key } else { Level::Leaf })
344- .as_ref()685+ });
345- .map_or(self.config.base_q_idx, RateLoop::q_idx);
346 686
347 let encoded: Encoded = if is_key {687 let encoded: Encoded = if is_key {
348 encode_key_frame_inner(688 encode_key_frame_inner(
@@ -373,6 +713,7 @@ impl Av1Encoder {
373 self.golden.as_ref(),713 self.golden.as_ref(),
374 self.prev2.as_ref(),714 self.prev2.as_ref(),
375 &self.fctx,715 &self.fctx,
716+ None,
376 )?717 )?
377 };718 };
378 719
@@ -386,14 +727,227 @@ impl Av1Encoder {
386 self.reference = Some(encoded.reconstruction.clone());727 self.reference = Some(encoded.reconstruction.clone());
387 self.next_index += 1;728 self.next_index += 1;
388 let cropped = crop_encoded(&encoded, render.0, render.1);729 let cropped = crop_encoded(&encoded, render.0, render.1);
730+ let level = if is_key { Level::Key } else { Level::Leaf };
389 if let Some(rate_loop) = self.rate_loop.as_mut() {731 if let Some(rate_loop) = self.rate_loop.as_mut() {
390- rate_loop.update(cropped.stream.len());732+ rate_loop.update(level, cropped.stream.len());
391 }733 }
392- Ok(Packet {734+ Ok(self.packet(cropped.stream, is_key, order, level))
393- data: cropped.stream,735+ }
394- key: is_key,736+
737+ /// Stamps a packet with its display and coding positions and advances the
738+ /// coding-order clock.
739+ fn packet(&mut self, data: Vec<u8>, key: bool, order: u64, level: Level) -> Packet {
740+ let dts = self.next_dts;
741+ self.next_dts += 1;
742+ Packet {
743+ data,
744+ key,
395 order,745 order,
396- })746+ dts,
747+ level,
748+ }
749+ }
750+
751+ /// Stores a coded frame into every DPB slot its `refresh_frame_flags`
752+ /// names (spec 7.20).
753+ fn refresh(&mut self, slots: &[u8], encoded: &Encoded, order_hint: u32) {
754+ let slot = DpbSlot {
755+ picture: encoded.reconstruction.clone(),
756+ order_hint,
757+ cdfs: encoded.next_cdfs.clone(),
758+ };
759+ for &s in slots {
760+ self.dpb[s as usize] = Some(slot.clone());
761+ }
762+ }
763+
764+ /// Codes a key frame in pyramid mode: it refreshes all eight slots, so it
765+ /// becomes the anchor, the `GOLDEN_FRAME` and the CDF source for the
766+ /// whole GOP at once.
767+ fn encode_key(&mut self, order: u64, picture: &Picture) -> Result<Packet> {
768+ let render = (self.config.width, self.config.height);
769+ let base_q_idx = self
770+ .rate_loop
771+ .as_ref()
772+ .map_or(self.config.base_q_idx, |r| r.q_idx(Level::Key));
773+ let encoded = encode_key_frame_inner(
774+ &picture.padded_to(SUPERBLOCK),
775+ base_q_idx,
776+ DEADZONE,
777+ &KEY_FRAME_MODES,
778+ split_blocks(),
779+ render,
780+ self.color_config,
781+ &self.fctx,
782+ )?;
783+ self.refresh(&[0, 1, 2, 3, 4, 5, 6, 7], &encoded, 0);
784+ self.anchor = 0;
785+ let cropped = crop_encoded(&encoded, render.0, render.1);
786+ if let Some(rate_loop) = self.rate_loop.as_mut() {
787+ rate_loop.update(Level::Key, cropped.stream.len());
788+ }
789+ Ok(self.packet(cropped.stream, true, order, Level::Key))
790+ }
791+
792+ /// Codes one inter frame at `order` from the DPB, in coding order.
793+ #[allow(clippy::too_many_arguments)]
794+ fn encode_pyramid_inter(
795+ &mut self,
796+ order: u64,
797+ picture: &Picture,
798+ last_slot: u8,
799+ self_slot: u8,
800+ altref_slot: u8,
801+ show_frame: bool,
802+ level: Level,
803+ ) -> Result<Packet> {
804+ let render = (self.config.width, self.config.height);
805+ let order_hint = (order & 0x7f) as u32;
806+ let pyramid = self.pyramid.expect("pyramid mode");
807+ let offset = match level {
808+ Level::Arf => pyramid.arf_q_offset,
809+ _ => pyramid.leaf_q_offset,
810+ };
811+ let base = self
812+ .rate_loop
813+ .as_ref()
814+ .map_or(i16::from(self.config.base_q_idx), |r| {
815+ i16::from(r.q_idx(level))
816+ });
817+ let base_q_idx = (base + offset).clamp(1, 255) as u8;
818+ // spec 5.9.2's `ref_frame_sign_bias`, derived from what the slots
819+ // this frame names actually hold: a reference whose order hint is
820+ // AHEAD of this frame's is backward-biased, and the MV stack scans
821+ // (writer and decoder alike) flip borrowed candidates across the
822+ // boundary. Only `ALTREF_FRAME` can be ahead here — the leaves of a
823+ // mini-GOP name the group's hidden frame there.
824+ let mut sign_bias = crate::mvstack::NO_SIGN_BIAS;
825+ let ahead = |slot: u8, dpb: &[Option<DpbSlot>; 8]| {
826+ dpb[slot as usize]
827+ .as_ref()
828+ .is_some_and(|s| s.order_hint > order_hint)
829+ };
830+ for (i, slot) in [
831+ last_slot, last_slot, last_slot, GOLDEN_SLOT, last_slot, last_slot, altref_slot,
832+ ]
833+ .into_iter()
834+ .enumerate()
835+ {
836+ sign_bias[i] = ahead(slot, &self.dpb);
837+ }
838+ let reference = self.dpb[last_slot as usize]
839+ .as_ref()
840+ .map(|s| s.picture.clone())
841+ .ok_or_else(|| {
842+ Error::unsupported("AV1 encode", "an inter frame needs a previous reconstruction")
843+ })?;
844+ let golden = self.dpb[GOLDEN_SLOT as usize].as_ref().map(|s| s.picture.clone());
845+ let altref = (altref_slot != GOLDEN_SLOT)
846+ .then(|| self.dpb[altref_slot as usize].as_ref().map(|s| s.picture.clone()))
847+ .flatten();
848+ let start_cdfs = self.dpb[last_slot as usize].as_ref().map(|s| s.cdfs.0.clone());
849+ let encoded = || -> Result<Encoded> { encode_inter_frame(
850+ &picture.padded_to(SUPERBLOCK),
851+ &reference,
852+ base_q_idx,
853+ DEADZONE,
854+ order_hint,
855+ render,
856+ start_cdfs.as_ref(),
857+ golden.as_ref(),
858+ altref.as_ref(),
859+ &self.fctx,
860+ Some(crate::encode::PyramidFrame {
861+ last_slot,
862+ self_slot,
863+ altref_slot,
864+ show_frame,
865+ sign_bias,
866+ }),
867+ ) }();
868+ // Name the pyramid position in any failure: an error out of the tile
869+ // writer or the filter search is otherwise indistinguishable between
870+ // the hidden frame and the leaves that read it.
871+ let encoded = encoded.map_err(|e| {
872+ Error::unsupported(
873+ "AV1 encode",
874+ format!(
875+ "{level:?} frame at order {order} (last slot {last_slot}, self {self_slot}, \
876+ altref {altref_slot}, shown {show_frame}, golden {}, altref pic {}): {e}",
877+ golden.is_some(),
878+ altref.is_some(),
879+ ),
880+ )
881+ })?;
882+ self.refresh(&[self_slot], &encoded, order_hint);
883+ let cropped = crop_encoded(&encoded, render.0, render.1);
884+ if let Some(rate_loop) = self.rate_loop.as_mut() {
885+ rate_loop.update(level, cropped.stream.len());
886+ }
887+ Ok(self.packet(cropped.stream, false, order, level))
888+ }
889+
890+ /// Codes the open mini-GOP: its hidden frame first, then its leaves, then
891+ /// the `show_existing_frame` header that puts the hidden frame back in
892+ /// display order.
893+ fn drain_pending(&mut self) -> Result<Vec<Packet>> {
894+ if self.pending.is_empty() {
895+ return Ok(Vec::new());
896+ }
897+ let group: Vec<(u64, Picture)> = std::mem::take(&mut self.pending);
898+ let mut packets = Vec::with_capacity(group.len() + 1);
899+ let anchor_slot = ANCHOR_SLOTS[self.anchor];
900+ let next_anchor_slot = ANCHOR_SLOTS[1 - self.anchor];
901+ let (arf_order, arf_picture) = group.last().cloned().expect("non-empty");
902+ if group.len() == 1 {
903+ // Nothing to predict backward, so no hidden frame: one shown leaf
904+ // that also becomes the next group's anchor.
905+ packets.push(self.encode_pyramid_inter(
906+ arf_order,
907+ &arf_picture,
908+ anchor_slot,
909+ next_anchor_slot,
910+ GOLDEN_SLOT,
911+ true,
912+ Level::Leaf,
913+ )?);
914+ self.anchor = 1 - self.anchor;
915+ return Ok(packets);
916+ }
917+ packets.push(self.encode_pyramid_inter(
918+ arf_order,
919+ &arf_picture,
920+ anchor_slot,
921+ next_anchor_slot,
922+ GOLDEN_SLOT,
923+ false,
924+ Level::Arf,
925+ )?);
926+ for (i, (order, picture)) in group[..group.len() - 1].iter().enumerate() {
927+ let last_slot = if i == 0 { anchor_slot } else { LEAF_SLOT };
928+ packets.push(self.encode_pyramid_inter(
929+ *order,
930+ picture,
931+ last_slot,
932+ LEAF_SLOT,
933+ next_anchor_slot,
934+ true,
935+ Level::Leaf,
936+ )?);
937+ }
938+ let (seq, _) = crate::encode::key_frame_headers(
939+ self.config.width,
940+ self.config.height,
941+ self.config.base_q_idx,
942+ )?;
943+ let mut data = crate::obu::temporal_delimiter();
944+ data.extend_from_slice(&crate::frame::show_existing_frame_obu(
945+ &seq,
946+ next_anchor_slot,
947+ )?);
948+ packets.push(self.packet(data, false, arf_order, Level::ShowExisting));
949+ self.anchor = 1 - self.anchor;
950+ Ok(packets)
397 }951 }
398 }952 }
399 953
@@ -778,6 +1332,65 @@ mod tests {
778 );1332 );
779 }1333 }
780 1334
1335+ /// [`RateTarget::Bitrate`] lands the achieved bitrate within ±10% of the
1336+ /// target over 48 frames of a real clip, flat and under a pyramid alike.
1337+ /// This is the accuracy claim of the target-bitrate mode: no two-pass, no
1338+ /// lookahead, just each frame's size predicted from the previous frame of
1339+ /// its own level and one clamped proportional step.
1340+ #[test]
1341+ fn bitrate_target_lands_within_10_percent_over_48_frames() {
1342+ let (width, height, frames) = (640usize, 384usize, 48usize);
1343+ let Some(pictures) = h264_clip_frames(width, height, frames) else {
1344+ eprintln!("SKIP bitrate_target_lands_within_10_percent_over_48_frames: no ffmpeg/fixture");
1345+ return;
1346+ };
1347+ let fps = 24.0;
1348+ for bits_per_second in [768_000u32, 1_536_000] {
1349+ let config = EncoderConfig {
1350+ width,
1351+ height,
1352+ base_q_idx: 100,
1353+ gop: frames,
1354+ colour: Colour::Bt709Limited,
1355+ };
1356+ let rate = RateTarget::Bitrate {
1357+ bits_per_second,
1358+ frames_per_second: fps,
1359+ };
1360+ for pyramid in [None, Some(Pyramid::default())] {
1361+ let mut enc = match pyramid {
1362+ None => Av1Encoder::with_rate_target(config, rate).unwrap(),
1363+ Some(p) => Av1Encoder::with_pyramid_and_rate_target(config, p, rate).unwrap(),
1364+ };
1365+ let mut coded = 0usize;
1366+ for picture in &pictures {
1367+ for packet in enc.encode_frames(picture).unwrap() {
1368+ coded += packet.data.len();
1369+ }
1370+ }
1371+ for packet in enc.flush().unwrap() {
1372+ coded += packet.data.len();
1373+ }
1374+ let seconds = frames as f64 / fps;
1375+ let achieved = coded as f64 * 8.0 / seconds;
1376+ let error = achieved / f64::from(bits_per_second) - 1.0;
1377+ eprintln!(
1378+ "bitrate {bits_per_second} bps, pyramid {}: {coded} bytes over {seconds:.2}s \
1379+ = {achieved:.0} bps ({:+.1}%)",
1380+ pyramid.is_some(),
1381+ 100.0 * error,
1382+ );
1383+ assert!(
1384+ error.abs() <= 0.10,
1385+ "achieved {achieved:.0} bps is {:+.1}% off the {bits_per_second} bps target \
1386+ (pyramid {})",
1387+ 100.0 * error,
1388+ pyramid.is_some(),
1389+ );
1390+ }
1391+ }
1392+ }
1393+
781 /// The `BytesPerFrame` controller's own windup bound: no frame's coded1394 /// The `BytesPerFrame` controller's own windup bound: no frame's coded
782 /// `base_q_idx` step exceeds [`RateLoop::STEP_CLAMP`], across a real1395 /// `base_q_idx` step exceeds [`RateLoop::STEP_CLAMP`], across a real
783 /// clip's full range of content (so a scene cut can't be the one frame1396 /// clip's full range of content (so a scene cut can't be the one frame
@@ -799,10 +1412,10 @@ mod tests {
799 };1412 };
800 let mut enc =1413 let mut enc =
801 Av1Encoder::with_rate_target(config, RateTarget::BytesPerFrame(4_000)).unwrap();1414 Av1Encoder::with_rate_target(config, RateTarget::BytesPerFrame(4_000)).unwrap();
802- let mut prev_q = enc.rate_loop.as_ref().unwrap().q_idx();1415+ let mut prev_q = enc.rate_loop.as_ref().unwrap().q_idx(Level::Leaf);
803 for picture in &pictures {1416 for picture in &pictures {
804 enc.encode(picture).unwrap();1417 enc.encode(picture).unwrap();
805- let q = enc.rate_loop.as_ref().unwrap().q_idx();1418+ let q = enc.rate_loop.as_ref().unwrap().q_idx(Level::Leaf);
806 let step = (i32::from(q) - i32::from(prev_q)).abs();1419 let step = (i32::from(q) - i32::from(prev_q)).abs();
807 assert!(1420 assert!(
808 f64::from(step) <= RateLoop::STEP_CLAMP + 1.0, // +1 for u8 rounding1421 f64::from(step) <= RateLoop::STEP_CLAMP + 1.0, // +1 for u8 rounding
@@ -859,6 +1472,105 @@ mod tests {
859 .collect()1472 .collect()
860 }1473 }
861 1474
1475+ /// A pyramid stream reorders pictures: the hidden `ALTREF` of each
1476+ /// mini-GOP is coded before the leaves that precede it in display order,
1477+ /// and a `show_existing_frame` header puts it back. This pins the shape
1478+ /// (one packet per source picture plus one `show_existing_frame` per
1479+ /// group, `dts` monotone, `order` NOT monotone) and then decodes the
1480+ /// whole stream through OUR decoder and through ffmpeg/dav1d and requires
1481+ /// the two display-order outputs to agree sample for sample — the
1482+ /// [[gate-blind-to-hidden-frames]] check: a hidden frame that is never
1483+ /// output, or output twice, or output in the wrong position, changes the
1484+ /// display-order list and fails here.
1485+ #[test]
1486+ fn a_pyramid_stream_decodes_in_display_order_through_both_decoders() {
1487+ let (width, height) = (128usize, 64usize);
1488+ let config = EncoderConfig {
1489+ width,
1490+ height,
1491+ base_q_idx: 120,
1492+ gop: 32,
1493+ colour: Colour::Bt709Limited,
1494+ };
1495+ let pyramid = Pyramid {
1496+ mini_gop: 4,
1497+ ..Pyramid::default()
1498+ };
1499+ let mut enc = Av1Encoder::with_pyramid(config, pyramid).unwrap();
1500+ let sources: Vec<Picture> = (0..9).map(|t| test_card(width, height, t * 3)).collect();
1501+ let _ = crate::encode::take_ref_frame_hits();
1502+ let mut packets = Vec::new();
1503+ for picture in &sources {
1504+ packets.extend(enc.encode_frames(picture).unwrap());
1505+ }
1506+ packets.extend(enc.flush().unwrap());
1507+
1508+ // Shape: every source picture is coded exactly once, and each closed
1509+ // group adds one `show_existing_frame` packet.
1510+ let coded: Vec<u64> = packets
1511+ .iter()
1512+ .filter(|p| p.level != Level::ShowExisting)
1513+ .map(|p| p.order)
1514+ .collect();
1515+ let mut sorted = coded.clone();
1516+ sorted.sort_unstable();
1517+ assert_eq!(sorted, (0..9).collect::<Vec<u64>>(), "one packet per picture");
1518+ assert_ne!(coded, sorted, "the pyramid never reordered anything");
1519+ let shown = packets.iter().filter(|p| p.level == Level::ShowExisting).count();
1520+ assert_eq!(shown, 2, "one show_existing_frame per closed mini-GOP");
1521+ for (i, p) in packets.iter().enumerate() {
1522+ assert_eq!(p.dts, i as u64, "packet {i}: dts is the coding position");
1523+ }
1524+ let hist = |l: Level| packets.iter().filter(|p| p.level == l).count();
1525+ eprintln!(
1526+ "pyramid levels: key {} arf {} leaf {} show_existing {}",
1527+ hist(Level::Key),
1528+ hist(Level::Arf),
1529+ hist(Level::Leaf),
1530+ hist(Level::ShowExisting),
1531+ );
1532+ assert_eq!(hist(Level::Arf), 2, "two hidden frames");
1533+ let refs = crate::encode::take_ref_frame_hits();
1534+ eprintln!(
1535+ "blocks per reference: LAST {} GOLDEN {} ALTREF {}",
1536+ refs[crate::mvstack::LAST_FRAME as usize],
1537+ refs[crate::mvstack::GOLDEN_FRAME as usize],
1538+ refs[crate::mvstack::ALTREF_FRAME as usize],
1539+ );
1540+ // [[gate-blind-to-feature]]: the whole point of the hidden frame is
1541+ // that the leaves predict BACKWARD off it, which is also the only
1542+ // thing that exercises `ref_frame_sign_bias` in the MV stack. A green
1543+ // round trip in which `ALTREF_FRAME` never won a block would prove
1544+ // only that a hidden frame can be written and re-output.
1545+ assert!(
1546+ refs[crate::mvstack::ALTREF_FRAME as usize] > 0,
1547+ "no block predicted off the hidden ALTREF"
1548+ );
1549+
1550+ let stream = concat(&packets);
1551+ let ours = crate::stream::decode_stream(&stream).expect("our decoder");
1552+ assert_eq!(ours.len(), sources.len(), "our decoder's display-order count");
1553+ if !have_ffmpeg() {
1554+ eprintln!("SKIP the ffmpeg half of the pyramid round trip: no ffmpeg");
1555+ return;
1556+ }
1557+ let theirs = ffmpeg_decode_luma(&stream, width, height);
1558+ assert_eq!(theirs.len(), sources.len(), "ffmpeg's display-order count");
1559+ for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() {
1560+ let got: Vec<u8> = a.y.iter().map(|&v| v as u8).collect();
1561+ assert_eq!(got.len(), b.len(), "frame {i}: luma size");
1562+ if let Some(at) = got.iter().zip(b).position(|(x, y)| x != y) {
1563+ panic!(
1564+ "display frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}",
1565+ at % width,
1566+ at / width,
1567+ got[at],
1568+ b[at],
1569+ );
1570+ }
1571+ }
1572+ }
1573+
862 /// [`RateTarget::Quality`] is monotone: a higher quality dial never1574 /// [`RateTarget::Quality`] is monotone: a higher quality dial never
863 /// produces a smaller stream or a worse mean PSNR than a lower one, on1575 /// produces a smaller stream or a worse mean PSNR than a lower one, on
864 /// the same real clip.1576 /// the same real clip.
crates/ec-av1/src/frame.rsmodified+79 -7
@@ -324,18 +324,59 @@ fn write_frame_size(w: &mut BitWriter, seq: &SequenceHeader, h: &FrameHeader) ->
324 Ok(())324 Ok(())
325 }325 }
326 326
327+/// `uncompressed_header()` (spec 5.9.2) for a `show_existing_frame` header:
328+/// the whole header is the flag, the three-bit DPB slot to output, and
329+/// nothing else -- no tile payload follows, and the OBU carrying it is an
330+/// `OBU_FRAME_HEADER`, not an `OBU_FRAME`. `frame_id_numbers_present_flag`
331+/// and `film_grain_params_present` are both false in every sequence header
332+/// this crate writes, and `decoder_model_info` is refused, so none of the
333+/// three conditional fields spec 5.9.2 lists after the index is coded.
334+///
335+/// # Errors
336+/// Returns an error when the sequence header carries any of the three, since
337+/// the extra fields are not written.
338+pub fn write_show_existing_frame_header(
339+ w: &mut BitWriter,
340+ seq: &SequenceHeader,
341+ frame_to_show_map_idx: u8,
342+) -> Result<()> {
343+ if seq.frame_id_numbers_present_flag
344+ || seq.film_grain_params_present
345+ || seq.decoder_model_info.is_some()
346+ {
347+ return Err(Error::unsupported(
348+ "AV1 frame header",
349+ "a show_existing_frame header with frame ids, film grain or decoder model timing is not written",
350+ ));
351+ }
352+ if frame_to_show_map_idx >= 8 {
353+ return Err(Error::corrupt(
354+ "AV1 frame header: show_existing_frame names a slot above 7",
355+ ));
356+ }
357+ w.write_bit(true); // show_existing_frame
358+ w.write_bits(u32::from(frame_to_show_map_idx), 3);
359+ Ok(())
360+}
361+
327 /// `uncompressed_header()` (spec 5.9.2) for a shown key or inter frame: no362 /// `uncompressed_header()` (spec 5.9.2) for a shown key or inter frame: no
328 /// decoder model, no frame ids, no still-picture shortcut, and (for an inter363 /// decoder model, no frame ids, no still-picture shortcut, and (for an inter
329 /// frame) short reference signalling, non-identity global motion, compound364 /// frame) short reference signalling, non-identity global motion, compound
330 /// reference selection and warped motion are all refused rather than written.365 /// reference selection and warped motion are all refused rather than written.
331 pub fn write_frame_header(w: &mut BitWriter, seq: &SequenceHeader, h: &FrameHeader) -> Result<()> {366 pub fn write_frame_header(w: &mut BitWriter, seq: &SequenceHeader, h: &FrameHeader) -> Result<()> {
332- if !matches!(h.frame_type, FrameType::Key | FrameType::Inter)367+ if !matches!(h.frame_type, FrameType::Key | FrameType::Inter) || h.show_existing_frame {
333- || !h.show_frame368+ return Err(Error::unsupported(
334- || h.show_existing_frame369+ "AV1 frame header",
335- {370+ "only a key or inter frame is written",
371+ ));
372+ }
373+ // A hidden frame is an inter frame only: a key frame with `show_frame`
374+ // clear changes the header layout further up (`error_resilient_mode` and
375+ // `refresh_frame_flags` stop being forced), and nothing writes one.
376+ if !h.show_frame && h.frame_type == FrameType::Key {
336 return Err(Error::unsupported(377 return Err(Error::unsupported(
337 "AV1 frame header",378 "AV1 frame header",
338- "only a shown key or inter frame is written",379+ "a key frame is only written shown",
339 ));380 ));
340 }381 }
341 let is_key = h.frame_type == FrameType::Key;382 let is_key = h.frame_type == FrameType::Key;
@@ -360,8 +401,14 @@ pub fn write_frame_header(w: &mut BitWriter, seq: &SequenceHeader, h: &FrameHead
360 401
361 w.write_bit(false); // show_existing_frame402 w.write_bit(false); // show_existing_frame
362 w.write_bits(if is_key { 0 } else { 1 }, 2); // frame_type403 w.write_bits(if is_key { 0 } else { 1 }, 2); // frame_type
363- w.write_bit(true); // show_frame404+ w.write_bit(h.show_frame);
364- // showable_frame is derived by the reader when show_frame is set, and not coded.405+ // spec 5.9.2: `showable_frame` is derived (`frame_type != KEY_FRAME`)
406+ // when `show_frame` is set and coded when it is not. A hidden frame this
407+ // encoder writes is always shown later by a `show_existing_frame` header
408+ // ([`write_show_existing_frame_header`]), so the bit it codes is 1.
409+ if !h.show_frame {
410+ w.write_bit(true);
411+ }
365 if is_key {412 if is_key {
366 // error_resilient_mode is forced true for a shown key frame.413 // error_resilient_mode is forced true for a shown key frame.
367 } else {414 } else {
@@ -523,6 +570,31 @@ pub fn write_frame_header(w: &mut BitWriter, seq: &SequenceHeader, h: &FrameHead
523 Ok(())570 Ok(())
524 }571 }
525 572
573+/// An `OBU_FRAME_HEADER` carrying nothing but a `show_existing_frame` header
574+/// (spec 5.9.2 + 5.3.4's `trailing_bits`): the OBU that re-outputs a hidden
575+/// frame from DPB slot `frame_to_show_map_idx`. Unlike [`frame_obu`] this is
576+/// `OBU_FRAME_HEADER`, so its payload ends with `trailing_bits` (a one bit
577+/// then zeroes) rather than a plain byte alignment.
578+///
579+/// # Errors
580+/// As [`write_show_existing_frame_header`].
581+pub fn show_existing_frame_obu(seq: &SequenceHeader, frame_to_show_map_idx: u8) -> Result<Vec<u8>> {
582+ let mut w = BitWriter::new();
583+ write_show_existing_frame_header(&mut w, seq, frame_to_show_map_idx)?;
584+ w.write_bit(true); // trailing_one_bit
585+ write_byte_alignment(&mut w);
586+ Ok(wrap_obu(
587+ &ObuHeader {
588+ obu_type: ObuType::FrameHeader,
589+ extension_flag: false,
590+ has_size_field: true,
591+ temporal_id: 0,
592+ spatial_id: 0,
593+ },
594+ &w.into_bytes(),
595+ ))
596+}
597+
526 /// A `OBU_FRAME`: the header above, byte-aligned, followed by the tile group598 /// A `OBU_FRAME`: the header above, byte-aligned, followed by the tile group
527 /// payload the caller supplies.599 /// payload the caller supplies.
528 pub fn frame_obu(seq: &SequenceHeader, h: &FrameHeader, tile_data: &[u8]) -> Result<Vec<u8>> {600 pub fn frame_obu(seq: &SequenceHeader, h: &FrameHeader, tile_data: &[u8]) -> Result<Vec<u8>> {
crates/ec-av1/src/mvstack.rsmodified+17 -1
@@ -256,6 +256,16 @@ pub struct MiGrid {
256 tile_col0: usize,256 tile_col0: usize,
257 tile_row1: usize,257 tile_row1: usize,
258 tile_col1: usize,258 tile_col1: usize,
259+ /// This frame's `ref_frame_sign_bias` (spec 5.9.2), the table
260+ /// [`find_mv_stack`] scans under. It lives on the grid rather than in
261+ /// every caller's argument list because it is frame-scoped exactly as the
262+ /// grid is, and because the tile WRITER reaches `find_mv_stack` through
263+ /// four nested helpers that would otherwise each grow a parameter. All
264+ /// `false` (every reference in the past) unless
265+ /// [`Self::set_sign_bias`] says otherwise -- which is what a frame with a
266+ /// backward `ALTREF_FRAME` (a pyramid's hidden future frame) must do, or
267+ /// its writer builds a different stack than the decoder does.
268+ sign_bias: SignBiasTable,
259 }269 }
260 270
261 impl MiGrid {271 impl MiGrid {
@@ -269,9 +279,15 @@ impl MiGrid {
269 tile_col0: 0,279 tile_col0: 0,
270 tile_row1: rows,280 tile_row1: rows,
271 tile_col1: cols,281 tile_col1: cols,
282+ sign_bias: NO_SIGN_BIAS,
272 }283 }
273 }284 }
274 285
286+ /// Sets this frame's `ref_frame_sign_bias` (see the field).
287+ pub fn set_sign_bias(&mut self, sign_bias: SignBiasTable) {
288+ self.sign_bias = sign_bias;
289+ }
290+
275 /// Narrows [`Self::get`]'s own read window to one tile's mi-unit span291 /// Narrows [`Self::get`]'s own read window to one tile's mi-unit span
276 /// (`row1`/`col1` exclusive) -- called once per tile, before that292 /// (`row1`/`col1` exclusive) -- called once per tile, before that
277 /// tile's own superblock walk, the same way `Neighbours::start_tile`293 /// tile's own superblock walk, the same way `Neighbours::start_tile`
@@ -1146,7 +1162,7 @@ pub fn find_mv_stack(
1146 ref_frame,1162 ref_frame,
1147 mi_cols,1163 mi_cols,
1148 mi_rows,1164 mi_rows,
1149- &NO_SIGN_BIAS,1165+ &grid.sign_bias,
1150 &NO_GM_MV,1166 &NO_GM_MV,
1151 None,1167 None,
1152 )1168 )
crates/ec-av1/src/tile.rsmodified+18 -0
@@ -144,6 +144,22 @@ pub(crate) fn arm_cdef_idx(bits: u8, sb_cols: usize, grid: Vec<u8>) {
144 });144 });
145 }145 }
146 146
147+thread_local! {
148+ static SIGN_BIAS: std::cell::Cell<crate::mvstack::SignBiasTable> =
149+ const { std::cell::Cell::new(crate::mvstack::NO_SIGN_BIAS) };
150+}
151+
152+/// Arms the next tile write with this frame's `ref_frame_sign_bias` (spec
153+/// 5.9.2), the table its MV-stack scans run under. Armed the same way
154+/// [`arm_cdef_idx`]/[`arm_lr`] are -- and disarmed by the same guard -- so
155+/// that a frame with a backward reference needs no new parameter on the four
156+/// nested writer helpers between here and `find_mv_stack`. A frame that never
157+/// names a future reference leaves this alone: all-`false` is what every
158+/// stream this crate wrote before pyramids existed codes under.
159+pub(crate) fn arm_sign_bias(sign_bias: crate::mvstack::SignBiasTable) {
160+ SIGN_BIAS.with(|c| c.set(sign_bias));
161+}
162+
147 /// Clears the armed plan when the tile writer that consumed it returns.163 /// Clears the armed plan when the tile writer that consumed it returns.
148 struct CdefIdxGuard;164 struct CdefIdxGuard;
149 165
@@ -151,6 +167,7 @@ impl Drop for CdefIdxGuard {
151 fn drop(&mut self) {167 fn drop(&mut self) {
152 CDEF_IDX.with(|c| *c.borrow_mut() = None);168 CDEF_IDX.with(|c| *c.borrow_mut() = None);
153 LR_PLAN.with(|c| *c.borrow_mut() = None);169 LR_PLAN.with(|c| *c.borrow_mut() = None);
170+ SIGN_BIAS.with(|c| c.set(crate::mvstack::NO_SIGN_BIAS));
154 }171 }
155 }172 }
156 173
@@ -3209,6 +3226,7 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs(
3209 mi_rows as usize,3226 mi_rows as usize,
3210 );3227 );
3211 let mut grid = MiGrid::new(mi_cols as usize, mi_rows as usize);3228 let mut grid = MiGrid::new(mi_cols as usize, mi_rows as usize);
3229+ grid.set_sign_bias(SIGN_BIAS.with(std::cell::Cell::get));
3212 let mut cdfs = cdfs;3230 let mut cdfs = cdfs;
3213 let mut enc = SymbolEncoder::new();3231 let mut enc = SymbolEncoder::new();
3214 // An `is_inter` block's 32x32 luma transform reads a different3232 // An `is_inter` block's 32x32 luma transform reads a different
tools/ec-bench/src/main.rsmodified+27 -4
@@ -13,7 +13,7 @@ use std::process::Command;
13 use std::time::Instant;13 use std::time::Instant;
14 14
15 use ec_av1::encode::Picture as Av1Picture;15 use ec_av1::encode::Picture as Av1Picture;
16-use ec_av1::encoder::{Av1Encoder, Colour, EncoderConfig as Av1Config};16+use ec_av1::encoder::{Av1Encoder, Colour, EncoderConfig as Av1Config, Level, Pyramid};
17 use ec_core::frame::{17 use ec_core::frame::{
18 AudioFrame, ChannelLayout, Frame, PixelFormat, Plane, SampleFormat, VideoFrame,18 AudioFrame, ChannelLayout, Frame, PixelFormat, Plane, SampleFormat, VideoFrame,
19 };19 };
@@ -352,9 +352,26 @@ fn bench_av1_encode(rows: &mut Vec<Row>) {
352 gop: 10,352 gop: 10,
353 colour: Colour::default(),353 colour: Colour::default(),
354 };354 };
355- let mut enc = Av1Encoder::new(cfg).expect("av1 encoder");355+ // `EC_AV1_PYRAMID=<mini_gop>[:<arf_q_offset>:<leaf_q_offset>]` benches the
356+ // encoder's coding pyramid (hidden ALTREF + show_existing_frame) instead
357+ // of the flat one-picture-one-packet stream, the same knob shape as
358+ // `EC_H265_RDOQ_ESTIMATE`. Unset keeps the flat default.
359+ let pyramid = std::env::var("EC_AV1_PYRAMID").ok().and_then(|spec| {
360+ let mut f = spec.split(':');
361+ let d = Pyramid::default();
362+ Some(Pyramid {
363+ mini_gop: f.next()?.parse().ok()?,
364+ arf_q_offset: f.next().and_then(|v| v.parse().ok()).unwrap_or(d.arf_q_offset),
365+ leaf_q_offset: f.next().and_then(|v| v.parse().ok()).unwrap_or(d.leaf_q_offset),
366+ })
367+ });
368+ let mut enc = match pyramid {
369+ None => Av1Encoder::new(cfg).expect("av1 encoder"),
370+ Some(p) => Av1Encoder::with_pyramid(cfg, p).expect("av1 encoder"),
371+ };
356 let frame_len = (w * h + 2 * (w.div_ceil(2) * h.div_ceil(2))) as usize;372 let frame_len = (w * h + 2 * (w.div_ceil(2) * h.div_ceil(2))) as usize;
357 let mut stream = Vec::new();373 let mut stream = Vec::new();
374+ let mut hidden = 0usize;
358 let start = Instant::now();375 let start = Instant::now();
359 for frame in planes.chunks_exact(frame_len) {376 for frame in planes.chunks_exact(frame_len) {
360 let (y, rest) = frame.split_at((w * h) as usize);377 let (y, rest) = frame.split_at((w * h) as usize);
@@ -368,7 +385,13 @@ fn bench_av1_encode(rows: &mut Vec<Row>) {
368 u: u.iter().map(|&s| u16::from(s)).collect(),385 u: u.iter().map(|&s| u16::from(s)).collect(),
369 v: v.iter().map(|&s| u16::from(s)).collect(),386 v: v.iter().map(|&s| u16::from(s)).collect(),
370 };387 };
371- let packet = enc.encode(&pic).expect("av1 encode");388+ for packet in enc.encode_frames(&pic).expect("av1 encode") {
389+ hidden += usize::from(packet.level == Level::Arf);
390+ stream.extend_from_slice(&packet.data);
391+ }
392+ }
393+ for packet in enc.flush().expect("av1 flush") {
394+ hidden += usize::from(packet.level == Level::Arf);
372 stream.extend_from_slice(&packet.data);395 stream.extend_from_slice(&packet.data);
373 }396 }
374 let wall = start.elapsed().as_secs_f64();397 let wall = start.elapsed().as_secs_f64();
@@ -379,7 +402,7 @@ fn bench_av1_encode(rows: &mut Vec<Row>) {
379 component: "ec-av1",402 component: "ec-av1",
380 direction: "encode",403 direction: "encode",
381 content: format!(404 content: format!(
382- "{w}x{h}, {n} frames, gop=10, {fps:.1} fps, {bytes_per_frame:.0} B/frame"405+ "{w}x{h}, {n} frames, gop=10, {hidden} hidden, {fps:.1} fps, {bytes_per_frame:.0} B/frame"
383 ),406 ),
384 media: format!("{media_s:.1}s"),407 media: format!("{media_s:.1}s"),
385 wall_ms: wall * 1000.0,408 wall_ms: wall * 1000.0,