edith_codecs
Clone
https://git.tahinli.com/Tahinli/edith_codecs.git
0 watching·0 forks·Rust·370.3 MiB·b978eaa·Tahinli·2 months ago·2527 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, mini_gop: Option<usize>) -> 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 | mini_gop, |
| 147 | )) |
| 148 | } |
| 149 | } |
| 150 | |
| 151 | /// `quality`'s mapping to `base_q_idx`, linear across the calibration sweep's |
| 152 | /// span (`q_idx` 40 at `quality` 100 down to `q_idx` 240 at `quality` 0); |
| 153 | /// `quality` above 100 clamps to the best point measured, matching a CRF |
| 154 | /// dial's own saturating ends rather than extrapolating past calibrated |
| 155 | /// data. |
| 156 | fn quality_to_q_idx(quality: u8) -> u8 { |
| 157 | let quality = f64::from(quality.min(100)); |
| 158 | (240.0 - quality * 2.0).round() as u8 |
| 159 | } |
| 160 | |
| 161 | /// How much of a mini-GOP's byte budget the hidden `ALTREF` frame is worth |
| 162 | /// relative to one leaf: every leaf of the group predicts off it, so it is |
| 163 | /// bought at roughly twice a leaf's size (libaom's `gf_group` spends its |
| 164 | /// `ARF` the same way, through a lower quantizer rather than a byte target). |
| 165 | const ARF_WEIGHT: f64 = 2.0; |
| 166 | |
| 167 | /// How much a key frame is worth relative to one leaf, same units. |
| 168 | const KEY_WEIGHT: f64 = 3.0; |
| 169 | |
| 170 | /// The closed-loop controller behind [`RateTarget::BytesPerFrame`] and |
| 171 | /// [`RateTarget::Bitrate`]: a proportional step on `base_q_idx`, sized from |
| 172 | /// the calibration sweep's own log-linear slope (bytes roughly halve every |
| 173 | /// ~45 `q_idx` steps there, i.e. `d(ln bytes)/d(q_idx) ≈ -0.0154`), clamped |
| 174 | /// per frame. Pure proportional — no accumulated error term — is the windup |
| 175 | /// bound itself ([[vorbis-rate-loop-windup]]'s class): the only state carried |
| 176 | /// between frames is `q`, already clamped to `0..=255`, so a quiet lead-in |
| 177 | /// cannot build a debt a later transient has to repay; each frame's step is |
| 178 | /// bounded by `STEP_CLAMP` regardless of history. |
| 179 | /// |
| 180 | /// In pyramid mode the state is kept PER LEVEL: each frame's size is |
| 181 | /// predicted from the previous frame of its own level, against that level's |
| 182 | /// own share of the budget, which is the whole "two-pass-free model" this |
| 183 | /// encoder carries. |
| 184 | #[derive(Debug, Clone, Copy)] |
| 185 | struct RateLoop { |
| 186 | /// Byte target per level, indexed by [`RateLoop::slot`]. |
| 187 | target: [f64; 3], |
| 188 | /// Quantizer per level, same index. |
| 189 | q: [f64; 3], |
| 190 | /// Whether the three slots are actually distinct (pyramid mode) or all |
| 191 | /// one shared controller (the flat path, unchanged from before levels |
| 192 | /// existed). |
| 193 | per_level: bool, |
| 194 | /// Whether each slot has already steered off a real coded frame. The |
| 195 | /// FIRST update of a slot is the seeding one and takes the model's whole |
| 196 | /// step ([`RateLoop::update`]); every later one is clamped. |
| 197 | seeded: [bool; 3], |
| 198 | } |
| 199 | |
| 200 | impl RateLoop { |
| 201 | /// The steepest a single frame is allowed to move `base_q_idx`, in |
| 202 | /// either direction — chosen so one wildly over/under-sized frame |
| 203 | /// (a scene cut, a black lead-in) nudges the next frame's quantizer |
| 204 | /// rather than slamming it to an extreme. |
| 205 | const STEP_CLAMP: f64 = 12.0; |
| 206 | /// The calibration sweep's own slope (see the struct doc), inverted to |
| 207 | /// convert a bytes ratio into a `q_idx` step. |
| 208 | const GAIN: f64 = 1.0 / 0.0154; |
| 209 | |
| 210 | fn new(target_bytes: f64, start_q: f64, mini_gop: Option<usize>) -> Self { |
| 211 | let Some(m) = mini_gop.map(|m| m as f64) else { |
| 212 | return Self { |
| 213 | target: [target_bytes; 3], |
| 214 | q: [start_q; 3], |
| 215 | per_level: false, |
| 216 | seeded: [false; 3], |
| 217 | }; |
| 218 | }; |
| 219 | // A group of `m` pictures gets `m * target_bytes`, split one |
| 220 | // `ARF_WEIGHT` share to the hidden frame and one each to the `m - 1` |
| 221 | // leaves, so the group's own average is the target exactly. |
| 222 | let share = target_bytes * m / (m - 1.0 + ARF_WEIGHT); |
| 223 | Self { |
| 224 | target: [target_bytes * KEY_WEIGHT, share * ARF_WEIGHT, share], |
| 225 | q: [start_q; 3], |
| 226 | per_level: true, |
| 227 | seeded: [false; 3], |
| 228 | } |
| 229 | } |
| 230 | |
| 231 | /// Which controller a level uses: one shared slot on the flat path, three |
| 232 | /// separate ones under a pyramid. |
| 233 | fn slot(&self, level: Level) -> usize { |
| 234 | if !self.per_level { |
| 235 | return 0; |
| 236 | } |
| 237 | match level { |
| 238 | Level::Key => 0, |
| 239 | Level::Arf => 1, |
| 240 | // A `show_existing_frame` packet codes no pixels and never |
| 241 | // reaches `update`; it shares the leaf slot so `q_idx` is total. |
| 242 | Level::Leaf | Level::ShowExisting => 2, |
| 243 | } |
| 244 | } |
| 245 | |
| 246 | fn q_idx(&self, level: Level) -> u8 { |
| 247 | self.q[self.slot(level)].round().clamp(0.0, 255.0) as u8 |
| 248 | } |
| 249 | |
| 250 | /// Steers this level's `q` toward its own target from the frame's actual |
| 251 | /// coded size. |
| 252 | fn update(&mut self, level: Level, actual_bytes: usize) { |
| 253 | let slot = self.slot(level); |
| 254 | if self.target[slot] <= 0.0 || actual_bytes == 0 { |
| 255 | return; |
| 256 | } |
| 257 | let ratio = actual_bytes as f64 / self.target[slot]; |
| 258 | // `STEP_CLAMP` protects an operating point this slot has not found |
| 259 | // yet: its `q` is still the caller's `base_q_idx` guess, and the |
| 260 | // clamp makes the loop WALK to the right quantizer at twelve steps a |
| 261 | // frame. Measured on the 48-frame bitrate gate, the pyramid's ARF |
| 262 | // slot spent five of its twelve frames pinned at `-STEP_CLAMP` and |
| 263 | // the stream landed -10.2% under target -- convergence lag, not a |
| 264 | // steady-state offset (the fixed point of this loop is `actual == |
| 265 | // target` exactly). So a slot's FIRST frame takes the model's whole |
| 266 | // step and seeds `q` where the log-linear slope says it belongs; from |
| 267 | // the second frame on the clamp is back, and nothing is accumulated |
| 268 | // between frames, so [[vorbis-rate-loop-windup]]'s bound still holds. |
| 269 | let raw = ratio.ln() * Self::GAIN; |
| 270 | let step = if std::mem::replace(&mut self.seeded[slot], true) { |
| 271 | raw.clamp(-Self::STEP_CLAMP, Self::STEP_CLAMP) |
| 272 | } else { |
| 273 | raw |
| 274 | }; |
| 275 | self.q[slot] = (self.q[slot] + step).clamp(0.0, 255.0); |
| 276 | } |
| 277 | } |
| 278 | |
| 279 | /// What [`Av1Encoder::new`] takes: geometry, rate, key-frame cadence and |
| 280 | /// colour. `base_q_idx` is picked directly (0..=255, `crate::encode`'s own |
| 281 | /// unit) rather than a bitrate — a bitrate control loop is not part of this |
| 282 | /// lane's charter, and a caller that wants one can still derive a |
| 283 | /// `base_q_idx` from its own target and set that field. A caller who wants |
| 284 | /// [`RateTarget`]'s quality/size dials instead of picking `base_q_idx` |
| 285 | /// itself uses [`Av1Encoder::with_rate_target`], which still starts from an |
| 286 | /// `EncoderConfig` (its `base_q_idx` is the loop's seed/fallback for |
| 287 | /// [`RateTarget::BytesPerFrame`], and is overwritten outright for the other |
| 288 | /// two variants). |
| 289 | #[derive(Debug, Clone, Copy)] |
| 290 | pub struct EncoderConfig { |
| 291 | /// The picture's width in luma samples; must be even and nonzero. |
| 292 | pub width: usize, |
| 293 | /// The picture's height in luma samples; must be even and nonzero. |
| 294 | pub height: usize, |
| 295 | /// The quantizer index every frame is coded at (0..=255). |
| 296 | pub base_q_idx: u8, |
| 297 | /// Pictures between key frames, inclusive of the key frame itself: `1` |
| 298 | /// codes every picture as a key frame, `gop` codes picture `gop` (and |
| 299 | /// `2*gop`, ...) as a key frame and every other picture inter. |
| 300 | pub gop: usize, |
| 301 | /// The colour the sequence header signals. |
| 302 | pub colour: Colour, |
| 303 | /// `TileColsLog2` (spec 5.9.15): the frame is split into `1 << |
| 304 | /// tile_cols_log2` uniformly spaced tile columns, each coded and |
| 305 | /// decodable on its own. `0` -- one tile column -- is the default and |
| 306 | /// is byte for byte the stream this encoder wrote before tiles existed. |
| 307 | pub tile_cols_log2: u32, |
| 308 | /// `TileRowsLog2`, the same down the rows. |
| 309 | pub tile_rows_log2: u32, |
| 310 | } |
| 311 | |
| 312 | impl EncoderConfig { |
| 313 | /// A config at `width`x`height` with one tile, `gop` pictures between |
| 314 | /// key frames and no colour signalling -- what every caller that does |
| 315 | /// not care about tiles writes, so that adding a field here does not |
| 316 | /// rewrite them. |
| 317 | #[must_use] |
| 318 | pub fn new(width: usize, height: usize, base_q_idx: u8, gop: usize, colour: Colour) -> Self { |
| 319 | Self { |
| 320 | width, |
| 321 | height, |
| 322 | base_q_idx, |
| 323 | gop, |
| 324 | colour, |
| 325 | tile_cols_log2: 0, |
| 326 | tile_rows_log2: 0, |
| 327 | } |
| 328 | } |
| 329 | } |
| 330 | |
| 331 | /// One coded picture: its OBUs, in the order a demuxer that just wants bytes |
| 332 | /// on the wire can concatenate them, and the two things a muxer needs to |
| 333 | /// know without parsing them back out. |
| 334 | #[derive(Debug, Clone)] |
| 335 | pub struct Packet { |
| 336 | /// A temporal delimiter, a sequence header and the frame OBU for a key |
| 337 | /// frame; a temporal delimiter and the frame OBU alone for an inter |
| 338 | /// frame (the sequence header is identical across a stream's key |
| 339 | /// frames, since only [`EncoderConfig`]'s own fields feed it, so it is |
| 340 | /// simplest to let every key frame carry its own copy rather than have |
| 341 | /// the facade special-case the first one). |
| 342 | pub data: Vec<u8>, |
| 343 | /// Whether this picture was coded as a key frame. |
| 344 | pub key: bool, |
| 345 | /// This picture's position in DISPLAY (presentation) order, starting at |
| 346 | /// 0 — a muxer's `pts` in picture units. Without a [`Pyramid`] this is |
| 347 | /// also the coding order and equals `dts`. |
| 348 | pub order: u64, |
| 349 | /// This packet's position in CODING (decode) order, starting at 0 — a |
| 350 | /// muxer's `dts` in packet units. With a [`Pyramid`] the hidden frame of |
| 351 | /// each mini-GOP is coded before the leaves it precedes in display order, |
| 352 | /// so `dts` and `order` diverge, and the `show_existing_frame` packet |
| 353 | /// that re-outputs the hidden frame carries the hidden frame's own |
| 354 | /// `order` with its own later `dts`. |
| 355 | pub dts: u64, |
| 356 | /// Which pyramid level this packet is. |
| 357 | pub level: Level, |
| 358 | } |
| 359 | |
| 360 | /// One mini-GOP of a two-level coding pyramid, and the quantizer offsets its |
| 361 | /// two levels are coded at. libaom's `gf_group` shape, cut down to the two |
| 362 | /// levels this encoder's reference set can carry: the last picture of each |
| 363 | /// mini-GOP is coded FIRST, hidden (`show_frame == 0`), as the group's |
| 364 | /// `ALTREF_FRAME`, then the pictures before it are coded as shown leaves that |
| 365 | /// may predict backward off it, and finally a `show_existing_frame` header |
| 366 | /// re-outputs the hidden frame in its own display position. |
| 367 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 368 | pub struct Pyramid { |
| 369 | /// Pictures per mini-GOP: the hidden frame is `mini_gop` pictures ahead |
| 370 | /// of the group's anchor, and `mini_gop - 1` leaves sit between them. |
| 371 | /// `1` would leave no leaf at all and is refused. |
| 372 | pub mini_gop: usize, |
| 373 | /// Added to `base_q_idx` for the hidden `ALTREF_FRAME` — negative, since |
| 374 | /// every leaf of the group predicts off it. |
| 375 | pub arf_q_offset: i16, |
| 376 | /// Added to `base_q_idx` for each shown leaf — positive, since nothing |
| 377 | /// predicts off a leaf but the next leaf. |
| 378 | pub leaf_q_offset: i16, |
| 379 | } |
| 380 | |
| 381 | impl Pyramid { |
| 382 | /// The pyramid a run asks for through the environment: |
| 383 | /// `EC_AV1_PYRAMID=<mini_gop>[:<arf_q_offset>:<leaf_q_offset>]`, with |
| 384 | /// `0` (or anything that is not a mini-GOP of at least 2, e.g. `flat`) |
| 385 | /// meaning the flat one-picture-one-frame path. UNSET is |
| 386 | /// [`Pyramid::default`]: the pyramid is what |
| 387 | /// [`crate::encode::encode_sequence`], the BD gate and `ec-bench` code |
| 388 | /// under unless a run turns it off for an A/B. |
| 389 | #[must_use] |
| 390 | pub fn from_env() -> Option<Self> { |
| 391 | let d = Self::default(); |
| 392 | let Some(spec) = std::env::var("EC_AV1_PYRAMID").ok() else { |
| 393 | return Some(d); |
| 394 | }; |
| 395 | let mut f = spec.split(':'); |
| 396 | let mini_gop: usize = f.next().and_then(|v| v.parse().ok()).unwrap_or(0); |
| 397 | if mini_gop < 2 { |
| 398 | return None; |
| 399 | } |
| 400 | Some(Self { |
| 401 | mini_gop, |
| 402 | arf_q_offset: f.next().and_then(|v| v.parse().ok()).unwrap_or(d.arf_q_offset), |
| 403 | leaf_q_offset: f.next().and_then(|v| v.parse().ok()).unwrap_or(d.leaf_q_offset), |
| 404 | }) |
| 405 | } |
| 406 | } |
| 407 | |
| 408 | impl Default for Pyramid { |
| 409 | /// The best point of the offset sweep run through the BD gate's own |
| 410 | /// `EC_AV1_PYRAMID=<mini_gop>[:<arf_q_offset>:<leaf_q_offset>]` knob |
| 411 | /// (`encode::tests::bd_rate_vs_libaom_and_rav1e`, 12 frames of each of |
| 412 | /// the three gate clips, BD-rate vs libaom / vs rav1e, wall = the four |
| 413 | /// encodes of the ladder together). |
| 414 | /// |
| 415 | /// First sweep, before the motion-search lane merged (its extra-reference |
| 416 | /// `NEWMV` is exactly what a pyramid leaf needs to reach its hidden |
| 417 | /// frame), so read it for the OFFSETS, not for the verdict: |
| 418 | /// |
| 419 | /// | mini_gop:arf:leaf | 1080p | 2160p | screen | |
| 420 | /// |---|---|---|---| |
| 421 | /// | flat (no pyramid) | +122.7 / +73.4 | +147.3 / +98.5 | +79.4 / +17.2 | |
| 422 | /// | 4:0:0 | +152.2 / +97.9 | +214.7 / +158.1 | +91.4 / +26.2 | |
| 423 | /// | 4:-16:8 | +139.9 / +87.1 | +201.5 / +143.7 | +78.5 / +19.5 | |
| 424 | /// | 4:-24:12 | +141.3 / +85.0 | +190.0 / +132.9 | +84.5 / +22.8 | |
| 425 | /// | 2:0:0 | +149.3 / +93.1 | +203.0 / +149.4 | +88.3 / +23.6 | |
| 426 | /// | 2:-8:4 | +143.1 / +89.1 | +196.2 / +141.6 | +82.5 / +20.4 | |
| 427 | /// | 2:-16:8 | +137.6 / +84.5 | +187.2 / +130.6 | +84.9 / +23.1 | |
| 428 | /// |
| 429 | /// `0:0` is the worst row at both mini-GOP sizes and `-16/+8` buys 12-16 |
| 430 | /// BD points over it, in the direction libaom's `gf_group` spends them |
| 431 | /// (lowest quantizer on the frame everything else predicts from). Those |
| 432 | /// are these defaults. |
| 433 | /// |
| 434 | /// Re-measured after that lane merged (wall ours, 1080p/2160p/screen): |
| 435 | /// |
| 436 | /// | arm | 1080p | 2160p | screen | wall | |
| 437 | /// |---|---|---|---|---| |
| 438 | /// | flat (no pyramid) | +121.1 / +71.8 | +146.1 / +97.5 | +79.3 / +17.2 | 6.3 / 5.8 / 6.2 s | |
| 439 | /// | 4:-16:8 | +131.9 / +81.1 | +178.7 / +123.6 | +78.4 / +19.5 | 6.2 / 5.6 / 5.5 s | |
| 440 | /// | 2:-16:8 | +125.4 / +76.2 | +173.0 / +119.5 | +84.9 / +23.1 | 6.2 / 5.6 / 6.2 s | |
| 441 | /// |
| 442 | /// So the pyramid still does NOT pay, and ships OFF: it wins 0.9 points |
| 443 | /// on screen capture at `4:-16:8` and loses 11 on 1080p and 33 on 2160p. |
| 444 | /// What keeps it from paying, in the order the numbers point at it: |
| 445 | /// |
| 446 | /// * The hidden frame predicts `mini_gop` pictures ahead of its own |
| 447 | /// reference with the SAME forward search a neighbouring frame gets, |
| 448 | /// and it is the largest frame in the group (73.8 kB of the 1080p |
| 449 | /// ladder's 184 kB at `4:-16:8`). On the 2160p clip, whose motion the |
| 450 | /// search only just reaches at distance 1, distance 4 is where it |
| 451 | /// falls off — that clip loses twice what 1080p does, and shrinking |
| 452 | /// the mini-GOP to 2 recovers most of the gap (+178.7 -> +173.0, |
| 453 | /// +131.9 -> +125.4). A distance-scaled search range is the fix, and |
| 454 | /// it lives in the motion-search lane, not here. |
| 455 | /// * The leaves reach the hidden frame through the extra-reference |
| 456 | /// modes only: `ALTREF_FRAME` wins about 13% of blocks |
| 457 | /// (`encode::take_ref_frame_hits`, printed by the round-trip test), |
| 458 | /// up from 4% before the motion lane merged. A compound |
| 459 | /// (`LAST` + `ALTREF`) prediction mode is the other half of what a |
| 460 | /// real B frame buys, and this crate codes no compound blocks at all. |
| 461 | /// |
| 462 | /// Neither is a defect in the pyramid itself: the reordering is exact |
| 463 | /// (`encoder::tests::a_pyramid_stream_decodes_in_display_order_through_both_decoders` |
| 464 | /// checks every shown frame in display order against ffmpeg AND our own |
| 465 | /// decoder, with the hidden frame proven to win blocks), and the |
| 466 | /// Re-measured a third time at NATIVE resolution (`encode::tests:: |
| 467 | /// bd_rate_screen_native`, 1920x1024 crops, 12 frames, four quantizers, |
| 468 | /// BD-rate vs libaom / vs rav1e), because every earlier verdict was taken |
| 469 | /// on the 4x-downscaled gate (class `gate-recipe-confound`) and because |
| 470 | /// leaf compound and the distance-scaled search have landed since: |
| 471 | /// |
| 472 | /// | arm | film 1080p | film 2160p | screen | |
| 473 | /// |---|---|---|---| |
| 474 | /// | flat (no pyramid) | +18.7 / +1.4 | +48.1 / +19.8 | +59.4 / -10.0 | |
| 475 | /// | 4:-16:8 | +23.2 / +5.3 | +48.1 / +19.7 | +62.7 / -6.5 | |
| 476 | /// | 2:-16:8 | +24.9 / +6.9 | +46.9 / +19.5 | +69.0 / -3.8 | |
| 477 | /// | 8:-16:8 | +22.6 / +4.6 | +48.7 / +19.8 | +59.3 / -8.2 | |
| 478 | /// | 4:-24:12 (before the leaf-compound merge) | +24.3 / +6.3 | +48.5 / +20.2 | +67.2 / -3.7 | |
| 479 | /// |
| 480 | /// The confound was real -- at native the gap is 5 BD points, not 30 -- |
| 481 | /// but the sign is not: no arm beats flat on both films, every arm costs |
| 482 | /// 4-6 points on 1080p, and the best 2160p arm (`2:-16:8`, -1.1 vs |
| 483 | /// libaom) pays +10 on screen. So the pyramid still ships OFF. |
| 484 | /// |
| 485 | /// A native offset sweep on the 2160p clip alone (mini-GOP 4) says the |
| 486 | /// offsets are not what is missing -- the whole 3x3 grid spans 2.9 BD |
| 487 | /// points and none of it reaches flat's +48.1: |
| 488 | /// |
| 489 | /// | arf \ leaf | +4 | +8 | +12 | |
| 490 | /// |---|---|---|---| |
| 491 | /// | -8 | +48.9 / +20.4 | +49.2 / +20.1 | +50.2 / +20.5 | |
| 492 | /// | -16 | +47.8 / +20.0 | +48.1 / +19.7 | +49.2 / +20.2 | |
| 493 | /// | -24 | +47.3 / +20.0 | +47.6 / +19.7 | +48.5 / +20.2 | |
| 494 | /// |
| 495 | /// The gradient is monotone in both knobs (deeper ARF better, shallower |
| 496 | /// leaf better), which is the shape of a group whose leaves cannot cash |
| 497 | /// in the ARF's extra quality: what the leaves reach the hidden frame |
| 498 | /// with is still one forward search per reference. Shrinking the mini-GOP |
| 499 | /// helps for the same reason (2:-16:8 is the only arm that beats flat on |
| 500 | /// any clip, and it beats it on the clip with the fastest motion). |
| 501 | /// |
| 502 | /// RE-SWEPT on lane-av1pyrgate, once the content gate below existed and |
| 503 | /// on the current defaults (`LAMBDA_SCALE` 0.0275, the 32x32 tx-depth |
| 504 | /// search and compound var-tx on): the earlier verdicts were taken with |
| 505 | /// the screen capture inside the arm, and it is the one clip a pyramid |
| 506 | /// never helps. With the gate, the screen row is the flat row by |
| 507 | /// construction, so the sweep is decided on the two real films |
| 508 | /// (`encode::tests::bd_rate_screen_native`, BD-rate vs libaom / vs |
| 509 | /// rav1e; bars are fixtures, recorded only): |
| 510 | /// |
| 511 | /// | arm | film A | film B | screen | bars 1080p | bars 2160p | |
| 512 | /// |---|---|---|---|---|---| |
| 513 | /// | flat (no pyramid) | +62.8 / +32.5 | +86.3 / +50.5 | +50.1 / -15.4 | +16.4 / -1.1 | +48.2 / +20.4 | |
| 514 | /// | 2:-16:8 | +60.3 / +29.1 | +83.6 / +50.2 | +50.1 / -15.4 | +24.0 / +5.9 | +47.2 / +20.2 | |
| 515 | /// | **4:-16:8** | **+54.1 / +24.2** | **+82.6 / +47.4** | +50.1 / -15.4 | +21.5 / +3.7 | +48.3 / +20.4 | |
| 516 | /// | 8:-16:8 | +55.9 / +25.8 | +83.6 / +47.3 | +50.1 / -15.4 | +19.8 / +2.0 | +48.7 / +20.4 | |
| 517 | /// | 4:-24:12 | +51.5 / +22.3 | +84.9 / +50.3 | +50.1 / -15.4 | +21.9 / +4.0 | +48.4 / +20.7 | |
| 518 | /// | 4:-12:6 | +57.6 / +27.1 | +84.8 / +49.3 | +50.1 / -15.4 | +21.7 / +3.9 | +48.8 / +20.9 | |
| 519 | /// |
| 520 | /// `4:-16:8` is the only arm that improves BOTH films on BOTH columns by |
| 521 | /// several points (-8.7 / -8.3 on film A, -3.7 / -3.1 on film B) and it |
| 522 | /// stays these defaults. `4:-24:12` buys another 2.6 on film A and gives |
| 523 | /// 2.3 back on film B (where it barely beats flat vs rav1e, -0.2), which |
| 524 | /// is the same "leaves cannot cash in the ARF's quality" shape as before, |
| 525 | /// now content-dependent rather than uniform. The screen column is |
| 526 | /// IDENTICAL in every arm -- that is the content gate, measured, not |
| 527 | /// asserted. `EC_AV1_LAMBDA=0.035` on top of `4:-16:8` was re-judged once |
| 528 | /// (the pyramid changes the reference structure): +54.5 / +24.5 and |
| 529 | /// +85.2 / +49.4, worse on both films, so 0.0275 stands. |
| 530 | /// |
| 531 | /// SHIPPED AS THE DEFAULT on lane-av1pyrdef. `4:-16:8` is what |
| 532 | /// [`crate::encode::encode_sequence`] (through |
| 533 | /// [`Av1Encoder::encode_sequence_pyramid`], the one mini-GOP driver both |
| 534 | /// paths run), the BD gates and `ec-bench` code a non-screen stream |
| 535 | /// under; a screen stream still codes flat, decided once per stream by |
| 536 | /// the content gate in [`Av1Encoder::encode_frames`]. `EC_AV1_PYRAMID=0` |
| 537 | /// restores the flat path everywhere for an A/B, and |
| 538 | /// `EC_AV1_PYRAMID=<mini_gop>[:<arf>:<leaf>]` another shape of it |
| 539 | /// ([`Pyramid::from_env`]). |
| 540 | /// |
| 541 | /// [`Av1Encoder::new`] is unchanged: the one-picture-one-packet facade |
| 542 | /// entry point still codes flat, since a picture no longer maps to a |
| 543 | /// packet under a pyramid — [`Av1Encoder::with_pyramid`] plus |
| 544 | /// [`Av1Encoder::encode_frames`] is the streaming surface that reorders. |
| 545 | fn default() -> Self { |
| 546 | Self { |
| 547 | mini_gop: 4, |
| 548 | arf_q_offset: -16, |
| 549 | leaf_q_offset: 8, |
| 550 | } |
| 551 | } |
| 552 | } |
| 553 | |
| 554 | /// Which level of the pyramid a coded frame sits at, reported on every |
| 555 | /// [`Packet`] so a caller (and the BD gate's histogram) can tell them apart |
| 556 | /// without parsing the frame headers back out. |
| 557 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 558 | pub enum Level { |
| 559 | /// A key frame. |
| 560 | Key, |
| 561 | /// A hidden `ALTREF_FRAME`, coded ahead of its display position. |
| 562 | Arf, |
| 563 | /// A shown leaf. |
| 564 | Leaf, |
| 565 | /// A `show_existing_frame` header re-outputting a hidden frame: no coded |
| 566 | /// pixels at all, four bits of header. |
| 567 | ShowExisting, |
| 568 | } |
| 569 | |
| 570 | /// The DPB slot the group anchors alternate between (see |
| 571 | /// [`Av1Encoder::encode_frames`]): the hidden frame of group `g` refreshes |
| 572 | /// `ANCHOR_SLOTS[(g + 1) % 2]`, which is the slot the leaves of group `g` |
| 573 | /// name as `ALTREF_FRAME` and which group `g + 1` reads as its own anchor. |
| 574 | /// Two slots alternate because a group's leaves must still be able to read |
| 575 | /// the previous anchor while the new one is already written. |
| 576 | const ANCHOR_SLOTS: [u8; 2] = [3, 4]; |
| 577 | |
| 578 | /// The slot the leaf chain refreshes and reads as `LAST_FRAME`. |
| 579 | const LEAF_SLOT: u8 = 0; |
| 580 | |
| 581 | /// The AV1 software encoder: [`EncoderConfig`] in, one [`Packet`] out per |
| 582 | /// [`Av1Encoder::encode`] call — or, with a [`Pyramid`] configured, a |
| 583 | /// coding-order burst of them per [`Av1Encoder::encode_frames`] call plus a |
| 584 | /// [`Av1Encoder::flush`] at the end of the stream. |
| 585 | #[derive(Debug)] |
| 586 | pub struct Av1Encoder { |
| 587 | config: EncoderConfig, |
| 588 | color_config: ColorConfig, |
| 589 | /// The previous picture's own (padded, uncropped) reconstruction — what |
| 590 | /// the next inter frame predicts from — or `None` right after a key |
| 591 | /// frame's turn comes up again, where it is about to be replaced rather |
| 592 | /// than read. |
| 593 | reference: Option<Picture>, |
| 594 | next_index: u64, |
| 595 | /// `Some` only when constructed via |
| 596 | /// [`Av1Encoder::with_rate_target`]`(_, RateTarget::BytesPerFrame(_))`; |
| 597 | /// otherwise every picture is coded at `config.base_q_idx`, unchanged |
| 598 | /// from before this field existed. |
| 599 | rate_loop: Option<RateLoop>, |
| 600 | /// This stream's decode-side per-frame state, owned here so `encode` |
| 601 | /// keeps the public signature it had before the state stopped being |
| 602 | /// thread-local. One per encoder, never per frame: several of its fields |
| 603 | /// (the inter-frame inheritance guards) carry state ACROSS frames. |
| 604 | fctx: crate::decode::FrameCtx, |
| 605 | /// What the last coded frame stored into the reference slot the next |
| 606 | /// inter frame reads (spec 7.20): the tables that frame's tile writer |
| 607 | /// must start from, since the header leaves |
| 608 | /// `disable_frame_end_update_cdf` off. `None` before the first frame. |
| 609 | carried_cdfs: Option<crate::encode::CdfSnapshot>, |
| 610 | /// The last key frame's own (padded) reconstruction: `GOLDEN_FRAME`, |
| 611 | /// which stays in DPB slot 1 until the next key frame refreshes it. |
| 612 | golden: Option<Picture>, |
| 613 | /// The frame two back: `ALTREF_FRAME`, in the slot the next frame is |
| 614 | /// about to refresh (`encode_inter_frame`'s 0/2 alternation). |
| 615 | prev2: Option<Picture>, |
| 616 | /// `Some` puts the encoder in pyramid mode: [`Av1Encoder::encode`] then |
| 617 | /// refuses (a picture no longer maps to one packet) and the state below |
| 618 | /// drives coding order. |
| 619 | pyramid: Option<Pyramid>, |
| 620 | /// The eight DPB slots, modelled exactly as the decoder does (spec 7.20): |
| 621 | /// what picture each holds, the order hint it was coded at, and the CDF |
| 622 | /// tables it stored. Only pyramid mode reads these; the flat path keeps |
| 623 | /// `reference`/`golden`/`prev2` so its bytes are unchanged. |
| 624 | dpb: [Option<DpbSlot>; 8], |
| 625 | /// Pictures held back waiting for their mini-GOP's hidden frame. |
| 626 | pending: Vec<(u64, Picture)>, |
| 627 | /// The flat path's delay queue: pictures whose packets later calls |
| 628 | /// return, each coded with the ones behind it as its lookahead window |
| 629 | /// (lane-av1facade, deepened to [`crate::encode::tpl_depth`] - 1 on |
| 630 | /// lane-av1tpl2). Unused in pyramid mode, which buffers in `pending`. |
| 631 | held: std::collections::VecDeque<Picture>, |
| 632 | /// Which of [`ANCHOR_SLOTS`] the group about to be coded reads as its |
| 633 | /// anchor. |
| 634 | anchor: usize, |
| 635 | /// Coding-order position of the next packet — a packet's `dts`. |
| 636 | next_dts: u64, |
| 637 | /// Set by [`Av1Encoder::encode_sequence_pyramid`]: every coded frame's |
| 638 | /// own cropped [`Encoded`] (its display position and its reconstruction), |
| 639 | /// which is what [`crate::encode::EncodedSequence`] carries and a packet |
| 640 | /// does not. `None` for every other caller, which pays nothing for it. |
| 641 | collected: Option<Vec<(u64, Encoded)>>, |
| 642 | } |
| 643 | |
| 644 | /// One decoded-picture-buffer slot: what a `refresh_frame_flags` bit stores |
| 645 | /// and what a `ref_frame_idx` entry reads back. |
| 646 | #[derive(Debug, Clone)] |
| 647 | struct DpbSlot { |
| 648 | picture: Picture, |
| 649 | order_hint: u32, |
| 650 | cdfs: crate::encode::CdfSnapshot, |
| 651 | } |
| 652 | |
| 653 | /// The encoder stays `Send` now that it owns a `FrameCtx` (whose cells are |
| 654 | /// `Send` but `!Sync`): it can move to another thread, it just cannot be |
| 655 | /// shared by reference across threads. |
| 656 | const _: fn() = || { |
| 657 | fn assert_send<T: Send>() {} |
| 658 | assert_send::<Av1Encoder>(); |
| 659 | }; |
| 660 | |
| 661 | impl Av1Encoder { |
| 662 | /// # Errors |
| 663 | /// Returns an error when `config.width`/`config.height` are zero, odd, |
| 664 | /// or larger than the 16-bit frame size an AV1 sequence header carries, |
| 665 | /// or when `config.gop` is zero (there would be no picture to code the |
| 666 | /// next key frame from a cadence of). |
| 667 | pub fn new(config: EncoderConfig) -> Result<Self> { |
| 668 | if config.gop == 0 { |
| 669 | return Err(Error::unsupported("AV1 encode", "gop must be at least 1")); |
| 670 | } |
| 671 | // Validate the geometry the same way the picture-level entry points |
| 672 | // do, before the first `encode()` call rather than only surfacing it |
| 673 | // then. |
| 674 | Picture::grey(config.width, config.height).check_even()?; |
| 675 | // A tile is a whole number of superblocks, so a frame cannot carry |
| 676 | // more tile columns (rows) than it has 64x64 superblocks across |
| 677 | // (down) -- the header's own `max_log2_tile_cols` bound (spec |
| 678 | // 5.9.15), refused here rather than at the first `encode()` call. |
| 679 | let sb_cols = config.width.div_ceil(64) as u32; |
| 680 | let sb_rows = config.height.div_ceil(64) as u32; |
| 681 | if (1u32 << config.tile_cols_log2) > sb_cols || (1u32 << config.tile_rows_log2) > sb_rows { |
| 682 | return Err(Error::unsupported( |
| 683 | "AV1 encode", |
| 684 | format!( |
| 685 | "{}x{} tiles need more than the {sb_cols}x{sb_rows} superblocks this frame has", |
| 686 | 1 << config.tile_cols_log2, |
| 687 | 1 << config.tile_rows_log2 |
| 688 | ), |
| 689 | )); |
| 690 | } |
| 691 | Ok(Self { |
| 692 | carried_cdfs: None, |
| 693 | golden: None, |
| 694 | prev2: None, |
| 695 | color_config: config.colour.color_config(), |
| 696 | config, |
| 697 | reference: None, |
| 698 | next_index: 0, |
| 699 | rate_loop: None, |
| 700 | fctx: crate::decode::FrameCtx::new(), |
| 701 | pyramid: None, |
| 702 | dpb: [const { None }; 8], |
| 703 | pending: Vec::new(), |
| 704 | held: std::collections::VecDeque::new(), |
| 705 | anchor: 0, |
| 706 | next_dts: 0, |
| 707 | collected: None, |
| 708 | }) |
| 709 | } |
| 710 | |
| 711 | /// [`Av1Encoder::new`] in pyramid mode: pictures are coded out of display |
| 712 | /// order, so a call to [`Av1Encoder::encode_frames`] returns zero, one or |
| 713 | /// several packets and [`Av1Encoder::flush`] drains whatever is still |
| 714 | /// held at the end of the stream. [`Av1Encoder::encode`]'s one-in-one-out |
| 715 | /// contract cannot hold here and it returns an error instead; a caller |
| 716 | /// that wants the old shape simply does not call this constructor. |
| 717 | /// |
| 718 | /// # Errors |
| 719 | /// As [`Av1Encoder::new`], plus a `mini_gop` below 2 (no leaf would be |
| 720 | /// left between the anchor and the hidden frame) or above `config.gop` |
| 721 | /// (the group would straddle a key frame). |
| 722 | pub fn with_pyramid(config: EncoderConfig, pyramid: Pyramid) -> Result<Self> { |
| 723 | if pyramid.mini_gop < 2 { |
| 724 | return Err(Error::unsupported( |
| 725 | "AV1 encode", |
| 726 | "a pyramid mini-GOP is at least 2 pictures", |
| 727 | )); |
| 728 | } |
| 729 | let mut encoder = Self::new(config)?; |
| 730 | encoder.pyramid = Some(pyramid); |
| 731 | Ok(encoder) |
| 732 | } |
| 733 | |
| 734 | /// [`Av1Encoder::new`], but `rate` picks `base_q_idx` (or steers it, |
| 735 | /// frame by frame, for [`RateTarget::BytesPerFrame`]) instead of |
| 736 | /// `config.base_q_idx` being used as-is. |
| 737 | /// |
| 738 | /// # Errors |
| 739 | /// Same as [`Av1Encoder::new`]. |
| 740 | pub fn with_rate_target(mut config: EncoderConfig, rate: RateTarget) -> Result<Self> { |
| 741 | let rate_loop = rate.into_loop(&mut config, None); |
| 742 | let mut encoder = Self::new(config)?; |
| 743 | encoder.rate_loop = rate_loop; |
| 744 | Ok(encoder) |
| 745 | } |
| 746 | |
| 747 | /// [`Av1Encoder::with_pyramid`] and [`Av1Encoder::with_rate_target`] at |
| 748 | /// once: the rate loop then keeps a separate quantizer per pyramid level, |
| 749 | /// predicting each frame's size from the previous frame of its OWN level |
| 750 | /// (a leaf and a hidden `ALTREF` differ by several times in size, so one |
| 751 | /// shared predictor would swing the quantizer every frame). |
| 752 | /// |
| 753 | /// # Errors |
| 754 | /// As both. |
| 755 | pub fn with_pyramid_and_rate_target( |
| 756 | mut config: EncoderConfig, |
| 757 | pyramid: Pyramid, |
| 758 | rate: RateTarget, |
| 759 | ) -> Result<Self> { |
| 760 | let rate_loop = rate.into_loop(&mut config, Some(pyramid.mini_gop)); |
| 761 | let mut encoder = Self::with_pyramid(config, pyramid)?; |
| 762 | encoder.rate_loop = rate_loop; |
| 763 | Ok(encoder) |
| 764 | } |
| 765 | |
| 766 | /// The [`Pyramid`] this stream is actually coding under: what |
| 767 | /// [`Av1Encoder::with_pyramid`] asked for, or `None` once the content gate |
| 768 | /// in [`Av1Encoder::encode_frames`] has dropped a screen-content stream |
| 769 | /// back to the flat path. Meaningful after the first picture has been |
| 770 | /// handed in. |
| 771 | #[must_use] |
| 772 | pub fn pyramid(&self) -> Option<Pyramid> { |
| 773 | self.pyramid |
| 774 | } |
| 775 | |
| 776 | /// The coded (padded-to-64) frame size every picture in this stream is |
| 777 | /// coded at — what a decoder allocates and what `ffprobe` reports. |
| 778 | #[must_use] |
| 779 | pub fn coded_size(&self) -> (usize, usize) { |
| 780 | ( |
| 781 | self.config.width.next_multiple_of(SUPERBLOCK), |
| 782 | self.config.height.next_multiple_of(SUPERBLOCK), |
| 783 | ) |
| 784 | } |
| 785 | |
| 786 | /// The display (render) size every frame header signals — [`EncoderConfig`]'s |
| 787 | /// own `width`/`height`, always, whatever the coded size pads it to. |
| 788 | #[must_use] |
| 789 | pub fn display_size(&self) -> (usize, usize) { |
| 790 | (self.config.width, self.config.height) |
| 791 | } |
| 792 | |
| 793 | /// Takes one picture and returns the PREVIOUS picture's packet, key or |
| 794 | /// inter by this stream's `gop` cadence — the facade's one frame of |
| 795 | /// latency (the picture just handed in is what the previous one is coded |
| 796 | /// against as its lookahead). The FIRST call has no previous picture and |
| 797 | /// returns a packet with an EMPTY `data` (its other fields are |
| 798 | /// placeholders; test `data.is_empty()`), and the last picture's packet |
| 799 | /// comes out of [`Av1Encoder::flush`] — so a caller that concatenates |
| 800 | /// `data` in call order still gets the whole stream, provided it flushes |
| 801 | /// at the end. |
| 802 | /// |
| 803 | /// # Errors |
| 804 | /// Returns an error when `picture`'s size does not match |
| 805 | /// [`EncoderConfig::width`]/[`EncoderConfig::height`], when the encoder |
| 806 | /// was built by [`Av1Encoder::with_pyramid`] (which reorders pictures, so |
| 807 | /// one call cannot return one packet), or under the same conditions |
| 808 | /// [`crate::encode::encode_key_frame`]/[`crate::encode::encode_sequence`] |
| 809 | /// do. |
| 810 | pub fn encode(&mut self, picture: &Picture) -> Result<Packet> { |
| 811 | if self.pyramid.is_some() { |
| 812 | return Err(Error::unsupported( |
| 813 | "AV1 encode", |
| 814 | "a pyramid stream reorders pictures -- use encode_frames()/flush()", |
| 815 | )); |
| 816 | } |
| 817 | let mut packets = self.encode_frames(picture)?; |
| 818 | Ok(packets.pop().unwrap_or(Packet { |
| 819 | data: Vec::new(), |
| 820 | key: false, |
| 821 | order: 0, |
| 822 | dts: 0, |
| 823 | level: Level::Leaf, |
| 824 | })) |
| 825 | } |
| 826 | |
| 827 | /// Takes one picture and returns every packet it completed, in coding |
| 828 | /// order. Without a [`Pyramid`] that is one packet — the PREVIOUS |
| 829 | /// picture's, since this one is its lookahead — and none at all on the |
| 830 | /// first call; with one it is |
| 831 | /// empty for most pictures and a whole mini-GOP's worth (the hidden |
| 832 | /// frame, its leaves and the `show_existing_frame` that re-outputs it) |
| 833 | /// for the picture that closes a group. |
| 834 | /// |
| 835 | /// # Errors |
| 836 | /// As [`Av1Encoder::encode`], minus the pyramid refusal. |
| 837 | pub fn encode_frames(&mut self, picture: &Picture) -> Result<Vec<Packet>> { |
| 838 | crate::encode::arm_tiles(self.config.tile_cols_log2, self.config.tile_rows_log2); |
| 839 | if (picture.width, picture.height) != (self.config.width, self.config.height) { |
| 840 | return Err(Error::unsupported( |
| 841 | "AV1 encode", |
| 842 | format!( |
| 843 | "picture is {}x{}, encoder is {}x{}", |
| 844 | picture.width, picture.height, self.config.width, self.config.height |
| 845 | ), |
| 846 | )); |
| 847 | } |
| 848 | // THE CONTENT GATE (lane-av1pyrgate): the pyramid is for camera |
| 849 | // material. A desktop capture is the one content class every pyramid |
| 850 | // sweep measured WORSE under it, and it is exactly the class the |
| 851 | // screen detector separates (`encode::screen_content`: 0/48 frames on |
| 852 | // both real films, 48/48 on the OBS capture), so a stream whose first |
| 853 | // picture reads as screen content drops back to the flat path and |
| 854 | // codes byte for byte what it coded before the pyramid existed. |
| 855 | // |
| 856 | // Decided ONCE, on the first picture, not per mini-GOP: the flat path |
| 857 | // keeps its references in `reference`/`golden`/`prev2` and the pyramid |
| 858 | // path in `dpb`, so a switch after the first frame would read slots |
| 859 | // the other path never filled. Per-GOP re-decision needs the two |
| 860 | // reference sets kept in step first; the gate's own recipe codes one |
| 861 | // GOP per stream, where the two are the same decision. |
| 862 | if self.pyramid.is_some() |
| 863 | && self.next_index == 0 |
| 864 | && crate::encode::picture_is_screen(picture) |
| 865 | { |
| 866 | self.pyramid = None; |
| 867 | } |
| 868 | let Some(pyramid) = self.pyramid else { |
| 869 | // The delay queue: the pictures behind this one are the |
| 870 | // lookahead window the one at its head is coded with, which is |
| 871 | // what makes the facade's bytes identical to |
| 872 | // `encode_sequence`'s (lane-av1facade, lane-av1tpl2). |
| 873 | self.held.push_back(picture.clone()); |
| 874 | if self.held.len() <= crate::encode::tpl_depth() - 1 { |
| 875 | return Ok(Vec::new()); |
| 876 | } |
| 877 | let previous = self.held.pop_front().expect("queue is over depth"); |
| 878 | let window: Vec<Picture> = self.held.iter().cloned().collect(); |
| 879 | return Ok(vec![self.encode_flat(&previous, &window)?]); |
| 880 | }; |
| 881 | let order = self.next_index; |
| 882 | self.next_index += 1; |
| 883 | if order.is_multiple_of(self.config.gop as u64) { |
| 884 | // A key frame closes whatever group is open (there is nothing for |
| 885 | // its leaves to point forward at across the boundary) and then |
| 886 | // restarts the pyramid from the key itself. |
| 887 | let mut packets = self.drain_pending()?; |
| 888 | packets.push(self.encode_key(order, picture)?); |
| 889 | return Ok(packets); |
| 890 | } |
| 891 | self.pending.push((order, picture.clone())); |
| 892 | // The group closes on its own size, or early when the next picture |
| 893 | // would be a key frame. |
| 894 | let next_is_key = (order + 1).is_multiple_of(self.config.gop as u64); |
| 895 | if self.pending.len() >= pyramid.mini_gop || next_is_key { |
| 896 | return self.drain_pending(); |
| 897 | } |
| 898 | Ok(Vec::new()) |
| 899 | } |
| 900 | |
| 901 | /// Codes and returns every picture still held back — the last picture of |
| 902 | /// a flat stream (which has no lookahead and is coded without one), or |
| 903 | /// the tail of a pyramid stream whose last mini-GOP never filled up. |
| 904 | /// Empty once there is nothing held. |
| 905 | /// |
| 906 | /// # Errors |
| 907 | /// As [`Av1Encoder::encode_frames`]. |
| 908 | pub fn flush(&mut self) -> Result<Vec<Packet>> { |
| 909 | crate::encode::arm_tiles(self.config.tile_cols_log2, self.config.tile_rows_log2); |
| 910 | if !self.held.is_empty() { |
| 911 | let mut packets = Vec::with_capacity(self.held.len()); |
| 912 | while let Some(previous) = self.held.pop_front() { |
| 913 | let window: Vec<Picture> = self.held.iter().cloned().collect(); |
| 914 | packets.push(self.encode_flat(&previous, &window)?); |
| 915 | } |
| 916 | return Ok(packets); |
| 917 | } |
| 918 | self.drain_pending() |
| 919 | } |
| 920 | |
| 921 | /// The flat path: one picture and its lookahead (the next source picture, |
| 922 | /// `None` at the end of the stream) in, one packet out — the same inputs |
| 923 | /// [`crate::encode::encode_sequence`] gives each of its inter frames, so |
| 924 | /// the bytes are identical. |
| 925 | fn encode_flat(&mut self, picture: &Picture, lookahead: &[Picture]) -> Result<Packet> { |
| 926 | let render = (self.config.width, self.config.height); |
| 927 | let padded = picture.padded_to(SUPERBLOCK); |
| 928 | let is_key = self.next_index.is_multiple_of(self.config.gop as u64); |
| 929 | let order = self.next_index; |
| 930 | let base_q_idx = self.rate_loop.as_ref().map_or(self.config.base_q_idx, |r| { |
| 931 | r.q_idx(if is_key { Level::Key } else { Level::Leaf }) |
| 932 | }); |
| 933 | |
| 934 | let encoded: Encoded = if is_key { |
| 935 | encode_key_frame_inner( |
| 936 | &padded, |
| 937 | base_q_idx, |
| 938 | DEADZONE, |
| 939 | &KEY_FRAME_MODES, |
| 940 | split_blocks(), |
| 941 | render, |
| 942 | self.color_config, |
| 943 | &self.fctx, |
| 944 | )? |
| 945 | } else { |
| 946 | let reference = self.reference.as_ref().ok_or_else(|| { |
| 947 | Error::unsupported( |
| 948 | "AV1 encode", |
| 949 | "an inter frame needs a previous reconstruction", |
| 950 | ) |
| 951 | })?; |
| 952 | encode_inter_frame( |
| 953 | &padded, |
| 954 | reference, |
| 955 | base_q_idx, |
| 956 | DEADZONE, |
| 957 | order as u32, |
| 958 | // The flat path's own slot plan, in order hints: the key frame |
| 959 | // of the GOP this picture sits in is what `GOLDEN_FRAME` |
| 960 | // names, and every reference but `ALTREF_FRAME` is the frame |
| 961 | // just coded. |
| 962 | crate::encode::flat_order_hints( |
| 963 | order as u32 & 0x7f, |
| 964 | (order - order % self.config.gop as u64) as u32 & 0x7f, |
| 965 | self.prev2.is_some(), |
| 966 | ), |
| 967 | render, |
| 968 | self.carried_cdfs.as_ref().map(|c| &c.0), |
| 969 | self.golden.as_ref(), |
| 970 | self.prev2.as_ref(), |
| 971 | &self.fctx, |
| 972 | None, |
| 973 | &lookahead.iter().map(|n| n.padded_to(SUPERBLOCK)).collect::<Vec<_>>(), |
| 974 | )? |
| 975 | }; |
| 976 | |
| 977 | self.carried_cdfs = Some(encoded.next_cdfs.clone()); |
| 978 | if is_key { |
| 979 | self.golden = Some(encoded.reconstruction.clone()); |
| 980 | self.prev2 = None; |
| 981 | } else { |
| 982 | self.prev2 = self.reference.take(); |
| 983 | } |
| 984 | self.reference = Some(encoded.reconstruction.clone()); |
| 985 | self.next_index += 1; |
| 986 | let cropped = crop_encoded(&encoded, render.0, render.1); |
| 987 | let level = if is_key { Level::Key } else { Level::Leaf }; |
| 988 | if let Some(rate_loop) = self.rate_loop.as_mut() { |
| 989 | rate_loop.update(level, cropped.stream.len()); |
| 990 | } |
| 991 | Ok(self.packet(cropped.stream, is_key, order, level)) |
| 992 | } |
| 993 | |
| 994 | /// THE SHARED MINI-GOP DRIVER: codes a whole sequence — one key frame |
| 995 | /// then all inter, which is [`crate::encode::encode_sequence`]'s only |
| 996 | /// shape — through this very facade, under `pyramid`, and hands back what |
| 997 | /// that path returns. The two are byte-identical BY CONSTRUCTION rather |
| 998 | /// than by a mirrored second implementation: there is one reordering, |
| 999 | /// one DPB/slot policy and one set of per-level quantizer offsets, here |
| 1000 | /// (`encoder::tests::the_facade_codes_the_same_bytes_as_encode_sequence` |
| 1001 | /// still pins it, now over a pyramid sequence too). |
| 1002 | /// |
| 1003 | /// The content gate lives in [`Av1Encoder::encode_frames`] and applies |
| 1004 | /// unchanged, so a screen-content clip handed in here codes flat. |
| 1005 | /// |
| 1006 | /// `EncodedSequence::frames` comes back in DISPLAY order, one entry per |
| 1007 | /// source picture — the order the flat path's coding order happens to be, |
| 1008 | /// and the order every reader of it (the BD gate's sample-exactness |
| 1009 | /// assertions against a decoder's output) needs. `stream` stays in coding |
| 1010 | /// order, which is the order a decoder reads. |
| 1011 | /// |
| 1012 | /// # Errors |
| 1013 | /// As [`Av1Encoder::encode_frames`]. |
| 1014 | pub(crate) fn encode_sequence_pyramid( |
| 1015 | pictures: &[Picture], |
| 1016 | base_q_idx: u8, |
| 1017 | pyramid: Pyramid, |
| 1018 | tiles: (u32, u32), |
| 1019 | ) -> Result<crate::encode::EncodedSequence> { |
| 1020 | let first = pictures.first().ok_or_else(|| { |
| 1021 | Error::unsupported("AV1 encode", "a sequence needs at least one picture") |
| 1022 | })?; |
| 1023 | let config = EncoderConfig { |
| 1024 | width: first.width, |
| 1025 | height: first.height, |
| 1026 | base_q_idx, |
| 1027 | // One key frame, at picture 0, and inter for the rest. |
| 1028 | gop: pictures.len().max(1), |
| 1029 | // `encode_sequence` writes an unspecified colour config. |
| 1030 | colour: Colour::Unspecified, |
| 1031 | tile_cols_log2: tiles.0, |
| 1032 | tile_rows_log2: tiles.1, |
| 1033 | }; |
| 1034 | let mut encoder = Self::with_pyramid(config, pyramid)?; |
| 1035 | encoder.collected = Some(Vec::with_capacity(pictures.len())); |
| 1036 | let mut stream = Vec::new(); |
| 1037 | for picture in pictures { |
| 1038 | for packet in encoder.encode_frames(picture)? { |
| 1039 | stream.extend_from_slice(&packet.data); |
| 1040 | } |
| 1041 | } |
| 1042 | for packet in encoder.flush()? { |
| 1043 | stream.extend_from_slice(&packet.data); |
| 1044 | } |
| 1045 | let mut collected = encoder.collected.take().expect("collecting"); |
| 1046 | // Every source picture is coded exactly once, so a frame's display |
| 1047 | // order IS its index once the list is sorted by it. |
| 1048 | let coding_order: Vec<usize> = |
| 1049 | collected.iter().map(|(order, _)| *order as usize).collect(); |
| 1050 | collected.sort_by_key(|(order, _)| *order); |
| 1051 | let frames: Vec<Encoded> = collected.into_iter().map(|(_, encoded)| encoded).collect(); |
| 1052 | assert!( |
| 1053 | coding_order.iter().all(|&i| i < frames.len()), |
| 1054 | "a coded frame's display position is outside the sequence" |
| 1055 | ); |
| 1056 | Ok(crate::encode::EncodedSequence { stream, frames, coding_order }) |
| 1057 | } |
| 1058 | |
| 1059 | /// Stamps a packet with its display and coding positions and advances the |
| 1060 | /// coding-order clock. |
| 1061 | fn packet(&mut self, data: Vec<u8>, key: bool, order: u64, level: Level) -> Packet { |
| 1062 | let dts = self.next_dts; |
| 1063 | self.next_dts += 1; |
| 1064 | Packet { |
| 1065 | data, |
| 1066 | key, |
| 1067 | order, |
| 1068 | dts, |
| 1069 | level, |
| 1070 | } |
| 1071 | } |
| 1072 | |
| 1073 | /// Stores a coded frame into every DPB slot its `refresh_frame_flags` |
| 1074 | /// names (spec 7.20). |
| 1075 | fn refresh(&mut self, slots: &[u8], encoded: &Encoded, order_hint: u32) { |
| 1076 | let slot = DpbSlot { |
| 1077 | picture: encoded.reconstruction.clone(), |
| 1078 | order_hint, |
| 1079 | cdfs: encoded.next_cdfs.clone(), |
| 1080 | }; |
| 1081 | for &s in slots { |
| 1082 | self.dpb[s as usize] = Some(slot.clone()); |
| 1083 | } |
| 1084 | } |
| 1085 | |
| 1086 | /// Codes a key frame in pyramid mode: it refreshes all eight slots, so it |
| 1087 | /// becomes the anchor, the `GOLDEN_FRAME` and the CDF source for the |
| 1088 | /// whole GOP at once. |
| 1089 | fn encode_key(&mut self, order: u64, picture: &Picture) -> Result<Packet> { |
| 1090 | let render = (self.config.width, self.config.height); |
| 1091 | let base_q_idx = self |
| 1092 | .rate_loop |
| 1093 | .as_ref() |
| 1094 | .map_or(self.config.base_q_idx, |r| r.q_idx(Level::Key)); |
| 1095 | let encoded = encode_key_frame_inner( |
| 1096 | &picture.padded_to(SUPERBLOCK), |
| 1097 | base_q_idx, |
| 1098 | DEADZONE, |
| 1099 | &KEY_FRAME_MODES, |
| 1100 | split_blocks(), |
| 1101 | render, |
| 1102 | self.color_config, |
| 1103 | &self.fctx, |
| 1104 | )?; |
| 1105 | self.refresh(&[0, 1, 2, 3, 4, 5, 6, 7], &encoded, 0); |
| 1106 | self.anchor = 0; |
| 1107 | let cropped = crop_encoded(&encoded, render.0, render.1); |
| 1108 | if let Some(rate_loop) = self.rate_loop.as_mut() { |
| 1109 | rate_loop.update(Level::Key, cropped.stream.len()); |
| 1110 | } |
| 1111 | if let Some(collected) = self.collected.as_mut() { |
| 1112 | collected.push((order, cropped.clone())); |
| 1113 | } |
| 1114 | Ok(self.packet(cropped.stream, true, order, Level::Key)) |
| 1115 | } |
| 1116 | |
| 1117 | /// Codes one inter frame at `order` from the DPB, in coding order. |
| 1118 | #[allow(clippy::too_many_arguments)] |
| 1119 | fn encode_pyramid_inter( |
| 1120 | &mut self, |
| 1121 | order: u64, |
| 1122 | picture: &Picture, |
| 1123 | last_slot: u8, |
| 1124 | self_slot: u8, |
| 1125 | altref_slot: u8, |
| 1126 | show_frame: bool, |
| 1127 | level: Level, |
| 1128 | ) -> Result<Packet> { |
| 1129 | let render = (self.config.width, self.config.height); |
| 1130 | let order_hint = (order & 0x7f) as u32; |
| 1131 | let pyramid = self.pyramid.expect("pyramid mode"); |
| 1132 | let offset = match level { |
| 1133 | Level::Arf => pyramid.arf_q_offset, |
| 1134 | _ => pyramid.leaf_q_offset, |
| 1135 | }; |
| 1136 | let base = self |
| 1137 | .rate_loop |
| 1138 | .as_ref() |
| 1139 | .map_or(i16::from(self.config.base_q_idx), |r| { |
| 1140 | i16::from(r.q_idx(level)) |
| 1141 | }); |
| 1142 | let base_q_idx = (base + offset).clamp(1, 255) as u8; |
| 1143 | // spec 5.9.2's `ref_frame_sign_bias`, derived from what the slots |
| 1144 | // this frame names actually hold: a reference whose order hint is |
| 1145 | // AHEAD of this frame's is backward-biased, and the MV stack scans |
| 1146 | // (writer and decoder alike) flip borrowed candidates across the |
| 1147 | // boundary. Only `ALTREF_FRAME` can be ahead here — the leaves of a |
| 1148 | // mini-GOP name the group's hidden frame there. |
| 1149 | let mut sign_bias = crate::mvstack::NO_SIGN_BIAS; |
| 1150 | let ahead = |slot: u8, dpb: &[Option<DpbSlot>; 8]| { |
| 1151 | dpb[slot as usize] |
| 1152 | .as_ref() |
| 1153 | .is_some_and(|s| s.order_hint > order_hint) |
| 1154 | }; |
| 1155 | let slots = [ |
| 1156 | last_slot, last_slot, last_slot, GOLDEN_SLOT, last_slot, last_slot, altref_slot, |
| 1157 | ]; |
| 1158 | for (i, slot) in slots.into_iter().enumerate() { |
| 1159 | sign_bias[i] = ahead(slot, &self.dpb); |
| 1160 | } |
| 1161 | // The same seven slots' order hints, for `skipModeAllowed` (spec |
| 1162 | // 5.9.22) in the frame-header writer. |
| 1163 | let order_hints: [u32; 7] = slots.map(|slot| { |
| 1164 | self.dpb[slot as usize] |
| 1165 | .as_ref() |
| 1166 | .map_or(0, |s| (s.order_hint & 0x7f) as u32) |
| 1167 | }); |
| 1168 | let reference = self.dpb[last_slot as usize] |
| 1169 | .as_ref() |
| 1170 | .map(|s| s.picture.clone()) |
| 1171 | .ok_or_else(|| { |
| 1172 | Error::unsupported("AV1 encode", "an inter frame needs a previous reconstruction") |
| 1173 | })?; |
| 1174 | let golden = self.dpb[GOLDEN_SLOT as usize].as_ref().map(|s| s.picture.clone()); |
| 1175 | let altref = (altref_slot != GOLDEN_SLOT) |
| 1176 | .then(|| self.dpb[altref_slot as usize].as_ref().map(|s| s.picture.clone())) |
| 1177 | .flatten(); |
| 1178 | let start_cdfs = self.dpb[last_slot as usize].as_ref().map(|s| s.cdfs.0.clone()); |
| 1179 | let encoded = || -> Result<Encoded> { encode_inter_frame( |
| 1180 | &picture.padded_to(SUPERBLOCK), |
| 1181 | &reference, |
| 1182 | base_q_idx, |
| 1183 | DEADZONE, |
| 1184 | order_hint, |
| 1185 | order_hints, |
| 1186 | render, |
| 1187 | start_cdfs.as_ref(), |
| 1188 | golden.as_ref(), |
| 1189 | altref.as_ref(), |
| 1190 | &self.fctx, |
| 1191 | Some(crate::encode::PyramidFrame { |
| 1192 | last_slot, |
| 1193 | self_slot, |
| 1194 | altref_slot, |
| 1195 | show_frame, |
| 1196 | sign_bias, |
| 1197 | }), |
| 1198 | // The pyramid path reorders pictures, so its own buffer is not |
| 1199 | // a lookahead window: the temporal lambda weighting is off on |
| 1200 | // this path (lane-av1tpl). |
| 1201 | &[], |
| 1202 | ) }(); |
| 1203 | // Name the pyramid position in any failure: an error out of the tile |
| 1204 | // writer or the filter search is otherwise indistinguishable between |
| 1205 | // the hidden frame and the leaves that read it. |
| 1206 | let encoded = encoded.map_err(|e| { |
| 1207 | Error::unsupported( |
| 1208 | "AV1 encode", |
| 1209 | format!( |
| 1210 | "{level:?} frame at order {order} (last slot {last_slot}, self {self_slot}, \ |
| 1211 | altref {altref_slot}, shown {show_frame}, golden {}, altref pic {}): {e}", |
| 1212 | golden.is_some(), |
| 1213 | altref.is_some(), |
| 1214 | ), |
| 1215 | ) |
| 1216 | })?; |
| 1217 | self.refresh(&[self_slot], &encoded, order_hint); |
| 1218 | let cropped = crop_encoded(&encoded, render.0, render.1); |
| 1219 | if let Some(rate_loop) = self.rate_loop.as_mut() { |
| 1220 | rate_loop.update(level, cropped.stream.len()); |
| 1221 | } |
| 1222 | if let Some(collected) = self.collected.as_mut() { |
| 1223 | collected.push((order, cropped.clone())); |
| 1224 | } |
| 1225 | Ok(self.packet(cropped.stream, false, order, level)) |
| 1226 | } |
| 1227 | |
| 1228 | /// Codes the open mini-GOP: its hidden frame first, then its leaves, then |
| 1229 | /// the `show_existing_frame` header that puts the hidden frame back in |
| 1230 | /// display order. |
| 1231 | fn drain_pending(&mut self) -> Result<Vec<Packet>> { |
| 1232 | if self.pending.is_empty() { |
| 1233 | return Ok(Vec::new()); |
| 1234 | } |
| 1235 | let group: Vec<(u64, Picture)> = std::mem::take(&mut self.pending); |
| 1236 | let mut packets = Vec::with_capacity(group.len() + 1); |
| 1237 | let anchor_slot = ANCHOR_SLOTS[self.anchor]; |
| 1238 | let next_anchor_slot = ANCHOR_SLOTS[1 - self.anchor]; |
| 1239 | let (arf_order, arf_picture) = group.last().cloned().expect("non-empty"); |
| 1240 | if group.len() == 1 { |
| 1241 | // Nothing to predict backward, so no hidden frame: one shown leaf |
| 1242 | // that also becomes the next group's anchor. |
| 1243 | packets.push(self.encode_pyramid_inter( |
| 1244 | arf_order, |
| 1245 | &arf_picture, |
| 1246 | anchor_slot, |
| 1247 | next_anchor_slot, |
| 1248 | GOLDEN_SLOT, |
| 1249 | true, |
| 1250 | Level::Leaf, |
| 1251 | )?); |
| 1252 | self.anchor = 1 - self.anchor; |
| 1253 | return Ok(packets); |
| 1254 | } |
| 1255 | packets.push(self.encode_pyramid_inter( |
| 1256 | arf_order, |
| 1257 | &arf_picture, |
| 1258 | anchor_slot, |
| 1259 | next_anchor_slot, |
| 1260 | GOLDEN_SLOT, |
| 1261 | false, |
| 1262 | Level::Arf, |
| 1263 | )?); |
| 1264 | for (i, (order, picture)) in group[..group.len() - 1].iter().enumerate() { |
| 1265 | let last_slot = if i == 0 { anchor_slot } else { LEAF_SLOT }; |
| 1266 | packets.push(self.encode_pyramid_inter( |
| 1267 | *order, |
| 1268 | picture, |
| 1269 | last_slot, |
| 1270 | LEAF_SLOT, |
| 1271 | next_anchor_slot, |
| 1272 | true, |
| 1273 | Level::Leaf, |
| 1274 | )?); |
| 1275 | } |
| 1276 | let (seq, _) = crate::encode::key_frame_headers( |
| 1277 | self.config.width, |
| 1278 | self.config.height, |
| 1279 | self.config.base_q_idx, |
| 1280 | )?; |
| 1281 | let mut data = crate::obu::temporal_delimiter(); |
| 1282 | data.extend_from_slice(&crate::frame::show_existing_frame_obu( |
| 1283 | &seq, |
| 1284 | next_anchor_slot, |
| 1285 | )?); |
| 1286 | packets.push(self.packet(data, false, arf_order, Level::ShowExisting)); |
| 1287 | self.anchor = 1 - self.anchor; |
| 1288 | Ok(packets) |
| 1289 | } |
| 1290 | } |
| 1291 | |
| 1292 | #[cfg(test)] |
| 1293 | mod tests { |
| 1294 | use super::*; |
| 1295 | use std::process::{Command, Stdio}; |
| 1296 | |
| 1297 | /// Whether ffmpeg is on PATH. Absence normally SKIPs, but |
| 1298 | /// `EC_AV1_REQUIRE_FFMPEG=1` -- or `EC_AV1_REQUIRE_AOMENC=1`, since every |
| 1299 | /// aomenc gate decodes its stream through ffmpeg and is meaningless |
| 1300 | /// without it -- turns it into a hard failure. Without this the require |
| 1301 | /// flag was silently short-circuited: `!have_ffmpeg()` is evaluated first |
| 1302 | /// in `if !have_ffmpeg() || !have_aomenc()`, so a machine with no ffmpeg |
| 1303 | /// printed SKIP and reported green (class gate-skips-on-its-own-failure). |
| 1304 | fn have_ffmpeg() -> bool { |
| 1305 | let present = Command::new("ffmpeg") |
| 1306 | .arg("-version") |
| 1307 | .stdout(Stdio::null()) |
| 1308 | .stderr(Stdio::null()) |
| 1309 | .status() |
| 1310 | .is_ok_and(|s| s.success()); |
| 1311 | assert!( |
| 1312 | present |
| 1313 | || (std::env::var_os("EC_AV1_REQUIRE_FFMPEG").is_none() |
| 1314 | && std::env::var_os("EC_AV1_REQUIRE_AOMENC").is_none()), |
| 1315 | "EC_AV1_REQUIRE_FFMPEG/EC_AV1_REQUIRE_AOMENC is set but no working ffmpeg on PATH" |
| 1316 | ); |
| 1317 | present |
| 1318 | } |
| 1319 | |
| 1320 | fn test_card(width: usize, height: usize, shift: usize) -> Picture { |
| 1321 | let mut picture = Picture::grey(width, height); |
| 1322 | for y in 0..height { |
| 1323 | for x in 0..width { |
| 1324 | let sx = (x + shift) % width; |
| 1325 | picture.y[y * width + x] = ((sx * 3 + y * 5) % 256) as u16; |
| 1326 | } |
| 1327 | } |
| 1328 | for y in 0..height / 2 { |
| 1329 | for x in 0..width / 2 { |
| 1330 | let i = y * (width / 2) + x; |
| 1331 | picture.u[i] = ((100 + shift * 4) % 256) as u16; |
| 1332 | picture.v[i] = ((200 + 256 - shift * 2 % 256) % 256) as u16; |
| 1333 | } |
| 1334 | } |
| 1335 | picture |
| 1336 | } |
| 1337 | |
| 1338 | /// Drives a whole stream through the facade the way a caller must since |
| 1339 | /// it holds one picture of lookahead: every picture through |
| 1340 | /// [`Av1Encoder::encode_frames`], then [`Av1Encoder::flush`]. |
| 1341 | fn encode_all(enc: &mut Av1Encoder, pictures: &[Picture]) -> Vec<Packet> { |
| 1342 | let mut packets = Vec::with_capacity(pictures.len()); |
| 1343 | for (i, picture) in pictures.iter().enumerate() { |
| 1344 | packets.extend( |
| 1345 | enc.encode_frames(picture) |
| 1346 | .unwrap_or_else(|e| panic!("picture {i}: {e}")), |
| 1347 | ); |
| 1348 | } |
| 1349 | packets.extend(enc.flush().unwrap_or_else(|e| panic!("flush: {e}"))); |
| 1350 | packets |
| 1351 | } |
| 1352 | |
| 1353 | /// Every OBU stream this test writes to `ffmpeg`/`ffprobe`, concatenated |
| 1354 | /// in order. |
| 1355 | fn concat(packets: &[Packet]) -> Vec<u8> { |
| 1356 | packets.iter().flat_map(|p| p.data.clone()).collect() |
| 1357 | } |
| 1358 | |
| 1359 | /// The facade's latency contract (lane-av1facade, deepened on |
| 1360 | /// lane-av1tpl2): the first [`crate::encode::tpl_depth`] - 1 calls hold |
| 1361 | /// their picture back and return an empty packet, every later call |
| 1362 | /// returns the packet of the picture that many frames earlier, and |
| 1363 | /// [`Av1Encoder::flush`] yields the whole queue — so a caller still gets |
| 1364 | /// exactly one non-empty packet per picture, `depth - 1` calls later. |
| 1365 | #[test] |
| 1366 | fn one_in_one_out_delayed_by_the_lookahead_depth() { |
| 1367 | let config = EncoderConfig { |
| 1368 | width: 64, |
| 1369 | height: 64, |
| 1370 | base_q_idx: 100, |
| 1371 | gop: 2, |
| 1372 | colour: Colour::Bt709Limited, |
| 1373 | tile_cols_log2: 0, |
| 1374 | tile_rows_log2: 0, |
| 1375 | }; |
| 1376 | let delay = crate::encode::tpl_depth() as u64 - 1; |
| 1377 | let pictures = delay + 5; |
| 1378 | let mut enc = Av1Encoder::new(config).unwrap(); |
| 1379 | for t in 0..pictures { |
| 1380 | let packet = enc.encode(&test_card(64, 64, t as usize)).unwrap(); |
| 1381 | if t < delay { |
| 1382 | assert!(packet.data.is_empty(), "call {t} holds its picture back"); |
| 1383 | continue; |
| 1384 | } |
| 1385 | assert!(!packet.data.is_empty(), "picture {t}: empty packet"); |
| 1386 | assert_eq!(packet.order, t - delay, "picture {t}: order"); |
| 1387 | } |
| 1388 | let tail = enc.flush().unwrap(); |
| 1389 | assert_eq!(tail.len() as u64, delay, "flush yields the whole queue"); |
| 1390 | for (i, p) in tail.iter().enumerate() { |
| 1391 | assert_eq!(p.order, pictures - delay + i as u64, "flushed packet {i}: order"); |
| 1392 | assert!(!p.data.is_empty(), "flushed packet {i}: empty"); |
| 1393 | } |
| 1394 | assert!(enc.flush().unwrap().is_empty(), "nothing is held twice"); |
| 1395 | } |
| 1396 | |
| 1397 | /// A screen-like card: hard-edged 4-pixel bands of two flat luma values |
| 1398 | /// with a moving block over the lower half — few colours per 16x16 block |
| 1399 | /// at high variance, which is exactly what |
| 1400 | /// [`crate::encode::picture_is_screen`] separates. Used unforced, so the |
| 1401 | /// gate below runs the real detector rather than an override. |
| 1402 | fn screen_card(width: usize, height: usize, shift: usize) -> Picture { |
| 1403 | let mut picture = Picture::grey(width, height); |
| 1404 | for y in 0..height { |
| 1405 | for x in 0..width { |
| 1406 | let band = if (x / 4).is_multiple_of(2) { 40 } else { 200 }; |
| 1407 | let over = y >= height / 2 && (x + shift) % width < width / 3; |
| 1408 | picture.y[y * width + x] = if over { 128 } else { band }; |
| 1409 | } |
| 1410 | } |
| 1411 | picture |
| 1412 | } |
| 1413 | |
| 1414 | /// THE ENTRY-SURFACE GATE (lane-av1facade, extended to the pyramid on |
| 1415 | /// lane-av1pyrdef): the streaming facade — what the editor's export |
| 1416 | /// drives — codes byte for byte what [`crate::encode::encode_sequence`] |
| 1417 | /// codes, which is the path the BD gate measures. Both now drive ONE |
| 1418 | /// mini-GOP driver ([`Av1Encoder::encode_sequence_pyramid`]), so the |
| 1419 | /// identity is by construction; this pins it anyway, over both content |
| 1420 | /// classes the content gate splits: |
| 1421 | /// |
| 1422 | /// * film-like (the gate's own clip when the fixture is there, a |
| 1423 | /// multi-tone moving card otherwise): the pyramid is EFFECTIVE, the |
| 1424 | /// stream is reordered (a hidden `ALTREF` per mini-GOP), and the two |
| 1425 | /// paths' whole streams are identical; |
| 1426 | /// * screen-like: the content gate drops BOTH paths back to flat, one |
| 1427 | /// packet per picture, identical frame by frame as well as whole. |
| 1428 | /// |
| 1429 | /// Never skipped, since a skipped identity gate is the defect it is meant |
| 1430 | /// to catch. |
| 1431 | #[test] |
| 1432 | fn the_facade_codes_the_same_bytes_as_encode_sequence() { |
| 1433 | let frames = 12usize; |
| 1434 | let film = h264_clip_frames(640, 384, frames).unwrap_or_else(|| { |
| 1435 | eprintln!("no h264 clip: the facade identity gate runs on a synthetic card"); |
| 1436 | (0..frames).map(|t| test_card(64, 64, t)).collect() |
| 1437 | }); |
| 1438 | let screen: Vec<Picture> = (0..frames).map(|t| screen_card(64, 64, t)).collect(); |
| 1439 | let pyramid = Pyramid::from_env().expect("the pyramid is this build's default"); |
| 1440 | for (content, pictures, is_screen) in |
| 1441 | [("film", &film, false), ("screen", &screen, true)] |
| 1442 | { |
| 1443 | let (width, height) = (pictures[0].width, pictures[0].height); |
| 1444 | for q in [150u8, 60] { |
| 1445 | let config = EncoderConfig { |
| 1446 | width, |
| 1447 | height, |
| 1448 | base_q_idx: q, |
| 1449 | // One key frame then all inter, which is |
| 1450 | // `encode_sequence`'s only shape, and the gate's recipe. |
| 1451 | gop: frames, |
| 1452 | // `encode_sequence` writes an unspecified colour config. |
| 1453 | colour: Colour::Unspecified, |
| 1454 | tile_cols_log2: 0, |
| 1455 | tile_rows_log2: 0, |
| 1456 | }; |
| 1457 | let mut enc = Av1Encoder::with_pyramid(config, pyramid).unwrap(); |
| 1458 | let mut packets = Vec::new(); |
| 1459 | for picture in pictures { |
| 1460 | packets.extend(enc.encode_frames(picture).unwrap()); |
| 1461 | } |
| 1462 | packets.extend(enc.flush().unwrap()); |
| 1463 | assert_eq!( |
| 1464 | enc.pyramid().is_none(), |
| 1465 | is_screen, |
| 1466 | "{content} q={q}: the content gate read this clip the other way round" |
| 1467 | ); |
| 1468 | let sequence = crate::encode::encode_sequence(pictures, q, DEADZONE).unwrap(); |
| 1469 | assert_eq!( |
| 1470 | (packets.iter().map(|p| p.data.len()).sum::<usize>(), concat(&packets)), |
| 1471 | (sequence.stream.len(), sequence.stream.clone()), |
| 1472 | "{content} q={q}: the facade's stream is not the sequence path's" |
| 1473 | ); |
| 1474 | assert_eq!( |
| 1475 | sequence.frames.len(), |
| 1476 | frames, |
| 1477 | "{content} q={q}: one entry per picture, in display order" |
| 1478 | ); |
| 1479 | if is_screen { |
| 1480 | assert_eq!(packets.len(), frames, "{content} q={q}: one packet per picture"); |
| 1481 | for (i, (packet, coded)) in packets.iter().zip(&sequence.frames).enumerate() { |
| 1482 | let cropped = crate::encode::crop_encoded(coded, width, height); |
| 1483 | assert_eq!( |
| 1484 | (packet.data.len(), packet.data.clone()), |
| 1485 | (cropped.stream.len(), cropped.stream.clone()), |
| 1486 | "{content} q={q} frame {i}: the facade's bytes are not the \ |
| 1487 | sequence path's" |
| 1488 | ); |
| 1489 | } |
| 1490 | } else { |
| 1491 | assert!( |
| 1492 | packets.iter().any(|p| p.level == Level::Arf), |
| 1493 | "{content} q={q}: a non-screen stream coded no hidden frame" |
| 1494 | ); |
| 1495 | } |
| 1496 | } |
| 1497 | } |
| 1498 | } |
| 1499 | |
| 1500 | /// THE CONTENT GATE (lane-av1pyrgate): the coding pyramid is asked for by |
| 1501 | /// the caller but applied only to camera material. Over screen content |
| 1502 | /// the encoder must drop back to the flat path and code byte for byte |
| 1503 | /// what a flat encoder codes — that is what keeps the BD gate's screen |
| 1504 | /// row identical to the flat baseline — and over non-screen content the |
| 1505 | /// same request must still reorder (class `gate-blind-to-feature`: a gate |
| 1506 | /// that only checked the screen half would pass with the pyramid deleted). |
| 1507 | #[test] |
| 1508 | fn the_content_gate_keeps_screen_streams_flat() { |
| 1509 | let frames = 8usize; |
| 1510 | let pictures: Vec<Picture> = (0..frames).map(|t| test_card(64, 64, t)).collect(); |
| 1511 | let config = EncoderConfig { |
| 1512 | width: 64, |
| 1513 | height: 64, |
| 1514 | base_q_idx: 120, |
| 1515 | gop: frames, |
| 1516 | colour: Colour::Unspecified, |
| 1517 | tile_cols_log2: 0, |
| 1518 | tile_rows_log2: 0, |
| 1519 | }; |
| 1520 | crate::encode::force_screen(Some(true)); |
| 1521 | let mut flat = Av1Encoder::new(config).unwrap(); |
| 1522 | let flat_packets = encode_all(&mut flat, &pictures); |
| 1523 | let mut gated = Av1Encoder::with_pyramid(config, Pyramid::default()).unwrap(); |
| 1524 | let gated_packets = encode_all(&mut gated, &pictures); |
| 1525 | assert_eq!(gated.pyramid(), None, "the gate left a screen stream on the pyramid"); |
| 1526 | assert_eq!( |
| 1527 | concat(&gated_packets), |
| 1528 | concat(&flat_packets), |
| 1529 | "a screen stream's bytes are not the flat path's" |
| 1530 | ); |
| 1531 | crate::encode::force_screen(Some(false)); |
| 1532 | let mut kept = Av1Encoder::with_pyramid(config, Pyramid::default()).unwrap(); |
| 1533 | let kept_packets = encode_all(&mut kept, &pictures); |
| 1534 | assert_eq!(kept.pyramid(), Some(Pyramid::default()), "the gate ate a film stream"); |
| 1535 | assert!( |
| 1536 | kept_packets.iter().any(|p| p.level == Level::Arf), |
| 1537 | "a non-screen stream coded no hidden frame" |
| 1538 | ); |
| 1539 | crate::encode::force_screen(None); |
| 1540 | } |
| 1541 | |
| 1542 | /// A key frame every `gop` pictures, inter otherwise — checked against |
| 1543 | /// what the facade itself reports, and (below) against what `ffprobe` |
| 1544 | /// reads back out of the coded bytes. |
| 1545 | #[test] |
| 1546 | fn gop_cadence_is_honored() { |
| 1547 | let config = EncoderConfig { |
| 1548 | width: 64, |
| 1549 | height: 64, |
| 1550 | base_q_idx: 100, |
| 1551 | gop: 3, |
| 1552 | colour: Colour::Unspecified, |
| 1553 | tile_cols_log2: 0, |
| 1554 | tile_rows_log2: 0, |
| 1555 | }; |
| 1556 | let mut enc = Av1Encoder::new(config).unwrap(); |
| 1557 | let pictures: Vec<Picture> = (0..7).map(|t| test_card(64, 64, t)).collect(); |
| 1558 | let keys: Vec<bool> = encode_all(&mut enc, &pictures) |
| 1559 | .iter() |
| 1560 | .map(|p| p.key) |
| 1561 | .collect(); |
| 1562 | assert_eq!(keys, vec![true, false, false, true, false, false, true]); |
| 1563 | } |
| 1564 | |
| 1565 | fn ffprobe_frames(stream: &[u8]) -> Vec<(bool, u32, u32)> { |
| 1566 | let path = std::env::temp_dir().join(format!( |
| 1567 | "ec-av1-facade-probe-{}-{}.obu", |
| 1568 | std::process::id(), |
| 1569 | std::ptr::addr_of!(stream) as usize |
| 1570 | )); |
| 1571 | std::fs::write(&path, stream).expect("writing the probe stream"); |
| 1572 | let out = Command::new("ffprobe") |
| 1573 | .args([ |
| 1574 | "-v", |
| 1575 | "error", |
| 1576 | "-f", |
| 1577 | "obu", |
| 1578 | "-select_streams", |
| 1579 | "v:0", |
| 1580 | "-show_entries", |
| 1581 | "frame=key_frame,width,height", |
| 1582 | "-of", |
| 1583 | "csv=p=0", |
| 1584 | ]) |
| 1585 | .arg(&path) |
| 1586 | .output() |
| 1587 | .expect("ffprobe failed to run"); |
| 1588 | let _ = std::fs::remove_file(&path); |
| 1589 | assert!( |
| 1590 | out.status.success(), |
| 1591 | "ffprobe refused the stream: {}", |
| 1592 | String::from_utf8_lossy(&out.stderr) |
| 1593 | ); |
| 1594 | String::from_utf8_lossy(&out.stdout) |
| 1595 | .lines() |
| 1596 | .map(|line| { |
| 1597 | let mut f = line.trim().split(','); |
| 1598 | let key: u32 = f.next().unwrap().parse().unwrap(); |
| 1599 | let width: u32 = f.next().unwrap().parse().unwrap(); |
| 1600 | let height: u32 = f.next().unwrap().parse().unwrap(); |
| 1601 | (key == 1, width, height) |
| 1602 | }) |
| 1603 | .collect() |
| 1604 | } |
| 1605 | |
| 1606 | fn ffprobe_colour(stream: &[u8]) -> String { |
| 1607 | let path = std::env::temp_dir().join(format!( |
| 1608 | "ec-av1-facade-colour-probe-{}-{}.obu", |
| 1609 | std::process::id(), |
| 1610 | std::ptr::addr_of!(stream) as usize |
| 1611 | )); |
| 1612 | std::fs::write(&path, stream).expect("writing the probe stream"); |
| 1613 | let out = Command::new("ffprobe") |
| 1614 | .args([ |
| 1615 | "-v", |
| 1616 | "error", |
| 1617 | "-f", |
| 1618 | "obu", |
| 1619 | "-select_streams", |
| 1620 | "v:0", |
| 1621 | "-show_entries", |
| 1622 | "stream=color_primaries,color_transfer,color_space,color_range", |
| 1623 | "-of", |
| 1624 | "csv=p=0", |
| 1625 | ]) |
| 1626 | .arg(&path) |
| 1627 | .output() |
| 1628 | .expect("ffprobe failed to run"); |
| 1629 | let _ = std::fs::remove_file(&path); |
| 1630 | assert!( |
| 1631 | out.status.success(), |
| 1632 | "ffprobe refused the stream: {}", |
| 1633 | String::from_utf8_lossy(&out.stderr) |
| 1634 | ); |
| 1635 | String::from_utf8_lossy(&out.stdout).trim().to_string() |
| 1636 | } |
| 1637 | |
| 1638 | /// A 30-picture stream at gop 15 codes 2 key frames (pictures 0 and 15) |
| 1639 | /// and 28 inter ones, at an odd-ish (not superblock-multiple) size that |
| 1640 | /// exercises the pad/crop path -- `ffprobe`'s own `key_frame` flags and |
| 1641 | /// coded size confirm what the facade already reported. |
| 1642 | #[test] |
| 1643 | fn thirty_pictures_at_gop_fifteen_decode_to_two_key_frames() { |
| 1644 | if !have_ffmpeg() { |
| 1645 | eprintln!("SKIP thirty_pictures_at_gop_fifteen_decode_to_two_key_frames: no ffmpeg"); |
| 1646 | return; |
| 1647 | } |
| 1648 | let (width, height) = (96usize, 96usize); |
| 1649 | let config = EncoderConfig { |
| 1650 | width, |
| 1651 | height, |
| 1652 | base_q_idx: 120, |
| 1653 | gop: 15, |
| 1654 | colour: Colour::Bt709Limited, |
| 1655 | tile_cols_log2: 0, |
| 1656 | tile_rows_log2: 0, |
| 1657 | }; |
| 1658 | let mut enc = Av1Encoder::new(config).unwrap(); |
| 1659 | assert_eq!(enc.display_size(), (width, height)); |
| 1660 | let (coded_w, coded_h) = enc.coded_size(); |
| 1661 | assert_eq!( |
| 1662 | (coded_w, coded_h), |
| 1663 | ( |
| 1664 | width.next_multiple_of(SUPERBLOCK), |
| 1665 | height.next_multiple_of(SUPERBLOCK) |
| 1666 | ) |
| 1667 | ); |
| 1668 | |
| 1669 | let pictures: Vec<Picture> = (0..30).map(|t| test_card(width, height, t)).collect(); |
| 1670 | let packets: Vec<Packet> = encode_all(&mut enc, &pictures); |
| 1671 | let expect_key: Vec<bool> = (0..30).map(|t| t % 15 == 0).collect(); |
| 1672 | assert_eq!( |
| 1673 | packets.iter().map(|p| p.key).collect::<Vec<_>>(), |
| 1674 | expect_key, |
| 1675 | "facade's own key/inter flags" |
| 1676 | ); |
| 1677 | |
| 1678 | let stream = concat(&packets); |
| 1679 | let frames = ffprobe_frames(&stream); |
| 1680 | assert_eq!(frames.len(), 30, "ffprobe frame count"); |
| 1681 | for (t, (key, w, h)) in frames.iter().enumerate() { |
| 1682 | assert_eq!(*key, expect_key[t], "picture {t}: ffprobe key_frame flag"); |
| 1683 | assert_eq!( |
| 1684 | (*w, *h), |
| 1685 | (width as u32, height as u32), |
| 1686 | "picture {t}: ffprobe reports the true (display) size, not the padded coded one" |
| 1687 | ); |
| 1688 | } |
| 1689 | } |
| 1690 | |
| 1691 | /// The configured colour properties are what `ffprobe` reports back, |
| 1692 | /// spec 5.5.2's CICP triple plus range -- BT.709 limited here, since it |
| 1693 | /// is the default a player assumes and the one this test would silently |
| 1694 | /// pass without wiring for (`ffprobe` reports "unknown" for the |
| 1695 | /// hardcoded "unspecified" this crate wrote before the facade existed, |
| 1696 | /// which is a visibly different string). |
| 1697 | #[test] |
| 1698 | fn bt709_limited_colour_is_reported_by_ffprobe() { |
| 1699 | if !have_ffmpeg() { |
| 1700 | eprintln!("SKIP bt709_limited_colour_is_reported_by_ffprobe: no ffmpeg"); |
| 1701 | return; |
| 1702 | } |
| 1703 | let config = EncoderConfig { |
| 1704 | width: 64, |
| 1705 | height: 64, |
| 1706 | base_q_idx: 100, |
| 1707 | gop: 4, |
| 1708 | colour: Colour::Bt709Limited, |
| 1709 | tile_cols_log2: 0, |
| 1710 | tile_rows_log2: 0, |
| 1711 | }; |
| 1712 | let mut enc = Av1Encoder::new(config).unwrap(); |
| 1713 | let packets = encode_all(&mut enc, &[test_card(64, 64, 0)]); |
| 1714 | let colour = ffprobe_colour(&packets[0].data); |
| 1715 | assert_eq!(colour, "tv,bt709,bt709,bt709", "ffprobe colour fields"); |
| 1716 | } |
| 1717 | |
| 1718 | /// The same, for BT.601: a different set of CICP integers must produce a |
| 1719 | /// different string, or the wiring could be a no-op that happens to read |
| 1720 | /// as BT.709 for every input. |
| 1721 | #[test] |
| 1722 | fn bt601_limited_colour_is_reported_by_ffprobe() { |
| 1723 | if !have_ffmpeg() { |
| 1724 | eprintln!("SKIP bt601_limited_colour_is_reported_by_ffprobe: no ffmpeg"); |
| 1725 | return; |
| 1726 | } |
| 1727 | let config = EncoderConfig { |
| 1728 | width: 64, |
| 1729 | height: 64, |
| 1730 | base_q_idx: 100, |
| 1731 | gop: 4, |
| 1732 | colour: Colour::Bt601Limited, |
| 1733 | tile_cols_log2: 0, |
| 1734 | tile_rows_log2: 0, |
| 1735 | }; |
| 1736 | let mut enc = Av1Encoder::new(config).unwrap(); |
| 1737 | let packets = encode_all(&mut enc, &[test_card(64, 64, 0)]); |
| 1738 | let colour = ffprobe_colour(&packets[0].data); |
| 1739 | assert_eq!( |
| 1740 | colour, "tv,smpte170m,smpte170m,smpte170m", |
| 1741 | "ffprobe colour fields" |
| 1742 | ); |
| 1743 | } |
| 1744 | |
| 1745 | /// A frame whose size does not match the encoder's configured geometry |
| 1746 | /// is refused by name. |
| 1747 | #[test] |
| 1748 | fn geometry_mismatch_is_refused() { |
| 1749 | let config = EncoderConfig { |
| 1750 | width: 64, |
| 1751 | height: 64, |
| 1752 | base_q_idx: 100, |
| 1753 | gop: 4, |
| 1754 | colour: Colour::Bt709Limited, |
| 1755 | tile_cols_log2: 0, |
| 1756 | tile_rows_log2: 0, |
| 1757 | }; |
| 1758 | let mut enc = Av1Encoder::new(config).unwrap(); |
| 1759 | let err = enc.encode(&Picture::grey(32, 32)).unwrap_err(); |
| 1760 | assert!(err.to_string().contains("64x64"), "{err}"); |
| 1761 | } |
| 1762 | |
| 1763 | /// `gop == 0` is refused at construction, not the first `encode()` call. |
| 1764 | #[test] |
| 1765 | fn zero_gop_is_refused() { |
| 1766 | let config = EncoderConfig { |
| 1767 | width: 64, |
| 1768 | height: 64, |
| 1769 | base_q_idx: 100, |
| 1770 | gop: 0, |
| 1771 | colour: Colour::Bt709Limited, |
| 1772 | tile_cols_log2: 0, |
| 1773 | tile_rows_log2: 0, |
| 1774 | }; |
| 1775 | let err = Av1Encoder::new(config).unwrap_err(); |
| 1776 | assert!(err.to_string().contains("gop"), "{err}"); |
| 1777 | } |
| 1778 | |
| 1779 | /// The 12-frame real clip `real_clip_encodes_within_its_quality_and_size_budget` |
| 1780 | /// already gates on at `q=100` (`crates/ec-av1/src/encode.rs`), decoded down |
| 1781 | /// to this facade's own input size, and re-coded through the facade so the |
| 1782 | /// rate-target surface is exercised at the entry point a caller actually |
| 1783 | /// drives. |
| 1784 | fn h264_clip_frames(width: usize, height: usize, frames: usize) -> Option<Vec<Picture>> { |
| 1785 | if !have_ffmpeg() { |
| 1786 | return None; |
| 1787 | } |
| 1788 | // lane-av1speed3: the wall tables below are read on REAL film as |
| 1789 | // well as on the colour-bar fixture (`bars` vs `film` in the BD |
| 1790 | // gate's own vocabulary), and the film crop lives outside the repo -- |
| 1791 | // `EC_AV1_WALL_CLIP` names it. Unset everywhere else, so every other |
| 1792 | // caller still gets the fixture. |
| 1793 | let clip = match std::env::var("EC_AV1_WALL_CLIP") { |
| 1794 | Ok(p) => std::path::PathBuf::from(p), |
| 1795 | Err(_) => std::path::Path::new(env!("CARGO_MANIFEST_DIR")) |
| 1796 | .join("../../fixtures/video/h264-1080p-23.976-8bit.mp4"), |
| 1797 | }; |
| 1798 | if !clip.exists() { |
| 1799 | return None; |
| 1800 | } |
| 1801 | let out = Command::new("ffmpeg") |
| 1802 | .args(["-v", "error", "-i", clip.to_str().unwrap()]) |
| 1803 | .args(["-frames:v", &frames.to_string()]) |
| 1804 | .args(["-vf", &format!("scale={width}:{height}")]) |
| 1805 | .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"]) |
| 1806 | .output() |
| 1807 | .expect("ffmpeg failed to run"); |
| 1808 | assert!( |
| 1809 | out.status.success(), |
| 1810 | "{}", |
| 1811 | String::from_utf8_lossy(&out.stderr) |
| 1812 | ); |
| 1813 | let (luma, chroma) = (width * height, width * height / 4); |
| 1814 | let frame_len = luma + 2 * chroma; |
| 1815 | assert_eq!( |
| 1816 | out.stdout.len(), |
| 1817 | frame_len * frames, |
| 1818 | "expected {frames} 4:2:0 frames" |
| 1819 | ); |
| 1820 | Some( |
| 1821 | (0..frames) |
| 1822 | .map(|i| { |
| 1823 | let bytes = &out.stdout[i * frame_len..][..frame_len]; |
| 1824 | Picture { |
| 1825 | width, |
| 1826 | height, |
| 1827 | y: bytes[..luma].iter().map(|&v| u16::from(v)).collect(), |
| 1828 | u: bytes[luma..luma + chroma].iter().map(|&v| u16::from(v)).collect(), |
| 1829 | v: bytes[luma + chroma..].iter().map(|&v| u16::from(v)).collect(), |
| 1830 | } |
| 1831 | }) |
| 1832 | .collect(), |
| 1833 | ) |
| 1834 | } |
| 1835 | |
| 1836 | /// [`RateTarget::BytesPerFrame`] on a real, 24-frame clip lands its total |
| 1837 | /// coded size within ±20% of `frames * target` once the first few |
| 1838 | /// frames' settling has been discarded (the key frame's own reference |
| 1839 | /// state and the controller's first couple of steps). |
| 1840 | #[test] |
| 1841 | fn bytes_per_frame_target_settles_within_20_percent() { |
| 1842 | let Some(pictures) = h264_clip_frames(640, 384, 24) else { |
| 1843 | eprintln!("SKIP bytes_per_frame_target_settles_within_20_percent: no ffmpeg/fixture"); |
| 1844 | return; |
| 1845 | }; |
| 1846 | let target_bytes = 4_000u32; |
| 1847 | let config = EncoderConfig { |
| 1848 | width: 640, |
| 1849 | height: 384, |
| 1850 | base_q_idx: 100, |
| 1851 | gop: 24, |
| 1852 | colour: Colour::Bt709Limited, |
| 1853 | tile_cols_log2: 0, |
| 1854 | tile_rows_log2: 0, |
| 1855 | }; |
| 1856 | let mut enc = |
| 1857 | Av1Encoder::with_rate_target(config, RateTarget::BytesPerFrame(target_bytes)).unwrap(); |
| 1858 | let sizes: Vec<usize> = encode_all(&mut enc, &pictures) |
| 1859 | .iter() |
| 1860 | .map(|p| p.data.len()) |
| 1861 | .collect(); |
| 1862 | // Discard the key frame (always far larger than an inter target) and |
| 1863 | // the next 4 inter frames the loop needs to step toward it. |
| 1864 | let settled = &sizes[5..]; |
| 1865 | let mean = settled.iter().sum::<usize>() as f64 / settled.len() as f64; |
| 1866 | let low = f64::from(target_bytes) * 0.8; |
| 1867 | let high = f64::from(target_bytes) * 1.2; |
| 1868 | assert!( |
| 1869 | mean >= low && mean <= high, |
| 1870 | "settled mean {mean:.0} bytes/frame outside ±20% of {target_bytes} ({low:.0}..{high:.0}); sizes={sizes:?}" |
| 1871 | ); |
| 1872 | } |
| 1873 | |
| 1874 | /// [`RateTarget::Bitrate`] lands the achieved bitrate within ±10% of the |
| 1875 | /// target over 48 frames of a real clip, flat and under a pyramid alike. |
| 1876 | /// This is the accuracy claim of the target-bitrate mode: no two-pass, no |
| 1877 | /// lookahead, just each frame's size predicted from the previous frame of |
| 1878 | /// its own level and one clamped proportional step. |
| 1879 | #[test] |
| 1880 | fn bitrate_target_lands_within_10_percent_over_48_frames() { |
| 1881 | let (width, height, frames) = (640usize, 384usize, 48usize); |
| 1882 | let Some(pictures) = h264_clip_frames(width, height, frames) else { |
| 1883 | eprintln!("SKIP bitrate_target_lands_within_10_percent_over_48_frames: no ffmpeg/fixture"); |
| 1884 | return; |
| 1885 | }; |
| 1886 | let fps = 24.0; |
| 1887 | for bits_per_second in [768_000u32, 1_536_000] { |
| 1888 | let config = EncoderConfig { |
| 1889 | width, |
| 1890 | height, |
| 1891 | base_q_idx: 100, |
| 1892 | gop: frames, |
| 1893 | colour: Colour::Bt709Limited, |
| 1894 | tile_cols_log2: 0, |
| 1895 | tile_rows_log2: 0, |
| 1896 | }; |
| 1897 | let rate = RateTarget::Bitrate { |
| 1898 | bits_per_second, |
| 1899 | frames_per_second: fps, |
| 1900 | }; |
| 1901 | for pyramid in [None, Some(Pyramid::default())] { |
| 1902 | let mut enc = match pyramid { |
| 1903 | None => Av1Encoder::with_rate_target(config, rate).unwrap(), |
| 1904 | Some(p) => Av1Encoder::with_pyramid_and_rate_target(config, p, rate).unwrap(), |
| 1905 | }; |
| 1906 | let mut coded = 0usize; |
| 1907 | for picture in &pictures { |
| 1908 | for packet in enc.encode_frames(picture).unwrap() { |
| 1909 | coded += packet.data.len(); |
| 1910 | } |
| 1911 | } |
| 1912 | for packet in enc.flush().unwrap() { |
| 1913 | coded += packet.data.len(); |
| 1914 | } |
| 1915 | let seconds = frames as f64 / fps; |
| 1916 | let achieved = coded as f64 * 8.0 / seconds; |
| 1917 | let error = achieved / f64::from(bits_per_second) - 1.0; |
| 1918 | eprintln!( |
| 1919 | "bitrate {bits_per_second} bps, pyramid {}: {coded} bytes over {seconds:.2}s \ |
| 1920 | = {achieved:.0} bps ({:+.1}%)", |
| 1921 | pyramid.is_some(), |
| 1922 | 100.0 * error, |
| 1923 | ); |
| 1924 | assert!( |
| 1925 | error.abs() <= 0.10, |
| 1926 | "achieved {achieved:.0} bps is {:+.1}% off the {bits_per_second} bps target \ |
| 1927 | (pyramid {})", |
| 1928 | 100.0 * error, |
| 1929 | pyramid.is_some(), |
| 1930 | ); |
| 1931 | } |
| 1932 | } |
| 1933 | } |
| 1934 | |
| 1935 | /// The `BytesPerFrame` controller's own windup bound: no frame's coded |
| 1936 | /// `base_q_idx` step exceeds [`RateLoop::STEP_CLAMP`], across a real |
| 1937 | /// clip's full range of content (so a scene cut can't be the one frame |
| 1938 | /// that breaks the bound). |
| 1939 | /// |
| 1940 | /// The SEEDING frame is the one exemption ([`RateLoop::update`]): a slot |
| 1941 | /// that has coded nothing yet is still sitting on the caller's |
| 1942 | /// `base_q_idx` guess, and its first step is the acquisition jump, not |
| 1943 | /// windup. Exactly one frame is exempt -- the loop below asserts the |
| 1944 | /// bound on every frame after it, which is where a scene cut would |
| 1945 | /// break it. |
| 1946 | #[test] |
| 1947 | fn bytes_per_frame_controller_never_oscillates_past_its_clamp() { |
| 1948 | let Some(pictures) = h264_clip_frames(640, 384, 24) else { |
| 1949 | eprintln!( |
| 1950 | "SKIP bytes_per_frame_controller_never_oscillates_past_its_clamp: no ffmpeg/fixture" |
| 1951 | ); |
| 1952 | return; |
| 1953 | }; |
| 1954 | let config = EncoderConfig { |
| 1955 | width: 640, |
| 1956 | height: 384, |
| 1957 | base_q_idx: 100, |
| 1958 | gop: 24, |
| 1959 | colour: Colour::Bt709Limited, |
| 1960 | tile_cols_log2: 0, |
| 1961 | tile_rows_log2: 0, |
| 1962 | }; |
| 1963 | let mut enc = |
| 1964 | Av1Encoder::with_rate_target(config, RateTarget::BytesPerFrame(4_000)).unwrap(); |
| 1965 | let mut prev_q = enc.rate_loop.as_ref().unwrap().q_idx(Level::Leaf); |
| 1966 | // The first frame this encoder EMITS is several `encode_frames` calls |
| 1967 | // in (the lookahead queue holds the earlier ones), so the seeding |
| 1968 | // step is not frame zero -- it is the first frame `q` moves at all. |
| 1969 | let mut seeded = false; |
| 1970 | let mut seed_frame = None; |
| 1971 | for (frame, picture) in pictures.iter().enumerate() { |
| 1972 | enc.encode_frames(picture).unwrap(); |
| 1973 | let q = enc.rate_loop.as_ref().unwrap().q_idx(Level::Leaf); |
| 1974 | let step = (i32::from(q) - i32::from(prev_q)).abs(); |
| 1975 | if step > 0 && !seeded { |
| 1976 | seeded = true; |
| 1977 | seed_frame = Some(frame); |
| 1978 | } else { |
| 1979 | assert!( |
| 1980 | f64::from(step) <= RateLoop::STEP_CLAMP + 1.0, // +1 for u8 rounding |
| 1981 | "frame {frame}: q stepped from {prev_q} to {q}, past the {} clamp", |
| 1982 | RateLoop::STEP_CLAMP |
| 1983 | ); |
| 1984 | } |
| 1985 | prev_q = q; |
| 1986 | } |
| 1987 | assert!( |
| 1988 | seed_frame.is_some(), |
| 1989 | "the controller never steered at all -- the bound below is vacuous" |
| 1990 | ); |
| 1991 | } |
| 1992 | |
| 1993 | fn psnr(a: &[u16], b: &[u16]) -> f64 { |
| 1994 | let squared: f64 = a |
| 1995 | .iter() |
| 1996 | .zip(b) |
| 1997 | .map(|(&x, &y)| { |
| 1998 | let d = f64::from(x) - f64::from(y); |
| 1999 | d * d |
| 2000 | }) |
| 2001 | .sum(); |
| 2002 | if squared == 0.0 { |
| 2003 | return f64::INFINITY; |
| 2004 | } |
| 2005 | 10.0 * (255.0 * 255.0 * a.len() as f64 / squared).log10() |
| 2006 | } |
| 2007 | |
| 2008 | /// Decodes an OBU stream back to raw luma planes via `ffmpeg`/dav1d, one |
| 2009 | /// entry per coded frame, in order — this facade's own equivalent of |
| 2010 | /// `encode::tests::ffmpeg_decode_sequence`, needed here too since a |
| 2011 | /// PSNR check needs the decoded pixels, not just the coded byte count. |
| 2012 | fn ffmpeg_decode_luma(stream: &[u8], width: usize, height: usize) -> Vec<Vec<u8>> { |
| 2013 | let path = std::env::temp_dir().join(format!( |
| 2014 | "ec-av1-facade-rate-decode-{}-{}.obu", |
| 2015 | std::process::id(), |
| 2016 | std::ptr::addr_of!(stream) as usize |
| 2017 | )); |
| 2018 | std::fs::write(&path, stream).expect("writing the decode probe stream"); |
| 2019 | let out = Command::new("ffmpeg") |
| 2020 | .args(["-v", "error", "-f", "obu", "-i"]) |
| 2021 | .arg(&path) |
| 2022 | .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"]) |
| 2023 | .output() |
| 2024 | .expect("ffmpeg failed to run"); |
| 2025 | let _ = std::fs::remove_file(&path); |
| 2026 | assert!( |
| 2027 | out.status.success(), |
| 2028 | "{}", |
| 2029 | String::from_utf8_lossy(&out.stderr) |
| 2030 | ); |
| 2031 | let (luma, chroma) = (width * height, width * height / 4); |
| 2032 | let frame_len = luma + 2 * chroma; |
| 2033 | out.stdout |
| 2034 | .chunks_exact(frame_len) |
| 2035 | .map(|f| f[..luma].to_vec()) |
| 2036 | .collect() |
| 2037 | } |
| 2038 | |
| 2039 | /// A pyramid stream reorders pictures: the hidden `ALTREF` of each |
| 2040 | /// mini-GOP is coded before the leaves that precede it in display order, |
| 2041 | /// and a `show_existing_frame` header puts it back. This pins the shape |
| 2042 | /// (one packet per source picture plus one `show_existing_frame` per |
| 2043 | /// group, `dts` monotone, `order` NOT monotone) and then decodes the |
| 2044 | /// whole stream through OUR decoder and through ffmpeg/dav1d and requires |
| 2045 | /// the two display-order outputs to agree sample for sample — the |
| 2046 | /// [[gate-blind-to-hidden-frames]] check: a hidden frame that is never |
| 2047 | /// output, or output twice, or output in the wrong position, changes the |
| 2048 | /// display-order list and fails here. |
| 2049 | #[test] |
| 2050 | fn a_pyramid_stream_decodes_in_display_order_through_both_decoders() { |
| 2051 | let (width, height) = (128usize, 128usize); |
| 2052 | let config = EncoderConfig { |
| 2053 | width, |
| 2054 | height, |
| 2055 | base_q_idx: 120, |
| 2056 | gop: 32, |
| 2057 | colour: Colour::Bt709Limited, |
| 2058 | tile_cols_log2: 0, |
| 2059 | tile_rows_log2: 0, |
| 2060 | }; |
| 2061 | let pyramid = Pyramid { |
| 2062 | mini_gop: 4, |
| 2063 | ..Pyramid::default() |
| 2064 | }; |
| 2065 | // The content gate ([`Av1Encoder::encode_frames`]) would drop a |
| 2066 | // screen-content stream to the flat path, and a synthetic test card |
| 2067 | // is exactly the few-colour picture the detector fires on: this gate |
| 2068 | // is about the reordering, so it asks for camera content explicitly. |
| 2069 | crate::encode::force_screen(Some(false)); |
| 2070 | let mut enc = Av1Encoder::with_pyramid(config, pyramid).unwrap(); |
| 2071 | let sources: Vec<Picture> = (0..9).map(|t| test_card(width, height, t * 3)).collect(); |
| 2072 | let _ = crate::encode::take_ref_frame_hits(); |
| 2073 | let mut packets = Vec::new(); |
| 2074 | for picture in &sources { |
| 2075 | packets.extend(enc.encode_frames(picture).unwrap()); |
| 2076 | } |
| 2077 | packets.extend(enc.flush().unwrap()); |
| 2078 | |
| 2079 | // Shape: every source picture is coded exactly once, and each closed |
| 2080 | // group adds one `show_existing_frame` packet. |
| 2081 | let coded: Vec<u64> = packets |
| 2082 | .iter() |
| 2083 | .filter(|p| p.level != Level::ShowExisting) |
| 2084 | .map(|p| p.order) |
| 2085 | .collect(); |
| 2086 | let mut sorted = coded.clone(); |
| 2087 | sorted.sort_unstable(); |
| 2088 | assert_eq!(sorted, (0..9).collect::<Vec<u64>>(), "one packet per picture"); |
| 2089 | assert_ne!(coded, sorted, "the pyramid never reordered anything"); |
| 2090 | let shown = packets.iter().filter(|p| p.level == Level::ShowExisting).count(); |
| 2091 | assert_eq!(shown, 2, "one show_existing_frame per closed mini-GOP"); |
| 2092 | for (i, p) in packets.iter().enumerate() { |
| 2093 | assert_eq!(p.dts, i as u64, "packet {i}: dts is the coding position"); |
| 2094 | } |
| 2095 | let hist = |l: Level| packets.iter().filter(|p| p.level == l).count(); |
| 2096 | eprintln!( |
| 2097 | "pyramid levels: key {} arf {} leaf {} show_existing {}", |
| 2098 | hist(Level::Key), |
| 2099 | hist(Level::Arf), |
| 2100 | hist(Level::Leaf), |
| 2101 | hist(Level::ShowExisting), |
| 2102 | ); |
| 2103 | assert_eq!(hist(Level::Arf), 2, "two hidden frames"); |
| 2104 | let refs = crate::encode::take_ref_frame_hits(); |
| 2105 | eprintln!( |
| 2106 | "blocks per reference: LAST {} GOLDEN {} ALTREF {}", |
| 2107 | refs[crate::mvstack::LAST_FRAME as usize], |
| 2108 | refs[crate::mvstack::GOLDEN_FRAME as usize], |
| 2109 | refs[crate::mvstack::ALTREF_FRAME as usize], |
| 2110 | ); |
| 2111 | // [[gate-blind-to-feature]]: the whole point of the hidden frame is |
| 2112 | // that the leaves predict BACKWARD off it, which is also the only |
| 2113 | // thing that exercises `ref_frame_sign_bias` in the MV stack. A green |
| 2114 | // round trip in which `ALTREF_FRAME` never won a block would prove |
| 2115 | // only that a hidden frame can be written and re-output. |
| 2116 | assert!( |
| 2117 | refs[crate::mvstack::ALTREF_FRAME as usize] > 0, |
| 2118 | "no block predicted off the hidden ALTREF" |
| 2119 | ); |
| 2120 | |
| 2121 | let stream = concat(&packets); |
| 2122 | let ours = crate::stream::decode_stream(&stream).expect("our decoder"); |
| 2123 | assert_eq!(ours.len(), sources.len(), "our decoder's display-order count"); |
| 2124 | if !have_ffmpeg() { |
| 2125 | eprintln!("SKIP the ffmpeg half of the pyramid round trip: no ffmpeg"); |
| 2126 | return; |
| 2127 | } |
| 2128 | let theirs = ffmpeg_decode_luma(&stream, width, height); |
| 2129 | assert_eq!(theirs.len(), sources.len(), "ffmpeg's display-order count"); |
| 2130 | for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() { |
| 2131 | let got: Vec<u8> = a.y.iter().map(|&v| v as u8).collect(); |
| 2132 | assert_eq!(got.len(), b.len(), "frame {i}: luma size"); |
| 2133 | if let Some(at) = got.iter().zip(b).position(|(x, y)| x != y) { |
| 2134 | panic!( |
| 2135 | "display frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}", |
| 2136 | at % width, |
| 2137 | at / width, |
| 2138 | got[at], |
| 2139 | b[at], |
| 2140 | ); |
| 2141 | } |
| 2142 | } |
| 2143 | } |
| 2144 | |
| 2145 | /// Every tile layout this encoder can write decodes SAMPLE-EXACT |
| 2146 | /// through both decoders -- ours and ffmpeg's -- and the frames really |
| 2147 | /// carry the tiles the header claims (the OBU parser locates one payload |
| 2148 | /// per tile, so a stream that quietly stayed single-tile fails here |
| 2149 | /// rather than passing on a green round trip). |
| 2150 | /// |
| 2151 | /// The bytes are what the gate is on: an encoder that clipped its |
| 2152 | /// neighbour availability wrong writes a stream whose two decoders agree |
| 2153 | /// with each other and disagree with nothing -- so the ffmpeg half is |
| 2154 | /// the one that catches a tile boundary the writer respected and the |
| 2155 | /// spec does not, and the parser half catches the reverse. |
| 2156 | #[test] |
| 2157 | fn every_tile_layout_decodes_sample_exact_through_both_decoders() { |
| 2158 | let (width, height) = (640usize, 384usize); |
| 2159 | let sources: Vec<Picture> = (0..4).map(|t| test_card(width, height, t * 3)).collect(); |
| 2160 | let mut sizes = Vec::new(); |
| 2161 | for (cols_log2, rows_log2) in [(0u32, 0u32), (1, 0), (0, 1), (1, 1), (2, 1)] { |
| 2162 | let config = EncoderConfig { |
| 2163 | width, |
| 2164 | height, |
| 2165 | base_q_idx: 120, |
| 2166 | gop: 4, |
| 2167 | colour: Colour::Bt709Limited, |
| 2168 | tile_cols_log2: cols_log2, |
| 2169 | tile_rows_log2: rows_log2, |
| 2170 | }; |
| 2171 | let layout = format!("{}x{} tiles", 1 << cols_log2, 1 << rows_log2); |
| 2172 | let mut enc = Av1Encoder::new(config).unwrap(); |
| 2173 | let mut stream = Vec::new(); |
| 2174 | for packet in encode_all(&mut enc, &sources) { |
| 2175 | stream.extend_from_slice(&packet.data); |
| 2176 | } |
| 2177 | sizes.push((layout.clone(), stream.len())); |
| 2178 | |
| 2179 | // The frames carry the tiles their headers claim. |
| 2180 | let mut parser = ec_av1_syntax::Av1Parser::new(); |
| 2181 | let mut frames = 0usize; |
| 2182 | let mut offset = 0usize; |
| 2183 | while offset < stream.len() { |
| 2184 | let obus = parser.parse_temporal_unit(&stream[offset..]).unwrap(); |
| 2185 | let unit: usize = obus.iter().map(|o| o.total_size).sum(); |
| 2186 | for obu in &obus { |
| 2187 | if let ec_av1_syntax::ObuKind::Frame(parsed, tiles) = &obu.kind { |
| 2188 | assert_eq!( |
| 2189 | (parsed.tile_info.cols, parsed.tile_info.rows), |
| 2190 | (1 << cols_log2, 1 << rows_log2), |
| 2191 | "{layout}: the header's own tile grid" |
| 2192 | ); |
| 2193 | assert_eq!( |
| 2194 | tiles.len(), |
| 2195 | 1 << (cols_log2 + rows_log2), |
| 2196 | "{layout}: tile payloads located in the tile group" |
| 2197 | ); |
| 2198 | frames += 1; |
| 2199 | } |
| 2200 | } |
| 2201 | offset += unit; |
| 2202 | } |
| 2203 | assert_eq!(frames, sources.len(), "{layout}: coded frames"); |
| 2204 | |
| 2205 | let ours = crate::stream::decode_stream(&stream).expect("our decoder"); |
| 2206 | assert_eq!(ours.len(), sources.len(), "{layout}: our decoder's frames"); |
| 2207 | if !have_ffmpeg() { |
| 2208 | eprintln!("SKIP the ffmpeg half of {layout}: no ffmpeg"); |
| 2209 | continue; |
| 2210 | } |
| 2211 | let theirs = ffmpeg_decode_luma(&stream, width, height); |
| 2212 | assert_eq!(theirs.len(), sources.len(), "{layout}: ffmpeg's frames"); |
| 2213 | for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() { |
| 2214 | let got: Vec<u8> = a.y.iter().map(|&v| v as u8).collect(); |
| 2215 | assert_eq!(got.len(), b.len(), "{layout} frame {i}: luma size"); |
| 2216 | if let Some(at) = got.iter().zip(b).position(|(x, y)| x != y) { |
| 2217 | panic!( |
| 2218 | "{layout} frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}", |
| 2219 | at % width, |
| 2220 | at / width, |
| 2221 | got[at], |
| 2222 | b[at], |
| 2223 | ); |
| 2224 | } |
| 2225 | } |
| 2226 | } |
| 2227 | let base = sizes[0].1 as f64; |
| 2228 | for (layout, bytes) in &sizes { |
| 2229 | eprintln!( |
| 2230 | "{layout}: {bytes} bytes ({:+.2}% vs one tile)", |
| 2231 | (*bytes as f64 / base - 1.0) * 100.0 |
| 2232 | ); |
| 2233 | } |
| 2234 | } |
| 2235 | |
| 2236 | /// What tiles and tile threads are worth at the size the editor exports |
| 2237 | /// at: 1920x1080, eight real pictures, two passes per cell (ABAB), wall |
| 2238 | /// per cell. Ignored by default (minutes). |
| 2239 | #[test] |
| 2240 | #[ignore = "1080p wall table: minutes, run it with --ignored"] |
| 2241 | fn tile_wall_table_at_1080p() { |
| 2242 | let _gate_lock = crate::stream::tests::lock_gate_counters(); |
| 2243 | let (width, height) = (1920usize, 1080usize); |
| 2244 | let Some(sources) = h264_clip_frames(width, height, 8) else { |
| 2245 | eprintln!("SKIP tile_wall_table_at_1080p: no fixture"); |
| 2246 | return; |
| 2247 | }; |
| 2248 | let layouts = [(0u32, 0u32), (1, 0), (1, 1), (2, 1)]; |
| 2249 | let threadings = [1usize, 2, 4, 8]; |
| 2250 | let mut table: Vec<(String, usize, f64, usize)> = Vec::new(); |
| 2251 | for pass in 0..2 { |
| 2252 | for &(cols_log2, rows_log2) in &layouts { |
| 2253 | for &threads in &threadings { |
| 2254 | crate::par::set_tile_threads(threads); |
| 2255 | let config = EncoderConfig { |
| 2256 | width, |
| 2257 | height, |
| 2258 | base_q_idx: 120, |
| 2259 | gop: 8, |
| 2260 | colour: Colour::Bt709Limited, |
| 2261 | tile_cols_log2: cols_log2, |
| 2262 | tile_rows_log2: rows_log2, |
| 2263 | }; |
| 2264 | let mut enc = Av1Encoder::new(config).unwrap(); |
| 2265 | let start = std::time::Instant::now(); |
| 2266 | let mut bytes = 0usize; |
| 2267 | for packet in encode_all(&mut enc, &sources) { |
| 2268 | bytes += packet.data.len(); |
| 2269 | } |
| 2270 | let wall = start.elapsed().as_secs_f64(); |
| 2271 | let name = format!("{}x{}", 1 << cols_log2, 1 << rows_log2); |
| 2272 | match table.iter_mut().find(|r| r.0 == name && r.1 == threads) { |
| 2273 | Some(row) => row.2 = row.2.min(wall), |
| 2274 | None => table.push((name, threads, wall, bytes)), |
| 2275 | } |
| 2276 | let _ = pass; |
| 2277 | } |
| 2278 | } |
| 2279 | } |
| 2280 | crate::par::set_tile_threads(1); |
| 2281 | eprintln!("| tiles | threads | wall (s, best of 2) | bytes |"); |
| 2282 | for (name, threads, wall, bytes) in &table { |
| 2283 | eprintln!("| {name} | {threads} | {wall:.2} | {bytes} |"); |
| 2284 | } |
| 2285 | } |
| 2286 | |
| 2287 | /// The tiles of a frame are entropy-independent, so the bytes must not |
| 2288 | /// depend on how many workers wrote them: the same stream at one tile |
| 2289 | /// thread and at four, per layout. |
| 2290 | #[test] |
| 2291 | fn tile_bytes_do_not_depend_on_the_thread_count() { |
| 2292 | let _gate_lock = crate::stream::tests::lock_gate_counters(); |
| 2293 | let (width, height) = (320usize, 192usize); |
| 2294 | let sources: Vec<Picture> = (0..3).map(|t| test_card(width, height, t * 3)).collect(); |
| 2295 | let coded = |threads: usize, cols_log2: u32, rows_log2: u32| { |
| 2296 | crate::par::set_tile_threads(threads); |
| 2297 | let config = EncoderConfig { |
| 2298 | width, |
| 2299 | height, |
| 2300 | base_q_idx: 120, |
| 2301 | gop: 3, |
| 2302 | colour: Colour::Bt709Limited, |
| 2303 | tile_cols_log2: cols_log2, |
| 2304 | tile_rows_log2: rows_log2, |
| 2305 | }; |
| 2306 | let mut enc = Av1Encoder::new(config).unwrap(); |
| 2307 | let mut stream = Vec::new(); |
| 2308 | for packet in encode_all(&mut enc, &sources) { |
| 2309 | stream.extend_from_slice(&packet.data); |
| 2310 | } |
| 2311 | stream |
| 2312 | }; |
| 2313 | for (cols_log2, rows_log2) in [(1u32, 0u32), (0, 1), (1, 1), (2, 1)] { |
| 2314 | let one = coded(1, cols_log2, rows_log2); |
| 2315 | let four = coded(4, cols_log2, rows_log2); |
| 2316 | assert_eq!( |
| 2317 | one, |
| 2318 | four, |
| 2319 | "{}x{} tiles: {} bytes at one thread, {} at four", |
| 2320 | 1 << cols_log2, |
| 2321 | 1 << rows_log2, |
| 2322 | one.len(), |
| 2323 | four.len() |
| 2324 | ); |
| 2325 | } |
| 2326 | crate::par::set_tile_threads(1); |
| 2327 | } |
| 2328 | |
| 2329 | /// What the per-tile search (lane-av1tsearch) is worth in wall and in |
| 2330 | /// frames per second at the editor's own export sizes: every tile layout |
| 2331 | /// crossed with every tile-thread count, plus librav1e at the matching |
| 2332 | /// `tile_cols`/`tile_rows`/`threads` as the reference point. Two passes |
| 2333 | /// over the whole table (A,B,A,B... rather than AA,BB) with the best of |
| 2334 | /// the two kept, so a thermal drift cannot order the rows. |
| 2335 | /// |
| 2336 | /// Measurement, not a pass/fail gate: it asserts only that every cell |
| 2337 | /// produced a stream. |
| 2338 | #[test] |
| 2339 | #[ignore = "wall measurement: minutes, run it with --ignored --nocapture"] |
| 2340 | fn tile_search_wall_1080p() { |
| 2341 | tile_search_wall(1920, 1080, 12, &[(0, 0), (1, 0), (1, 1), (2, 1)], &[1, 2, 4, 8]); |
| 2342 | } |
| 2343 | |
| 2344 | /// The same table at the 4K frame size the editor exports (3840x1608), |
| 2345 | /// at the two layouts with enough tiles to fill this box. |
| 2346 | #[test] |
| 2347 | #[ignore = "wall measurement: minutes, run it with --ignored --nocapture"] |
| 2348 | fn tile_search_wall_4k() { |
| 2349 | tile_search_wall(3840, 1608, 6, &[(2, 1), (3, 2)], &[1, 8, 12]); |
| 2350 | } |
| 2351 | |
| 2352 | /// lane-av1fpar: the frame-level FILTER stage is banded across the same |
| 2353 | /// workers the tile search uses (`par::override_filter_threads`), so the |
| 2354 | /// deblock/CDEF replays, the per-64 SSE and the plane copies all run in |
| 2355 | /// pieces. Every piece is a disjoint band of the same integers, so the |
| 2356 | /// stream must not move -- at a size that crops and is several superblock |
| 2357 | /// rows tall, which is what makes the bands non-trivial. |
| 2358 | #[test] |
| 2359 | fn filter_stage_bytes_do_not_depend_on_the_thread_count() { |
| 2360 | let _gate_lock = crate::stream::tests::lock_gate_counters(); |
| 2361 | let (width, height) = (384usize, 288usize); |
| 2362 | let sources: Vec<Picture> = (0..4).map(|t| test_card(width, height, t * 3)).collect(); |
| 2363 | let coded = |threads: usize| { |
| 2364 | crate::par::set_tile_threads(threads); |
| 2365 | let config = EncoderConfig { |
| 2366 | width, |
| 2367 | height, |
| 2368 | base_q_idx: 120, |
| 2369 | gop: 2, |
| 2370 | colour: Colour::Bt709Limited, |
| 2371 | tile_cols_log2: 0, |
| 2372 | tile_rows_log2: 0, |
| 2373 | }; |
| 2374 | let mut enc = Av1Encoder::new(config).unwrap(); |
| 2375 | let mut stream = Vec::new(); |
| 2376 | for packet in encode_all(&mut enc, &sources) { |
| 2377 | stream.extend_from_slice(&packet.data); |
| 2378 | } |
| 2379 | stream |
| 2380 | }; |
| 2381 | // One tile, so only the filter stage can differ between these. |
| 2382 | let one = coded(1); |
| 2383 | for threads in [2usize, 4, 8] { |
| 2384 | assert_eq!(one, coded(threads), "the filter stage moved at {threads} threads"); |
| 2385 | } |
| 2386 | crate::par::set_tile_threads(1); |
| 2387 | } |
| 2388 | |
| 2389 | /// lane-av1fpar: the filter search scores its ~30 candidates by replaying |
| 2390 | /// the loop filters on one captured reconstruction instead of decoding |
| 2391 | /// the coded tile again per candidate. The replay must be that decode, |
| 2392 | /// byte for byte -- including at a size that CROPS (1080 and 1608 both |
| 2393 | /// pad to a superblock row, i.e. every export size the editor uses), |
| 2394 | /// which is the arm this lane opened. |
| 2395 | #[test] |
| 2396 | fn filter_replay_codes_the_same_stream_as_a_full_decode() { |
| 2397 | let _gate_lock = crate::stream::tests::lock_gate_counters(); |
| 2398 | let run = |width: usize, height: usize, off: bool| { |
| 2399 | let sources: Vec<Picture> = (0..4).map(|t| test_card(width, height, t * 3)).collect(); |
| 2400 | crate::decode::set_filter_replay_disabled(off); |
| 2401 | let config = EncoderConfig { |
| 2402 | width, |
| 2403 | height, |
| 2404 | base_q_idx: 120, |
| 2405 | gop: 2, |
| 2406 | colour: Colour::Bt709Limited, |
| 2407 | tile_cols_log2: 0, |
| 2408 | tile_rows_log2: 0, |
| 2409 | }; |
| 2410 | let mut enc = Av1Encoder::new(config).unwrap(); |
| 2411 | let mut stream = Vec::new(); |
| 2412 | for packet in encode_all(&mut enc, &sources) { |
| 2413 | stream.extend_from_slice(&packet.data); |
| 2414 | } |
| 2415 | crate::decode::set_filter_replay_disabled(false); |
| 2416 | stream |
| 2417 | }; |
| 2418 | // 320x160 crops (the coding surface is 320x192, one superblock row |
| 2419 | // taller); 320x192 is a whole number of superblocks, the shape the |
| 2420 | // replay already covered. |
| 2421 | for (width, height) in [(320usize, 160usize), (320, 192)] { |
| 2422 | let replayed = run(width, height, false); |
| 2423 | let decoded = run(width, height, true); |
| 2424 | assert_eq!( |
| 2425 | replayed, |
| 2426 | decoded, |
| 2427 | "{width}x{height}: the filter replay is not the decode it stands in for \ |
| 2428 | ({} bytes replayed, {} decoded)", |
| 2429 | replayed.len(), |
| 2430 | decoded.len(), |
| 2431 | ); |
| 2432 | } |
| 2433 | } |
| 2434 | |
| 2435 | /// lane-av1cap: the filter stage's FINAL replay -- the one that replaced |
| 2436 | /// the capture decode -- against that decode. `set_verify_final_replay` |
| 2437 | /// makes `encode::pick_and_apply_filters` run both on every frame and |
| 2438 | /// assert, per frame, that the spliced picture and the two filter stages |
| 2439 | /// the loop-restoration search reads are bit-identical. |
| 2440 | #[test] |
| 2441 | fn filter_replay_final_matches_the_capture_decode() { |
| 2442 | let _gate_lock = crate::stream::tests::lock_gate_counters(); |
| 2443 | let run = |sources: &[Picture], width: usize, height: usize, tiles: (u32, u32)| { |
| 2444 | let config = EncoderConfig { |
| 2445 | width, |
| 2446 | height, |
| 2447 | base_q_idx: 120, |
| 2448 | gop: 2, |
| 2449 | colour: Colour::Bt709Limited, |
| 2450 | tile_cols_log2: tiles.0, |
| 2451 | tile_rows_log2: tiles.1, |
| 2452 | }; |
| 2453 | let mut enc = Av1Encoder::new(config).unwrap(); |
| 2454 | for packet in encode_all(&mut enc, sources) { |
| 2455 | assert!(!packet.data.is_empty()); |
| 2456 | } |
| 2457 | }; |
| 2458 | crate::decode::set_verify_final_replay(true); |
| 2459 | // 320x160 crops (its coding surface is one superblock row taller); |
| 2460 | // 320x192 is a whole number of superblocks. |
| 2461 | for (width, height) in [(320usize, 160usize), (320, 192)] { |
| 2462 | let sources: Vec<Picture> = |
| 2463 | (0..4).map(|t| test_card(width, height, t * 3)).collect(); |
| 2464 | run(&sources, width, height, (0, 0)); |
| 2465 | } |
| 2466 | // Real gate content, where the CDEF preset search actually chooses |
| 2467 | // `bits > 0` and the tile is re-coded, one tile and four. |
| 2468 | if let Some(sources) = h264_clip_frames(640, 384, 3) { |
| 2469 | run(&sources, 640, 384, (0, 0)); |
| 2470 | run(&sources, 640, 384, (1, 1)); |
| 2471 | } else { |
| 2472 | eprintln!("SKIP the gate-clip arm: no fixture or no ffmpeg"); |
| 2473 | } |
| 2474 | crate::decode::set_verify_final_replay(false); |
| 2475 | } |
| 2476 | |
| 2477 | /// lane-av1fpar: where a frame's wall actually goes, stage by stage -- |
| 2478 | /// the per-tile search, the tile write, the frame-level filter search |
| 2479 | /// (with its deblock/CDEF replay and per-64 SSE inside it), the capture |
| 2480 | /// decode the loop-restoration search rides on, and that search itself. |
| 2481 | /// Measurement, not a pass/fail gate. |
| 2482 | #[test] |
| 2483 | #[ignore = "wall measurement: minutes, run it with --ignored --nocapture"] |
| 2484 | fn filter_stage_wall_1080p() { |
| 2485 | filter_stage_wall(1920, 1080, 8, (2, 1), &[8]); |
| 2486 | } |
| 2487 | |
| 2488 | #[test] |
| 2489 | #[ignore = "wall measurement: minutes, run it with --ignored --nocapture"] |
| 2490 | fn filter_stage_wall_4k() { |
| 2491 | filter_stage_wall(3840, 1608, 4, (2, 1), &[8, 12]); |
| 2492 | } |
| 2493 | |
| 2494 | /// The same breakdown at the real films' own crop size. With |
| 2495 | /// `EC_AV1_WALL_CLIP` pointing at a film window this is the film row; with |
| 2496 | /// it unset it is the colour-bar fixture at the same size, which is what |
| 2497 | /// makes the pair a comparison rather than a number. |
| 2498 | #[test] |
| 2499 | #[ignore = "wall measurement: minutes, run it with --ignored --nocapture"] |
| 2500 | fn filter_stage_wall_film() { |
| 2501 | filter_stage_wall(1920, 768, 4, (2, 1), &[8]); |
| 2502 | } |
| 2503 | |
| 2504 | fn filter_stage_wall( |
| 2505 | width: usize, |
| 2506 | height: usize, |
| 2507 | frames: usize, |
| 2508 | (cols_log2, rows_log2): (u32, u32), |
| 2509 | threads: &[usize], |
| 2510 | ) { |
| 2511 | let _gate_lock = crate::stream::tests::lock_gate_counters(); |
| 2512 | let Some(sources) = h264_clip_frames(width, height, frames) else { |
| 2513 | eprintln!("SKIP the filter-stage breakdown: no fixture or no ffmpeg"); |
| 2514 | return; |
| 2515 | }; |
| 2516 | crate::par::set_stage_times(true); |
| 2517 | for &t in threads { |
| 2518 | crate::par::set_tile_threads(t); |
| 2519 | let config = EncoderConfig { |
| 2520 | width, |
| 2521 | height, |
| 2522 | base_q_idx: 120, |
| 2523 | gop: frames, |
| 2524 | colour: Colour::Bt709Limited, |
| 2525 | tile_cols_log2: cols_log2, |
| 2526 | tile_rows_log2: rows_log2, |
| 2527 | }; |
| 2528 | let mut enc = Av1Encoder::new(config).unwrap(); |
| 2529 | let _ = crate::par::take_stage_ns(); |
| 2530 | let start = std::time::Instant::now(); |
| 2531 | for packet in encode_all(&mut enc, &sources) { |
| 2532 | assert!(!packet.data.is_empty()); |
| 2533 | } |
| 2534 | let wall = start.elapsed().as_secs_f64(); |
| 2535 | let ns = crate::par::take_stage_ns(); |
| 2536 | let ms = |i: usize| ns[i] as f64 / 1e6; |
| 2537 | eprintln!( |
| 2538 | "\n{width}x{height}, {frames} frames, {}x{} tiles, {t} tile threads: \ |
| 2539 | {wall:.2}s wall, {:.2} fps", |
| 2540 | 1 << cols_log2, |
| 2541 | 1 << rows_log2, |
| 2542 | frames as f64 / wall, |
| 2543 | ); |
| 2544 | eprintln!("| stage | ms | ms/frame | % of wall |"); |
| 2545 | for (i, name) in crate::par::STAGES.iter().enumerate() { |
| 2546 | eprintln!( |
| 2547 | "| {name} | {:.0} | {:.1} | {:.1}% |", |
| 2548 | ms(i), |
| 2549 | ms(i) / frames as f64, |
| 2550 | 100.0 * ms(i) / (wall * 1e3), |
| 2551 | ); |
| 2552 | } |
| 2553 | // Top-level stages only (the deblock/CDEF/SSE rows are inside |
| 2554 | // the filter-search total); the rest is per-frame setup, the |
| 2555 | // source conversion and the splice. |
| 2556 | let top: f64 = [ |
| 2557 | crate::par::S_TILE_SEARCH, |
| 2558 | crate::par::S_TILE_WRITE, |
| 2559 | crate::par::S_FILTER, |
| 2560 | crate::par::S_CAPTURE, |
| 2561 | crate::par::S_LR, |
| 2562 | ] |
| 2563 | .iter() |
| 2564 | .map(|&i| ms(i)) |
| 2565 | .sum(); |
| 2566 | eprintln!( |
| 2567 | "accounted {:.1}% of wall; outside the tile search {:.1}%", |
| 2568 | 100.0 * top / (wall * 1e3), |
| 2569 | 100.0 * (1.0 - ms(crate::par::S_TILE_SEARCH) / (wall * 1e3)), |
| 2570 | ); |
| 2571 | } |
| 2572 | crate::par::set_stage_times(false); |
| 2573 | crate::par::set_tile_threads(1); |
| 2574 | } |
| 2575 | |
| 2576 | fn tile_search_wall( |
| 2577 | width: usize, |
| 2578 | height: usize, |
| 2579 | frames: usize, |
| 2580 | layouts: &[(u32, u32)], |
| 2581 | threads: &[usize], |
| 2582 | ) { |
| 2583 | let _gate_lock = crate::stream::tests::lock_gate_counters(); |
| 2584 | let Some(sources) = h264_clip_frames(width, height, frames) else { |
| 2585 | eprintln!("SKIP the tile-search wall table: no fixture or no ffmpeg"); |
| 2586 | return; |
| 2587 | }; |
| 2588 | let run = |cols_log2: u32, rows_log2: u32, t: usize| -> (std::time::Duration, usize) { |
| 2589 | crate::par::set_tile_threads(t); |
| 2590 | let config = EncoderConfig { |
| 2591 | width, |
| 2592 | height, |
| 2593 | base_q_idx: 120, |
| 2594 | gop: frames, |
| 2595 | colour: Colour::Bt709Limited, |
| 2596 | tile_cols_log2: cols_log2, |
| 2597 | tile_rows_log2: rows_log2, |
| 2598 | }; |
| 2599 | let mut enc = Av1Encoder::new(config).unwrap(); |
| 2600 | let start = std::time::Instant::now(); |
| 2601 | let mut bytes = 0usize; |
| 2602 | for packet in encode_all(&mut enc, &sources) { |
| 2603 | bytes += packet.data.len(); |
| 2604 | } |
| 2605 | (start.elapsed(), bytes) |
| 2606 | }; |
| 2607 | let cells: Vec<((u32, u32), usize)> = layouts |
| 2608 | .iter() |
| 2609 | .flat_map(|&l| threads.iter().map(move |&t| (l, t))) |
| 2610 | .collect(); |
| 2611 | let mut best: Vec<Option<(std::time::Duration, usize)>> = vec![None; cells.len()]; |
| 2612 | for _pass in 0..2 { |
| 2613 | for (i, &((c, r), t)) in cells.iter().enumerate() { |
| 2614 | let got = run(c, r, t); |
| 2615 | assert!(got.1 > 0, "{}x{} tiles at {t} threads: empty stream", 1 << c, 1 << r); |
| 2616 | if best[i].is_none_or(|(w, _)| got.0 < w) { |
| 2617 | best[i] = Some(got); |
| 2618 | } |
| 2619 | } |
| 2620 | } |
| 2621 | crate::par::set_tile_threads(1); |
| 2622 | eprintln!("\n{width}x{height}, {frames} frames, base_q_idx 120 -- best of two passes"); |
| 2623 | eprintln!("| layout | tiles | threads | wall | fps | speedup vs 1 tile 1 thread | bytes |"); |
| 2624 | let base = best[0].expect("the first cell ran").0.as_secs_f64(); |
| 2625 | for (i, &((c, r), t)) in cells.iter().enumerate() { |
| 2626 | let (wall, bytes) = best[i].expect("every cell ran"); |
| 2627 | let secs = wall.as_secs_f64(); |
| 2628 | eprintln!( |
| 2629 | "| {}x{} | {} | {t} | {secs:.2}s | {:.2} | {:.2}x | {bytes} |", |
| 2630 | 1 << c, |
| 2631 | 1 << r, |
| 2632 | 1 << (c + r), |
| 2633 | frames as f64 / secs, |
| 2634 | base / secs, |
| 2635 | ); |
| 2636 | } |
| 2637 | // Parallel efficiency per layout: what the extra threads actually |
| 2638 | // took off that layout's own single-threaded wall, and so what share |
| 2639 | // of the added cores sat idle. |
| 2640 | for &(c, r) in layouts { |
| 2641 | let one = cells |
| 2642 | .iter() |
| 2643 | .position(|&(l, t)| l == (c, r) && t == threads[0]) |
| 2644 | .map(|i| best[i].expect("cell").0.as_secs_f64()); |
| 2645 | let Some(one) = one else { continue }; |
| 2646 | for &t in &threads[1..] { |
| 2647 | let i = cells.iter().position(|&(l, tt)| l == (c, r) && tt == t).expect("cell"); |
| 2648 | let secs = best[i].expect("cell").0.as_secs_f64(); |
| 2649 | let workers = (t.min(1 << (c + r))) as f64 / threads[0] as f64; |
| 2650 | let speedup = one / secs; |
| 2651 | eprintln!( |
| 2652 | "{}x{} tiles, {} -> {t} threads: {speedup:.2}x of a possible {workers:.2}x, \ |
| 2653 | idle share {:.0}%", |
| 2654 | 1 << c, |
| 2655 | 1 << r, |
| 2656 | threads[0], |
| 2657 | 100.0 * (1.0 - speedup / workers).max(0.0), |
| 2658 | ); |
| 2659 | } |
| 2660 | } |
| 2661 | rav1e_wall_reference(width, height, frames, layouts, threads); |
| 2662 | } |
| 2663 | |
| 2664 | /// librav1e at the same sizes, layouts and thread counts, through ffmpeg |
| 2665 | /// -- the reference the wall table is read against. |
| 2666 | fn rav1e_wall_reference( |
| 2667 | width: usize, |
| 2668 | height: usize, |
| 2669 | frames: usize, |
| 2670 | layouts: &[(u32, u32)], |
| 2671 | threads: &[usize], |
| 2672 | ) { |
| 2673 | let clip = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) |
| 2674 | .join("../../fixtures/video/h264-1080p-23.976-8bit.mp4"); |
| 2675 | let listed = Command::new("ffmpeg").args(["-hide_banner", "-encoders"]).output(); |
| 2676 | let has_rav1e = listed |
| 2677 | .map(|o| String::from_utf8_lossy(&o.stdout).contains("librav1e")) |
| 2678 | .unwrap_or(false); |
| 2679 | if !has_rav1e || !clip.exists() { |
| 2680 | eprintln!("SKIP the rav1e reference: no librav1e or no fixture"); |
| 2681 | return; |
| 2682 | } |
| 2683 | eprintln!("| rav1e layout | threads | wall | fps | bytes |"); |
| 2684 | for &(c, r) in layouts { |
| 2685 | for &t in threads { |
| 2686 | let out = std::env::temp_dir().join(format!("ec-av1-rav1e-{}.ivf", std::process::id())); |
| 2687 | let params = format!( |
| 2688 | "speed=6:quantizer=100:tile_cols={}:tile_rows={}:threads={t}", |
| 2689 | 1 << c, |
| 2690 | 1 << r |
| 2691 | ); |
| 2692 | let start = std::time::Instant::now(); |
| 2693 | let status = Command::new("ffmpeg") |
| 2694 | .args(["-v", "error", "-y", "-i", clip.to_str().unwrap()]) |
| 2695 | .args(["-frames:v", &frames.to_string()]) |
| 2696 | .args(["-vf", &format!("scale={width}:{height}")]) |
| 2697 | .args(["-c:v", "librav1e", "-rav1e-params", ¶ms]) |
| 2698 | .arg(out.to_str().unwrap()) |
| 2699 | .output() |
| 2700 | .expect("ffmpeg failed to run"); |
| 2701 | let secs = start.elapsed().as_secs_f64(); |
| 2702 | if !status.status.success() { |
| 2703 | eprintln!("| {}x{} | {t} | FAILED: {} |", 1 << c, 1 << r, String::from_utf8_lossy(&status.stderr).lines().last().unwrap_or("")); |
| 2704 | continue; |
| 2705 | } |
| 2706 | let bytes = std::fs::metadata(&out).map(|m| m.len()).unwrap_or(0); |
| 2707 | let _ = std::fs::remove_file(&out); |
| 2708 | eprintln!( |
| 2709 | "| {}x{} | {t} | {secs:.2}s | {:.2} | {bytes} |", |
| 2710 | 1 << c, |
| 2711 | 1 << r, |
| 2712 | frames as f64 / secs |
| 2713 | ); |
| 2714 | } |
| 2715 | } |
| 2716 | } |
| 2717 | |
| 2718 | /// The same round trip at a real 1920x1080 crop of the gate's own clip |
| 2719 | /// -- the size the editor's export actually runs at, where a tile grid |
| 2720 | /// is worth having. Ignored by default only for its wall (a 1080p |
| 2721 | /// encode of three pictures), not for any weakness in the check. |
| 2722 | #[test] |
| 2723 | #[ignore = "1080p encode: minutes, run it with --ignored"] |
| 2724 | fn a_1080p_multi_tile_stream_decodes_sample_exact_through_both_decoders() { |
| 2725 | let (width, height) = (1920usize, 1080usize); |
| 2726 | let Some(sources) = h264_clip_frames(width, height, 3) else { |
| 2727 | eprintln!("SKIP the 1080p tile round trip: no fixture"); |
| 2728 | return; |
| 2729 | }; |
| 2730 | for (cols_log2, rows_log2) in [(1u32, 0u32), (1, 1), (2, 1)] { |
| 2731 | let config = EncoderConfig { |
| 2732 | width, |
| 2733 | height, |
| 2734 | base_q_idx: 120, |
| 2735 | gop: 3, |
| 2736 | colour: Colour::Bt709Limited, |
| 2737 | tile_cols_log2: cols_log2, |
| 2738 | tile_rows_log2: rows_log2, |
| 2739 | }; |
| 2740 | let layout = format!("{}x{} tiles", 1 << cols_log2, 1 << rows_log2); |
| 2741 | let mut enc = Av1Encoder::new(config).unwrap(); |
| 2742 | let mut stream = Vec::new(); |
| 2743 | for packet in encode_all(&mut enc, &sources) { |
| 2744 | stream.extend_from_slice(&packet.data); |
| 2745 | } |
| 2746 | let ours = crate::stream::decode_stream(&stream).expect("our decoder"); |
| 2747 | assert_eq!(ours.len(), sources.len(), "{layout}: our decoder's frames"); |
| 2748 | if !have_ffmpeg() { |
| 2749 | eprintln!("SKIP the ffmpeg half of 1080p {layout}: no ffmpeg"); |
| 2750 | continue; |
| 2751 | } |
| 2752 | let theirs = ffmpeg_decode_luma(&stream, width, height); |
| 2753 | assert_eq!(theirs.len(), sources.len(), "{layout}: ffmpeg's frames"); |
| 2754 | for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() { |
| 2755 | let got: Vec<u8> = a.y.iter().map(|&v| v as u8).collect(); |
| 2756 | if let Some(at) = got.iter().zip(b).position(|(x, y)| x != y) { |
| 2757 | panic!( |
| 2758 | "1080p {layout} frame {i}: luma differs first at ({}, {})", |
| 2759 | at % width, |
| 2760 | at / width |
| 2761 | ); |
| 2762 | } |
| 2763 | } |
| 2764 | eprintln!("1080p {layout}: {} bytes, sample-exact", stream.len()); |
| 2765 | } |
| 2766 | } |
| 2767 | |
| 2768 | /// [`RateTarget::Quality`] is monotone: a higher quality dial never |
| 2769 | /// produces a smaller stream or a worse mean PSNR than a lower one, on |
| 2770 | /// the same real clip. |
| 2771 | #[test] |
| 2772 | fn quality_target_is_monotone_in_bytes_and_psnr() { |
| 2773 | if !have_ffmpeg() { |
| 2774 | eprintln!("SKIP quality_target_is_monotone_in_bytes_and_psnr: no ffmpeg"); |
| 2775 | return; |
| 2776 | } |
| 2777 | let (width, height) = (640, 384); |
| 2778 | let Some(pictures) = h264_clip_frames(width, height, 8) else { |
| 2779 | eprintln!("SKIP quality_target_is_monotone_in_bytes_and_psnr: no fixture"); |
| 2780 | return; |
| 2781 | }; |
| 2782 | let mut prev_bytes = 0usize; |
| 2783 | let mut prev_psnr = 0.0f64; |
| 2784 | for quality in [20u8, 50, 80] { |
| 2785 | let config = EncoderConfig { |
| 2786 | width, |
| 2787 | height, |
| 2788 | base_q_idx: 100, |
| 2789 | gop: 8, |
| 2790 | colour: Colour::Bt709Limited, |
| 2791 | tile_cols_log2: 0, |
| 2792 | tile_rows_log2: 0, |
| 2793 | }; |
| 2794 | let mut enc = |
| 2795 | Av1Encoder::with_rate_target(config, RateTarget::Quality(quality)).unwrap(); |
| 2796 | let mut stream = Vec::new(); |
| 2797 | let mut total_bytes = 0usize; |
| 2798 | for packet in encode_all(&mut enc, &pictures) { |
| 2799 | total_bytes += packet.data.len(); |
| 2800 | stream.extend_from_slice(&packet.data); |
| 2801 | } |
| 2802 | let decoded = ffmpeg_decode_luma(&stream, width, height); |
| 2803 | assert_eq!( |
| 2804 | decoded.len(), |
| 2805 | pictures.len(), |
| 2806 | "quality {quality}: dav1d frame count" |
| 2807 | ); |
| 2808 | let mean_psnr: f64 = decoded |
| 2809 | .iter() |
| 2810 | .zip(&pictures) |
| 2811 | .map(|(d, p)| { |
| 2812 | let d16: Vec<u16> = d.iter().map(|&v| u16::from(v)).collect(); |
| 2813 | psnr(&d16, &p.y) |
| 2814 | }) |
| 2815 | .sum::<f64>() |
| 2816 | / decoded.len() as f64; |
| 2817 | assert!( |
| 2818 | total_bytes >= prev_bytes, |
| 2819 | "quality {quality}: {total_bytes} bytes not >= previous {prev_bytes}" |
| 2820 | ); |
| 2821 | assert!( |
| 2822 | mean_psnr >= prev_psnr - 0.01, // rounding slack, same-ish q_idx neighbours |
| 2823 | "quality {quality}: {mean_psnr:.2} dB not >= previous {prev_psnr:.2} dB" |
| 2824 | ); |
| 2825 | prev_bytes = total_bytes; |
| 2826 | prev_psnr = mean_psnr; |
| 2827 | } |
| 2828 | } |
| 2829 | } |