A two-level frame pyramid in the encoder facade
Browse files at this commitd4969055e1ff540255a09be1968ae5688b53109cParent: 56a796a- feat
- a two-level frame pyramid in the encoder facade
5 changed files +705 -75
- crates/ec-av1/src/encode.rs +60 -13
- crates/ec-av1/src/encoder.rs +531 -54
- crates/ec-av1/src/frame.rs +79 -7
- crates/ec-av1/src/mvstack.rs +17 -1
- crates/ec-av1/src/tile.rs +18 -0
crates/ec-av1/src/encode.rsmodified+60 -13
| @@ -3988,6 +3988,33 @@ fn search_inter_block( | |||
| 3988 | ) | 3988 | ) |
| 3989 | } | 3989 | } |
| 3990 | 3990 | ||
| 3991 | +/// Where one inter frame sits in a coding-order pyramid: which DPB slots its | ||
| 3992 | +/// references name, which slot it refreshes, whether it is shown when it is | ||
| 3993 | +/// coded, and the `ref_frame_sign_bias` that follows from all of it. `None` | ||
| 3994 | +/// keeps `encode_inter_frame`'s pre-pyramid flat behaviour verbatim (slot | ||
| 3995 | +/// 0/2 alternation, every frame shown, every reference in the past). | ||
| 3996 | +/// | ||
| 3997 | +/// The sign bias is carried rather than derived here because only the caller | ||
| 3998 | +/// knows what order hint each slot holds; it is armed onto the tile writer | ||
| 3999 | +/// ([`crate::tile::arm_sign_bias`]) and set on the encoder's own MV grid, so | ||
| 4000 | +/// the writer scans the same stacks the decoder will. | ||
| 4001 | +#[derive(Debug, Clone, Copy)] | ||
| 4002 | +pub(crate) struct PyramidFrame { | ||
| 4003 | + /// The slot `LAST_FRAME` (and every reference this encoder does not name | ||
| 4004 | + /// apart) reads. | ||
| 4005 | + pub last_slot: u8, | ||
| 4006 | + /// The single slot `refresh_frame_flags` sets. | ||
| 4007 | + pub self_slot: u8, | ||
| 4008 | + /// The slot `ALTREF_FRAME` reads -- a FUTURE frame for a leaf of a | ||
| 4009 | + /// pyramid, which is what makes `sign_bias`'s last entry true. | ||
| 4010 | + pub altref_slot: u8, | ||
| 4011 | + /// `show_frame`: false for a hidden frame, output later by a | ||
| 4012 | + /// `show_existing_frame` header. | ||
| 4013 | + pub show_frame: bool, | ||
| 4014 | + /// This frame's `ref_frame_sign_bias` (spec 5.9.2). | ||
| 4015 | + pub sign_bias: crate::mvstack::SignBiasTable, | ||
| 4016 | +} | ||
| 4017 | + | ||
| 3991 | /// Encodes one picture as an inter frame predicting from `reference`'s | 4018 | /// Encodes one picture as an inter frame predicting from `reference`'s |
| 3992 | /// reconstruction, which the caller decoded (or, for the frame right after | 4019 | /// reconstruction, which the caller decoded (or, for the frame right after |
| 3993 | /// the key frame, is the key frame's own reconstruction). | 4020 | /// the key frame, is the key frame's own reconstruction). |
| @@ -4011,6 +4038,9 @@ pub(crate) fn encode_inter_frame( | |||
| 4011 | // (the encoder alternates 0/2): `ALTREF_FRAME`. `None` for the first two | 4038 | // (the encoder alternates 0/2): `ALTREF_FRAME`. `None` for the first two |
| 4012 | // inter frames of a GOP, where the frame two back IS the key frame. | 4039 | // inter frames of a GOP, where the frame two back IS the key frame. |
| 4013 | altref: Option<&Picture>, fctx: &crate::decode::FrameCtx, | 4040 | altref: Option<&Picture>, fctx: &crate::decode::FrameCtx, |
| 4041 | + // Where this frame sits in the coding-order pyramid; `None` is the flat | ||
| 4042 | + // one-shown-frame-per-picture stream this encoder wrote before. | ||
| 4043 | + pyramid: Option<PyramidFrame>, | ||
| 4014 | ) -> Result<Encoded> { | 4044 | ) -> Result<Encoded> { |
| 4015 | picture.check()?; | 4045 | picture.check()?; |
| 4016 | if !picture.width.is_multiple_of(SUPERBLOCK) || !picture.height.is_multiple_of(SUPERBLOCK) { | 4046 | if !picture.width.is_multiple_of(SUPERBLOCK) || !picture.height.is_multiple_of(SUPERBLOCK) { |
| @@ -4037,14 +4067,17 @@ pub(crate) fn encode_inter_frame( | |||
| 4037 | // frame: frame n writes A(n) = 0 for odd n, 2 for even, so A(n) = A(n-2) | 4067 | // frame: frame n writes A(n) = 0 for odd n, 2 for even, so A(n) = A(n-2) |
| 4038 | // and the picture this frame names as `ALTREF_FRAME` is the one sitting | 4068 | // and the picture this frame names as `ALTREF_FRAME` is the one sitting |
| 4039 | // in the very slot it will overwrite. | 4069 | // in the very slot it will overwrite. |
| 4040 | - let self_slot = if order_hint % 2 == 1 { 0 } else { 2 }; | 4070 | + let self_slot = pyramid.map_or(if order_hint % 2 == 1 { 0 } else { 2 }, |p| p.self_slot); |
| 4041 | - let last_slot = if order_hint <= 1 { | 4071 | + let last_slot = pyramid.map_or( |
| 4042 | - LAST_SLOT | 4072 | + if order_hint <= 1 { |
| 4043 | - } else if (order_hint - 1) % 2 == 1 { | 4073 | + LAST_SLOT |
| 4044 | - 0 | 4074 | + } else if (order_hint - 1) % 2 == 1 { |
| 4045 | - } else { | 4075 | + 0 |
| 4046 | - 2 | 4076 | + } else { |
| 4047 | - }; | 4077 | + 2 |
| 4078 | + }, | ||
| 4079 | + |p| p.last_slot, | ||
| 4080 | + ); | ||
| 4048 | // `render`, not `picture.width`/`picture.height`: `picture` here is | 4081 | // `render`, not `picture.width`/`picture.height`: `picture` here is |
| 4049 | // already padded to a whole number of superblocks (`encode_sequence`'s | 4082 | // already padded to a whole number of superblocks (`encode_sequence`'s |
| 4050 | // `padded_to(SUPERBLOCK)`), and the header's `mi_cols`/`mi_rows` (and so | 4083 | // `padded_to(SUPERBLOCK)`), and the header's `mi_cols`/`mi_rows` (and so |
| @@ -4058,10 +4091,20 @@ pub(crate) fn encode_inter_frame( | |||
| 4058 | order_hint, | 4091 | order_hint, |
| 4059 | last_slot, | 4092 | last_slot, |
| 4060 | self_slot, | 4093 | self_slot, |
| 4061 | - if altref.is_some() { self_slot } else { GOLDEN_SLOT }, | 4094 | + match pyramid { |
| 4095 | + Some(p) => p.altref_slot, | ||
| 4096 | + None if altref.is_some() => self_slot, | ||
| 4097 | + None => GOLDEN_SLOT, | ||
| 4098 | + }, | ||
| 4062 | )?; | 4099 | )?; |
| 4063 | header.render_width = render.0 as u32; | 4100 | header.render_width = render.0 as u32; |
| 4064 | header.render_height = render.1 as u32; | 4101 | header.render_height = render.1 as u32; |
| 4102 | + let sign_bias = pyramid.map_or(crate::mvstack::NO_SIGN_BIAS, |p| p.sign_bias); | ||
| 4103 | + if let Some(p) = pyramid { | ||
| 4104 | + header.show_frame = p.show_frame; | ||
| 4105 | + header.showable_frame = !p.show_frame; | ||
| 4106 | + header.ref_frame_sign_bias = p.sign_bias; | ||
| 4107 | + } | ||
| 4065 | // `TxMode::Select` here too: an inter block then codes one `txfm_split` | 4108 | // `TxMode::Select` here too: an inter block then codes one `txfm_split` |
| 4066 | // flag (kept at zero -- its var-tx tree is not searched yet) and an INTRA | 4109 | // flag (kept at zero -- its var-tx tree is not searched yet) and an INTRA |
| 4067 | // block inside this frame codes and searches its own `tx_depth`, the same | 4110 | // block inside this frame codes and searches its own `tx_depth`, the same |
| @@ -4128,6 +4171,7 @@ pub(crate) fn encode_inter_frame( | |||
| 4128 | // once per frame (lane-av1rd2), not once per block, which is a whole | 4171 | // once per frame (lane-av1rd2), not once per block, which is a whole |
| 4129 | // plane's map per 32x32 block and now per leaf too. | 4172 | // plane's map per 32x32 block and now per leaf too. |
| 4130 | let mut grid = MiGrid::new(mi_cols, mi_rows); | 4173 | let mut grid = MiGrid::new(mi_cols, mi_rows); |
| 4174 | + grid.set_sign_bias(sign_bias); | ||
| 4131 | let mut blocks = vec![Quadrant::Whole(BlockCoeffs::default()); cols * rows]; | 4175 | let mut blocks = vec![Quadrant::Whole(BlockCoeffs::default()); cols * rows]; |
| 4132 | 4176 | ||
| 4133 | for sb_r in 0..sb_rows { | 4177 | for sb_r in 0..sb_rows { |
| @@ -4522,6 +4566,7 @@ pub(crate) fn encode_inter_frame( | |||
| 4522 | .cloned() | 4566 | .cloned() |
| 4523 | .unwrap_or_else(|| crate::cdf_state::Cdfs::new(crate::tile::q_ctx_of(base_q_idx))); | 4567 | .unwrap_or_else(|| crate::cdf_state::Cdfs::new(crate::tile::q_ctx_of(base_q_idx))); |
| 4524 | let start_cdfs = CdfSnapshot(cdfs.clone()); | 4568 | let start_cdfs = CdfSnapshot(cdfs.clone()); |
| 4569 | + crate::tile::arm_sign_bias(sign_bias); | ||
| 4525 | let mut tile = crate::tile::sb_coeff_inter_frame_tile_cdfs( | 4570 | let mut tile = crate::tile::sb_coeff_inter_frame_tile_cdfs( |
| 4526 | mi_cols, | 4571 | mi_cols, |
| 4527 | mi_rows, | 4572 | mi_rows, |
| @@ -4611,6 +4656,7 @@ pub(crate) fn encode_inter_frame( | |||
| 4611 | |bits, sb_cols, grid, units| { | 4656 | |bits, sb_cols, grid, units| { |
| 4612 | crate::tile::arm_cdef_idx(bits, sb_cols, grid.to_vec()); | 4657 | crate::tile::arm_cdef_idx(bits, sb_cols, grid.to_vec()); |
| 4613 | crate::tile::arm_lr(64, lr_horz, lr_vert, units.to_vec()); | 4658 | crate::tile::arm_lr(64, lr_horz, lr_vert, units.to_vec()); |
| 4659 | + crate::tile::arm_sign_bias(sign_bias); | ||
| 4614 | let mut cdfs = start_cdfs.0.clone(); | 4660 | let mut cdfs = start_cdfs.0.clone(); |
| 4615 | let coded = crate::tile::sb_coeff_inter_frame_tile_cdfs( | 4661 | let coded = crate::tile::sb_coeff_inter_frame_tile_cdfs( |
| 4616 | mi_cols, | 4662 | mi_cols, |
| @@ -4766,6 +4812,7 @@ pub(crate) fn encode_sequence_with_ctx( | |||
| 4766 | Some(&carried.0), | 4812 | Some(&carried.0), |
| 4767 | Some(&golden), | 4813 | Some(&golden), |
| 4768 | prev2.as_ref(), fctx, | 4814 | prev2.as_ref(), fctx, |
| 4815 | + None, | ||
| 4769 | )?; | 4816 | )?; |
| 4770 | stream.extend_from_slice(&inter.stream); | 4817 | stream.extend_from_slice(&inter.stream); |
| 4771 | carried = inter.next_cdfs.clone(); | 4818 | carried = inter.next_cdfs.clone(); |
| @@ -6805,7 +6852,7 @@ mod tests { | |||
| 6805 | let padded_pic = picture.padded_to(SUPERBLOCK); | 6852 | let padded_pic = picture.padded_to(SUPERBLOCK); |
| 6806 | let t = Instant::now(); | 6853 | let t = Instant::now(); |
| 6807 | let inter = | 6854 | let inter = |
| 6808 | - encode_inter_frame(&padded_pic, &padded_ref, 100, 0.5, 1, (width, height), None, None, None, fctx).unwrap(); | 6855 | + encode_inter_frame(&padded_pic, &padded_ref, 100, 0.5, 1, (width, height), None, None, None, fctx, None).unwrap(); |
| 6809 | let inter_t = t.elapsed(); | 6856 | let inter_t = t.elapsed(); |
| 6810 | eprintln!( | 6857 | eprintln!( |
| 6811 | "inter frame vs its own key frame: {inter_t:>9.2?} ({} bytes, inter share \ | 6858 | "inter frame vs its own key frame: {inter_t:>9.2?} ({} bytes, inter share \ |
| @@ -6903,7 +6950,7 @@ mod tests { | |||
| 6903 | stage_reset(); | 6950 | stage_reset(); |
| 6904 | let t = Instant::now(); | 6951 | let t = Instant::now(); |
| 6905 | let inter = | 6952 | let inter = |
| 6906 | - encode_inter_frame(&padded_pic, &padded_ref, 100, 0.5, 1, (width, height), None, None, None, fctx).unwrap(); | 6953 | + encode_inter_frame(&padded_pic, &padded_ref, 100, 0.5, 1, (width, height), None, None, None, fctx, None).unwrap(); |
| 6907 | let total_t = t.elapsed(); | 6954 | let total_t = t.elapsed(); |
| 6908 | let [motion_search, interpolation, transform_quant, entropy] = stage_read(); | 6955 | let [motion_search, interpolation, transform_quant, entropy] = stage_read(); |
| 6909 | let accounted = motion_search + transform_quant + entropy; | 6956 | let accounted = motion_search + transform_quant + entropy; |
| @@ -7080,7 +7127,7 @@ mod tests { | |||
| 7080 | q, | 7127 | q, |
| 7081 | 0.5, | 7128 | 0.5, |
| 7082 | 1, | 7129 | 1, |
| 7083 | - (width, height), None, None, None, fctx, | 7130 | + (width, height), None, None, None, fctx, None, |
| 7084 | ) | 7131 | ) |
| 7085 | .unwrap(); | 7132 | .unwrap(); |
| 7086 | let baseline_psnr = psnr(&baseline.reconstruction.y, &inter_source.y); | 7133 | let baseline_psnr = psnr(&baseline.reconstruction.y, &inter_source.y); |
| @@ -7097,7 +7144,7 @@ mod tests { | |||
| 7097 | q, | 7144 | q, |
| 7098 | 0.5, | 7145 | 0.5, |
| 7099 | 1, | 7146 | 1, |
| 7100 | - (width, height), None, None, None, fctx, | 7147 | + (width, height), None, None, None, fctx, None, |
| 7101 | ) | 7148 | ) |
| 7102 | .unwrap(); | 7149 | .unwrap(); |
| 7103 | let pruned_psnr = psnr(&pruned.reconstruction.y, &inter_source.y); | 7150 | let pruned_psnr = psnr(&pruned.reconstruction.y, &inter_source.y); |
crates/ec-av1/src/encoder.rsmodified+531 -54
| @@ -17,8 +17,8 @@ use ec_av1_syntax::sequence::{ChromaSamplePosition, ColorConfig}; | |||
| 17 | use ec_core::{Error, Result}; | 17 | use ec_core::{Error, Result}; |
| 18 | 18 | ||
| 19 | use crate::encode::{ | 19 | use crate::encode::{ |
| 20 | - Encoded, Picture, SUPERBLOCK, crop_encoded, encode_inter_frame, encode_key_frame_inner, | 20 | + Encoded, GOLDEN_SLOT, Picture, SUPERBLOCK, crop_encoded, encode_inter_frame, |
| 21 | - split_blocks, | 21 | + encode_key_frame_inner, split_blocks, |
| 22 | }; | 22 | }; |
| 23 | use crate::intra::KEY_FRAME_MODES; | 23 | use crate::intra::KEY_FRAME_MODES; |
| 24 | 24 | ||
| @@ -100,6 +100,46 @@ pub enum RateTarget { | |||
| 100 | /// coded frame near this many bytes, via [`RateLoop`] — see there for | 100 | /// coded frame near this many bytes, via [`RateLoop`] — see there for |
| 101 | /// the controller and its windup bound. | 101 | /// the controller and its windup bound. |
| 102 | BytesPerFrame(u32), | 102 | BytesPerFrame(u32), |
| 103 | + /// A target BITRATE: the same closed loop, with the per-frame byte | ||
| 104 | + /// target derived from `bits_per_second` and `frames_per_second` | ||
| 105 | + /// (`bits_per_second / 8 / frames_per_second`), and — in pyramid mode — | ||
| 106 | + /// split across the levels by their reference weight, since a hidden | ||
| 107 | + /// `ALTREF` and a leaf differ by several times in size and one shared | ||
| 108 | + /// predictor would swing the quantizer every frame. | ||
| 109 | + Bitrate { | ||
| 110 | + /// The stream's target bitrate. | ||
| 111 | + bits_per_second: u32, | ||
| 112 | + /// The frame rate the bitrate is spent at. | ||
| 113 | + frames_per_second: f64, | ||
| 114 | + }, | ||
| 115 | +} | ||
| 116 | + | ||
| 117 | +impl RateTarget { | ||
| 118 | + /// Applies this target to `config` and returns the closed loop it needs | ||
| 119 | + /// (`None` for the two open-loop variants). `mini_gop` is `Some` in | ||
| 120 | + /// pyramid mode, which is what makes the loop keep a quantizer per level. | ||
| 121 | + fn into_loop(self, config: &mut EncoderConfig, mini_gop: Option<usize>) -> Option<RateLoop> { | ||
| 122 | + let target_bytes = match self { | ||
| 123 | + RateTarget::QIndex(q) => { | ||
| 124 | + config.base_q_idx = q; | ||
| 125 | + return None; | ||
| 126 | + } | ||
| 127 | + RateTarget::Quality(quality) => { | ||
| 128 | + config.base_q_idx = quality_to_q_idx(quality); | ||
| 129 | + return None; | ||
| 130 | + } | ||
| 131 | + RateTarget::BytesPerFrame(target_bytes) => f64::from(target_bytes), | ||
| 132 | + RateTarget::Bitrate { | ||
| 133 | + bits_per_second, | ||
| 134 | + frames_per_second, | ||
| 135 | + } => f64::from(bits_per_second) / 8.0 / frames_per_second.max(1.0), | ||
| 136 | + }; | ||
| 137 | + Some(RateLoop::new( | ||
| 138 | + target_bytes, | ||
| 139 | + f64::from(config.base_q_idx), | ||
| 140 | + mini_gop, | ||
| 141 | + )) | ||
| 142 | + } | ||
| 103 | } | 143 | } |
| 104 | 144 | ||
| 105 | /// `quality`'s mapping to `base_q_idx`, linear across the calibration sweep's | 145 | /// `quality`'s mapping to `base_q_idx`, linear across the calibration sweep's |
| @@ -112,19 +152,39 @@ fn quality_to_q_idx(quality: u8) -> u8 { | |||
| 112 | (240.0 - quality * 2.0).round() as u8 | 152 | (240.0 - quality * 2.0).round() as u8 |
| 113 | } | 153 | } |
| 114 | 154 | ||
| 115 | -/// The closed-loop controller behind [`RateTarget::BytesPerFrame`]: a | 155 | +/// 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 own | 156 | +/// 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. | 157 | +/// 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 — | 158 | +/// `ARF` the same way, through a lower quantizer rather than a byte target). |
| 119 | -/// no accumulated error term — is the windup bound itself | 159 | +const ARF_WEIGHT: f64 = 2.0; |
| 120 | -/// ([[vorbis-rate-loop-windup]]'s class): the only state carried between | 160 | + |
| 121 | -/// frames is `q`, already clamped to `0..=255`, so a quiet lead-in cannot | 161 | +/// 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 bounded | 162 | +const KEY_WEIGHT: f64 = 3.0; |
| 123 | -/// by `STEP_CLAMP` regardless of history. | 163 | + |
| 164 | +/// The closed-loop controller behind [`RateTarget::BytesPerFrame`] and | ||
| 165 | +/// [`RateTarget::Bitrate`]: a proportional step on `base_q_idx`, sized from | ||
| 166 | +/// the calibration sweep's own log-linear slope (bytes roughly halve every | ||
| 167 | +/// ~45 `q_idx` steps there, i.e. `d(ln bytes)/d(q_idx) ≈ -0.0154`), clamped | ||
| 168 | +/// per frame. Pure proportional — no accumulated error term — is the windup | ||
| 169 | +/// bound itself ([[vorbis-rate-loop-windup]]'s class): the only state carried | ||
| 170 | +/// between frames is `q`, already clamped to `0..=255`, so a quiet lead-in | ||
| 171 | +/// cannot build a debt a later transient has to repay; each frame's step is | ||
| 172 | +/// bounded by `STEP_CLAMP` regardless of history. | ||
| 173 | +/// | ||
| 174 | +/// In pyramid mode the state is kept PER LEVEL: each frame's size is | ||
| 175 | +/// predicted from the previous frame of its own level, against that level's | ||
| 176 | +/// own share of the budget, which is the whole "two-pass-free model" this | ||
| 177 | +/// encoder carries. | ||
| 124 | #[derive(Debug, Clone, Copy)] | 178 | #[derive(Debug, Clone, Copy)] |
| 125 | struct RateLoop { | 179 | struct RateLoop { |
| 126 | - target_bytes: u32, | 180 | + /// Byte target per level, indexed by [`RateLoop::slot`]. |
| 127 | - q: f64, | 181 | + target: [f64; 3], |
| 182 | + /// Quantizer per level, same index. | ||
| 183 | + q: [f64; 3], | ||
| 184 | + /// Whether the three slots are actually distinct (pyramid mode) or all | ||
| 185 | + /// one shared controller (the flat path, unchanged from before levels | ||
| 186 | + /// existed). | ||
| 187 | + per_level: bool, | ||
| 128 | } | 188 | } |
| 129 | 189 | ||
| 130 | impl RateLoop { | 190 | impl RateLoop { |
| @@ -137,25 +197,54 @@ impl RateLoop { | |||
| 137 | /// convert a bytes ratio into a `q_idx` step. | 197 | /// convert a bytes ratio into a `q_idx` step. |
| 138 | const GAIN: f64 = 1.0 / 0.0154; | 198 | const GAIN: f64 = 1.0 / 0.0154; |
| 139 | 199 | ||
| 140 | - fn new(target_bytes: u32, start_q: f64) -> Self { | 200 | + fn new(target_bytes: f64, start_q: f64, mini_gop: Option<usize>) -> Self { |
| 201 | + let Some(m) = mini_gop.map(|m| m as f64) else { | ||
| 202 | + return Self { | ||
| 203 | + target: [target_bytes; 3], | ||
| 204 | + q: [start_q; 3], | ||
| 205 | + per_level: false, | ||
| 206 | + }; | ||
| 207 | + }; | ||
| 208 | + // A group of `m` pictures gets `m * target_bytes`, split one | ||
| 209 | + // `ARF_WEIGHT` share to the hidden frame and one each to the `m - 1` | ||
| 210 | + // leaves, so the group's own average is the target exactly. | ||
| 211 | + let share = target_bytes * m / (m - 1.0 + ARF_WEIGHT); | ||
| 141 | Self { | 212 | Self { |
| 142 | - target_bytes, | 213 | + target: [target_bytes * KEY_WEIGHT, share * ARF_WEIGHT, share], |
| 143 | - q: start_q, | 214 | + q: [start_q; 3], |
| 215 | + per_level: true, | ||
| 144 | } | 216 | } |
| 145 | } | 217 | } |
| 146 | 218 | ||
| 147 | - fn q_idx(&self) -> u8 { | 219 | + /// Which controller a level uses: one shared slot on the flat path, three |
| 148 | - self.q.round().clamp(0.0, 255.0) as u8 | 220 | + /// separate ones under a pyramid. |
| 221 | + fn slot(&self, level: Level) -> usize { | ||
| 222 | + if !self.per_level { | ||
| 223 | + return 0; | ||
| 224 | + } | ||
| 225 | + match level { | ||
| 226 | + Level::Key => 0, | ||
| 227 | + Level::Arf => 1, | ||
| 228 | + // A `show_existing_frame` packet codes no pixels and never | ||
| 229 | + // reaches `update`; it shares the leaf slot so `q_idx` is total. | ||
| 230 | + Level::Leaf | Level::ShowExisting => 2, | ||
| 231 | + } | ||
| 149 | } | 232 | } |
| 150 | 233 | ||
| 151 | - /// Steers `q` toward `target_bytes` from this frame's actual coded size. | 234 | + fn q_idx(&self, level: Level) -> u8 { |
| 152 | - fn update(&mut self, actual_bytes: usize) { | 235 | + self.q[self.slot(level)].round().clamp(0.0, 255.0) as u8 |
| 153 | - if self.target_bytes == 0 || actual_bytes == 0 { | 236 | + } |
| 237 | + | ||
| 238 | + /// Steers this level's `q` toward its own target from the frame's actual | ||
| 239 | + /// coded size. | ||
| 240 | + fn update(&mut self, level: Level, actual_bytes: usize) { | ||
| 241 | + let slot = self.slot(level); | ||
| 242 | + if self.target[slot] <= 0.0 || actual_bytes == 0 { | ||
| 154 | return; | 243 | return; |
| 155 | } | 244 | } |
| 156 | - let ratio = actual_bytes as f64 / f64::from(self.target_bytes); | 245 | + let ratio = actual_bytes as f64 / self.target[slot]; |
| 157 | let step = (ratio.ln() * Self::GAIN).clamp(-Self::STEP_CLAMP, Self::STEP_CLAMP); | 246 | let step = (ratio.ln() * Self::GAIN).clamp(-Self::STEP_CLAMP, Self::STEP_CLAMP); |
| 158 | - self.q = (self.q + step).clamp(0.0, 255.0); | 247 | + self.q[slot] = (self.q[slot] + step).clamp(0.0, 255.0); |
| 159 | } | 248 | } |
| 160 | } | 249 | } |
| 161 | 250 | ||
| @@ -199,13 +288,85 @@ pub struct Packet { | |||
| 199 | pub data: Vec<u8>, | 288 | pub data: Vec<u8>, |
| 200 | /// Whether this picture was coded as a key frame. | 289 | /// Whether this picture was coded as a key frame. |
| 201 | pub key: bool, | 290 | pub key: bool, |
| 202 | - /// This picture's position in the stream, in coding (== presentation, | 291 | + /// This picture's position in DISPLAY (presentation) order, starting at |
| 203 | - /// since this encoder has no B frames) order, starting at 0. | 292 | + /// 0 — a muxer's `pts` in picture units. Without a [`Pyramid`] this is |
| 293 | + /// also the coding order and equals `dts`. | ||
| 204 | pub order: u64, | 294 | pub order: u64, |
| 295 | + /// This packet's position in CODING (decode) order, starting at 0 — a | ||
| 296 | + /// muxer's `dts` in packet units. With a [`Pyramid`] the hidden frame of | ||
| 297 | + /// each mini-GOP is coded before the leaves it precedes in display order, | ||
| 298 | + /// so `dts` and `order` diverge, and the `show_existing_frame` packet | ||
| 299 | + /// that re-outputs the hidden frame carries the hidden frame's own | ||
| 300 | + /// `order` with its own later `dts`. | ||
| 301 | + pub dts: u64, | ||
| 302 | + /// Which pyramid level this packet is. | ||
| 303 | + pub level: Level, | ||
| 304 | +} | ||
| 305 | + | ||
| 306 | +/// One mini-GOP of a two-level coding pyramid, and the quantizer offsets its | ||
| 307 | +/// two levels are coded at. libaom's `gf_group` shape, cut down to the two | ||
| 308 | +/// levels this encoder's reference set can carry: the last picture of each | ||
| 309 | +/// mini-GOP is coded FIRST, hidden (`show_frame == 0`), as the group's | ||
| 310 | +/// `ALTREF_FRAME`, then the pictures before it are coded as shown leaves that | ||
| 311 | +/// may predict backward off it, and finally a `show_existing_frame` header | ||
| 312 | +/// re-outputs the hidden frame in its own display position. | ||
| 313 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] | ||
| 314 | +pub struct Pyramid { | ||
| 315 | + /// Pictures per mini-GOP: the hidden frame is `mini_gop` pictures ahead | ||
| 316 | + /// of the group's anchor, and `mini_gop - 1` leaves sit between them. | ||
| 317 | + /// `1` would leave no leaf at all and is refused. | ||
| 318 | + pub mini_gop: usize, | ||
| 319 | + /// Added to `base_q_idx` for the hidden `ALTREF_FRAME` — negative, since | ||
| 320 | + /// every leaf of the group predicts off it. | ||
| 321 | + pub arf_q_offset: i16, | ||
| 322 | + /// Added to `base_q_idx` for each shown leaf — positive, since nothing | ||
| 323 | + /// predicts off a leaf but the next leaf. | ||
| 324 | + pub leaf_q_offset: i16, | ||
| 325 | +} | ||
| 326 | + | ||
| 327 | +impl Default for Pyramid { | ||
| 328 | + /// The offsets `encode::tests::pyramid_q_offset_sweep` measured (see the | ||
| 329 | + /// sweep's own report) at the mini-GOP size that won it. | ||
| 330 | + fn default() -> Self { | ||
| 331 | + Self { | ||
| 332 | + mini_gop: 4, | ||
| 333 | + arf_q_offset: -16, | ||
| 334 | + leaf_q_offset: 8, | ||
| 335 | + } | ||
| 336 | + } | ||
| 337 | +} | ||
| 338 | + | ||
| 339 | +/// Which level of the pyramid a coded frame sits at, reported on every | ||
| 340 | +/// [`Packet`] so a caller (and the BD gate's histogram) can tell them apart | ||
| 341 | +/// without parsing the frame headers back out. | ||
| 342 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] | ||
| 343 | +pub enum Level { | ||
| 344 | + /// A key frame. | ||
| 345 | + Key, | ||
| 346 | + /// A hidden `ALTREF_FRAME`, coded ahead of its display position. | ||
| 347 | + Arf, | ||
| 348 | + /// A shown leaf. | ||
| 349 | + Leaf, | ||
| 350 | + /// A `show_existing_frame` header re-outputting a hidden frame: no coded | ||
| 351 | + /// pixels at all, four bits of header. | ||
| 352 | + ShowExisting, | ||
| 205 | } | 353 | } |
| 206 | 354 | ||
| 355 | +/// The DPB slot the group anchors alternate between (see | ||
| 356 | +/// [`Av1Encoder::encode_frames`]): the hidden frame of group `g` refreshes | ||
| 357 | +/// `ANCHOR_SLOTS[(g + 1) % 2]`, which is the slot the leaves of group `g` | ||
| 358 | +/// name as `ALTREF_FRAME` and which group `g + 1` reads as its own anchor. | ||
| 359 | +/// Two slots alternate because a group's leaves must still be able to read | ||
| 360 | +/// the previous anchor while the new one is already written. | ||
| 361 | +const ANCHOR_SLOTS: [u8; 2] = [3, 4]; | ||
| 362 | + | ||
| 363 | +/// The slot the leaf chain refreshes and reads as `LAST_FRAME`. | ||
| 364 | +const LEAF_SLOT: u8 = 0; | ||
| 365 | + | ||
| 207 | /// The AV1 software encoder: [`EncoderConfig`] in, one [`Packet`] out per | 366 | /// The AV1 software encoder: [`EncoderConfig`] in, one [`Packet`] out per |
| 208 | -/// [`Av1Encoder::encode`] call. | 367 | +/// [`Av1Encoder::encode`] call — or, with a [`Pyramid`] configured, a |
| 368 | +/// coding-order burst of them per [`Av1Encoder::encode_frames`] call plus a | ||
| 369 | +/// [`Av1Encoder::flush`] at the end of the stream. | ||
| 209 | #[derive(Debug)] | 370 | #[derive(Debug)] |
| 210 | pub struct Av1Encoder { | 371 | pub struct Av1Encoder { |
| 211 | config: EncoderConfig, | 372 | config: EncoderConfig, |
| @@ -237,6 +398,31 @@ pub struct Av1Encoder { | |||
| 237 | /// The frame two back: `ALTREF_FRAME`, in the slot the next frame is | 398 | /// The frame two back: `ALTREF_FRAME`, in the slot the next frame is |
| 238 | /// about to refresh (`encode_inter_frame`'s 0/2 alternation). | 399 | /// about to refresh (`encode_inter_frame`'s 0/2 alternation). |
| 239 | prev2: Option<Picture>, | 400 | prev2: Option<Picture>, |
| 401 | + /// `Some` puts the encoder in pyramid mode: [`Av1Encoder::encode`] then | ||
| 402 | + /// refuses (a picture no longer maps to one packet) and the state below | ||
| 403 | + /// drives coding order. | ||
| 404 | + pyramid: Option<Pyramid>, | ||
| 405 | + /// The eight DPB slots, modelled exactly as the decoder does (spec 7.20): | ||
| 406 | + /// what picture each holds, the order hint it was coded at, and the CDF | ||
| 407 | + /// tables it stored. Only pyramid mode reads these; the flat path keeps | ||
| 408 | + /// `reference`/`golden`/`prev2` so its bytes are unchanged. | ||
| 409 | + dpb: [Option<DpbSlot>; 8], | ||
| 410 | + /// Pictures held back waiting for their mini-GOP's hidden frame. | ||
| 411 | + pending: Vec<(u64, Picture)>, | ||
| 412 | + /// Which of [`ANCHOR_SLOTS`] the group about to be coded reads as its | ||
| 413 | + /// anchor. | ||
| 414 | + anchor: usize, | ||
| 415 | + /// Coding-order position of the next packet — a packet's `dts`. | ||
| 416 | + next_dts: u64, | ||
| 417 | +} | ||
| 418 | + | ||
| 419 | +/// One decoded-picture-buffer slot: what a `refresh_frame_flags` bit stores | ||
| 420 | +/// and what a `ref_frame_idx` entry reads back. | ||
| 421 | +#[derive(Debug, Clone)] | ||
| 422 | +struct DpbSlot { | ||
| 423 | + picture: Picture, | ||
| 424 | + order_hint: u32, | ||
| 425 | + cdfs: crate::encode::CdfSnapshot, | ||
| 240 | } | 426 | } |
| 241 | 427 | ||
| 242 | /// The encoder stays `Send` now that it owns a `FrameCtx` (whose cells are | 428 | /// The encoder stays `Send` now that it owns a `FrameCtx` (whose cells are |
| @@ -271,9 +457,37 @@ impl Av1Encoder { | |||
| 271 | next_index: 0, | 457 | next_index: 0, |
| 272 | rate_loop: None, | 458 | rate_loop: None, |
| 273 | fctx: crate::decode::FrameCtx::new(), | 459 | fctx: crate::decode::FrameCtx::new(), |
| 460 | + pyramid: None, | ||
| 461 | + dpb: [const { None }; 8], | ||
| 462 | + pending: Vec::new(), | ||
| 463 | + anchor: 0, | ||
| 464 | + next_dts: 0, | ||
| 274 | }) | 465 | }) |
| 275 | } | 466 | } |
| 276 | 467 | ||
| 468 | + /// [`Av1Encoder::new`] in pyramid mode: pictures are coded out of display | ||
| 469 | + /// order, so a call to [`Av1Encoder::encode_frames`] returns zero, one or | ||
| 470 | + /// several packets and [`Av1Encoder::flush`] drains whatever is still | ||
| 471 | + /// held at the end of the stream. [`Av1Encoder::encode`]'s one-in-one-out | ||
| 472 | + /// contract cannot hold here and it returns an error instead; a caller | ||
| 473 | + /// that wants the old shape simply does not call this constructor. | ||
| 474 | + /// | ||
| 475 | + /// # Errors | ||
| 476 | + /// As [`Av1Encoder::new`], plus a `mini_gop` below 2 (no leaf would be | ||
| 477 | + /// left between the anchor and the hidden frame) or above `config.gop` | ||
| 478 | + /// (the group would straddle a key frame). | ||
| 479 | + pub fn with_pyramid(config: EncoderConfig, pyramid: Pyramid) -> Result<Self> { | ||
| 480 | + if pyramid.mini_gop < 2 { | ||
| 481 | + return Err(Error::unsupported( | ||
| 482 | + "AV1 encode", | ||
| 483 | + "a pyramid mini-GOP is at least 2 pictures", | ||
| 484 | + )); | ||
| 485 | + } | ||
| 486 | + let mut encoder = Self::new(config)?; | ||
| 487 | + encoder.pyramid = Some(pyramid); | ||
| 488 | + Ok(encoder) | ||
| 489 | + } | ||
| 490 | + | ||
| 277 | /// [`Av1Encoder::new`], but `rate` picks `base_q_idx` (or steers it, | 491 | /// [`Av1Encoder::new`], but `rate` picks `base_q_idx` (or steers it, |
| 278 | /// frame by frame, for [`RateTarget::BytesPerFrame`]) instead of | 492 | /// frame by frame, for [`RateTarget::BytesPerFrame`]) instead of |
| 279 | /// `config.base_q_idx` being used as-is. | 493 | /// `config.base_q_idx` being used as-is. |
| @@ -281,24 +495,31 @@ impl Av1Encoder { | |||
| 281 | /// # Errors | 495 | /// # Errors |
| 282 | /// Same as [`Av1Encoder::new`]. | 496 | /// Same as [`Av1Encoder::new`]. |
| 283 | pub fn with_rate_target(mut config: EncoderConfig, rate: RateTarget) -> Result<Self> { | 497 | pub fn with_rate_target(mut config: EncoderConfig, rate: RateTarget) -> Result<Self> { |
| 284 | - let rate_loop = match rate { | 498 | + 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)?; | 499 | let mut encoder = Self::new(config)?; |
| 298 | encoder.rate_loop = rate_loop; | 500 | encoder.rate_loop = rate_loop; |
| 299 | Ok(encoder) | 501 | Ok(encoder) |
| 300 | } | 502 | } |
| 301 | 503 | ||
| 504 | + /// [`Av1Encoder::with_pyramid`] and [`Av1Encoder::with_rate_target`] at | ||
| 505 | + /// once: the rate loop then keeps a separate quantizer per pyramid level, | ||
| 506 | + /// predicting each frame's size from the previous frame of its OWN level | ||
| 507 | + /// (a leaf and a hidden `ALTREF` differ by several times in size, so one | ||
| 508 | + /// shared predictor would swing the quantizer every frame). | ||
| 509 | + /// | ||
| 510 | + /// # Errors | ||
| 511 | + /// As both. | ||
| 512 | + pub fn with_pyramid_and_rate_target( | ||
| 513 | + mut config: EncoderConfig, | ||
| 514 | + pyramid: Pyramid, | ||
| 515 | + rate: RateTarget, | ||
| 516 | + ) -> Result<Self> { | ||
| 517 | + let rate_loop = rate.into_loop(&mut config, Some(pyramid.mini_gop)); | ||
| 518 | + let mut encoder = Self::with_pyramid(config, pyramid)?; | ||
| 519 | + encoder.rate_loop = rate_loop; | ||
| 520 | + Ok(encoder) | ||
| 521 | + } | ||
| 522 | + | ||
| 302 | /// The coded (padded-to-64) frame size every picture in this stream is | 523 | /// The coded (padded-to-64) frame size every picture in this stream is |
| 303 | /// coded at — what a decoder allocates and what `ffprobe` reports. | 524 | /// coded at — what a decoder allocates and what `ffprobe` reports. |
| 304 | #[must_use] | 525 | #[must_use] |
| @@ -322,10 +543,32 @@ impl Av1Encoder { | |||
| 322 | /// | 543 | /// |
| 323 | /// # Errors | 544 | /// # Errors |
| 324 | /// Returns an error when `picture`'s size does not match | 545 | /// Returns an error when `picture`'s size does not match |
| 325 | - /// [`EncoderConfig::width`]/[`EncoderConfig::height`], or under the same | 546 | + /// [`EncoderConfig::width`]/[`EncoderConfig::height`], when the encoder |
| 326 | - /// conditions [`crate::encode::encode_key_frame`]/ | 547 | + /// was built by [`Av1Encoder::with_pyramid`] (which reorders pictures, so |
| 327 | - /// [`crate::encode::encode_sequence`] do. | 548 | + /// one call cannot return one packet), or under the same conditions |
| 549 | + /// [`crate::encode::encode_key_frame`]/[`crate::encode::encode_sequence`] | ||
| 550 | + /// do. | ||
| 328 | pub fn encode(&mut self, picture: &Picture) -> Result<Packet> { | 551 | pub fn encode(&mut self, picture: &Picture) -> Result<Packet> { |
| 552 | + if self.pyramid.is_some() { | ||
| 553 | + return Err(Error::unsupported( | ||
| 554 | + "AV1 encode", | ||
| 555 | + "a pyramid stream reorders pictures -- use encode_frames()/flush()", | ||
| 556 | + )); | ||
| 557 | + } | ||
| 558 | + let mut packets = self.encode_frames(picture)?; | ||
| 559 | + Ok(packets.pop().expect("the flat path emits exactly one packet")) | ||
| 560 | + } | ||
| 561 | + | ||
| 562 | + /// Encodes one picture and returns every packet it completed, in coding | ||
| 563 | + /// order. Without a [`Pyramid`] that is always exactly one packet and | ||
| 564 | + /// this is [`Av1Encoder::encode`] with a `Vec` around it; with one it is | ||
| 565 | + /// empty for most pictures and a whole mini-GOP's worth (the hidden | ||
| 566 | + /// frame, its leaves and the `show_existing_frame` that re-outputs it) | ||
| 567 | + /// for the picture that closes a group. | ||
| 568 | + /// | ||
| 569 | + /// # Errors | ||
| 570 | + /// As [`Av1Encoder::encode`], minus the pyramid refusal. | ||
| 571 | + pub fn encode_frames(&mut self, picture: &Picture) -> Result<Vec<Packet>> { | ||
| 329 | if (picture.width, picture.height) != (self.config.width, self.config.height) { | 572 | if (picture.width, picture.height) != (self.config.width, self.config.height) { |
| 330 | return Err(Error::unsupported( | 573 | return Err(Error::unsupported( |
| 331 | "AV1 encode", | 574 | "AV1 encode", |
| @@ -335,14 +578,48 @@ impl Av1Encoder { | |||
| 335 | ), | 578 | ), |
| 336 | )); | 579 | )); |
| 337 | } | 580 | } |
| 581 | + let Some(pyramid) = self.pyramid else { | ||
| 582 | + return Ok(vec![self.encode_flat(picture)?]); | ||
| 583 | + }; | ||
| 584 | + let order = self.next_index; | ||
| 585 | + self.next_index += 1; | ||
| 586 | + if order.is_multiple_of(self.config.gop as u64) { | ||
| 587 | + // A key frame closes whatever group is open (there is nothing for | ||
| 588 | + // its leaves to point forward at across the boundary) and then | ||
| 589 | + // restarts the pyramid from the key itself. | ||
| 590 | + let mut packets = self.drain_pending()?; | ||
| 591 | + packets.push(self.encode_key(order, picture)?); | ||
| 592 | + return Ok(packets); | ||
| 593 | + } | ||
| 594 | + self.pending.push((order, picture.clone())); | ||
| 595 | + // The group closes on its own size, or early when the next picture | ||
| 596 | + // would be a key frame. | ||
| 597 | + let next_is_key = (order + 1).is_multiple_of(self.config.gop as u64); | ||
| 598 | + if self.pending.len() >= pyramid.mini_gop || next_is_key { | ||
| 599 | + return self.drain_pending(); | ||
| 600 | + } | ||
| 601 | + Ok(Vec::new()) | ||
| 602 | + } | ||
| 603 | + | ||
| 604 | + /// Codes and returns every picture still held back — the tail of a stream | ||
| 605 | + /// whose last mini-GOP never filled up. Empty (and cheap) for a stream | ||
| 606 | + /// with no [`Pyramid`], which never holds a picture at all. | ||
| 607 | + /// | ||
| 608 | + /// # Errors | ||
| 609 | + /// As [`Av1Encoder::encode_frames`]. | ||
| 610 | + pub fn flush(&mut self) -> Result<Vec<Packet>> { | ||
| 611 | + self.drain_pending() | ||
| 612 | + } | ||
| 613 | + | ||
| 614 | + /// The pre-pyramid path, byte for byte: one picture in, one packet out. | ||
| 615 | + fn encode_flat(&mut self, picture: &Picture) -> Result<Packet> { | ||
| 338 | let render = (self.config.width, self.config.height); | 616 | let render = (self.config.width, self.config.height); |
| 339 | let padded = picture.padded_to(SUPERBLOCK); | 617 | let padded = picture.padded_to(SUPERBLOCK); |
| 340 | - let is_key = self.next_index % self.config.gop as u64 == 0; | 618 | + let is_key = self.next_index.is_multiple_of(self.config.gop as u64); |
| 341 | let order = self.next_index; | 619 | let order = self.next_index; |
| 342 | - let base_q_idx = self | 620 | + let base_q_idx = self.rate_loop.as_ref().map_or(self.config.base_q_idx, |r| { |
| 343 | - .rate_loop | 621 | + r.q_idx(if is_key { Level::Key } else { Level::Leaf }) |
| 344 | - .as_ref() | 622 | + }); |
| 345 | - .map_or(self.config.base_q_idx, RateLoop::q_idx); | ||
| 346 | 623 | ||
| 347 | let encoded: Encoded = if is_key { | 624 | let encoded: Encoded = if is_key { |
| 348 | encode_key_frame_inner( | 625 | encode_key_frame_inner( |
| @@ -373,6 +650,7 @@ impl Av1Encoder { | |||
| 373 | self.golden.as_ref(), | 650 | self.golden.as_ref(), |
| 374 | self.prev2.as_ref(), | 651 | self.prev2.as_ref(), |
| 375 | &self.fctx, | 652 | &self.fctx, |
| 653 | + None, | ||
| 376 | )? | 654 | )? |
| 377 | }; | 655 | }; |
| 378 | 656 | ||
| @@ -386,14 +664,213 @@ impl Av1Encoder { | |||
| 386 | self.reference = Some(encoded.reconstruction.clone()); | 664 | self.reference = Some(encoded.reconstruction.clone()); |
| 387 | self.next_index += 1; | 665 | self.next_index += 1; |
| 388 | let cropped = crop_encoded(&encoded, render.0, render.1); | 666 | let cropped = crop_encoded(&encoded, render.0, render.1); |
| 667 | + let level = if is_key { Level::Key } else { Level::Leaf }; | ||
| 389 | if let Some(rate_loop) = self.rate_loop.as_mut() { | 668 | if let Some(rate_loop) = self.rate_loop.as_mut() { |
| 390 | - rate_loop.update(cropped.stream.len()); | 669 | + rate_loop.update(level, cropped.stream.len()); |
| 391 | } | 670 | } |
| 392 | - Ok(Packet { | 671 | + Ok(self.packet(cropped.stream, is_key, order, level)) |
| 393 | - data: cropped.stream, | 672 | + } |
| 394 | - key: is_key, | 673 | + |
| 674 | + /// Stamps a packet with its display and coding positions and advances the | ||
| 675 | + /// coding-order clock. | ||
| 676 | + fn packet(&mut self, data: Vec<u8>, key: bool, order: u64, level: Level) -> Packet { | ||
| 677 | + let dts = self.next_dts; | ||
| 678 | + self.next_dts += 1; | ||
| 679 | + Packet { | ||
| 680 | + data, | ||
| 681 | + key, | ||
| 395 | order, | 682 | order, |
| 396 | - }) | 683 | + dts, |
| 684 | + level, | ||
| 685 | + } | ||
| 686 | + } | ||
| 687 | + | ||
| 688 | + /// Stores a coded frame into every DPB slot its `refresh_frame_flags` | ||
| 689 | + /// names (spec 7.20). | ||
| 690 | + fn refresh(&mut self, slots: &[u8], encoded: &Encoded, order_hint: u32) { | ||
| 691 | + let slot = DpbSlot { | ||
| 692 | + picture: encoded.reconstruction.clone(), | ||
| 693 | + order_hint, | ||
| 694 | + cdfs: encoded.next_cdfs.clone(), | ||
| 695 | + }; | ||
| 696 | + for &s in slots { | ||
| 697 | + self.dpb[s as usize] = Some(slot.clone()); | ||
| 698 | + } | ||
| 699 | + } | ||
| 700 | + | ||
| 701 | + /// Codes a key frame in pyramid mode: it refreshes all eight slots, so it | ||
| 702 | + /// becomes the anchor, the `GOLDEN_FRAME` and the CDF source for the | ||
| 703 | + /// whole GOP at once. | ||
| 704 | + fn encode_key(&mut self, order: u64, picture: &Picture) -> Result<Packet> { | ||
| 705 | + let render = (self.config.width, self.config.height); | ||
| 706 | + let base_q_idx = self | ||
| 707 | + .rate_loop | ||
| 708 | + .as_ref() | ||
| 709 | + .map_or(self.config.base_q_idx, |r| r.q_idx(Level::Key)); | ||
| 710 | + let encoded = encode_key_frame_inner( | ||
| 711 | + &picture.padded_to(SUPERBLOCK), | ||
| 712 | + base_q_idx, | ||
| 713 | + DEADZONE, | ||
| 714 | + &KEY_FRAME_MODES, | ||
| 715 | + split_blocks(), | ||
| 716 | + render, | ||
| 717 | + self.color_config, | ||
| 718 | + &self.fctx, | ||
| 719 | + )?; | ||
| 720 | + self.refresh(&[0, 1, 2, 3, 4, 5, 6, 7], &encoded, 0); | ||
| 721 | + self.anchor = 0; | ||
| 722 | + let cropped = crop_encoded(&encoded, render.0, render.1); | ||
| 723 | + if let Some(rate_loop) = self.rate_loop.as_mut() { | ||
| 724 | + rate_loop.update(Level::Key, cropped.stream.len()); | ||
| 725 | + } | ||
| 726 | + Ok(self.packet(cropped.stream, true, order, Level::Key)) | ||
| 727 | + } | ||
| 728 | + | ||
| 729 | + /// Codes one inter frame at `order` from the DPB, in coding order. | ||
| 730 | + #[allow(clippy::too_many_arguments)] | ||
| 731 | + fn encode_pyramid_inter( | ||
| 732 | + &mut self, | ||
| 733 | + order: u64, | ||
| 734 | + picture: &Picture, | ||
| 735 | + last_slot: u8, | ||
| 736 | + self_slot: u8, | ||
| 737 | + altref_slot: u8, | ||
| 738 | + show_frame: bool, | ||
| 739 | + level: Level, | ||
| 740 | + ) -> Result<Packet> { | ||
| 741 | + let render = (self.config.width, self.config.height); | ||
| 742 | + let order_hint = (order & 0x7f) as u32; | ||
| 743 | + let pyramid = self.pyramid.expect("pyramid mode"); | ||
| 744 | + let offset = match level { | ||
| 745 | + Level::Arf => pyramid.arf_q_offset, | ||
| 746 | + _ => pyramid.leaf_q_offset, | ||
| 747 | + }; | ||
| 748 | + let base = self | ||
| 749 | + .rate_loop | ||
| 750 | + .as_ref() | ||
| 751 | + .map_or(i16::from(self.config.base_q_idx), |r| { | ||
| 752 | + i16::from(r.q_idx(level)) | ||
| 753 | + }); | ||
| 754 | + let base_q_idx = (base + offset).clamp(1, 255) as u8; | ||
| 755 | + // spec 5.9.2's `ref_frame_sign_bias`, derived from what the slots | ||
| 756 | + // this frame names actually hold: a reference whose order hint is | ||
| 757 | + // AHEAD of this frame's is backward-biased, and the MV stack scans | ||
| 758 | + // (writer and decoder alike) flip borrowed candidates across the | ||
| 759 | + // boundary. Only `ALTREF_FRAME` can be ahead here — the leaves of a | ||
| 760 | + // mini-GOP name the group's hidden frame there. | ||
| 761 | + let mut sign_bias = crate::mvstack::NO_SIGN_BIAS; | ||
| 762 | + let ahead = |slot: u8, dpb: &[Option<DpbSlot>; 8]| { | ||
| 763 | + dpb[slot as usize] | ||
| 764 | + .as_ref() | ||
| 765 | + .is_some_and(|s| s.order_hint > order_hint) | ||
| 766 | + }; | ||
| 767 | + for (i, slot) in [ | ||
| 768 | + last_slot, last_slot, last_slot, GOLDEN_SLOT, last_slot, last_slot, altref_slot, | ||
| 769 | + ] | ||
| 770 | + .into_iter() | ||
| 771 | + .enumerate() | ||
| 772 | + { | ||
| 773 | + sign_bias[i] = ahead(slot, &self.dpb); | ||
| 774 | + } | ||
| 775 | + let reference = self.dpb[last_slot as usize] | ||
| 776 | + .as_ref() | ||
| 777 | + .map(|s| s.picture.clone()) | ||
| 778 | + .ok_or_else(|| { | ||
| 779 | + Error::unsupported("AV1 encode", "an inter frame needs a previous reconstruction") | ||
| 780 | + })?; | ||
| 781 | + let golden = self.dpb[GOLDEN_SLOT as usize].as_ref().map(|s| s.picture.clone()); | ||
| 782 | + let altref = (altref_slot != GOLDEN_SLOT) | ||
| 783 | + .then(|| self.dpb[altref_slot as usize].as_ref().map(|s| s.picture.clone())) | ||
| 784 | + .flatten(); | ||
| 785 | + let start_cdfs = self.dpb[last_slot as usize].as_ref().map(|s| s.cdfs.0.clone()); | ||
| 786 | + let encoded = encode_inter_frame( | ||
| 787 | + &picture.padded_to(SUPERBLOCK), | ||
| 788 | + &reference, | ||
| 789 | + base_q_idx, | ||
| 790 | + DEADZONE, | ||
| 791 | + order_hint, | ||
| 792 | + render, | ||
| 793 | + start_cdfs.as_ref(), | ||
| 794 | + golden.as_ref(), | ||
| 795 | + altref.as_ref(), | ||
| 796 | + &self.fctx, | ||
| 797 | + Some(crate::encode::PyramidFrame { | ||
| 798 | + last_slot, | ||
| 799 | + self_slot, | ||
| 800 | + altref_slot, | ||
| 801 | + show_frame, | ||
| 802 | + sign_bias, | ||
| 803 | + }), | ||
| 804 | + )?; | ||
| 805 | + self.refresh(&[self_slot], &encoded, order_hint); | ||
| 806 | + let cropped = crop_encoded(&encoded, render.0, render.1); | ||
| 807 | + if let Some(rate_loop) = self.rate_loop.as_mut() { | ||
| 808 | + rate_loop.update(level, cropped.stream.len()); | ||
| 809 | + } | ||
| 810 | + Ok(self.packet(cropped.stream, false, order, level)) | ||
| 811 | + } | ||
| 812 | + | ||
| 813 | + /// Codes the open mini-GOP: its hidden frame first, then its leaves, then | ||
| 814 | + /// the `show_existing_frame` header that puts the hidden frame back in | ||
| 815 | + /// display order. | ||
| 816 | + fn drain_pending(&mut self) -> Result<Vec<Packet>> { | ||
| 817 | + if self.pending.is_empty() { | ||
| 818 | + return Ok(Vec::new()); | ||
| 819 | + } | ||
| 820 | + let group: Vec<(u64, Picture)> = std::mem::take(&mut self.pending); | ||
| 821 | + let mut packets = Vec::with_capacity(group.len() + 1); | ||
| 822 | + let anchor_slot = ANCHOR_SLOTS[self.anchor]; | ||
| 823 | + let next_anchor_slot = ANCHOR_SLOTS[1 - self.anchor]; | ||
| 824 | + let (arf_order, arf_picture) = group.last().cloned().expect("non-empty"); | ||
| 825 | + if group.len() == 1 { | ||
| 826 | + // Nothing to predict backward, so no hidden frame: one shown leaf | ||
| 827 | + // that also becomes the next group's anchor. | ||
| 828 | + packets.push(self.encode_pyramid_inter( | ||
| 829 | + arf_order, | ||
| 830 | + &arf_picture, | ||
| 831 | + anchor_slot, | ||
| 832 | + next_anchor_slot, | ||
| 833 | + GOLDEN_SLOT, | ||
| 834 | + true, | ||
| 835 | + Level::Leaf, | ||
| 836 | + )?); | ||
| 837 | + self.anchor = 1 - self.anchor; | ||
| 838 | + return Ok(packets); | ||
| 839 | + } | ||
| 840 | + packets.push(self.encode_pyramid_inter( | ||
| 841 | + arf_order, | ||
| 842 | + &arf_picture, | ||
| 843 | + anchor_slot, | ||
| 844 | + next_anchor_slot, | ||
| 845 | + GOLDEN_SLOT, | ||
| 846 | + false, | ||
| 847 | + Level::Arf, | ||
| 848 | + )?); | ||
| 849 | + for (i, (order, picture)) in group[..group.len() - 1].iter().enumerate() { | ||
| 850 | + let last_slot = if i == 0 { anchor_slot } else { LEAF_SLOT }; | ||
| 851 | + packets.push(self.encode_pyramid_inter( | ||
| 852 | + *order, | ||
| 853 | + picture, | ||
| 854 | + last_slot, | ||
| 855 | + LEAF_SLOT, | ||
| 856 | + next_anchor_slot, | ||
| 857 | + true, | ||
| 858 | + Level::Leaf, | ||
| 859 | + )?); | ||
| 860 | + } | ||
| 861 | + let (seq, _) = crate::encode::key_frame_headers( | ||
| 862 | + self.config.width, | ||
| 863 | + self.config.height, | ||
| 864 | + self.config.base_q_idx, | ||
| 865 | + )?; | ||
| 866 | + let mut data = crate::obu::temporal_delimiter(); | ||
| 867 | + data.extend_from_slice(&crate::frame::show_existing_frame_obu( | ||
| 868 | + &seq, | ||
| 869 | + next_anchor_slot, | ||
| 870 | + )?); | ||
| 871 | + packets.push(self.packet(data, false, arf_order, Level::ShowExisting)); | ||
| 872 | + self.anchor = 1 - self.anchor; | ||
| 873 | + Ok(packets) | ||
| 397 | } | 874 | } |
| 398 | } | 875 | } |
| 399 | 876 | ||
| @@ -799,10 +1276,10 @@ mod tests { | |||
| 799 | }; | 1276 | }; |
| 800 | let mut enc = | 1277 | let mut enc = |
| 801 | Av1Encoder::with_rate_target(config, RateTarget::BytesPerFrame(4_000)).unwrap(); | 1278 | Av1Encoder::with_rate_target(config, RateTarget::BytesPerFrame(4_000)).unwrap(); |
| 802 | - let mut prev_q = enc.rate_loop.as_ref().unwrap().q_idx(); | 1279 | + let mut prev_q = enc.rate_loop.as_ref().unwrap().q_idx(Level::Leaf); |
| 803 | for picture in &pictures { | 1280 | for picture in &pictures { |
| 804 | enc.encode(picture).unwrap(); | 1281 | enc.encode(picture).unwrap(); |
| 805 | - let q = enc.rate_loop.as_ref().unwrap().q_idx(); | 1282 | + let q = enc.rate_loop.as_ref().unwrap().q_idx(Level::Leaf); |
| 806 | let step = (i32::from(q) - i32::from(prev_q)).abs(); | 1283 | let step = (i32::from(q) - i32::from(prev_q)).abs(); |
| 807 | assert!( | 1284 | assert!( |
| 808 | f64::from(step) <= RateLoop::STEP_CLAMP + 1.0, // +1 for u8 rounding | 1285 | f64::from(step) <= RateLoop::STEP_CLAMP + 1.0, // +1 for u8 rounding |
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: no | 362 | /// `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 inter | 363 | /// decoder model, no frame ids, no still-picture shortcut, and (for an inter |
| 329 | /// frame) short reference signalling, non-identity global motion, compound | 364 | /// 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_frame | 368 | + return Err(Error::unsupported( |
| 334 | - || h.show_existing_frame | 369 | + "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_frame | 402 | w.write_bit(false); // show_existing_frame |
| 362 | w.write_bits(if is_key { 0 } else { 1 }, 2); // frame_type | 403 | w.write_bits(if is_key { 0 } else { 1 }, 2); // frame_type |
| 363 | - w.write_bit(true); // show_frame | 404 | + 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 group | 598 | /// 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 span | 291 | /// Narrows [`Self::get`]'s own read window to one tile's mi-unit span |
| 276 | /// (`row1`/`col1` exclusive) -- called once per tile, before that | 292 | /// (`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 | ||
| @@ -3184,6 +3201,7 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs( | |||
| 3184 | mi_rows as usize, | 3201 | mi_rows as usize, |
| 3185 | ); | 3202 | ); |
| 3186 | let mut grid = MiGrid::new(mi_cols as usize, mi_rows as usize); | 3203 | let mut grid = MiGrid::new(mi_cols as usize, mi_rows as usize); |
| 3204 | + grid.set_sign_bias(SIGN_BIAS.with(std::cell::Cell::get)); | ||
| 3187 | let mut cdfs = cdfs; | 3205 | let mut cdfs = cdfs; |
| 3188 | let mut enc = SymbolEncoder::new(); | 3206 | let mut enc = SymbolEncoder::new(); |
| 3189 | // An `is_inter` block's 32x32 luma transform reads a different | 3207 | // An `is_inter` block's 32x32 luma transform reads a different |