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