edith_codecs
Clone
https://git.tahinli.com/Tahinli/edith_codecs.git
0 watching·0 forks·Rust·370.3 MiB·dfeffbc·Tahinli·2 months ago·3180 commits
| 1 | //! The streaming encoder facade — I11 of `lanes/av1-inter-plan.md`, the |
| 2 | //! surface `edith_replica`'s engine calls in place of rav1e. |
| 3 | //! |
| 4 | //! ONE FRAME OF LATENCY, everywhere: a picture handed to |
| 5 | //! [`Av1Encoder::encode`]/[`Av1Encoder::encode_frames`] is held until the |
| 6 | //! NEXT picture arrives, because an inter frame's per-superblock temporal |
| 7 | //! lambda map reads the next source picture as its lookahead (lane-av1tpl) |
| 8 | //! — exactly as [`crate::encode::encode_sequence`] does, so the facade and |
| 9 | //! the sequence path now code the same bytes for the same pictures. A |
| 10 | //! stream therefore ENDS with [`Av1Encoder::flush`], which codes whatever is |
| 11 | //! still held. [`Av1Encoder::with_pyramid`] holds a whole mini-GOP for the |
| 12 | //! same kind of reason (it reorders pictures) and is driven through |
| 13 | //! [`Av1Encoder::encode_frames`]/[`Av1Encoder::flush`] too. Internally it |
| 14 | //! is [`crate::encode::encode_key_frame_inner`] and |
| 15 | //! [`crate::encode::encode_inter_frame`] driven by a small state machine — |
| 16 | //! a key frame every `gop` pictures, an inter frame predicting from the |
| 17 | //! previous picture's own reconstruction otherwise — which is the same core |
| 18 | //! [`crate::encode::encode_sequence`] uses for its one-key-frame-then-all-inter |
| 19 | //! case; both now share it rather than each padding/cropping/refreshing the |
| 20 | //! reference on their own. |
| 21 | |
| 22 | use ec_av1_syntax::sequence::{ChromaSamplePosition, ColorConfig}; |
| 23 | use ec_core::{Error, Result}; |
| 24 | |
| 25 | use crate::encode::{ |
| 26 | Encoded, GOLDEN_SLOT, Picture, SUPERBLOCK, crop_encoded, encode_inter_frame, |
| 27 | encode_key_frame_inner, split_blocks, |
| 28 | }; |
| 29 | use crate::intra::KEY_FRAME_MODES; |
| 30 | |
| 31 | /// A quantizer step round to nearest: half a step either way costs the same |
| 32 | /// rate, so this is the deadzone every facade-driven frame is coded with. |
| 33 | /// (`crate::encode`'s public entry points take a caller-chosen deadzone |
| 34 | /// instead; the facade has no field for it because nothing downstream of it |
| 35 | /// picks one.) |
| 36 | const DEADZONE: f64 = 0.5; |
| 37 | |
| 38 | /// The colour a played-back frame is transformed by, named at what a |
| 39 | /// container/player picks a colour space from (spec 5.5.2's CICP triple plus |
| 40 | /// range) rather than at the raw integers. `edith_replica`'s rav1e seat sets |
| 41 | /// limited-range BT.709 or BT.601 (`export.rs:3494-3507`); this crate's |
| 42 | /// pre-facade sequence header always wrote [`Colour::Unspecified`]. |
| 43 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] |
| 44 | pub enum Colour { |
| 45 | /// `color_primaries`/`transfer_characteristics`/`matrix_coefficients` = |
| 46 | /// 1 (BT.709, H.273), studio range: consumer HD video's own space, and |
| 47 | /// the default a player assumes when nothing is signalled at all. |
| 48 | #[default] |
| 49 | Bt709Limited, |
| 50 | /// The same three fields = 6 (BT.601, H.273), studio range: SD video's |
| 51 | /// space. |
| 52 | Bt601Limited, |
| 53 | /// Every field = 2 ("unspecified", H.273): what this crate wrote before |
| 54 | /// any of this was configurable. |
| 55 | Unspecified, |
| 56 | } |
| 57 | |
| 58 | impl Colour { |
| 59 | fn color_config(self) -> ColorConfig { |
| 60 | let (color_primaries, transfer_characteristics, matrix_coefficients) = match self { |
| 61 | Colour::Bt709Limited => (1, 1, 1), |
| 62 | Colour::Bt601Limited => (6, 6, 6), |
| 63 | Colour::Unspecified => (2, 2, 2), |
| 64 | }; |
| 65 | ColorConfig { |
| 66 | bit_depth: 8, |
| 67 | mono_chrome: false, |
| 68 | num_planes: 3, |
| 69 | color_primaries, |
| 70 | transfer_characteristics, |
| 71 | matrix_coefficients, |
| 72 | // Every variant here is studio (limited) swing; a full-range |
| 73 | // variant would need its own name, not a fourth field on this |
| 74 | // enum, since a played-back frame's range is a property of the |
| 75 | // pictures fed in, not just a label. |
| 76 | color_range: false, |
| 77 | subsampling_x: 1, |
| 78 | subsampling_y: 1, |
| 79 | chroma_sample_position: ChromaSamplePosition::Unknown, |
| 80 | separate_uv_delta_q: false, |
| 81 | } |
| 82 | } |
| 83 | } |
| 84 | |
| 85 | /// A quality/size targeting surface for callers who would rather not pick a |
| 86 | /// `base_q_idx` themselves, oracled at CRF's own shape (a single "quality" |
| 87 | /// dial that holds a stable perceptual level across content, `ffmpeg -crf`) |
| 88 | /// since a from-scratch scheme is not this lane's charter to invent. |
| 89 | /// [`Av1Encoder::with_rate_target`] is additive: [`EncoderConfig::base_q_idx`] |
| 90 | /// keeps working exactly as before for every existing caller, this is a |
| 91 | /// second, opt-in constructor. |
| 92 | #[derive(Debug, Clone, Copy, PartialEq)] |
| 93 | pub enum RateTarget { |
| 94 | /// Exactly `base_q_idx`, unchanged — the `EncoderConfig` field's own |
| 95 | /// value, for a caller that already has one. |
| 96 | QIndex(u8), |
| 97 | /// A CRF-like single dial, 0 (smallest/worst) to 100 (largest/best), |
| 98 | /// mapped to a fixed `base_q_idx` by the calibration in |
| 99 | /// `encode::tests::calibration_sweep_base_q_idx` (linear in `q_idx` |
| 100 | /// across the sweep's own 40..=240 span, since the measured bytes/PSNR |
| 101 | /// curve is close enough to log-linear there that a straight line is |
| 102 | /// the "simplest correct" fit this lane's charter asks for). No |
| 103 | /// per-frame feedback: one value, picked once at construction. |
| 104 | Quality(u8), |
| 105 | /// A closed loop that steers `base_q_idx` frame by frame to land each |
| 106 | /// coded frame near this many bytes, via [`RateLoop`] — see there for |
| 107 | /// the controller and its windup bound. |
| 108 | BytesPerFrame(u32), |
| 109 | /// A target BITRATE: the same closed loop, with the per-frame byte |
| 110 | /// target derived from `bits_per_second` and `frames_per_second` |
| 111 | /// (`bits_per_second / 8 / frames_per_second`), and — in pyramid mode — |
| 112 | /// split across the levels by their reference weight, since a hidden |
| 113 | /// `ALTREF` and a leaf differ by several times in size and one shared |
| 114 | /// predictor would swing the quantizer every frame. |
| 115 | Bitrate { |
| 116 | /// The stream's target bitrate. |
| 117 | bits_per_second: u32, |
| 118 | /// The frame rate the bitrate is spent at. |
| 119 | frames_per_second: f64, |
| 120 | }, |
| 121 | } |
| 122 | |
| 123 | impl RateTarget { |
| 124 | /// Applies this target to `config` and returns the closed loop it needs |
| 125 | /// (`None` for the two open-loop variants). `mini_gop` is `Some` in |
| 126 | /// pyramid mode, which is what makes the loop keep a quantizer per level. |
| 127 | fn into_loop(self, config: &mut EncoderConfig, pyramid: Option<Pyramid>) -> Option<RateLoop> { |
| 128 | let target_bytes = match self { |
| 129 | RateTarget::QIndex(q) => { |
| 130 | config.base_q_idx = q; |
| 131 | return None; |
| 132 | } |
| 133 | RateTarget::Quality(quality) => { |
| 134 | config.base_q_idx = quality_to_q_idx(quality); |
| 135 | return None; |
| 136 | } |
| 137 | RateTarget::BytesPerFrame(target_bytes) => f64::from(target_bytes), |
| 138 | RateTarget::Bitrate { |
| 139 | bits_per_second, |
| 140 | frames_per_second, |
| 141 | } => f64::from(bits_per_second) / 8.0 / frames_per_second.max(1.0), |
| 142 | }; |
| 143 | Some(RateLoop::new( |
| 144 | target_bytes, |
| 145 | f64::from(config.base_q_idx), |
| 146 | pyramid, |
| 147 | config.gop, |
| 148 | )) |
| 149 | } |
| 150 | } |
| 151 | |
| 152 | /// `quality`'s mapping to `base_q_idx`, linear across the calibration sweep's |
| 153 | /// span (`q_idx` 40 at `quality` 100 down to `q_idx` 240 at `quality` 0); |
| 154 | /// `quality` above 100 clamps to the best point measured, matching a CRF |
| 155 | /// dial's own saturating ends rather than extrapolating past calibrated |
| 156 | /// data. |
| 157 | fn quality_to_q_idx(quality: u8) -> u8 { |
| 158 | let quality = f64::from(quality.min(100)); |
| 159 | (240.0 - quality * 2.0).round() as u8 |
| 160 | } |
| 161 | |
| 162 | /// What one coded frame is worth, relative to a leaf, as a function of how |
| 163 | /// much FINER than the leaf it is coded (`leaf_q_offset - own offset`, in |
| 164 | /// `q_idx` steps): `exp(WEIGHT_LEVEL_GAIN * delta)`. |
| 165 | /// |
| 166 | /// This is the level model the byte budget is split by, and it is MEASURED, |
| 167 | /// not the old flat "a hidden frame is worth two leaves" guess: the long-GOP |
| 168 | /// census (`lanes/rc.report.md`, films A and B at three quantizers each, |
| 169 | /// `lanes/census-longgop-v2.md`'s q150 row among them) reads a level's |
| 170 | /// bytes/frame as very close to log-linear in its own q offset, at |
| 171 | /// d(ln bytes)/d(q_idx) = -0.0557 -- three and a half times the SLOPE of the |
| 172 | /// controller's own `RateLoop::GAIN` (0.0154), because a deeper level is not |
| 173 | /// just quantized finer, it also carries the group's residual for every |
| 174 | /// frame that predicts off it. |
| 175 | const WEIGHT_LEVEL_GAIN: f64 = 0.0557; |
| 176 | |
| 177 | /// The key frame's own correction on top of `WEIGHT_LEVEL_GAIN`: an intra |
| 178 | /// frame at the key's offset codes this much of what the level model alone |
| 179 | /// predicts (the census's key frames are consistently smaller than the pure |
| 180 | /// exponential, since the exponential is fitted on INTER levels whose size |
| 181 | /// keeps growing with reference depth). |
| 182 | const KEY_WEIGHT: f64 = 1.08; |
| 183 | |
| 184 | /// `EC_AV1_RL_CENSUS=1` — one stderr line per frame the rate loop steers. |
| 185 | fn census_on() -> bool { |
| 186 | std::env::var("EC_AV1_RL_CENSUS").is_ok_and(|v| v == "1") |
| 187 | } |
| 188 | |
| 189 | /// One level of a run, as the re-plan sees it: how much of the run's weight |
| 190 | /// it carries, how much of that is still to be coded, and -- once its |
| 191 | /// effective quantizer has hit the coder's 1..=255 bound -- the leaf- |
| 192 | /// equivalent bytes it actually spends there. |
| 193 | #[derive(Debug, Clone, Copy)] |
| 194 | struct LevelPlan { |
| 195 | /// The controller slot this level shares ([`RateLoop::slot`]). |
| 196 | slot: usize, |
| 197 | /// The level's own `base_q_idx` offset: what tells two hidden levels |
| 198 | /// apart inside slot 1. |
| 199 | offset: i16, |
| 200 | weight: f64, |
| 201 | left: f64, |
| 202 | bound: bool, |
| 203 | rate: f64, |
| 204 | } |
| 205 | |
| 206 | impl LevelPlan { |
| 207 | fn new(slot: usize, offset: i16, weight: f64) -> Self { |
| 208 | Self { slot, offset, weight, left: weight, bound: false, rate: 0.0 } |
| 209 | } |
| 210 | } |
| 211 | |
| 212 | /// The closed-loop controller behind [`RateTarget::BytesPerFrame`] and |
| 213 | /// [`RateTarget::Bitrate`]: a proportional step on `base_q_idx`, sized from |
| 214 | /// the calibration sweep's own log-linear slope (bytes roughly halve every |
| 215 | /// ~45 `q_idx` steps there, i.e. `d(ln bytes)/d(q_idx) ≈ -0.0154`), clamped |
| 216 | /// per frame. Pure proportional — no accumulated error term — is the windup |
| 217 | /// bound itself ([[vorbis-rate-loop-windup]]'s class): the only state carried |
| 218 | /// between frames is `q`, already clamped to `0..=255`, so a quiet lead-in |
| 219 | /// cannot build a debt a later transient has to repay; each frame's step is |
| 220 | /// bounded by `STEP_CLAMP` regardless of history. |
| 221 | /// |
| 222 | /// In pyramid mode the state is kept PER LEVEL: each frame's size is |
| 223 | /// predicted from the previous frame of its own level, against that level's |
| 224 | /// own share of the budget, which is the whole "two-pass-free model" this |
| 225 | /// encoder carries. |
| 226 | #[derive(Debug, Clone, Copy)] |
| 227 | struct RateLoop { |
| 228 | /// Byte target per level, indexed by [`RateLoop::slot`]. |
| 229 | target: [f64; 3], |
| 230 | /// Quantizer per level, same index. |
| 231 | q: [f64; 3], |
| 232 | /// Whether the three slots are actually distinct (pyramid mode) or all |
| 233 | /// one shared controller (the flat path, unchanged from before levels |
| 234 | /// existed). |
| 235 | per_level: bool, |
| 236 | /// Whether each slot has already steered off a real coded frame. The |
| 237 | /// FIRST update of a slot is the seeding one and takes the model's whole |
| 238 | /// step ([`RateLoop::update`]); every later one is clamped. |
| 239 | seeded: [bool; 3], |
| 240 | /// The leaf's own q offset: the zero of the level weight |
| 241 | /// ([`WEIGHT_LEVEL_GAIN`]), so slot 1's target can be read in |
| 242 | /// LEAF-EQUIVALENT bytes and scaled per frame by that frame's offset. |
| 243 | leaf_q_offset: i16, |
| 244 | /// The key frame's own leaf-equivalent weight ([`KEY_WEIGHT`]). |
| 245 | key_weight: f64, |
| 246 | /// The leaf-equivalent weight of a whole run (key included), and the |
| 247 | /// run's whole byte budget (`gop` frame targets): what a run RE-PLANS |
| 248 | /// from, and what a key frame resets the re-plan to. |
| 249 | run_weight: f64, |
| 250 | run_bytes: f64, |
| 251 | /// What is left of both, ahead of the next frame. |
| 252 | left_weight: f64, |
| 253 | left_bytes: f64, |
| 254 | /// The run's shape, ONE ENTRY PER LEVEL: the key, each distinct hidden |
| 255 | /// offset, the leaves. A level whose effective quantizer has hit a bound |
| 256 | /// cannot follow the plan, so [`RateLoop::replan`] prices its remaining |
| 257 | /// weight at what it MEASURABLY spends and re-solves the run's budget |
| 258 | /// over the levels that can still move. Per LEVEL and not per slot: the |
| 259 | /// hidden slot mixes the top and mid ARFs, whose leaf-equivalent rates |
| 260 | /// differ by 4x at the floor (both code the same bytes at `q_idx` 1, at |
| 261 | /// weights that differ by that much), and projecting one onto the other's |
| 262 | /// remaining weight drove the whole plan negative. |
| 263 | plans: [Option<LevelPlan>; 5], |
| 264 | /// The plan's scale at construction — the WINDUP BOUND on the re-plan: |
| 265 | /// a level held at its bound hands its unspent bytes to the others, but |
| 266 | /// no level's target may exceed this many times its own opening share. |
| 267 | scale0: f64, |
| 268 | /// `EC_AV1_RL_CENSUS=1`: one line per coded frame on stderr. |
| 269 | census: bool, |
| 270 | coded: usize, |
| 271 | } |
| 272 | |
| 273 | impl RateLoop { |
| 274 | /// The steepest a single frame is allowed to move `base_q_idx`, in |
| 275 | /// either direction — chosen so one wildly over/under-sized frame |
| 276 | /// (a scene cut, a black lead-in) nudges the next frame's quantizer |
| 277 | /// rather than slamming it to an extreme. |
| 278 | const STEP_CLAMP: f64 = 12.0; |
| 279 | /// The calibration sweep's own slope (see the struct doc), inverted to |
| 280 | /// convert a bytes ratio into a `q_idx` step. |
| 281 | const GAIN: f64 = 1.0 / 0.0154; |
| 282 | /// The windup bound on [`RateLoop::replan`]: however much a bound level |
| 283 | /// fails to spend, no other level's target may grow past this multiple of |
| 284 | /// its opening share. Without it a run whose hidden levels are all at the |
| 285 | /// floor would keep piling the whole run's budget onto the leaves. |
| 286 | const REPLAN_CLAMP: f64 = 4.0; |
| 287 | /// The same bound the other way: a re-plan may not drive a level's target |
| 288 | /// below this multiple of its opening share. A target of zero would STOP |
| 289 | /// the loop outright ([`RateLoop::update`] returns on a non-positive |
| 290 | /// target), which is how the first cut of this fix froze every level of a |
| 291 | /// run at whatever quantizer it had reached. |
| 292 | const REPLAN_FLOOR: f64 = 0.25; |
| 293 | |
| 294 | fn new(target_bytes: f64, start_q: f64, pyramid: Option<Pyramid>, gop: usize) -> Self { |
| 295 | let Some(p) = pyramid else { |
| 296 | return Self { |
| 297 | target: [target_bytes; 3], |
| 298 | q: [start_q; 3], |
| 299 | per_level: false, |
| 300 | seeded: [false; 3], |
| 301 | leaf_q_offset: 0, |
| 302 | key_weight: 1.0, |
| 303 | run_weight: 0.0, |
| 304 | run_bytes: 0.0, |
| 305 | left_weight: 0.0, |
| 306 | left_bytes: 0.0, |
| 307 | plans: [None; 5], |
| 308 | scale0: target_bytes, |
| 309 | census: census_on(), |
| 310 | coded: 0, |
| 311 | }; |
| 312 | }; |
| 313 | // THE LEVEL MODEL. Every coded frame of the run is priced by its own |
| 314 | // q offset through `WEIGHT_LEVEL_GAIN`, in units of one leaf, and the |
| 315 | // run's `gop` frame targets are shared out in those units. The old |
| 316 | // model priced a group as "one hidden frame worth `ARF_WEIGHT` = 2 |
| 317 | // leaves plus `m - 1` leaves", which was wrong twice over and the two |
| 318 | // errors cancelled (lane-pyr6): the group has coded TWO hidden frames |
| 319 | // since the mid level landed (four with |
| 320 | // [`Pyramid::quarter_q_offset`]), and a hidden frame is worth far |
| 321 | // more than two leaves -- the census reads the top ARF at 24x a leaf |
| 322 | // and the mid at 5x. Both are fixed here, in one diff. |
| 323 | let w = |offset: i16| { |
| 324 | ((f64::from(p.leaf_q_offset) - f64::from(offset)) * WEIGHT_LEVEL_GAIN).exp() |
| 325 | }; |
| 326 | let (hidden, leaves) = gop_shape(p, gop); |
| 327 | let key = KEY_WEIGHT * w(p.key_q_offset); |
| 328 | let total: f64 = key |
| 329 | + leaves as f64 |
| 330 | + hidden.iter().map(|&(o, n)| n as f64 * w(o)).sum::<f64>(); |
| 331 | // One leaf's byte target: the run is worth `gop` frame targets and |
| 332 | // `total` leaves. |
| 333 | let scale = target_bytes * gop.max(1) as f64 / total.max(f64::EPSILON); |
| 334 | // THE HIDDEN SLOT holds every hidden level at once (`Level::Arf` is |
| 335 | // the top ARF, the mid and the quarters alike -- one controller, |
| 336 | // different q offsets), so its target is kept in LEAF-EQUIVALENT |
| 337 | // bytes and [`RateLoop::update`] scales it by the coded frame's own |
| 338 | // `w(offset)`. Measuring each hidden frame against its OWN predicted |
| 339 | // size is what keeps the shared slot from oscillating between the |
| 340 | // levels it mixes. |
| 341 | // One plan per level, in coding order: key, hidden levels (at most |
| 342 | // three distinct offsets -- top, mid, quarters), leaves. |
| 343 | let mut plans = [None; 5]; |
| 344 | plans[0] = Some(LevelPlan::new(0, p.key_q_offset, key)); |
| 345 | let mut i = 1; |
| 346 | for &(o, n) in hidden.iter().take(3) { |
| 347 | plans[i] = Some(LevelPlan::new(1, o, n as f64 * w(o))); |
| 348 | i += 1; |
| 349 | } |
| 350 | plans[i] = Some(LevelPlan::new(2, p.leaf_q_offset, leaves as f64)); |
| 351 | Self { |
| 352 | target: [scale * key, scale, scale], |
| 353 | q: [start_q; 3], |
| 354 | per_level: true, |
| 355 | seeded: [false; 3], |
| 356 | leaf_q_offset: p.leaf_q_offset, |
| 357 | key_weight: key, |
| 358 | run_weight: total, |
| 359 | run_bytes: target_bytes * gop.max(1) as f64, |
| 360 | left_weight: total, |
| 361 | left_bytes: target_bytes * gop.max(1) as f64, |
| 362 | plans, |
| 363 | scale0: scale, |
| 364 | census: census_on(), |
| 365 | coded: 0, |
| 366 | } |
| 367 | } |
| 368 | |
| 369 | /// What a frame coded `offset` steps off `base_q_idx` is worth in |
| 370 | /// leaf-equivalent bytes ([`WEIGHT_LEVEL_GAIN`]). |
| 371 | fn weight(&self, offset: i16) -> f64 { |
| 372 | ((f64::from(self.leaf_q_offset) - f64::from(offset)) * WEIGHT_LEVEL_GAIN).exp() |
| 373 | } |
| 374 | |
| 375 | /// Which [`LevelPlan`] a coded frame belongs to. Only the hidden slot |
| 376 | /// holds more than one level, so only there does the offset decide. |
| 377 | fn plan_of(&self, slot: usize, offset: i16) -> Option<usize> { |
| 378 | self.plans |
| 379 | .iter() |
| 380 | .position(|p| p.is_some_and(|p| p.slot == slot && (slot != 1 || p.offset == offset))) |
| 381 | } |
| 382 | |
| 383 | /// Which controller a level uses: one shared slot on the flat path, three |
| 384 | /// separate ones under a pyramid. |
| 385 | fn slot(&self, level: Level) -> usize { |
| 386 | if !self.per_level { |
| 387 | return 0; |
| 388 | } |
| 389 | match level { |
| 390 | Level::Key => 0, |
| 391 | Level::Arf => 1, |
| 392 | // A `show_existing_frame` packet codes no pixels and never |
| 393 | // reaches `update`; it shares the leaf slot so `q_idx` is total. |
| 394 | Level::Leaf | Level::ShowExisting => 2, |
| 395 | } |
| 396 | } |
| 397 | |
| 398 | fn q_idx(&self, level: Level) -> u8 { |
| 399 | self.q[self.slot(level)].round().clamp(0.0, 255.0) as u8 |
| 400 | } |
| 401 | |
| 402 | /// Steers this level's `q` toward its own target from the frame's actual |
| 403 | /// coded size. |
| 404 | /// |
| 405 | /// `raw_q` is the quantizer the frame WANTED (`base_q_idx + offset`, |
| 406 | /// before the coder's own 1..=255 clamp): outside that range the level is |
| 407 | /// at its bound and its share of the budget has to move elsewhere. |
| 408 | fn update(&mut self, level: Level, offset: i16, raw_q: i16, actual_bytes: usize) { |
| 409 | let slot = self.slot(level); |
| 410 | if self.target[slot] <= 0.0 || actual_bytes == 0 { |
| 411 | return; |
| 412 | } |
| 413 | // A hidden frame is measured against ITS OWN level's predicted size: |
| 414 | // slot 1's target is in leaf-equivalent bytes. |
| 415 | let frame_weight = match slot { |
| 416 | 0 => self.key_weight, |
| 417 | 1 => self.weight(offset), |
| 418 | _ => 1.0, |
| 419 | }; |
| 420 | let target = match self.per_level && slot == 1 { |
| 421 | true => self.target[slot] * frame_weight, |
| 422 | false => self.target[slot], |
| 423 | }; |
| 424 | let ratio = actual_bytes as f64 / target; |
| 425 | // `STEP_CLAMP` protects an operating point this slot has not found |
| 426 | // yet: its `q` is still the caller's `base_q_idx` guess, and the |
| 427 | // clamp makes the loop WALK to the right quantizer at twelve steps a |
| 428 | // frame. Measured on the 48-frame bitrate gate, the pyramid's ARF |
| 429 | // slot spent five of its twelve frames pinned at `-STEP_CLAMP` and |
| 430 | // the stream landed -10.2% under target -- convergence lag, not a |
| 431 | // steady-state offset (the fixed point of this loop is `actual == |
| 432 | // target` exactly). So a slot's FIRST frame takes the model's whole |
| 433 | // step and seeds `q` where the log-linear slope says it belongs; from |
| 434 | // the second frame on the clamp is back, and nothing is accumulated |
| 435 | // between frames, so [[vorbis-rate-loop-windup]]'s bound still holds. |
| 436 | let raw = ratio.ln() * Self::GAIN; |
| 437 | let step = if std::mem::replace(&mut self.seeded[slot], true) { |
| 438 | raw.clamp(-Self::STEP_CLAMP, Self::STEP_CLAMP) |
| 439 | } else { |
| 440 | raw |
| 441 | }; |
| 442 | self.q[slot] = (self.q[slot] + step).clamp(0.0, 255.0); |
| 443 | let bound = !(1..=255).contains(&raw_q); |
| 444 | if let Some(plan) = self.plan_of(slot, offset).and_then(|i| self.plans[i].as_mut()) { |
| 445 | plan.bound = bound; |
| 446 | plan.rate = actual_bytes as f64 / frame_weight.max(f64::EPSILON); |
| 447 | } |
| 448 | if self.census { |
| 449 | eprintln!( |
| 450 | "RLCENSUS n={} level={level:?} slot={slot} target={target:.0} actual={actual_bytes} \ |
| 451 | base_q={:.1} raw_q={raw_q} eff_q={} bound={} left_bytes={:.0} left_w={:.1}", |
| 452 | self.coded, |
| 453 | self.q[slot], |
| 454 | raw_q.clamp(1, 255), |
| 455 | bound, |
| 456 | self.left_bytes, |
| 457 | self.left_weight, |
| 458 | ); |
| 459 | self.coded += 1; |
| 460 | } |
| 461 | self.replan(level, slot, offset, frame_weight, actual_bytes as f64); |
| 462 | } |
| 463 | |
| 464 | /// Re-plans the REST OF THE RUN from what it has actually spent: the |
| 465 | /// level model says how the budget SPLITS, and nothing but a measurement |
| 466 | /// says what a frame of this content costs at all. |
| 467 | /// |
| 468 | /// Two frames of a run cannot be steered by the loop and both are pure |
| 469 | /// model error without this: the KEY, coded once at the caller's seed `q` |
| 470 | /// before anything has been measured (the census's key frames run 0.5x to |
| 471 | /// 2.7x the model across the two films), and any level whose `q` has hit |
| 472 | /// the floor -- at 3 Mbit/s on the gate's clip the hidden slot codes at |
| 473 | /// `q_idx` 1 and physically cannot spend its share, which the leaves must |
| 474 | /// then absorb or the stream lands a third under target. |
| 475 | /// |
| 476 | /// It is NOT an accumulated error term in `q` ([[vorbis-rate-loop-windup]] |
| 477 | /// is about exactly that): `q` still moves only by this frame's own |
| 478 | /// clamped proportional step, the re-plan only moves the TARGET the next |
| 479 | /// frame is measured against, and every key frame resets the whole plan, |
| 480 | /// so no debt outlives one run. |
| 481 | fn replan(&mut self, level: Level, slot: usize, offset: i16, frame_weight: f64, actual_bytes: f64) { |
| 482 | if !self.per_level { |
| 483 | return; |
| 484 | } |
| 485 | if level == Level::Key { |
| 486 | self.left_weight = self.run_weight; |
| 487 | self.left_bytes = self.run_bytes; |
| 488 | for plan in self.plans.iter_mut().flatten() { |
| 489 | plan.left = plan.weight; |
| 490 | } |
| 491 | } |
| 492 | self.left_weight -= frame_weight; |
| 493 | self.left_bytes -= actual_bytes; |
| 494 | if let Some(plan) = self.plan_of(slot, offset).and_then(|i| self.plans[i].as_mut()) { |
| 495 | plan.left = (plan.left - frame_weight).max(0.0); |
| 496 | } |
| 497 | // The tail of a run is not re-planned: under a leaf's worth of weight |
| 498 | // left, the division is noise. |
| 499 | if self.left_weight <= 1.0 { |
| 500 | return; |
| 501 | } |
| 502 | // A BOUND level is held at what it measurably spends and its weight |
| 503 | // is taken out of the division, so the bytes it cannot spend land on |
| 504 | // the levels that can (and, at the ceiling, the other way round). The |
| 505 | // old code divided the whole remainder by the whole remaining weight, |
| 506 | // which handed the biggest share of the shortfall straight back to |
| 507 | // the level that had just failed to spend it -- at the default |
| 508 | // pyramid the hidden levels carry most of the run's weight, so most |
| 509 | // of the surplus evaporated there every frame. |
| 510 | // ABLATION (`EC_AV1_RL_NOREDIST=1`, this lane's before/after arm): |
| 511 | // the old division, whole remainder over whole remaining weight. |
| 512 | if std::env::var("EC_AV1_RL_NOREDIST").is_ok_and(|v| v == "1") { |
| 513 | let scale = (self.left_bytes / self.left_weight).max(0.0); |
| 514 | self.target = [scale * self.key_weight, scale, scale]; |
| 515 | return; |
| 516 | } |
| 517 | let (mut bytes, mut weight) = (self.left_bytes, 0.0); |
| 518 | for plan in self.plans.iter().flatten() { |
| 519 | if plan.bound { |
| 520 | bytes -= plan.rate * plan.left; |
| 521 | } else { |
| 522 | weight += plan.left; |
| 523 | } |
| 524 | } |
| 525 | if weight <= 1.0 { |
| 526 | // Every movable level is spent: nothing left to re-solve over. |
| 527 | return; |
| 528 | } |
| 529 | let scale = (bytes / weight) |
| 530 | .clamp(self.scale0 * Self::REPLAN_FLOOR, self.scale0 * Self::REPLAN_CLAMP); |
| 531 | self.target = [scale * self.key_weight, scale, scale]; |
| 532 | } |
| 533 | } |
| 534 | |
| 535 | /// What [`Av1Encoder::new`] takes: geometry, rate, key-frame cadence and |
| 536 | /// colour. `base_q_idx` is picked directly (0..=255, `crate::encode`'s own |
| 537 | /// unit) rather than a bitrate — a bitrate control loop is not part of this |
| 538 | /// lane's charter, and a caller that wants one can still derive a |
| 539 | /// `base_q_idx` from its own target and set that field. A caller who wants |
| 540 | /// [`RateTarget`]'s quality/size dials instead of picking `base_q_idx` |
| 541 | /// itself uses [`Av1Encoder::with_rate_target`], which still starts from an |
| 542 | /// `EncoderConfig` (its `base_q_idx` is the loop's seed/fallback for |
| 543 | /// [`RateTarget::BytesPerFrame`], and is overwritten outright for the other |
| 544 | /// two variants). |
| 545 | #[derive(Debug, Clone, Copy)] |
| 546 | pub struct EncoderConfig { |
| 547 | /// The picture's width in luma samples; must be even and nonzero. |
| 548 | pub width: usize, |
| 549 | /// The picture's height in luma samples; must be even and nonzero. |
| 550 | pub height: usize, |
| 551 | /// The quantizer index every frame is coded at (0..=255). |
| 552 | pub base_q_idx: u8, |
| 553 | /// Pictures between key frames, inclusive of the key frame itself: `1` |
| 554 | /// codes every picture as a key frame, `gop` codes picture `gop` (and |
| 555 | /// `2*gop`, ...) as a key frame and every other picture inter. |
| 556 | pub gop: usize, |
| 557 | /// The colour the sequence header signals. |
| 558 | pub colour: Colour, |
| 559 | /// `TileColsLog2` (spec 5.9.15): the frame is split into `1 << |
| 560 | /// tile_cols_log2` uniformly spaced tile columns, each coded and |
| 561 | /// decodable on its own. `0` -- one tile column -- is the default and |
| 562 | /// is byte for byte the stream this encoder wrote before tiles existed. |
| 563 | pub tile_cols_log2: u32, |
| 564 | /// `TileRowsLog2`, the same down the rows. |
| 565 | pub tile_rows_log2: u32, |
| 566 | } |
| 567 | |
| 568 | impl EncoderConfig { |
| 569 | /// A config at `width`x`height` with one tile, `gop` pictures between |
| 570 | /// key frames and no colour signalling -- what every caller that does |
| 571 | /// not care about tiles writes, so that adding a field here does not |
| 572 | /// rewrite them. |
| 573 | #[must_use] |
| 574 | pub fn new(width: usize, height: usize, base_q_idx: u8, gop: usize, colour: Colour) -> Self { |
| 575 | Self { |
| 576 | width, |
| 577 | height, |
| 578 | base_q_idx, |
| 579 | gop, |
| 580 | colour, |
| 581 | tile_cols_log2: 0, |
| 582 | tile_rows_log2: 0, |
| 583 | } |
| 584 | } |
| 585 | } |
| 586 | |
| 587 | /// One coded picture: its OBUs, in the order a demuxer that just wants bytes |
| 588 | /// on the wire can concatenate them, and the two things a muxer needs to |
| 589 | /// know without parsing them back out. |
| 590 | #[derive(Debug, Clone)] |
| 591 | pub struct Packet { |
| 592 | /// A temporal delimiter, a sequence header and the frame OBU for a key |
| 593 | /// frame; a temporal delimiter and the frame OBU alone for an inter |
| 594 | /// frame (the sequence header is identical across a stream's key |
| 595 | /// frames, since only [`EncoderConfig`]'s own fields feed it, so it is |
| 596 | /// simplest to let every key frame carry its own copy rather than have |
| 597 | /// the facade special-case the first one). |
| 598 | pub data: Vec<u8>, |
| 599 | /// Whether this picture was coded as a key frame. |
| 600 | pub key: bool, |
| 601 | /// This picture's position in DISPLAY (presentation) order, starting at |
| 602 | /// 0 — a muxer's `pts` in picture units. Without a [`Pyramid`] this is |
| 603 | /// also the coding order and equals `dts`. |
| 604 | pub order: u64, |
| 605 | /// This packet's position in CODING (decode) order, starting at 0 — a |
| 606 | /// muxer's `dts` in packet units. With a [`Pyramid`] the hidden frame of |
| 607 | /// each mini-GOP is coded before the leaves it precedes in display order, |
| 608 | /// so `dts` and `order` diverge, and the `show_existing_frame` packet |
| 609 | /// that re-outputs the hidden frame carries the hidden frame's own |
| 610 | /// `order` with its own later `dts`. |
| 611 | pub dts: u64, |
| 612 | /// Which pyramid level this packet is. |
| 613 | pub level: Level, |
| 614 | } |
| 615 | |
| 616 | /// One mini-GOP of a two-level coding pyramid, and the quantizer offsets its |
| 617 | /// two levels are coded at. libaom's `gf_group` shape, cut down to the two |
| 618 | /// levels this encoder's reference set can carry: the last picture of each |
| 619 | /// mini-GOP is coded FIRST, hidden (`show_frame == 0`), as the group's |
| 620 | /// `ALTREF_FRAME`, then the pictures before it are coded as shown leaves that |
| 621 | /// may predict backward off it, and finally a `show_existing_frame` header |
| 622 | /// re-outputs the hidden frame in its own display position. |
| 623 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 624 | pub struct Pyramid { |
| 625 | /// Pictures per mini-GOP: the hidden frame is `mini_gop` pictures ahead |
| 626 | /// of the group's anchor, and `mini_gop - 1` leaves sit between them. |
| 627 | /// `1` would leave no leaf at all and is refused. It is the group size a |
| 628 | /// long run takes; the last group of a run is up to 1.5x it, since |
| 629 | /// [`group_target`] absorbs a tail shorter than half a group rather than |
| 630 | /// leaving one behind. |
| 631 | pub mini_gop: usize, |
| 632 | /// Added to `base_q_idx` for the hidden `ALTREF_FRAME` — negative, since |
| 633 | /// every leaf of the group predicts off it. |
| 634 | pub arf_q_offset: i16, |
| 635 | /// Added to `base_q_idx` for each shown leaf — positive, since nothing |
| 636 | /// predicts off a leaf but the next leaf. |
| 637 | pub leaf_q_offset: i16, |
| 638 | /// THE THIRD LEVEL, or `None` for the two-level pyramid: the offset a |
| 639 | /// second hidden frame, at the middle of the mini-GOP, is coded at |
| 640 | /// (between [`Pyramid::arf_q_offset`] and [`Pyramid::leaf_q_offset`], so |
| 641 | /// the group reads key -> top ARF -> mid ARF -> leaves). The leaves |
| 642 | /// before it name it as their `ALTREF_FRAME` and the leaves after it |
| 643 | /// start their chain from it, which halves every leaf's distance to its |
| 644 | /// nearest good reference. Ignored by a group of fewer than four |
| 645 | /// pictures, where there is no leaf on both sides of a midpoint. |
| 646 | pub mid_q_offset: Option<i16>, |
| 647 | /// THE FOURTH LEVEL, or `None` for the three-level pyramid: the offset |
| 648 | /// the two hidden QUARTER-POINT ARFs are coded at (between |
| 649 | /// [`Pyramid::mid_q_offset`] and [`Pyramid::leaf_q_offset`], so the group |
| 650 | /// reads key -> top ARF -> mid ARF -> quarter ARFs -> leaves). In a group |
| 651 | /// of eight they sit at pictures 2 and 6, halving again the distance from |
| 652 | /// a leaf to its nearest good reference; every leaf then names the |
| 653 | /// nearest hidden frame on each side. Ignored by a group with fewer than |
| 654 | /// seven leaves, where a quarter point has no leaf on both sides, and -- |
| 655 | /// like the mid level -- by a run no longer than one mini-GOP. |
| 656 | pub quarter_q_offset: Option<i16>, |
| 657 | /// Added to `base_q_idx` for the GOP's KEY FRAME — negative, since every |
| 658 | /// frame of the run reads it, directly or through an ARF. The 48-frame |
| 659 | /// census (`lanes/census-longgop.md`) found ours coded at base q while |
| 660 | /// its own ARFs sat 32 steps finer, where rav1e (key 100 / arf 120 / |
| 661 | /// leaf 153) and libaom (63 / 95 / 163) both make the key the best frame |
| 662 | /// of the run and spend 22--37% of the stream on it against our 10--11%. |
| 663 | pub key_q_offset: i16, |
| 664 | } |
| 665 | |
| 666 | /// How many pictures the mini-GOP now being collected takes, given how many |
| 667 | /// are left in this run (the pictures before the next key frame) and the |
| 668 | /// [`Pyramid::mini_gop`] shape. |
| 669 | /// |
| 670 | /// A fixed `mini_gop` leaves a SHORT TAIL group whenever the run is not a |
| 671 | /// multiple of it: a 12-picture GOP under `mini_gop` 8 codes 8 + 3, and that |
| 672 | /// 3-picture tail is the expensive part -- the 12-frame gate preferred one |
| 673 | /// group of 11 by 7.0 / 20.5 BD points while the 48-frame gate picked 8 |
| 674 | /// (lane-pyr4). The rule here ABSORBS a tail shorter than half a group into |
| 675 | /// the group before it, so a run takes groups of `mini_gop` until at most |
| 676 | /// 1.5 x `mini_gop` is left and then one final group of all of it: |
| 677 | /// remaining 11 under 8 -> 11 (was 8 + 3) |
| 678 | /// remaining 47 under 8 -> 8, 8, 8, 8, 8, 7 -- what the fixed rule already |
| 679 | /// coded, so a long GOP is byte-identical |
| 680 | /// (`the_mini_gop_layout_leaves_no_short_tail`; sweep `lanes/gopad.sweep.txt`). |
| 681 | /// |
| 682 | /// `EC_AV1_GOP_LAYOUT=fixed` restores the old fixed-size rule for an A/B. |
| 683 | fn group_target(remaining: usize, mini_gop: usize, absorb_tail: bool) -> usize { |
| 684 | match absorb_tail && remaining <= mini_gop + mini_gop / 2 { |
| 685 | true => remaining.max(1), |
| 686 | false => mini_gop, |
| 687 | } |
| 688 | } |
| 689 | |
| 690 | /// How one GOP of `gop` pictures is actually coded, as [`Av1Encoder::encode_frames`] |
| 691 | /// and [`Av1Encoder::drain_pending`] lay it out: the HIDDEN frames as |
| 692 | /// `(q offset, count)` (the group's top `ALTREF`, the mid level and the two |
| 693 | /// quarter-point ARFs, each at its own offset) and the number of shown |
| 694 | /// leaves. The key frame is the remaining picture and is not listed. |
| 695 | /// |
| 696 | /// This is what [`RateLoop::new`] prices the run by, so the two must agree on |
| 697 | /// the gating rules -- a mid level needs three leaves and a run longer than |
| 698 | /// 1.5 mini-GOPs, quarters need seven leaves and a mid -- which |
| 699 | /// `the_rate_loop_prices_the_frames_the_pyramid_codes` pins against the real |
| 700 | /// packet stream. |
| 701 | fn gop_shape(p: Pyramid, gop: usize) -> (Vec<(i16, usize)>, usize) { |
| 702 | let (mut hidden, mut leaves) = (Vec::<(i16, usize)>::new(), 0usize); |
| 703 | let mut add = |offset: i16, n: usize| match hidden.iter_mut().find(|(o, _)| *o == offset) { |
| 704 | Some((_, c)) => *c += n, |
| 705 | None => hidden.push((offset, n)), |
| 706 | }; |
| 707 | let long_run = gop > p.mini_gop + p.mini_gop / 2; |
| 708 | let mut left = gop.saturating_sub(1); |
| 709 | while left > 0 { |
| 710 | let g = group_target(left, p.mini_gop, absorb_tail()).min(left); |
| 711 | left -= g; |
| 712 | if g == 1 { |
| 713 | leaves += 1; |
| 714 | continue; |
| 715 | } |
| 716 | let inner = g - 1; |
| 717 | add(p.arf_q_offset, 1); |
| 718 | let mid = p.mid_q_offset.filter(|_| inner >= 3 && long_run); |
| 719 | let quarters = mid.and(p.quarter_q_offset).filter(|_| inner >= 7); |
| 720 | if let Some(o) = mid { |
| 721 | add(o, 1); |
| 722 | } |
| 723 | if let Some(o) = quarters { |
| 724 | add(o, 2); |
| 725 | } |
| 726 | leaves += inner - usize::from(mid.is_some()) - 2 * usize::from(quarters.is_some()); |
| 727 | } |
| 728 | (hidden, leaves) |
| 729 | } |
| 730 | |
| 731 | /// Whether this run absorbs a short tail group (the default) or cuts every |
| 732 | /// mini-GOP at `mini_gop`: `EC_AV1_GOP_LAYOUT=fixed`, read once. |
| 733 | fn absorb_tail() -> bool { |
| 734 | static ABSORB: std::sync::LazyLock<bool> = std::sync::LazyLock::new(|| { |
| 735 | std::env::var("EC_AV1_GOP_LAYOUT").ok().as_deref() != Some("fixed") |
| 736 | }); |
| 737 | *ABSORB |
| 738 | } |
| 739 | |
| 740 | impl Pyramid { |
| 741 | /// The pyramid a run asks for through the environment: |
| 742 | /// `EC_AV1_PYRAMID=<mini_gop>[:<arf_q_offset>:<leaf_q_offset>[:<mid>[:<key>]]]`, |
| 743 | /// where `<mid>` is the third level's offset or `off` for none, with |
| 744 | /// `0` (or anything that is not a mini-GOP of at least 2, e.g. `flat`) |
| 745 | /// meaning the flat one-picture-one-frame path. UNSET is |
| 746 | /// [`Pyramid::default`]: the pyramid is what |
| 747 | /// [`crate::encode::encode_sequence`], the BD gate and `ec-bench` code |
| 748 | /// under unless a run turns it off for an A/B. |
| 749 | #[must_use] |
| 750 | pub fn from_env() -> Option<Self> { |
| 751 | let d = Self::default(); |
| 752 | let Some(spec) = std::env::var("EC_AV1_PYRAMID").ok() else { |
| 753 | return Some(d); |
| 754 | }; |
| 755 | let mut f = spec.split(':'); |
| 756 | let mini_gop: usize = f.next().and_then(|v| v.parse().ok()).unwrap_or(0); |
| 757 | if mini_gop < 2 { |
| 758 | return None; |
| 759 | } |
| 760 | Some(Self { |
| 761 | mini_gop, |
| 762 | arf_q_offset: f.next().and_then(|v| v.parse().ok()).unwrap_or(d.arf_q_offset), |
| 763 | leaf_q_offset: f.next().and_then(|v| v.parse().ok()).unwrap_or(d.leaf_q_offset), |
| 764 | // A fourth field is the mid-level offset; the literal `off` asks |
| 765 | // for the two-level pyramid at the same shape (the A/B arm the |
| 766 | // sweep needs), and no field at all keeps the default's. |
| 767 | mid_q_offset: match f.next() { |
| 768 | None => d.mid_q_offset, |
| 769 | Some("off") => None, |
| 770 | Some(v) => v.parse().ok().or(d.mid_q_offset), |
| 771 | }, |
| 772 | // A fifth field is the key frame's own offset. |
| 773 | key_q_offset: f.next().and_then(|v| v.parse().ok()).unwrap_or(d.key_q_offset), |
| 774 | // A sixth field is the quarter level's offset, `off` for none. |
| 775 | quarter_q_offset: match f.next() { |
| 776 | None => d.quarter_q_offset, |
| 777 | Some("off") => None, |
| 778 | Some(v) => v.parse().ok().or(d.quarter_q_offset), |
| 779 | }, |
| 780 | }) |
| 781 | } |
| 782 | } |
| 783 | |
| 784 | impl Default for Pyramid { |
| 785 | /// The best point of the offset sweep run through the BD gate's own |
| 786 | /// `EC_AV1_PYRAMID=<mini_gop>[:<arf_q_offset>:<leaf_q_offset>]` knob |
| 787 | /// (`encode::tests::bd_rate_vs_libaom_and_rav1e`, 12 frames of each of |
| 788 | /// the three gate clips, BD-rate vs libaom / vs rav1e, wall = the four |
| 789 | /// encodes of the ladder together). |
| 790 | /// |
| 791 | /// First sweep, before the motion-search lane merged (its extra-reference |
| 792 | /// `NEWMV` is exactly what a pyramid leaf needs to reach its hidden |
| 793 | /// frame), so read it for the OFFSETS, not for the verdict: |
| 794 | /// |
| 795 | /// | mini_gop:arf:leaf | 1080p | 2160p | screen | |
| 796 | /// |---|---|---|---| |
| 797 | /// | flat (no pyramid) | +122.7 / +73.4 | +147.3 / +98.5 | +79.4 / +17.2 | |
| 798 | /// | 4:0:0 | +152.2 / +97.9 | +214.7 / +158.1 | +91.4 / +26.2 | |
| 799 | /// | 4:-16:8 | +139.9 / +87.1 | +201.5 / +143.7 | +78.5 / +19.5 | |
| 800 | /// | 4:-24:12 | +141.3 / +85.0 | +190.0 / +132.9 | +84.5 / +22.8 | |
| 801 | /// | 2:0:0 | +149.3 / +93.1 | +203.0 / +149.4 | +88.3 / +23.6 | |
| 802 | /// | 2:-8:4 | +143.1 / +89.1 | +196.2 / +141.6 | +82.5 / +20.4 | |
| 803 | /// | 2:-16:8 | +137.6 / +84.5 | +187.2 / +130.6 | +84.9 / +23.1 | |
| 804 | /// |
| 805 | /// `0:0` is the worst row at both mini-GOP sizes and `-16/+8` buys 12-16 |
| 806 | /// BD points over it, in the direction libaom's `gf_group` spends them |
| 807 | /// (lowest quantizer on the frame everything else predicts from). Those |
| 808 | /// are these defaults. |
| 809 | /// |
| 810 | /// Re-measured after that lane merged (wall ours, 1080p/2160p/screen): |
| 811 | /// |
| 812 | /// | arm | 1080p | 2160p | screen | wall | |
| 813 | /// |---|---|---|---|---| |
| 814 | /// | flat (no pyramid) | +121.1 / +71.8 | +146.1 / +97.5 | +79.3 / +17.2 | 6.3 / 5.8 / 6.2 s | |
| 815 | /// | 4:-16:8 | +131.9 / +81.1 | +178.7 / +123.6 | +78.4 / +19.5 | 6.2 / 5.6 / 5.5 s | |
| 816 | /// | 2:-16:8 | +125.4 / +76.2 | +173.0 / +119.5 | +84.9 / +23.1 | 6.2 / 5.6 / 6.2 s | |
| 817 | /// |
| 818 | /// So the pyramid still does NOT pay, and ships OFF: it wins 0.9 points |
| 819 | /// on screen capture at `4:-16:8` and loses 11 on 1080p and 33 on 2160p. |
| 820 | /// What keeps it from paying, in the order the numbers point at it: |
| 821 | /// |
| 822 | /// * The hidden frame predicts `mini_gop` pictures ahead of its own |
| 823 | /// reference with the SAME forward search a neighbouring frame gets, |
| 824 | /// and it is the largest frame in the group (73.8 kB of the 1080p |
| 825 | /// ladder's 184 kB at `4:-16:8`). On the 2160p clip, whose motion the |
| 826 | /// search only just reaches at distance 1, distance 4 is where it |
| 827 | /// falls off — that clip loses twice what 1080p does, and shrinking |
| 828 | /// the mini-GOP to 2 recovers most of the gap (+178.7 -> +173.0, |
| 829 | /// +131.9 -> +125.4). A distance-scaled search range is the fix, and |
| 830 | /// it lives in the motion-search lane, not here. |
| 831 | /// * The leaves reach the hidden frame through the extra-reference |
| 832 | /// modes only: `ALTREF_FRAME` wins about 13% of blocks |
| 833 | /// (`encode::take_ref_frame_hits`, printed by the round-trip test), |
| 834 | /// up from 4% before the motion lane merged. A compound |
| 835 | /// (`LAST` + `ALTREF`) prediction mode is the other half of what a |
| 836 | /// real B frame buys, and this crate codes no compound blocks at all. |
| 837 | /// |
| 838 | /// Neither is a defect in the pyramid itself: the reordering is exact |
| 839 | /// (`encoder::tests::a_pyramid_stream_decodes_in_display_order_through_both_decoders` |
| 840 | /// checks every shown frame in display order against ffmpeg AND our own |
| 841 | /// decoder, with the hidden frame proven to win blocks), and the |
| 842 | /// Re-measured a third time at NATIVE resolution (`encode::tests:: |
| 843 | /// bd_rate_screen_native`, 1920x1024 crops, 12 frames, four quantizers, |
| 844 | /// BD-rate vs libaom / vs rav1e), because every earlier verdict was taken |
| 845 | /// on the 4x-downscaled gate (class `gate-recipe-confound`) and because |
| 846 | /// leaf compound and the distance-scaled search have landed since: |
| 847 | /// |
| 848 | /// | arm | film 1080p | film 2160p | screen | |
| 849 | /// |---|---|---|---| |
| 850 | /// | flat (no pyramid) | +18.7 / +1.4 | +48.1 / +19.8 | +59.4 / -10.0 | |
| 851 | /// | 4:-16:8 | +23.2 / +5.3 | +48.1 / +19.7 | +62.7 / -6.5 | |
| 852 | /// | 2:-16:8 | +24.9 / +6.9 | +46.9 / +19.5 | +69.0 / -3.8 | |
| 853 | /// | 8:-16:8 | +22.6 / +4.6 | +48.7 / +19.8 | +59.3 / -8.2 | |
| 854 | /// | 4:-24:12 (before the leaf-compound merge) | +24.3 / +6.3 | +48.5 / +20.2 | +67.2 / -3.7 | |
| 855 | /// |
| 856 | /// The confound was real -- at native the gap is 5 BD points, not 30 -- |
| 857 | /// but the sign is not: no arm beats flat on both films, every arm costs |
| 858 | /// 4-6 points on 1080p, and the best 2160p arm (`2:-16:8`, -1.1 vs |
| 859 | /// libaom) pays +10 on screen. So the pyramid still ships OFF. |
| 860 | /// |
| 861 | /// A native offset sweep on the 2160p clip alone (mini-GOP 4) says the |
| 862 | /// offsets are not what is missing -- the whole 3x3 grid spans 2.9 BD |
| 863 | /// points and none of it reaches flat's +48.1: |
| 864 | /// |
| 865 | /// | arf \ leaf | +4 | +8 | +12 | |
| 866 | /// |---|---|---|---| |
| 867 | /// | -8 | +48.9 / +20.4 | +49.2 / +20.1 | +50.2 / +20.5 | |
| 868 | /// | -16 | +47.8 / +20.0 | +48.1 / +19.7 | +49.2 / +20.2 | |
| 869 | /// | -24 | +47.3 / +20.0 | +47.6 / +19.7 | +48.5 / +20.2 | |
| 870 | /// |
| 871 | /// The gradient is monotone in both knobs (deeper ARF better, shallower |
| 872 | /// leaf better), which is the shape of a group whose leaves cannot cash |
| 873 | /// in the ARF's extra quality: what the leaves reach the hidden frame |
| 874 | /// with is still one forward search per reference. Shrinking the mini-GOP |
| 875 | /// helps for the same reason (2:-16:8 is the only arm that beats flat on |
| 876 | /// any clip, and it beats it on the clip with the fastest motion). |
| 877 | /// |
| 878 | /// RE-SWEPT on lane-av1pyrgate, once the content gate below existed and |
| 879 | /// on the current defaults (`LAMBDA_SCALE` 0.0275, the 32x32 tx-depth |
| 880 | /// search and compound var-tx on): the earlier verdicts were taken with |
| 881 | /// the screen capture inside the arm, and it is the one clip a pyramid |
| 882 | /// never helps. With the gate, the screen row is the flat row by |
| 883 | /// construction, so the sweep is decided on the two real films |
| 884 | /// (`encode::tests::bd_rate_screen_native`, BD-rate vs libaom / vs |
| 885 | /// rav1e; bars are fixtures, recorded only): |
| 886 | /// |
| 887 | /// | arm | film A | film B | screen | bars 1080p | bars 2160p | |
| 888 | /// |---|---|---|---|---|---| |
| 889 | /// | flat (no pyramid) | +62.8 / +32.5 | +86.3 / +50.5 | +50.1 / -15.4 | +16.4 / -1.1 | +48.2 / +20.4 | |
| 890 | /// | 2:-16:8 | +60.3 / +29.1 | +83.6 / +50.2 | +50.1 / -15.4 | +24.0 / +5.9 | +47.2 / +20.2 | |
| 891 | /// | **4:-16:8** | **+54.1 / +24.2** | **+82.6 / +47.4** | +50.1 / -15.4 | +21.5 / +3.7 | +48.3 / +20.4 | |
| 892 | /// | 8:-16:8 | +55.9 / +25.8 | +83.6 / +47.3 | +50.1 / -15.4 | +19.8 / +2.0 | +48.7 / +20.4 | |
| 893 | /// | 4:-24:12 | +51.5 / +22.3 | +84.9 / +50.3 | +50.1 / -15.4 | +21.9 / +4.0 | +48.4 / +20.7 | |
| 894 | /// | 4:-12:6 | +57.6 / +27.1 | +84.8 / +49.3 | +50.1 / -15.4 | +21.7 / +3.9 | +48.8 / +20.9 | |
| 895 | /// |
| 896 | /// `4:-16:8` is the only arm that improves BOTH films on BOTH columns by |
| 897 | /// several points (-8.7 / -8.3 on film A, -3.7 / -3.1 on film B) and it |
| 898 | /// stays these defaults. `4:-24:12` buys another 2.6 on film A and gives |
| 899 | /// 2.3 back on film B (where it barely beats flat vs rav1e, -0.2), which |
| 900 | /// is the same "leaves cannot cash in the ARF's quality" shape as before, |
| 901 | /// now content-dependent rather than uniform. The screen column is |
| 902 | /// IDENTICAL in every arm -- that is the content gate, measured, not |
| 903 | /// asserted. `EC_AV1_LAMBDA=0.035` on top of `4:-16:8` was re-judged once |
| 904 | /// (the pyramid changes the reference structure): +54.5 / +24.5 and |
| 905 | /// +85.2 / +49.4, worse on both films, so 0.0275 stands. |
| 906 | /// |
| 907 | /// SHIPPED AS THE DEFAULT on lane-av1pyrdef. `4:-16:8` is what |
| 908 | /// [`crate::encode::encode_sequence`] (through |
| 909 | /// [`Av1Encoder::encode_sequence_pyramid`], the one mini-GOP driver both |
| 910 | /// paths run), the BD gates and `ec-bench` code a non-screen stream |
| 911 | /// under; a screen stream still codes flat, decided once per stream by |
| 912 | /// the content gate in [`Av1Encoder::encode_frames`]. `EC_AV1_PYRAMID=0` |
| 913 | /// restores the flat path everywhere for an A/B, and |
| 914 | /// `EC_AV1_PYRAMID=<mini_gop>[:<arf>:<leaf>]` another shape of it |
| 915 | /// ([`Pyramid::from_env`]). |
| 916 | /// |
| 917 | /// [`Av1Encoder::new`] is unchanged: the one-picture-one-packet facade |
| 918 | /// entry point still codes flat, since a picture no longer maps to a |
| 919 | /// packet under a pyramid — [`Av1Encoder::with_pyramid`] plus |
| 920 | /// [`Av1Encoder::encode_frames`] is the streaming surface that reorders. |
| 921 | /// RE-SWEPT on lane-pyr3, on main 503d7aa9 -- `4:-16:8` was chosen when |
| 922 | /// the gate's "film" rows were still colour bars, and CfL, the luma |
| 923 | /// angle deltas, filter intra, the propagating tpl map and the rate-loop |
| 924 | /// step have all landed since (class `unswept decision constants`). The |
| 925 | /// axes were swept in the order mini-GOP first at the shipped offsets, |
| 926 | /// then both offset axes at the best mini-GOP, then the joint corners |
| 927 | /// (`encode::tests::bd_rate_screen_native`, BD-rate vs libaom / vs |
| 928 | /// rav1e; the bars rows move by at most 4 points across the WHOLE sweep |
| 929 | /// and decide nothing, the screen row is byte-identical in every arm |
| 930 | /// because the content gate codes it flat): |
| 931 | /// |
| 932 | /// | arm | film A | film B | |
| 933 | /// |---|---|---| |
| 934 | /// | flat (no pyramid) | +61.4 / +31.3 | +85.3 / +49.7 | |
| 935 | /// | 2:-16:8 | +59.2 / +28.1 | +82.3 / +49.1 | |
| 936 | /// | 4:-16:8 (was shipped) | +52.8 / +23.3 | +81.0 / +46.1 | |
| 937 | /// | 8:-16:8 | +54.3 / +24.4 | +81.8 / +45.8 | |
| 938 | /// | 16:-16:8 | +50.8 / +21.4 | +73.8 / +38.7 | |
| 939 | /// | 8:-8:8 | +58.0 / +27.5 | +83.3 / +46.5 | |
| 940 | /// | 8:-24:8 | +52.7 / +23.4 | +83.7 / +48.4 | |
| 941 | /// | 8:-32:8 | +52.3 / +23.1 | +86.8 / +51.9 | |
| 942 | /// | 8:-16:0 | +60.7 / +30.7 | +85.3 / +51.2 | |
| 943 | /// | 8:-16:4 | +57.6 / +27.4 | +84.1 / +48.6 | |
| 944 | /// | 8:-16:12 | +51.8 / +22.2 | +80.4 / +43.9 | |
| 945 | /// | 8:-16:16 | +50.1 / +20.5 | +80.6 / +43.4 | |
| 946 | /// | 16:-24:8 | +47.8 / +19.0 | +71.5 / +37.4 | |
| 947 | /// | 16:-16:12 | +48.0 / +18.9 | +71.1 / +35.7 | |
| 948 | /// | 16:-16:16 | +45.9 / +17.0 | +69.3 / +34.0 | |
| 949 | /// | 16:-24:12 | +45.6 / +17.0 | +70.2 / +35.6 | |
| 950 | /// | **16:-24:16** | **+44.2 / +15.7** | **+70.5 / +35.2** | |
| 951 | /// | 16:-32:16 | +43.6 / +15.2 | +71.2 / +36.2 | |
| 952 | /// | 16:-24:20 (past the swept range) | +42.9 / +14.5 | +70.8 / +34.9 | |
| 953 | /// | 16:-24:24 (past the swept range) | +42.6 / +14.1 | +71.3 / +35.7 | |
| 954 | /// |
| 955 | /// `16:-24:16` ships: it takes 8.6 / 7.6 points off film A and 10.5 / |
| 956 | /// 10.9 off film B against the old defaults, and every axis through it |
| 957 | /// is at or next to its own minimum. The two arms past the swept leaf |
| 958 | /// range were run because leaf `+16` was the range's edge and still |
| 959 | /// improving (class `instrument at bound`): film A keeps falling to |
| 960 | /// `+24` but film B turns back up at `+20`, so `+16` is where BOTH films |
| 961 | /// are minimal and the bound is not the answer. Deeper ARF is the same |
| 962 | /// shape -- `-32` buys 0.6 on film A and gives 0.7 back on film B. |
| 963 | /// |
| 964 | /// WHAT THAT SWEEP COULD NOT SAY, and the LONG-GOP sweep that answers it |
| 965 | /// (lane-pyr4, `lanes/pyr4.sweep.txt`). The table above is measured |
| 966 | /// against a gate that codes 12 frames with `gop = 12`, and a group is |
| 967 | /// cut at every key frame (`encode_frames`), so `16` there is really |
| 968 | /// "one hidden ARF per GOP" and ANY mini-GOP over 12 codes the same |
| 969 | /// stream (class `instrument at bound`). The user's exports are long |
| 970 | /// GOPs, so the shape is decided on |
| 971 | /// [`crate::encode::tests::bd_rate_film_long_gop`] -- 48 pictures, `gop |
| 972 | /// = 48`, the two real films, four quantizers, vs libaom `cpu-used 6` |
| 973 | /// and rav1e `speed=6` at the same key interval: |
| 974 | /// |
| 975 | /// | mini_gop:arf:leaf | film A vs libaom / rav1e | film B vs libaom / rav1e | |
| 976 | /// |---|---|---| |
| 977 | /// | 32:-24:16 | +79.0 / +29.8 | +164.4 / +58.8 | |
| 978 | /// | 16:-24:16 (was the default) | +67.4 / +21.0 | +165.5 / +57.6 | |
| 979 | /// | 8:-16:16 | +63.7 / +19.0 | +167.6 / +58.6 | |
| 980 | /// | 4:-24:16 | +61.9 / +19.5 | +160.8 / +56.7 | |
| 981 | /// | 8:-24:16 | +58.5 / +15.5 | +166.1 / +56.8 | |
| 982 | /// | 8:-24:12 | +60.2 / +17.3 | +166.8 / +58.0 | |
| 983 | /// | 8:-24:20 | +57.1 / +14.0 | +166.2 / +56.6 | |
| 984 | /// | 8:-40:16 | +56.1 / +13.3 | +167.6 / +57.3 | |
| 985 | /// | 8:-32:12 | +56.5 / +14.7 | +163.0 / +56.3 | |
| 986 | /// | 8:-32:20 | +55.4 / +12.9 | +167.9 / +57.4 | |
| 987 | /// | **8:-32:16** | **+55.7 / +13.5** | **+165.1 / +56.6** | |
| 988 | /// |
| 989 | /// `8:-32:16` ships: against the old `16:-24:16` it takes 11.7 / 7.5 |
| 990 | /// points off film A and 0.4 / 1.0 off film B -- all four columns down. |
| 991 | /// A real 16- or 32-picture group is WORSE than an 8-picture one on film |
| 992 | /// A once the GOP is long enough for the distinction to exist, which the |
| 993 | /// 12-frame gate could not see; `4` was probed below the swept edge and |
| 994 | /// turns back up on film A. ARF `-32` is an interior optimum (`-40` |
| 995 | /// turns back on both films). The leaf axis has content-opposite optima |
| 996 | /// (film A wants `20`, film B wants `12`, within 1.1 and 4.9 points) so |
| 997 | /// `16` stays, being the only value down on all four columns. |
| 998 | /// |
| 999 | /// THE PRICE THAT WAS, and how it was paid (lane-gopad): on the |
| 1000 | /// SHORT-GOP gate (12 frames, `gop = 12`) a fixed mini-GOP of 8 split the |
| 1001 | /// run into 8 + 3 and read film A +51.2 / +21.4, film B +91.0 / +53.5, |
| 1002 | /// against `16:-24:16`'s +44.2 / +15.7 and +70.5 / +35.2 -- the tail |
| 1003 | /// group, not the shape, was the cost. [`group_target`] now absorbs a |
| 1004 | /// short tail, so the same 12 pictures code as ONE group of 11 and read |
| 1005 | /// film A +43.9 / +15.6 and film B +68.4 / +38.2 (three of the four |
| 1006 | /// columns better than `16:-24:16` ever was, film B vs rav1e 3.0 short), |
| 1007 | /// while 47 inter pictures still take 8 x 5 + 7 -- the long-GOP table |
| 1008 | /// above is coded byte for byte as it was measured. |
| 1009 | /// THE THIRD LEVEL (lane-pyr5, `lanes/pyr5.sweep.txt`), swept on the |
| 1010 | /// long-GOP gate against a control arm on this very head: |
| 1011 | /// |
| 1012 | /// | mini_gop:arf:leaf:mid | film A vs libaom / rav1e | film B vs libaom / rav1e | |
| 1013 | /// |---|---|---| |
| 1014 | /// | 8:-32:16 (control, 2-level) | +55.2 / +12.8 | +151.3 / +47.4 | |
| 1015 | /// | 8:-32:16:-4 | +51.8 / +11.4 | +146.2 / +45.4 | |
| 1016 | /// | **8:-32:16:-8** | **+52.1 / +11.7** | **+145.3 / +45.0** | |
| 1017 | /// | 8:-32:16:-16 | +53.4 / +13.0 | +146.0 / +46.1 | |
| 1018 | /// | 8:-32:20:-8 | +52.4 / +11.5 | +148.0 / +46.1 | |
| 1019 | /// | 16:-32:16:-8 | +55.0 / +12.3 | +146.0 / +44.3 | |
| 1020 | /// | 16:-32:16:-16 | +54.6 / +12.1 | +148.7 / +46.0 | |
| 1021 | /// | 4:-32:16:-8 | +61.7 / +20.4 | +147.5 / +51.3 | |
| 1022 | /// |
| 1023 | /// `-4` and `-8` are within a point of each other and split the two |
| 1024 | /// films; `-8` ships because film B is the wider gap. A mini-GOP of 4 |
| 1025 | /// with a mid level -- rav1e's own shape at speed 6 -- is far worse here, |
| 1026 | /// so the third level is worth more than a shorter group, and the census |
| 1027 | /// (`lanes/census-longgop.md`) says why: at 8 pictures our leaves are |
| 1028 | /// already cheap and the bytes sit in the ARFs. |
| 1029 | /// |
| 1030 | /// The 12-frame gate keeps its numbers exactly (+43.9 / +15.6 and +68.4 / |
| 1031 | /// +38.2, byte-identical streams): a GOP that is one single mini-GOP does |
| 1032 | /// not code the third level at all (see `drain_pending`). |
| 1033 | /// THE LEAF OFFSET, RE-SWEPT ONCE THE ANCHORS MOVED (lane-arfq, |
| 1034 | /// `lanes/arfq.sweep.txt`). The table above chose `16` when the key frame |
| 1035 | /// still sat at the base quantizer; with [`Pyramid::key_q_offset`] at |
| 1036 | /// `-48` the whole run predicts off a much finer anchor and the leaves |
| 1037 | /// want to be finer with it. Long-GOP gate, control arm on the same head: |
| 1038 | /// |
| 1039 | /// | mini_gop:arf:leaf:mid:key | film A vs libaom / rav1e | film B vs libaom / rav1e | |
| 1040 | /// |---|---|---| |
| 1041 | /// | 8:-32:8:-8:-48 | +43.4 / +5.1 | +127.6 / +34.1 | |
| 1042 | /// | **8:-32:12:-8:-48** | **+43.1 / +4.6** | **+129.0 / +34.3** | |
| 1043 | /// | 8:-32:16:-8:-48 (control) | +43.5 / +4.6 | +131.3 / +35.0 | |
| 1044 | /// | 8:-32:24:-8:-48 | +45.6 / +5.6 | +138.8 / +38.4 | |
| 1045 | /// | 8:-32:12:-12:-48 | +43.4 / +5.0 | +128.1 / +33.8 | |
| 1046 | /// | 8:-32:12:-16:-48 | +44.0 / +5.6 | +127.7 / +34.1 | |
| 1047 | /// | 8:-24:12:-8:-48 | +44.5 / +5.2 | +128.6 / +33.3 | |
| 1048 | /// | 16:-32:12:-8:-48 | +47.2 / +6.3 | +134.7 / +35.6 | |
| 1049 | /// |
| 1050 | /// `12` ships: film B 2.3 / 0.7 down, film A 0.4 down against libaom and |
| 1051 | /// flat against rav1e. `8` is past the optimum (it buys film B and gives |
| 1052 | /// film A back), `24` is worse on all four. The other two axes were |
| 1053 | /// re-swept at `12` and did not move: a deeper mid (`-12`, `-16`) and a |
| 1054 | /// shallower ARF (`-24`) both trade film A away for film B, so the top |
| 1055 | /// ARF keeps its `-32` and the mid its `-8`. A 16-picture mini-GOP is |
| 1056 | /// worse on all four -- the pyramid has exactly three levels, so one mid |
| 1057 | /// frame cannot carry fifteen leaves. |
| 1058 | /// |
| 1059 | /// Unlike the third level this is NOT gated on GOP length: the 12-frame |
| 1060 | /// gate improves on every row too (film A +38.5 / +8.2 -> +37.5 / +7.6, |
| 1061 | /// film B +58.2 / +26.5 -> +54.1 / +23.9, both bars rows down, the screen |
| 1062 | /// capture byte-identical). |
| 1063 | fn default() -> Self { |
| 1064 | Self { |
| 1065 | mini_gop: 8, |
| 1066 | arf_q_offset: -32, |
| 1067 | leaf_q_offset: 12, |
| 1068 | mid_q_offset: MID_DEFAULT, |
| 1069 | key_q_offset: KEY_DEFAULT, |
| 1070 | quarter_q_offset: QUARTER_DEFAULT, |
| 1071 | } |
| 1072 | } |
| 1073 | } |
| 1074 | |
| 1075 | /// Which level of the pyramid a coded frame sits at, reported on every |
| 1076 | /// [`Packet`] so a caller (and the BD gate's histogram) can tell them apart |
| 1077 | /// without parsing the frame headers back out. |
| 1078 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 1079 | pub enum Level { |
| 1080 | /// A key frame. |
| 1081 | Key, |
| 1082 | /// A hidden `ALTREF_FRAME`, coded ahead of its display position. |
| 1083 | Arf, |
| 1084 | /// A shown leaf. |
| 1085 | Leaf, |
| 1086 | /// A `show_existing_frame` header re-outputting a hidden frame: no coded |
| 1087 | /// pixels at all, four bits of header. |
| 1088 | ShowExisting, |
| 1089 | } |
| 1090 | |
| 1091 | /// The DPB slot the group anchors alternate between (see |
| 1092 | /// [`Av1Encoder::encode_frames`]): the hidden frame of group `g` refreshes |
| 1093 | /// `ANCHOR_SLOTS[(g + 1) % 2]`, which is the slot the leaves of group `g` |
| 1094 | /// name as `ALTREF_FRAME` and which group `g + 1` reads as its own anchor. |
| 1095 | /// Two slots alternate because a group's leaves must still be able to read |
| 1096 | /// the previous anchor while the new one is already written. |
| 1097 | const ANCHOR_SLOTS: [u8; 2] = [3, 4]; |
| 1098 | |
| 1099 | /// The slot the leaf chain refreshes and reads as `LAST_FRAME`. |
| 1100 | const LEAF_SLOT: u8 = 0; |
| 1101 | |
| 1102 | /// lane-last2: the two slots the leaf chain alternates its refresh between |
| 1103 | /// once [`last2`] is on, so that the shown frame BEFORE `LAST_FRAME` is still |
| 1104 | /// in the DPB and can be named `LAST2_FRAME`. Slot 7 is the one the key frame |
| 1105 | /// writes and nothing has ever read back, so this costs no other level a slot; |
| 1106 | /// leaf `k` refreshes `LEAF_SLOTS[k % 2]`, which is the slot leaf `k - 2` |
| 1107 | /// wrote -- read before write, spec 7.20's decode order. |
| 1108 | const LEAF_SLOTS: [u8; 2] = [LEAF_SLOT, 7]; |
| 1109 | |
| 1110 | /// Whether the leaf chain retains that second past picture and offers it to |
| 1111 | /// the block search as `LAST2_FRAME` (`EC_AV1_LAST2=0` / `=1`). The census |
| 1112 | /// that priced the lever is `lanes/refs.report.md` §1; what it buys on the |
| 1113 | /// gate is `lanes/last2.report.md`. |
| 1114 | fn last2() -> bool { |
| 1115 | match LAST2_OVERRIDE.load(std::sync::atomic::Ordering::Relaxed) { |
| 1116 | 0 => return false, |
| 1117 | 1 => return true, |
| 1118 | _ => {} |
| 1119 | } |
| 1120 | match std::env::var("EC_AV1_LAST2").ok() { |
| 1121 | Some(v) => v != "0", |
| 1122 | None => LAST2, |
| 1123 | } |
| 1124 | } |
| 1125 | |
| 1126 | /// A PROCESS-GLOBAL [`last2`] override that wins over the environment |
| 1127 | /// (`u8::MAX` = unset), the shape `crate::encode::set_frame_interp` has -- |
| 1128 | /// this crate's tests never call `set_var` (`crate::envflags`), so the |
| 1129 | /// witness turns the lever on through this while holding |
| 1130 | /// [`crate::speed::knob_write`]. |
| 1131 | static LAST2_OVERRIDE: std::sync::atomic::AtomicU8 = |
| 1132 | std::sync::atomic::AtomicU8::new(u8::MAX); |
| 1133 | |
| 1134 | /// Sets [`LAST2_OVERRIDE`]; `None` clears it. |
| 1135 | #[allow(dead_code)] // set only from the `#[cfg(test)]` witness |
| 1136 | pub(crate) fn set_last2(on: Option<bool>) { |
| 1137 | LAST2_OVERRIDE.store( |
| 1138 | on.map_or(u8::MAX, u8::from), |
| 1139 | std::sync::atomic::Ordering::Relaxed, |
| 1140 | ); |
| 1141 | } |
| 1142 | |
| 1143 | /// [`last2`]'s default. |
| 1144 | const LAST2: bool = false; |
| 1145 | |
| 1146 | /// The slot the mid-level hidden frame of a three-level group refreshes |
| 1147 | /// ([`Pyramid::mid_q_offset`]): free of the two anchors (3, 4), of the leaf |
| 1148 | /// chain (0) and of `GOLDEN_SLOT` (1), so all four levels are live at once. |
| 1149 | const MID_SLOT: u8 = 2; |
| 1150 | |
| 1151 | /// The two slots the QUARTER-POINT hidden frames refresh |
| 1152 | /// ([`Pyramid::quarter_q_offset`]). THE WHOLE SLOT MAP, with all four levels |
| 1153 | /// live at once: |
| 1154 | /// |
| 1155 | /// | slot | holds | written by | read as | |
| 1156 | /// |---|---|---|---| |
| 1157 | /// | 0 (`LEAF_SLOT`) | the previous shown leaf | every leaf | `LAST_FRAME` of the next leaf | |
| 1158 | /// | 1 (`GOLDEN_SLOT`) | the key frame | the key | `GOLDEN_FRAME` everywhere | |
| 1159 | /// | 2 (`MID_SLOT`) | the mid ARF | the mid ARF | `LAST_FRAME` / `ALTREF_FRAME` of the leaves and quarters around it | |
| 1160 | /// | 3, 4 (`ANCHOR_SLOTS`) | this group's anchor and the next one (the top ARF) | the key, each top ARF | anchor = `LAST_FRAME`, next = `ALTREF_FRAME` | |
| 1161 | /// | 5, 6 (`QUARTER_SLOTS`) | the first and second quarter ARF | the quarter ARFs | `LAST_FRAME` / `ALTREF_FRAME` of the leaves beside them | |
| 1162 | /// | 7 | unused (the key's copy is never read back) | the key | -- | |
| 1163 | /// |
| 1164 | /// A frame names exactly two of them plus `GOLDEN_SLOT` |
| 1165 | /// ([`Av1Encoder::encode_pyramid_inter`] fills all seven `ref_frame_idx` |
| 1166 | /// entries from `last_slot`/`altref_slot`), and `refresh_frame_flags` is the |
| 1167 | /// single `self_slot` bit, so no level ever overwrites a slot another level |
| 1168 | /// is still reading. |
| 1169 | const QUARTER_SLOTS: [u8; 2] = [5, 6]; |
| 1170 | |
| 1171 | /// [`Pyramid::default`]'s fourth level (`None` = the three-level pyramid). |
| 1172 | /// The long-GOP sweep's winner (`lanes/pyr6.sweep.txt`). |
| 1173 | const QUARTER_DEFAULT: Option<i16> = None; |
| 1174 | |
| 1175 | /// [`Pyramid::default`]'s third level (`None` = the two-level pyramid), the |
| 1176 | /// long-GOP sweep's winner (`lanes/pyr5.sweep.txt`): every one of the four |
| 1177 | /// long-GOP columns improves against the two-level shape, film B (the wider |
| 1178 | /// gap) by 6.0 / 2.4 BD points. |
| 1179 | const MID_DEFAULT: Option<i16> = Some(-8); |
| 1180 | |
| 1181 | /// [`Pyramid::default`]'s key-frame offset: the long-GOP sweep's winner |
| 1182 | /// (`lanes/keyq.sweep.txt`, 48 pictures, gop 48, BD-rate vs libaom cpu-used 6 |
| 1183 | /// / vs rav1e speed 6), which the 12-frame gate agrees with, so it is NOT |
| 1184 | /// gated on GOP length the way the third level is: |
| 1185 | /// |
| 1186 | /// | key offset | film A (48) | film B (48) | film A (12) | film B (12) | |
| 1187 | /// |---|---|---|---|---| |
| 1188 | /// | 0 (base q) | +52.0 / +11.7 | +144.5 / +44.3 | +43.3 / +15.0 | +66.9 / +35.1 | |
| 1189 | /// | -16 | +48.8 / +9.4 | +138.0 / +40.2 | | | |
| 1190 | /// | -32 | +45.3 / +6.7 | +132.8 / +36.8 | | | |
| 1191 | /// | -48 | +43.5 / +4.6 | +131.3 / +35.0 | +38.5 / +8.2 | +58.2 / +26.5 | |
| 1192 | /// | -64 | +44.9 / +3.8 | +140.7 / +37.5 | | | |
| 1193 | /// |
| 1194 | /// `-64` overshoots on film B, and a deeper ARF (`-40`) under the same key |
| 1195 | /// gives bytes back on both films (+44.4 / +5.1, +137.4 / +38.6), so what the |
| 1196 | /// group was short of is the ANCHOR, not more ARF. The bars rows move by |
| 1197 | /// 0.3 / 0.6 BD points and the screen capture is byte-identical (its pyramid |
| 1198 | /// is gated off). |
| 1199 | const KEY_DEFAULT: i16 = -48; |
| 1200 | |
| 1201 | /// Whether the pyramid path hands each frame a lookahead window, i.e. |
| 1202 | /// whether the temporal lambda map (`encode::tpl_lambda_factors`) runs on |
| 1203 | /// the DEFAULT stream at all. It did not until lane-arfcen: the pyramid |
| 1204 | /// reorders pictures, so this path passed `&[]` and the map -- measured and |
| 1205 | /// shipped on the flat path -- was inert on every frame of every pyramid |
| 1206 | /// stream, including the ARFs that carry 54% of a long-GOP stream's bytes |
| 1207 | /// (class `tool disabled in every gate recipe`). |
| 1208 | /// lane-arfpred: the top ARF source temporal filter's strength |
| 1209 | /// ([`crate::speed::ARF_TF`]), `EC_AV1_ARF_TF=<strength>` overriding it; |
| 1210 | /// `0` is off. |
| 1211 | fn arf_tf_strength() -> f64 { |
| 1212 | std::env::var("EC_AV1_ARF_TF") |
| 1213 | .ok() |
| 1214 | .and_then(|v| v.parse().ok()) |
| 1215 | .unwrap_or_else(|| crate::speed::at(&crate::speed::ARF_TF)) |
| 1216 | } |
| 1217 | |
| 1218 | /// lane-arftf: the same filter's strength on the MID ARF, whose own window |
| 1219 | /// is the display-FUTURE leaves of its group (`tpl_window(at, false)`). |
| 1220 | /// `EC_AV1_ARF_TF_MID=<strength>` overrides [`crate::speed::ARF_TF_MID`]; |
| 1221 | /// `0` is off. |
| 1222 | fn arf_tf_mid_strength() -> f64 { |
| 1223 | std::env::var("EC_AV1_ARF_TF_MID") |
| 1224 | .ok() |
| 1225 | .and_then(|v| v.parse().ok()) |
| 1226 | .unwrap_or_else(|| crate::speed::at(&crate::speed::ARF_TF_MID)) |
| 1227 | } |
| 1228 | |
| 1229 | /// lane-arftf: how many of the window's pictures the filter averages in |
| 1230 | /// ([`crate::speed::ARF_TF_WIN`], `EC_AV1_ARF_TF_WIN=<n>`). The top ARF's |
| 1231 | /// window holds only DISPLAY-PAST neighbours -- it is the group's last |
| 1232 | /// picture and the next group's sources are not buffered when it is coded -- |
| 1233 | /// so this widens the filter backwards only. |
| 1234 | pub(crate) fn arf_tf_window() -> usize { |
| 1235 | std::env::var("EC_AV1_ARF_TF_WIN") |
| 1236 | .ok() |
| 1237 | .and_then(|v| v.parse().ok()) |
| 1238 | .unwrap_or_else(|| crate::speed::at(&crate::speed::ARF_TF_WIN)) |
| 1239 | } |
| 1240 | |
| 1241 | /// lane-lookahead: how many DISPLAY-FUTURE neighbours the top ARF's filter |
| 1242 | /// takes out of the buffered next group ([`crate::speed::ARF_TF_WIN_FUT`], |
| 1243 | /// `EC_AV1_ARF_TF_WIN_FUT=<n>`). Inert without [`lookahead`]. |
| 1244 | pub(crate) fn arf_tf_window_future() -> usize { |
| 1245 | match ARF_TF_FUT_OVERRIDE.load(std::sync::atomic::Ordering::Relaxed) { |
| 1246 | usize::MAX => {} |
| 1247 | n => return n, |
| 1248 | } |
| 1249 | std::env::var("EC_AV1_ARF_TF_WIN_FUT") |
| 1250 | .ok() |
| 1251 | .and_then(|v| v.parse().ok()) |
| 1252 | .unwrap_or_else(|| crate::speed::at(&crate::speed::ARF_TF_WIN_FUT)) |
| 1253 | } |
| 1254 | |
| 1255 | /// PROCESS-GLOBAL overrides of the two lane-lookahead knobs, the shape |
| 1256 | /// [`set_last2`] has (this crate's tests never call `set_var`); `u8::MAX` / |
| 1257 | /// `usize::MAX` is unset, and a witness holds [`crate::speed::knob_write`] |
| 1258 | /// while it uses them. |
| 1259 | static LOOKAHEAD_OVERRIDE: std::sync::atomic::AtomicU8 = |
| 1260 | std::sync::atomic::AtomicU8::new(u8::MAX); |
| 1261 | static ARF_TF_FUT_OVERRIDE: std::sync::atomic::AtomicUsize = |
| 1262 | std::sync::atomic::AtomicUsize::new(usize::MAX); |
| 1263 | static TPL_FUT_OVERRIDE: std::sync::atomic::AtomicUsize = |
| 1264 | std::sync::atomic::AtomicUsize::new(usize::MAX); |
| 1265 | |
| 1266 | /// Sets [`LOOKAHEAD_OVERRIDE`]; `None` clears it. |
| 1267 | #[allow(dead_code)] // set only from the `#[cfg(test)]` witness |
| 1268 | pub(crate) fn set_lookahead(on: Option<bool>) { |
| 1269 | LOOKAHEAD_OVERRIDE.store( |
| 1270 | on.map_or(u8::MAX, u8::from), |
| 1271 | std::sync::atomic::Ordering::Relaxed, |
| 1272 | ); |
| 1273 | } |
| 1274 | |
| 1275 | /// Sets [`ARF_TF_FUT_OVERRIDE`]; `None` clears it. |
| 1276 | #[allow(dead_code)] // set only from the `#[cfg(test)]` witness |
| 1277 | pub(crate) fn set_arf_tf_future(n: Option<usize>) { |
| 1278 | ARF_TF_FUT_OVERRIDE.store(n.unwrap_or(usize::MAX), std::sync::atomic::Ordering::Relaxed); |
| 1279 | } |
| 1280 | |
| 1281 | /// Sets [`TPL_FUT_OVERRIDE`]; `None` clears it. |
| 1282 | #[allow(dead_code)] // set only from the `#[cfg(test)]` witness |
| 1283 | pub(crate) fn set_tpl_fut(n: Option<usize>) { |
| 1284 | TPL_FUT_OVERRIDE.store(n.unwrap_or(usize::MAX), std::sync::atomic::Ordering::Relaxed); |
| 1285 | } |
| 1286 | |
| 1287 | /// lane-tplfut: which window the TOP ARF's temporal lambda map propagates |
| 1288 | /// back through ([`crate::speed::TPL_FUT`], `EC_AV1_TPL_FUT=<n>`). Inert |
| 1289 | /// without [`lookahead`] -- mode 0 is the shipped past window. |
| 1290 | pub(crate) fn tpl_fut() -> usize { |
| 1291 | match TPL_FUT_OVERRIDE.load(std::sync::atomic::Ordering::Relaxed) { |
| 1292 | usize::MAX => {} |
| 1293 | n => return n, |
| 1294 | } |
| 1295 | std::env::var("EC_AV1_TPL_FUT") |
| 1296 | .ok() |
| 1297 | .and_then(|v| v.parse().ok()) |
| 1298 | .unwrap_or_else(|| crate::speed::at(&crate::speed::TPL_FUT)) |
| 1299 | } |
| 1300 | |
| 1301 | /// lane-tplhalf: mode 2's split -- how many display-PAST neighbours the top |
| 1302 | /// ARF's window opens with, the rest of the budget coming from the buffered |
| 1303 | /// future ([`crate::speed::TPL_FUT_HALF`], `EC_AV1_TPL_FUT_HALF=<n>`). |
| 1304 | pub(crate) fn tpl_fut_half() -> usize { |
| 1305 | std::env::var("EC_AV1_TPL_FUT_HALF") |
| 1306 | .ok() |
| 1307 | .and_then(|v| v.parse().ok()) |
| 1308 | .unwrap_or_else(|| crate::speed::at(&crate::speed::TPL_FUT_HALF)) |
| 1309 | } |
| 1310 | |
| 1311 | /// lane-tplhalf: how many entries mode 2's window holds in total, `0` meaning |
| 1312 | /// `tpl_depth() - 1` -- the ARF window's budget alone, so raising it does not |
| 1313 | /// deepen every other frame's lambda pass the way `EC_AV1_TPL_D` does |
| 1314 | /// ([`crate::speed::TPL_FUT_WIN`], `EC_AV1_TPL_FUT_WIN=<n>`). |
| 1315 | pub(crate) fn tpl_fut_win(depth: usize) -> usize { |
| 1316 | match std::env::var("EC_AV1_TPL_FUT_WIN") |
| 1317 | .ok() |
| 1318 | .and_then(|v| v.parse().ok()) |
| 1319 | .unwrap_or_else(|| crate::speed::at(&crate::speed::TPL_FUT_WIN)) |
| 1320 | { |
| 1321 | 0 => depth - 1, |
| 1322 | n => n, |
| 1323 | } |
| 1324 | } |
| 1325 | |
| 1326 | /// lane-lookahead: whether the pyramid path holds one group of lookahead |
| 1327 | /// ([`crate::speed::LOOKAHEAD`], `EC_AV1_LOOKAHEAD=0|1`). |
| 1328 | fn lookahead() -> bool { |
| 1329 | match LOOKAHEAD_OVERRIDE.load(std::sync::atomic::Ordering::Relaxed) { |
| 1330 | 0 => return false, |
| 1331 | 1 => return true, |
| 1332 | _ => {} |
| 1333 | } |
| 1334 | match std::env::var("EC_AV1_LOOKAHEAD").ok() { |
| 1335 | Some(v) => v != "0", |
| 1336 | None => crate::speed::LOOKAHEAD, |
| 1337 | } |
| 1338 | } |
| 1339 | |
| 1340 | fn tpl_pyramid() -> bool { |
| 1341 | match std::env::var("EC_AV1_TPL_PYRAMID").ok() { |
| 1342 | Some(v) => v != "0", |
| 1343 | None => TPL_PYRAMID, |
| 1344 | } |
| 1345 | } |
| 1346 | |
| 1347 | /// [`tpl_pyramid`]'s default. |
| 1348 | const TPL_PYRAMID: bool = true; |
| 1349 | |
| 1350 | /// Whether a group's TOP ARF names the ARF from TWO groups back as its own |
| 1351 | /// `ALTREF_FRAME` (lane-arfcen). It has always named `GOLDEN_SLOT` there, |
| 1352 | /// which for a top ARF is the key frame it already reads as `GOLDEN`, i.e. |
| 1353 | /// its second reference is the same picture as its first for the first group |
| 1354 | /// and adds nothing after: the ARF-vs-ARF census reads |
| 1355 | /// `LAST@-8 GOLDEN@-8` on our first ARF where rav1e's reads two DISTINCT |
| 1356 | /// anchors. The slot the ARF is about to refresh still holds that older |
| 1357 | /// anchor while this frame is coded, so naming it costs no extra DPB slot. |
| 1358 | fn arf_altref() -> bool { |
| 1359 | match std::env::var("EC_AV1_ARF_ALTREF").ok() { |
| 1360 | Some(v) => v != "0", |
| 1361 | None => ARF_ALTREF, |
| 1362 | } |
| 1363 | } |
| 1364 | |
| 1365 | /// [`arf_altref`]'s default. ON since its long-GOP arm: film A |
| 1366 | /// +42.8%/+4.5% -> +40.9%/+3.1% and film B +127.3%/+32.9% -> +125.6%/+32.0% |
| 1367 | /// (BD vs libaom cpu-used 6 / vs rav1e speed 6), i.e. both films down on both |
| 1368 | /// columns. |
| 1369 | const ARF_ALTREF: bool = true; |
| 1370 | |
| 1371 | /// The AV1 software encoder: [`EncoderConfig`] in, one [`Packet`] out per |
| 1372 | /// [`Av1Encoder::encode`] call — or, with a [`Pyramid`] configured, a |
| 1373 | /// coding-order burst of them per [`Av1Encoder::encode_frames`] call plus a |
| 1374 | /// [`Av1Encoder::flush`] at the end of the stream. |
| 1375 | #[derive(Debug)] |
| 1376 | pub struct Av1Encoder { |
| 1377 | config: EncoderConfig, |
| 1378 | color_config: ColorConfig, |
| 1379 | /// The previous picture's own (padded, uncropped) reconstruction — what |
| 1380 | /// the next inter frame predicts from — or `None` right after a key |
| 1381 | /// frame's turn comes up again, where it is about to be replaced rather |
| 1382 | /// than read. |
| 1383 | reference: Option<Picture>, |
| 1384 | next_index: u64, |
| 1385 | /// `Some` only when constructed via |
| 1386 | /// [`Av1Encoder::with_rate_target`]`(_, RateTarget::BytesPerFrame(_))`; |
| 1387 | /// otherwise every picture is coded at `config.base_q_idx`, unchanged |
| 1388 | /// from before this field existed. |
| 1389 | rate_loop: Option<RateLoop>, |
| 1390 | /// This stream's decode-side per-frame state, owned here so `encode` |
| 1391 | /// keeps the public signature it had before the state stopped being |
| 1392 | /// thread-local. One per encoder, never per frame: several of its fields |
| 1393 | /// (the inter-frame inheritance guards) carry state ACROSS frames. |
| 1394 | fctx: crate::decode::FrameCtx, |
| 1395 | /// What the last coded frame stored into the reference slot the next |
| 1396 | /// inter frame reads (spec 7.20): the tables that frame's tile writer |
| 1397 | /// must start from, since the header leaves |
| 1398 | /// `disable_frame_end_update_cdf` off. `None` before the first frame. |
| 1399 | carried_cdfs: Option<crate::encode::CdfSnapshot>, |
| 1400 | /// The last key frame's own (padded) reconstruction: `GOLDEN_FRAME`, |
| 1401 | /// which stays in DPB slot 1 until the next key frame refreshes it. |
| 1402 | golden: Option<Picture>, |
| 1403 | /// The frame two back: `ALTREF_FRAME`, in the slot the next frame is |
| 1404 | /// about to refresh (`encode_inter_frame`'s 0/2 alternation). |
| 1405 | prev2: Option<Picture>, |
| 1406 | /// `Some` puts the encoder in pyramid mode: [`Av1Encoder::encode`] then |
| 1407 | /// refuses (a picture no longer maps to one packet) and the state below |
| 1408 | /// drives coding order. |
| 1409 | pyramid: Option<Pyramid>, |
| 1410 | /// The eight DPB slots, modelled exactly as the decoder does (spec 7.20): |
| 1411 | /// what picture each holds, the order hint it was coded at, and the CDF |
| 1412 | /// tables it stored. Only pyramid mode reads these; the flat path keeps |
| 1413 | /// `reference`/`golden`/`prev2` so its bytes are unchanged. |
| 1414 | dpb: [Option<DpbSlot>; 8], |
| 1415 | /// Pictures held back waiting for their mini-GOP's hidden frame. |
| 1416 | pending: Vec<(u64, Picture)>, |
| 1417 | /// lane-lookahead: the CLOSED group waiting for the next group's sources |
| 1418 | /// before it is coded, so its top ARF -- the group's last picture in |
| 1419 | /// display order -- has display-future neighbours available. Always empty |
| 1420 | /// with [`lookahead`] off. |
| 1421 | ready: Vec<(u64, Picture)>, |
| 1422 | /// The flat path's delay queue: pictures whose packets later calls |
| 1423 | /// return, each coded with the ones behind it as its lookahead window |
| 1424 | /// (lane-av1facade, deepened to [`crate::encode::tpl_depth`] - 1 on |
| 1425 | /// lane-av1tpl2). Unused in pyramid mode, which buffers in `pending`. |
| 1426 | held: std::collections::VecDeque<Picture>, |
| 1427 | /// Which of [`ANCHOR_SLOTS`] the group about to be coded reads as its |
| 1428 | /// anchor. |
| 1429 | anchor: usize, |
| 1430 | /// lane-last2: the [`LEAF_SLOTS`] the last two SHOWN leaves refreshed, |
| 1431 | /// most recent first, across mini-GOP boundaries (the first leaf of a |
| 1432 | /// group reads the anchor as `LAST_FRAME`, so its `LAST2_FRAME` is the |
| 1433 | /// previous group's last leaf). Cleared by every key frame. |
| 1434 | leaf_hist: Vec<u8>, |
| 1435 | /// Coding-order position of the next packet — a packet's `dts`. |
| 1436 | next_dts: u64, |
| 1437 | /// Set by [`Av1Encoder::encode_sequence_pyramid`]: every coded frame's |
| 1438 | /// own cropped [`Encoded`] (its display position and its reconstruction), |
| 1439 | /// which is what [`crate::encode::EncodedSequence`] carries and a packet |
| 1440 | /// does not. `None` for every other caller, which pays nothing for it. |
| 1441 | collected: Option<Vec<(u64, Encoded)>>, |
| 1442 | } |
| 1443 | |
| 1444 | /// One decoded-picture-buffer slot: what a `refresh_frame_flags` bit stores |
| 1445 | /// and what a `ref_frame_idx` entry reads back. |
| 1446 | #[derive(Debug, Clone)] |
| 1447 | struct DpbSlot { |
| 1448 | picture: Picture, |
| 1449 | order_hint: u32, |
| 1450 | cdfs: crate::encode::CdfSnapshot, |
| 1451 | } |
| 1452 | |
| 1453 | /// The encoder stays `Send` now that it owns a `FrameCtx` (whose cells are |
| 1454 | /// `Send` but `!Sync`): it can move to another thread, it just cannot be |
| 1455 | /// shared by reference across threads. |
| 1456 | const _: fn() = || { |
| 1457 | fn assert_send<T: Send>() {} |
| 1458 | assert_send::<Av1Encoder>(); |
| 1459 | }; |
| 1460 | |
| 1461 | impl Av1Encoder { |
| 1462 | /// [`Av1Encoder::new`] at a SPEED PRESET (`speed` 0..=10, rav1e's scale: |
| 1463 | /// 0 is the full search this encoder has always run and is byte for byte |
| 1464 | /// identical to [`Av1Encoder::new`]; higher presets switch search levers |
| 1465 | /// off, [`crate::speed::levers`] naming which). |
| 1466 | /// |
| 1467 | /// The preset is process-global (the tile search reads it from worker |
| 1468 | /// threads -- see [`crate::speed`]), so it is set here for every encode |
| 1469 | /// that follows on this process, and two encoders at different speeds |
| 1470 | /// must not run concurrently. `EC_AV1_SPEED=<n>` is the same knob for a |
| 1471 | /// caller that does not construct the encoder itself. |
| 1472 | /// |
| 1473 | /// # Errors |
| 1474 | /// [`Av1Encoder::new`]'s. |
| 1475 | pub fn with_speed(config: EncoderConfig, speed: u8) -> Result<Self> { |
| 1476 | crate::speed::set_speed(speed); |
| 1477 | Self::new(config) |
| 1478 | } |
| 1479 | |
| 1480 | /// # Errors |
| 1481 | /// Returns an error when `config.width`/`config.height` are zero, odd, |
| 1482 | /// or larger than the 16-bit frame size an AV1 sequence header carries, |
| 1483 | /// or when `config.gop` is zero (there would be no picture to code the |
| 1484 | /// next key frame from a cadence of). |
| 1485 | pub fn new(config: EncoderConfig) -> Result<Self> { |
| 1486 | if config.gop == 0 { |
| 1487 | return Err(Error::unsupported("AV1 encode", "gop must be at least 1")); |
| 1488 | } |
| 1489 | // Validate the geometry the same way the picture-level entry points |
| 1490 | // do, before the first `encode()` call rather than only surfacing it |
| 1491 | // then. |
| 1492 | Picture::grey(config.width, config.height).check_even()?; |
| 1493 | // A tile is a whole number of superblocks, so a frame cannot carry |
| 1494 | // more tile columns (rows) than it has 64x64 superblocks across |
| 1495 | // (down) -- the header's own `max_log2_tile_cols` bound (spec |
| 1496 | // 5.9.15), refused here rather than at the first `encode()` call. |
| 1497 | let sb_cols = config.width.div_ceil(64) as u32; |
| 1498 | let sb_rows = config.height.div_ceil(64) as u32; |
| 1499 | if (1u32 << config.tile_cols_log2) > sb_cols || (1u32 << config.tile_rows_log2) > sb_rows { |
| 1500 | return Err(Error::unsupported( |
| 1501 | "AV1 encode", |
| 1502 | format!( |
| 1503 | "{}x{} tiles need more than the {sb_cols}x{sb_rows} superblocks this frame has", |
| 1504 | 1 << config.tile_cols_log2, |
| 1505 | 1 << config.tile_rows_log2 |
| 1506 | ), |
| 1507 | )); |
| 1508 | } |
| 1509 | Ok(Self { |
| 1510 | carried_cdfs: None, |
| 1511 | golden: None, |
| 1512 | prev2: None, |
| 1513 | color_config: config.colour.color_config(), |
| 1514 | config, |
| 1515 | reference: None, |
| 1516 | next_index: 0, |
| 1517 | rate_loop: None, |
| 1518 | fctx: crate::decode::FrameCtx::for_encoder(), |
| 1519 | pyramid: None, |
| 1520 | dpb: [const { None }; 8], |
| 1521 | pending: Vec::new(), |
| 1522 | ready: Vec::new(), |
| 1523 | held: std::collections::VecDeque::new(), |
| 1524 | anchor: 0, |
| 1525 | leaf_hist: Vec::new(), |
| 1526 | next_dts: 0, |
| 1527 | collected: None, |
| 1528 | }) |
| 1529 | } |
| 1530 | |
| 1531 | /// [`Av1Encoder::new`] in pyramid mode: pictures are coded out of display |
| 1532 | /// order, so a call to [`Av1Encoder::encode_frames`] returns zero, one or |
| 1533 | /// several packets and [`Av1Encoder::flush`] drains whatever is still |
| 1534 | /// held at the end of the stream. [`Av1Encoder::encode`]'s one-in-one-out |
| 1535 | /// contract cannot hold here and it returns an error instead; a caller |
| 1536 | /// that wants the old shape simply does not call this constructor. |
| 1537 | /// |
| 1538 | /// # Errors |
| 1539 | /// As [`Av1Encoder::new`], plus a `mini_gop` below 2 (no leaf would be |
| 1540 | /// left between the anchor and the hidden frame) or above `config.gop` |
| 1541 | /// (the group would straddle a key frame). |
| 1542 | pub fn with_pyramid(config: EncoderConfig, pyramid: Pyramid) -> Result<Self> { |
| 1543 | if pyramid.mini_gop < 2 { |
| 1544 | return Err(Error::unsupported( |
| 1545 | "AV1 encode", |
| 1546 | "a pyramid mini-GOP is at least 2 pictures", |
| 1547 | )); |
| 1548 | } |
| 1549 | let mut encoder = Self::new(config)?; |
| 1550 | encoder.pyramid = Some(pyramid); |
| 1551 | Ok(encoder) |
| 1552 | } |
| 1553 | |
| 1554 | /// [`Av1Encoder::new`], but `rate` picks `base_q_idx` (or steers it, |
| 1555 | /// frame by frame, for [`RateTarget::BytesPerFrame`]) instead of |
| 1556 | /// `config.base_q_idx` being used as-is. |
| 1557 | /// |
| 1558 | /// # Errors |
| 1559 | /// Same as [`Av1Encoder::new`]. |
| 1560 | pub fn with_rate_target(mut config: EncoderConfig, rate: RateTarget) -> Result<Self> { |
| 1561 | let rate_loop = rate.into_loop(&mut config, None); |
| 1562 | let mut encoder = Self::new(config)?; |
| 1563 | encoder.rate_loop = rate_loop; |
| 1564 | Ok(encoder) |
| 1565 | } |
| 1566 | |
| 1567 | /// [`Av1Encoder::with_pyramid`] and [`Av1Encoder::with_rate_target`] at |
| 1568 | /// once: the rate loop then keeps a separate quantizer per pyramid level, |
| 1569 | /// predicting each frame's size from the previous frame of its OWN level |
| 1570 | /// (a leaf and a hidden `ALTREF` differ by several times in size, so one |
| 1571 | /// shared predictor would swing the quantizer every frame). |
| 1572 | /// |
| 1573 | /// # Errors |
| 1574 | /// As both. |
| 1575 | pub fn with_pyramid_and_rate_target( |
| 1576 | mut config: EncoderConfig, |
| 1577 | pyramid: Pyramid, |
| 1578 | rate: RateTarget, |
| 1579 | ) -> Result<Self> { |
| 1580 | let rate_loop = rate.into_loop(&mut config, Some(pyramid)); |
| 1581 | let mut encoder = Self::with_pyramid(config, pyramid)?; |
| 1582 | encoder.rate_loop = rate_loop; |
| 1583 | Ok(encoder) |
| 1584 | } |
| 1585 | |
| 1586 | /// The [`Pyramid`] this stream is actually coding under: what |
| 1587 | /// [`Av1Encoder::with_pyramid`] asked for, or `None` once the content gate |
| 1588 | /// in [`Av1Encoder::encode_frames`] has dropped a screen-content stream |
| 1589 | /// back to the flat path. Meaningful after the first picture has been |
| 1590 | /// handed in. |
| 1591 | #[must_use] |
| 1592 | pub fn pyramid(&self) -> Option<Pyramid> { |
| 1593 | self.pyramid |
| 1594 | } |
| 1595 | |
| 1596 | /// The coded (padded-to-64) frame size every picture in this stream is |
| 1597 | /// coded at — what a decoder allocates and what `ffprobe` reports. |
| 1598 | #[must_use] |
| 1599 | pub fn coded_size(&self) -> (usize, usize) { |
| 1600 | ( |
| 1601 | self.config.width.next_multiple_of(SUPERBLOCK), |
| 1602 | self.config.height.next_multiple_of(SUPERBLOCK), |
| 1603 | ) |
| 1604 | } |
| 1605 | |
| 1606 | /// The display (render) size every frame header signals — [`EncoderConfig`]'s |
| 1607 | /// own `width`/`height`, always, whatever the coded size pads it to. |
| 1608 | #[must_use] |
| 1609 | pub fn display_size(&self) -> (usize, usize) { |
| 1610 | (self.config.width, self.config.height) |
| 1611 | } |
| 1612 | |
| 1613 | /// Takes one picture and returns the PREVIOUS picture's packet, key or |
| 1614 | /// inter by this stream's `gop` cadence — the facade's one frame of |
| 1615 | /// latency (the picture just handed in is what the previous one is coded |
| 1616 | /// against as its lookahead). The FIRST call has no previous picture and |
| 1617 | /// returns a packet with an EMPTY `data` (its other fields are |
| 1618 | /// placeholders; test `data.is_empty()`), and the last picture's packet |
| 1619 | /// comes out of [`Av1Encoder::flush`] — so a caller that concatenates |
| 1620 | /// `data` in call order still gets the whole stream, provided it flushes |
| 1621 | /// at the end. |
| 1622 | /// |
| 1623 | /// # Errors |
| 1624 | /// Returns an error when `picture`'s size does not match |
| 1625 | /// [`EncoderConfig::width`]/[`EncoderConfig::height`], when the encoder |
| 1626 | /// was built by [`Av1Encoder::with_pyramid`] (which reorders pictures, so |
| 1627 | /// one call cannot return one packet), or under the same conditions |
| 1628 | /// [`crate::encode::encode_key_frame`]/[`crate::encode::encode_sequence`] |
| 1629 | /// do. |
| 1630 | pub fn encode(&mut self, picture: &Picture) -> Result<Packet> { |
| 1631 | if self.pyramid.is_some() { |
| 1632 | return Err(Error::unsupported( |
| 1633 | "AV1 encode", |
| 1634 | "a pyramid stream reorders pictures -- use encode_frames()/flush()", |
| 1635 | )); |
| 1636 | } |
| 1637 | let mut packets = self.encode_frames(picture)?; |
| 1638 | Ok(packets.pop().unwrap_or(Packet { |
| 1639 | data: Vec::new(), |
| 1640 | key: false, |
| 1641 | order: 0, |
| 1642 | dts: 0, |
| 1643 | level: Level::Leaf, |
| 1644 | })) |
| 1645 | } |
| 1646 | |
| 1647 | /// Takes one picture and returns every packet it completed, in coding |
| 1648 | /// order. Without a [`Pyramid`] that is one packet — the PREVIOUS |
| 1649 | /// picture's, since this one is its lookahead — and none at all on the |
| 1650 | /// first call; with one it is |
| 1651 | /// empty for most pictures and a whole mini-GOP's worth (the hidden |
| 1652 | /// frame, its leaves and the `show_existing_frame` that re-outputs it) |
| 1653 | /// for the picture that closes a group. |
| 1654 | /// |
| 1655 | /// # Errors |
| 1656 | /// As [`Av1Encoder::encode`], minus the pyramid refusal. |
| 1657 | pub fn encode_frames(&mut self, picture: &Picture) -> Result<Vec<Packet>> { |
| 1658 | crate::encode::arm_tiles(self.config.tile_cols_log2, self.config.tile_rows_log2); |
| 1659 | // lane-split: the split census prints on every exit of this call when |
| 1660 | // armed, so no `return` path loses it; the counters are cumulative, so |
| 1661 | // the last table a run prints is that run's total. |
| 1662 | struct SplitCensusDump; |
| 1663 | impl Drop for SplitCensusDump { |
| 1664 | fn drop(&mut self) { |
| 1665 | if crate::encode::split_census_on() { |
| 1666 | crate::encode::dump_split_census(); |
| 1667 | } |
| 1668 | if crate::encode::newmv_census_on() { |
| 1669 | crate::encode::dump_newmv_census(); |
| 1670 | } |
| 1671 | } |
| 1672 | } |
| 1673 | // `then_some` would CONSTRUCT the guard eagerly and drop it when the |
| 1674 | // flag is off, which runs `Drop` -- and printed the census header on |
| 1675 | // every unarmed encode. `then` builds it only when armed. |
| 1676 | let _census = (crate::encode::split_census_on() || crate::encode::newmv_census_on()) |
| 1677 | .then(|| SplitCensusDump); |
| 1678 | if (picture.width, picture.height) != (self.config.width, self.config.height) { |
| 1679 | return Err(Error::unsupported( |
| 1680 | "AV1 encode", |
| 1681 | format!( |
| 1682 | "picture is {}x{}, encoder is {}x{}", |
| 1683 | picture.width, picture.height, self.config.width, self.config.height |
| 1684 | ), |
| 1685 | )); |
| 1686 | } |
| 1687 | // THE CONTENT GATE (lane-av1pyrgate): the pyramid is for camera |
| 1688 | // material. A desktop capture is the one content class every pyramid |
| 1689 | // sweep measured WORSE under it, and it is exactly the class the |
| 1690 | // screen detector separates (`encode::screen_content`: 0/48 frames on |
| 1691 | // both real films, 48/48 on the OBS capture), so a stream whose first |
| 1692 | // picture reads as screen content drops back to the flat path and |
| 1693 | // codes byte for byte what it coded before the pyramid existed. |
| 1694 | // |
| 1695 | // Decided ONCE, on the first picture, not per mini-GOP: the flat path |
| 1696 | // keeps its references in `reference`/`golden`/`prev2` and the pyramid |
| 1697 | // path in `dpb`, so a switch after the first frame would read slots |
| 1698 | // the other path never filled. Per-GOP re-decision needs the two |
| 1699 | // reference sets kept in step first; the gate's own recipe codes one |
| 1700 | // GOP per stream, where the two are the same decision. |
| 1701 | if self.pyramid.is_some() |
| 1702 | && self.next_index == 0 |
| 1703 | && crate::encode::picture_is_screen(picture) |
| 1704 | { |
| 1705 | self.pyramid = None; |
| 1706 | } |
| 1707 | let Some(pyramid) = self.pyramid else { |
| 1708 | // The delay queue: the pictures behind this one are the |
| 1709 | // lookahead window the one at its head is coded with, which is |
| 1710 | // what makes the facade's bytes identical to |
| 1711 | // `encode_sequence`'s (lane-av1facade, lane-av1tpl2). |
| 1712 | self.held.push_back(picture.clone()); |
| 1713 | if self.held.len() <= crate::encode::tpl_depth() - 1 { |
| 1714 | return Ok(Vec::new()); |
| 1715 | } |
| 1716 | let previous = self.held.pop_front().expect("queue is over depth"); |
| 1717 | let window: Vec<Picture> = self.held.iter().cloned().collect(); |
| 1718 | return Ok(vec![self.encode_flat(&previous, &window)?]); |
| 1719 | }; |
| 1720 | let order = self.next_index; |
| 1721 | self.next_index += 1; |
| 1722 | if order.is_multiple_of(self.config.gop as u64) { |
| 1723 | // A key frame closes whatever group is open (there is nothing for |
| 1724 | // its leaves to point forward at across the boundary) and then |
| 1725 | // restarts the pyramid from the key itself. |
| 1726 | let mut packets = self.drain_all(Some(picture))?; |
| 1727 | packets.push(self.encode_key(order, picture)?); |
| 1728 | return Ok(packets); |
| 1729 | } |
| 1730 | self.pending.push((order, picture.clone())); |
| 1731 | // The group closes on the size the LAYOUT gives it (which depends on |
| 1732 | // how many pictures are left before the next key frame, so no short |
| 1733 | // tail group is left behind), or early when the next picture would be |
| 1734 | // a key frame. |
| 1735 | let run_start = self.pending[0].0; |
| 1736 | let remaining = self.config.gop - (run_start % self.config.gop as u64) as usize; |
| 1737 | let next_is_key = (order + 1).is_multiple_of(self.config.gop as u64); |
| 1738 | if self.pending.len() >= group_target(remaining, pyramid.mini_gop, absorb_tail()) |
| 1739 | || next_is_key |
| 1740 | { |
| 1741 | return self.drain_pending(); |
| 1742 | } |
| 1743 | Ok(Vec::new()) |
| 1744 | } |
| 1745 | |
| 1746 | /// Codes and returns every picture still held back — the last picture of |
| 1747 | /// a flat stream (which has no lookahead and is coded without one), or |
| 1748 | /// the tail of a pyramid stream whose last mini-GOP never filled up. |
| 1749 | /// Empty once there is nothing held. |
| 1750 | /// |
| 1751 | /// # Errors |
| 1752 | /// As [`Av1Encoder::encode_frames`]. |
| 1753 | pub fn flush(&mut self) -> Result<Vec<Packet>> { |
| 1754 | crate::encode::arm_tiles(self.config.tile_cols_log2, self.config.tile_rows_log2); |
| 1755 | if !self.held.is_empty() { |
| 1756 | let mut packets = Vec::with_capacity(self.held.len()); |
| 1757 | while let Some(previous) = self.held.pop_front() { |
| 1758 | let window: Vec<Picture> = self.held.iter().cloned().collect(); |
| 1759 | packets.push(self.encode_flat(&previous, &window)?); |
| 1760 | } |
| 1761 | return Ok(packets); |
| 1762 | } |
| 1763 | self.drain_all(None) |
| 1764 | } |
| 1765 | |
| 1766 | /// The flat path: one picture and its lookahead (the next source picture, |
| 1767 | /// `None` at the end of the stream) in, one packet out — the same inputs |
| 1768 | /// [`crate::encode::encode_sequence`] gives each of its inter frames, so |
| 1769 | /// the bytes are identical. |
| 1770 | fn encode_flat(&mut self, picture: &Picture, lookahead: &[Picture]) -> Result<Packet> { |
| 1771 | let render = (self.config.width, self.config.height); |
| 1772 | let padded = picture.padded_to(SUPERBLOCK); |
| 1773 | let is_key = self.next_index.is_multiple_of(self.config.gop as u64); |
| 1774 | let order = self.next_index; |
| 1775 | let base_q_idx = self.rate_loop.as_ref().map_or(self.config.base_q_idx, |r| { |
| 1776 | r.q_idx(if is_key { Level::Key } else { Level::Leaf }) |
| 1777 | }); |
| 1778 | |
| 1779 | let encoded: Encoded = if is_key { |
| 1780 | encode_key_frame_inner( |
| 1781 | &padded, |
| 1782 | base_q_idx, |
| 1783 | DEADZONE, |
| 1784 | &KEY_FRAME_MODES, |
| 1785 | split_blocks(), |
| 1786 | render, |
| 1787 | self.color_config, |
| 1788 | &self.fctx, |
| 1789 | )? |
| 1790 | } else { |
| 1791 | let reference = self.reference.as_ref().ok_or_else(|| { |
| 1792 | Error::unsupported( |
| 1793 | "AV1 encode", |
| 1794 | "an inter frame needs a previous reconstruction", |
| 1795 | ) |
| 1796 | })?; |
| 1797 | encode_inter_frame( |
| 1798 | &padded, |
| 1799 | reference, |
| 1800 | base_q_idx, |
| 1801 | DEADZONE, |
| 1802 | order as u32, |
| 1803 | // The flat path's own slot plan, in order hints: the key frame |
| 1804 | // of the GOP this picture sits in is what `GOLDEN_FRAME` |
| 1805 | // names, and every reference but `ALTREF_FRAME` is the frame |
| 1806 | // just coded. |
| 1807 | crate::encode::flat_order_hints( |
| 1808 | order as u32 & 0x7f, |
| 1809 | (order - order % self.config.gop as u64) as u32 & 0x7f, |
| 1810 | self.prev2.is_some(), |
| 1811 | ), |
| 1812 | render, |
| 1813 | self.carried_cdfs.as_ref().map(|c| &c.0), |
| 1814 | self.golden.as_ref(), |
| 1815 | self.prev2.as_ref(), |
| 1816 | None, |
| 1817 | &self.fctx, |
| 1818 | None, |
| 1819 | &lookahead.iter().map(|n| n.padded_to(SUPERBLOCK)).collect::<Vec<_>>(), |
| 1820 | )? |
| 1821 | }; |
| 1822 | |
| 1823 | self.carried_cdfs = Some(encoded.next_cdfs.clone()); |
| 1824 | if is_key { |
| 1825 | self.golden = Some(encoded.reconstruction.clone()); |
| 1826 | self.prev2 = None; |
| 1827 | } else { |
| 1828 | self.prev2 = self.reference.take(); |
| 1829 | } |
| 1830 | self.reference = Some(encoded.reconstruction.clone()); |
| 1831 | self.next_index += 1; |
| 1832 | let cropped = crop_encoded(&encoded, render.0, render.1); |
| 1833 | let level = if is_key { Level::Key } else { Level::Leaf }; |
| 1834 | if let Some(rate_loop) = self.rate_loop.as_mut() { |
| 1835 | // The flat path codes every frame at the slot's own q, no offset. |
| 1836 | rate_loop.update(level, 0, i16::from(base_q_idx), cropped.stream.len()); |
| 1837 | } |
| 1838 | Ok(self.packet(cropped.stream, is_key, order, level)) |
| 1839 | } |
| 1840 | |
| 1841 | /// THE SHARED MINI-GOP DRIVER: codes a whole sequence — one key frame |
| 1842 | /// then all inter, which is [`crate::encode::encode_sequence`]'s only |
| 1843 | /// shape — through this very facade, under `pyramid`, and hands back what |
| 1844 | /// that path returns. The two are byte-identical BY CONSTRUCTION rather |
| 1845 | /// than by a mirrored second implementation: there is one reordering, |
| 1846 | /// one DPB/slot policy and one set of per-level quantizer offsets, here |
| 1847 | /// (`encoder::tests::the_facade_codes_the_same_bytes_as_encode_sequence` |
| 1848 | /// still pins it, now over a pyramid sequence too). |
| 1849 | /// |
| 1850 | /// The content gate lives in [`Av1Encoder::encode_frames`] and applies |
| 1851 | /// unchanged, so a screen-content clip handed in here codes flat. |
| 1852 | /// |
| 1853 | /// `EncodedSequence::frames` comes back in DISPLAY order, one entry per |
| 1854 | /// source picture — the order the flat path's coding order happens to be, |
| 1855 | /// and the order every reader of it (the BD gate's sample-exactness |
| 1856 | /// assertions against a decoder's output) needs. `stream` stays in coding |
| 1857 | /// order, which is the order a decoder reads. |
| 1858 | /// |
| 1859 | /// # Errors |
| 1860 | /// As [`Av1Encoder::encode_frames`]. |
| 1861 | pub(crate) fn encode_sequence_pyramid( |
| 1862 | pictures: &[Picture], |
| 1863 | base_q_idx: u8, |
| 1864 | pyramid: Pyramid, |
| 1865 | tiles: (u32, u32), |
| 1866 | ) -> Result<crate::encode::EncodedSequence> { |
| 1867 | let first = pictures.first().ok_or_else(|| { |
| 1868 | Error::unsupported("AV1 encode", "a sequence needs at least one picture") |
| 1869 | })?; |
| 1870 | let config = EncoderConfig { |
| 1871 | width: first.width, |
| 1872 | height: first.height, |
| 1873 | base_q_idx, |
| 1874 | // One key frame, at picture 0, and inter for the rest. |
| 1875 | gop: pictures.len().max(1), |
| 1876 | // `encode_sequence` writes an unspecified colour config. |
| 1877 | colour: Colour::Unspecified, |
| 1878 | tile_cols_log2: tiles.0, |
| 1879 | tile_rows_log2: tiles.1, |
| 1880 | }; |
| 1881 | let mut encoder = Self::with_pyramid(config, pyramid)?; |
| 1882 | encoder.collected = Some(Vec::with_capacity(pictures.len())); |
| 1883 | let mut stream = Vec::new(); |
| 1884 | for picture in pictures { |
| 1885 | for packet in encoder.encode_frames(picture)? { |
| 1886 | stream.extend_from_slice(&packet.data); |
| 1887 | } |
| 1888 | } |
| 1889 | for packet in encoder.flush()? { |
| 1890 | stream.extend_from_slice(&packet.data); |
| 1891 | } |
| 1892 | let mut collected = encoder.collected.take().expect("collecting"); |
| 1893 | // Every source picture is coded exactly once, so a frame's display |
| 1894 | // order IS its index once the list is sorted by it. |
| 1895 | let coding_order: Vec<usize> = |
| 1896 | collected.iter().map(|(order, _)| *order as usize).collect(); |
| 1897 | collected.sort_by_key(|(order, _)| *order); |
| 1898 | let frames: Vec<Encoded> = collected.into_iter().map(|(_, encoded)| encoded).collect(); |
| 1899 | assert!( |
| 1900 | coding_order.iter().all(|&i| i < frames.len()), |
| 1901 | "a coded frame's display position is outside the sequence" |
| 1902 | ); |
| 1903 | Ok(crate::encode::EncodedSequence { stream, frames, coding_order }) |
| 1904 | } |
| 1905 | |
| 1906 | /// Stamps a packet with its display and coding positions and advances the |
| 1907 | /// coding-order clock. |
| 1908 | fn packet(&mut self, data: Vec<u8>, key: bool, order: u64, level: Level) -> Packet { |
| 1909 | let dts = self.next_dts; |
| 1910 | self.next_dts += 1; |
| 1911 | Packet { |
| 1912 | data, |
| 1913 | key, |
| 1914 | order, |
| 1915 | dts, |
| 1916 | level, |
| 1917 | } |
| 1918 | } |
| 1919 | |
| 1920 | /// Stores a coded frame into every DPB slot its `refresh_frame_flags` |
| 1921 | /// names (spec 7.20). |
| 1922 | fn refresh(&mut self, slots: &[u8], encoded: &Encoded, order_hint: u32) { |
| 1923 | let slot = DpbSlot { |
| 1924 | picture: encoded.reconstruction.clone(), |
| 1925 | order_hint, |
| 1926 | cdfs: encoded.next_cdfs.clone(), |
| 1927 | }; |
| 1928 | for &s in slots { |
| 1929 | self.dpb[s as usize] = Some(slot.clone()); |
| 1930 | } |
| 1931 | } |
| 1932 | |
| 1933 | /// Codes a key frame in pyramid mode: it refreshes all eight slots, so it |
| 1934 | /// becomes the anchor, the `GOLDEN_FRAME` and the CDF source for the |
| 1935 | /// whole GOP at once. |
| 1936 | fn encode_key(&mut self, order: u64, picture: &Picture) -> Result<Packet> { |
| 1937 | let render = (self.config.width, self.config.height); |
| 1938 | let base = self |
| 1939 | .rate_loop |
| 1940 | .as_ref() |
| 1941 | .map_or(i16::from(self.config.base_q_idx), |r| i16::from(r.q_idx(Level::Key))); |
| 1942 | let offset = self.pyramid.map_or(0, |p| p.key_q_offset); |
| 1943 | let base_q_idx = (base + offset).clamp(1, 255) as u8; |
| 1944 | let encoded = encode_key_frame_inner( |
| 1945 | &picture.padded_to(SUPERBLOCK), |
| 1946 | base_q_idx, |
| 1947 | DEADZONE, |
| 1948 | &KEY_FRAME_MODES, |
| 1949 | split_blocks(), |
| 1950 | render, |
| 1951 | self.color_config, |
| 1952 | &self.fctx, |
| 1953 | )?; |
| 1954 | self.refresh(&[0, 1, 2, 3, 4, 5, 6, 7], &encoded, 0); |
| 1955 | self.anchor = 0; |
| 1956 | // Every leaf slot now holds the key frame, which `GOLDEN_FRAME` |
| 1957 | // already names: the chain starts empty again. |
| 1958 | self.leaf_hist.clear(); |
| 1959 | let cropped = crop_encoded(&encoded, render.0, render.1); |
| 1960 | if let Some(rate_loop) = self.rate_loop.as_mut() { |
| 1961 | rate_loop.update(Level::Key, 0, base + offset, cropped.stream.len()); |
| 1962 | } |
| 1963 | if let Some(collected) = self.collected.as_mut() { |
| 1964 | collected.push((order, cropped.clone())); |
| 1965 | } |
| 1966 | Ok(self.packet(cropped.stream, true, order, Level::Key)) |
| 1967 | } |
| 1968 | |
| 1969 | /// Codes one inter frame at `order` from the DPB, in coding order. |
| 1970 | #[allow(clippy::too_many_arguments)] |
| 1971 | fn encode_pyramid_inter( |
| 1972 | &mut self, |
| 1973 | order: u64, |
| 1974 | picture: &Picture, |
| 1975 | last_slot: u8, |
| 1976 | self_slot: u8, |
| 1977 | altref_slot: u8, |
| 1978 | // lane-last2: the slot read as `LAST2_FRAME`. `None` -- and any slot |
| 1979 | // holding no picture, or the same one `LAST_FRAME` reads -- leaves |
| 1980 | // the reference set exactly as it was before this lane. |
| 1981 | last2_slot: Option<u8>, |
| 1982 | show_frame: bool, |
| 1983 | level: Level, |
| 1984 | // The quantizer offset comes from the CALLER, not from `level`: a |
| 1985 | // three-level group codes two `Level::Arf` frames (the group's top |
| 1986 | // ARF and the mid one) at different offsets, and they share the |
| 1987 | // rate-control slot but not the offset. |
| 1988 | offset: i16, |
| 1989 | // The lookahead window this frame's temporal lambda map is built |
| 1990 | // from, already padded (lane-arfcen). Empty codes the frame at one |
| 1991 | // lambda, which is what the whole pyramid path used to do. |
| 1992 | lookahead: &[Picture], |
| 1993 | // lane-lookahead: DISPLAY-FUTURE pictures for the SOURCE temporal |
| 1994 | // filter only (the top ARF's, out of the buffered next group), never |
| 1995 | // for the temporal lambda map -- keeping the filter's window and the |
| 1996 | // tpl window separate levers. Empty everywhere else. |
| 1997 | future: &[Picture], |
| 1998 | ) -> Result<Packet> { |
| 1999 | let render = (self.config.width, self.config.height); |
| 2000 | let order_hint = (order & 0x7f) as u32; |
| 2001 | let base = self |
| 2002 | .rate_loop |
| 2003 | .as_ref() |
| 2004 | .map_or(i16::from(self.config.base_q_idx), |r| { |
| 2005 | i16::from(r.q_idx(level)) |
| 2006 | }); |
| 2007 | let base_q_idx = (base + offset).clamp(1, 255) as u8; |
| 2008 | // lane-arfq: the top ARF of a mini-GOP is the hidden frame coded at |
| 2009 | // the pyramid's OWN `arf_q_offset` (the mid and quarter levels are |
| 2010 | // `Level::Arf` too but sit at their own offsets), and it is the level |
| 2011 | // the whole group predicts from -- so it reads its own `delta_q` |
| 2012 | // strength (`crate::speed::DQ_LEVEL_K`). |
| 2013 | let dq_level = match (show_frame, self.pyramid.map(|p| p.arf_q_offset)) { |
| 2014 | (true, _) => crate::encode::DqLevel::Leaf, |
| 2015 | (false, Some(arf)) if arf == offset => crate::encode::DqLevel::TopArf, |
| 2016 | (false, _) => crate::encode::DqLevel::MidArf, |
| 2017 | }; |
| 2018 | // spec 5.9.2's `ref_frame_sign_bias`, derived from what the slots |
| 2019 | // this frame names actually hold: a reference whose order hint is |
| 2020 | // AHEAD of this frame's is backward-biased, and the MV stack scans |
| 2021 | // (writer and decoder alike) flip borrowed candidates across the |
| 2022 | // boundary. Only `ALTREF_FRAME` can be ahead here — the leaves of a |
| 2023 | // mini-GOP name the group's hidden frame there. |
| 2024 | let mut sign_bias = crate::mvstack::NO_SIGN_BIAS; |
| 2025 | let ahead = |slot: u8, dpb: &[Option<DpbSlot>; 8]| { |
| 2026 | dpb[slot as usize] |
| 2027 | .as_ref() |
| 2028 | .is_some_and(|s| s.order_hint > order_hint) |
| 2029 | }; |
| 2030 | // A LAST2 slot only counts when it holds a picture that is not the |
| 2031 | // one `LAST_FRAME` already names; otherwise the frame codes the |
| 2032 | // reference set it always did. |
| 2033 | let last2_slot = last2_slot |
| 2034 | .filter(|&s| s != last_slot && self.dpb[s as usize].is_some()); |
| 2035 | let slots = [ |
| 2036 | last_slot, |
| 2037 | last2_slot.unwrap_or(last_slot), |
| 2038 | last_slot, |
| 2039 | GOLDEN_SLOT, |
| 2040 | last_slot, |
| 2041 | last_slot, |
| 2042 | altref_slot, |
| 2043 | ]; |
| 2044 | for (i, slot) in slots.into_iter().enumerate() { |
| 2045 | sign_bias[i] = ahead(slot, &self.dpb); |
| 2046 | } |
| 2047 | // The same seven slots' order hints, for `skipModeAllowed` (spec |
| 2048 | // 5.9.22) in the frame-header writer. |
| 2049 | let order_hints: [u32; 7] = slots.map(|slot| { |
| 2050 | self.dpb[slot as usize] |
| 2051 | .as_ref() |
| 2052 | .map_or(0, |s| (s.order_hint & 0x7f) as u32) |
| 2053 | }); |
| 2054 | let reference = self.dpb[last_slot as usize] |
| 2055 | .as_ref() |
| 2056 | .map(|s| s.picture.clone()) |
| 2057 | .ok_or_else(|| { |
| 2058 | Error::unsupported("AV1 encode", "an inter frame needs a previous reconstruction") |
| 2059 | })?; |
| 2060 | let last2 = last2_slot.and_then(|s| self.dpb[s as usize].as_ref().map(|d| d.picture.clone())); |
| 2061 | let golden = self.dpb[GOLDEN_SLOT as usize].as_ref().map(|s| s.picture.clone()); |
| 2062 | let altref = (altref_slot != GOLDEN_SLOT) |
| 2063 | .then(|| self.dpb[altref_slot as usize].as_ref().map(|s| s.picture.clone())) |
| 2064 | .flatten(); |
| 2065 | let start_cdfs = self.dpb[last_slot as usize].as_ref().map(|s| s.cdfs.0.clone()); |
| 2066 | // lane-arfpred: the top ARF is coded from a TEMPORALLY FILTERED |
| 2067 | // source when `speed::ARF_TF` is non-zero -- the grain it would |
| 2068 | // otherwise spend its residual on is averaged out against the |
| 2069 | // group's own display neighbours (`lookahead`, already padded). |
| 2070 | let source = picture.padded_to(SUPERBLOCK); |
| 2071 | // ... and never at the very top of the quality range, where the |
| 2072 | // anchor's own quantizer has hit the rate loop's floor |
| 2073 | // ([`crate::speed::ARF_TF_QMIN`]). |
| 2074 | let tf = match dq_level { |
| 2075 | crate::encode::DqLevel::TopArf => arf_tf_strength(), |
| 2076 | // lane-arftf: the mid ARF gets its own strength -- its window is |
| 2077 | // the group's later leaves, i.e. the filter runs FORWARD there. |
| 2078 | crate::encode::DqLevel::MidArf => arf_tf_mid_strength(), |
| 2079 | crate::encode::DqLevel::Leaf => 0.0, |
| 2080 | }; |
| 2081 | let tf = match base_q_idx >= crate::speed::ARF_TF_QMIN { |
| 2082 | true => tf, |
| 2083 | false => 0.0, |
| 2084 | }; |
| 2085 | let source = match tf > 0.0 { |
| 2086 | true => { |
| 2087 | // lane-lookahead: the filter's window is sized HERE -- up to |
| 2088 | // `ARF_TF_WIN` display-past neighbours (nearest first) and |
| 2089 | // then the display-future ones the caller buffered. |
| 2090 | let window: Vec<Picture> = lookahead |
| 2091 | .iter() |
| 2092 | .take(arf_tf_window()) |
| 2093 | .chain(future.iter()) |
| 2094 | .cloned() |
| 2095 | .collect(); |
| 2096 | crate::encode::arf_temporal_filter(&source, &window, tf) |
| 2097 | } |
| 2098 | false => source, |
| 2099 | }; |
| 2100 | let encoded = || -> Result<Encoded> { encode_inter_frame( |
| 2101 | &source, |
| 2102 | &reference, |
| 2103 | base_q_idx, |
| 2104 | DEADZONE, |
| 2105 | order_hint, |
| 2106 | order_hints, |
| 2107 | render, |
| 2108 | start_cdfs.as_ref(), |
| 2109 | golden.as_ref(), |
| 2110 | altref.as_ref(), |
| 2111 | last2.as_ref(), |
| 2112 | &self.fctx, |
| 2113 | Some(crate::encode::PyramidFrame { |
| 2114 | last_slot, |
| 2115 | self_slot, |
| 2116 | altref_slot, |
| 2117 | last2_slot, |
| 2118 | show_frame, |
| 2119 | sign_bias, |
| 2120 | dq_level, |
| 2121 | }), |
| 2122 | // lane-arfcen: the group's own sources ARE this frame's window |
| 2123 | // (`tpl_window`); it was `&[]` here, which switched the temporal |
| 2124 | // lambda map off on every frame the default stream codes. |
| 2125 | lookahead, |
| 2126 | ) }(); |
| 2127 | // Name the pyramid position in any failure: an error out of the tile |
| 2128 | // writer or the filter search is otherwise indistinguishable between |
| 2129 | // the hidden frame and the leaves that read it. |
| 2130 | let encoded = encoded.map_err(|e| { |
| 2131 | Error::unsupported( |
| 2132 | "AV1 encode", |
| 2133 | format!( |
| 2134 | "{level:?} frame at order {order} (last slot {last_slot}, self {self_slot}, \ |
| 2135 | altref {altref_slot}, last2 {last2_slot:?}, shown {show_frame}, golden {}, \ |
| 2136 | altref pic {}): {e}", |
| 2137 | golden.is_some(), |
| 2138 | altref.is_some(), |
| 2139 | ), |
| 2140 | ) |
| 2141 | })?; |
| 2142 | self.refresh(&[self_slot], &encoded, order_hint); |
| 2143 | let cropped = crop_encoded(&encoded, render.0, render.1); |
| 2144 | if let Some(rate_loop) = self.rate_loop.as_mut() { |
| 2145 | rate_loop.update(level, offset, base + offset, cropped.stream.len()); |
| 2146 | } |
| 2147 | if let Some(collected) = self.collected.as_mut() { |
| 2148 | collected.push((order, cropped.clone())); |
| 2149 | } |
| 2150 | Ok(self.packet(cropped.stream, false, order, level)) |
| 2151 | } |
| 2152 | |
| 2153 | /// Closes the open mini-GOP. With the lookahead off that codes it |
| 2154 | /// straight away, which is byte for byte what this encoder did before |
| 2155 | /// lane-lookahead; with it on the open group takes the `ready` slot and |
| 2156 | /// the group ALREADY there is coded, with the open one's sources as its |
| 2157 | /// display-future window. |
| 2158 | fn drain_pending(&mut self) -> Result<Vec<Packet>> { |
| 2159 | if !lookahead() { |
| 2160 | let group = std::mem::take(&mut self.pending); |
| 2161 | return self.code_group(group, &[]); |
| 2162 | } |
| 2163 | let group = std::mem::take(&mut self.ready); |
| 2164 | let next = std::mem::take(&mut self.pending); |
| 2165 | let packets = self.code_group(group, &next); |
| 2166 | self.ready = next; |
| 2167 | packets |
| 2168 | } |
| 2169 | |
| 2170 | /// Codes every group still buffered, in coding order -- what a key frame |
| 2171 | /// (`next` is the key picture, the last buffered group's own |
| 2172 | /// display-future) and the end of stream (`None`) both need. The tail |
| 2173 | /// group can be any length, down to the single picture `code_group` |
| 2174 | /// codes as one shown leaf. |
| 2175 | fn drain_all(&mut self, next: Option<&Picture>) -> Result<Vec<Packet>> { |
| 2176 | let tail: Vec<(u64, Picture)> = next |
| 2177 | .filter(|_| lookahead()) |
| 2178 | .map(|p| vec![(self.next_index, p.clone())]) |
| 2179 | .unwrap_or_default(); |
| 2180 | let ready = std::mem::take(&mut self.ready); |
| 2181 | let pending = std::mem::take(&mut self.pending); |
| 2182 | let mut packets = self.code_group(ready, &pending)?; |
| 2183 | packets.extend(self.code_group(pending, &tail)?); |
| 2184 | Ok(packets) |
| 2185 | } |
| 2186 | |
| 2187 | /// Codes one mini-GOP: its hidden frame first, then its leaves, then |
| 2188 | /// the `show_existing_frame` header that puts the hidden frame back in |
| 2189 | /// display order. `future` is the display-future sources the caller has |
| 2190 | /// buffered past this group (lane-lookahead), empty without a lookahead. |
| 2191 | fn code_group( |
| 2192 | &mut self, |
| 2193 | group: Vec<(u64, Picture)>, |
| 2194 | future: &[(u64, Picture)], |
| 2195 | ) -> Result<Vec<Packet>> { |
| 2196 | if group.is_empty() { |
| 2197 | return Ok(Vec::new()); |
| 2198 | } |
| 2199 | let mut packets = Vec::with_capacity(group.len() + 1); |
| 2200 | // The lookahead window of the group's picture at index `pos`: the |
| 2201 | // display-order successors inside this group, or -- for the group's |
| 2202 | // top ARF, the last picture, whose successors are not buffered yet -- |
| 2203 | // the leaves BEHIND it in reverse display order, which are exactly |
| 2204 | // the pictures that predict backward from it. Padded like the frame |
| 2205 | // itself, as `encode_inter_frame` wants it. |
| 2206 | let tpl_window = |pos: usize, back: bool| -> Vec<Picture> { |
| 2207 | let depth = crate::encode::tpl_depth(); |
| 2208 | if !tpl_pyramid() || depth < 2 { |
| 2209 | return Vec::new(); |
| 2210 | } |
| 2211 | let window: Vec<&Picture> = match back { |
| 2212 | false => group[pos + 1..].iter().map(|(_, p)| p).collect(), |
| 2213 | true => group[..pos].iter().rev().map(|(_, p)| p).collect(), |
| 2214 | }; |
| 2215 | window.into_iter().take(depth - 1).map(|p| p.padded_to(SUPERBLOCK)).collect() |
| 2216 | }; |
| 2217 | // lane-last2: the slot a frame reading `last_slot` as `LAST_FRAME` |
| 2218 | // names as `LAST2_FRAME` -- the most recent shown leaf that is not |
| 2219 | // the one it already reads. `None` with the lever off, or before two |
| 2220 | // distinct past pictures exist. |
| 2221 | let last2_of = |hist: &[u8], last_slot: u8| -> Option<u8> { |
| 2222 | last2().then(|| hist.iter().copied().find(|&s| s != last_slot)).flatten() |
| 2223 | }; |
| 2224 | let anchor_slot = ANCHOR_SLOTS[self.anchor]; |
| 2225 | let next_anchor_slot = ANCHOR_SLOTS[1 - self.anchor]; |
| 2226 | let (arf_order, arf_picture) = group.last().cloned().expect("non-empty"); |
| 2227 | let pyramid = self.pyramid.expect("pyramid mode"); |
| 2228 | if group.len() == 1 { |
| 2229 | // Nothing to predict backward, so no hidden frame: one shown leaf |
| 2230 | // that also becomes the next group's anchor. |
| 2231 | packets.push(self.encode_pyramid_inter( |
| 2232 | arf_order, |
| 2233 | &arf_picture, |
| 2234 | anchor_slot, |
| 2235 | next_anchor_slot, |
| 2236 | GOLDEN_SLOT, |
| 2237 | last2_of(&self.leaf_hist, anchor_slot), |
| 2238 | true, |
| 2239 | Level::Leaf, |
| 2240 | pyramid.leaf_q_offset, |
| 2241 | &tpl_window(0, false), |
| 2242 | &[], |
| 2243 | )?); |
| 2244 | self.anchor = 1 - self.anchor; |
| 2245 | return Ok(packets); |
| 2246 | } |
| 2247 | // lane-lookahead: the display-future half of the top ARF's temporal |
| 2248 | // filter window, padded like the frame itself. Empty when the |
| 2249 | // lookahead is off (`future` is then always empty) or when the filter |
| 2250 | // asks for no future neighbours, which is what keeps the default |
| 2251 | // stream byte-identical. |
| 2252 | let arf_future: Vec<Picture> = future |
| 2253 | .iter() |
| 2254 | .take(arf_tf_window_future()) |
| 2255 | .map(|(_, p)| p.padded_to(SUPERBLOCK)) |
| 2256 | .collect(); |
| 2257 | // lane-tplfut: the top ARF's TEMPORAL LAMBDA window. Mode 0 (and any |
| 2258 | // mode with no buffered future picture) keeps the group's own |
| 2259 | // display-PAST sources, reversed -- the only window that exists |
| 2260 | // without a lookahead, and the one every measurement so far was |
| 2261 | // taken with. The other modes read the next group's sources, which |
| 2262 | // is the direction libaom's tpl looks at an ARF. |
| 2263 | // `n` of the buffered display-future sources, nearest first, padded |
| 2264 | // like the frame being coded. |
| 2265 | let arf_tpl_future = |n: usize| -> Vec<Picture> { |
| 2266 | future.iter().take(n).map(|(_, p)| p.padded_to(SUPERBLOCK)).collect() |
| 2267 | }; |
| 2268 | let arf_tpl: Vec<Picture> = { |
| 2269 | let depth = crate::encode::tpl_depth(); |
| 2270 | let past = || tpl_window(group.len() - 1, true); |
| 2271 | match (tpl_fut(), future.is_empty(), tpl_pyramid() && depth >= 2) { |
| 2272 | (_, _, false) => Vec::new(), |
| 2273 | (0, _, _) | (_, true, _) => past(), |
| 2274 | (1, _, _) => arf_tpl_future(depth - 1), |
| 2275 | // Half the budget each side (`EC_AV1_TPL_FUT_HALF=<n>` |
| 2276 | // moves the split), past first: the chain then has |
| 2277 | // ONE discontinuity in the middle (the coarse pass between |
| 2278 | // the nearest past and the nearest future neighbour spans the |
| 2279 | // whole group), which is the arm's known cost. |
| 2280 | (2, _, _) => { |
| 2281 | let budget = tpl_fut_win(depth); |
| 2282 | let mut w = past(); |
| 2283 | w.truncate(tpl_fut_half().max(1)); |
| 2284 | let room = budget.saturating_sub(w.len()); |
| 2285 | w.extend(arf_tpl_future(room)); |
| 2286 | w |
| 2287 | } |
| 2288 | // Mode 3 and anything above: the WHOLE buffered next group. |
| 2289 | (_, _, _) => arf_tpl_future(future.len()), |
| 2290 | } |
| 2291 | }; |
| 2292 | // The group's top level: the last picture, hidden, off the anchor. |
| 2293 | packets.push(self.encode_pyramid_inter( |
| 2294 | arf_order, |
| 2295 | &arf_picture, |
| 2296 | anchor_slot, |
| 2297 | next_anchor_slot, |
| 2298 | // lane-arfcen: the slot this ARF refreshes still holds the ARF |
| 2299 | // from two groups back, so naming it here gives the frame a |
| 2300 | // SECOND, distinct past anchor instead of the key it already |
| 2301 | // reads as GOLDEN. |
| 2302 | match arf_altref() { |
| 2303 | true => next_anchor_slot, |
| 2304 | false => GOLDEN_SLOT, |
| 2305 | }, |
| 2306 | // The ARF levels take no LAST2: the anchor pair already gives a |
| 2307 | // top ARF two distinct past anchors (`arf_altref`), and the mid |
| 2308 | // and quarter frames have only the one past anchor in the DPB. |
| 2309 | None, |
| 2310 | false, |
| 2311 | Level::Arf, |
| 2312 | pyramid.arf_q_offset, |
| 2313 | &arf_tpl, |
| 2314 | // lane-lookahead: the group's top ARF is its LAST picture in |
| 2315 | // display order, so every picture of the next group is a |
| 2316 | // display-future neighbour of it -- nearest first. |
| 2317 | &arf_future, |
| 2318 | )?); |
| 2319 | let leaves = group.len() - 1; |
| 2320 | // THE THIRD LEVEL: a second hidden frame at the middle of the leaf |
| 2321 | // run, coded off the anchor with the top ARF as its own backward |
| 2322 | // reference. It needs a leaf on both sides of it, so a group of |
| 2323 | // three or fewer stays two-level. |
| 2324 | // |
| 2325 | // AND IT NEEDS A RUN LONG ENOUGH TO AMORTISE IT: a GOP that is one |
| 2326 | // single mini-GOP (`group_target` absorbs a tail, so a 12-picture GOP |
| 2327 | // under `mini_gop` 8 is ONE group of 11) pays for the second hidden |
| 2328 | // frame out of eleven pictures and reads +2.8 BD points worse against |
| 2329 | // libaom on film B at every mid offset measured (-4: +71.1, -8: |
| 2330 | // +71.2, against the two-level +68.4), while the 48-picture GOP -- six |
| 2331 | // groups sharing the same machinery -- is 6.0 points BETTER. So the |
| 2332 | // third level is switched on by the RUN's length, not by the group's: |
| 2333 | // the same GOP-length dependence `group_target` itself was built for. |
| 2334 | let long_run = self.config.gop > pyramid.mini_gop + pyramid.mini_gop / 2; |
| 2335 | let mid = pyramid.mid_q_offset.filter(|_| leaves >= 3 && long_run).map(|offset| { |
| 2336 | let at = (leaves - 1) / 2; |
| 2337 | (at, offset) |
| 2338 | }); |
| 2339 | if let Some((at, offset)) = mid { |
| 2340 | let (order, picture) = group[at].clone(); |
| 2341 | packets.push(self.encode_pyramid_inter( |
| 2342 | order, |
| 2343 | &picture, |
| 2344 | anchor_slot, |
| 2345 | MID_SLOT, |
| 2346 | next_anchor_slot, |
| 2347 | None, |
| 2348 | false, |
| 2349 | Level::Arf, |
| 2350 | offset, |
| 2351 | &tpl_window(at, false), |
| 2352 | &[], |
| 2353 | )?); |
| 2354 | } |
| 2355 | // THE FOURTH LEVEL: one hidden frame at the middle of each half of |
| 2356 | // the leaf run, so no leaf is more than one picture from a hidden |
| 2357 | // reference on either side -- the depth the references run (rav1e |
| 2358 | // speed 6 codes 23 hidden frames per 48 pictures, libaom four levels |
| 2359 | // per 16-picture group) and the lever three levels had run out of. |
| 2360 | // It hangs off the mid level, and it needs a leaf on both sides of |
| 2361 | // both quarter points, which a run of fewer than seven leaves cannot |
| 2362 | // give. |
| 2363 | let quarters = match (mid, pyramid.quarter_q_offset) { |
| 2364 | (Some((at, _)), Some(offset)) if leaves >= 7 => { |
| 2365 | Some(([(at - 1) / 2, (at + leaves) / 2], offset)) |
| 2366 | } |
| 2367 | _ => None, |
| 2368 | }; |
| 2369 | if let Some((at, offset)) = quarters { |
| 2370 | // The first quarter predicts forward off the group's anchor and |
| 2371 | // backward off the mid ARF; the second starts FROM the mid ARF |
| 2372 | // and reads the group's top ARF backward. |
| 2373 | for (i, &pos) in at.iter().enumerate() { |
| 2374 | let (order, picture) = group[pos].clone(); |
| 2375 | let (last_slot, altref_slot) = match i { |
| 2376 | 0 => (anchor_slot, MID_SLOT), |
| 2377 | _ => (MID_SLOT, next_anchor_slot), |
| 2378 | }; |
| 2379 | packets.push(self.encode_pyramid_inter( |
| 2380 | order, |
| 2381 | &picture, |
| 2382 | last_slot, |
| 2383 | QUARTER_SLOTS[i], |
| 2384 | altref_slot, |
| 2385 | None, |
| 2386 | false, |
| 2387 | Level::Arf, |
| 2388 | offset, |
| 2389 | &tpl_window(pos, false), |
| 2390 | &[], |
| 2391 | )?); |
| 2392 | } |
| 2393 | } |
| 2394 | // Every hidden frame INSIDE the leaf run, by leaf index, in display |
| 2395 | // order: what a leaf reads forward (the nearest one behind it) and |
| 2396 | // backward (the nearest one ahead of it, the group's top ARF when |
| 2397 | // there is none). |
| 2398 | let mut inner: Vec<(usize, u8)> = Vec::new(); |
| 2399 | if let Some((at, _)) = mid { |
| 2400 | inner.push((at, MID_SLOT)); |
| 2401 | } |
| 2402 | if let Some((at, _)) = quarters { |
| 2403 | inner.extend(at.iter().zip(QUARTER_SLOTS).map(|(&at, slot)| (at, slot))); |
| 2404 | } |
| 2405 | inner.sort_unstable(); |
| 2406 | let (seq, _) = crate::encode::key_frame_headers( |
| 2407 | self.config.width, |
| 2408 | self.config.height, |
| 2409 | self.config.base_q_idx, |
| 2410 | )?; |
| 2411 | let show_existing = |encoder: &mut Self, slot: u8, order: u64| -> Result<Packet> { |
| 2412 | let mut data = crate::obu::temporal_delimiter(); |
| 2413 | data.extend_from_slice(&crate::frame::show_existing_frame_obu(&seq, slot)?); |
| 2414 | Ok(encoder.packet(data, false, order, Level::ShowExisting)) |
| 2415 | }; |
| 2416 | // The leaves, in display order, so every `show_existing_frame` lands |
| 2417 | // in its own display position. Each leaf names the nearest hidden |
| 2418 | // frame BEHIND it as `LAST_FRAME` (the group's anchor for the first |
| 2419 | // leaf, otherwise the previous leaf) and the nearest one AHEAD as |
| 2420 | // `ALTREF_FRAME` (the group's top ARF when none is closer). |
| 2421 | for (i, (order, picture)) in group[..leaves].iter().enumerate() { |
| 2422 | if let Some(&(_, slot)) = inner.iter().find(|(at, _)| *at == i) { |
| 2423 | let packet = show_existing(self, slot, *order)?; |
| 2424 | packets.push(packet); |
| 2425 | continue; |
| 2426 | } |
| 2427 | // The previous shown leaf's own slot: `LEAF_SLOT` with the |
| 2428 | // lever off, and with it on whichever of [`LEAF_SLOTS`] that leaf |
| 2429 | // refreshed. |
| 2430 | let prev_leaf = self.leaf_hist.first().copied().unwrap_or(LEAF_SLOT); |
| 2431 | let last_slot = match i { |
| 2432 | 0 => anchor_slot, |
| 2433 | i => inner |
| 2434 | .iter() |
| 2435 | .find(|(at, _)| at + 1 == i) |
| 2436 | .map_or(prev_leaf, |&(_, slot)| slot), |
| 2437 | }; |
| 2438 | // Alternate the refresh: this leaf takes the leaf slot the |
| 2439 | // PREVIOUS leaf did not, which is the one the leaf before that |
| 2440 | // wrote and which this frame may still read as `LAST2_FRAME` |
| 2441 | // (read before write). |
| 2442 | let self_slot = match last2() { |
| 2443 | true => LEAF_SLOTS |
| 2444 | .into_iter() |
| 2445 | .find(|&s| Some(s) != self.leaf_hist.first().copied()) |
| 2446 | .unwrap_or(LEAF_SLOT), |
| 2447 | false => LEAF_SLOT, |
| 2448 | }; |
| 2449 | let last2_slot = last2_of(&self.leaf_hist, last_slot); |
| 2450 | let altref_slot = inner |
| 2451 | .iter() |
| 2452 | .find(|(at, _)| *at > i) |
| 2453 | .map_or(next_anchor_slot, |&(_, slot)| slot); |
| 2454 | self.leaf_hist.insert(0, self_slot); |
| 2455 | self.leaf_hist.truncate(2); |
| 2456 | packets.push(self.encode_pyramid_inter( |
| 2457 | *order, |
| 2458 | picture, |
| 2459 | last_slot, |
| 2460 | self_slot, |
| 2461 | altref_slot, |
| 2462 | last2_slot, |
| 2463 | true, |
| 2464 | Level::Leaf, |
| 2465 | pyramid.leaf_q_offset, |
| 2466 | &tpl_window(i, false), |
| 2467 | &[], |
| 2468 | )?); |
| 2469 | } |
| 2470 | let packet = show_existing(self, next_anchor_slot, arf_order)?; |
| 2471 | packets.push(packet); |
| 2472 | self.anchor = 1 - self.anchor; |
| 2473 | Ok(packets) |
| 2474 | } |
| 2475 | } |
| 2476 | |
| 2477 | #[cfg(test)] |
| 2478 | mod tests { |
| 2479 | use super::*; |
| 2480 | use std::process::{Command, Stdio}; |
| 2481 | |
| 2482 | /// Whether ffmpeg is on PATH. Absence normally SKIPs, but |
| 2483 | /// `EC_AV1_REQUIRE_FFMPEG=1` -- or `EC_AV1_REQUIRE_AOMENC=1`, since every |
| 2484 | /// aomenc gate decodes its stream through ffmpeg and is meaningless |
| 2485 | /// without it -- turns it into a hard failure. Without this the require |
| 2486 | /// flag was silently short-circuited: `!have_ffmpeg()` is evaluated first |
| 2487 | /// in `if !have_ffmpeg() || !have_aomenc()`, so a machine with no ffmpeg |
| 2488 | /// printed SKIP and reported green (class gate-skips-on-its-own-failure). |
| 2489 | fn have_ffmpeg() -> bool { |
| 2490 | let present = Command::new("ffmpeg") |
| 2491 | .arg("-version") |
| 2492 | .stdout(Stdio::null()) |
| 2493 | .stderr(Stdio::null()) |
| 2494 | .status() |
| 2495 | .is_ok_and(|s| s.success()); |
| 2496 | assert!( |
| 2497 | present |
| 2498 | || (std::env::var_os("EC_AV1_REQUIRE_FFMPEG").is_none() |
| 2499 | && std::env::var_os("EC_AV1_REQUIRE_AOMENC").is_none()), |
| 2500 | "EC_AV1_REQUIRE_FFMPEG/EC_AV1_REQUIRE_AOMENC is set but no working ffmpeg on PATH" |
| 2501 | ); |
| 2502 | present |
| 2503 | } |
| 2504 | |
| 2505 | fn test_card(width: usize, height: usize, shift: usize) -> Picture { |
| 2506 | let mut picture = Picture::grey(width, height); |
| 2507 | for y in 0..height { |
| 2508 | for x in 0..width { |
| 2509 | let sx = (x + shift) % width; |
| 2510 | picture.y[y * width + x] = ((sx * 3 + y * 5) % 256) as u16; |
| 2511 | } |
| 2512 | } |
| 2513 | for y in 0..height / 2 { |
| 2514 | for x in 0..width / 2 { |
| 2515 | let i = y * (width / 2) + x; |
| 2516 | picture.u[i] = ((100 + shift * 4) % 256) as u16; |
| 2517 | picture.v[i] = ((200 + 256 - shift * 2 % 256) % 256) as u16; |
| 2518 | } |
| 2519 | } |
| 2520 | picture |
| 2521 | } |
| 2522 | |
| 2523 | /// Drives a whole stream through the facade the way a caller must since |
| 2524 | /// it holds one picture of lookahead: every picture through |
| 2525 | /// [`Av1Encoder::encode_frames`], then [`Av1Encoder::flush`]. |
| 2526 | fn encode_all(enc: &mut Av1Encoder, pictures: &[Picture]) -> Vec<Packet> { |
| 2527 | let mut packets = Vec::with_capacity(pictures.len()); |
| 2528 | for (i, picture) in pictures.iter().enumerate() { |
| 2529 | packets.extend( |
| 2530 | enc.encode_frames(picture) |
| 2531 | .unwrap_or_else(|e| panic!("picture {i}: {e}")), |
| 2532 | ); |
| 2533 | } |
| 2534 | packets.extend(enc.flush().unwrap_or_else(|e| panic!("flush: {e}"))); |
| 2535 | packets |
| 2536 | } |
| 2537 | |
| 2538 | /// [`gop_shape`] prices the frames the pyramid actually CODES: its hidden |
| 2539 | /// counts and leaf count match the packets a real run emits, at three |
| 2540 | /// pyramid shapes, and the plan [`RateLoop::new`] builds from it spends |
| 2541 | /// the run's budget exactly (`gop` frame targets, no more and no less). |
| 2542 | /// |
| 2543 | /// Both halves matter: a shape that misses a level (the old model priced |
| 2544 | /// ONE hidden frame per group when the mid level had made it two) splits |
| 2545 | /// the budget by weights that do not add up to the run. |
| 2546 | #[test] |
| 2547 | fn the_rate_loop_prices_the_frames_the_pyramid_codes() { |
| 2548 | let _knobs = crate::speed::knob_read(); |
| 2549 | let pictures: Vec<Picture> = (0..48).map(|i| test_card(64, 64, i)).collect(); |
| 2550 | let quarters = Pyramid { |
| 2551 | quarter_q_offset: Some(-20), |
| 2552 | ..Pyramid::default() |
| 2553 | }; |
| 2554 | let two_level = Pyramid { |
| 2555 | mid_q_offset: None, |
| 2556 | ..Pyramid::default() |
| 2557 | }; |
| 2558 | for (gop, pyramid) in [ |
| 2559 | (48, Pyramid::default()), |
| 2560 | (12, Pyramid::default()), |
| 2561 | (48, quarters), |
| 2562 | (48, two_level), |
| 2563 | ] { |
| 2564 | let config = EncoderConfig { |
| 2565 | width: 64, |
| 2566 | height: 64, |
| 2567 | base_q_idx: 100, |
| 2568 | gop, |
| 2569 | colour: Colour::Bt709Limited, |
| 2570 | tile_cols_log2: 0, |
| 2571 | tile_rows_log2: 0, |
| 2572 | }; |
| 2573 | let rate = RateTarget::BytesPerFrame(2_000); |
| 2574 | let mut enc = |
| 2575 | Av1Encoder::with_pyramid_and_rate_target(config, pyramid, rate).unwrap(); |
| 2576 | let packets = encode_all(&mut enc, &pictures[..gop]); |
| 2577 | let coded = |level: Level| packets.iter().filter(|p| p.level == level).count(); |
| 2578 | let (hidden, leaves) = gop_shape(pyramid, gop); |
| 2579 | let hidden_frames: usize = hidden.iter().map(|&(_, n)| n).sum(); |
| 2580 | assert_eq!( |
| 2581 | (hidden_frames, leaves, 1), |
| 2582 | (coded(Level::Arf), coded(Level::Leaf), coded(Level::Key)), |
| 2583 | "gop {gop} {pyramid:?}: shape {hidden:?} + {leaves} leaves" |
| 2584 | ); |
| 2585 | assert_eq!( |
| 2586 | hidden_frames + leaves + 1, |
| 2587 | gop, |
| 2588 | "gop {gop}: every picture is coded exactly once" |
| 2589 | ); |
| 2590 | // The plan adds up: one leaf's target times the run's whole |
| 2591 | // weight is the run's whole budget. |
| 2592 | let target_bytes = 2_000.0; |
| 2593 | let loop_ = RateLoop::new(target_bytes, 100.0, Some(pyramid), gop); |
| 2594 | let planned = loop_.target[0] |
| 2595 | + loop_.target[2] * (leaves as f64 |
| 2596 | + hidden.iter().map(|&(o, n)| n as f64 * loop_.weight(o)).sum::<f64>()); |
| 2597 | assert!( |
| 2598 | (planned - target_bytes * gop as f64).abs() < 1.0, |
| 2599 | "gop {gop}: plan {planned:.0} bytes against a {:.0} byte run", |
| 2600 | target_bytes * gop as f64 |
| 2601 | ); |
| 2602 | } |
| 2603 | } |
| 2604 | |
| 2605 | /// A level at its quantizer BOUND hands its unspent bytes to the levels |
| 2606 | /// that can still move ([[vorbis-rate-loop-windup]]'s class in the |
| 2607 | /// small), and it does so AT ONCE, not once the bound level's frames are |
| 2608 | /// all coded: the loop is driven by a synthetic per-level model where the |
| 2609 | /// first hidden frame is coded at `raw_q` 0 (past the coder's own 1..=255 |
| 2610 | /// clamp) and spends half its plan, and the leaves' target must jump to |
| 2611 | /// the run's remainder with EVERY remaining hidden frame priced at that |
| 2612 | /// measured rate. The old division -- whole remainder over whole |
| 2613 | /// remaining weight -- handed most of the shortfall straight back to the |
| 2614 | /// hidden slot (which carries most of the pyramid's weight and cannot |
| 2615 | /// spend it), so the leaves only saw the surplus at the end of the run, |
| 2616 | /// when there was nothing left to code with it. |
| 2617 | #[test] |
| 2618 | fn a_bound_level_hands_its_unspent_bytes_to_the_others() { |
| 2619 | let pyramid = Pyramid::default(); |
| 2620 | let (gop, target_bytes) = (48usize, 2_000.0); |
| 2621 | let (hidden, leaves) = gop_shape(pyramid, gop); |
| 2622 | let run_bytes = target_bytes * gop as f64; |
| 2623 | let mut rl = RateLoop::new(target_bytes, 100.0, Some(pyramid), gop); |
| 2624 | let scale0 = rl.target[2]; |
| 2625 | let hidden_weight: f64 = hidden.iter().map(|&(o, n)| n as f64 * rl.weight(o)).sum(); |
| 2626 | // The key codes exactly its plan; the first hidden frame is at the |
| 2627 | // floor and spends half of its. |
| 2628 | let key_bytes = rl.target[0].round(); |
| 2629 | rl.update(Level::Key, 0, 100, key_bytes as usize); |
| 2630 | let (offset, n0) = hidden[0]; |
| 2631 | let arf_bytes = (0.5 * scale0 * rl.weight(offset)).round(); |
| 2632 | rl.update(Level::Arf, offset, 0, arf_bytes as usize); |
| 2633 | // Every frame of THAT LEVEL still to come is priced at what the bound |
| 2634 | // one measured -- and only that level: its slot-mates (the mid ARF) |
| 2635 | // sit at their own offset and are still free to follow the plan. |
| 2636 | // Everything else shares the rest. |
| 2637 | let want = (run_bytes - key_bytes - arf_bytes * n0 as f64) |
| 2638 | / (leaves as f64 + hidden_weight - n0 as f64 * rl.weight(offset)); |
| 2639 | assert!( |
| 2640 | want < scale0 * RateLoop::REPLAN_CLAMP, |
| 2641 | "this arm must not reach the windup bound: {want:.1} vs {:.1}", |
| 2642 | scale0 * RateLoop::REPLAN_CLAMP |
| 2643 | ); |
| 2644 | assert!( |
| 2645 | (rl.target[2] - want).abs() < 1e-6, |
| 2646 | "leaf target {:.3} is not the exact remainder {want:.3} (naive division would \ |
| 2647 | give {:.3})", |
| 2648 | rl.target[2], |
| 2649 | (run_bytes - key_bytes - arf_bytes) / (leaves as f64 + hidden_weight - rl.weight(offset)) |
| 2650 | ); |
| 2651 | // And the re-plan stays BOUNDED: hidden levels that spend nothing at |
| 2652 | // all cannot run the leaves' target away. |
| 2653 | let mut rl = RateLoop::new(target_bytes, 100.0, Some(pyramid), gop); |
| 2654 | rl.update(Level::Key, 0, 100, key_bytes as usize); |
| 2655 | for &(offset, n) in &hidden { |
| 2656 | for _ in 0..n { |
| 2657 | rl.update(Level::Arf, offset, 0, 1); |
| 2658 | } |
| 2659 | } |
| 2660 | assert!( |
| 2661 | rl.target[2] <= scale0 * RateLoop::REPLAN_CLAMP + 1e-9, |
| 2662 | "the re-plan is unbounded: leaf target {:.1} past {:.1}", |
| 2663 | rl.target[2], |
| 2664 | scale0 * RateLoop::REPLAN_CLAMP |
| 2665 | ); |
| 2666 | // ... and BOTH ways: a re-plan that reached zero would stop the loop |
| 2667 | // dead (`update` returns on a non-positive target). |
| 2668 | let mut rl = RateLoop::new(target_bytes, 100.0, Some(pyramid), gop); |
| 2669 | rl.update(Level::Key, 0, 100, key_bytes as usize); |
| 2670 | for &(offset, n) in &hidden { |
| 2671 | for _ in 0..n { |
| 2672 | rl.update(Level::Arf, offset, 0, 40 * key_bytes as usize); |
| 2673 | } |
| 2674 | } |
| 2675 | assert!( |
| 2676 | rl.target[2] >= scale0 * RateLoop::REPLAN_FLOOR - 1e-9, |
| 2677 | "the re-plan froze the loop: leaf target {:.1} under {:.1}", |
| 2678 | rl.target[2], |
| 2679 | scale0 * RateLoop::REPLAN_FLOOR |
| 2680 | ); |
| 2681 | } |
| 2682 | |
| 2683 | /// The mini-GOP layout leaves no short tail group, and leaves the long |
| 2684 | /// GOP the fixed rule already coded alone: 47 inter pictures are |
| 2685 | /// 8 x 5 + 7 under both rules (so a 48-picture GOP is byte-identical), |
| 2686 | /// while a 12-picture GOP stops being 8 + 3 (lane-gopad). |
| 2687 | #[test] |
| 2688 | fn the_mini_gop_layout_leaves_no_short_tail() { |
| 2689 | let groups = |remaining: usize, mini_gop: usize, absorb: bool| { |
| 2690 | let (mut left, mut out) = (remaining, Vec::new()); |
| 2691 | while left > 0 { |
| 2692 | let g = group_target(left, mini_gop, absorb).min(left); |
| 2693 | assert!(g > 0); |
| 2694 | out.push(g); |
| 2695 | left -= g; |
| 2696 | } |
| 2697 | out |
| 2698 | }; |
| 2699 | // gop 48: what mini_gop 8 already coded, under either rule. |
| 2700 | assert_eq!(groups(47, 8, true), vec![8, 8, 8, 8, 8, 7]); |
| 2701 | assert_eq!(groups(47, 8, false), vec![8, 8, 8, 8, 8, 7]); |
| 2702 | // gop 12: 8 + 3 becomes one group of 11. |
| 2703 | assert_eq!(groups(11, 8, false), vec![8, 3]); |
| 2704 | assert_eq!(groups(11, 8, true), vec![11]); |
| 2705 | // A run shorter than a group is one group, as before (the 4-picture |
| 2706 | // pin clip). |
| 2707 | assert_eq!(groups(3, 8, true), vec![3]); |
| 2708 | // No group is ever below half the shape, and none is over 1.5x it. |
| 2709 | for mini_gop in 2..=16 { |
| 2710 | for remaining in 1..=64 { |
| 2711 | for g in groups(remaining, mini_gop, true) { |
| 2712 | assert!(g * 2 <= 3 * mini_gop, "{remaining}/{mini_gop}: long {g}"); |
| 2713 | assert!( |
| 2714 | g * 2 >= mini_gop || remaining < mini_gop, |
| 2715 | "{remaining}/{mini_gop}: short tail {g}" |
| 2716 | ); |
| 2717 | } |
| 2718 | } |
| 2719 | } |
| 2720 | } |
| 2721 | |
| 2722 | /// Every OBU stream this test writes to `ffmpeg`/`ffprobe`, concatenated |
| 2723 | /// in order. |
| 2724 | fn concat(packets: &[Packet]) -> Vec<u8> { |
| 2725 | packets.iter().flat_map(|p| p.data.clone()).collect() |
| 2726 | } |
| 2727 | |
| 2728 | /// The facade's latency contract (lane-av1facade, deepened on |
| 2729 | /// lane-av1tpl2): the first [`crate::encode::tpl_depth`] - 1 calls hold |
| 2730 | /// their picture back and return an empty packet, every later call |
| 2731 | /// returns the packet of the picture that many frames earlier, and |
| 2732 | /// [`Av1Encoder::flush`] yields the whole queue — so a caller still gets |
| 2733 | /// exactly one non-empty packet per picture, `depth - 1` calls later. |
| 2734 | #[test] |
| 2735 | fn one_in_one_out_delayed_by_the_lookahead_depth() { |
| 2736 | let _knobs = crate::speed::knob_read(); |
| 2737 | let config = EncoderConfig { |
| 2738 | width: 64, |
| 2739 | height: 64, |
| 2740 | base_q_idx: 100, |
| 2741 | gop: 2, |
| 2742 | colour: Colour::Bt709Limited, |
| 2743 | tile_cols_log2: 0, |
| 2744 | tile_rows_log2: 0, |
| 2745 | }; |
| 2746 | let delay = crate::encode::tpl_depth() as u64 - 1; |
| 2747 | let pictures = delay + 5; |
| 2748 | let mut enc = Av1Encoder::new(config).unwrap(); |
| 2749 | for t in 0..pictures { |
| 2750 | let packet = enc.encode(&test_card(64, 64, t as usize)).unwrap(); |
| 2751 | if t < delay { |
| 2752 | assert!(packet.data.is_empty(), "call {t} holds its picture back"); |
| 2753 | continue; |
| 2754 | } |
| 2755 | assert!(!packet.data.is_empty(), "picture {t}: empty packet"); |
| 2756 | assert_eq!(packet.order, t - delay, "picture {t}: order"); |
| 2757 | } |
| 2758 | let tail = enc.flush().unwrap(); |
| 2759 | assert_eq!(tail.len() as u64, delay, "flush yields the whole queue"); |
| 2760 | for (i, p) in tail.iter().enumerate() { |
| 2761 | assert_eq!(p.order, pictures - delay + i as u64, "flushed packet {i}: order"); |
| 2762 | assert!(!p.data.is_empty(), "flushed packet {i}: empty"); |
| 2763 | } |
| 2764 | assert!(enc.flush().unwrap().is_empty(), "nothing is held twice"); |
| 2765 | } |
| 2766 | |
| 2767 | /// A screen-like card: hard-edged 4-pixel bands of two flat luma values |
| 2768 | /// with a moving block over the lower half — few colours per 16x16 block |
| 2769 | /// at high variance, which is exactly what |
| 2770 | /// [`crate::encode::picture_is_screen`] separates. Used unforced, so the |
| 2771 | /// gate below runs the real detector rather than an override. |
| 2772 | fn screen_card(width: usize, height: usize, shift: usize) -> Picture { |
| 2773 | let mut picture = Picture::grey(width, height); |
| 2774 | for y in 0..height { |
| 2775 | for x in 0..width { |
| 2776 | let band = if (x / 4).is_multiple_of(2) { 40 } else { 200 }; |
| 2777 | let over = y >= height / 2 && (x + shift) % width < width / 3; |
| 2778 | picture.y[y * width + x] = if over { 128 } else { band }; |
| 2779 | } |
| 2780 | } |
| 2781 | picture |
| 2782 | } |
| 2783 | |
| 2784 | /// THE ENTRY-SURFACE GATE (lane-av1facade, extended to the pyramid on |
| 2785 | /// lane-av1pyrdef): the streaming facade — what the editor's export |
| 2786 | /// drives — codes byte for byte what [`crate::encode::encode_sequence`] |
| 2787 | /// codes, which is the path the BD gate measures. Both now drive ONE |
| 2788 | /// mini-GOP driver ([`Av1Encoder::encode_sequence_pyramid`]), so the |
| 2789 | /// identity is by construction; this pins it anyway, over both content |
| 2790 | /// classes the content gate splits: |
| 2791 | /// |
| 2792 | /// * film-like (the gate's own clip when the fixture is there, a |
| 2793 | /// multi-tone moving card otherwise): the pyramid is EFFECTIVE, the |
| 2794 | /// stream is reordered (a hidden `ALTREF` per mini-GOP), and the two |
| 2795 | /// paths' whole streams are identical; |
| 2796 | /// * screen-like: the content gate drops BOTH paths back to flat, one |
| 2797 | /// packet per picture, identical frame by frame as well as whole. |
| 2798 | /// |
| 2799 | /// Never skipped, since a skipped identity gate is the defect it is meant |
| 2800 | /// to catch. |
| 2801 | #[test] |
| 2802 | fn the_facade_codes_the_same_bytes_as_encode_sequence() { |
| 2803 | let _knobs = crate::speed::knob_read(); |
| 2804 | let frames = 12usize; |
| 2805 | let film = h264_clip_frames(640, 384, frames).unwrap_or_else(|| { |
| 2806 | eprintln!("no h264 clip: the facade identity gate runs on a synthetic card"); |
| 2807 | (0..frames).map(|t| test_card(64, 64, t)).collect() |
| 2808 | }); |
| 2809 | let screen: Vec<Picture> = (0..frames).map(|t| screen_card(64, 64, t)).collect(); |
| 2810 | let pyramid = Pyramid::from_env().expect("the pyramid is this build's default"); |
| 2811 | for (content, pictures, is_screen) in |
| 2812 | [("film", &film, false), ("screen", &screen, true)] |
| 2813 | { |
| 2814 | let (width, height) = (pictures[0].width, pictures[0].height); |
| 2815 | for q in [150u8, 60] { |
| 2816 | let config = EncoderConfig { |
| 2817 | width, |
| 2818 | height, |
| 2819 | base_q_idx: q, |
| 2820 | // One key frame then all inter, which is |
| 2821 | // `encode_sequence`'s only shape, and the gate's recipe. |
| 2822 | gop: frames, |
| 2823 | // `encode_sequence` writes an unspecified colour config. |
| 2824 | colour: Colour::Unspecified, |
| 2825 | tile_cols_log2: 0, |
| 2826 | tile_rows_log2: 0, |
| 2827 | }; |
| 2828 | let mut enc = Av1Encoder::with_pyramid(config, pyramid).unwrap(); |
| 2829 | let mut packets = Vec::new(); |
| 2830 | for picture in pictures { |
| 2831 | packets.extend(enc.encode_frames(picture).unwrap()); |
| 2832 | } |
| 2833 | packets.extend(enc.flush().unwrap()); |
| 2834 | assert_eq!( |
| 2835 | enc.pyramid().is_none(), |
| 2836 | is_screen, |
| 2837 | "{content} q={q}: the content gate read this clip the other way round" |
| 2838 | ); |
| 2839 | let sequence = crate::encode::encode_sequence(pictures, q, DEADZONE).unwrap(); |
| 2840 | assert_eq!( |
| 2841 | (packets.iter().map(|p| p.data.len()).sum::<usize>(), concat(&packets)), |
| 2842 | (sequence.stream.len(), sequence.stream.clone()), |
| 2843 | "{content} q={q}: the facade's stream is not the sequence path's" |
| 2844 | ); |
| 2845 | assert_eq!( |
| 2846 | sequence.frames.len(), |
| 2847 | frames, |
| 2848 | "{content} q={q}: one entry per picture, in display order" |
| 2849 | ); |
| 2850 | if is_screen { |
| 2851 | assert_eq!(packets.len(), frames, "{content} q={q}: one packet per picture"); |
| 2852 | for (i, (packet, coded)) in packets.iter().zip(&sequence.frames).enumerate() { |
| 2853 | let cropped = crate::encode::crop_encoded(coded, width, height); |
| 2854 | assert_eq!( |
| 2855 | (packet.data.len(), packet.data.clone()), |
| 2856 | (cropped.stream.len(), cropped.stream.clone()), |
| 2857 | "{content} q={q} frame {i}: the facade's bytes are not the \ |
| 2858 | sequence path's" |
| 2859 | ); |
| 2860 | } |
| 2861 | } else { |
| 2862 | assert!( |
| 2863 | packets.iter().any(|p| p.level == Level::Arf), |
| 2864 | "{content} q={q}: a non-screen stream coded no hidden frame" |
| 2865 | ); |
| 2866 | } |
| 2867 | } |
| 2868 | } |
| 2869 | } |
| 2870 | |
| 2871 | /// THE CONTENT GATE (lane-av1pyrgate): the coding pyramid is asked for by |
| 2872 | /// the caller but applied only to camera material. Over screen content |
| 2873 | /// the encoder must drop back to the flat path and code byte for byte |
| 2874 | /// what a flat encoder codes — that is what keeps the BD gate's screen |
| 2875 | /// row identical to the flat baseline — and over non-screen content the |
| 2876 | /// same request must still reorder (class `gate-blind-to-feature`: a gate |
| 2877 | /// that only checked the screen half would pass with the pyramid deleted). |
| 2878 | #[test] |
| 2879 | fn the_content_gate_keeps_screen_streams_flat() { |
| 2880 | let _knobs = crate::speed::knob_read(); |
| 2881 | let frames = 8usize; |
| 2882 | let pictures: Vec<Picture> = (0..frames).map(|t| test_card(64, 64, t)).collect(); |
| 2883 | let config = EncoderConfig { |
| 2884 | width: 64, |
| 2885 | height: 64, |
| 2886 | base_q_idx: 120, |
| 2887 | gop: frames, |
| 2888 | colour: Colour::Unspecified, |
| 2889 | tile_cols_log2: 0, |
| 2890 | tile_rows_log2: 0, |
| 2891 | }; |
| 2892 | crate::encode::force_screen(Some(true)); |
| 2893 | let mut flat = Av1Encoder::new(config).unwrap(); |
| 2894 | let flat_packets = encode_all(&mut flat, &pictures); |
| 2895 | let mut gated = Av1Encoder::with_pyramid(config, Pyramid::default()).unwrap(); |
| 2896 | let gated_packets = encode_all(&mut gated, &pictures); |
| 2897 | assert_eq!(gated.pyramid(), None, "the gate left a screen stream on the pyramid"); |
| 2898 | assert_eq!( |
| 2899 | concat(&gated_packets), |
| 2900 | concat(&flat_packets), |
| 2901 | "a screen stream's bytes are not the flat path's" |
| 2902 | ); |
| 2903 | crate::encode::force_screen(Some(false)); |
| 2904 | let mut kept = Av1Encoder::with_pyramid(config, Pyramid::default()).unwrap(); |
| 2905 | let kept_packets = encode_all(&mut kept, &pictures); |
| 2906 | assert_eq!(kept.pyramid(), Some(Pyramid::default()), "the gate ate a film stream"); |
| 2907 | assert!( |
| 2908 | kept_packets.iter().any(|p| p.level == Level::Arf), |
| 2909 | "a non-screen stream coded no hidden frame" |
| 2910 | ); |
| 2911 | crate::encode::force_screen(None); |
| 2912 | } |
| 2913 | |
| 2914 | /// A key frame every `gop` pictures, inter otherwise — checked against |
| 2915 | /// what the facade itself reports, and (below) against what `ffprobe` |
| 2916 | /// reads back out of the coded bytes. |
| 2917 | #[test] |
| 2918 | fn gop_cadence_is_honored() { |
| 2919 | let _knobs = crate::speed::knob_read(); |
| 2920 | let config = EncoderConfig { |
| 2921 | width: 64, |
| 2922 | height: 64, |
| 2923 | base_q_idx: 100, |
| 2924 | gop: 3, |
| 2925 | colour: Colour::Unspecified, |
| 2926 | tile_cols_log2: 0, |
| 2927 | tile_rows_log2: 0, |
| 2928 | }; |
| 2929 | let mut enc = Av1Encoder::new(config).unwrap(); |
| 2930 | let pictures: Vec<Picture> = (0..7).map(|t| test_card(64, 64, t)).collect(); |
| 2931 | let keys: Vec<bool> = encode_all(&mut enc, &pictures) |
| 2932 | .iter() |
| 2933 | .map(|p| p.key) |
| 2934 | .collect(); |
| 2935 | assert_eq!(keys, vec![true, false, false, true, false, false, true]); |
| 2936 | } |
| 2937 | |
| 2938 | fn ffprobe_frames(stream: &[u8]) -> Vec<(bool, u32, u32)> { |
| 2939 | let path = std::env::temp_dir().join(format!( |
| 2940 | "ec-av1-facade-probe-{}-{}.obu", |
| 2941 | std::process::id(), |
| 2942 | std::ptr::addr_of!(stream) as usize |
| 2943 | )); |
| 2944 | std::fs::write(&path, stream).expect("writing the probe stream"); |
| 2945 | let out = Command::new("ffprobe") |
| 2946 | .args([ |
| 2947 | "-v", |
| 2948 | "error", |
| 2949 | "-f", |
| 2950 | "obu", |
| 2951 | "-select_streams", |
| 2952 | "v:0", |
| 2953 | "-show_entries", |
| 2954 | "frame=key_frame,width,height", |
| 2955 | "-of", |
| 2956 | "csv=p=0", |
| 2957 | ]) |
| 2958 | .arg(&path) |
| 2959 | .output() |
| 2960 | .expect("ffprobe failed to run"); |
| 2961 | let _ = std::fs::remove_file(&path); |
| 2962 | assert!( |
| 2963 | out.status.success(), |
| 2964 | "ffprobe refused the stream: {}", |
| 2965 | String::from_utf8_lossy(&out.stderr) |
| 2966 | ); |
| 2967 | String::from_utf8_lossy(&out.stdout) |
| 2968 | .lines() |
| 2969 | .map(|line| { |
| 2970 | let mut f = line.trim().split(','); |
| 2971 | let key: u32 = f.next().unwrap().parse().unwrap(); |
| 2972 | let width: u32 = f.next().unwrap().parse().unwrap(); |
| 2973 | let height: u32 = f.next().unwrap().parse().unwrap(); |
| 2974 | (key == 1, width, height) |
| 2975 | }) |
| 2976 | .collect() |
| 2977 | } |
| 2978 | |
| 2979 | fn ffprobe_colour(stream: &[u8]) -> String { |
| 2980 | let path = std::env::temp_dir().join(format!( |
| 2981 | "ec-av1-facade-colour-probe-{}-{}.obu", |
| 2982 | std::process::id(), |
| 2983 | std::ptr::addr_of!(stream) as usize |
| 2984 | )); |
| 2985 | std::fs::write(&path, stream).expect("writing the probe stream"); |
| 2986 | let out = Command::new("ffprobe") |
| 2987 | .args([ |
| 2988 | "-v", |
| 2989 | "error", |
| 2990 | "-f", |
| 2991 | "obu", |
| 2992 | "-select_streams", |
| 2993 | "v:0", |
| 2994 | "-show_entries", |
| 2995 | "stream=color_primaries,color_transfer,color_space,color_range", |
| 2996 | "-of", |
| 2997 | "csv=p=0", |
| 2998 | ]) |
| 2999 | .arg(&path) |
| 3000 | .output() |
| 3001 | .expect("ffprobe failed to run"); |
| 3002 | let _ = std::fs::remove_file(&path); |
| 3003 | assert!( |
| 3004 | out.status.success(), |
| 3005 | "ffprobe refused the stream: {}", |
| 3006 | String::from_utf8_lossy(&out.stderr) |
| 3007 | ); |
| 3008 | String::from_utf8_lossy(&out.stdout).trim().to_string() |
| 3009 | } |
| 3010 | |
| 3011 | /// A 30-picture stream at gop 15 codes 2 key frames (pictures 0 and 15) |
| 3012 | /// and 28 inter ones, at an odd-ish (not superblock-multiple) size that |
| 3013 | /// exercises the pad/crop path -- `ffprobe`'s own `key_frame` flags and |
| 3014 | /// coded size confirm what the facade already reported. |
| 3015 | #[test] |
| 3016 | fn thirty_pictures_at_gop_fifteen_decode_to_two_key_frames() { |
| 3017 | let _knobs = crate::speed::knob_read(); |
| 3018 | if !have_ffmpeg() { |
| 3019 | eprintln!("SKIP thirty_pictures_at_gop_fifteen_decode_to_two_key_frames: no ffmpeg"); |
| 3020 | return; |
| 3021 | } |
| 3022 | let (width, height) = (96usize, 96usize); |
| 3023 | let config = EncoderConfig { |
| 3024 | width, |
| 3025 | height, |
| 3026 | base_q_idx: 120, |
| 3027 | gop: 15, |
| 3028 | colour: Colour::Bt709Limited, |
| 3029 | tile_cols_log2: 0, |
| 3030 | tile_rows_log2: 0, |
| 3031 | }; |
| 3032 | let mut enc = Av1Encoder::new(config).unwrap(); |
| 3033 | assert_eq!(enc.display_size(), (width, height)); |
| 3034 | let (coded_w, coded_h) = enc.coded_size(); |
| 3035 | assert_eq!( |
| 3036 | (coded_w, coded_h), |
| 3037 | ( |
| 3038 | width.next_multiple_of(SUPERBLOCK), |
| 3039 | height.next_multiple_of(SUPERBLOCK) |
| 3040 | ) |
| 3041 | ); |
| 3042 | |
| 3043 | let pictures: Vec<Picture> = (0..30).map(|t| test_card(width, height, t)).collect(); |
| 3044 | let packets: Vec<Packet> = encode_all(&mut enc, &pictures); |
| 3045 | let expect_key: Vec<bool> = (0..30).map(|t| t % 15 == 0).collect(); |
| 3046 | assert_eq!( |
| 3047 | packets.iter().map(|p| p.key).collect::<Vec<_>>(), |
| 3048 | expect_key, |
| 3049 | "facade's own key/inter flags" |
| 3050 | ); |
| 3051 | |
| 3052 | let stream = concat(&packets); |
| 3053 | let frames = ffprobe_frames(&stream); |
| 3054 | assert_eq!(frames.len(), 30, "ffprobe frame count"); |
| 3055 | for (t, (key, w, h)) in frames.iter().enumerate() { |
| 3056 | assert_eq!(*key, expect_key[t], "picture {t}: ffprobe key_frame flag"); |
| 3057 | assert_eq!( |
| 3058 | (*w, *h), |
| 3059 | (width as u32, height as u32), |
| 3060 | "picture {t}: ffprobe reports the true (display) size, not the padded coded one" |
| 3061 | ); |
| 3062 | } |
| 3063 | } |
| 3064 | |
| 3065 | /// The configured colour properties are what `ffprobe` reports back, |
| 3066 | /// spec 5.5.2's CICP triple plus range -- BT.709 limited here, since it |
| 3067 | /// is the default a player assumes and the one this test would silently |
| 3068 | /// pass without wiring for (`ffprobe` reports "unknown" for the |
| 3069 | /// hardcoded "unspecified" this crate wrote before the facade existed, |
| 3070 | /// which is a visibly different string). |
| 3071 | #[test] |
| 3072 | fn bt709_limited_colour_is_reported_by_ffprobe() { |
| 3073 | let _knobs = crate::speed::knob_read(); |
| 3074 | if !have_ffmpeg() { |
| 3075 | eprintln!("SKIP bt709_limited_colour_is_reported_by_ffprobe: no ffmpeg"); |
| 3076 | return; |
| 3077 | } |
| 3078 | let config = EncoderConfig { |
| 3079 | width: 64, |
| 3080 | height: 64, |
| 3081 | base_q_idx: 100, |
| 3082 | gop: 4, |
| 3083 | colour: Colour::Bt709Limited, |
| 3084 | tile_cols_log2: 0, |
| 3085 | tile_rows_log2: 0, |
| 3086 | }; |
| 3087 | let mut enc = Av1Encoder::new(config).unwrap(); |
| 3088 | let packets = encode_all(&mut enc, &[test_card(64, 64, 0)]); |
| 3089 | let colour = ffprobe_colour(&packets[0].data); |
| 3090 | assert_eq!(colour, "tv,bt709,bt709,bt709", "ffprobe colour fields"); |
| 3091 | } |
| 3092 | |
| 3093 | /// The same, for BT.601: a different set of CICP integers must produce a |
| 3094 | /// different string, or the wiring could be a no-op that happens to read |
| 3095 | /// as BT.709 for every input. |
| 3096 | #[test] |
| 3097 | fn bt601_limited_colour_is_reported_by_ffprobe() { |
| 3098 | let _knobs = crate::speed::knob_read(); |
| 3099 | if !have_ffmpeg() { |
| 3100 | eprintln!("SKIP bt601_limited_colour_is_reported_by_ffprobe: no ffmpeg"); |
| 3101 | return; |
| 3102 | } |
| 3103 | let config = EncoderConfig { |
| 3104 | width: 64, |
| 3105 | height: 64, |
| 3106 | base_q_idx: 100, |
| 3107 | gop: 4, |
| 3108 | colour: Colour::Bt601Limited, |
| 3109 | tile_cols_log2: 0, |
| 3110 | tile_rows_log2: 0, |
| 3111 | }; |
| 3112 | let mut enc = Av1Encoder::new(config).unwrap(); |
| 3113 | let packets = encode_all(&mut enc, &[test_card(64, 64, 0)]); |
| 3114 | let colour = ffprobe_colour(&packets[0].data); |
| 3115 | assert_eq!( |
| 3116 | colour, "tv,smpte170m,smpte170m,smpte170m", |
| 3117 | "ffprobe colour fields" |
| 3118 | ); |
| 3119 | } |
| 3120 | |
| 3121 | /// A frame whose size does not match the encoder's configured geometry |
| 3122 | /// is refused by name. |
| 3123 | #[test] |
| 3124 | fn geometry_mismatch_is_refused() { |
| 3125 | let _knobs = crate::speed::knob_read(); |
| 3126 | let config = EncoderConfig { |
| 3127 | width: 64, |
| 3128 | height: 64, |
| 3129 | base_q_idx: 100, |
| 3130 | gop: 4, |
| 3131 | colour: Colour::Bt709Limited, |
| 3132 | tile_cols_log2: 0, |
| 3133 | tile_rows_log2: 0, |
| 3134 | }; |
| 3135 | let mut enc = Av1Encoder::new(config).unwrap(); |
| 3136 | let err = enc.encode(&Picture::grey(32, 32)).unwrap_err(); |
| 3137 | assert!(err.to_string().contains("64x64"), "{err}"); |
| 3138 | } |
| 3139 | |
| 3140 | /// `gop == 0` is refused at construction, not the first `encode()` call. |
| 3141 | #[test] |
| 3142 | fn zero_gop_is_refused() { |
| 3143 | let _knobs = crate::speed::knob_read(); |
| 3144 | let config = EncoderConfig { |
| 3145 | width: 64, |
| 3146 | height: 64, |
| 3147 | base_q_idx: 100, |
| 3148 | gop: 0, |
| 3149 | colour: Colour::Bt709Limited, |
| 3150 | tile_cols_log2: 0, |
| 3151 | tile_rows_log2: 0, |
| 3152 | }; |
| 3153 | let err = Av1Encoder::new(config).unwrap_err(); |
| 3154 | assert!(err.to_string().contains("gop"), "{err}"); |
| 3155 | } |
| 3156 | |
| 3157 | /// The 12-frame real clip `real_clip_encodes_within_its_quality_and_size_budget` |
| 3158 | /// already gates on at `q=100` (`crates/ec-av1/src/encode.rs`), decoded down |
| 3159 | /// to this facade's own input size, and re-coded through the facade so the |
| 3160 | /// rate-target surface is exercised at the entry point a caller actually |
| 3161 | /// drives. |
| 3162 | fn h264_clip_frames(width: usize, height: usize, frames: usize) -> Option<Vec<Picture>> { |
| 3163 | if !have_ffmpeg() { |
| 3164 | return None; |
| 3165 | } |
| 3166 | // lane-av1speed3: the wall tables below are read on REAL film as |
| 3167 | // well as on the colour-bar fixture (`bars` vs `film` in the BD |
| 3168 | // gate's own vocabulary), and the film crop lives outside the repo -- |
| 3169 | // `EC_AV1_WALL_CLIP` names it. Unset everywhere else, so every other |
| 3170 | // caller still gets the fixture. |
| 3171 | let clip = match std::env::var("EC_AV1_WALL_CLIP") { |
| 3172 | Ok(p) => std::path::PathBuf::from(p), |
| 3173 | Err(_) => std::path::Path::new(env!("CARGO_MANIFEST_DIR")) |
| 3174 | .join("../../fixtures/video/h264-1080p-23.976-8bit.mp4"), |
| 3175 | }; |
| 3176 | if !clip.exists() { |
| 3177 | return None; |
| 3178 | } |
| 3179 | let out = Command::new("ffmpeg") |
| 3180 | .args(["-v", "error", "-i", clip.to_str().unwrap()]) |
| 3181 | .args(["-frames:v", &frames.to_string()]) |
| 3182 | .args(["-vf", &format!("scale={width}:{height}")]) |
| 3183 | .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"]) |
| 3184 | .output() |
| 3185 | .expect("ffmpeg failed to run"); |
| 3186 | assert!( |
| 3187 | out.status.success(), |
| 3188 | "{}", |
| 3189 | String::from_utf8_lossy(&out.stderr) |
| 3190 | ); |
| 3191 | let (luma, chroma) = (width * height, width * height / 4); |
| 3192 | let frame_len = luma + 2 * chroma; |
| 3193 | assert_eq!( |
| 3194 | out.stdout.len(), |
| 3195 | frame_len * frames, |
| 3196 | "expected {frames} 4:2:0 frames" |
| 3197 | ); |
| 3198 | Some( |
| 3199 | (0..frames) |
| 3200 | .map(|i| { |
| 3201 | let bytes = &out.stdout[i * frame_len..][..frame_len]; |
| 3202 | Picture { |
| 3203 | width, |
| 3204 | height, |
| 3205 | y: bytes[..luma].iter().map(|&v| u16::from(v)).collect(), |
| 3206 | u: bytes[luma..luma + chroma].iter().map(|&v| u16::from(v)).collect(), |
| 3207 | v: bytes[luma + chroma..].iter().map(|&v| u16::from(v)).collect(), |
| 3208 | } |
| 3209 | }) |
| 3210 | .collect(), |
| 3211 | ) |
| 3212 | } |
| 3213 | |
| 3214 | /// [`RateTarget::BytesPerFrame`] on a real, 24-frame clip lands its total |
| 3215 | /// coded size within ±20% of `frames * target` once the first few |
| 3216 | /// frames' settling has been discarded (the key frame's own reference |
| 3217 | /// state and the controller's first couple of steps). |
| 3218 | #[test] |
| 3219 | fn bytes_per_frame_target_settles_within_20_percent() { |
| 3220 | let _knobs = crate::speed::knob_read(); |
| 3221 | let Some(pictures) = h264_clip_frames(640, 384, 24) else { |
| 3222 | eprintln!("SKIP bytes_per_frame_target_settles_within_20_percent: no ffmpeg/fixture"); |
| 3223 | return; |
| 3224 | }; |
| 3225 | let target_bytes = 4_000u32; |
| 3226 | let config = EncoderConfig { |
| 3227 | width: 640, |
| 3228 | height: 384, |
| 3229 | base_q_idx: 100, |
| 3230 | gop: 24, |
| 3231 | colour: Colour::Bt709Limited, |
| 3232 | tile_cols_log2: 0, |
| 3233 | tile_rows_log2: 0, |
| 3234 | }; |
| 3235 | let mut enc = |
| 3236 | Av1Encoder::with_rate_target(config, RateTarget::BytesPerFrame(target_bytes)).unwrap(); |
| 3237 | let sizes: Vec<usize> = encode_all(&mut enc, &pictures) |
| 3238 | .iter() |
| 3239 | .map(|p| p.data.len()) |
| 3240 | .collect(); |
| 3241 | // Discard the key frame (always far larger than an inter target) and |
| 3242 | // the next 4 inter frames the loop needs to step toward it. |
| 3243 | let settled = &sizes[5..]; |
| 3244 | let mean = settled.iter().sum::<usize>() as f64 / settled.len() as f64; |
| 3245 | let low = f64::from(target_bytes) * 0.8; |
| 3246 | let high = f64::from(target_bytes) * 1.2; |
| 3247 | assert!( |
| 3248 | mean >= low && mean <= high, |
| 3249 | "settled mean {mean:.0} bytes/frame outside ±20% of {target_bytes} ({low:.0}..{high:.0}); sizes={sizes:?}" |
| 3250 | ); |
| 3251 | } |
| 3252 | |
| 3253 | /// [`RateTarget::Bitrate`] lands the achieved bitrate within ±5% of the |
| 3254 | /// target over 48 frames of a real clip, flat and under a pyramid alike, |
| 3255 | /// across a 5x span of bitrates. This is the accuracy claim of the |
| 3256 | /// target-bitrate mode: no two-pass, no lookahead, just each frame's size |
| 3257 | /// predicted from the previous frame of its own level, one clamped |
| 3258 | /// proportional step, and the level model |
| 3259 | /// ([`WEIGHT_LEVEL_GAIN`]) that says how the run's budget splits. |
| 3260 | /// |
| 3261 | /// The tolerance was ±10% and every arm was inside ±3.0% when it was cut |
| 3262 | /// to ±5%; the worst arm is the 2 Mbit/s pyramid at -4.4%, which is the |
| 3263 | /// ENCODER'S OWN CEILING showing through, not the loop's aim: at that |
| 3264 | /// rate the hidden slot already codes at `q_idx` 1 (its 22863 bytes a |
| 3265 | /// frame are the same at 1.5 and 2 Mbit/s) and the leaves sit at 1 + 12 |
| 3266 | /// `leaf_q_offset`, so this clip cannot be made to spend much past |
| 3267 | /// 2.4 Mbit/s under the default pyramid however the budget is split. |
| 3268 | #[test] |
| 3269 | fn bitrate_target_lands_within_5_percent_over_48_frames() { |
| 3270 | let _knobs = crate::speed::knob_read(); |
| 3271 | let (width, height, frames) = (640usize, 384usize, 48usize); |
| 3272 | let Some(pictures) = h264_clip_frames(width, height, frames) else { |
| 3273 | eprintln!("SKIP bitrate_target_lands_within_5_percent_over_48_frames: no ffmpeg/fixture"); |
| 3274 | return; |
| 3275 | }; |
| 3276 | let fps = 24.0; |
| 3277 | for bits_per_second in [384_000u32, 768_000, 1_536_000, 2_000_000] { |
| 3278 | let config = EncoderConfig { |
| 3279 | width, |
| 3280 | height, |
| 3281 | base_q_idx: 100, |
| 3282 | gop: frames, |
| 3283 | colour: Colour::Bt709Limited, |
| 3284 | tile_cols_log2: 0, |
| 3285 | tile_rows_log2: 0, |
| 3286 | }; |
| 3287 | let rate = RateTarget::Bitrate { |
| 3288 | bits_per_second, |
| 3289 | frames_per_second: fps, |
| 3290 | }; |
| 3291 | for pyramid in [None, Some(Pyramid::default())] { |
| 3292 | let mut enc = match pyramid { |
| 3293 | None => Av1Encoder::with_rate_target(config, rate).unwrap(), |
| 3294 | Some(p) => Av1Encoder::with_pyramid_and_rate_target(config, p, rate).unwrap(), |
| 3295 | }; |
| 3296 | let targets = enc.rate_loop.as_ref().unwrap().target; |
| 3297 | let mut coded = 0usize; |
| 3298 | // Per level, so a miss reads as WHICH level's model is off |
| 3299 | // rather than as one aggregate percentage. |
| 3300 | let (mut bytes, mut count) = ([0usize; 4], [0usize; 4]); |
| 3301 | let mut take = |packets: Vec<Packet>| { |
| 3302 | for packet in packets { |
| 3303 | coded += packet.data.len(); |
| 3304 | let i = match packet.level { |
| 3305 | Level::Key => 0, |
| 3306 | Level::Arf => 1, |
| 3307 | Level::Leaf => 2, |
| 3308 | Level::ShowExisting => 3, |
| 3309 | }; |
| 3310 | bytes[i] += packet.data.len(); |
| 3311 | count[i] += 1; |
| 3312 | } |
| 3313 | }; |
| 3314 | for picture in &pictures { |
| 3315 | take(enc.encode_frames(picture).unwrap()); |
| 3316 | } |
| 3317 | take(enc.flush().unwrap()); |
| 3318 | let seconds = frames as f64 / fps; |
| 3319 | let achieved = coded as f64 * 8.0 / seconds; |
| 3320 | let error = achieved / f64::from(bits_per_second) - 1.0; |
| 3321 | let per = |i: usize| match count[i] { |
| 3322 | 0 => "-".to_string(), |
| 3323 | n => format!("{n}x{}", bytes[i] / n), |
| 3324 | }; |
| 3325 | eprintln!( |
| 3326 | "bitrate {bits_per_second} bps, pyramid {}: {coded} bytes over {seconds:.2}s \ |
| 3327 | = {achieved:.0} bps ({:+.1}%) | targets {:.0}/{:.0}/{:.0} \ |
| 3328 | coded key {} arf {} leaf {}", |
| 3329 | pyramid.is_some(), |
| 3330 | 100.0 * error, |
| 3331 | targets[0], |
| 3332 | targets[1], |
| 3333 | targets[2], |
| 3334 | per(0), |
| 3335 | per(1), |
| 3336 | per(2), |
| 3337 | ); |
| 3338 | assert!( |
| 3339 | error.abs() <= 0.05, |
| 3340 | "achieved {achieved:.0} bps is {:+.1}% off the {bits_per_second} bps target \ |
| 3341 | (pyramid {})", |
| 3342 | 100.0 * error, |
| 3343 | pyramid.is_some(), |
| 3344 | ); |
| 3345 | } |
| 3346 | } |
| 3347 | } |
| 3348 | |
| 3349 | /// The `BytesPerFrame` controller's own windup bound: no frame's coded |
| 3350 | /// `base_q_idx` step exceeds [`RateLoop::STEP_CLAMP`], across a real |
| 3351 | /// clip's full range of content (so a scene cut can't be the one frame |
| 3352 | /// that breaks the bound). |
| 3353 | /// |
| 3354 | /// The SEEDING frame is the one exemption ([`RateLoop::update`]): a slot |
| 3355 | /// that has coded nothing yet is still sitting on the caller's |
| 3356 | /// `base_q_idx` guess, and its first step is the acquisition jump, not |
| 3357 | /// windup. Exactly one frame is exempt -- the loop below asserts the |
| 3358 | /// bound on every frame after it, which is where a scene cut would |
| 3359 | /// break it. |
| 3360 | #[test] |
| 3361 | fn bytes_per_frame_controller_never_oscillates_past_its_clamp() { |
| 3362 | let _knobs = crate::speed::knob_read(); |
| 3363 | let Some(pictures) = h264_clip_frames(640, 384, 24) else { |
| 3364 | eprintln!( |
| 3365 | "SKIP bytes_per_frame_controller_never_oscillates_past_its_clamp: no ffmpeg/fixture" |
| 3366 | ); |
| 3367 | return; |
| 3368 | }; |
| 3369 | let config = EncoderConfig { |
| 3370 | width: 640, |
| 3371 | height: 384, |
| 3372 | base_q_idx: 100, |
| 3373 | gop: 24, |
| 3374 | colour: Colour::Bt709Limited, |
| 3375 | tile_cols_log2: 0, |
| 3376 | tile_rows_log2: 0, |
| 3377 | }; |
| 3378 | let mut enc = |
| 3379 | Av1Encoder::with_rate_target(config, RateTarget::BytesPerFrame(4_000)).unwrap(); |
| 3380 | let mut prev_q = enc.rate_loop.as_ref().unwrap().q_idx(Level::Leaf); |
| 3381 | // The first frame this encoder EMITS is several `encode_frames` calls |
| 3382 | // in (the lookahead queue holds the earlier ones), so the seeding |
| 3383 | // step is not frame zero -- it is the first frame `q` moves at all. |
| 3384 | let mut seeded = false; |
| 3385 | let mut seed_frame = None; |
| 3386 | for (frame, picture) in pictures.iter().enumerate() { |
| 3387 | enc.encode_frames(picture).unwrap(); |
| 3388 | let q = enc.rate_loop.as_ref().unwrap().q_idx(Level::Leaf); |
| 3389 | let step = (i32::from(q) - i32::from(prev_q)).abs(); |
| 3390 | if step > 0 && !seeded { |
| 3391 | seeded = true; |
| 3392 | seed_frame = Some(frame); |
| 3393 | } else { |
| 3394 | assert!( |
| 3395 | f64::from(step) <= RateLoop::STEP_CLAMP + 1.0, // +1 for u8 rounding |
| 3396 | "frame {frame}: q stepped from {prev_q} to {q}, past the {} clamp", |
| 3397 | RateLoop::STEP_CLAMP |
| 3398 | ); |
| 3399 | } |
| 3400 | prev_q = q; |
| 3401 | } |
| 3402 | assert!( |
| 3403 | seed_frame.is_some(), |
| 3404 | "the controller never steered at all -- the bound below is vacuous" |
| 3405 | ); |
| 3406 | } |
| 3407 | |
| 3408 | fn psnr(a: &[u16], b: &[u16]) -> f64 { |
| 3409 | let squared: f64 = a |
| 3410 | .iter() |
| 3411 | .zip(b) |
| 3412 | .map(|(&x, &y)| { |
| 3413 | let d = f64::from(x) - f64::from(y); |
| 3414 | d * d |
| 3415 | }) |
| 3416 | .sum(); |
| 3417 | if squared == 0.0 { |
| 3418 | return f64::INFINITY; |
| 3419 | } |
| 3420 | 10.0 * (255.0 * 255.0 * a.len() as f64 / squared).log10() |
| 3421 | } |
| 3422 | |
| 3423 | /// Decodes an OBU stream back to raw luma planes via `ffmpeg`/dav1d, one |
| 3424 | /// entry per coded frame, in order — this facade's own equivalent of |
| 3425 | /// `encode::tests::ffmpeg_decode_sequence`, needed here too since a |
| 3426 | /// PSNR check needs the decoded pixels, not just the coded byte count. |
| 3427 | fn ffmpeg_decode_planes( |
| 3428 | stream: &[u8], |
| 3429 | width: usize, |
| 3430 | height: usize, |
| 3431 | ) -> Vec<(Vec<u8>, Vec<u8>, Vec<u8>)> { |
| 3432 | let path = std::env::temp_dir().join(format!( |
| 3433 | "ec-av1-facade-rate-decode-{}-{}.obu", |
| 3434 | std::process::id(), |
| 3435 | std::ptr::addr_of!(stream) as usize |
| 3436 | )); |
| 3437 | std::fs::write(&path, stream).expect("writing the decode probe stream"); |
| 3438 | let out = Command::new("ffmpeg") |
| 3439 | .args(["-v", "error", "-f", "obu", "-i"]) |
| 3440 | .arg(&path) |
| 3441 | .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"]) |
| 3442 | .output() |
| 3443 | .expect("ffmpeg failed to run"); |
| 3444 | let _ = std::fs::remove_file(&path); |
| 3445 | assert!( |
| 3446 | out.status.success(), |
| 3447 | "{}", |
| 3448 | String::from_utf8_lossy(&out.stderr) |
| 3449 | ); |
| 3450 | let (luma, chroma) = (width * height, width * height / 4); |
| 3451 | let frame_len = luma + 2 * chroma; |
| 3452 | out.stdout |
| 3453 | .chunks_exact(frame_len) |
| 3454 | .map(|f| { |
| 3455 | ( |
| 3456 | f[..luma].to_vec(), |
| 3457 | f[luma..luma + chroma].to_vec(), |
| 3458 | f[luma + chroma..].to_vec(), |
| 3459 | ) |
| 3460 | }) |
| 3461 | .collect() |
| 3462 | } |
| 3463 | |
| 3464 | /// [`ffmpeg_decode_planes`]' luma half, which is what most rows compare. |
| 3465 | fn ffmpeg_decode_luma(stream: &[u8], width: usize, height: usize) -> Vec<Vec<u8>> { |
| 3466 | ffmpeg_decode_planes(stream, width, height) |
| 3467 | .into_iter() |
| 3468 | .map(|(y, _, _)| y) |
| 3469 | .collect() |
| 3470 | } |
| 3471 | |
| 3472 | /// lane-palw: OUR encoder's own witness for the writer half of the |
| 3473 | /// palette on-screen defect. `screen_card` at 384x152 is 38 mi rows tall, |
| 3474 | /// so the bottom superblock row's palette blocks hang 8 luma rows off the |
| 3475 | /// mi grid: spec 5.11.50 codes their colour-index map over the ON-SCREEN |
| 3476 | /// corner only and replicates it outward, and the writer used to code the |
| 3477 | /// full block grid -- symbols a conformant decoder never reads, so |
| 3478 | /// ffmpeg/dav1d desynced the rest of the tile while our own trial decode |
| 3479 | /// (unclamped on both sides) agreed with itself. Class |
| 3480 | /// `writer-phantom-units-past-edge`. |
| 3481 | /// |
| 3482 | /// Driven through the ENTRY SURFACE, `Av1Encoder` (what the editor's |
| 3483 | /// export calls), and compared on EVERY plane -- a chroma palette map is |
| 3484 | /// cut by the same edge. `palette_cut_maps_written` is asserted non-zero |
| 3485 | /// so the row cannot pass on a stream that cuts no palette map (class |
| 3486 | /// gate-blind-to-feature). |
| 3487 | #[test] |
| 3488 | fn a_palette_block_cut_by_the_frame_edge_decodes_exactly_through_ffmpeg() { |
| 3489 | const NAME: &str = "a_palette_block_cut_by_the_frame_edge_decodes_exactly_through_ffmpeg"; |
| 3490 | let _knobs = crate::speed::knob_read(); |
| 3491 | let _gate_lock = crate::stream::tests::lock_gate_counters(); |
| 3492 | let (width, height) = (384usize, 152usize); |
| 3493 | // A 16-px two-tone checkerboard: every 16x16 and 32x32 block holds at |
| 3494 | // most two luma values, so the palette arm wins across the WHOLE |
| 3495 | // frame -- including the bottom superblock row, whose 16x16 blocks at |
| 3496 | // y=144 and 32x32 blocks at y=128 hang past the 152-row mi grid. |
| 3497 | // `screen_card`'s 4-px bands fire only 9 palettes here and none of |
| 3498 | // them at the cut edge (class gate-blind-to-feature). |
| 3499 | let card = |shift: usize| -> Picture { |
| 3500 | let mut picture = Picture::grey(width, height); |
| 3501 | for y in 0..height { |
| 3502 | for x in 0..width { |
| 3503 | let cell = ((x + shift) / 8 + y / 8) % 2; |
| 3504 | picture.y[y * width + x] = if cell == 0 { 40 } else { 200 }; |
| 3505 | } |
| 3506 | } |
| 3507 | picture |
| 3508 | }; |
| 3509 | let sources: Vec<Picture> = (0..2).map(|t| card(t * 16)).collect(); |
| 3510 | let config = EncoderConfig { |
| 3511 | width, |
| 3512 | height, |
| 3513 | base_q_idx: 60, |
| 3514 | gop: 2, |
| 3515 | colour: Colour::Bt709Limited, |
| 3516 | tile_cols_log2: 0, |
| 3517 | tile_rows_log2: 0, |
| 3518 | }; |
| 3519 | let mut enc = Av1Encoder::new(config).unwrap(); |
| 3520 | crate::tile::reset_palette_cut_maps_written(); |
| 3521 | let mut stream = Vec::new(); |
| 3522 | for packet in encode_all(&mut enc, &sources) { |
| 3523 | stream.extend_from_slice(&packet.data); |
| 3524 | } |
| 3525 | eprintln!("{NAME}: {} cut colour-index maps written", crate::tile::palette_cut_maps_written()); |
| 3526 | assert!( |
| 3527 | crate::tile::palette_cut_maps_written() > 0, |
| 3528 | "{NAME}: no palette block is cut by the frame edge here -- the gate would pass blind" |
| 3529 | ); |
| 3530 | let ours = crate::stream::decode_stream(&stream).expect("our decoder"); |
| 3531 | assert_eq!(ours.len(), sources.len(), "{NAME}: our decoder's frames"); |
| 3532 | if !have_ffmpeg() { |
| 3533 | eprintln!("SKIP the ffmpeg half of {NAME}: no ffmpeg"); |
| 3534 | return; |
| 3535 | } |
| 3536 | let theirs = ffmpeg_decode_planes(&stream, width, height); |
| 3537 | assert_eq!(theirs.len(), sources.len(), "{NAME}: ffmpeg's frames"); |
| 3538 | for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() { |
| 3539 | for (plane, got, want) in [ |
| 3540 | ("luma", &a.y, &b.0), |
| 3541 | ("U", &a.u, &b.1), |
| 3542 | ("V", &a.v, &b.2), |
| 3543 | ] { |
| 3544 | let got: Vec<u8> = got.iter().map(|&v| v as u8).collect(); |
| 3545 | if let Some(at) = got.iter().zip(want).position(|(x, y)| x != y) { |
| 3546 | let w = if plane == "luma" { width } else { width / 2 }; |
| 3547 | panic!( |
| 3548 | "{NAME}: frame {i} {plane} differs first at ({}, {}): ours {} vs ffmpeg {}", |
| 3549 | at % w, |
| 3550 | at / w, |
| 3551 | got[at], |
| 3552 | want[at], |
| 3553 | ); |
| 3554 | } |
| 3555 | } |
| 3556 | } |
| 3557 | } |
| 3558 | |
| 3559 | /// A pyramid stream reorders pictures: the hidden `ALTREF` of each |
| 3560 | /// mini-GOP is coded before the leaves that precede it in display order, |
| 3561 | /// and a `show_existing_frame` header puts it back. This pins the shape |
| 3562 | /// (one packet per source picture plus one `show_existing_frame` per |
| 3563 | /// group, `dts` monotone, `order` NOT monotone) and then decodes the |
| 3564 | /// whole stream through OUR decoder and through ffmpeg/dav1d and requires |
| 3565 | /// the two display-order outputs to agree sample for sample — the |
| 3566 | /// [[gate-blind-to-hidden-frames]] check: a hidden frame that is never |
| 3567 | /// output, or output twice, or output in the wrong position, changes the |
| 3568 | /// display-order list and fails here. |
| 3569 | #[test] |
| 3570 | fn a_pyramid_stream_decodes_in_display_order_through_both_decoders() { |
| 3571 | // `take_ref_frame_hits` is a process-global counter: a reader-locked |
| 3572 | // sibling encoding at the same time zeroes it between our encode and |
| 3573 | // our read (seen once: LAST 0 GOLDEN 0 ALTREF 0), so this takes the |
| 3574 | // exclusive lock. |
| 3575 | let _knobs = crate::speed::knob_write(); |
| 3576 | pyramid_round_trip(Pyramid { mini_gop: 4, mid_q_offset: None, ..Pyramid::default() }, 2); |
| 3577 | } |
| 3578 | |
| 3579 | /// The same round trip over a THREE-level group (`mid_q_offset`): each |
| 3580 | /// mini-GOP now codes two hidden frames -- the top ARF at the group's |
| 3581 | /// last picture and the mid ARF at the middle of the leaf run -- and |
| 3582 | /// re-outputs both with `show_existing_frame`, so a mid frame emitted in |
| 3583 | /// the wrong display position, or twice, fails the display-order compare |
| 3584 | /// against ffmpeg exactly as a top ARF does. |
| 3585 | #[test] |
| 3586 | fn a_three_level_pyramid_stream_decodes_in_display_order() { |
| 3587 | let _knobs = crate::speed::knob_write(); |
| 3588 | pyramid_round_trip( |
| 3589 | Pyramid { mini_gop: 8, mid_q_offset: Some(-8), ..Pyramid::default() }, |
| 3590 | 2, |
| 3591 | ); |
| 3592 | } |
| 3593 | |
| 3594 | /// The same round trip over a FOUR-level group |
| 3595 | /// ([`Pyramid::quarter_q_offset`]): a mini-GOP of eight now codes four |
| 3596 | /// hidden frames -- the top ARF at picture 8, the mid at 4 and the two |
| 3597 | /// quarters at 2 and 6 -- each re-output by its own |
| 3598 | /// `show_existing_frame`. Every leaf reads a different pair of DPB slots |
| 3599 | /// than it did at three levels, so a slot map that lets one level |
| 3600 | /// overwrite a picture another is still reading shows up here as a |
| 3601 | /// display-order mismatch against ffmpeg. |
| 3602 | #[test] |
| 3603 | fn a_four_level_pyramid_stream_decodes_in_display_order() { |
| 3604 | let _knobs = crate::speed::knob_write(); |
| 3605 | pyramid_round_trip( |
| 3606 | Pyramid { |
| 3607 | mini_gop: 8, |
| 3608 | mid_q_offset: Some(-8), |
| 3609 | quarter_q_offset: Some(4), |
| 3610 | ..Pyramid::default() |
| 3611 | }, |
| 3612 | 4, |
| 3613 | ); |
| 3614 | } |
| 3615 | |
| 3616 | /// [`Pyramid::key_q_offset`] reaches the key frame: the whole run reads |
| 3617 | /// the key, so an offset that never arrived would be invisible in the BD |
| 3618 | /// table except as "no change" (class symbol-consumption-gap). A finer |
| 3619 | /// key must cost strictly more bytes than the same picture at base q. |
| 3620 | #[test] |
| 3621 | fn the_key_q_offset_reaches_the_key_frame() { |
| 3622 | let _knobs = crate::speed::knob_read(); |
| 3623 | crate::encode::force_screen(Some(false)); |
| 3624 | let key_bytes = |offset: i16| { |
| 3625 | let config = EncoderConfig { |
| 3626 | width: 128, |
| 3627 | height: 128, |
| 3628 | base_q_idx: 120, |
| 3629 | gop: 32, |
| 3630 | colour: Colour::Bt709Limited, |
| 3631 | tile_cols_log2: 0, |
| 3632 | tile_rows_log2: 0, |
| 3633 | }; |
| 3634 | let pyramid = Pyramid { key_q_offset: offset, ..Pyramid::default() }; |
| 3635 | let mut enc = Av1Encoder::with_pyramid(config, pyramid).unwrap(); |
| 3636 | let packets = enc.encode_frames(&test_card(128, 128, 0)).unwrap(); |
| 3637 | let key = packets.iter().find(|p| p.level == Level::Key).expect("key frame"); |
| 3638 | key.data.len() |
| 3639 | }; |
| 3640 | let (base, finer) = (key_bytes(0), key_bytes(-48)); |
| 3641 | eprintln!("key at base q {base} bytes, at base q - 48 {finer} bytes"); |
| 3642 | assert!(finer > base, "key_q_offset -48 did not reach the key frame ({finer} <= {base})"); |
| 3643 | } |
| 3644 | |
| 3645 | /// lane-last2's witness: a clip whose pictures ALTERNATE between two |
| 3646 | /// textures, so for every leaf the picture two back is an exact match and |
| 3647 | /// the one before it (`LAST_FRAME`) is not. With the lever on, the leaf |
| 3648 | /// chain alternates its refresh over [`LEAF_SLOTS`] and names the older |
| 3649 | /// slot `LAST2_FRAME`; blocks must actually be CODED off it |
| 3650 | /// ([[gate-blind-to-feature]]: a slot that is retained but never chosen |
| 3651 | /// proves only that the bookkeeping compiles), the stream must decode |
| 3652 | /// sample-exact through OUR decoder and through ffmpeg, and the hidden |
| 3653 | /// frames must still come out in display order. With the lever OFF the |
| 3654 | /// same clip codes ZERO `LAST2` blocks, which is what makes the counter a |
| 3655 | /// measurement of this lane and not of the reference set we already had. |
| 3656 | #[test] |
| 3657 | fn a_leaf_predicts_off_last2_when_the_picture_two_back_matches() { |
| 3658 | let _knobs = crate::speed::knob_write(); |
| 3659 | crate::encode::force_screen(Some(false)); |
| 3660 | let (width, height) = (128usize, 128usize); |
| 3661 | let sources: Vec<Picture> = |
| 3662 | (0..9).map(|t| test_card(width, height, (t % 2) * 24)).collect(); |
| 3663 | let run = |on: bool| -> ([usize; 8], Vec<u8>, Vec<Packet>) { |
| 3664 | set_last2(Some(on)); |
| 3665 | let config = EncoderConfig { |
| 3666 | width, |
| 3667 | height, |
| 3668 | base_q_idx: 120, |
| 3669 | gop: 32, |
| 3670 | colour: Colour::Bt709Limited, |
| 3671 | tile_cols_log2: 0, |
| 3672 | tile_rows_log2: 0, |
| 3673 | }; |
| 3674 | let pyramid = Pyramid { mini_gop: 4, mid_q_offset: None, ..Pyramid::default() }; |
| 3675 | let mut enc = Av1Encoder::with_pyramid(config, pyramid).unwrap(); |
| 3676 | let _ = crate::encode::take_ref_frame_hits(); |
| 3677 | let mut packets = Vec::new(); |
| 3678 | for picture in &sources { |
| 3679 | packets.extend(enc.encode_frames(picture).unwrap()); |
| 3680 | } |
| 3681 | packets.extend(enc.flush().unwrap()); |
| 3682 | let hits = crate::encode::take_ref_frame_hits(); |
| 3683 | (hits, concat(&packets), packets) |
| 3684 | }; |
| 3685 | let (off_hits, off_stream, _) = run(false); |
| 3686 | let (on_hits, stream, packets) = run(true); |
| 3687 | set_last2(None); |
| 3688 | eprintln!( |
| 3689 | "LAST2 off: LAST {} LAST2 {} GOLDEN {} ALTREF {} ({} B); \ |
| 3690 | on: LAST {} LAST2 {} GOLDEN {} ALTREF {} ({} B)", |
| 3691 | off_hits[1], off_hits[2], off_hits[4], off_hits[7], off_stream.len(), |
| 3692 | on_hits[1], on_hits[2], on_hits[4], on_hits[7], stream.len(), |
| 3693 | ); |
| 3694 | assert_eq!(off_hits[2], 0, "LAST2 was coded with the lever OFF"); |
| 3695 | assert!( |
| 3696 | on_hits[2] >= 8, |
| 3697 | "the picture two back matches exactly and only {} blocks were coded off LAST2", |
| 3698 | on_hits[2], |
| 3699 | ); |
| 3700 | |
| 3701 | // Display order and sample-exactness, both decoders (the same shape |
| 3702 | // `pyramid_round_trip` gates the hidden frames with). |
| 3703 | let ours = crate::stream::decode_stream(&stream).expect("our decoder"); |
| 3704 | assert_eq!(ours.len(), sources.len(), "our decoder's display-order count"); |
| 3705 | if !have_ffmpeg() { |
| 3706 | eprintln!("SKIP the ffmpeg half of the LAST2 witness: no ffmpeg"); |
| 3707 | return; |
| 3708 | } |
| 3709 | let theirs = ffmpeg_decode_luma(&stream, width, height); |
| 3710 | assert_eq!(theirs.len(), sources.len(), "ffmpeg's display-order count"); |
| 3711 | for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() { |
| 3712 | let got: Vec<u8> = a.y.iter().map(|&v| v as u8).collect(); |
| 3713 | assert_eq!(got.len(), b.len(), "frame {i}: luma size"); |
| 3714 | if let Some(at) = got.iter().zip(b).position(|(x, y)| x != y) { |
| 3715 | panic!( |
| 3716 | "display frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}", |
| 3717 | at % width, |
| 3718 | at / width, |
| 3719 | got[at], |
| 3720 | b[at], |
| 3721 | ); |
| 3722 | } |
| 3723 | } |
| 3724 | // The reordering itself is unchanged by the second leaf slot. |
| 3725 | let shown = packets.iter().filter(|p| p.level == Level::ShowExisting).count(); |
| 3726 | let arfs = packets.iter().filter(|p| p.level == Level::Arf).count(); |
| 3727 | assert_eq!(shown, arfs, "one show_existing_frame per hidden frame"); |
| 3728 | } |
| 3729 | |
| 3730 | /// A picture whose content is a static gradient plus a per-picture |
| 3731 | /// pseudo-random +-2 of noise: motion search matches the neighbours |
| 3732 | /// almost exactly, so the ARF temporal filter's weights are near 1 and |
| 3733 | /// the filter actually changes the source (a moving test card gives every |
| 3734 | /// neighbour a large MSE, weight ~0, and the filter is a no-op that would |
| 3735 | /// make the future-window witness below pass blind). |
| 3736 | fn noisy_card(width: usize, height: usize, t: usize) -> Picture { |
| 3737 | let mut picture = Picture::grey(width, height); |
| 3738 | let mut seed = (t as u64 + 1).wrapping_mul(0x9e37_79b9_7f4a_7c15); |
| 3739 | for y in 0..height { |
| 3740 | for x in 0..width { |
| 3741 | seed = seed.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1); |
| 3742 | let noise = ((seed >> 33) % 5) as i32 - 2; |
| 3743 | let base = 40 + (x + y) as i32 / 2; |
| 3744 | picture.y[y * width + x] = base.saturating_add(noise).clamp(0, 255) as u16; |
| 3745 | } |
| 3746 | } |
| 3747 | for i in 0..(width / 2) * (height / 2) { |
| 3748 | picture.u[i] = 110; |
| 3749 | picture.v[i] = 140; |
| 3750 | } |
| 3751 | picture |
| 3752 | } |
| 3753 | |
| 3754 | /// lane-lookahead's correctness witness. One group of lookahead |
| 3755 | /// (`Av1Encoder::drain_pending` hands the closed group to `ready` and |
| 3756 | /// codes the group before it) must not change WHAT is coded: |
| 3757 | /// |
| 3758 | /// * with the future half of the filter window empty AND the top ARF's |
| 3759 | /// temporal lambda window pinned to the past (`TPL_FUT=0`) the stream |
| 3760 | /// is byte for byte the one the encoder coded without a lookahead, at |
| 3761 | /// every run length -- 1 picture (no hidden frame at all), 7 (a short |
| 3762 | /// group), 8 (exactly `mini_gop`), 9 (a group plus a tail) and 17 -- |
| 3763 | /// and at a GOP short enough (8) that key frames drain the buffer |
| 3764 | /// mid-run. lane-tplhalf's WIN=11 default also reads that buffer, so |
| 3765 | /// the identity arm pins the lambda window off or this witness tests |
| 3766 | /// a different lever; |
| 3767 | /// * every run decodes to exactly its picture count through OUR decoder |
| 3768 | /// and through ffmpeg, sample-exact between the two, so the flush and |
| 3769 | /// the `show_existing_frame` order survive the delay; |
| 3770 | /// * and with ONE future neighbour the top ARF's source filter actually |
| 3771 | /// reads it -- the stream MOVES (class gate-blind-to-feature: a |
| 3772 | /// buffered picture nothing consumes would pass every check above). |
| 3773 | #[test] |
| 3774 | fn the_lookahead_holds_one_group_and_still_codes_every_picture() { |
| 3775 | let _knobs = crate::speed::knob_write(); |
| 3776 | // The preset is PROCESS-GLOBAL and another test may have left it |
| 3777 | // anywhere: at a high one every block of this fixture codes as skip |
| 3778 | // (17 pictures in 493 bytes) and the source filter cannot change a |
| 3779 | // byte, which failed the future-half assertion below in the suite and |
| 3780 | // passed it standalone (class process-global-knob-races-tests). |
| 3781 | let was = crate::speed::speed(); |
| 3782 | crate::speed::set_speed(0); |
| 3783 | crate::encode::force_screen(Some(false)); |
| 3784 | let (width, height) = (128usize, 128usize); |
| 3785 | let run = |n: usize, gop: usize, on: bool, fut: usize| -> (Vec<u8>, Vec<Packet>) { |
| 3786 | set_lookahead(Some(on)); |
| 3787 | set_arf_tf_future(Some(fut)); |
| 3788 | set_tpl_fut(Some(0)); |
| 3789 | let config = EncoderConfig { |
| 3790 | // FINE (not the 120 the other facade tests use): at a coarse |
| 3791 | // quantizer this fixture's ARF codes almost pure skip (17 |
| 3792 | // pictures in 493 bytes) and a filtered source quantizes back |
| 3793 | // to the same bytes, which made the future-half assertion |
| 3794 | // below depend on where the suite's other tests had left the |
| 3795 | // process-global preset. At q=60 the anchor carries real |
| 3796 | // coefficients and the filter must move them. |
| 3797 | base_q_idx: 60, |
| 3798 | width, |
| 3799 | height, |
| 3800 | gop, |
| 3801 | colour: Colour::Bt709Limited, |
| 3802 | tile_cols_log2: 0, |
| 3803 | tile_rows_log2: 0, |
| 3804 | }; |
| 3805 | let mut enc = Av1Encoder::with_pyramid(config, Pyramid::default()).unwrap(); |
| 3806 | let sources: Vec<Picture> = (0..n).map(|t| noisy_card(width, height, t)).collect(); |
| 3807 | let packets = encode_all(&mut enc, &sources); |
| 3808 | // The content gate is process-global and so is the preset: if |
| 3809 | // either has been flipped under this test the pyramid is gone and |
| 3810 | // there is no ARF to filter, which is a different failure from |
| 3811 | // "the future neighbour changed nothing" (the suite reported the |
| 3812 | // second when it meant the first). |
| 3813 | assert!( |
| 3814 | enc.pyramid().is_some(), |
| 3815 | "{n} pictures at gop {gop}: the content gate dropped the pyramid, so no ARF was coded (speed {})", |
| 3816 | crate::speed::speed(), |
| 3817 | ); |
| 3818 | (concat(&packets), packets) |
| 3819 | }; |
| 3820 | for gop in [32usize, 8] { |
| 3821 | for n in [1usize, 7, 8, 9, 17] { |
| 3822 | let (flat, flat_packets) = run(n, gop, false, 0); |
| 3823 | let (held, packets) = run(n, gop, true, 0); |
| 3824 | assert_eq!( |
| 3825 | flat.len(), |
| 3826 | held.len(), |
| 3827 | "{n} pictures at gop {gop}: the lookahead changed the stream LENGTH" |
| 3828 | ); |
| 3829 | assert!(flat == held, "{n} pictures at gop {gop}: the stream is not byte-identical"); |
| 3830 | assert_eq!( |
| 3831 | packets.iter().map(|p| (p.order, p.key, p.level)).collect::<Vec<_>>(), |
| 3832 | flat_packets.iter().map(|p| (p.order, p.key, p.level)).collect::<Vec<_>>(), |
| 3833 | "{n} pictures at gop {gop}: coding order/levels moved" |
| 3834 | ); |
| 3835 | let ours = crate::stream::decode_stream(&held).expect("our decoder"); |
| 3836 | assert_eq!(ours.len(), n, "{n} pictures at gop {gop}: our decoder's count"); |
| 3837 | if !have_ffmpeg() { |
| 3838 | continue; |
| 3839 | } |
| 3840 | let theirs = ffmpeg_decode_luma(&held, width, height); |
| 3841 | assert_eq!(theirs.len(), n, "{n} pictures at gop {gop}: ffmpeg's count"); |
| 3842 | for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() { |
| 3843 | let got: Vec<u8> = a.y.iter().map(|&v| v as u8).collect(); |
| 3844 | assert!( |
| 3845 | got == *b, |
| 3846 | "{n} pictures at gop {gop}, display frame {i}: ours differs from ffmpeg" |
| 3847 | ); |
| 3848 | } |
| 3849 | } |
| 3850 | } |
| 3851 | // The future half REACHES the filter, and what it produces still |
| 3852 | // decodes exactly. |
| 3853 | let (base, _) = run(17, 32, true, 0); |
| 3854 | let (symmetric, _) = run(17, 32, true, 1); |
| 3855 | set_lookahead(None); |
| 3856 | set_arf_tf_future(None); |
| 3857 | set_tpl_fut(None); |
| 3858 | assert!( |
| 3859 | base != symmetric, |
| 3860 | "one display-future neighbour left the top ARF's filter unchanged \ |
| 3861 | ({} B vs {} B, preset {})", |
| 3862 | base.len(), |
| 3863 | symmetric.len(), |
| 3864 | crate::speed::speed() |
| 3865 | ); |
| 3866 | let ours = crate::stream::decode_stream(&symmetric).expect("our decoder"); |
| 3867 | assert_eq!(ours.len(), 17, "the symmetric arm's display-order count"); |
| 3868 | if have_ffmpeg() { |
| 3869 | let theirs = ffmpeg_decode_luma(&symmetric, width, height); |
| 3870 | assert_eq!(theirs.len(), 17, "the symmetric arm's ffmpeg count"); |
| 3871 | for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() { |
| 3872 | let got: Vec<u8> = a.y.iter().map(|&v| v as u8).collect(); |
| 3873 | assert!(got == *b, "symmetric arm, display frame {i}: ours differs from ffmpeg"); |
| 3874 | } |
| 3875 | } |
| 3876 | crate::speed::set_speed(was); |
| 3877 | } |
| 3878 | |
| 3879 | /// lane-tplfut's correctness witness, the sibling of |
| 3880 | /// [`the_lookahead_holds_one_group_and_still_codes_every_picture`]: with |
| 3881 | /// the top ARF's TEMPORAL LAMBDA window taken out of the buffered next |
| 3882 | /// group (`speed::TPL_FUT`), every picture is still coded, the streams |
| 3883 | /// decode exactly through our decoder and ffmpeg, and the stream MOVES |
| 3884 | /// against the knob off wherever a next group exists (class |
| 3885 | /// gate-blind-to-feature). Coded at q=60, not 120: at a coarse |
| 3886 | /// quantizer this fixture's ARF is almost pure skip and a different |
| 3887 | /// lambda map re-quantises to identical bytes. |
| 3888 | #[test] |
| 3889 | fn the_future_tpl_window_still_codes_every_picture_and_moves_the_stream() { |
| 3890 | let _knobs = crate::speed::knob_write(); |
| 3891 | let was = crate::speed::speed(); |
| 3892 | crate::speed::set_speed(0); |
| 3893 | crate::encode::force_screen(Some(false)); |
| 3894 | let (width, height) = (128usize, 128usize); |
| 3895 | let run = |n: usize, gop: usize, fut: usize| -> (Vec<u8>, Vec<Packet>) { |
| 3896 | set_lookahead(Some(true)); |
| 3897 | set_arf_tf_future(Some(0)); |
| 3898 | set_tpl_fut(Some(fut)); |
| 3899 | let config = EncoderConfig { |
| 3900 | base_q_idx: 60, |
| 3901 | width, |
| 3902 | height, |
| 3903 | gop, |
| 3904 | colour: Colour::Bt709Limited, |
| 3905 | tile_cols_log2: 0, |
| 3906 | tile_rows_log2: 0, |
| 3907 | }; |
| 3908 | let mut enc = Av1Encoder::with_pyramid(config, Pyramid::default()).unwrap(); |
| 3909 | let sources: Vec<Picture> = (0..n).map(|t| noisy_card(width, height, t)).collect(); |
| 3910 | let packets = encode_all(&mut enc, &sources); |
| 3911 | assert!( |
| 3912 | enc.pyramid().is_some(), |
| 3913 | "{n} pictures at gop {gop}: the content gate dropped the pyramid (speed {})", |
| 3914 | crate::speed::speed(), |
| 3915 | ); |
| 3916 | (concat(&packets), packets) |
| 3917 | }; |
| 3918 | for gop in [32usize, 8] { |
| 3919 | for n in [1usize, 7, 8, 9, 17] { |
| 3920 | let (off, off_packets) = run(n, gop, 0); |
| 3921 | for mode in [1usize, 2, 3] { |
| 3922 | let (on, packets) = run(n, gop, mode); |
| 3923 | assert_eq!( |
| 3924 | packets.iter().map(|p| (p.order, p.key, p.level)).collect::<Vec<_>>(), |
| 3925 | off_packets.iter().map(|p| (p.order, p.key, p.level)).collect::<Vec<_>>(), |
| 3926 | "{n} pictures at gop {gop} mode {mode}: coding order/levels moved" |
| 3927 | ); |
| 3928 | let ours = crate::stream::decode_stream(&on).expect("our decoder"); |
| 3929 | assert_eq!(ours.len(), n, "{n} pictures at gop {gop} mode {mode}: our count"); |
| 3930 | if !have_ffmpeg() { |
| 3931 | continue; |
| 3932 | } |
| 3933 | let theirs = ffmpeg_decode_luma(&on, width, height); |
| 3934 | assert_eq!(theirs.len(), n, "{n} pictures at gop {gop} mode {mode}: ffmpeg count"); |
| 3935 | for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() { |
| 3936 | let got: Vec<u8> = a.y.iter().map(|&v| v as u8).collect(); |
| 3937 | assert!( |
| 3938 | got == *b, |
| 3939 | "{n} pictures at gop {gop} mode {mode}, frame {i}: ours differs from ffmpeg" |
| 3940 | ); |
| 3941 | } |
| 3942 | } |
| 3943 | let _ = &off; |
| 3944 | } |
| 3945 | } |
| 3946 | // The future window REACHES the lambda map: 17 pictures at gop 32 is |
| 3947 | // three groups, so the first two top ARFs each have a next group |
| 3948 | // buffered and their windows really are display-future. |
| 3949 | let (off, _) = run(17, 32, 0); |
| 3950 | // Mode 2 is NOT in this list: at its default split it keeps the three |
| 3951 | // NEAREST past neighbours, and those dominate the propagation -- on |
| 3952 | // this 128x128 fixture the map moves too little to flip an RD |
| 3953 | // decision and the stream comes back byte-identical to mode 0. Not a |
| 3954 | // dead knob: the same run with `EC_AV1_TPL_FUT_HALF=1` (one past |
| 3955 | // neighbour, six future) does move the stream, and the gate below |
| 3956 | // measures mode 2 on real content. |
| 3957 | for mode in [1usize, 3] { |
| 3958 | let (on, _) = run(17, 32, mode); |
| 3959 | assert!( |
| 3960 | off != on, |
| 3961 | "mode {mode} left the top ARF's temporal lambda map unchanged \ |
| 3962 | ({} B vs {} B, preset {})", |
| 3963 | off.len(), |
| 3964 | on.len(), |
| 3965 | crate::speed::speed() |
| 3966 | ); |
| 3967 | } |
| 3968 | set_lookahead(None); |
| 3969 | set_arf_tf_future(None); |
| 3970 | set_tpl_fut(None); |
| 3971 | crate::speed::set_speed(was); |
| 3972 | } |
| 3973 | |
| 3974 | /// lane-arfmode: the top ARF's leaf offer set. Three guards in one |
| 3975 | /// witness, over 17 pictures at gop 32 (three groups, so several top |
| 3976 | /// ARFs) at q=60 -- the lookahead witness's lesson: at a fine q the |
| 3977 | /// anchor carries real coefficients, so a cut that moves only the |
| 3978 | /// hidden frame's internal decisions cannot hide behind "everything |
| 3979 | /// quantized to the same bytes": |
| 3980 | /// |
| 3981 | /// 1. OFF (default and explicit `Some(0)`) is byte-identical -- the |
| 3982 | /// shipped table is 0 and the lever is bit-exact when off; |
| 3983 | /// 2. each armed mode (1 no intra, 2 no 8x8, 4 no compound) really |
| 3984 | /// FIRES -- its own [`crate::encode::take_arfmode_hits`] counter |
| 3985 | /// moves (class `gate-blind-to-feature`) -- and MOVES THE STREAM; |
| 3986 | /// 3. the coding order and levels never change, and every armed stream |
| 3987 | /// decodes sample-exact through `decode_stream` AND ffmpeg. |
| 3988 | #[test] |
| 3989 | fn the_arf_leaf_offer_set_fires_moves_the_stream_and_decodes_sample_exact() { |
| 3990 | let _knobs = crate::speed::knob_write(); |
| 3991 | let was = crate::speed::speed(); |
| 3992 | crate::speed::set_speed(0); |
| 3993 | crate::encode::force_screen(Some(false)); |
| 3994 | let (width, height) = (128usize, 128usize); |
| 3995 | let run = |mode: Option<u8>| -> (Vec<u8>, Vec<Packet>) { |
| 3996 | crate::encode::set_arfmode(mode); |
| 3997 | let _ = crate::encode::take_arfmode_hits(); |
| 3998 | let config = EncoderConfig { |
| 3999 | base_q_idx: 60, |
| 4000 | width, |
| 4001 | height, |
| 4002 | gop: 32, |
| 4003 | colour: Colour::Bt709Limited, |
| 4004 | tile_cols_log2: 0, |
| 4005 | tile_rows_log2: 0, |
| 4006 | }; |
| 4007 | let mut enc = Av1Encoder::with_pyramid(config, Pyramid::default()).unwrap(); |
| 4008 | // Groups at three luma LEVELS (the base ramp 40/110/180): the |
| 4009 | // middle group's top ARF sits halfway between the two dark/light |
| 4010 | // anchors its slots hold, which is exactly where neither |
| 4011 | // single-reference prediction nor intra wins by default -- the |
| 4012 | // AVERAGE of two references (compound) and the DC of the new |
| 4013 | // level (intra) do. Without this the synthetic cards' noise |
| 4014 | // quantizes to skip and no arm can move anything (measured: |
| 4015 | // 516 intra trials skipped, zero won, stream identical). |
| 4016 | let sources: Vec<Picture> = (0..17) |
| 4017 | .map(|t| { |
| 4018 | let mut p = noisy_card(width, height, t); |
| 4019 | let shift = 70i32 * (t / 8) as i32; |
| 4020 | for v in p.y.iter_mut() { |
| 4021 | *v = (i32::from(*v) + shift).clamp(0, 255) as u16; |
| 4022 | } |
| 4023 | p |
| 4024 | }) |
| 4025 | .collect(); |
| 4026 | let packets = encode_all(&mut enc, &sources); |
| 4027 | (concat(&packets), packets) |
| 4028 | }; |
| 4029 | let (off, off_packets) = run(None); |
| 4030 | let (explicit_off, _) = run(Some(0)); |
| 4031 | assert_eq!(off, explicit_off, "mode 0 is not bit-exact with the default"); |
| 4032 | for (mode, arm) in [(1u8, 0usize), (2, 1), (4, 2)] { |
| 4033 | let (on, packets) = run(Some(mode)); |
| 4034 | let hits = crate::encode::take_arfmode_hits(); |
| 4035 | assert_eq!( |
| 4036 | packets.iter().map(|p| (p.order, p.key, p.level)).collect::<Vec<_>>(), |
| 4037 | off_packets.iter().map(|p| (p.order, p.key, p.level)).collect::<Vec<_>>(), |
| 4038 | "mode {mode}: coding order/levels moved" |
| 4039 | ); |
| 4040 | assert!( |
| 4041 | hits[arm] > 0, |
| 4042 | "mode {mode}: its counter never fired ({hits:?}) -- the lever is \ |
| 4043 | gate-blind on this fixture", |
| 4044 | ); |
| 4045 | assert_ne!( |
| 4046 | off, on, |
| 4047 | "mode {mode} left the stream byte-identical despite {} firing hits", |
| 4048 | hits[arm], |
| 4049 | ); |
| 4050 | eprintln!("mode {mode}: {} -> {} B, hits {hits:?}", off.len(), on.len()); |
| 4051 | let ours = crate::stream::decode_stream(&on).expect("our decoder"); |
| 4052 | assert_eq!(ours.len(), 17, "mode {mode}: our decoder's picture count"); |
| 4053 | if !have_ffmpeg() { |
| 4054 | continue; |
| 4055 | } |
| 4056 | let theirs = ffmpeg_decode_luma(&on, width, height); |
| 4057 | assert_eq!(theirs.len(), 17, "mode {mode}: ffmpeg's picture count"); |
| 4058 | for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() { |
| 4059 | let got: Vec<u8> = a.y.iter().map(|&v| v as u8).collect(); |
| 4060 | assert!(got == *b, "mode {mode}, frame {i}: ours differs from ffmpeg"); |
| 4061 | } |
| 4062 | } |
| 4063 | crate::encode::set_arfmode(None); |
| 4064 | crate::speed::set_speed(was); |
| 4065 | } |
| 4066 | |
| 4067 | fn pyramid_round_trip(pyramid: Pyramid, hidden: usize) { |
| 4068 | let (width, height) = (128usize, 128usize); |
| 4069 | let config = EncoderConfig { |
| 4070 | width, |
| 4071 | height, |
| 4072 | base_q_idx: 120, |
| 4073 | gop: 32, |
| 4074 | colour: Colour::Bt709Limited, |
| 4075 | tile_cols_log2: 0, |
| 4076 | tile_rows_log2: 0, |
| 4077 | }; |
| 4078 | // The content gate ([`Av1Encoder::encode_frames`]) would drop a |
| 4079 | // screen-content stream to the flat path, and a synthetic test card |
| 4080 | // is exactly the few-colour picture the detector fires on: this gate |
| 4081 | // is about the reordering, so it asks for camera content explicitly. |
| 4082 | crate::encode::force_screen(Some(false)); |
| 4083 | let mut enc = Av1Encoder::with_pyramid(config, pyramid).unwrap(); |
| 4084 | let sources: Vec<Picture> = (0..9).map(|t| test_card(width, height, t * 3)).collect(); |
| 4085 | let _ = crate::encode::take_ref_frame_hits(); |
| 4086 | let mut packets = Vec::new(); |
| 4087 | for picture in &sources { |
| 4088 | packets.extend(enc.encode_frames(picture).unwrap()); |
| 4089 | } |
| 4090 | packets.extend(enc.flush().unwrap()); |
| 4091 | |
| 4092 | // Shape: every source picture is coded exactly once, and each closed |
| 4093 | // group adds one `show_existing_frame` packet. |
| 4094 | let coded: Vec<u64> = packets |
| 4095 | .iter() |
| 4096 | .filter(|p| p.level != Level::ShowExisting) |
| 4097 | .map(|p| p.order) |
| 4098 | .collect(); |
| 4099 | let mut sorted = coded.clone(); |
| 4100 | sorted.sort_unstable(); |
| 4101 | assert_eq!(sorted, (0..9).collect::<Vec<u64>>(), "one packet per picture"); |
| 4102 | assert_ne!(coded, sorted, "the pyramid never reordered anything"); |
| 4103 | let shown = packets.iter().filter(|p| p.level == Level::ShowExisting).count(); |
| 4104 | assert_eq!(shown, hidden, "one show_existing_frame per hidden frame"); |
| 4105 | for (i, p) in packets.iter().enumerate() { |
| 4106 | assert_eq!(p.dts, i as u64, "packet {i}: dts is the coding position"); |
| 4107 | } |
| 4108 | let hist = |l: Level| packets.iter().filter(|p| p.level == l).count(); |
| 4109 | eprintln!( |
| 4110 | "pyramid levels: key {} arf {} leaf {} show_existing {}", |
| 4111 | hist(Level::Key), |
| 4112 | hist(Level::Arf), |
| 4113 | hist(Level::Leaf), |
| 4114 | hist(Level::ShowExisting), |
| 4115 | ); |
| 4116 | assert_eq!(hist(Level::Arf), hidden, "hidden frames"); |
| 4117 | let refs = crate::encode::take_ref_frame_hits(); |
| 4118 | eprintln!( |
| 4119 | "blocks per reference: LAST {} GOLDEN {} ALTREF {}", |
| 4120 | refs[crate::mvstack::LAST_FRAME as usize], |
| 4121 | refs[crate::mvstack::GOLDEN_FRAME as usize], |
| 4122 | refs[crate::mvstack::ALTREF_FRAME as usize], |
| 4123 | ); |
| 4124 | // [[gate-blind-to-feature]]: the whole point of the hidden frame is |
| 4125 | // that the leaves predict BACKWARD off it, which is also the only |
| 4126 | // thing that exercises `ref_frame_sign_bias` in the MV stack. A green |
| 4127 | // round trip in which `ALTREF_FRAME` never won a block would prove |
| 4128 | // only that a hidden frame can be written and re-output. |
| 4129 | assert!( |
| 4130 | refs[crate::mvstack::ALTREF_FRAME as usize] > 0, |
| 4131 | "no block predicted off the hidden ALTREF" |
| 4132 | ); |
| 4133 | |
| 4134 | let stream = concat(&packets); |
| 4135 | let ours = crate::stream::decode_stream(&stream).expect("our decoder"); |
| 4136 | assert_eq!(ours.len(), sources.len(), "our decoder's display-order count"); |
| 4137 | if !have_ffmpeg() { |
| 4138 | eprintln!("SKIP the ffmpeg half of the pyramid round trip: no ffmpeg"); |
| 4139 | return; |
| 4140 | } |
| 4141 | let theirs = ffmpeg_decode_luma(&stream, width, height); |
| 4142 | assert_eq!(theirs.len(), sources.len(), "ffmpeg's display-order count"); |
| 4143 | for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() { |
| 4144 | let got: Vec<u8> = a.y.iter().map(|&v| v as u8).collect(); |
| 4145 | assert_eq!(got.len(), b.len(), "frame {i}: luma size"); |
| 4146 | if let Some(at) = got.iter().zip(b).position(|(x, y)| x != y) { |
| 4147 | panic!( |
| 4148 | "display frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}", |
| 4149 | at % width, |
| 4150 | at / width, |
| 4151 | got[at], |
| 4152 | b[at], |
| 4153 | ); |
| 4154 | } |
| 4155 | } |
| 4156 | } |
| 4157 | |
| 4158 | /// Every tile layout this encoder can write decodes SAMPLE-EXACT |
| 4159 | /// through both decoders -- ours and ffmpeg's -- and the frames really |
| 4160 | /// carry the tiles the header claims (the OBU parser locates one payload |
| 4161 | /// per tile, so a stream that quietly stayed single-tile fails here |
| 4162 | /// rather than passing on a green round trip). |
| 4163 | /// |
| 4164 | /// The bytes are what the gate is on: an encoder that clipped its |
| 4165 | /// neighbour availability wrong writes a stream whose two decoders agree |
| 4166 | /// with each other and disagree with nothing -- so the ffmpeg half is |
| 4167 | /// the one that catches a tile boundary the writer respected and the |
| 4168 | /// spec does not, and the parser half catches the reverse. |
| 4169 | |
| 4170 | /// A STATIC clip: every inter frame predicts perfectly from the last, so |
| 4171 | /// the search takes the 64x64 root ([`crate::encode::B64_ROOT`]) instead |
| 4172 | /// of coding four 32x32 quadrants, and the stream both decoders |
| 4173 | /// reconstruct is still sample-exact against the encoder's own |
| 4174 | /// reconstruction. The counter is the point (class |
| 4175 | /// `gate-blind-to-feature`): without it a green three-way compare says |
| 4176 | /// nothing about whether a single 64x64 block was ever written. |
| 4177 | /// lane-sb128 step 1: the same static clip under a 128x128 SUPERBLOCK. |
| 4178 | /// Every partition decision below the root is the one the 64-superblock |
| 4179 | /// encoder makes -- the root itself is always `PARTITION_SPLIT` into the |
| 4180 | /// four 64x64 superblocks -- so the only thing this proves is the |
| 4181 | /// structural syntax: the root's own partition symbol, its loop |
| 4182 | /// restoration read once over the 128 span at the 128 unit size, and |
| 4183 | /// libaom's TL/TR/BL/BR visit order. 256x128 is 2x1 128x128 superblocks |
| 4184 | /// per frame over three frames, so the root fires 6 times. |
| 4185 | /// |
| 4186 | /// `#[ignore]`: [`crate::encode::force_sb128`] moves a process-global |
| 4187 | /// (the superblock size is a sequence field), so this gate runs alone: |
| 4188 | /// |
| 4189 | /// cargo test -p ec-av1 --release --lib -- --ignored \ |
| 4190 | /// a_static_clip_codes_128x128_superblock_roots --nocapture |
| 4191 | #[test] |
| 4192 | #[ignore = "sets the process-global superblock size: run it alone"] |
| 4193 | fn a_static_clip_codes_128x128_superblock_roots_and_decodes_sample_exact() { |
| 4194 | let _knobs = crate::speed::knob_write(); |
| 4195 | let _gate_lock = crate::stream::tests::lock_gate_counters(); |
| 4196 | crate::encode::force_sb128(true); |
| 4197 | let (width, height) = (256usize, 128usize); |
| 4198 | let still = test_card(width, height, 0); |
| 4199 | let sources: Vec<Picture> = (0..3).map(|_| still.clone()).collect(); |
| 4200 | let config = EncoderConfig { |
| 4201 | width, |
| 4202 | height, |
| 4203 | base_q_idx: 120, |
| 4204 | gop: 8, |
| 4205 | colour: Colour::Bt709Limited, |
| 4206 | tile_cols_log2: 0, |
| 4207 | tile_rows_log2: 0, |
| 4208 | }; |
| 4209 | let mut enc = Av1Encoder::new(config).unwrap(); |
| 4210 | let mut stream = Vec::new(); |
| 4211 | let _ = crate::tile::take_sb128_root_hits(); |
| 4212 | for packet in encode_all(&mut enc, &sources) { |
| 4213 | stream.extend_from_slice(&packet.data); |
| 4214 | } |
| 4215 | let roots = crate::tile::take_sb128_root_hits(); |
| 4216 | assert!( |
| 4217 | roots >= 4, |
| 4218 | "a 128x128-superblock clip coded {roots} superblock roots, wanted at least 4" |
| 4219 | ); |
| 4220 | eprintln!("128x128 superblock roots: {roots}"); |
| 4221 | |
| 4222 | let ours = crate::stream::decode_stream(&stream).expect("our decoder"); |
| 4223 | assert_eq!(ours.len(), sources.len(), "our decoder's frames"); |
| 4224 | assert!( |
| 4225 | crate::decode::part128_split_hits() >= 4, |
| 4226 | "our decoder read no 128x128 superblock root" |
| 4227 | ); |
| 4228 | if !have_ffmpeg() { |
| 4229 | eprintln!("SKIP the ffmpeg half: no ffmpeg"); |
| 4230 | return; |
| 4231 | } |
| 4232 | let theirs = ffmpeg_decode_luma(&stream, width, height); |
| 4233 | assert_eq!(theirs.len(), sources.len(), "ffmpeg's frames"); |
| 4234 | for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() { |
| 4235 | let got: Vec<u8> = a.y.iter().map(|&v| v as u8).collect(); |
| 4236 | assert_eq!(&got, b, "frame {i}: ffmpeg and our decoder disagree"); |
| 4237 | } |
| 4238 | } |
| 4239 | |
| 4240 | #[test] |
| 4241 | fn a_static_clip_codes_64x64_roots_and_decodes_sample_exact() { |
| 4242 | let _knobs = crate::speed::knob_write(); |
| 4243 | let _gate_lock = crate::stream::tests::lock_gate_counters(); |
| 4244 | let (width, height) = (256usize, 128usize); |
| 4245 | let still = test_card(width, height, 0); |
| 4246 | let sources: Vec<Picture> = (0..3).map(|_| still.clone()).collect(); |
| 4247 | let config = EncoderConfig { |
| 4248 | width, |
| 4249 | height, |
| 4250 | base_q_idx: 120, |
| 4251 | gop: 8, |
| 4252 | colour: Colour::Bt709Limited, |
| 4253 | tile_cols_log2: 0, |
| 4254 | tile_rows_log2: 0, |
| 4255 | }; |
| 4256 | let mut enc = Av1Encoder::new(config).unwrap(); |
| 4257 | let mut stream = Vec::new(); |
| 4258 | let _ = crate::encode::take_b64_root_hits(); |
| 4259 | for packet in encode_all(&mut enc, &sources) { |
| 4260 | stream.extend_from_slice(&packet.data); |
| 4261 | } |
| 4262 | let roots = crate::encode::take_b64_root_hits(); |
| 4263 | // 8 superblocks per frame, two inter frames. |
| 4264 | assert!( |
| 4265 | roots > 0, |
| 4266 | "a static clip coded no 64x64 root at all (of 16 inter superblocks)" |
| 4267 | ); |
| 4268 | eprintln!("64x64 roots on a static clip: {roots} of 16 inter superblocks"); |
| 4269 | |
| 4270 | let ours = crate::stream::decode_stream(&stream).expect("our decoder"); |
| 4271 | assert_eq!(ours.len(), sources.len(), "our decoder's frames"); |
| 4272 | if !have_ffmpeg() { |
| 4273 | eprintln!("SKIP the ffmpeg half: no ffmpeg"); |
| 4274 | return; |
| 4275 | } |
| 4276 | let theirs = ffmpeg_decode_luma(&stream, width, height); |
| 4277 | assert_eq!(theirs.len(), sources.len(), "ffmpeg's frames"); |
| 4278 | for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() { |
| 4279 | let got: Vec<u8> = a.y.iter().map(|&v| v as u8).collect(); |
| 4280 | if let Some(at) = got.iter().zip(b).position(|(x, y)| x != y) { |
| 4281 | panic!( |
| 4282 | "frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}", |
| 4283 | at % width, |
| 4284 | at / width, |
| 4285 | got[at], |
| 4286 | b[at], |
| 4287 | ); |
| 4288 | } |
| 4289 | } |
| 4290 | } |
| 4291 | |
| 4292 | /// The same clip with a DC step between frames (lane-tx64): the 64x64 |
| 4293 | /// root still predicts the whole superblock from the last frame, but the |
| 4294 | /// prediction is uniformly off, so the root's NON-skip arm -- one |
| 4295 | /// TX_64X64 luma transform and two TX_32X32 chroma ones -- prices below |
| 4296 | /// its skip arm and a 64x64 residual is really written. The counter is |
| 4297 | /// the gate (class `gate-blind-to-feature`; the static clip above cannot |
| 4298 | /// reach this arm at all because its prediction is exact), and both |
| 4299 | /// decoders have to reconstruct those coefficients sample-exact -- a |
| 4300 | /// writer that names the wrong coefficient set or the wrong `txfm_split` |
| 4301 | /// desyncs the whole tile here. |
| 4302 | #[test] |
| 4303 | fn a_dc_stepped_clip_codes_a_64x64_residual_and_decodes_sample_exact() { |
| 4304 | let _knobs = crate::speed::knob_write(); |
| 4305 | let _gate_lock = crate::stream::tests::lock_gate_counters(); |
| 4306 | let (width, height) = (256usize, 128usize); |
| 4307 | let still = test_card(width, height, 0); |
| 4308 | let sources: Vec<Picture> = (0..3) |
| 4309 | .map(|t| { |
| 4310 | let mut p = still.clone(); |
| 4311 | let step = (t * 6) as u16; |
| 4312 | for v in &mut p.y { |
| 4313 | *v = (*v + step).min(255); |
| 4314 | } |
| 4315 | p |
| 4316 | }) |
| 4317 | .collect(); |
| 4318 | let config = EncoderConfig { |
| 4319 | width, |
| 4320 | height, |
| 4321 | base_q_idx: 120, |
| 4322 | gop: 8, |
| 4323 | colour: Colour::Bt709Limited, |
| 4324 | tile_cols_log2: 0, |
| 4325 | tile_rows_log2: 0, |
| 4326 | }; |
| 4327 | let mut enc = Av1Encoder::new(config).unwrap(); |
| 4328 | let mut stream = Vec::new(); |
| 4329 | let _ = crate::encode::take_b64_residual_hits(); |
| 4330 | for packet in encode_all(&mut enc, &sources) { |
| 4331 | stream.extend_from_slice(&packet.data); |
| 4332 | } |
| 4333 | let residuals = crate::encode::take_b64_residual_hits(); |
| 4334 | assert!( |
| 4335 | residuals > 0, |
| 4336 | "a DC-stepped clip coded no 64x64 root with a residual at all" |
| 4337 | ); |
| 4338 | eprintln!("64x64 roots with a residual: {residuals} of 16 inter superblocks"); |
| 4339 | |
| 4340 | let ours = crate::stream::decode_stream(&stream).expect("our decoder"); |
| 4341 | assert_eq!(ours.len(), sources.len(), "our decoder's frames"); |
| 4342 | if !have_ffmpeg() { |
| 4343 | eprintln!("SKIP the ffmpeg half: no ffmpeg"); |
| 4344 | return; |
| 4345 | } |
| 4346 | let theirs = ffmpeg_decode_luma(&stream, width, height); |
| 4347 | assert_eq!(theirs.len(), sources.len(), "ffmpeg's frames"); |
| 4348 | for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() { |
| 4349 | let got: Vec<u8> = a.y.iter().map(|&v| v as u8).collect(); |
| 4350 | if let Some(at) = got.iter().zip(b).position(|(x, y)| x != y) { |
| 4351 | panic!( |
| 4352 | "frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}", |
| 4353 | at % width, |
| 4354 | at / width, |
| 4355 | got[at], |
| 4356 | b[at], |
| 4357 | ); |
| 4358 | } |
| 4359 | } |
| 4360 | } |
| 4361 | |
| 4362 | /// A frame whose size is NOT a multiple of a superblock (lane-b64b): |
| 4363 | /// 232x168 leaves the last superblock column and row cut by the true |
| 4364 | /// frame edge, with more than half of each inside -- which is exactly |
| 4365 | /// what AV1's `has_cols`/`has_rows` allow to stay whole. Both gate films |
| 4366 | /// are superblock-aligned, so nothing but a synthetic size reaches this |
| 4367 | /// path at all (class `gate-blind-to-feature`), and the user's own |
| 4368 | /// exports are arbitrary sizes. |
| 4369 | #[test] |
| 4370 | fn a_non_superblock_aligned_clip_codes_edge_64x64_roots_and_decodes_sample_exact() { |
| 4371 | let _knobs = crate::speed::knob_write(); |
| 4372 | let _gate_lock = crate::stream::tests::lock_gate_counters(); |
| 4373 | let (width, height) = (232usize, 168usize); |
| 4374 | let still = test_card(width, height, 0); |
| 4375 | let sources: Vec<Picture> = (0..3).map(|_| still.clone()).collect(); |
| 4376 | let config = EncoderConfig { |
| 4377 | width, |
| 4378 | height, |
| 4379 | base_q_idx: 120, |
| 4380 | gop: 8, |
| 4381 | colour: Colour::Bt709Limited, |
| 4382 | tile_cols_log2: 0, |
| 4383 | tile_rows_log2: 0, |
| 4384 | }; |
| 4385 | let mut enc = Av1Encoder::new(config).unwrap(); |
| 4386 | let mut stream = Vec::new(); |
| 4387 | let _ = crate::encode::take_b64_edge_hits(); |
| 4388 | for packet in encode_all(&mut enc, &sources) { |
| 4389 | stream.extend_from_slice(&packet.data); |
| 4390 | } |
| 4391 | let edges = crate::encode::take_b64_edge_hits(); |
| 4392 | assert!(edges > 0, "no 64x64 root was taken at a superblock the frame edge cuts"); |
| 4393 | eprintln!("edge 64x64 roots: {edges}"); |
| 4394 | |
| 4395 | let ours = crate::stream::decode_stream(&stream).expect("our decoder"); |
| 4396 | assert_eq!(ours.len(), sources.len(), "our decoder's frames"); |
| 4397 | if !have_ffmpeg() { |
| 4398 | eprintln!("SKIP the ffmpeg half: no ffmpeg"); |
| 4399 | return; |
| 4400 | } |
| 4401 | let theirs = ffmpeg_decode_luma(&stream, width, height); |
| 4402 | assert_eq!(theirs.len(), sources.len(), "ffmpeg's frames"); |
| 4403 | for (i, (ours_i, theirs_i)) in ours.iter().zip(&theirs).enumerate() { |
| 4404 | let got: Vec<u8> = ours_i.y.iter().map(|&v| v as u8).collect(); |
| 4405 | if let Some(at) = got.iter().zip(theirs_i).position(|(x, y)| x != y) { |
| 4406 | panic!( |
| 4407 | "frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}", |
| 4408 | at % width, |
| 4409 | at / width, |
| 4410 | got[at], |
| 4411 | theirs_i[at], |
| 4412 | ); |
| 4413 | } |
| 4414 | } |
| 4415 | } |
| 4416 | |
| 4417 | /// The 1080p SHAPE at a fifth of its size (lane-sse): 384x216 is three |
| 4418 | /// whole superblock columns and 1.6875 superblock rows, so the bottom |
| 4419 | /// 88-pixel band straddles at EVERY level -- the 64x64 root lane-b64b |
| 4420 | /// already clipped, and the 32x32 (216 = 6*32 + 24) and 16x16 (13*16 + 8) |
| 4421 | /// leaves it did not. Every one of them is now scored over its inside |
| 4422 | /// part alone, and a distortion change that moved a partition or a |
| 4423 | /// transform decision the writer did not follow would desync the tile, so |
| 4424 | /// both decoders reconstruct it sample-exact. |
| 4425 | #[test] |
| 4426 | fn a_1080p_shaped_clip_straddles_at_every_block_size_and_decodes_sample_exact() { |
| 4427 | let _knobs = crate::speed::knob_write(); |
| 4428 | let _gate_lock = crate::stream::tests::lock_gate_counters(); |
| 4429 | let (width, height) = (384usize, 216usize); |
| 4430 | let sources: Vec<Picture> = (0..3).map(|i| test_card(width, height, i)).collect(); |
| 4431 | let config = EncoderConfig { |
| 4432 | width, |
| 4433 | height, |
| 4434 | base_q_idx: 120, |
| 4435 | gop: 8, |
| 4436 | colour: Colour::Bt709Limited, |
| 4437 | tile_cols_log2: 0, |
| 4438 | tile_rows_log2: 0, |
| 4439 | }; |
| 4440 | let mut enc = Av1Encoder::new(config).unwrap(); |
| 4441 | let mut stream = Vec::new(); |
| 4442 | for packet in encode_all(&mut enc, &sources) { |
| 4443 | stream.extend_from_slice(&packet.data); |
| 4444 | } |
| 4445 | let ours = crate::stream::decode_stream(&stream).expect("our decoder"); |
| 4446 | assert_eq!(ours.len(), sources.len(), "our decoder's frames"); |
| 4447 | if !have_ffmpeg() { |
| 4448 | eprintln!("SKIP the ffmpeg half: no ffmpeg"); |
| 4449 | return; |
| 4450 | } |
| 4451 | let theirs = ffmpeg_decode_luma(&stream, width, height); |
| 4452 | assert_eq!(theirs.len(), sources.len(), "ffmpeg's frames"); |
| 4453 | for (i, (ours_i, theirs_i)) in ours.iter().zip(&theirs).enumerate() { |
| 4454 | let got: Vec<u8> = ours_i.y.iter().map(|&v| v as u8).collect(); |
| 4455 | if let Some(at) = got.iter().zip(theirs_i).position(|(x, y)| x != y) { |
| 4456 | panic!( |
| 4457 | "frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}", |
| 4458 | at % width, |
| 4459 | at / width, |
| 4460 | got[at], |
| 4461 | theirs_i[at], |
| 4462 | ); |
| 4463 | } |
| 4464 | } |
| 4465 | } |
| 4466 | |
| 4467 | /// A clip whose inter residual is HIGH-FREQUENCY (lane-b64b): every |
| 4468 | /// frame adds a 4-pixel checkerboard, so the 64x64 root's prediction is |
| 4469 | /// off by exactly the detail a TX_64X64 throws away (it codes only the |
| 4470 | /// top-left 32x32 corner of its coefficient space) and the root's var-tx |
| 4471 | /// arm splits its luma into four TX_32X32 units instead. The counter is |
| 4472 | /// the gate (class `gate-blind-to-feature`), and a `txfm_split` the |
| 4473 | /// reader does not expect desyncs the whole tile, so both decoders have |
| 4474 | /// to reconstruct it sample-exact. |
| 4475 | #[test] |
| 4476 | fn a_high_frequency_clip_splits_the_64x64_roots_luma_and_decodes_sample_exact() { |
| 4477 | let _knobs = crate::speed::knob_write(); |
| 4478 | let _gate_lock = crate::stream::tests::lock_gate_counters(); |
| 4479 | let (width, height) = (256usize, 128usize); |
| 4480 | let still = test_card(width, height, 0); |
| 4481 | let sources: Vec<Picture> = (0..4) |
| 4482 | .map(|t| { |
| 4483 | let mut p = still.clone(); |
| 4484 | for (i, v) in p.y.iter_mut().enumerate() { |
| 4485 | let checker = ((i % width) / 4 + (i / width) / 4) % 2; |
| 4486 | let bump = (t * 5 * (checker + 1)) as u16; |
| 4487 | *v = (*v + bump).min(255); |
| 4488 | } |
| 4489 | p |
| 4490 | }) |
| 4491 | .collect(); |
| 4492 | let config = EncoderConfig { |
| 4493 | width, |
| 4494 | height, |
| 4495 | base_q_idx: 90, |
| 4496 | gop: 8, |
| 4497 | colour: Colour::Bt709Limited, |
| 4498 | tile_cols_log2: 0, |
| 4499 | tile_rows_log2: 0, |
| 4500 | }; |
| 4501 | let mut enc = Av1Encoder::new(config).unwrap(); |
| 4502 | let mut stream = Vec::new(); |
| 4503 | let _ = crate::encode::take_b64_var_tx_hits(); |
| 4504 | for packet in encode_all(&mut enc, &sources) { |
| 4505 | stream.extend_from_slice(&packet.data); |
| 4506 | } |
| 4507 | let split = crate::encode::take_b64_var_tx_hits(); |
| 4508 | assert!(split > 0, "no 64x64 root split its luma transform at all"); |
| 4509 | eprintln!("64x64 roots with a SPLIT luma transform: {split}"); |
| 4510 | |
| 4511 | let ours = crate::stream::decode_stream(&stream).expect("our decoder"); |
| 4512 | assert_eq!(ours.len(), sources.len(), "our decoder's frames"); |
| 4513 | if !have_ffmpeg() { |
| 4514 | eprintln!("SKIP the ffmpeg half: no ffmpeg"); |
| 4515 | return; |
| 4516 | } |
| 4517 | let theirs = ffmpeg_decode_luma(&stream, width, height); |
| 4518 | assert_eq!(theirs.len(), sources.len(), "ffmpeg's frames"); |
| 4519 | for (i, (ours_i, theirs_i)) in ours.iter().zip(&theirs).enumerate() { |
| 4520 | let got: Vec<u8> = ours_i.y.iter().map(|&v| v as u8).collect(); |
| 4521 | if let Some(at) = got.iter().zip(theirs_i).position(|(x, y)| x != y) { |
| 4522 | panic!( |
| 4523 | "frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}", |
| 4524 | at % width, |
| 4525 | at / width, |
| 4526 | got[at], |
| 4527 | theirs_i[at], |
| 4528 | ); |
| 4529 | } |
| 4530 | } |
| 4531 | } |
| 4532 | |
| 4533 | /// A CROSSFADE clip (lane-b64b): each picture is a linear blend of two |
| 4534 | /// stills, so on a leaf frame the average of its past (`LAST`) and future |
| 4535 | /// (`ALTREF`) references IS the source and neither reference alone is -- |
| 4536 | /// exactly the content a COMPOUND 64x64 root pays on. The counter is the |
| 4537 | /// gate (class `gate-blind-to-feature`): without it a green three-way |
| 4538 | /// compare says nothing about whether one compound root was written, and |
| 4539 | /// the writer's compound arm (`write_compound_block` at `SB_MI` 16, no |
| 4540 | /// `motion_mode` symbol) desyncs the whole tile if it is wrong. |
| 4541 | #[test] |
| 4542 | fn a_crossfade_clip_codes_a_compound_64x64_root_and_decodes_sample_exact() { |
| 4543 | let _knobs = crate::speed::knob_write(); |
| 4544 | let _gate_lock = crate::stream::tests::lock_gate_counters(); |
| 4545 | let (width, height) = (256usize, 128usize); |
| 4546 | let (a, b) = (test_card(width, height, 0), test_card(width, height, 24)); |
| 4547 | let sources: Vec<Picture> = (0..9) |
| 4548 | .map(|t| { |
| 4549 | let mut p = a.clone(); |
| 4550 | let w = t as u32; |
| 4551 | for (v, &other) in p.y.iter_mut().zip(&b.y) { |
| 4552 | *v = ((u32::from(*v) * (8 - w) + u32::from(other) * w) / 8) as u16; |
| 4553 | } |
| 4554 | p |
| 4555 | }) |
| 4556 | .collect(); |
| 4557 | let config = EncoderConfig { |
| 4558 | width, |
| 4559 | height, |
| 4560 | base_q_idx: 120, |
| 4561 | gop: 9, |
| 4562 | colour: Colour::Bt709Limited, |
| 4563 | tile_cols_log2: 0, |
| 4564 | tile_rows_log2: 0, |
| 4565 | }; |
| 4566 | let mut enc = Av1Encoder::new(config).unwrap(); |
| 4567 | let mut stream = Vec::new(); |
| 4568 | let _ = crate::encode::take_b64_compound_hits(); |
| 4569 | for packet in encode_all(&mut enc, &sources) { |
| 4570 | stream.extend_from_slice(&packet.data); |
| 4571 | } |
| 4572 | let compound = crate::encode::take_b64_compound_hits(); |
| 4573 | assert!(compound > 0, "a crossfade clip coded no COMPOUND 64x64 root at all"); |
| 4574 | eprintln!("compound 64x64 roots on a crossfade clip: {compound}"); |
| 4575 | |
| 4576 | let ours = crate::stream::decode_stream(&stream).expect("our decoder"); |
| 4577 | assert_eq!(ours.len(), sources.len(), "our decoder's frames"); |
| 4578 | if !have_ffmpeg() { |
| 4579 | eprintln!("SKIP the ffmpeg half: no ffmpeg"); |
| 4580 | return; |
| 4581 | } |
| 4582 | let theirs = ffmpeg_decode_luma(&stream, width, height); |
| 4583 | assert_eq!(theirs.len(), sources.len(), "ffmpeg's frames"); |
| 4584 | for (i, (ours_i, theirs_i)) in ours.iter().zip(&theirs).enumerate() { |
| 4585 | let got: Vec<u8> = ours_i.y.iter().map(|&v| v as u8).collect(); |
| 4586 | if let Some(at) = got.iter().zip(theirs_i).position(|(x, y)| x != y) { |
| 4587 | panic!( |
| 4588 | "frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}", |
| 4589 | at % width, |
| 4590 | at / width, |
| 4591 | got[at], |
| 4592 | theirs_i[at], |
| 4593 | ); |
| 4594 | } |
| 4595 | } |
| 4596 | } |
| 4597 | |
| 4598 | #[test] |
| 4599 | fn every_tile_layout_decodes_sample_exact_through_both_decoders() { |
| 4600 | let _knobs = crate::speed::knob_read(); |
| 4601 | let (width, height) = (640usize, 384usize); |
| 4602 | let sources: Vec<Picture> = (0..4).map(|t| test_card(width, height, t * 3)).collect(); |
| 4603 | let mut sizes = Vec::new(); |
| 4604 | for (cols_log2, rows_log2) in [(0u32, 0u32), (1, 0), (0, 1), (1, 1), (2, 1)] { |
| 4605 | let config = EncoderConfig { |
| 4606 | width, |
| 4607 | height, |
| 4608 | base_q_idx: 120, |
| 4609 | gop: 4, |
| 4610 | colour: Colour::Bt709Limited, |
| 4611 | tile_cols_log2: cols_log2, |
| 4612 | tile_rows_log2: rows_log2, |
| 4613 | }; |
| 4614 | let layout = format!("{}x{} tiles", 1 << cols_log2, 1 << rows_log2); |
| 4615 | // lane-b128m: the SPEC's uniform spacing derives the tile count |
| 4616 | // from the superblock grid (`tileWidthSb = ceil(sbCols >> log2)`), |
| 4617 | // so a frame with fewer superblock columns than the requested |
| 4618 | // count codes fewer tiles -- which is what a 128-superblock |
| 4619 | // sequence does here. The grid the encoder itself computes is the |
| 4620 | // expectation; at 64 superblocks it is `1 << log2` exactly. |
| 4621 | let grid = crate::tile::TileLayout::new( |
| 4622 | (width as u32).div_ceil(4), |
| 4623 | (height as u32).div_ceil(4), |
| 4624 | cols_log2, |
| 4625 | rows_log2, |
| 4626 | ); |
| 4627 | let (want_cols, want_rows) = (grid.cols(), grid.rows()); |
| 4628 | let mut enc = Av1Encoder::new(config).unwrap(); |
| 4629 | let mut stream = Vec::new(); |
| 4630 | for packet in encode_all(&mut enc, &sources) { |
| 4631 | stream.extend_from_slice(&packet.data); |
| 4632 | } |
| 4633 | sizes.push((layout.clone(), stream.len())); |
| 4634 | |
| 4635 | // The frames carry the tiles their headers claim. |
| 4636 | let mut parser = ec_av1_syntax::Av1Parser::new(); |
| 4637 | let mut frames = 0usize; |
| 4638 | let mut offset = 0usize; |
| 4639 | while offset < stream.len() { |
| 4640 | let obus = parser.parse_temporal_unit(&stream[offset..]).unwrap(); |
| 4641 | let unit: usize = obus.iter().map(|o| o.total_size).sum(); |
| 4642 | for obu in &obus { |
| 4643 | if let ec_av1_syntax::ObuKind::Frame(parsed, tiles) = &obu.kind { |
| 4644 | assert_eq!( |
| 4645 | (parsed.tile_info.cols, parsed.tile_info.rows), |
| 4646 | (want_cols, want_rows), |
| 4647 | "{layout}: the header's own tile grid" |
| 4648 | ); |
| 4649 | assert_eq!( |
| 4650 | tiles.len(), |
| 4651 | (want_cols * want_rows) as usize, |
| 4652 | "{layout}: tile payloads located in the tile group" |
| 4653 | ); |
| 4654 | frames += 1; |
| 4655 | } |
| 4656 | } |
| 4657 | offset += unit; |
| 4658 | } |
| 4659 | assert_eq!(frames, sources.len(), "{layout}: coded frames"); |
| 4660 | |
| 4661 | let ours = crate::stream::decode_stream(&stream).expect("our decoder"); |
| 4662 | assert_eq!(ours.len(), sources.len(), "{layout}: our decoder's frames"); |
| 4663 | if !have_ffmpeg() { |
| 4664 | eprintln!("SKIP the ffmpeg half of {layout}: no ffmpeg"); |
| 4665 | continue; |
| 4666 | } |
| 4667 | let theirs = ffmpeg_decode_luma(&stream, width, height); |
| 4668 | assert_eq!(theirs.len(), sources.len(), "{layout}: ffmpeg's frames"); |
| 4669 | for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() { |
| 4670 | let got: Vec<u8> = a.y.iter().map(|&v| v as u8).collect(); |
| 4671 | assert_eq!(got.len(), b.len(), "{layout} frame {i}: luma size"); |
| 4672 | if let Some(at) = got.iter().zip(b).position(|(x, y)| x != y) { |
| 4673 | panic!( |
| 4674 | "{layout} frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}", |
| 4675 | at % width, |
| 4676 | at / width, |
| 4677 | got[at], |
| 4678 | b[at], |
| 4679 | ); |
| 4680 | } |
| 4681 | } |
| 4682 | } |
| 4683 | let base = sizes[0].1 as f64; |
| 4684 | for (layout, bytes) in &sizes { |
| 4685 | eprintln!( |
| 4686 | "{layout}: {bytes} bytes ({:+.2}% vs one tile)", |
| 4687 | (*bytes as f64 / base - 1.0) * 100.0 |
| 4688 | ); |
| 4689 | } |
| 4690 | } |
| 4691 | |
| 4692 | /// lane-deltaq's three-way witness: a clip with a real gradient of tpl |
| 4693 | /// factors -- a moving detail region over a flat background, so the |
| 4694 | /// superblocks the NEXT picture predicts from are worth more than the |
| 4695 | /// ones it does not -- codes at least two distinct per-superblock |
| 4696 | /// quantizer levels (the fire count, class `gate-blind-to-feature`), and |
| 4697 | /// both decoders reconstruct every frame sample-exact from the |
| 4698 | /// `delta_qindex` syntax that carries them. |
| 4699 | #[test] |
| 4700 | fn a_moving_detail_clip_codes_two_delta_q_levels_both_decoders_read_exactly() { |
| 4701 | // `knob_write`, not `knob_read`: the override below is |
| 4702 | // process-global and every other test's bytes move under it. |
| 4703 | let _knobs = crate::speed::knob_write(); |
| 4704 | let _gate_lock = crate::stream::tests::lock_gate_counters(); |
| 4705 | crate::encode::set_deltaq_res(Some(2)); |
| 4706 | let (width, height) = (640usize, 384usize); |
| 4707 | // The gate's own moving test card, with a 128x128 patch of fine |
| 4708 | // detail travelling right by 32 samples a frame laid over it: the |
| 4709 | // patch is what the tpl pass finds worth propagating and the card |
| 4710 | // around it is not, so the map -- and with it the quantizer grid -- |
| 4711 | // is a gradient and not one flat number. |
| 4712 | let sources: Vec<Picture> = (0..4) |
| 4713 | .map(|t| { |
| 4714 | let mut p = test_card(width, height, t * 3); |
| 4715 | let x0 = 32 + t * 32; |
| 4716 | for y in 128..256 { |
| 4717 | for x in x0..x0 + 128 { |
| 4718 | p.y[y * width + x] = |
| 4719 | if (x / 2 + y / 3) % 2 == 0 { 40 } else { 210 }; |
| 4720 | } |
| 4721 | } |
| 4722 | p |
| 4723 | }) |
| 4724 | .collect(); |
| 4725 | let config = EncoderConfig { |
| 4726 | width, |
| 4727 | height, |
| 4728 | base_q_idx: 120, |
| 4729 | gop: 4, |
| 4730 | colour: Colour::Bt709Limited, |
| 4731 | tile_cols_log2: 0, |
| 4732 | tile_rows_log2: 0, |
| 4733 | }; |
| 4734 | let mut enc = Av1Encoder::new(config).unwrap(); |
| 4735 | let _ = crate::encode::take_deltaq_levels(); |
| 4736 | let mut stream = Vec::new(); |
| 4737 | for packet in encode_all(&mut enc, &sources) { |
| 4738 | stream.extend_from_slice(&packet.data); |
| 4739 | } |
| 4740 | let levels = crate::encode::take_deltaq_levels(); |
| 4741 | // The quantizer grid rides the tpl map, and `speed::TPL_DEPTH` cuts |
| 4742 | // the lookahead window to one picture at the top presets, so there IS |
| 4743 | // no map -- and no delta_q syntax -- there. The exactness half below |
| 4744 | // still runs; only the fire count needs a window (lane-tplwin: the |
| 4745 | // predicate is the window, not preset 0, since presets 1..6 have one). |
| 4746 | if crate::speed::at(&crate::speed::TPL_DEPTH) > 1 { |
| 4747 | assert!( |
| 4748 | levels >= 2, |
| 4749 | "the quantizer grid was flat ({levels} level(s)): no delta_qindex was coded" |
| 4750 | ); |
| 4751 | } else { |
| 4752 | eprintln!("SKIP the fire count at preset {}: no tpl map", crate::speed::speed()); |
| 4753 | } |
| 4754 | let ours = crate::stream::decode_stream(&stream).expect("our decoder"); |
| 4755 | assert_eq!(ours.len(), sources.len(), "our decoder's frames"); |
| 4756 | if have_ffmpeg() { |
| 4757 | let theirs = ffmpeg_decode_luma(&stream, width, height); |
| 4758 | assert_eq!(theirs.len(), sources.len(), "ffmpeg's frames"); |
| 4759 | for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() { |
| 4760 | let got: Vec<u8> = a.y.iter().map(|&v| v as u8).collect(); |
| 4761 | if let Some(at) = got.iter().zip(b).position(|(x, y)| x != y) { |
| 4762 | panic!( |
| 4763 | "frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}", |
| 4764 | at % width, |
| 4765 | at / width, |
| 4766 | got[at], |
| 4767 | b[at], |
| 4768 | ); |
| 4769 | } |
| 4770 | } |
| 4771 | } else { |
| 4772 | eprintln!("SKIP the ffmpeg half: no ffmpeg"); |
| 4773 | } |
| 4774 | crate::encode::set_deltaq_res(None); |
| 4775 | eprintln!("delta_q witness: {levels} quantizer levels, {} bytes", stream.len()); |
| 4776 | } |
| 4777 | |
| 4778 | /// lane-txset's witness: a clip of hard directional edges makes the intra |
| 4779 | /// luma search take EVERY type of the five-type reduced set |
| 4780 | /// (`TX_SET_INTRA_2`: `DCT_DCT`, `ADST_ADST`, `ADST_DCT`, `DCT_ADST`, |
| 4781 | /// `IDTX`) at least once -- the fire count, class `gate-blind-to-feature` |
| 4782 | /// -- and both decoders reconstruct every frame sample-exact from the |
| 4783 | /// `tx_type` symbols that name them. Before the lane the writer coded |
| 4784 | /// `DCT_DCT` for every luma transform unit ever written, so this is also |
| 4785 | /// the statement that the other four are REACHABLE at all. |
| 4786 | #[test] |
| 4787 | fn an_edge_clip_codes_every_reduced_set_tx_type_both_decoders_read_exactly() { |
| 4788 | // `knob_write`: the screen override below is process-global, and the |
| 4789 | // type search is SCREEN-ONLY (`encode::tx_type_candidates`). |
| 4790 | let _knobs = crate::speed::knob_write(); |
| 4791 | crate::encode::force_screen(Some(true)); |
| 4792 | let _gate_lock = crate::stream::tests::lock_gate_counters(); |
| 4793 | let (width, height) = (320usize, 192usize); |
| 4794 | // Sharp horizontal and vertical steps: a vertical edge is what an |
| 4795 | // `ADST` column pass beats a `DCT` one on, a horizontal edge the |
| 4796 | // mirror, and the flat/ramp areas between them are where `IDTX` wins. |
| 4797 | let sources: Vec<Picture> = (0..2) |
| 4798 | .map(|t| { |
| 4799 | let mut p = test_card(width, height, t * 3); |
| 4800 | for y in 0..height { |
| 4801 | for x in 0..width { |
| 4802 | let v = match ((x + t * 4) / 16 % 2, y / 16 % 2) { |
| 4803 | (0, 0) => 16u16, |
| 4804 | (1, 0) => 235, |
| 4805 | (0, 1) => (x % 64 * 3) as u16, |
| 4806 | _ => (y % 64 * 3) as u16, |
| 4807 | }; |
| 4808 | p.y[y * width + x] = v; |
| 4809 | } |
| 4810 | } |
| 4811 | p |
| 4812 | }) |
| 4813 | .collect(); |
| 4814 | let config = EncoderConfig { |
| 4815 | width, |
| 4816 | height, |
| 4817 | base_q_idx: 90, |
| 4818 | gop: 2, |
| 4819 | colour: Colour::Bt709Limited, |
| 4820 | tile_cols_log2: 0, |
| 4821 | tile_rows_log2: 0, |
| 4822 | }; |
| 4823 | let mut enc = Av1Encoder::new(config).unwrap(); |
| 4824 | let _ = crate::encode::take_tx_type_hits(); |
| 4825 | let mut stream = Vec::new(); |
| 4826 | for packet in encode_all(&mut enc, &sources) { |
| 4827 | stream.extend_from_slice(&packet.data); |
| 4828 | } |
| 4829 | let hits = crate::encode::take_tx_type_hits(); |
| 4830 | // The type search is a speed lever (`speed::TX_TYPE_SEARCH`); above |
| 4831 | // the presets that carry it only `DCT_DCT` is offered, and the |
| 4832 | // exactness half below is what still runs there. The FULL five-type |
| 4833 | // fire count is preset 0's to make: a faster preset prunes modes and |
| 4834 | // partitions before a type is ever priced on them, so `ADST_ADST` and |
| 4835 | // `IDTX` stop winning on this clip at preset 6 (measured: hits |
| 4836 | // `[0, 6192, 0, 79, 284, ..]`). Every preset that carries the lever |
| 4837 | // still has to reach SOME non-`DCT_DCT` type -- that is the |
| 4838 | // "reachable at all" statement, class `gate-blind-to-feature`. |
| 4839 | if crate::speed::at(&crate::speed::TX_TYPE_SEARCH) { |
| 4840 | let non_dct: usize = hits.iter().sum::<usize>() |
| 4841 | - hits[crate::transform::TxType::DctDct as usize]; |
| 4842 | assert!( |
| 4843 | non_dct > 0, |
| 4844 | "every luma transform unit took DCT_DCT: {hits:?}" |
| 4845 | ); |
| 4846 | } |
| 4847 | if crate::speed::at(&crate::speed::TX_TYPE_SEARCH) && crate::speed::speed() == 0 { |
| 4848 | for (name, ty) in [ |
| 4849 | ("DCT_DCT", crate::transform::TxType::DctDct), |
| 4850 | ("ADST_ADST", crate::transform::TxType::AdstAdst), |
| 4851 | ("ADST_DCT", crate::transform::TxType::AdstDct), |
| 4852 | ("DCT_ADST", crate::transform::TxType::DctAdst), |
| 4853 | ("IDTX", crate::transform::TxType::Idtx), |
| 4854 | ] { |
| 4855 | assert!( |
| 4856 | hits[ty as usize] > 0, |
| 4857 | "no luma transform unit took {name}: {hits:?}" |
| 4858 | ); |
| 4859 | } |
| 4860 | } else { |
| 4861 | eprintln!( |
| 4862 | "SKIP the five-type fire count at preset {}: {hits:?}", |
| 4863 | crate::speed::speed() |
| 4864 | ); |
| 4865 | } |
| 4866 | let ours = crate::stream::decode_stream(&stream).expect("our decoder"); |
| 4867 | assert_eq!(ours.len(), sources.len(), "our decoder's frames"); |
| 4868 | if have_ffmpeg() { |
| 4869 | let theirs = ffmpeg_decode_luma(&stream, width, height); |
| 4870 | assert_eq!(theirs.len(), sources.len(), "ffmpeg's frames"); |
| 4871 | for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() { |
| 4872 | let got: Vec<u8> = a.y.iter().map(|&v| v as u8).collect(); |
| 4873 | if let Some(at) = got.iter().zip(b).position(|(x, y)| x != y) { |
| 4874 | panic!( |
| 4875 | "frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}", |
| 4876 | at % width, |
| 4877 | at / width, |
| 4878 | got[at], |
| 4879 | b[at], |
| 4880 | ); |
| 4881 | } |
| 4882 | } |
| 4883 | } else { |
| 4884 | eprintln!("SKIP the ffmpeg half: no ffmpeg"); |
| 4885 | } |
| 4886 | crate::encode::force_screen(None); |
| 4887 | eprintln!("tx_type witness: hits {hits:?}, {} bytes", stream.len()); |
| 4888 | } |
| 4889 | |
| 4890 | /// lane-txset2's witness: an INTER frame's luma transform units take BOTH |
| 4891 | /// types of the two-type inter set the writer already codes a symbol for |
| 4892 | /// (`TX_SET_INTER_3`: `IDTX` and `DCT_DCT`) at least once -- the fire |
| 4893 | /// count, class `gate-blind-to-feature` -- and both decoders reconstruct |
| 4894 | /// every frame sample-exact from the `tx_type` symbols that name them. |
| 4895 | /// Before this lane every inter luma unit was coded `DCT_DCT`. |
| 4896 | #[test] |
| 4897 | fn an_inter_clip_codes_both_inter_set_tx_types_both_decoders_read_exactly() { |
| 4898 | // The lever is OFF at every preset (`speed::TX_TYPE_SEARCH_INTER`), so |
| 4899 | // this turns it on process-globally under the same exclusive lock the |
| 4900 | // presets take. |
| 4901 | let _knobs = crate::speed::knob_write(); |
| 4902 | let _gate_lock = crate::stream::tests::lock_gate_counters(); |
| 4903 | crate::encode::set_inter_tx_search(Some(true)); |
| 4904 | let (width, height) = (320usize, 192usize); |
| 4905 | // Sharp steps that MOVE: the motion-compensated residual along a |
| 4906 | // moving edge is exactly where the identity transform beats a DCT, |
| 4907 | // and the flat plateaus between them predict to nothing at all. |
| 4908 | let sources: Vec<Picture> = (0..4) |
| 4909 | .map(|t| { |
| 4910 | let mut p = test_card(width, height, t * 3); |
| 4911 | for y in 0..height { |
| 4912 | for x in 0..width { |
| 4913 | let v = match ((x + t * 5) / 16 % 2, (y + t * 3) / 16 % 2) { |
| 4914 | (0, 0) => 16u16, |
| 4915 | (1, 0) => 235, |
| 4916 | (0, 1) => ((x + t) % 64 * 3) as u16, |
| 4917 | _ => ((y + t) % 64 * 3) as u16, |
| 4918 | }; |
| 4919 | p.y[y * width + x] = v; |
| 4920 | } |
| 4921 | } |
| 4922 | p |
| 4923 | }) |
| 4924 | .collect(); |
| 4925 | let config = EncoderConfig { |
| 4926 | width, |
| 4927 | height, |
| 4928 | base_q_idx: 90, |
| 4929 | gop: 4, |
| 4930 | colour: Colour::Bt709Limited, |
| 4931 | tile_cols_log2: 0, |
| 4932 | tile_rows_log2: 0, |
| 4933 | }; |
| 4934 | let mut enc = Av1Encoder::new(config).unwrap(); |
| 4935 | let _ = crate::encode::take_inter_tx_type_hits(); |
| 4936 | let mut stream = Vec::new(); |
| 4937 | for packet in encode_all(&mut enc, &sources) { |
| 4938 | stream.extend_from_slice(&packet.data); |
| 4939 | } |
| 4940 | let hits = crate::encode::take_inter_tx_type_hits(); |
| 4941 | crate::encode::set_inter_tx_search(None); |
| 4942 | for (name, ty) in [ |
| 4943 | ("DCT_DCT", crate::transform::TxType::DctDct), |
| 4944 | ("IDTX", crate::transform::TxType::Idtx), |
| 4945 | ] { |
| 4946 | assert!( |
| 4947 | hits[ty as usize] > 0, |
| 4948 | "no inter luma transform unit was CODED {name}: {hits:?}" |
| 4949 | ); |
| 4950 | } |
| 4951 | let ours = crate::stream::decode_stream(&stream).expect("our decoder"); |
| 4952 | assert_eq!(ours.len(), sources.len(), "our decoder's frames"); |
| 4953 | if have_ffmpeg() { |
| 4954 | let theirs = ffmpeg_decode_luma(&stream, width, height); |
| 4955 | assert_eq!(theirs.len(), sources.len(), "ffmpeg's frames"); |
| 4956 | for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() { |
| 4957 | let got: Vec<u8> = a.y.iter().map(|&v| v as u8).collect(); |
| 4958 | if let Some(at) = got.iter().zip(b).position(|(x, y)| x != y) { |
| 4959 | panic!( |
| 4960 | "frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}", |
| 4961 | at % width, |
| 4962 | at / width, |
| 4963 | got[at], |
| 4964 | b[at], |
| 4965 | ); |
| 4966 | } |
| 4967 | } |
| 4968 | } else { |
| 4969 | eprintln!("SKIP the ffmpeg half: no ffmpeg"); |
| 4970 | } |
| 4971 | eprintln!("inter tx_type witness: hits {hits:?}, {} bytes", stream.len()); |
| 4972 | } |
| 4973 | |
| 4974 | /// lane-txi's witness: a `reduced_tx_set = 0` frame codes the WIDER |
| 4975 | /// `tx_type` alphabets -- the seven-type `TX_SET_INTRA_1` at intra |
| 4976 | /// 8x8/4x4 and the twelve/sixteen-type inter sets at 16x16 and below -- |
| 4977 | /// and both decoders reconstruct every frame sample-exact from them. The |
| 4978 | /// statement is that the types only those alphabets can NAME (`V_DCT`, |
| 4979 | /// `H_DCT`, and any inter type outside the two-type `DCT_IDTX`) are |
| 4980 | /// reachable at all, and that the header bit, the writer's set map and |
| 4981 | /// the search's pricer agree on which alphabet a symbol was coded into |
| 4982 | /// (class `wrong-alphabet-same-value`: a disagreement here changes no |
| 4983 | /// symbol VALUE and desyncs the arithmetic coder anyway). |
| 4984 | #[test] |
| 4985 | #[ignore = "sets process-global search levers: run it alone"] |
| 4986 | fn a_wide_tx_set_clip_codes_the_new_alphabets_both_decoders_read_exactly() { |
| 4987 | // Every lever below is process-global: the same exclusive lock the |
| 4988 | // presets take. |
| 4989 | let _knobs = crate::speed::knob_write(); |
| 4990 | let _gate_lock = crate::stream::tests::lock_gate_counters(); |
| 4991 | crate::encode::set_intra_tx_search(Some(true)); |
| 4992 | crate::encode::set_inter_tx_search(Some(true)); |
| 4993 | crate::encode::set_wide_tx_set(Some(true)); |
| 4994 | let (width, height) = (320usize, 192usize); |
| 4995 | // The same moving hard-edge card the two narrow-set witnesses use: |
| 4996 | // vertical steps are what a 1-D `V_DCT`/`H_DCT` pass wins on, the |
| 4997 | // ramps are `ADST`'s and the moving plateaus `IDTX`'s. |
| 4998 | let sources: Vec<Picture> = (0..4) |
| 4999 | .map(|t| { |
| 5000 | let mut p = test_card(width, height, t * 3); |
| 5001 | for y in 0..height { |
| 5002 | for x in 0..width { |
| 5003 | let v = match ((x + t * 5) / 16 % 2, (y + t * 3) / 16 % 2) { |
| 5004 | (0, 0) => 16u16, |
| 5005 | (1, 0) => 235, |
| 5006 | (0, 1) => ((x + t) % 64 * 3) as u16, |
| 5007 | _ => ((y + t) % 64 * 3) as u16, |
| 5008 | }; |
| 5009 | p.y[y * width + x] = v; |
| 5010 | } |
| 5011 | } |
| 5012 | p |
| 5013 | }) |
| 5014 | .collect(); |
| 5015 | let config = EncoderConfig { |
| 5016 | width, |
| 5017 | height, |
| 5018 | base_q_idx: 90, |
| 5019 | gop: 4, |
| 5020 | colour: Colour::Bt709Limited, |
| 5021 | tile_cols_log2: 0, |
| 5022 | tile_rows_log2: 0, |
| 5023 | }; |
| 5024 | let mut enc = Av1Encoder::new(config).unwrap(); |
| 5025 | let _ = crate::encode::take_tx_type_hits(); |
| 5026 | let _ = crate::encode::take_inter_tx_type_hits(); |
| 5027 | let mut stream = Vec::new(); |
| 5028 | for packet in encode_all(&mut enc, &sources) { |
| 5029 | stream.extend_from_slice(&packet.data); |
| 5030 | } |
| 5031 | let (intra, inter) = ( |
| 5032 | crate::encode::take_tx_type_hits(), |
| 5033 | crate::encode::take_inter_tx_type_hits(), |
| 5034 | ); |
| 5035 | crate::encode::set_wide_tx_set(None); |
| 5036 | crate::encode::set_inter_tx_search(None); |
| 5037 | crate::encode::set_intra_tx_search(None); |
| 5038 | eprintln!("wide tx_type witness: intra {intra:?} inter {inter:?}, {} bytes", stream.len()); |
| 5039 | // The fire count is preset 0's, for the reason the five-type witness |
| 5040 | // spells out: a faster preset prunes the modes and partitions a type |
| 5041 | // wins on before it is ever priced (class `gate-blind-to-feature`). |
| 5042 | if crate::speed::at(&crate::speed::TX_TYPE_SEARCH) && crate::speed::speed() == 0 { |
| 5043 | use crate::transform::TxType; |
| 5044 | let wide_only = |hits: &[usize; 16]| -> usize { |
| 5045 | hits[TxType::VDct as usize] + hits[TxType::HDct as usize] |
| 5046 | }; |
| 5047 | assert!( |
| 5048 | wide_only(&intra) > 0, |
| 5049 | "no intra luma unit took a 1-D DCT, the type only TX_SET_INTRA_1 names: {intra:?}" |
| 5050 | ); |
| 5051 | // The INTER units of this same frame are coded into the |
| 5052 | // twelve/sixteen-symbol alphabets too (the header bit widens |
| 5053 | // every luma set at once), but their SEARCH still offers the |
| 5054 | // two-type list -- see `encode::inter_luma_set`'s note on the |
| 5055 | // reference-slot refusal the wider inter candidates trip. So the |
| 5056 | // statement here is that those units still decode sample-exact |
| 5057 | // out of the wider alphabet, which the two decoders below make. |
| 5058 | assert!( |
| 5059 | inter.iter().sum::<usize>() > 0, |
| 5060 | "the clip coded no inter luma transform unit at all: {inter:?}" |
| 5061 | ); |
| 5062 | } else { |
| 5063 | eprintln!( |
| 5064 | "SKIP the wide-alphabet fire count at preset {}", |
| 5065 | crate::speed::speed() |
| 5066 | ); |
| 5067 | } |
| 5068 | let ours = crate::stream::decode_stream(&stream).expect("our decoder"); |
| 5069 | assert_eq!(ours.len(), sources.len(), "our decoder's frames"); |
| 5070 | if have_ffmpeg() { |
| 5071 | let theirs = ffmpeg_decode_luma(&stream, width, height); |
| 5072 | assert_eq!(theirs.len(), sources.len(), "ffmpeg's frames"); |
| 5073 | for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() { |
| 5074 | let got: Vec<u8> = a.y.iter().map(|&v| v as u8).collect(); |
| 5075 | if let Some(at) = got.iter().zip(b).position(|(x, y)| x != y) { |
| 5076 | panic!( |
| 5077 | "frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}", |
| 5078 | at % width, |
| 5079 | at / width, |
| 5080 | got[at], |
| 5081 | b[at], |
| 5082 | ); |
| 5083 | } |
| 5084 | } |
| 5085 | } else { |
| 5086 | eprintln!("SKIP the ffmpeg half: no ffmpeg"); |
| 5087 | } |
| 5088 | } |
| 5089 | /// lane-intertx's witness: on a clip the screen detector calls |
| 5090 | /// NON-screen, the inter luma search offers the wider |
| 5091 | /// `reduced_tx_set = 0` alphabets and CODES a 1-D `V_DCT`/`H_DCT` unit |
| 5092 | /// (a `coded > 0` guard on the committed-winners census, class |
| 5093 | /// `gate-blind-to-feature`), the block's chroma transforms inherit that |
| 5094 | /// type reduced to the chroma size's set against the frame's own honest |
| 5095 | /// header bit, and BOTH decoders reconstruct every frame sample-exact on |
| 5096 | /// ALL THREE planes -- chroma is the plane the inheritance desync |
| 5097 | /// corrupts, so luma-only comparisons cannot see it. |
| 5098 | #[test] |
| 5099 | #[ignore = "sets process-global search levers: run it alone"] |
| 5100 | fn a_non_screen_inter_clip_codes_a_one_d_type_both_decoders_read_every_plane_exactly() { |
| 5101 | let _knobs = crate::speed::knob_write(); |
| 5102 | let _gate_lock = crate::stream::tests::lock_gate_counters(); |
| 5103 | crate::encode::set_intra_tx_search(Some(true)); |
| 5104 | crate::encode::set_inter_tx_search(Some(true)); |
| 5105 | crate::encode::set_wide_tx_set(Some(true)); |
| 5106 | crate::encode::force_screen(Some(false)); |
| 5107 | let (width, height) = (320usize, 192usize); |
| 5108 | // The wide witness's moving card: vertical steps (where a 1-D |
| 5109 | // `V_DCT`/`H_DCT` beats the 2-D DCT on the motion-compensated |
| 5110 | // residual), ramps (`ADST`) and moving plateaus (`IDTX`), translated |
| 5111 | // a few samples per frame so the inter search sees real motion. |
| 5112 | let sources: Vec<Picture> = (0..4) |
| 5113 | .map(|t| { |
| 5114 | let mut p = test_card(width, height, t * 3); |
| 5115 | for y in 0..height { |
| 5116 | for x in 0..width { |
| 5117 | let v = match ((x + t * 5) / 16 % 2, (y + t * 3) / 16 % 2) { |
| 5118 | (0, 0) => 16u16, |
| 5119 | (1, 0) => 235, |
| 5120 | (0, 1) => ((x + t) % 64 * 3) as u16, |
| 5121 | _ => ((y + t) % 64 * 3) as u16, |
| 5122 | }; |
| 5123 | p.y[y * width + x] = v; |
| 5124 | } |
| 5125 | } |
| 5126 | p |
| 5127 | }) |
| 5128 | .collect(); |
| 5129 | let config = EncoderConfig { |
| 5130 | width, |
| 5131 | height, |
| 5132 | base_q_idx: 90, |
| 5133 | gop: 4, |
| 5134 | colour: Colour::Bt709Limited, |
| 5135 | tile_cols_log2: 0, |
| 5136 | tile_rows_log2: 0, |
| 5137 | }; |
| 5138 | let mut enc = Av1Encoder::new(config).unwrap(); |
| 5139 | let _ = crate::encode::take_inter_tx_type_hits(); |
| 5140 | let mut stream = Vec::new(); |
| 5141 | for packet in encode_all(&mut enc, &sources) { |
| 5142 | stream.extend_from_slice(&packet.data); |
| 5143 | } |
| 5144 | let hits = crate::encode::take_inter_tx_type_hits(); |
| 5145 | crate::encode::force_screen(None); |
| 5146 | crate::encode::set_wide_tx_set(None); |
| 5147 | crate::encode::set_inter_tx_search(None); |
| 5148 | crate::encode::set_intra_tx_search(None); |
| 5149 | use crate::transform::TxType; |
| 5150 | eprintln!( |
| 5151 | "inter wide-set witness: inter hits {hits:?}, {} bytes", |
| 5152 | stream.len() |
| 5153 | ); |
| 5154 | assert!( |
| 5155 | hits[TxType::Idtx as usize] > 0, |
| 5156 | "no inter luma unit was CODED IDTX: {hits:?}" |
| 5157 | ); |
| 5158 | assert!( |
| 5159 | hits[TxType::VDct as usize] + hits[TxType::HDct as usize] > 0, |
| 5160 | "no inter luma unit was CODED a 1-D type -- the wider search \ |
| 5161 | never fired on non-screen content (class gate-blind-to-feature): {hits:?}" |
| 5162 | ); |
| 5163 | let ours = crate::stream::decode_stream(&stream).expect("our decoder"); |
| 5164 | assert_eq!(ours.len(), sources.len(), "our decoder's frames"); |
| 5165 | if have_ffmpeg() { |
| 5166 | let theirs = ffmpeg_decode_planes(&stream, width, height); |
| 5167 | assert_eq!(theirs.len(), sources.len(), "ffmpeg's frames"); |
| 5168 | let (cw, ch) = (width / 2, height / 2); |
| 5169 | for (i, (a, (y, u, v))) in ours.iter().zip(&theirs).enumerate() { |
| 5170 | for (name, got16, want, w) in |
| 5171 | [("y", &a.y, y, width), ("u", &a.u, u, cw), ("v", &a.v, v, ch)] |
| 5172 | { |
| 5173 | let got: Vec<u8> = got16.iter().map(|&s| s as u8).collect(); |
| 5174 | assert_eq!(got.len(), want.len(), "frame {i} {name} plane size"); |
| 5175 | if let Some(at) = got.iter().zip(want.iter()).position(|(x, y)| x != y) { |
| 5176 | panic!( |
| 5177 | "frame {i}: {name} differs first at ({}, {}): ours {} vs ffmpeg {}", |
| 5178 | at % w, |
| 5179 | at / w, |
| 5180 | got[at], |
| 5181 | want[at], |
| 5182 | ); |
| 5183 | } |
| 5184 | } |
| 5185 | } |
| 5186 | } else { |
| 5187 | eprintln!("SKIP the ffmpeg half: no ffmpeg"); |
| 5188 | } |
| 5189 | } |
| 5190 | |
| 5191 | /// Every SHIPPED SPEED PRESET codes a stream both decoders reconstruct |
| 5192 | /// sample-exact -- ours and ffmpeg's -- and codes a DIFFERENT stream from |
| 5193 | /// its neighbour (a preset that changes no byte is a preset that buys no |
| 5194 | /// wall: class `gate-blind-to-feature`). Preset 0's bytes are the |
| 5195 | /// full-search ones, which is the cheap in-suite statement of the byte |
| 5196 | /// pins' rule. |
| 5197 | /// |
| 5198 | /// Ignored by default because the preset is PROCESS-GLOBAL |
| 5199 | /// ([`crate::speed`]): flipping it while the suite's other tests encode |
| 5200 | /// in parallel would move their bytes under them. Run it on its own: |
| 5201 | /// `cargo test -p ec-av1 --release -- --ignored every_speed_preset`. |
| 5202 | #[test] |
| 5203 | #[ignore = "sets the process-global speed preset: run it alone"] |
| 5204 | fn every_speed_preset_decodes_sample_exact_through_both_decoders() { |
| 5205 | let _knobs = crate::speed::knob_write(); |
| 5206 | let _gate_lock = crate::stream::tests::lock_gate_counters(); |
| 5207 | let (width, height) = (640usize, 384usize); |
| 5208 | let sources: Vec<Picture> = (0..4).map(|t| test_card(width, height, t * 3)).collect(); |
| 5209 | let mut sizes: Vec<(u8, usize)> = Vec::new(); |
| 5210 | for speed in [0u8, 3, 6, 10] { |
| 5211 | let config = EncoderConfig { |
| 5212 | width, |
| 5213 | height, |
| 5214 | base_q_idx: 120, |
| 5215 | gop: 4, |
| 5216 | colour: Colour::Bt709Limited, |
| 5217 | tile_cols_log2: 1, |
| 5218 | tile_rows_log2: 0, |
| 5219 | }; |
| 5220 | let mut enc = Av1Encoder::with_speed(config, speed).unwrap(); |
| 5221 | let mut stream = Vec::new(); |
| 5222 | for packet in encode_all(&mut enc, &sources) { |
| 5223 | stream.extend_from_slice(&packet.data); |
| 5224 | } |
| 5225 | let ours = crate::stream::decode_stream(&stream).expect("our decoder"); |
| 5226 | assert_eq!(ours.len(), sources.len(), "speed {speed}: our decoder's frames"); |
| 5227 | if have_ffmpeg() { |
| 5228 | let theirs = ffmpeg_decode_luma(&stream, width, height); |
| 5229 | assert_eq!(theirs.len(), sources.len(), "speed {speed}: ffmpeg's frames"); |
| 5230 | for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() { |
| 5231 | let got: Vec<u8> = a.y.iter().map(|&v| v as u8).collect(); |
| 5232 | if let Some(at) = got.iter().zip(b).position(|(x, y)| x != y) { |
| 5233 | panic!( |
| 5234 | "speed {speed} frame {i}: luma differs first at ({}, {}): \ |
| 5235 | ours {} vs ffmpeg {}", |
| 5236 | at % width, |
| 5237 | at / width, |
| 5238 | got[at], |
| 5239 | b[at], |
| 5240 | ); |
| 5241 | } |
| 5242 | } |
| 5243 | } else { |
| 5244 | eprintln!("SKIP the ffmpeg half of speed {speed}: no ffmpeg"); |
| 5245 | } |
| 5246 | eprintln!( |
| 5247 | "speed {speed}: {} bytes [{}]", |
| 5248 | stream.len(), |
| 5249 | crate::speed::levers(speed).join(", ") |
| 5250 | ); |
| 5251 | sizes.push((speed, stream.len())); |
| 5252 | } |
| 5253 | crate::speed::set_speed(0); |
| 5254 | for w in sizes.windows(2) { |
| 5255 | assert_ne!( |
| 5256 | w[0].1, w[1].1, |
| 5257 | "speed {} and {} coded the same bytes: the preset changed no decision", |
| 5258 | w[0].0, w[1].0 |
| 5259 | ); |
| 5260 | } |
| 5261 | } |
| 5262 | |
| 5263 | /// What tiles and tile threads are worth at the size the editor exports |
| 5264 | /// at: 1920x1080, eight real pictures, two passes per cell (ABAB), wall |
| 5265 | /// per cell. Ignored by default (minutes). |
| 5266 | #[test] |
| 5267 | #[ignore = "1080p wall table: minutes, run it with --ignored"] |
| 5268 | fn tile_wall_table_at_1080p() { |
| 5269 | let _knobs = crate::speed::knob_write(); |
| 5270 | let _gate_lock = crate::stream::tests::lock_gate_counters(); |
| 5271 | let (width, height) = (1920usize, 1080usize); |
| 5272 | let Some(sources) = h264_clip_frames(width, height, 8) else { |
| 5273 | eprintln!("SKIP tile_wall_table_at_1080p: no fixture"); |
| 5274 | return; |
| 5275 | }; |
| 5276 | let layouts = [(0u32, 0u32), (1, 0), (1, 1), (2, 1)]; |
| 5277 | let threadings = [1usize, 2, 4, 8]; |
| 5278 | let mut table: Vec<(String, usize, f64, usize)> = Vec::new(); |
| 5279 | for pass in 0..2 { |
| 5280 | for &(cols_log2, rows_log2) in &layouts { |
| 5281 | for &threads in &threadings { |
| 5282 | crate::par::set_tile_threads(threads); |
| 5283 | let config = EncoderConfig { |
| 5284 | width, |
| 5285 | height, |
| 5286 | base_q_idx: 120, |
| 5287 | gop: 8, |
| 5288 | colour: Colour::Bt709Limited, |
| 5289 | tile_cols_log2: cols_log2, |
| 5290 | tile_rows_log2: rows_log2, |
| 5291 | }; |
| 5292 | let mut enc = Av1Encoder::new(config).unwrap(); |
| 5293 | let start = std::time::Instant::now(); |
| 5294 | let mut bytes = 0usize; |
| 5295 | for packet in encode_all(&mut enc, &sources) { |
| 5296 | bytes += packet.data.len(); |
| 5297 | } |
| 5298 | let wall = start.elapsed().as_secs_f64(); |
| 5299 | let name = format!("{}x{}", 1 << cols_log2, 1 << rows_log2); |
| 5300 | match table.iter_mut().find(|r| r.0 == name && r.1 == threads) { |
| 5301 | Some(row) => row.2 = row.2.min(wall), |
| 5302 | None => table.push((name, threads, wall, bytes)), |
| 5303 | } |
| 5304 | let _ = pass; |
| 5305 | } |
| 5306 | } |
| 5307 | } |
| 5308 | crate::par::set_tile_threads(1); |
| 5309 | eprintln!("| tiles | threads | wall (s, best of 2) | bytes |"); |
| 5310 | for (name, threads, wall, bytes) in &table { |
| 5311 | eprintln!("| {name} | {threads} | {wall:.2} | {bytes} |"); |
| 5312 | } |
| 5313 | } |
| 5314 | |
| 5315 | /// The tiles of a frame are entropy-independent, so the bytes must not |
| 5316 | /// depend on how many workers wrote them: the same stream at one tile |
| 5317 | /// thread and at four, per layout. |
| 5318 | #[test] |
| 5319 | fn tile_bytes_do_not_depend_on_the_thread_count() { |
| 5320 | let _knobs = crate::speed::knob_write(); |
| 5321 | let _gate_lock = crate::stream::tests::lock_gate_counters(); |
| 5322 | let (width, height) = (320usize, 192usize); |
| 5323 | let sources: Vec<Picture> = (0..3).map(|t| test_card(width, height, t * 3)).collect(); |
| 5324 | let coded = |threads: usize, cols_log2: u32, rows_log2: u32| { |
| 5325 | crate::par::set_tile_threads(threads); |
| 5326 | let config = EncoderConfig { |
| 5327 | width, |
| 5328 | height, |
| 5329 | base_q_idx: 120, |
| 5330 | gop: 3, |
| 5331 | colour: Colour::Bt709Limited, |
| 5332 | tile_cols_log2: cols_log2, |
| 5333 | tile_rows_log2: rows_log2, |
| 5334 | }; |
| 5335 | let mut enc = Av1Encoder::new(config).unwrap(); |
| 5336 | let mut stream = Vec::new(); |
| 5337 | for packet in encode_all(&mut enc, &sources) { |
| 5338 | stream.extend_from_slice(&packet.data); |
| 5339 | } |
| 5340 | stream |
| 5341 | }; |
| 5342 | for (cols_log2, rows_log2) in [(1u32, 0u32), (0, 1), (1, 1), (2, 1)] { |
| 5343 | let one = coded(1, cols_log2, rows_log2); |
| 5344 | let four = coded(4, cols_log2, rows_log2); |
| 5345 | assert_eq!( |
| 5346 | one, |
| 5347 | four, |
| 5348 | "{}x{} tiles: {} bytes at one thread, {} at four", |
| 5349 | 1 << cols_log2, |
| 5350 | 1 << rows_log2, |
| 5351 | one.len(), |
| 5352 | four.len() |
| 5353 | ); |
| 5354 | } |
| 5355 | crate::par::set_tile_threads(1); |
| 5356 | } |
| 5357 | |
| 5358 | /// What the per-tile search (lane-av1tsearch) is worth in wall and in |
| 5359 | /// frames per second at the editor's own export sizes: every tile layout |
| 5360 | /// crossed with every tile-thread count, plus librav1e at the matching |
| 5361 | /// `tile_cols`/`tile_rows`/`threads` as the reference point. Two passes |
| 5362 | /// over the whole table (A,B,A,B... rather than AA,BB) with the best of |
| 5363 | /// the two kept, so a thermal drift cannot order the rows. |
| 5364 | /// |
| 5365 | /// Measurement, not a pass/fail gate: it asserts only that every cell |
| 5366 | /// produced a stream. |
| 5367 | #[test] |
| 5368 | #[ignore = "wall measurement: minutes, run it with --ignored --nocapture"] |
| 5369 | fn tile_search_wall_1080p() { |
| 5370 | let _knobs = crate::speed::knob_write(); |
| 5371 | tile_search_wall(1920, 1080, 12, &[(0, 0), (1, 0), (1, 1), (2, 1)], &[1, 2, 4, 8]); |
| 5372 | } |
| 5373 | |
| 5374 | /// The same table at the 4K frame size the editor exports (3840x1608), |
| 5375 | /// at the two layouts with enough tiles to fill this box. |
| 5376 | #[test] |
| 5377 | #[ignore = "wall measurement: minutes, run it with --ignored --nocapture"] |
| 5378 | fn tile_search_wall_4k() { |
| 5379 | let _knobs = crate::speed::knob_write(); |
| 5380 | tile_search_wall(3840, 1608, 6, &[(2, 1), (3, 2)], &[1, 8, 12]); |
| 5381 | } |
| 5382 | |
| 5383 | /// lane-av1fpar: the frame-level FILTER stage is banded across the same |
| 5384 | /// workers the tile search uses (`par::override_filter_threads`), so the |
| 5385 | /// deblock/CDEF replays, the per-64 SSE and the plane copies all run in |
| 5386 | /// pieces. Every piece is a disjoint band of the same integers, so the |
| 5387 | /// stream must not move -- at a size that crops and is several superblock |
| 5388 | /// rows tall, which is what makes the bands non-trivial. |
| 5389 | #[test] |
| 5390 | fn filter_stage_bytes_do_not_depend_on_the_thread_count() { |
| 5391 | let _knobs = crate::speed::knob_write(); |
| 5392 | let _gate_lock = crate::stream::tests::lock_gate_counters(); |
| 5393 | let (width, height) = (384usize, 288usize); |
| 5394 | let sources: Vec<Picture> = (0..4).map(|t| test_card(width, height, t * 3)).collect(); |
| 5395 | let coded = |threads: usize| { |
| 5396 | crate::par::set_tile_threads(threads); |
| 5397 | let config = EncoderConfig { |
| 5398 | width, |
| 5399 | height, |
| 5400 | base_q_idx: 120, |
| 5401 | gop: 2, |
| 5402 | colour: Colour::Bt709Limited, |
| 5403 | tile_cols_log2: 0, |
| 5404 | tile_rows_log2: 0, |
| 5405 | }; |
| 5406 | let mut enc = Av1Encoder::new(config).unwrap(); |
| 5407 | let mut stream = Vec::new(); |
| 5408 | for packet in encode_all(&mut enc, &sources) { |
| 5409 | stream.extend_from_slice(&packet.data); |
| 5410 | } |
| 5411 | stream |
| 5412 | }; |
| 5413 | // One tile, so only the filter stage can differ between these. |
| 5414 | let one = coded(1); |
| 5415 | for threads in [2usize, 4, 8] { |
| 5416 | assert_eq!(one, coded(threads), "the filter stage moved at {threads} threads"); |
| 5417 | } |
| 5418 | crate::par::set_tile_threads(1); |
| 5419 | } |
| 5420 | |
| 5421 | /// lane-av1fpar: the filter search scores its ~30 candidates by replaying |
| 5422 | /// the loop filters on one captured reconstruction instead of decoding |
| 5423 | /// the coded tile again per candidate. The replay must be that decode, |
| 5424 | /// byte for byte -- including at a size that CROPS (1080 and 1608 both |
| 5425 | /// pad to a superblock row, i.e. every export size the editor uses), |
| 5426 | /// which is the arm this lane opened. |
| 5427 | #[test] |
| 5428 | fn filter_replay_codes_the_same_stream_as_a_full_decode() { |
| 5429 | let _knobs = crate::speed::knob_read(); |
| 5430 | let _gate_lock = crate::stream::tests::lock_gate_counters(); |
| 5431 | let run = |width: usize, height: usize, off: bool| { |
| 5432 | let sources: Vec<Picture> = (0..4).map(|t| test_card(width, height, t * 3)).collect(); |
| 5433 | crate::decode::set_filter_replay_disabled(off); |
| 5434 | let config = EncoderConfig { |
| 5435 | width, |
| 5436 | height, |
| 5437 | base_q_idx: 120, |
| 5438 | gop: 2, |
| 5439 | colour: Colour::Bt709Limited, |
| 5440 | tile_cols_log2: 0, |
| 5441 | tile_rows_log2: 0, |
| 5442 | }; |
| 5443 | let mut enc = Av1Encoder::new(config).unwrap(); |
| 5444 | let mut stream = Vec::new(); |
| 5445 | for packet in encode_all(&mut enc, &sources) { |
| 5446 | stream.extend_from_slice(&packet.data); |
| 5447 | } |
| 5448 | crate::decode::set_filter_replay_disabled(false); |
| 5449 | stream |
| 5450 | }; |
| 5451 | // 320x160 crops (the coding surface is 320x192, one superblock row |
| 5452 | // taller); 320x192 is a whole number of superblocks, the shape the |
| 5453 | // replay already covered. |
| 5454 | for (width, height) in [(320usize, 160usize), (320, 192)] { |
| 5455 | let replayed = run(width, height, false); |
| 5456 | let decoded = run(width, height, true); |
| 5457 | assert_eq!( |
| 5458 | replayed, |
| 5459 | decoded, |
| 5460 | "{width}x{height}: the filter replay is not the decode it stands in for \ |
| 5461 | ({} bytes replayed, {} decoded)", |
| 5462 | replayed.len(), |
| 5463 | decoded.len(), |
| 5464 | ); |
| 5465 | } |
| 5466 | } |
| 5467 | |
| 5468 | /// lane-av1cap: the filter stage's FINAL replay -- the one that replaced |
| 5469 | /// the capture decode -- against that decode. `set_verify_final_replay` |
| 5470 | /// makes `encode::pick_and_apply_filters` run both on every frame and |
| 5471 | /// assert, per frame, that the spliced picture and the two filter stages |
| 5472 | /// the loop-restoration search reads are bit-identical. |
| 5473 | #[test] |
| 5474 | fn filter_replay_final_matches_the_capture_decode() { |
| 5475 | let _knobs = crate::speed::knob_read(); |
| 5476 | let _gate_lock = crate::stream::tests::lock_gate_counters(); |
| 5477 | let run = |sources: &[Picture], width: usize, height: usize, tiles: (u32, u32)| { |
| 5478 | let config = EncoderConfig { |
| 5479 | width, |
| 5480 | height, |
| 5481 | base_q_idx: 120, |
| 5482 | gop: 2, |
| 5483 | colour: Colour::Bt709Limited, |
| 5484 | tile_cols_log2: tiles.0, |
| 5485 | tile_rows_log2: tiles.1, |
| 5486 | }; |
| 5487 | let mut enc = Av1Encoder::new(config).unwrap(); |
| 5488 | for packet in encode_all(&mut enc, sources) { |
| 5489 | assert!(!packet.data.is_empty()); |
| 5490 | } |
| 5491 | }; |
| 5492 | crate::decode::set_verify_final_replay(true); |
| 5493 | // 320x160 crops (its coding surface is one superblock row taller); |
| 5494 | // 320x192 is a whole number of superblocks. |
| 5495 | for (width, height) in [(320usize, 160usize), (320, 192)] { |
| 5496 | let sources: Vec<Picture> = |
| 5497 | (0..4).map(|t| test_card(width, height, t * 3)).collect(); |
| 5498 | run(&sources, width, height, (0, 0)); |
| 5499 | } |
| 5500 | // Real gate content, where the CDEF preset search actually chooses |
| 5501 | // `bits > 0` and the tile is re-coded, one tile and four. |
| 5502 | if let Some(sources) = h264_clip_frames(640, 384, 3) { |
| 5503 | run(&sources, 640, 384, (0, 0)); |
| 5504 | run(&sources, 640, 384, (1, 1)); |
| 5505 | } else { |
| 5506 | eprintln!("SKIP the gate-clip arm: no fixture or no ffmpeg"); |
| 5507 | } |
| 5508 | crate::decode::set_verify_final_replay(false); |
| 5509 | } |
| 5510 | |
| 5511 | /// lane-av1fpar: where a frame's wall actually goes, stage by stage -- |
| 5512 | /// the per-tile search, the tile write, the frame-level filter search |
| 5513 | /// (with its deblock/CDEF replay and per-64 SSE inside it), the capture |
| 5514 | /// decode the loop-restoration search rides on, and that search itself. |
| 5515 | /// Measurement, not a pass/fail gate. |
| 5516 | #[test] |
| 5517 | #[ignore = "wall measurement: minutes, run it with --ignored --nocapture"] |
| 5518 | fn filter_stage_wall_1080p() { |
| 5519 | let _knobs = crate::speed::knob_write(); |
| 5520 | filter_stage_wall(1920, 1080, 8, (2, 1), &[8]); |
| 5521 | } |
| 5522 | |
| 5523 | #[test] |
| 5524 | #[ignore = "wall measurement: minutes, run it with --ignored --nocapture"] |
| 5525 | fn filter_stage_wall_4k() { |
| 5526 | let _knobs = crate::speed::knob_write(); |
| 5527 | filter_stage_wall(3840, 1608, 4, (2, 1), &[8, 12]); |
| 5528 | } |
| 5529 | |
| 5530 | /// The same breakdown at the real films' own crop size. With |
| 5531 | /// `EC_AV1_WALL_CLIP` pointing at a film window this is the film row; with |
| 5532 | /// it unset it is the colour-bar fixture at the same size, which is what |
| 5533 | /// makes the pair a comparison rather than a number. |
| 5534 | #[test] |
| 5535 | #[ignore = "wall measurement: minutes, run it with --ignored --nocapture"] |
| 5536 | fn filter_stage_wall_film() { |
| 5537 | let _knobs = crate::speed::knob_write(); |
| 5538 | filter_stage_wall(1920, 768, 4, (2, 1), &[8]); |
| 5539 | } |
| 5540 | |
| 5541 | fn filter_stage_wall( |
| 5542 | width: usize, |
| 5543 | height: usize, |
| 5544 | frames: usize, |
| 5545 | (cols_log2, rows_log2): (u32, u32), |
| 5546 | threads: &[usize], |
| 5547 | ) { |
| 5548 | let _gate_lock = crate::stream::tests::lock_gate_counters(); |
| 5549 | let Some(sources) = h264_clip_frames(width, height, frames) else { |
| 5550 | eprintln!("SKIP the filter-stage breakdown: no fixture or no ffmpeg"); |
| 5551 | return; |
| 5552 | }; |
| 5553 | crate::par::set_stage_times(true); |
| 5554 | for &t in threads { |
| 5555 | crate::par::set_tile_threads(t); |
| 5556 | let config = EncoderConfig { |
| 5557 | width, |
| 5558 | height, |
| 5559 | base_q_idx: 120, |
| 5560 | gop: frames, |
| 5561 | colour: Colour::Bt709Limited, |
| 5562 | tile_cols_log2: cols_log2, |
| 5563 | tile_rows_log2: rows_log2, |
| 5564 | }; |
| 5565 | let mut enc = Av1Encoder::new(config).unwrap(); |
| 5566 | let _ = crate::par::take_stage_ns(); |
| 5567 | let start = std::time::Instant::now(); |
| 5568 | for packet in encode_all(&mut enc, &sources) { |
| 5569 | assert!(!packet.data.is_empty()); |
| 5570 | } |
| 5571 | let wall = start.elapsed().as_secs_f64(); |
| 5572 | let ns = crate::par::take_stage_ns(); |
| 5573 | let ms = |i: usize| ns[i] as f64 / 1e6; |
| 5574 | eprintln!( |
| 5575 | "\n{width}x{height}, {frames} frames, {}x{} tiles, {t} tile threads: \ |
| 5576 | {wall:.2}s wall, {:.2} fps", |
| 5577 | 1 << cols_log2, |
| 5578 | 1 << rows_log2, |
| 5579 | frames as f64 / wall, |
| 5580 | ); |
| 5581 | eprintln!("| stage | ms | ms/frame | % of wall |"); |
| 5582 | for (i, name) in crate::par::STAGES.iter().enumerate() { |
| 5583 | eprintln!( |
| 5584 | "| {name} | {:.0} | {:.1} | {:.1}% |", |
| 5585 | ms(i), |
| 5586 | ms(i) / frames as f64, |
| 5587 | 100.0 * ms(i) / (wall * 1e3), |
| 5588 | ); |
| 5589 | } |
| 5590 | // Top-level stages only (the deblock/CDEF/SSE rows are inside |
| 5591 | // the filter-search total); the rest is per-frame setup, the |
| 5592 | // source conversion and the splice. |
| 5593 | let top: f64 = [ |
| 5594 | crate::par::S_TILE_SEARCH, |
| 5595 | crate::par::S_TILE_WRITE, |
| 5596 | crate::par::S_FILTER, |
| 5597 | crate::par::S_CAPTURE, |
| 5598 | crate::par::S_LR, |
| 5599 | ] |
| 5600 | .iter() |
| 5601 | .map(|&i| ms(i)) |
| 5602 | .sum(); |
| 5603 | eprintln!( |
| 5604 | "accounted {:.1}% of wall; outside the tile search {:.1}%", |
| 5605 | 100.0 * top / (wall * 1e3), |
| 5606 | 100.0 * (1.0 - ms(crate::par::S_TILE_SEARCH) / (wall * 1e3)), |
| 5607 | ); |
| 5608 | } |
| 5609 | crate::par::set_stage_times(false); |
| 5610 | crate::par::set_tile_threads(1); |
| 5611 | } |
| 5612 | |
| 5613 | fn tile_search_wall( |
| 5614 | width: usize, |
| 5615 | height: usize, |
| 5616 | frames: usize, |
| 5617 | layouts: &[(u32, u32)], |
| 5618 | threads: &[usize], |
| 5619 | ) { |
| 5620 | let _gate_lock = crate::stream::tests::lock_gate_counters(); |
| 5621 | let Some(sources) = h264_clip_frames(width, height, frames) else { |
| 5622 | eprintln!("SKIP the tile-search wall table: no fixture or no ffmpeg"); |
| 5623 | return; |
| 5624 | }; |
| 5625 | let run = |cols_log2: u32, rows_log2: u32, t: usize| -> (std::time::Duration, usize) { |
| 5626 | crate::par::set_tile_threads(t); |
| 5627 | let config = EncoderConfig { |
| 5628 | width, |
| 5629 | height, |
| 5630 | base_q_idx: 120, |
| 5631 | gop: frames, |
| 5632 | colour: Colour::Bt709Limited, |
| 5633 | tile_cols_log2: cols_log2, |
| 5634 | tile_rows_log2: rows_log2, |
| 5635 | }; |
| 5636 | let mut enc = Av1Encoder::new(config).unwrap(); |
| 5637 | let start = std::time::Instant::now(); |
| 5638 | let mut bytes = 0usize; |
| 5639 | for packet in encode_all(&mut enc, &sources) { |
| 5640 | bytes += packet.data.len(); |
| 5641 | } |
| 5642 | (start.elapsed(), bytes) |
| 5643 | }; |
| 5644 | let cells: Vec<((u32, u32), usize)> = layouts |
| 5645 | .iter() |
| 5646 | .flat_map(|&l| threads.iter().map(move |&t| (l, t))) |
| 5647 | .collect(); |
| 5648 | let mut best: Vec<Option<(std::time::Duration, usize)>> = vec![None; cells.len()]; |
| 5649 | for _pass in 0..2 { |
| 5650 | for (i, &((c, r), t)) in cells.iter().enumerate() { |
| 5651 | let got = run(c, r, t); |
| 5652 | assert!(got.1 > 0, "{}x{} tiles at {t} threads: empty stream", 1 << c, 1 << r); |
| 5653 | if best[i].is_none_or(|(w, _)| got.0 < w) { |
| 5654 | best[i] = Some(got); |
| 5655 | } |
| 5656 | } |
| 5657 | } |
| 5658 | crate::par::set_tile_threads(1); |
| 5659 | eprintln!("\n{width}x{height}, {frames} frames, base_q_idx 120 -- best of two passes"); |
| 5660 | eprintln!("| layout | tiles | threads | wall | fps | speedup vs 1 tile 1 thread | bytes |"); |
| 5661 | let base = best[0].expect("the first cell ran").0.as_secs_f64(); |
| 5662 | for (i, &((c, r), t)) in cells.iter().enumerate() { |
| 5663 | let (wall, bytes) = best[i].expect("every cell ran"); |
| 5664 | let secs = wall.as_secs_f64(); |
| 5665 | eprintln!( |
| 5666 | "| {}x{} | {} | {t} | {secs:.2}s | {:.2} | {:.2}x | {bytes} |", |
| 5667 | 1 << c, |
| 5668 | 1 << r, |
| 5669 | 1 << (c + r), |
| 5670 | frames as f64 / secs, |
| 5671 | base / secs, |
| 5672 | ); |
| 5673 | } |
| 5674 | // Parallel efficiency per layout: what the extra threads actually |
| 5675 | // took off that layout's own single-threaded wall, and so what share |
| 5676 | // of the added cores sat idle. |
| 5677 | for &(c, r) in layouts { |
| 5678 | let one = cells |
| 5679 | .iter() |
| 5680 | .position(|&(l, t)| l == (c, r) && t == threads[0]) |
| 5681 | .map(|i| best[i].expect("cell").0.as_secs_f64()); |
| 5682 | let Some(one) = one else { continue }; |
| 5683 | for &t in &threads[1..] { |
| 5684 | let i = cells.iter().position(|&(l, tt)| l == (c, r) && tt == t).expect("cell"); |
| 5685 | let secs = best[i].expect("cell").0.as_secs_f64(); |
| 5686 | let workers = (t.min(1 << (c + r))) as f64 / threads[0] as f64; |
| 5687 | let speedup = one / secs; |
| 5688 | eprintln!( |
| 5689 | "{}x{} tiles, {} -> {t} threads: {speedup:.2}x of a possible {workers:.2}x, \ |
| 5690 | idle share {:.0}%", |
| 5691 | 1 << c, |
| 5692 | 1 << r, |
| 5693 | threads[0], |
| 5694 | 100.0 * (1.0 - speedup / workers).max(0.0), |
| 5695 | ); |
| 5696 | } |
| 5697 | } |
| 5698 | rav1e_wall_reference(width, height, frames, layouts, threads); |
| 5699 | } |
| 5700 | |
| 5701 | /// librav1e at the same sizes, layouts and thread counts, through ffmpeg |
| 5702 | /// -- the reference the wall table is read against. |
| 5703 | fn rav1e_wall_reference( |
| 5704 | width: usize, |
| 5705 | height: usize, |
| 5706 | frames: usize, |
| 5707 | layouts: &[(u32, u32)], |
| 5708 | threads: &[usize], |
| 5709 | ) { |
| 5710 | let clip = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) |
| 5711 | .join("../../fixtures/video/h264-1080p-23.976-8bit.mp4"); |
| 5712 | let listed = Command::new("ffmpeg").args(["-hide_banner", "-encoders"]).output(); |
| 5713 | let has_rav1e = listed |
| 5714 | .map(|o| String::from_utf8_lossy(&o.stdout).contains("librav1e")) |
| 5715 | .unwrap_or(false); |
| 5716 | if !has_rav1e || !clip.exists() { |
| 5717 | eprintln!("SKIP the rav1e reference: no librav1e or no fixture"); |
| 5718 | return; |
| 5719 | } |
| 5720 | eprintln!("| rav1e layout | threads | wall | fps | bytes |"); |
| 5721 | for &(c, r) in layouts { |
| 5722 | for &t in threads { |
| 5723 | let out = std::env::temp_dir().join(format!("ec-av1-rav1e-{}.ivf", std::process::id())); |
| 5724 | let params = format!( |
| 5725 | "speed=6:quantizer=100:tile_cols={}:tile_rows={}:threads={t}", |
| 5726 | 1 << c, |
| 5727 | 1 << r |
| 5728 | ); |
| 5729 | let start = std::time::Instant::now(); |
| 5730 | let status = Command::new("ffmpeg") |
| 5731 | .args(["-v", "error", "-y", "-i", clip.to_str().unwrap()]) |
| 5732 | .args(["-frames:v", &frames.to_string()]) |
| 5733 | .args(["-vf", &format!("scale={width}:{height}")]) |
| 5734 | .args(["-c:v", "librav1e", "-rav1e-params", ¶ms]) |
| 5735 | .arg(out.to_str().unwrap()) |
| 5736 | .output() |
| 5737 | .expect("ffmpeg failed to run"); |
| 5738 | let secs = start.elapsed().as_secs_f64(); |
| 5739 | if !status.status.success() { |
| 5740 | eprintln!("| {}x{} | {t} | FAILED: {} |", 1 << c, 1 << r, String::from_utf8_lossy(&status.stderr).lines().last().unwrap_or("")); |
| 5741 | continue; |
| 5742 | } |
| 5743 | let bytes = std::fs::metadata(&out).map(|m| m.len()).unwrap_or(0); |
| 5744 | let _ = std::fs::remove_file(&out); |
| 5745 | eprintln!( |
| 5746 | "| {}x{} | {t} | {secs:.2}s | {:.2} | {bytes} |", |
| 5747 | 1 << c, |
| 5748 | 1 << r, |
| 5749 | frames as f64 / secs |
| 5750 | ); |
| 5751 | } |
| 5752 | } |
| 5753 | } |
| 5754 | |
| 5755 | /// The same round trip at a real 1920x1080 crop of the gate's own clip |
| 5756 | /// -- the size the editor's export actually runs at, where a tile grid |
| 5757 | /// is worth having. Ignored by default only for its wall (a 1080p |
| 5758 | /// encode of three pictures), not for any weakness in the check. |
| 5759 | #[test] |
| 5760 | #[ignore = "1080p encode: minutes, run it with --ignored"] |
| 5761 | fn a_1080p_multi_tile_stream_decodes_sample_exact_through_both_decoders() { |
| 5762 | let _knobs = crate::speed::knob_read(); |
| 5763 | let (width, height) = (1920usize, 1080usize); |
| 5764 | let Some(sources) = h264_clip_frames(width, height, 3) else { |
| 5765 | eprintln!("SKIP the 1080p tile round trip: no fixture"); |
| 5766 | return; |
| 5767 | }; |
| 5768 | for (cols_log2, rows_log2) in [(1u32, 0u32), (1, 1), (2, 1)] { |
| 5769 | let config = EncoderConfig { |
| 5770 | width, |
| 5771 | height, |
| 5772 | base_q_idx: 120, |
| 5773 | gop: 3, |
| 5774 | colour: Colour::Bt709Limited, |
| 5775 | tile_cols_log2: cols_log2, |
| 5776 | tile_rows_log2: rows_log2, |
| 5777 | }; |
| 5778 | let layout = format!("{}x{} tiles", 1 << cols_log2, 1 << rows_log2); |
| 5779 | let mut enc = Av1Encoder::new(config).unwrap(); |
| 5780 | let mut stream = Vec::new(); |
| 5781 | for packet in encode_all(&mut enc, &sources) { |
| 5782 | stream.extend_from_slice(&packet.data); |
| 5783 | } |
| 5784 | let ours = crate::stream::decode_stream(&stream).expect("our decoder"); |
| 5785 | assert_eq!(ours.len(), sources.len(), "{layout}: our decoder's frames"); |
| 5786 | if !have_ffmpeg() { |
| 5787 | eprintln!("SKIP the ffmpeg half of 1080p {layout}: no ffmpeg"); |
| 5788 | continue; |
| 5789 | } |
| 5790 | let theirs = ffmpeg_decode_luma(&stream, width, height); |
| 5791 | assert_eq!(theirs.len(), sources.len(), "{layout}: ffmpeg's frames"); |
| 5792 | for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() { |
| 5793 | let got: Vec<u8> = a.y.iter().map(|&v| v as u8).collect(); |
| 5794 | if let Some(at) = got.iter().zip(b).position(|(x, y)| x != y) { |
| 5795 | panic!( |
| 5796 | "1080p {layout} frame {i}: luma differs first at ({}, {})", |
| 5797 | at % width, |
| 5798 | at / width |
| 5799 | ); |
| 5800 | } |
| 5801 | } |
| 5802 | eprintln!("1080p {layout}: {} bytes, sample-exact", stream.len()); |
| 5803 | } |
| 5804 | } |
| 5805 | |
| 5806 | /// [`RateTarget::Quality`] is monotone: a higher quality dial never |
| 5807 | /// produces a smaller stream or a worse mean PSNR than a lower one, on |
| 5808 | /// the same real clip. |
| 5809 | #[test] |
| 5810 | fn quality_target_is_monotone_in_bytes_and_psnr() { |
| 5811 | let _knobs = crate::speed::knob_read(); |
| 5812 | if !have_ffmpeg() { |
| 5813 | eprintln!("SKIP quality_target_is_monotone_in_bytes_and_psnr: no ffmpeg"); |
| 5814 | return; |
| 5815 | } |
| 5816 | let (width, height) = (640, 384); |
| 5817 | let Some(pictures) = h264_clip_frames(width, height, 8) else { |
| 5818 | eprintln!("SKIP quality_target_is_monotone_in_bytes_and_psnr: no fixture"); |
| 5819 | return; |
| 5820 | }; |
| 5821 | let mut prev_bytes = 0usize; |
| 5822 | let mut prev_psnr = 0.0f64; |
| 5823 | for quality in [20u8, 50, 80] { |
| 5824 | let config = EncoderConfig { |
| 5825 | width, |
| 5826 | height, |
| 5827 | base_q_idx: 100, |
| 5828 | gop: 8, |
| 5829 | colour: Colour::Bt709Limited, |
| 5830 | tile_cols_log2: 0, |
| 5831 | tile_rows_log2: 0, |
| 5832 | }; |
| 5833 | let mut enc = |
| 5834 | Av1Encoder::with_rate_target(config, RateTarget::Quality(quality)).unwrap(); |
| 5835 | let mut stream = Vec::new(); |
| 5836 | let mut total_bytes = 0usize; |
| 5837 | for packet in encode_all(&mut enc, &pictures) { |
| 5838 | total_bytes += packet.data.len(); |
| 5839 | stream.extend_from_slice(&packet.data); |
| 5840 | } |
| 5841 | let decoded = ffmpeg_decode_luma(&stream, width, height); |
| 5842 | assert_eq!( |
| 5843 | decoded.len(), |
| 5844 | pictures.len(), |
| 5845 | "quality {quality}: dav1d frame count" |
| 5846 | ); |
| 5847 | let mean_psnr: f64 = decoded |
| 5848 | .iter() |
| 5849 | .zip(&pictures) |
| 5850 | .map(|(d, p)| { |
| 5851 | let d16: Vec<u16> = d.iter().map(|&v| u16::from(v)).collect(); |
| 5852 | psnr(&d16, &p.y) |
| 5853 | }) |
| 5854 | .sum::<f64>() |
| 5855 | / decoded.len() as f64; |
| 5856 | assert!( |
| 5857 | total_bytes >= prev_bytes, |
| 5858 | "quality {quality}: {total_bytes} bytes not >= previous {prev_bytes}" |
| 5859 | ); |
| 5860 | assert!( |
| 5861 | mean_psnr >= prev_psnr - 0.01, // rounding slack, same-ish q_idx neighbours |
| 5862 | "quality {quality}: {mean_psnr:.2} dB not >= previous {prev_psnr:.2} dB" |
| 5863 | ); |
| 5864 | prev_bytes = total_bytes; |
| 5865 | prev_psnr = mean_psnr; |
| 5866 | } |
| 5867 | } |
| 5868 | } |