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