edith_codecs
Clone
https://git.tahinli.com/Tahinli/edith_codecs.git
0 watching·0 forks·Rust·370.3 MiB·682c080·Tahinli·2 months ago·2434 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 picture in, one [`Packet`] out, same contract as the repo's other |
| 5 | //! software encoder shims (`shims/rusty_h264`'s `Encoder::try_encode`, |
| 6 | //! "nothing is ever held back"): [`Av1Encoder::encode`] never buffers a |
| 7 | //! picture past its own call, so there is no flush to drain. That contract |
| 8 | //! still holds for every caller that does not opt into a coding pyramid; |
| 9 | //! [`Av1Encoder::with_pyramid`] does reorder pictures, and such a stream is |
| 10 | //! driven through [`Av1Encoder::encode_frames`] (zero or more packets per |
| 11 | //! picture) and [`Av1Encoder::flush`] instead. Internally it |
| 12 | //! is [`crate::encode::encode_key_frame_inner`] and |
| 13 | //! [`crate::encode::encode_inter_frame`] driven by a small state machine — |
| 14 | //! a key frame every `gop` pictures, an inter frame predicting from the |
| 15 | //! previous picture's own reconstruction otherwise — which is the same core |
| 16 | //! [`crate::encode::encode_sequence`] uses for its one-key-frame-then-all-inter |
| 17 | //! case; both now share it rather than each padding/cropping/refreshing the |
| 18 | //! reference on their own. |
| 19 | |
| 20 | use ec_av1_syntax::sequence::{ChromaSamplePosition, ColorConfig}; |
| 21 | use ec_core::{Error, Result}; |
| 22 | |
| 23 | use crate::encode::{ |
| 24 | Encoded, GOLDEN_SLOT, Picture, SUPERBLOCK, crop_encoded, encode_inter_frame, |
| 25 | encode_key_frame_inner, split_blocks, |
| 26 | }; |
| 27 | use crate::intra::KEY_FRAME_MODES; |
| 28 | |
| 29 | /// A quantizer step round to nearest: half a step either way costs the same |
| 30 | /// rate, so this is the deadzone every facade-driven frame is coded with. |
| 31 | /// (`crate::encode`'s public entry points take a caller-chosen deadzone |
| 32 | /// instead; the facade has no field for it because nothing downstream of it |
| 33 | /// picks one.) |
| 34 | const DEADZONE: f64 = 0.5; |
| 35 | |
| 36 | /// The colour a played-back frame is transformed by, named at what a |
| 37 | /// container/player picks a colour space from (spec 5.5.2's CICP triple plus |
| 38 | /// range) rather than at the raw integers. `edith_replica`'s rav1e seat sets |
| 39 | /// limited-range BT.709 or BT.601 (`export.rs:3494-3507`); this crate's |
| 40 | /// pre-facade sequence header always wrote [`Colour::Unspecified`]. |
| 41 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] |
| 42 | pub enum Colour { |
| 43 | /// `color_primaries`/`transfer_characteristics`/`matrix_coefficients` = |
| 44 | /// 1 (BT.709, H.273), studio range: consumer HD video's own space, and |
| 45 | /// the default a player assumes when nothing is signalled at all. |
| 46 | #[default] |
| 47 | Bt709Limited, |
| 48 | /// The same three fields = 6 (BT.601, H.273), studio range: SD video's |
| 49 | /// space. |
| 50 | Bt601Limited, |
| 51 | /// Every field = 2 ("unspecified", H.273): what this crate wrote before |
| 52 | /// any of this was configurable. |
| 53 | Unspecified, |
| 54 | } |
| 55 | |
| 56 | impl Colour { |
| 57 | fn color_config(self) -> ColorConfig { |
| 58 | let (color_primaries, transfer_characteristics, matrix_coefficients) = match self { |
| 59 | Colour::Bt709Limited => (1, 1, 1), |
| 60 | Colour::Bt601Limited => (6, 6, 6), |
| 61 | Colour::Unspecified => (2, 2, 2), |
| 62 | }; |
| 63 | ColorConfig { |
| 64 | bit_depth: 8, |
| 65 | mono_chrome: false, |
| 66 | num_planes: 3, |
| 67 | color_primaries, |
| 68 | transfer_characteristics, |
| 69 | matrix_coefficients, |
| 70 | // Every variant here is studio (limited) swing; a full-range |
| 71 | // variant would need its own name, not a fourth field on this |
| 72 | // enum, since a played-back frame's range is a property of the |
| 73 | // pictures fed in, not just a label. |
| 74 | color_range: false, |
| 75 | subsampling_x: 1, |
| 76 | subsampling_y: 1, |
| 77 | chroma_sample_position: ChromaSamplePosition::Unknown, |
| 78 | separate_uv_delta_q: false, |
| 79 | } |
| 80 | } |
| 81 | } |
| 82 | |
| 83 | /// A quality/size targeting surface for callers who would rather not pick a |
| 84 | /// `base_q_idx` themselves, oracled at CRF's own shape (a single "quality" |
| 85 | /// dial that holds a stable perceptual level across content, `ffmpeg -crf`) |
| 86 | /// since a from-scratch scheme is not this lane's charter to invent. |
| 87 | /// [`Av1Encoder::with_rate_target`] is additive: [`EncoderConfig::base_q_idx`] |
| 88 | /// keeps working exactly as before for every existing caller, this is a |
| 89 | /// second, opt-in constructor. |
| 90 | #[derive(Debug, Clone, Copy, PartialEq)] |
| 91 | pub enum RateTarget { |
| 92 | /// Exactly `base_q_idx`, unchanged — the `EncoderConfig` field's own |
| 93 | /// value, for a caller that already has one. |
| 94 | QIndex(u8), |
| 95 | /// A CRF-like single dial, 0 (smallest/worst) to 100 (largest/best), |
| 96 | /// mapped to a fixed `base_q_idx` by the calibration in |
| 97 | /// `encode::tests::calibration_sweep_base_q_idx` (linear in `q_idx` |
| 98 | /// across the sweep's own 40..=240 span, since the measured bytes/PSNR |
| 99 | /// curve is close enough to log-linear there that a straight line is |
| 100 | /// the "simplest correct" fit this lane's charter asks for). No |
| 101 | /// per-frame feedback: one value, picked once at construction. |
| 102 | Quality(u8), |
| 103 | /// A closed loop that steers `base_q_idx` frame by frame to land each |
| 104 | /// coded frame near this many bytes, via [`RateLoop`] — see there for |
| 105 | /// the controller and its windup bound. |
| 106 | BytesPerFrame(u32), |
| 107 | /// A target BITRATE: the same closed loop, with the per-frame byte |
| 108 | /// target derived from `bits_per_second` and `frames_per_second` |
| 109 | /// (`bits_per_second / 8 / frames_per_second`), and — in pyramid mode — |
| 110 | /// split across the levels by their reference weight, since a hidden |
| 111 | /// `ALTREF` and a leaf differ by several times in size and one shared |
| 112 | /// predictor would swing the quantizer every frame. |
| 113 | Bitrate { |
| 114 | /// The stream's target bitrate. |
| 115 | bits_per_second: u32, |
| 116 | /// The frame rate the bitrate is spent at. |
| 117 | frames_per_second: f64, |
| 118 | }, |
| 119 | } |
| 120 | |
| 121 | impl RateTarget { |
| 122 | /// Applies this target to `config` and returns the closed loop it needs |
| 123 | /// (`None` for the two open-loop variants). `mini_gop` is `Some` in |
| 124 | /// pyramid mode, which is what makes the loop keep a quantizer per level. |
| 125 | fn into_loop(self, config: &mut EncoderConfig, mini_gop: Option<usize>) -> Option<RateLoop> { |
| 126 | let target_bytes = match self { |
| 127 | RateTarget::QIndex(q) => { |
| 128 | config.base_q_idx = q; |
| 129 | return None; |
| 130 | } |
| 131 | RateTarget::Quality(quality) => { |
| 132 | config.base_q_idx = quality_to_q_idx(quality); |
| 133 | return None; |
| 134 | } |
| 135 | RateTarget::BytesPerFrame(target_bytes) => f64::from(target_bytes), |
| 136 | RateTarget::Bitrate { |
| 137 | bits_per_second, |
| 138 | frames_per_second, |
| 139 | } => f64::from(bits_per_second) / 8.0 / frames_per_second.max(1.0), |
| 140 | }; |
| 141 | Some(RateLoop::new( |
| 142 | target_bytes, |
| 143 | f64::from(config.base_q_idx), |
| 144 | mini_gop, |
| 145 | )) |
| 146 | } |
| 147 | } |
| 148 | |
| 149 | /// `quality`'s mapping to `base_q_idx`, linear across the calibration sweep's |
| 150 | /// span (`q_idx` 40 at `quality` 100 down to `q_idx` 240 at `quality` 0); |
| 151 | /// `quality` above 100 clamps to the best point measured, matching a CRF |
| 152 | /// dial's own saturating ends rather than extrapolating past calibrated |
| 153 | /// data. |
| 154 | fn quality_to_q_idx(quality: u8) -> u8 { |
| 155 | let quality = f64::from(quality.min(100)); |
| 156 | (240.0 - quality * 2.0).round() as u8 |
| 157 | } |
| 158 | |
| 159 | /// How much of a mini-GOP's byte budget the hidden `ALTREF` frame is worth |
| 160 | /// relative to one leaf: every leaf of the group predicts off it, so it is |
| 161 | /// bought at roughly twice a leaf's size (libaom's `gf_group` spends its |
| 162 | /// `ARF` the same way, through a lower quantizer rather than a byte target). |
| 163 | const ARF_WEIGHT: f64 = 2.0; |
| 164 | |
| 165 | /// How much a key frame is worth relative to one leaf, same units. |
| 166 | const KEY_WEIGHT: f64 = 3.0; |
| 167 | |
| 168 | /// The closed-loop controller behind [`RateTarget::BytesPerFrame`] and |
| 169 | /// [`RateTarget::Bitrate`]: a proportional step on `base_q_idx`, sized from |
| 170 | /// the calibration sweep's own log-linear slope (bytes roughly halve every |
| 171 | /// ~45 `q_idx` steps there, i.e. `d(ln bytes)/d(q_idx) ≈ -0.0154`), clamped |
| 172 | /// per frame. Pure proportional — no accumulated error term — is the windup |
| 173 | /// bound itself ([[vorbis-rate-loop-windup]]'s class): the only state carried |
| 174 | /// between frames is `q`, already clamped to `0..=255`, so a quiet lead-in |
| 175 | /// cannot build a debt a later transient has to repay; each frame's step is |
| 176 | /// bounded by `STEP_CLAMP` regardless of history. |
| 177 | /// |
| 178 | /// In pyramid mode the state is kept PER LEVEL: each frame's size is |
| 179 | /// predicted from the previous frame of its own level, against that level's |
| 180 | /// own share of the budget, which is the whole "two-pass-free model" this |
| 181 | /// encoder carries. |
| 182 | #[derive(Debug, Clone, Copy)] |
| 183 | struct RateLoop { |
| 184 | /// Byte target per level, indexed by [`RateLoop::slot`]. |
| 185 | target: [f64; 3], |
| 186 | /// Quantizer per level, same index. |
| 187 | q: [f64; 3], |
| 188 | /// Whether the three slots are actually distinct (pyramid mode) or all |
| 189 | /// one shared controller (the flat path, unchanged from before levels |
| 190 | /// existed). |
| 191 | per_level: bool, |
| 192 | } |
| 193 | |
| 194 | impl RateLoop { |
| 195 | /// The steepest a single frame is allowed to move `base_q_idx`, in |
| 196 | /// either direction — chosen so one wildly over/under-sized frame |
| 197 | /// (a scene cut, a black lead-in) nudges the next frame's quantizer |
| 198 | /// rather than slamming it to an extreme. |
| 199 | const STEP_CLAMP: f64 = 12.0; |
| 200 | /// The calibration sweep's own slope (see the struct doc), inverted to |
| 201 | /// convert a bytes ratio into a `q_idx` step. |
| 202 | const GAIN: f64 = 1.0 / 0.0154; |
| 203 | |
| 204 | fn new(target_bytes: f64, start_q: f64, mini_gop: Option<usize>) -> Self { |
| 205 | let Some(m) = mini_gop.map(|m| m as f64) else { |
| 206 | return Self { |
| 207 | target: [target_bytes; 3], |
| 208 | q: [start_q; 3], |
| 209 | per_level: false, |
| 210 | }; |
| 211 | }; |
| 212 | // A group of `m` pictures gets `m * target_bytes`, split one |
| 213 | // `ARF_WEIGHT` share to the hidden frame and one each to the `m - 1` |
| 214 | // leaves, so the group's own average is the target exactly. |
| 215 | let share = target_bytes * m / (m - 1.0 + ARF_WEIGHT); |
| 216 | Self { |
| 217 | target: [target_bytes * KEY_WEIGHT, share * ARF_WEIGHT, share], |
| 218 | q: [start_q; 3], |
| 219 | per_level: true, |
| 220 | } |
| 221 | } |
| 222 | |
| 223 | /// Which controller a level uses: one shared slot on the flat path, three |
| 224 | /// separate ones under a pyramid. |
| 225 | fn slot(&self, level: Level) -> usize { |
| 226 | if !self.per_level { |
| 227 | return 0; |
| 228 | } |
| 229 | match level { |
| 230 | Level::Key => 0, |
| 231 | Level::Arf => 1, |
| 232 | // A `show_existing_frame` packet codes no pixels and never |
| 233 | // reaches `update`; it shares the leaf slot so `q_idx` is total. |
| 234 | Level::Leaf | Level::ShowExisting => 2, |
| 235 | } |
| 236 | } |
| 237 | |
| 238 | fn q_idx(&self, level: Level) -> u8 { |
| 239 | self.q[self.slot(level)].round().clamp(0.0, 255.0) as u8 |
| 240 | } |
| 241 | |
| 242 | /// Steers this level's `q` toward its own target from the frame's actual |
| 243 | /// coded size. |
| 244 | fn update(&mut self, level: Level, actual_bytes: usize) { |
| 245 | let slot = self.slot(level); |
| 246 | if self.target[slot] <= 0.0 || actual_bytes == 0 { |
| 247 | return; |
| 248 | } |
| 249 | let ratio = actual_bytes as f64 / self.target[slot]; |
| 250 | let step = (ratio.ln() * Self::GAIN).clamp(-Self::STEP_CLAMP, Self::STEP_CLAMP); |
| 251 | self.q[slot] = (self.q[slot] + step).clamp(0.0, 255.0); |
| 252 | } |
| 253 | } |
| 254 | |
| 255 | /// What [`Av1Encoder::new`] takes: geometry, rate, key-frame cadence and |
| 256 | /// colour. `base_q_idx` is picked directly (0..=255, `crate::encode`'s own |
| 257 | /// unit) rather than a bitrate — a bitrate control loop is not part of this |
| 258 | /// lane's charter, and a caller that wants one can still derive a |
| 259 | /// `base_q_idx` from its own target and set that field. A caller who wants |
| 260 | /// [`RateTarget`]'s quality/size dials instead of picking `base_q_idx` |
| 261 | /// itself uses [`Av1Encoder::with_rate_target`], which still starts from an |
| 262 | /// `EncoderConfig` (its `base_q_idx` is the loop's seed/fallback for |
| 263 | /// [`RateTarget::BytesPerFrame`], and is overwritten outright for the other |
| 264 | /// two variants). |
| 265 | #[derive(Debug, Clone, Copy)] |
| 266 | pub struct EncoderConfig { |
| 267 | /// The picture's width in luma samples; must be even and nonzero. |
| 268 | pub width: usize, |
| 269 | /// The picture's height in luma samples; must be even and nonzero. |
| 270 | pub height: usize, |
| 271 | /// The quantizer index every frame is coded at (0..=255). |
| 272 | pub base_q_idx: u8, |
| 273 | /// Pictures between key frames, inclusive of the key frame itself: `1` |
| 274 | /// codes every picture as a key frame, `gop` codes picture `gop` (and |
| 275 | /// `2*gop`, ...) as a key frame and every other picture inter. |
| 276 | pub gop: usize, |
| 277 | /// The colour the sequence header signals. |
| 278 | pub colour: Colour, |
| 279 | /// `TileColsLog2` (spec 5.9.15): the frame is split into `1 << |
| 280 | /// tile_cols_log2` uniformly spaced tile columns, each coded and |
| 281 | /// decodable on its own. `0` -- one tile column -- is the default and |
| 282 | /// is byte for byte the stream this encoder wrote before tiles existed. |
| 283 | pub tile_cols_log2: u32, |
| 284 | /// `TileRowsLog2`, the same down the rows. |
| 285 | pub tile_rows_log2: u32, |
| 286 | } |
| 287 | |
| 288 | impl EncoderConfig { |
| 289 | /// A config at `width`x`height` with one tile, `gop` pictures between |
| 290 | /// key frames and no colour signalling -- what every caller that does |
| 291 | /// not care about tiles writes, so that adding a field here does not |
| 292 | /// rewrite them. |
| 293 | #[must_use] |
| 294 | pub fn new(width: usize, height: usize, base_q_idx: u8, gop: usize, colour: Colour) -> Self { |
| 295 | Self { |
| 296 | width, |
| 297 | height, |
| 298 | base_q_idx, |
| 299 | gop, |
| 300 | colour, |
| 301 | tile_cols_log2: 0, |
| 302 | tile_rows_log2: 0, |
| 303 | } |
| 304 | } |
| 305 | } |
| 306 | |
| 307 | /// One coded picture: its OBUs, in the order a demuxer that just wants bytes |
| 308 | /// on the wire can concatenate them, and the two things a muxer needs to |
| 309 | /// know without parsing them back out. |
| 310 | #[derive(Debug, Clone)] |
| 311 | pub struct Packet { |
| 312 | /// A temporal delimiter, a sequence header and the frame OBU for a key |
| 313 | /// frame; a temporal delimiter and the frame OBU alone for an inter |
| 314 | /// frame (the sequence header is identical across a stream's key |
| 315 | /// frames, since only [`EncoderConfig`]'s own fields feed it, so it is |
| 316 | /// simplest to let every key frame carry its own copy rather than have |
| 317 | /// the facade special-case the first one). |
| 318 | pub data: Vec<u8>, |
| 319 | /// Whether this picture was coded as a key frame. |
| 320 | pub key: bool, |
| 321 | /// This picture's position in DISPLAY (presentation) order, starting at |
| 322 | /// 0 — a muxer's `pts` in picture units. Without a [`Pyramid`] this is |
| 323 | /// also the coding order and equals `dts`. |
| 324 | pub order: u64, |
| 325 | /// This packet's position in CODING (decode) order, starting at 0 — a |
| 326 | /// muxer's `dts` in packet units. With a [`Pyramid`] the hidden frame of |
| 327 | /// each mini-GOP is coded before the leaves it precedes in display order, |
| 328 | /// so `dts` and `order` diverge, and the `show_existing_frame` packet |
| 329 | /// that re-outputs the hidden frame carries the hidden frame's own |
| 330 | /// `order` with its own later `dts`. |
| 331 | pub dts: u64, |
| 332 | /// Which pyramid level this packet is. |
| 333 | pub level: Level, |
| 334 | } |
| 335 | |
| 336 | /// One mini-GOP of a two-level coding pyramid, and the quantizer offsets its |
| 337 | /// two levels are coded at. libaom's `gf_group` shape, cut down to the two |
| 338 | /// levels this encoder's reference set can carry: the last picture of each |
| 339 | /// mini-GOP is coded FIRST, hidden (`show_frame == 0`), as the group's |
| 340 | /// `ALTREF_FRAME`, then the pictures before it are coded as shown leaves that |
| 341 | /// may predict backward off it, and finally a `show_existing_frame` header |
| 342 | /// re-outputs the hidden frame in its own display position. |
| 343 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 344 | pub struct Pyramid { |
| 345 | /// Pictures per mini-GOP: the hidden frame is `mini_gop` pictures ahead |
| 346 | /// of the group's anchor, and `mini_gop - 1` leaves sit between them. |
| 347 | /// `1` would leave no leaf at all and is refused. |
| 348 | pub mini_gop: usize, |
| 349 | /// Added to `base_q_idx` for the hidden `ALTREF_FRAME` — negative, since |
| 350 | /// every leaf of the group predicts off it. |
| 351 | pub arf_q_offset: i16, |
| 352 | /// Added to `base_q_idx` for each shown leaf — positive, since nothing |
| 353 | /// predicts off a leaf but the next leaf. |
| 354 | pub leaf_q_offset: i16, |
| 355 | } |
| 356 | |
| 357 | impl Default for Pyramid { |
| 358 | /// The best point of the offset sweep run through the BD gate's own |
| 359 | /// `EC_AV1_PYRAMID=<mini_gop>[:<arf_q_offset>:<leaf_q_offset>]` knob |
| 360 | /// (`encode::tests::bd_rate_vs_libaom_and_rav1e`, 12 frames of each of |
| 361 | /// the three gate clips, BD-rate vs libaom / vs rav1e, wall = the four |
| 362 | /// encodes of the ladder together). |
| 363 | /// |
| 364 | /// First sweep, before the motion-search lane merged (its extra-reference |
| 365 | /// `NEWMV` is exactly what a pyramid leaf needs to reach its hidden |
| 366 | /// frame), so read it for the OFFSETS, not for the verdict: |
| 367 | /// |
| 368 | /// | mini_gop:arf:leaf | 1080p | 2160p | screen | |
| 369 | /// |---|---|---|---| |
| 370 | /// | flat (no pyramid) | +122.7 / +73.4 | +147.3 / +98.5 | +79.4 / +17.2 | |
| 371 | /// | 4:0:0 | +152.2 / +97.9 | +214.7 / +158.1 | +91.4 / +26.2 | |
| 372 | /// | 4:-16:8 | +139.9 / +87.1 | +201.5 / +143.7 | +78.5 / +19.5 | |
| 373 | /// | 4:-24:12 | +141.3 / +85.0 | +190.0 / +132.9 | +84.5 / +22.8 | |
| 374 | /// | 2:0:0 | +149.3 / +93.1 | +203.0 / +149.4 | +88.3 / +23.6 | |
| 375 | /// | 2:-8:4 | +143.1 / +89.1 | +196.2 / +141.6 | +82.5 / +20.4 | |
| 376 | /// | 2:-16:8 | +137.6 / +84.5 | +187.2 / +130.6 | +84.9 / +23.1 | |
| 377 | /// |
| 378 | /// `0:0` is the worst row at both mini-GOP sizes and `-16/+8` buys 12-16 |
| 379 | /// BD points over it, in the direction libaom's `gf_group` spends them |
| 380 | /// (lowest quantizer on the frame everything else predicts from). Those |
| 381 | /// are these defaults. |
| 382 | /// |
| 383 | /// Re-measured after that lane merged (wall ours, 1080p/2160p/screen): |
| 384 | /// |
| 385 | /// | arm | 1080p | 2160p | screen | wall | |
| 386 | /// |---|---|---|---|---| |
| 387 | /// | flat (no pyramid) | +121.1 / +71.8 | +146.1 / +97.5 | +79.3 / +17.2 | 6.3 / 5.8 / 6.2 s | |
| 388 | /// | 4:-16:8 | +131.9 / +81.1 | +178.7 / +123.6 | +78.4 / +19.5 | 6.2 / 5.6 / 5.5 s | |
| 389 | /// | 2:-16:8 | +125.4 / +76.2 | +173.0 / +119.5 | +84.9 / +23.1 | 6.2 / 5.6 / 6.2 s | |
| 390 | /// |
| 391 | /// So the pyramid still does NOT pay, and ships OFF: it wins 0.9 points |
| 392 | /// on screen capture at `4:-16:8` and loses 11 on 1080p and 33 on 2160p. |
| 393 | /// What keeps it from paying, in the order the numbers point at it: |
| 394 | /// |
| 395 | /// * The hidden frame predicts `mini_gop` pictures ahead of its own |
| 396 | /// reference with the SAME forward search a neighbouring frame gets, |
| 397 | /// and it is the largest frame in the group (73.8 kB of the 1080p |
| 398 | /// ladder's 184 kB at `4:-16:8`). On the 2160p clip, whose motion the |
| 399 | /// search only just reaches at distance 1, distance 4 is where it |
| 400 | /// falls off — that clip loses twice what 1080p does, and shrinking |
| 401 | /// the mini-GOP to 2 recovers most of the gap (+178.7 -> +173.0, |
| 402 | /// +131.9 -> +125.4). A distance-scaled search range is the fix, and |
| 403 | /// it lives in the motion-search lane, not here. |
| 404 | /// * The leaves reach the hidden frame through the extra-reference |
| 405 | /// modes only: `ALTREF_FRAME` wins about 13% of blocks |
| 406 | /// (`encode::take_ref_frame_hits`, printed by the round-trip test), |
| 407 | /// up from 4% before the motion lane merged. A compound |
| 408 | /// (`LAST` + `ALTREF`) prediction mode is the other half of what a |
| 409 | /// real B frame buys, and this crate codes no compound blocks at all. |
| 410 | /// |
| 411 | /// Neither is a defect in the pyramid itself: the reordering is exact |
| 412 | /// (`encoder::tests::a_pyramid_stream_decodes_in_display_order_through_both_decoders` |
| 413 | /// checks every shown frame in display order against ffmpeg AND our own |
| 414 | /// decoder, with the hidden frame proven to win blocks), and the |
| 415 | /// Re-measured a third time at NATIVE resolution (`encode::tests:: |
| 416 | /// bd_rate_screen_native`, 1920x1024 crops, 12 frames, four quantizers, |
| 417 | /// BD-rate vs libaom / vs rav1e), because every earlier verdict was taken |
| 418 | /// on the 4x-downscaled gate (class `gate-recipe-confound`) and because |
| 419 | /// leaf compound and the distance-scaled search have landed since: |
| 420 | /// |
| 421 | /// | arm | film 1080p | film 2160p | screen | |
| 422 | /// |---|---|---|---| |
| 423 | /// | flat (no pyramid) | +18.7 / +1.4 | +48.1 / +19.8 | +59.4 / -10.0 | |
| 424 | /// | 4:-16:8 | +23.2 / +5.3 | +48.1 / +19.7 | +62.7 / -6.5 | |
| 425 | /// | 2:-16:8 | +24.9 / +6.9 | +46.9 / +19.5 | +69.0 / -3.8 | |
| 426 | /// | 8:-16:8 | +22.6 / +4.6 | +48.7 / +19.8 | +59.3 / -8.2 | |
| 427 | /// | 4:-24:12 (before the leaf-compound merge) | +24.3 / +6.3 | +48.5 / +20.2 | +67.2 / -3.7 | |
| 428 | /// |
| 429 | /// The confound was real -- at native the gap is 5 BD points, not 30 -- |
| 430 | /// but the sign is not: no arm beats flat on both films, every arm costs |
| 431 | /// 4-6 points on 1080p, and the best 2160p arm (`2:-16:8`, -1.1 vs |
| 432 | /// libaom) pays +10 on screen. So the pyramid still ships OFF. |
| 433 | /// |
| 434 | /// A native offset sweep on the 2160p clip alone (mini-GOP 4) says the |
| 435 | /// offsets are not what is missing -- the whole 3x3 grid spans 2.9 BD |
| 436 | /// points and none of it reaches flat's +48.1: |
| 437 | /// |
| 438 | /// | arf \ leaf | +4 | +8 | +12 | |
| 439 | /// |---|---|---|---| |
| 440 | /// | -8 | +48.9 / +20.4 | +49.2 / +20.1 | +50.2 / +20.5 | |
| 441 | /// | -16 | +47.8 / +20.0 | +48.1 / +19.7 | +49.2 / +20.2 | |
| 442 | /// | -24 | +47.3 / +20.0 | +47.6 / +19.7 | +48.5 / +20.2 | |
| 443 | /// |
| 444 | /// The gradient is monotone in both knobs (deeper ARF better, shallower |
| 445 | /// leaf better), which is the shape of a group whose leaves cannot cash |
| 446 | /// in the ARF's extra quality: what the leaves reach the hidden frame |
| 447 | /// with is still one forward search per reference. Shrinking the mini-GOP |
| 448 | /// helps for the same reason (2:-16:8 is the only arm that beats flat on |
| 449 | /// any clip, and it beats it on the clip with the fastest motion). |
| 450 | /// |
| 451 | /// quantizer offsets behave. Nothing selects the pyramid but an explicit |
| 452 | /// [`Av1Encoder::with_pyramid`] call (or `EC_AV1_PYRAMID` on the gate and |
| 453 | /// on `ec-bench`); the default one-in-one-out path is byte-identical to |
| 454 | /// before it existed. |
| 455 | fn default() -> Self { |
| 456 | Self { |
| 457 | mini_gop: 4, |
| 458 | arf_q_offset: -16, |
| 459 | leaf_q_offset: 8, |
| 460 | } |
| 461 | } |
| 462 | } |
| 463 | |
| 464 | /// Which level of the pyramid a coded frame sits at, reported on every |
| 465 | /// [`Packet`] so a caller (and the BD gate's histogram) can tell them apart |
| 466 | /// without parsing the frame headers back out. |
| 467 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 468 | pub enum Level { |
| 469 | /// A key frame. |
| 470 | Key, |
| 471 | /// A hidden `ALTREF_FRAME`, coded ahead of its display position. |
| 472 | Arf, |
| 473 | /// A shown leaf. |
| 474 | Leaf, |
| 475 | /// A `show_existing_frame` header re-outputting a hidden frame: no coded |
| 476 | /// pixels at all, four bits of header. |
| 477 | ShowExisting, |
| 478 | } |
| 479 | |
| 480 | /// The DPB slot the group anchors alternate between (see |
| 481 | /// [`Av1Encoder::encode_frames`]): the hidden frame of group `g` refreshes |
| 482 | /// `ANCHOR_SLOTS[(g + 1) % 2]`, which is the slot the leaves of group `g` |
| 483 | /// name as `ALTREF_FRAME` and which group `g + 1` reads as its own anchor. |
| 484 | /// Two slots alternate because a group's leaves must still be able to read |
| 485 | /// the previous anchor while the new one is already written. |
| 486 | const ANCHOR_SLOTS: [u8; 2] = [3, 4]; |
| 487 | |
| 488 | /// The slot the leaf chain refreshes and reads as `LAST_FRAME`. |
| 489 | const LEAF_SLOT: u8 = 0; |
| 490 | |
| 491 | /// The AV1 software encoder: [`EncoderConfig`] in, one [`Packet`] out per |
| 492 | /// [`Av1Encoder::encode`] call — or, with a [`Pyramid`] configured, a |
| 493 | /// coding-order burst of them per [`Av1Encoder::encode_frames`] call plus a |
| 494 | /// [`Av1Encoder::flush`] at the end of the stream. |
| 495 | #[derive(Debug)] |
| 496 | pub struct Av1Encoder { |
| 497 | config: EncoderConfig, |
| 498 | color_config: ColorConfig, |
| 499 | /// The previous picture's own (padded, uncropped) reconstruction — what |
| 500 | /// the next inter frame predicts from — or `None` right after a key |
| 501 | /// frame's turn comes up again, where it is about to be replaced rather |
| 502 | /// than read. |
| 503 | reference: Option<Picture>, |
| 504 | next_index: u64, |
| 505 | /// `Some` only when constructed via |
| 506 | /// [`Av1Encoder::with_rate_target`]`(_, RateTarget::BytesPerFrame(_))`; |
| 507 | /// otherwise every picture is coded at `config.base_q_idx`, unchanged |
| 508 | /// from before this field existed. |
| 509 | rate_loop: Option<RateLoop>, |
| 510 | /// This stream's decode-side per-frame state, owned here so `encode` |
| 511 | /// keeps the public signature it had before the state stopped being |
| 512 | /// thread-local. One per encoder, never per frame: several of its fields |
| 513 | /// (the inter-frame inheritance guards) carry state ACROSS frames. |
| 514 | fctx: crate::decode::FrameCtx, |
| 515 | /// What the last coded frame stored into the reference slot the next |
| 516 | /// inter frame reads (spec 7.20): the tables that frame's tile writer |
| 517 | /// must start from, since the header leaves |
| 518 | /// `disable_frame_end_update_cdf` off. `None` before the first frame. |
| 519 | carried_cdfs: Option<crate::encode::CdfSnapshot>, |
| 520 | /// The last key frame's own (padded) reconstruction: `GOLDEN_FRAME`, |
| 521 | /// which stays in DPB slot 1 until the next key frame refreshes it. |
| 522 | golden: Option<Picture>, |
| 523 | /// The frame two back: `ALTREF_FRAME`, in the slot the next frame is |
| 524 | /// about to refresh (`encode_inter_frame`'s 0/2 alternation). |
| 525 | prev2: Option<Picture>, |
| 526 | /// `Some` puts the encoder in pyramid mode: [`Av1Encoder::encode`] then |
| 527 | /// refuses (a picture no longer maps to one packet) and the state below |
| 528 | /// drives coding order. |
| 529 | pyramid: Option<Pyramid>, |
| 530 | /// The eight DPB slots, modelled exactly as the decoder does (spec 7.20): |
| 531 | /// what picture each holds, the order hint it was coded at, and the CDF |
| 532 | /// tables it stored. Only pyramid mode reads these; the flat path keeps |
| 533 | /// `reference`/`golden`/`prev2` so its bytes are unchanged. |
| 534 | dpb: [Option<DpbSlot>; 8], |
| 535 | /// Pictures held back waiting for their mini-GOP's hidden frame. |
| 536 | pending: Vec<(u64, Picture)>, |
| 537 | /// Which of [`ANCHOR_SLOTS`] the group about to be coded reads as its |
| 538 | /// anchor. |
| 539 | anchor: usize, |
| 540 | /// Coding-order position of the next packet — a packet's `dts`. |
| 541 | next_dts: u64, |
| 542 | } |
| 543 | |
| 544 | /// One decoded-picture-buffer slot: what a `refresh_frame_flags` bit stores |
| 545 | /// and what a `ref_frame_idx` entry reads back. |
| 546 | #[derive(Debug, Clone)] |
| 547 | struct DpbSlot { |
| 548 | picture: Picture, |
| 549 | order_hint: u32, |
| 550 | cdfs: crate::encode::CdfSnapshot, |
| 551 | } |
| 552 | |
| 553 | /// The encoder stays `Send` now that it owns a `FrameCtx` (whose cells are |
| 554 | /// `Send` but `!Sync`): it can move to another thread, it just cannot be |
| 555 | /// shared by reference across threads. |
| 556 | const _: fn() = || { |
| 557 | fn assert_send<T: Send>() {} |
| 558 | assert_send::<Av1Encoder>(); |
| 559 | }; |
| 560 | |
| 561 | impl Av1Encoder { |
| 562 | /// # Errors |
| 563 | /// Returns an error when `config.width`/`config.height` are zero, odd, |
| 564 | /// or larger than the 16-bit frame size an AV1 sequence header carries, |
| 565 | /// or when `config.gop` is zero (there would be no picture to code the |
| 566 | /// next key frame from a cadence of). |
| 567 | pub fn new(config: EncoderConfig) -> Result<Self> { |
| 568 | if config.gop == 0 { |
| 569 | return Err(Error::unsupported("AV1 encode", "gop must be at least 1")); |
| 570 | } |
| 571 | // Validate the geometry the same way the picture-level entry points |
| 572 | // do, before the first `encode()` call rather than only surfacing it |
| 573 | // then. |
| 574 | Picture::grey(config.width, config.height).check_even()?; |
| 575 | // A tile is a whole number of superblocks, so a frame cannot carry |
| 576 | // more tile columns (rows) than it has 64x64 superblocks across |
| 577 | // (down) -- the header's own `max_log2_tile_cols` bound (spec |
| 578 | // 5.9.15), refused here rather than at the first `encode()` call. |
| 579 | let sb_cols = config.width.div_ceil(64) as u32; |
| 580 | let sb_rows = config.height.div_ceil(64) as u32; |
| 581 | if (1u32 << config.tile_cols_log2) > sb_cols || (1u32 << config.tile_rows_log2) > sb_rows { |
| 582 | return Err(Error::unsupported( |
| 583 | "AV1 encode", |
| 584 | format!( |
| 585 | "{}x{} tiles need more than the {sb_cols}x{sb_rows} superblocks this frame has", |
| 586 | 1 << config.tile_cols_log2, |
| 587 | 1 << config.tile_rows_log2 |
| 588 | ), |
| 589 | )); |
| 590 | } |
| 591 | Ok(Self { |
| 592 | carried_cdfs: None, |
| 593 | golden: None, |
| 594 | prev2: None, |
| 595 | color_config: config.colour.color_config(), |
| 596 | config, |
| 597 | reference: None, |
| 598 | next_index: 0, |
| 599 | rate_loop: None, |
| 600 | fctx: crate::decode::FrameCtx::new(), |
| 601 | pyramid: None, |
| 602 | dpb: [const { None }; 8], |
| 603 | pending: Vec::new(), |
| 604 | anchor: 0, |
| 605 | next_dts: 0, |
| 606 | }) |
| 607 | } |
| 608 | |
| 609 | /// [`Av1Encoder::new`] in pyramid mode: pictures are coded out of display |
| 610 | /// order, so a call to [`Av1Encoder::encode_frames`] returns zero, one or |
| 611 | /// several packets and [`Av1Encoder::flush`] drains whatever is still |
| 612 | /// held at the end of the stream. [`Av1Encoder::encode`]'s one-in-one-out |
| 613 | /// contract cannot hold here and it returns an error instead; a caller |
| 614 | /// that wants the old shape simply does not call this constructor. |
| 615 | /// |
| 616 | /// # Errors |
| 617 | /// As [`Av1Encoder::new`], plus a `mini_gop` below 2 (no leaf would be |
| 618 | /// left between the anchor and the hidden frame) or above `config.gop` |
| 619 | /// (the group would straddle a key frame). |
| 620 | pub fn with_pyramid(config: EncoderConfig, pyramid: Pyramid) -> Result<Self> { |
| 621 | if pyramid.mini_gop < 2 { |
| 622 | return Err(Error::unsupported( |
| 623 | "AV1 encode", |
| 624 | "a pyramid mini-GOP is at least 2 pictures", |
| 625 | )); |
| 626 | } |
| 627 | let mut encoder = Self::new(config)?; |
| 628 | encoder.pyramid = Some(pyramid); |
| 629 | Ok(encoder) |
| 630 | } |
| 631 | |
| 632 | /// [`Av1Encoder::new`], but `rate` picks `base_q_idx` (or steers it, |
| 633 | /// frame by frame, for [`RateTarget::BytesPerFrame`]) instead of |
| 634 | /// `config.base_q_idx` being used as-is. |
| 635 | /// |
| 636 | /// # Errors |
| 637 | /// Same as [`Av1Encoder::new`]. |
| 638 | pub fn with_rate_target(mut config: EncoderConfig, rate: RateTarget) -> Result<Self> { |
| 639 | let rate_loop = rate.into_loop(&mut config, None); |
| 640 | let mut encoder = Self::new(config)?; |
| 641 | encoder.rate_loop = rate_loop; |
| 642 | Ok(encoder) |
| 643 | } |
| 644 | |
| 645 | /// [`Av1Encoder::with_pyramid`] and [`Av1Encoder::with_rate_target`] at |
| 646 | /// once: the rate loop then keeps a separate quantizer per pyramid level, |
| 647 | /// predicting each frame's size from the previous frame of its OWN level |
| 648 | /// (a leaf and a hidden `ALTREF` differ by several times in size, so one |
| 649 | /// shared predictor would swing the quantizer every frame). |
| 650 | /// |
| 651 | /// # Errors |
| 652 | /// As both. |
| 653 | pub fn with_pyramid_and_rate_target( |
| 654 | mut config: EncoderConfig, |
| 655 | pyramid: Pyramid, |
| 656 | rate: RateTarget, |
| 657 | ) -> Result<Self> { |
| 658 | let rate_loop = rate.into_loop(&mut config, Some(pyramid.mini_gop)); |
| 659 | let mut encoder = Self::with_pyramid(config, pyramid)?; |
| 660 | encoder.rate_loop = rate_loop; |
| 661 | Ok(encoder) |
| 662 | } |
| 663 | |
| 664 | /// The coded (padded-to-64) frame size every picture in this stream is |
| 665 | /// coded at — what a decoder allocates and what `ffprobe` reports. |
| 666 | #[must_use] |
| 667 | pub fn coded_size(&self) -> (usize, usize) { |
| 668 | ( |
| 669 | self.config.width.next_multiple_of(SUPERBLOCK), |
| 670 | self.config.height.next_multiple_of(SUPERBLOCK), |
| 671 | ) |
| 672 | } |
| 673 | |
| 674 | /// The display (render) size every frame header signals — [`EncoderConfig`]'s |
| 675 | /// own `width`/`height`, always, whatever the coded size pads it to. |
| 676 | #[must_use] |
| 677 | pub fn display_size(&self) -> (usize, usize) { |
| 678 | (self.config.width, self.config.height) |
| 679 | } |
| 680 | |
| 681 | /// Encodes one picture, key or inter by this stream's `gop` cadence, and |
| 682 | /// returns its packet — always exactly one, never held back for a later |
| 683 | /// call. |
| 684 | /// |
| 685 | /// # Errors |
| 686 | /// Returns an error when `picture`'s size does not match |
| 687 | /// [`EncoderConfig::width`]/[`EncoderConfig::height`], when the encoder |
| 688 | /// was built by [`Av1Encoder::with_pyramid`] (which reorders pictures, so |
| 689 | /// one call cannot return one packet), or under the same conditions |
| 690 | /// [`crate::encode::encode_key_frame`]/[`crate::encode::encode_sequence`] |
| 691 | /// do. |
| 692 | pub fn encode(&mut self, picture: &Picture) -> Result<Packet> { |
| 693 | if self.pyramid.is_some() { |
| 694 | return Err(Error::unsupported( |
| 695 | "AV1 encode", |
| 696 | "a pyramid stream reorders pictures -- use encode_frames()/flush()", |
| 697 | )); |
| 698 | } |
| 699 | let mut packets = self.encode_frames(picture)?; |
| 700 | Ok(packets.pop().expect("the flat path emits exactly one packet")) |
| 701 | } |
| 702 | |
| 703 | /// Encodes one picture and returns every packet it completed, in coding |
| 704 | /// order. Without a [`Pyramid`] that is always exactly one packet and |
| 705 | /// this is [`Av1Encoder::encode`] with a `Vec` around it; with one it is |
| 706 | /// empty for most pictures and a whole mini-GOP's worth (the hidden |
| 707 | /// frame, its leaves and the `show_existing_frame` that re-outputs it) |
| 708 | /// for the picture that closes a group. |
| 709 | /// |
| 710 | /// # Errors |
| 711 | /// As [`Av1Encoder::encode`], minus the pyramid refusal. |
| 712 | pub fn encode_frames(&mut self, picture: &Picture) -> Result<Vec<Packet>> { |
| 713 | crate::encode::arm_tiles(self.config.tile_cols_log2, self.config.tile_rows_log2); |
| 714 | if (picture.width, picture.height) != (self.config.width, self.config.height) { |
| 715 | return Err(Error::unsupported( |
| 716 | "AV1 encode", |
| 717 | format!( |
| 718 | "picture is {}x{}, encoder is {}x{}", |
| 719 | picture.width, picture.height, self.config.width, self.config.height |
| 720 | ), |
| 721 | )); |
| 722 | } |
| 723 | let Some(pyramid) = self.pyramid else { |
| 724 | return Ok(vec![self.encode_flat(picture)?]); |
| 725 | }; |
| 726 | let order = self.next_index; |
| 727 | self.next_index += 1; |
| 728 | if order.is_multiple_of(self.config.gop as u64) { |
| 729 | // A key frame closes whatever group is open (there is nothing for |
| 730 | // its leaves to point forward at across the boundary) and then |
| 731 | // restarts the pyramid from the key itself. |
| 732 | let mut packets = self.drain_pending()?; |
| 733 | packets.push(self.encode_key(order, picture)?); |
| 734 | return Ok(packets); |
| 735 | } |
| 736 | self.pending.push((order, picture.clone())); |
| 737 | // The group closes on its own size, or early when the next picture |
| 738 | // would be a key frame. |
| 739 | let next_is_key = (order + 1).is_multiple_of(self.config.gop as u64); |
| 740 | if self.pending.len() >= pyramid.mini_gop || next_is_key { |
| 741 | return self.drain_pending(); |
| 742 | } |
| 743 | Ok(Vec::new()) |
| 744 | } |
| 745 | |
| 746 | /// Codes and returns every picture still held back — the tail of a stream |
| 747 | /// whose last mini-GOP never filled up. Empty (and cheap) for a stream |
| 748 | /// with no [`Pyramid`], which never holds a picture at all. |
| 749 | /// |
| 750 | /// # Errors |
| 751 | /// As [`Av1Encoder::encode_frames`]. |
| 752 | pub fn flush(&mut self) -> Result<Vec<Packet>> { |
| 753 | crate::encode::arm_tiles(self.config.tile_cols_log2, self.config.tile_rows_log2); |
| 754 | self.drain_pending() |
| 755 | } |
| 756 | |
| 757 | /// The pre-pyramid path, byte for byte: one picture in, one packet out. |
| 758 | fn encode_flat(&mut self, picture: &Picture) -> Result<Packet> { |
| 759 | let render = (self.config.width, self.config.height); |
| 760 | let padded = picture.padded_to(SUPERBLOCK); |
| 761 | let is_key = self.next_index.is_multiple_of(self.config.gop as u64); |
| 762 | let order = self.next_index; |
| 763 | let base_q_idx = self.rate_loop.as_ref().map_or(self.config.base_q_idx, |r| { |
| 764 | r.q_idx(if is_key { Level::Key } else { Level::Leaf }) |
| 765 | }); |
| 766 | |
| 767 | let encoded: Encoded = if is_key { |
| 768 | encode_key_frame_inner( |
| 769 | &padded, |
| 770 | base_q_idx, |
| 771 | DEADZONE, |
| 772 | &KEY_FRAME_MODES, |
| 773 | split_blocks(), |
| 774 | render, |
| 775 | self.color_config, |
| 776 | &self.fctx, |
| 777 | )? |
| 778 | } else { |
| 779 | let reference = self.reference.as_ref().ok_or_else(|| { |
| 780 | Error::unsupported( |
| 781 | "AV1 encode", |
| 782 | "an inter frame needs a previous reconstruction", |
| 783 | ) |
| 784 | })?; |
| 785 | encode_inter_frame( |
| 786 | &padded, |
| 787 | reference, |
| 788 | base_q_idx, |
| 789 | DEADZONE, |
| 790 | order as u32, |
| 791 | // The flat path's own slot plan, in order hints: the key frame |
| 792 | // of the GOP this picture sits in is what `GOLDEN_FRAME` |
| 793 | // names, and every reference but `ALTREF_FRAME` is the frame |
| 794 | // just coded. |
| 795 | crate::encode::flat_order_hints( |
| 796 | order as u32 & 0x7f, |
| 797 | (order - order % self.config.gop as u64) as u32 & 0x7f, |
| 798 | self.prev2.is_some(), |
| 799 | ), |
| 800 | render, |
| 801 | self.carried_cdfs.as_ref().map(|c| &c.0), |
| 802 | self.golden.as_ref(), |
| 803 | self.prev2.as_ref(), |
| 804 | &self.fctx, |
| 805 | None, |
| 806 | )? |
| 807 | }; |
| 808 | |
| 809 | self.carried_cdfs = Some(encoded.next_cdfs.clone()); |
| 810 | if is_key { |
| 811 | self.golden = Some(encoded.reconstruction.clone()); |
| 812 | self.prev2 = None; |
| 813 | } else { |
| 814 | self.prev2 = self.reference.take(); |
| 815 | } |
| 816 | self.reference = Some(encoded.reconstruction.clone()); |
| 817 | self.next_index += 1; |
| 818 | let cropped = crop_encoded(&encoded, render.0, render.1); |
| 819 | let level = if is_key { Level::Key } else { Level::Leaf }; |
| 820 | if let Some(rate_loop) = self.rate_loop.as_mut() { |
| 821 | rate_loop.update(level, cropped.stream.len()); |
| 822 | } |
| 823 | Ok(self.packet(cropped.stream, is_key, order, level)) |
| 824 | } |
| 825 | |
| 826 | /// Stamps a packet with its display and coding positions and advances the |
| 827 | /// coding-order clock. |
| 828 | fn packet(&mut self, data: Vec<u8>, key: bool, order: u64, level: Level) -> Packet { |
| 829 | let dts = self.next_dts; |
| 830 | self.next_dts += 1; |
| 831 | Packet { |
| 832 | data, |
| 833 | key, |
| 834 | order, |
| 835 | dts, |
| 836 | level, |
| 837 | } |
| 838 | } |
| 839 | |
| 840 | /// Stores a coded frame into every DPB slot its `refresh_frame_flags` |
| 841 | /// names (spec 7.20). |
| 842 | fn refresh(&mut self, slots: &[u8], encoded: &Encoded, order_hint: u32) { |
| 843 | let slot = DpbSlot { |
| 844 | picture: encoded.reconstruction.clone(), |
| 845 | order_hint, |
| 846 | cdfs: encoded.next_cdfs.clone(), |
| 847 | }; |
| 848 | for &s in slots { |
| 849 | self.dpb[s as usize] = Some(slot.clone()); |
| 850 | } |
| 851 | } |
| 852 | |
| 853 | /// Codes a key frame in pyramid mode: it refreshes all eight slots, so it |
| 854 | /// becomes the anchor, the `GOLDEN_FRAME` and the CDF source for the |
| 855 | /// whole GOP at once. |
| 856 | fn encode_key(&mut self, order: u64, picture: &Picture) -> Result<Packet> { |
| 857 | let render = (self.config.width, self.config.height); |
| 858 | let base_q_idx = self |
| 859 | .rate_loop |
| 860 | .as_ref() |
| 861 | .map_or(self.config.base_q_idx, |r| r.q_idx(Level::Key)); |
| 862 | let encoded = encode_key_frame_inner( |
| 863 | &picture.padded_to(SUPERBLOCK), |
| 864 | base_q_idx, |
| 865 | DEADZONE, |
| 866 | &KEY_FRAME_MODES, |
| 867 | split_blocks(), |
| 868 | render, |
| 869 | self.color_config, |
| 870 | &self.fctx, |
| 871 | )?; |
| 872 | self.refresh(&[0, 1, 2, 3, 4, 5, 6, 7], &encoded, 0); |
| 873 | self.anchor = 0; |
| 874 | let cropped = crop_encoded(&encoded, render.0, render.1); |
| 875 | if let Some(rate_loop) = self.rate_loop.as_mut() { |
| 876 | rate_loop.update(Level::Key, cropped.stream.len()); |
| 877 | } |
| 878 | Ok(self.packet(cropped.stream, true, order, Level::Key)) |
| 879 | } |
| 880 | |
| 881 | /// Codes one inter frame at `order` from the DPB, in coding order. |
| 882 | #[allow(clippy::too_many_arguments)] |
| 883 | fn encode_pyramid_inter( |
| 884 | &mut self, |
| 885 | order: u64, |
| 886 | picture: &Picture, |
| 887 | last_slot: u8, |
| 888 | self_slot: u8, |
| 889 | altref_slot: u8, |
| 890 | show_frame: bool, |
| 891 | level: Level, |
| 892 | ) -> Result<Packet> { |
| 893 | let render = (self.config.width, self.config.height); |
| 894 | let order_hint = (order & 0x7f) as u32; |
| 895 | let pyramid = self.pyramid.expect("pyramid mode"); |
| 896 | let offset = match level { |
| 897 | Level::Arf => pyramid.arf_q_offset, |
| 898 | _ => pyramid.leaf_q_offset, |
| 899 | }; |
| 900 | let base = self |
| 901 | .rate_loop |
| 902 | .as_ref() |
| 903 | .map_or(i16::from(self.config.base_q_idx), |r| { |
| 904 | i16::from(r.q_idx(level)) |
| 905 | }); |
| 906 | let base_q_idx = (base + offset).clamp(1, 255) as u8; |
| 907 | // spec 5.9.2's `ref_frame_sign_bias`, derived from what the slots |
| 908 | // this frame names actually hold: a reference whose order hint is |
| 909 | // AHEAD of this frame's is backward-biased, and the MV stack scans |
| 910 | // (writer and decoder alike) flip borrowed candidates across the |
| 911 | // boundary. Only `ALTREF_FRAME` can be ahead here — the leaves of a |
| 912 | // mini-GOP name the group's hidden frame there. |
| 913 | let mut sign_bias = crate::mvstack::NO_SIGN_BIAS; |
| 914 | let ahead = |slot: u8, dpb: &[Option<DpbSlot>; 8]| { |
| 915 | dpb[slot as usize] |
| 916 | .as_ref() |
| 917 | .is_some_and(|s| s.order_hint > order_hint) |
| 918 | }; |
| 919 | let slots = [ |
| 920 | last_slot, last_slot, last_slot, GOLDEN_SLOT, last_slot, last_slot, altref_slot, |
| 921 | ]; |
| 922 | for (i, slot) in slots.into_iter().enumerate() { |
| 923 | sign_bias[i] = ahead(slot, &self.dpb); |
| 924 | } |
| 925 | // The same seven slots' order hints, for `skipModeAllowed` (spec |
| 926 | // 5.9.22) in the frame-header writer. |
| 927 | let order_hints: [u32; 7] = slots.map(|slot| { |
| 928 | self.dpb[slot as usize] |
| 929 | .as_ref() |
| 930 | .map_or(0, |s| (s.order_hint & 0x7f) as u32) |
| 931 | }); |
| 932 | let reference = self.dpb[last_slot as usize] |
| 933 | .as_ref() |
| 934 | .map(|s| s.picture.clone()) |
| 935 | .ok_or_else(|| { |
| 936 | Error::unsupported("AV1 encode", "an inter frame needs a previous reconstruction") |
| 937 | })?; |
| 938 | let golden = self.dpb[GOLDEN_SLOT as usize].as_ref().map(|s| s.picture.clone()); |
| 939 | let altref = (altref_slot != GOLDEN_SLOT) |
| 940 | .then(|| self.dpb[altref_slot as usize].as_ref().map(|s| s.picture.clone())) |
| 941 | .flatten(); |
| 942 | let start_cdfs = self.dpb[last_slot as usize].as_ref().map(|s| s.cdfs.0.clone()); |
| 943 | let encoded = || -> Result<Encoded> { encode_inter_frame( |
| 944 | &picture.padded_to(SUPERBLOCK), |
| 945 | &reference, |
| 946 | base_q_idx, |
| 947 | DEADZONE, |
| 948 | order_hint, |
| 949 | order_hints, |
| 950 | render, |
| 951 | start_cdfs.as_ref(), |
| 952 | golden.as_ref(), |
| 953 | altref.as_ref(), |
| 954 | &self.fctx, |
| 955 | Some(crate::encode::PyramidFrame { |
| 956 | last_slot, |
| 957 | self_slot, |
| 958 | altref_slot, |
| 959 | show_frame, |
| 960 | sign_bias, |
| 961 | }), |
| 962 | ) }(); |
| 963 | // Name the pyramid position in any failure: an error out of the tile |
| 964 | // writer or the filter search is otherwise indistinguishable between |
| 965 | // the hidden frame and the leaves that read it. |
| 966 | let encoded = encoded.map_err(|e| { |
| 967 | Error::unsupported( |
| 968 | "AV1 encode", |
| 969 | format!( |
| 970 | "{level:?} frame at order {order} (last slot {last_slot}, self {self_slot}, \ |
| 971 | altref {altref_slot}, shown {show_frame}, golden {}, altref pic {}): {e}", |
| 972 | golden.is_some(), |
| 973 | altref.is_some(), |
| 974 | ), |
| 975 | ) |
| 976 | })?; |
| 977 | self.refresh(&[self_slot], &encoded, order_hint); |
| 978 | let cropped = crop_encoded(&encoded, render.0, render.1); |
| 979 | if let Some(rate_loop) = self.rate_loop.as_mut() { |
| 980 | rate_loop.update(level, cropped.stream.len()); |
| 981 | } |
| 982 | Ok(self.packet(cropped.stream, false, order, level)) |
| 983 | } |
| 984 | |
| 985 | /// Codes the open mini-GOP: its hidden frame first, then its leaves, then |
| 986 | /// the `show_existing_frame` header that puts the hidden frame back in |
| 987 | /// display order. |
| 988 | fn drain_pending(&mut self) -> Result<Vec<Packet>> { |
| 989 | if self.pending.is_empty() { |
| 990 | return Ok(Vec::new()); |
| 991 | } |
| 992 | let group: Vec<(u64, Picture)> = std::mem::take(&mut self.pending); |
| 993 | let mut packets = Vec::with_capacity(group.len() + 1); |
| 994 | let anchor_slot = ANCHOR_SLOTS[self.anchor]; |
| 995 | let next_anchor_slot = ANCHOR_SLOTS[1 - self.anchor]; |
| 996 | let (arf_order, arf_picture) = group.last().cloned().expect("non-empty"); |
| 997 | if group.len() == 1 { |
| 998 | // Nothing to predict backward, so no hidden frame: one shown leaf |
| 999 | // that also becomes the next group's anchor. |
| 1000 | packets.push(self.encode_pyramid_inter( |
| 1001 | arf_order, |
| 1002 | &arf_picture, |
| 1003 | anchor_slot, |
| 1004 | next_anchor_slot, |
| 1005 | GOLDEN_SLOT, |
| 1006 | true, |
| 1007 | Level::Leaf, |
| 1008 | )?); |
| 1009 | self.anchor = 1 - self.anchor; |
| 1010 | return Ok(packets); |
| 1011 | } |
| 1012 | packets.push(self.encode_pyramid_inter( |
| 1013 | arf_order, |
| 1014 | &arf_picture, |
| 1015 | anchor_slot, |
| 1016 | next_anchor_slot, |
| 1017 | GOLDEN_SLOT, |
| 1018 | false, |
| 1019 | Level::Arf, |
| 1020 | )?); |
| 1021 | for (i, (order, picture)) in group[..group.len() - 1].iter().enumerate() { |
| 1022 | let last_slot = if i == 0 { anchor_slot } else { LEAF_SLOT }; |
| 1023 | packets.push(self.encode_pyramid_inter( |
| 1024 | *order, |
| 1025 | picture, |
| 1026 | last_slot, |
| 1027 | LEAF_SLOT, |
| 1028 | next_anchor_slot, |
| 1029 | true, |
| 1030 | Level::Leaf, |
| 1031 | )?); |
| 1032 | } |
| 1033 | let (seq, _) = crate::encode::key_frame_headers( |
| 1034 | self.config.width, |
| 1035 | self.config.height, |
| 1036 | self.config.base_q_idx, |
| 1037 | )?; |
| 1038 | let mut data = crate::obu::temporal_delimiter(); |
| 1039 | data.extend_from_slice(&crate::frame::show_existing_frame_obu( |
| 1040 | &seq, |
| 1041 | next_anchor_slot, |
| 1042 | )?); |
| 1043 | packets.push(self.packet(data, false, arf_order, Level::ShowExisting)); |
| 1044 | self.anchor = 1 - self.anchor; |
| 1045 | Ok(packets) |
| 1046 | } |
| 1047 | } |
| 1048 | |
| 1049 | #[cfg(test)] |
| 1050 | mod tests { |
| 1051 | use super::*; |
| 1052 | use std::process::{Command, Stdio}; |
| 1053 | |
| 1054 | /// Whether ffmpeg is on PATH. Absence normally SKIPs, but |
| 1055 | /// `EC_AV1_REQUIRE_FFMPEG=1` -- or `EC_AV1_REQUIRE_AOMENC=1`, since every |
| 1056 | /// aomenc gate decodes its stream through ffmpeg and is meaningless |
| 1057 | /// without it -- turns it into a hard failure. Without this the require |
| 1058 | /// flag was silently short-circuited: `!have_ffmpeg()` is evaluated first |
| 1059 | /// in `if !have_ffmpeg() || !have_aomenc()`, so a machine with no ffmpeg |
| 1060 | /// printed SKIP and reported green (class gate-skips-on-its-own-failure). |
| 1061 | fn have_ffmpeg() -> bool { |
| 1062 | let present = Command::new("ffmpeg") |
| 1063 | .arg("-version") |
| 1064 | .stdout(Stdio::null()) |
| 1065 | .stderr(Stdio::null()) |
| 1066 | .status() |
| 1067 | .is_ok_and(|s| s.success()); |
| 1068 | assert!( |
| 1069 | present |
| 1070 | || (std::env::var_os("EC_AV1_REQUIRE_FFMPEG").is_none() |
| 1071 | && std::env::var_os("EC_AV1_REQUIRE_AOMENC").is_none()), |
| 1072 | "EC_AV1_REQUIRE_FFMPEG/EC_AV1_REQUIRE_AOMENC is set but no working ffmpeg on PATH" |
| 1073 | ); |
| 1074 | present |
| 1075 | } |
| 1076 | |
| 1077 | fn test_card(width: usize, height: usize, shift: usize) -> Picture { |
| 1078 | let mut picture = Picture::grey(width, height); |
| 1079 | for y in 0..height { |
| 1080 | for x in 0..width { |
| 1081 | let sx = (x + shift) % width; |
| 1082 | picture.y[y * width + x] = ((sx * 3 + y * 5) % 256) as u16; |
| 1083 | } |
| 1084 | } |
| 1085 | for y in 0..height / 2 { |
| 1086 | for x in 0..width / 2 { |
| 1087 | let i = y * (width / 2) + x; |
| 1088 | picture.u[i] = ((100 + shift * 4) % 256) as u16; |
| 1089 | picture.v[i] = ((200 + 256 - shift * 2 % 256) % 256) as u16; |
| 1090 | } |
| 1091 | } |
| 1092 | picture |
| 1093 | } |
| 1094 | |
| 1095 | /// Every OBU stream this test writes to `ffmpeg`/`ffprobe`, concatenated |
| 1096 | /// in order. |
| 1097 | fn concat(packets: &[Packet]) -> Vec<u8> { |
| 1098 | packets.iter().flat_map(|p| p.data.clone()).collect() |
| 1099 | } |
| 1100 | |
| 1101 | /// One call to [`Av1Encoder::encode`] returns exactly one packet, always |
| 1102 | /// — the facade's whole "nothing held back" contract, checked without |
| 1103 | /// ffmpeg since it is a property of the return type, not the bytes. |
| 1104 | #[test] |
| 1105 | fn one_in_one_out() { |
| 1106 | let config = EncoderConfig { |
| 1107 | width: 64, |
| 1108 | height: 64, |
| 1109 | base_q_idx: 100, |
| 1110 | gop: 2, |
| 1111 | colour: Colour::Bt709Limited, |
| 1112 | tile_cols_log2: 0, |
| 1113 | tile_rows_log2: 0, |
| 1114 | }; |
| 1115 | let mut enc = Av1Encoder::new(config).unwrap(); |
| 1116 | for t in 0..5u64 { |
| 1117 | let packet = enc.encode(&test_card(64, 64, t as usize)).unwrap(); |
| 1118 | assert!(!packet.data.is_empty(), "picture {t}: empty packet"); |
| 1119 | assert_eq!(packet.order, t, "picture {t}: order"); |
| 1120 | } |
| 1121 | } |
| 1122 | |
| 1123 | /// A key frame every `gop` pictures, inter otherwise — checked against |
| 1124 | /// what the facade itself reports, and (below) against what `ffprobe` |
| 1125 | /// reads back out of the coded bytes. |
| 1126 | #[test] |
| 1127 | fn gop_cadence_is_honored() { |
| 1128 | let config = EncoderConfig { |
| 1129 | width: 64, |
| 1130 | height: 64, |
| 1131 | base_q_idx: 100, |
| 1132 | gop: 3, |
| 1133 | colour: Colour::Unspecified, |
| 1134 | tile_cols_log2: 0, |
| 1135 | tile_rows_log2: 0, |
| 1136 | }; |
| 1137 | let mut enc = Av1Encoder::new(config).unwrap(); |
| 1138 | let keys: Vec<bool> = (0..7) |
| 1139 | .map(|t| enc.encode(&test_card(64, 64, t)).unwrap().key) |
| 1140 | .collect(); |
| 1141 | assert_eq!(keys, vec![true, false, false, true, false, false, true]); |
| 1142 | } |
| 1143 | |
| 1144 | fn ffprobe_frames(stream: &[u8]) -> Vec<(bool, u32, u32)> { |
| 1145 | let path = std::env::temp_dir().join(format!( |
| 1146 | "ec-av1-facade-probe-{}-{}.obu", |
| 1147 | std::process::id(), |
| 1148 | std::ptr::addr_of!(stream) as usize |
| 1149 | )); |
| 1150 | std::fs::write(&path, stream).expect("writing the probe stream"); |
| 1151 | let out = Command::new("ffprobe") |
| 1152 | .args([ |
| 1153 | "-v", |
| 1154 | "error", |
| 1155 | "-f", |
| 1156 | "obu", |
| 1157 | "-select_streams", |
| 1158 | "v:0", |
| 1159 | "-show_entries", |
| 1160 | "frame=key_frame,width,height", |
| 1161 | "-of", |
| 1162 | "csv=p=0", |
| 1163 | ]) |
| 1164 | .arg(&path) |
| 1165 | .output() |
| 1166 | .expect("ffprobe failed to run"); |
| 1167 | let _ = std::fs::remove_file(&path); |
| 1168 | assert!( |
| 1169 | out.status.success(), |
| 1170 | "ffprobe refused the stream: {}", |
| 1171 | String::from_utf8_lossy(&out.stderr) |
| 1172 | ); |
| 1173 | String::from_utf8_lossy(&out.stdout) |
| 1174 | .lines() |
| 1175 | .map(|line| { |
| 1176 | let mut f = line.trim().split(','); |
| 1177 | let key: u32 = f.next().unwrap().parse().unwrap(); |
| 1178 | let width: u32 = f.next().unwrap().parse().unwrap(); |
| 1179 | let height: u32 = f.next().unwrap().parse().unwrap(); |
| 1180 | (key == 1, width, height) |
| 1181 | }) |
| 1182 | .collect() |
| 1183 | } |
| 1184 | |
| 1185 | fn ffprobe_colour(stream: &[u8]) -> String { |
| 1186 | let path = std::env::temp_dir().join(format!( |
| 1187 | "ec-av1-facade-colour-probe-{}-{}.obu", |
| 1188 | std::process::id(), |
| 1189 | std::ptr::addr_of!(stream) as usize |
| 1190 | )); |
| 1191 | std::fs::write(&path, stream).expect("writing the probe stream"); |
| 1192 | let out = Command::new("ffprobe") |
| 1193 | .args([ |
| 1194 | "-v", |
| 1195 | "error", |
| 1196 | "-f", |
| 1197 | "obu", |
| 1198 | "-select_streams", |
| 1199 | "v:0", |
| 1200 | "-show_entries", |
| 1201 | "stream=color_primaries,color_transfer,color_space,color_range", |
| 1202 | "-of", |
| 1203 | "csv=p=0", |
| 1204 | ]) |
| 1205 | .arg(&path) |
| 1206 | .output() |
| 1207 | .expect("ffprobe failed to run"); |
| 1208 | let _ = std::fs::remove_file(&path); |
| 1209 | assert!( |
| 1210 | out.status.success(), |
| 1211 | "ffprobe refused the stream: {}", |
| 1212 | String::from_utf8_lossy(&out.stderr) |
| 1213 | ); |
| 1214 | String::from_utf8_lossy(&out.stdout).trim().to_string() |
| 1215 | } |
| 1216 | |
| 1217 | /// A 30-picture stream at gop 15 codes 2 key frames (pictures 0 and 15) |
| 1218 | /// and 28 inter ones, at an odd-ish (not superblock-multiple) size that |
| 1219 | /// exercises the pad/crop path -- `ffprobe`'s own `key_frame` flags and |
| 1220 | /// coded size confirm what the facade already reported. |
| 1221 | #[test] |
| 1222 | fn thirty_pictures_at_gop_fifteen_decode_to_two_key_frames() { |
| 1223 | if !have_ffmpeg() { |
| 1224 | eprintln!("SKIP thirty_pictures_at_gop_fifteen_decode_to_two_key_frames: no ffmpeg"); |
| 1225 | return; |
| 1226 | } |
| 1227 | let (width, height) = (96usize, 96usize); |
| 1228 | let config = EncoderConfig { |
| 1229 | width, |
| 1230 | height, |
| 1231 | base_q_idx: 120, |
| 1232 | gop: 15, |
| 1233 | colour: Colour::Bt709Limited, |
| 1234 | tile_cols_log2: 0, |
| 1235 | tile_rows_log2: 0, |
| 1236 | }; |
| 1237 | let mut enc = Av1Encoder::new(config).unwrap(); |
| 1238 | assert_eq!(enc.display_size(), (width, height)); |
| 1239 | let (coded_w, coded_h) = enc.coded_size(); |
| 1240 | assert_eq!( |
| 1241 | (coded_w, coded_h), |
| 1242 | ( |
| 1243 | width.next_multiple_of(SUPERBLOCK), |
| 1244 | height.next_multiple_of(SUPERBLOCK) |
| 1245 | ) |
| 1246 | ); |
| 1247 | |
| 1248 | let packets: Vec<Packet> = (0..30) |
| 1249 | .map(|t| enc.encode(&test_card(width, height, t)).unwrap()) |
| 1250 | .collect(); |
| 1251 | let expect_key: Vec<bool> = (0..30).map(|t| t % 15 == 0).collect(); |
| 1252 | assert_eq!( |
| 1253 | packets.iter().map(|p| p.key).collect::<Vec<_>>(), |
| 1254 | expect_key, |
| 1255 | "facade's own key/inter flags" |
| 1256 | ); |
| 1257 | |
| 1258 | let stream = concat(&packets); |
| 1259 | let frames = ffprobe_frames(&stream); |
| 1260 | assert_eq!(frames.len(), 30, "ffprobe frame count"); |
| 1261 | for (t, (key, w, h)) in frames.iter().enumerate() { |
| 1262 | assert_eq!(*key, expect_key[t], "picture {t}: ffprobe key_frame flag"); |
| 1263 | assert_eq!( |
| 1264 | (*w, *h), |
| 1265 | (width as u32, height as u32), |
| 1266 | "picture {t}: ffprobe reports the true (display) size, not the padded coded one" |
| 1267 | ); |
| 1268 | } |
| 1269 | } |
| 1270 | |
| 1271 | /// The configured colour properties are what `ffprobe` reports back, |
| 1272 | /// spec 5.5.2's CICP triple plus range -- BT.709 limited here, since it |
| 1273 | /// is the default a player assumes and the one this test would silently |
| 1274 | /// pass without wiring for (`ffprobe` reports "unknown" for the |
| 1275 | /// hardcoded "unspecified" this crate wrote before the facade existed, |
| 1276 | /// which is a visibly different string). |
| 1277 | #[test] |
| 1278 | fn bt709_limited_colour_is_reported_by_ffprobe() { |
| 1279 | if !have_ffmpeg() { |
| 1280 | eprintln!("SKIP bt709_limited_colour_is_reported_by_ffprobe: no ffmpeg"); |
| 1281 | return; |
| 1282 | } |
| 1283 | let config = EncoderConfig { |
| 1284 | width: 64, |
| 1285 | height: 64, |
| 1286 | base_q_idx: 100, |
| 1287 | gop: 4, |
| 1288 | colour: Colour::Bt709Limited, |
| 1289 | tile_cols_log2: 0, |
| 1290 | tile_rows_log2: 0, |
| 1291 | }; |
| 1292 | let mut enc = Av1Encoder::new(config).unwrap(); |
| 1293 | let packet = enc.encode(&test_card(64, 64, 0)).unwrap(); |
| 1294 | let colour = ffprobe_colour(&packet.data); |
| 1295 | assert_eq!(colour, "tv,bt709,bt709,bt709", "ffprobe colour fields"); |
| 1296 | } |
| 1297 | |
| 1298 | /// The same, for BT.601: a different set of CICP integers must produce a |
| 1299 | /// different string, or the wiring could be a no-op that happens to read |
| 1300 | /// as BT.709 for every input. |
| 1301 | #[test] |
| 1302 | fn bt601_limited_colour_is_reported_by_ffprobe() { |
| 1303 | if !have_ffmpeg() { |
| 1304 | eprintln!("SKIP bt601_limited_colour_is_reported_by_ffprobe: no ffmpeg"); |
| 1305 | return; |
| 1306 | } |
| 1307 | let config = EncoderConfig { |
| 1308 | width: 64, |
| 1309 | height: 64, |
| 1310 | base_q_idx: 100, |
| 1311 | gop: 4, |
| 1312 | colour: Colour::Bt601Limited, |
| 1313 | tile_cols_log2: 0, |
| 1314 | tile_rows_log2: 0, |
| 1315 | }; |
| 1316 | let mut enc = Av1Encoder::new(config).unwrap(); |
| 1317 | let packet = enc.encode(&test_card(64, 64, 0)).unwrap(); |
| 1318 | let colour = ffprobe_colour(&packet.data); |
| 1319 | assert_eq!( |
| 1320 | colour, "tv,smpte170m,smpte170m,smpte170m", |
| 1321 | "ffprobe colour fields" |
| 1322 | ); |
| 1323 | } |
| 1324 | |
| 1325 | /// A frame whose size does not match the encoder's configured geometry |
| 1326 | /// is refused by name. |
| 1327 | #[test] |
| 1328 | fn geometry_mismatch_is_refused() { |
| 1329 | let config = EncoderConfig { |
| 1330 | width: 64, |
| 1331 | height: 64, |
| 1332 | base_q_idx: 100, |
| 1333 | gop: 4, |
| 1334 | colour: Colour::Bt709Limited, |
| 1335 | tile_cols_log2: 0, |
| 1336 | tile_rows_log2: 0, |
| 1337 | }; |
| 1338 | let mut enc = Av1Encoder::new(config).unwrap(); |
| 1339 | let err = enc.encode(&Picture::grey(32, 32)).unwrap_err(); |
| 1340 | assert!(err.to_string().contains("64x64"), "{err}"); |
| 1341 | } |
| 1342 | |
| 1343 | /// `gop == 0` is refused at construction, not the first `encode()` call. |
| 1344 | #[test] |
| 1345 | fn zero_gop_is_refused() { |
| 1346 | let config = EncoderConfig { |
| 1347 | width: 64, |
| 1348 | height: 64, |
| 1349 | base_q_idx: 100, |
| 1350 | gop: 0, |
| 1351 | colour: Colour::Bt709Limited, |
| 1352 | tile_cols_log2: 0, |
| 1353 | tile_rows_log2: 0, |
| 1354 | }; |
| 1355 | let err = Av1Encoder::new(config).unwrap_err(); |
| 1356 | assert!(err.to_string().contains("gop"), "{err}"); |
| 1357 | } |
| 1358 | |
| 1359 | /// The 12-frame real clip `real_clip_encodes_within_its_quality_and_size_budget` |
| 1360 | /// already gates on at `q=100` (`crates/ec-av1/src/encode.rs`), decoded down |
| 1361 | /// to this facade's own input size, and re-coded through the facade so the |
| 1362 | /// rate-target surface is exercised at the entry point a caller actually |
| 1363 | /// drives. |
| 1364 | fn h264_clip_frames(width: usize, height: usize, frames: usize) -> Option<Vec<Picture>> { |
| 1365 | if !have_ffmpeg() { |
| 1366 | return None; |
| 1367 | } |
| 1368 | let clip = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) |
| 1369 | .join("../../fixtures/video/h264-1080p-23.976-8bit.mp4"); |
| 1370 | if !clip.exists() { |
| 1371 | return None; |
| 1372 | } |
| 1373 | let out = Command::new("ffmpeg") |
| 1374 | .args(["-v", "error", "-i", clip.to_str().unwrap()]) |
| 1375 | .args(["-frames:v", &frames.to_string()]) |
| 1376 | .args(["-vf", &format!("scale={width}:{height}")]) |
| 1377 | .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"]) |
| 1378 | .output() |
| 1379 | .expect("ffmpeg failed to run"); |
| 1380 | assert!( |
| 1381 | out.status.success(), |
| 1382 | "{}", |
| 1383 | String::from_utf8_lossy(&out.stderr) |
| 1384 | ); |
| 1385 | let (luma, chroma) = (width * height, width * height / 4); |
| 1386 | let frame_len = luma + 2 * chroma; |
| 1387 | assert_eq!( |
| 1388 | out.stdout.len(), |
| 1389 | frame_len * frames, |
| 1390 | "expected {frames} 4:2:0 frames" |
| 1391 | ); |
| 1392 | Some( |
| 1393 | (0..frames) |
| 1394 | .map(|i| { |
| 1395 | let bytes = &out.stdout[i * frame_len..][..frame_len]; |
| 1396 | Picture { |
| 1397 | width, |
| 1398 | height, |
| 1399 | y: bytes[..luma].iter().map(|&v| u16::from(v)).collect(), |
| 1400 | u: bytes[luma..luma + chroma].iter().map(|&v| u16::from(v)).collect(), |
| 1401 | v: bytes[luma + chroma..].iter().map(|&v| u16::from(v)).collect(), |
| 1402 | } |
| 1403 | }) |
| 1404 | .collect(), |
| 1405 | ) |
| 1406 | } |
| 1407 | |
| 1408 | /// [`RateTarget::BytesPerFrame`] on a real, 24-frame clip lands its total |
| 1409 | /// coded size within ±20% of `frames * target` once the first few |
| 1410 | /// frames' settling has been discarded (the key frame's own reference |
| 1411 | /// state and the controller's first couple of steps). |
| 1412 | #[test] |
| 1413 | fn bytes_per_frame_target_settles_within_20_percent() { |
| 1414 | let Some(pictures) = h264_clip_frames(640, 384, 24) else { |
| 1415 | eprintln!("SKIP bytes_per_frame_target_settles_within_20_percent: no ffmpeg/fixture"); |
| 1416 | return; |
| 1417 | }; |
| 1418 | let target_bytes = 4_000u32; |
| 1419 | let config = EncoderConfig { |
| 1420 | width: 640, |
| 1421 | height: 384, |
| 1422 | base_q_idx: 100, |
| 1423 | gop: 24, |
| 1424 | colour: Colour::Bt709Limited, |
| 1425 | tile_cols_log2: 0, |
| 1426 | tile_rows_log2: 0, |
| 1427 | }; |
| 1428 | let mut enc = |
| 1429 | Av1Encoder::with_rate_target(config, RateTarget::BytesPerFrame(target_bytes)).unwrap(); |
| 1430 | let sizes: Vec<usize> = pictures |
| 1431 | .iter() |
| 1432 | .map(|p| enc.encode(p).unwrap().data.len()) |
| 1433 | .collect(); |
| 1434 | // Discard the key frame (always far larger than an inter target) and |
| 1435 | // the next 4 inter frames the loop needs to step toward it. |
| 1436 | let settled = &sizes[5..]; |
| 1437 | let mean = settled.iter().sum::<usize>() as f64 / settled.len() as f64; |
| 1438 | let low = f64::from(target_bytes) * 0.8; |
| 1439 | let high = f64::from(target_bytes) * 1.2; |
| 1440 | assert!( |
| 1441 | mean >= low && mean <= high, |
| 1442 | "settled mean {mean:.0} bytes/frame outside ±20% of {target_bytes} ({low:.0}..{high:.0}); sizes={sizes:?}" |
| 1443 | ); |
| 1444 | } |
| 1445 | |
| 1446 | /// [`RateTarget::Bitrate`] lands the achieved bitrate within ±10% of the |
| 1447 | /// target over 48 frames of a real clip, flat and under a pyramid alike. |
| 1448 | /// This is the accuracy claim of the target-bitrate mode: no two-pass, no |
| 1449 | /// lookahead, just each frame's size predicted from the previous frame of |
| 1450 | /// its own level and one clamped proportional step. |
| 1451 | #[test] |
| 1452 | fn bitrate_target_lands_within_10_percent_over_48_frames() { |
| 1453 | let (width, height, frames) = (640usize, 384usize, 48usize); |
| 1454 | let Some(pictures) = h264_clip_frames(width, height, frames) else { |
| 1455 | eprintln!("SKIP bitrate_target_lands_within_10_percent_over_48_frames: no ffmpeg/fixture"); |
| 1456 | return; |
| 1457 | }; |
| 1458 | let fps = 24.0; |
| 1459 | for bits_per_second in [768_000u32, 1_536_000] { |
| 1460 | let config = EncoderConfig { |
| 1461 | width, |
| 1462 | height, |
| 1463 | base_q_idx: 100, |
| 1464 | gop: frames, |
| 1465 | colour: Colour::Bt709Limited, |
| 1466 | tile_cols_log2: 0, |
| 1467 | tile_rows_log2: 0, |
| 1468 | }; |
| 1469 | let rate = RateTarget::Bitrate { |
| 1470 | bits_per_second, |
| 1471 | frames_per_second: fps, |
| 1472 | }; |
| 1473 | for pyramid in [None, Some(Pyramid::default())] { |
| 1474 | let mut enc = match pyramid { |
| 1475 | None => Av1Encoder::with_rate_target(config, rate).unwrap(), |
| 1476 | Some(p) => Av1Encoder::with_pyramid_and_rate_target(config, p, rate).unwrap(), |
| 1477 | }; |
| 1478 | let mut coded = 0usize; |
| 1479 | for picture in &pictures { |
| 1480 | for packet in enc.encode_frames(picture).unwrap() { |
| 1481 | coded += packet.data.len(); |
| 1482 | } |
| 1483 | } |
| 1484 | for packet in enc.flush().unwrap() { |
| 1485 | coded += packet.data.len(); |
| 1486 | } |
| 1487 | let seconds = frames as f64 / fps; |
| 1488 | let achieved = coded as f64 * 8.0 / seconds; |
| 1489 | let error = achieved / f64::from(bits_per_second) - 1.0; |
| 1490 | eprintln!( |
| 1491 | "bitrate {bits_per_second} bps, pyramid {}: {coded} bytes over {seconds:.2}s \ |
| 1492 | = {achieved:.0} bps ({:+.1}%)", |
| 1493 | pyramid.is_some(), |
| 1494 | 100.0 * error, |
| 1495 | ); |
| 1496 | assert!( |
| 1497 | error.abs() <= 0.10, |
| 1498 | "achieved {achieved:.0} bps is {:+.1}% off the {bits_per_second} bps target \ |
| 1499 | (pyramid {})", |
| 1500 | 100.0 * error, |
| 1501 | pyramid.is_some(), |
| 1502 | ); |
| 1503 | } |
| 1504 | } |
| 1505 | } |
| 1506 | |
| 1507 | /// The `BytesPerFrame` controller's own windup bound: no frame's coded |
| 1508 | /// `base_q_idx` step exceeds [`RateLoop::STEP_CLAMP`], across a real |
| 1509 | /// clip's full range of content (so a scene cut can't be the one frame |
| 1510 | /// that breaks the bound). |
| 1511 | #[test] |
| 1512 | fn bytes_per_frame_controller_never_oscillates_past_its_clamp() { |
| 1513 | let Some(pictures) = h264_clip_frames(640, 384, 24) else { |
| 1514 | eprintln!( |
| 1515 | "SKIP bytes_per_frame_controller_never_oscillates_past_its_clamp: no ffmpeg/fixture" |
| 1516 | ); |
| 1517 | return; |
| 1518 | }; |
| 1519 | let config = EncoderConfig { |
| 1520 | width: 640, |
| 1521 | height: 384, |
| 1522 | base_q_idx: 100, |
| 1523 | gop: 24, |
| 1524 | colour: Colour::Bt709Limited, |
| 1525 | tile_cols_log2: 0, |
| 1526 | tile_rows_log2: 0, |
| 1527 | }; |
| 1528 | let mut enc = |
| 1529 | Av1Encoder::with_rate_target(config, RateTarget::BytesPerFrame(4_000)).unwrap(); |
| 1530 | let mut prev_q = enc.rate_loop.as_ref().unwrap().q_idx(Level::Leaf); |
| 1531 | for picture in &pictures { |
| 1532 | enc.encode(picture).unwrap(); |
| 1533 | let q = enc.rate_loop.as_ref().unwrap().q_idx(Level::Leaf); |
| 1534 | let step = (i32::from(q) - i32::from(prev_q)).abs(); |
| 1535 | assert!( |
| 1536 | f64::from(step) <= RateLoop::STEP_CLAMP + 1.0, // +1 for u8 rounding |
| 1537 | "q stepped from {prev_q} to {q}, past the {} clamp", |
| 1538 | RateLoop::STEP_CLAMP |
| 1539 | ); |
| 1540 | prev_q = q; |
| 1541 | } |
| 1542 | } |
| 1543 | |
| 1544 | fn psnr(a: &[u16], b: &[u16]) -> f64 { |
| 1545 | let squared: f64 = a |
| 1546 | .iter() |
| 1547 | .zip(b) |
| 1548 | .map(|(&x, &y)| { |
| 1549 | let d = f64::from(x) - f64::from(y); |
| 1550 | d * d |
| 1551 | }) |
| 1552 | .sum(); |
| 1553 | if squared == 0.0 { |
| 1554 | return f64::INFINITY; |
| 1555 | } |
| 1556 | 10.0 * (255.0 * 255.0 * a.len() as f64 / squared).log10() |
| 1557 | } |
| 1558 | |
| 1559 | /// Decodes an OBU stream back to raw luma planes via `ffmpeg`/dav1d, one |
| 1560 | /// entry per coded frame, in order — this facade's own equivalent of |
| 1561 | /// `encode::tests::ffmpeg_decode_sequence`, needed here too since a |
| 1562 | /// PSNR check needs the decoded pixels, not just the coded byte count. |
| 1563 | fn ffmpeg_decode_luma(stream: &[u8], width: usize, height: usize) -> Vec<Vec<u8>> { |
| 1564 | let path = std::env::temp_dir().join(format!( |
| 1565 | "ec-av1-facade-rate-decode-{}-{}.obu", |
| 1566 | std::process::id(), |
| 1567 | std::ptr::addr_of!(stream) as usize |
| 1568 | )); |
| 1569 | std::fs::write(&path, stream).expect("writing the decode probe stream"); |
| 1570 | let out = Command::new("ffmpeg") |
| 1571 | .args(["-v", "error", "-f", "obu", "-i"]) |
| 1572 | .arg(&path) |
| 1573 | .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"]) |
| 1574 | .output() |
| 1575 | .expect("ffmpeg failed to run"); |
| 1576 | let _ = std::fs::remove_file(&path); |
| 1577 | assert!( |
| 1578 | out.status.success(), |
| 1579 | "{}", |
| 1580 | String::from_utf8_lossy(&out.stderr) |
| 1581 | ); |
| 1582 | let (luma, chroma) = (width * height, width * height / 4); |
| 1583 | let frame_len = luma + 2 * chroma; |
| 1584 | out.stdout |
| 1585 | .chunks_exact(frame_len) |
| 1586 | .map(|f| f[..luma].to_vec()) |
| 1587 | .collect() |
| 1588 | } |
| 1589 | |
| 1590 | /// A pyramid stream reorders pictures: the hidden `ALTREF` of each |
| 1591 | /// mini-GOP is coded before the leaves that precede it in display order, |
| 1592 | /// and a `show_existing_frame` header puts it back. This pins the shape |
| 1593 | /// (one packet per source picture plus one `show_existing_frame` per |
| 1594 | /// group, `dts` monotone, `order` NOT monotone) and then decodes the |
| 1595 | /// whole stream through OUR decoder and through ffmpeg/dav1d and requires |
| 1596 | /// the two display-order outputs to agree sample for sample — the |
| 1597 | /// [[gate-blind-to-hidden-frames]] check: a hidden frame that is never |
| 1598 | /// output, or output twice, or output in the wrong position, changes the |
| 1599 | /// display-order list and fails here. |
| 1600 | #[test] |
| 1601 | fn a_pyramid_stream_decodes_in_display_order_through_both_decoders() { |
| 1602 | let (width, height) = (128usize, 128usize); |
| 1603 | let config = EncoderConfig { |
| 1604 | width, |
| 1605 | height, |
| 1606 | base_q_idx: 120, |
| 1607 | gop: 32, |
| 1608 | colour: Colour::Bt709Limited, |
| 1609 | tile_cols_log2: 0, |
| 1610 | tile_rows_log2: 0, |
| 1611 | }; |
| 1612 | let pyramid = Pyramid { |
| 1613 | mini_gop: 4, |
| 1614 | ..Pyramid::default() |
| 1615 | }; |
| 1616 | let mut enc = Av1Encoder::with_pyramid(config, pyramid).unwrap(); |
| 1617 | let sources: Vec<Picture> = (0..9).map(|t| test_card(width, height, t * 3)).collect(); |
| 1618 | let _ = crate::encode::take_ref_frame_hits(); |
| 1619 | let mut packets = Vec::new(); |
| 1620 | for picture in &sources { |
| 1621 | packets.extend(enc.encode_frames(picture).unwrap()); |
| 1622 | } |
| 1623 | packets.extend(enc.flush().unwrap()); |
| 1624 | |
| 1625 | // Shape: every source picture is coded exactly once, and each closed |
| 1626 | // group adds one `show_existing_frame` packet. |
| 1627 | let coded: Vec<u64> = packets |
| 1628 | .iter() |
| 1629 | .filter(|p| p.level != Level::ShowExisting) |
| 1630 | .map(|p| p.order) |
| 1631 | .collect(); |
| 1632 | let mut sorted = coded.clone(); |
| 1633 | sorted.sort_unstable(); |
| 1634 | assert_eq!(sorted, (0..9).collect::<Vec<u64>>(), "one packet per picture"); |
| 1635 | assert_ne!(coded, sorted, "the pyramid never reordered anything"); |
| 1636 | let shown = packets.iter().filter(|p| p.level == Level::ShowExisting).count(); |
| 1637 | assert_eq!(shown, 2, "one show_existing_frame per closed mini-GOP"); |
| 1638 | for (i, p) in packets.iter().enumerate() { |
| 1639 | assert_eq!(p.dts, i as u64, "packet {i}: dts is the coding position"); |
| 1640 | } |
| 1641 | let hist = |l: Level| packets.iter().filter(|p| p.level == l).count(); |
| 1642 | eprintln!( |
| 1643 | "pyramid levels: key {} arf {} leaf {} show_existing {}", |
| 1644 | hist(Level::Key), |
| 1645 | hist(Level::Arf), |
| 1646 | hist(Level::Leaf), |
| 1647 | hist(Level::ShowExisting), |
| 1648 | ); |
| 1649 | assert_eq!(hist(Level::Arf), 2, "two hidden frames"); |
| 1650 | let refs = crate::encode::take_ref_frame_hits(); |
| 1651 | eprintln!( |
| 1652 | "blocks per reference: LAST {} GOLDEN {} ALTREF {}", |
| 1653 | refs[crate::mvstack::LAST_FRAME as usize], |
| 1654 | refs[crate::mvstack::GOLDEN_FRAME as usize], |
| 1655 | refs[crate::mvstack::ALTREF_FRAME as usize], |
| 1656 | ); |
| 1657 | // [[gate-blind-to-feature]]: the whole point of the hidden frame is |
| 1658 | // that the leaves predict BACKWARD off it, which is also the only |
| 1659 | // thing that exercises `ref_frame_sign_bias` in the MV stack. A green |
| 1660 | // round trip in which `ALTREF_FRAME` never won a block would prove |
| 1661 | // only that a hidden frame can be written and re-output. |
| 1662 | assert!( |
| 1663 | refs[crate::mvstack::ALTREF_FRAME as usize] > 0, |
| 1664 | "no block predicted off the hidden ALTREF" |
| 1665 | ); |
| 1666 | |
| 1667 | let stream = concat(&packets); |
| 1668 | let ours = crate::stream::decode_stream(&stream).expect("our decoder"); |
| 1669 | assert_eq!(ours.len(), sources.len(), "our decoder's display-order count"); |
| 1670 | if !have_ffmpeg() { |
| 1671 | eprintln!("SKIP the ffmpeg half of the pyramid round trip: no ffmpeg"); |
| 1672 | return; |
| 1673 | } |
| 1674 | let theirs = ffmpeg_decode_luma(&stream, width, height); |
| 1675 | assert_eq!(theirs.len(), sources.len(), "ffmpeg's display-order count"); |
| 1676 | for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() { |
| 1677 | let got: Vec<u8> = a.y.iter().map(|&v| v as u8).collect(); |
| 1678 | assert_eq!(got.len(), b.len(), "frame {i}: luma size"); |
| 1679 | if let Some(at) = got.iter().zip(b).position(|(x, y)| x != y) { |
| 1680 | panic!( |
| 1681 | "display frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}", |
| 1682 | at % width, |
| 1683 | at / width, |
| 1684 | got[at], |
| 1685 | b[at], |
| 1686 | ); |
| 1687 | } |
| 1688 | } |
| 1689 | } |
| 1690 | |
| 1691 | /// Every tile layout this encoder can write decodes SAMPLE-EXACT |
| 1692 | /// through both decoders -- ours and ffmpeg's -- and the frames really |
| 1693 | /// carry the tiles the header claims (the OBU parser locates one payload |
| 1694 | /// per tile, so a stream that quietly stayed single-tile fails here |
| 1695 | /// rather than passing on a green round trip). |
| 1696 | /// |
| 1697 | /// The bytes are what the gate is on: an encoder that clipped its |
| 1698 | /// neighbour availability wrong writes a stream whose two decoders agree |
| 1699 | /// with each other and disagree with nothing -- so the ffmpeg half is |
| 1700 | /// the one that catches a tile boundary the writer respected and the |
| 1701 | /// spec does not, and the parser half catches the reverse. |
| 1702 | #[test] |
| 1703 | fn every_tile_layout_decodes_sample_exact_through_both_decoders() { |
| 1704 | let (width, height) = (640usize, 384usize); |
| 1705 | let sources: Vec<Picture> = (0..4).map(|t| test_card(width, height, t * 3)).collect(); |
| 1706 | let mut sizes = Vec::new(); |
| 1707 | for (cols_log2, rows_log2) in [(0u32, 0u32), (1, 0), (0, 1), (1, 1), (2, 1)] { |
| 1708 | let config = EncoderConfig { |
| 1709 | width, |
| 1710 | height, |
| 1711 | base_q_idx: 120, |
| 1712 | gop: 4, |
| 1713 | colour: Colour::Bt709Limited, |
| 1714 | tile_cols_log2: cols_log2, |
| 1715 | tile_rows_log2: rows_log2, |
| 1716 | }; |
| 1717 | let layout = format!("{}x{} tiles", 1 << cols_log2, 1 << rows_log2); |
| 1718 | let mut enc = Av1Encoder::new(config).unwrap(); |
| 1719 | let mut stream = Vec::new(); |
| 1720 | for (i, picture) in sources.iter().enumerate() { |
| 1721 | let packet = enc |
| 1722 | .encode(picture) |
| 1723 | .unwrap_or_else(|e| panic!("{layout} frame {i}: {e}")); |
| 1724 | stream.extend_from_slice(&packet.data); |
| 1725 | } |
| 1726 | sizes.push((layout.clone(), stream.len())); |
| 1727 | |
| 1728 | // The frames carry the tiles their headers claim. |
| 1729 | let mut parser = ec_av1_syntax::Av1Parser::new(); |
| 1730 | let mut frames = 0usize; |
| 1731 | let mut offset = 0usize; |
| 1732 | while offset < stream.len() { |
| 1733 | let obus = parser.parse_temporal_unit(&stream[offset..]).unwrap(); |
| 1734 | let unit: usize = obus.iter().map(|o| o.total_size).sum(); |
| 1735 | for obu in &obus { |
| 1736 | if let ec_av1_syntax::ObuKind::Frame(parsed, tiles) = &obu.kind { |
| 1737 | assert_eq!( |
| 1738 | (parsed.tile_info.cols, parsed.tile_info.rows), |
| 1739 | (1 << cols_log2, 1 << rows_log2), |
| 1740 | "{layout}: the header's own tile grid" |
| 1741 | ); |
| 1742 | assert_eq!( |
| 1743 | tiles.len(), |
| 1744 | 1 << (cols_log2 + rows_log2), |
| 1745 | "{layout}: tile payloads located in the tile group" |
| 1746 | ); |
| 1747 | frames += 1; |
| 1748 | } |
| 1749 | } |
| 1750 | offset += unit; |
| 1751 | } |
| 1752 | assert_eq!(frames, sources.len(), "{layout}: coded frames"); |
| 1753 | |
| 1754 | let ours = crate::stream::decode_stream(&stream).expect("our decoder"); |
| 1755 | assert_eq!(ours.len(), sources.len(), "{layout}: our decoder's frames"); |
| 1756 | if !have_ffmpeg() { |
| 1757 | eprintln!("SKIP the ffmpeg half of {layout}: no ffmpeg"); |
| 1758 | continue; |
| 1759 | } |
| 1760 | let theirs = ffmpeg_decode_luma(&stream, width, height); |
| 1761 | assert_eq!(theirs.len(), sources.len(), "{layout}: ffmpeg's frames"); |
| 1762 | for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() { |
| 1763 | let got: Vec<u8> = a.y.iter().map(|&v| v as u8).collect(); |
| 1764 | assert_eq!(got.len(), b.len(), "{layout} frame {i}: luma size"); |
| 1765 | if let Some(at) = got.iter().zip(b).position(|(x, y)| x != y) { |
| 1766 | panic!( |
| 1767 | "{layout} frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}", |
| 1768 | at % width, |
| 1769 | at / width, |
| 1770 | got[at], |
| 1771 | b[at], |
| 1772 | ); |
| 1773 | } |
| 1774 | } |
| 1775 | } |
| 1776 | let base = sizes[0].1 as f64; |
| 1777 | for (layout, bytes) in &sizes { |
| 1778 | eprintln!( |
| 1779 | "{layout}: {bytes} bytes ({:+.2}% vs one tile)", |
| 1780 | (*bytes as f64 / base - 1.0) * 100.0 |
| 1781 | ); |
| 1782 | } |
| 1783 | } |
| 1784 | |
| 1785 | /// What tiles and tile threads are worth at the size the editor exports |
| 1786 | /// at: 1920x1080, eight real pictures, two passes per cell (ABAB), wall |
| 1787 | /// per cell. Ignored by default (minutes). |
| 1788 | #[test] |
| 1789 | #[ignore = "1080p wall table: minutes, run it with --ignored"] |
| 1790 | fn tile_wall_table_at_1080p() { |
| 1791 | let _gate_lock = crate::stream::tests::lock_gate_counters(); |
| 1792 | let (width, height) = (1920usize, 1080usize); |
| 1793 | let Some(sources) = h264_clip_frames(width, height, 8) else { |
| 1794 | eprintln!("SKIP tile_wall_table_at_1080p: no fixture"); |
| 1795 | return; |
| 1796 | }; |
| 1797 | let layouts = [(0u32, 0u32), (1, 0), (1, 1), (2, 1)]; |
| 1798 | let threadings = [1usize, 2, 4, 8]; |
| 1799 | let mut table: Vec<(String, usize, f64, usize)> = Vec::new(); |
| 1800 | for pass in 0..2 { |
| 1801 | for &(cols_log2, rows_log2) in &layouts { |
| 1802 | for &threads in &threadings { |
| 1803 | crate::par::set_tile_threads(threads); |
| 1804 | let config = EncoderConfig { |
| 1805 | width, |
| 1806 | height, |
| 1807 | base_q_idx: 120, |
| 1808 | gop: 8, |
| 1809 | colour: Colour::Bt709Limited, |
| 1810 | tile_cols_log2: cols_log2, |
| 1811 | tile_rows_log2: rows_log2, |
| 1812 | }; |
| 1813 | let mut enc = Av1Encoder::new(config).unwrap(); |
| 1814 | let start = std::time::Instant::now(); |
| 1815 | let mut bytes = 0usize; |
| 1816 | for picture in &sources { |
| 1817 | bytes += enc.encode(picture).unwrap().data.len(); |
| 1818 | } |
| 1819 | let wall = start.elapsed().as_secs_f64(); |
| 1820 | let name = format!("{}x{}", 1 << cols_log2, 1 << rows_log2); |
| 1821 | match table.iter_mut().find(|r| r.0 == name && r.1 == threads) { |
| 1822 | Some(row) => row.2 = row.2.min(wall), |
| 1823 | None => table.push((name, threads, wall, bytes)), |
| 1824 | } |
| 1825 | let _ = pass; |
| 1826 | } |
| 1827 | } |
| 1828 | } |
| 1829 | crate::par::set_tile_threads(1); |
| 1830 | eprintln!("| tiles | threads | wall (s, best of 2) | bytes |"); |
| 1831 | for (name, threads, wall, bytes) in &table { |
| 1832 | eprintln!("| {name} | {threads} | {wall:.2} | {bytes} |"); |
| 1833 | } |
| 1834 | } |
| 1835 | |
| 1836 | /// The tiles of a frame are entropy-independent, so the bytes must not |
| 1837 | /// depend on how many workers wrote them: the same stream at one tile |
| 1838 | /// thread and at four, per layout. |
| 1839 | #[test] |
| 1840 | fn tile_bytes_do_not_depend_on_the_thread_count() { |
| 1841 | let _gate_lock = crate::stream::tests::lock_gate_counters(); |
| 1842 | let (width, height) = (320usize, 192usize); |
| 1843 | let sources: Vec<Picture> = (0..3).map(|t| test_card(width, height, t * 3)).collect(); |
| 1844 | let coded = |threads: usize, cols_log2: u32, rows_log2: u32| { |
| 1845 | crate::par::set_tile_threads(threads); |
| 1846 | let config = EncoderConfig { |
| 1847 | width, |
| 1848 | height, |
| 1849 | base_q_idx: 120, |
| 1850 | gop: 3, |
| 1851 | colour: Colour::Bt709Limited, |
| 1852 | tile_cols_log2: cols_log2, |
| 1853 | tile_rows_log2: rows_log2, |
| 1854 | }; |
| 1855 | let mut enc = Av1Encoder::new(config).unwrap(); |
| 1856 | let mut stream = Vec::new(); |
| 1857 | for picture in &sources { |
| 1858 | stream.extend_from_slice(&enc.encode(picture).unwrap().data); |
| 1859 | } |
| 1860 | stream |
| 1861 | }; |
| 1862 | for (cols_log2, rows_log2) in [(1u32, 0u32), (0, 1), (1, 1), (2, 1)] { |
| 1863 | let one = coded(1, cols_log2, rows_log2); |
| 1864 | let four = coded(4, cols_log2, rows_log2); |
| 1865 | assert_eq!( |
| 1866 | one, |
| 1867 | four, |
| 1868 | "{}x{} tiles: {} bytes at one thread, {} at four", |
| 1869 | 1 << cols_log2, |
| 1870 | 1 << rows_log2, |
| 1871 | one.len(), |
| 1872 | four.len() |
| 1873 | ); |
| 1874 | } |
| 1875 | crate::par::set_tile_threads(1); |
| 1876 | } |
| 1877 | |
| 1878 | /// What the per-tile search (lane-av1tsearch) is worth in wall and in |
| 1879 | /// frames per second at the editor's own export sizes: every tile layout |
| 1880 | /// crossed with every tile-thread count, plus librav1e at the matching |
| 1881 | /// `tile_cols`/`tile_rows`/`threads` as the reference point. Two passes |
| 1882 | /// over the whole table (A,B,A,B... rather than AA,BB) with the best of |
| 1883 | /// the two kept, so a thermal drift cannot order the rows. |
| 1884 | /// |
| 1885 | /// Measurement, not a pass/fail gate: it asserts only that every cell |
| 1886 | /// produced a stream. |
| 1887 | #[test] |
| 1888 | #[ignore = "wall measurement: minutes, run it with --ignored --nocapture"] |
| 1889 | fn tile_search_wall_1080p() { |
| 1890 | tile_search_wall(1920, 1080, 12, &[(0, 0), (1, 0), (1, 1), (2, 1)], &[1, 2, 4, 8]); |
| 1891 | } |
| 1892 | |
| 1893 | /// The same table at the 4K frame size the editor exports (3840x1608), |
| 1894 | /// at the two layouts with enough tiles to fill this box. |
| 1895 | #[test] |
| 1896 | #[ignore = "wall measurement: minutes, run it with --ignored --nocapture"] |
| 1897 | fn tile_search_wall_4k() { |
| 1898 | tile_search_wall(3840, 1608, 6, &[(2, 1), (3, 2)], &[1, 8, 12]); |
| 1899 | } |
| 1900 | |
| 1901 | /// lane-av1fpar: the frame-level FILTER stage is banded across the same |
| 1902 | /// workers the tile search uses (`par::override_filter_threads`), so the |
| 1903 | /// deblock/CDEF replays, the per-64 SSE and the plane copies all run in |
| 1904 | /// pieces. Every piece is a disjoint band of the same integers, so the |
| 1905 | /// stream must not move -- at a size that crops and is several superblock |
| 1906 | /// rows tall, which is what makes the bands non-trivial. |
| 1907 | #[test] |
| 1908 | fn filter_stage_bytes_do_not_depend_on_the_thread_count() { |
| 1909 | let _gate_lock = crate::stream::tests::lock_gate_counters(); |
| 1910 | let (width, height) = (384usize, 288usize); |
| 1911 | let sources: Vec<Picture> = (0..4).map(|t| test_card(width, height, t * 3)).collect(); |
| 1912 | let coded = |threads: usize| { |
| 1913 | crate::par::set_tile_threads(threads); |
| 1914 | let config = EncoderConfig { |
| 1915 | width, |
| 1916 | height, |
| 1917 | base_q_idx: 120, |
| 1918 | gop: 2, |
| 1919 | colour: Colour::Bt709Limited, |
| 1920 | tile_cols_log2: 0, |
| 1921 | tile_rows_log2: 0, |
| 1922 | }; |
| 1923 | let mut enc = Av1Encoder::new(config).unwrap(); |
| 1924 | let mut stream = Vec::new(); |
| 1925 | for picture in &sources { |
| 1926 | stream.extend_from_slice(&enc.encode(picture).unwrap().data); |
| 1927 | } |
| 1928 | stream |
| 1929 | }; |
| 1930 | // One tile, so only the filter stage can differ between these. |
| 1931 | let one = coded(1); |
| 1932 | for threads in [2usize, 4, 8] { |
| 1933 | assert_eq!(one, coded(threads), "the filter stage moved at {threads} threads"); |
| 1934 | } |
| 1935 | crate::par::set_tile_threads(1); |
| 1936 | } |
| 1937 | |
| 1938 | /// lane-av1fpar: the filter search scores its ~30 candidates by replaying |
| 1939 | /// the loop filters on one captured reconstruction instead of decoding |
| 1940 | /// the coded tile again per candidate. The replay must be that decode, |
| 1941 | /// byte for byte -- including at a size that CROPS (1080 and 1608 both |
| 1942 | /// pad to a superblock row, i.e. every export size the editor uses), |
| 1943 | /// which is the arm this lane opened. |
| 1944 | #[test] |
| 1945 | fn filter_replay_codes_the_same_stream_as_a_full_decode() { |
| 1946 | let _gate_lock = crate::stream::tests::lock_gate_counters(); |
| 1947 | let run = |width: usize, height: usize, off: bool| { |
| 1948 | let sources: Vec<Picture> = (0..4).map(|t| test_card(width, height, t * 3)).collect(); |
| 1949 | crate::decode::set_filter_replay_disabled(off); |
| 1950 | let config = EncoderConfig { |
| 1951 | width, |
| 1952 | height, |
| 1953 | base_q_idx: 120, |
| 1954 | gop: 2, |
| 1955 | colour: Colour::Bt709Limited, |
| 1956 | tile_cols_log2: 0, |
| 1957 | tile_rows_log2: 0, |
| 1958 | }; |
| 1959 | let mut enc = Av1Encoder::new(config).unwrap(); |
| 1960 | let mut stream = Vec::new(); |
| 1961 | for picture in &sources { |
| 1962 | stream.extend_from_slice(&enc.encode(picture).unwrap().data); |
| 1963 | } |
| 1964 | crate::decode::set_filter_replay_disabled(false); |
| 1965 | stream |
| 1966 | }; |
| 1967 | // 320x160 crops (the coding surface is 320x192, one superblock row |
| 1968 | // taller); 320x192 is a whole number of superblocks, the shape the |
| 1969 | // replay already covered. |
| 1970 | for (width, height) in [(320usize, 160usize), (320, 192)] { |
| 1971 | let replayed = run(width, height, false); |
| 1972 | let decoded = run(width, height, true); |
| 1973 | assert_eq!( |
| 1974 | replayed, |
| 1975 | decoded, |
| 1976 | "{width}x{height}: the filter replay is not the decode it stands in for \ |
| 1977 | ({} bytes replayed, {} decoded)", |
| 1978 | replayed.len(), |
| 1979 | decoded.len(), |
| 1980 | ); |
| 1981 | } |
| 1982 | } |
| 1983 | |
| 1984 | /// lane-av1fpar: where a frame's wall actually goes, stage by stage -- |
| 1985 | /// the per-tile search, the tile write, the frame-level filter search |
| 1986 | /// (with its deblock/CDEF replay and per-64 SSE inside it), the capture |
| 1987 | /// decode the loop-restoration search rides on, and that search itself. |
| 1988 | /// Measurement, not a pass/fail gate. |
| 1989 | #[test] |
| 1990 | #[ignore = "wall measurement: minutes, run it with --ignored --nocapture"] |
| 1991 | fn filter_stage_wall_1080p() { |
| 1992 | filter_stage_wall(1920, 1080, 8, (2, 1), &[8]); |
| 1993 | } |
| 1994 | |
| 1995 | #[test] |
| 1996 | #[ignore = "wall measurement: minutes, run it with --ignored --nocapture"] |
| 1997 | fn filter_stage_wall_4k() { |
| 1998 | filter_stage_wall(3840, 1608, 4, (2, 1), &[8, 12]); |
| 1999 | } |
| 2000 | |
| 2001 | fn filter_stage_wall( |
| 2002 | width: usize, |
| 2003 | height: usize, |
| 2004 | frames: usize, |
| 2005 | (cols_log2, rows_log2): (u32, u32), |
| 2006 | threads: &[usize], |
| 2007 | ) { |
| 2008 | let _gate_lock = crate::stream::tests::lock_gate_counters(); |
| 2009 | let Some(sources) = h264_clip_frames(width, height, frames) else { |
| 2010 | eprintln!("SKIP the filter-stage breakdown: no fixture or no ffmpeg"); |
| 2011 | return; |
| 2012 | }; |
| 2013 | crate::par::set_stage_times(true); |
| 2014 | for &t in threads { |
| 2015 | crate::par::set_tile_threads(t); |
| 2016 | let config = EncoderConfig { |
| 2017 | width, |
| 2018 | height, |
| 2019 | base_q_idx: 120, |
| 2020 | gop: frames, |
| 2021 | colour: Colour::Bt709Limited, |
| 2022 | tile_cols_log2: cols_log2, |
| 2023 | tile_rows_log2: rows_log2, |
| 2024 | }; |
| 2025 | let mut enc = Av1Encoder::new(config).unwrap(); |
| 2026 | let _ = crate::par::take_stage_ns(); |
| 2027 | let start = std::time::Instant::now(); |
| 2028 | for picture in &sources { |
| 2029 | assert!(!enc.encode(picture).unwrap().data.is_empty()); |
| 2030 | } |
| 2031 | let wall = start.elapsed().as_secs_f64(); |
| 2032 | let ns = crate::par::take_stage_ns(); |
| 2033 | let ms = |i: usize| ns[i] as f64 / 1e6; |
| 2034 | eprintln!( |
| 2035 | "\n{width}x{height}, {frames} frames, {}x{} tiles, {t} tile threads: \ |
| 2036 | {wall:.2}s wall, {:.2} fps", |
| 2037 | 1 << cols_log2, |
| 2038 | 1 << rows_log2, |
| 2039 | frames as f64 / wall, |
| 2040 | ); |
| 2041 | eprintln!("| stage | ms | ms/frame | % of wall |"); |
| 2042 | for (i, name) in crate::par::STAGES.iter().enumerate() { |
| 2043 | eprintln!( |
| 2044 | "| {name} | {:.0} | {:.1} | {:.1}% |", |
| 2045 | ms(i), |
| 2046 | ms(i) / frames as f64, |
| 2047 | 100.0 * ms(i) / (wall * 1e3), |
| 2048 | ); |
| 2049 | } |
| 2050 | // Top-level stages only (the deblock/CDEF/SSE rows are inside |
| 2051 | // the filter-search total); the rest is per-frame setup, the |
| 2052 | // source conversion and the splice. |
| 2053 | let top: f64 = [ |
| 2054 | crate::par::S_TILE_SEARCH, |
| 2055 | crate::par::S_TILE_WRITE, |
| 2056 | crate::par::S_FILTER, |
| 2057 | crate::par::S_CAPTURE, |
| 2058 | crate::par::S_LR, |
| 2059 | ] |
| 2060 | .iter() |
| 2061 | .map(|&i| ms(i)) |
| 2062 | .sum(); |
| 2063 | eprintln!( |
| 2064 | "accounted {:.1}% of wall; outside the tile search {:.1}%", |
| 2065 | 100.0 * top / (wall * 1e3), |
| 2066 | 100.0 * (1.0 - ms(crate::par::S_TILE_SEARCH) / (wall * 1e3)), |
| 2067 | ); |
| 2068 | } |
| 2069 | crate::par::set_stage_times(false); |
| 2070 | crate::par::set_tile_threads(1); |
| 2071 | } |
| 2072 | |
| 2073 | fn tile_search_wall( |
| 2074 | width: usize, |
| 2075 | height: usize, |
| 2076 | frames: usize, |
| 2077 | layouts: &[(u32, u32)], |
| 2078 | threads: &[usize], |
| 2079 | ) { |
| 2080 | let _gate_lock = crate::stream::tests::lock_gate_counters(); |
| 2081 | let Some(sources) = h264_clip_frames(width, height, frames) else { |
| 2082 | eprintln!("SKIP the tile-search wall table: no fixture or no ffmpeg"); |
| 2083 | return; |
| 2084 | }; |
| 2085 | let run = |cols_log2: u32, rows_log2: u32, t: usize| -> (std::time::Duration, usize) { |
| 2086 | crate::par::set_tile_threads(t); |
| 2087 | let config = EncoderConfig { |
| 2088 | width, |
| 2089 | height, |
| 2090 | base_q_idx: 120, |
| 2091 | gop: frames, |
| 2092 | colour: Colour::Bt709Limited, |
| 2093 | tile_cols_log2: cols_log2, |
| 2094 | tile_rows_log2: rows_log2, |
| 2095 | }; |
| 2096 | let mut enc = Av1Encoder::new(config).unwrap(); |
| 2097 | let start = std::time::Instant::now(); |
| 2098 | let mut bytes = 0usize; |
| 2099 | for picture in &sources { |
| 2100 | bytes += enc.encode(picture).unwrap().data.len(); |
| 2101 | } |
| 2102 | (start.elapsed(), bytes) |
| 2103 | }; |
| 2104 | let cells: Vec<((u32, u32), usize)> = layouts |
| 2105 | .iter() |
| 2106 | .flat_map(|&l| threads.iter().map(move |&t| (l, t))) |
| 2107 | .collect(); |
| 2108 | let mut best: Vec<Option<(std::time::Duration, usize)>> = vec![None; cells.len()]; |
| 2109 | for _pass in 0..2 { |
| 2110 | for (i, &((c, r), t)) in cells.iter().enumerate() { |
| 2111 | let got = run(c, r, t); |
| 2112 | assert!(got.1 > 0, "{}x{} tiles at {t} threads: empty stream", 1 << c, 1 << r); |
| 2113 | if best[i].is_none_or(|(w, _)| got.0 < w) { |
| 2114 | best[i] = Some(got); |
| 2115 | } |
| 2116 | } |
| 2117 | } |
| 2118 | crate::par::set_tile_threads(1); |
| 2119 | eprintln!("\n{width}x{height}, {frames} frames, base_q_idx 120 -- best of two passes"); |
| 2120 | eprintln!("| layout | tiles | threads | wall | fps | speedup vs 1 tile 1 thread | bytes |"); |
| 2121 | let base = best[0].expect("the first cell ran").0.as_secs_f64(); |
| 2122 | for (i, &((c, r), t)) in cells.iter().enumerate() { |
| 2123 | let (wall, bytes) = best[i].expect("every cell ran"); |
| 2124 | let secs = wall.as_secs_f64(); |
| 2125 | eprintln!( |
| 2126 | "| {}x{} | {} | {t} | {secs:.2}s | {:.2} | {:.2}x | {bytes} |", |
| 2127 | 1 << c, |
| 2128 | 1 << r, |
| 2129 | 1 << (c + r), |
| 2130 | frames as f64 / secs, |
| 2131 | base / secs, |
| 2132 | ); |
| 2133 | } |
| 2134 | // Parallel efficiency per layout: what the extra threads actually |
| 2135 | // took off that layout's own single-threaded wall, and so what share |
| 2136 | // of the added cores sat idle. |
| 2137 | for &(c, r) in layouts { |
| 2138 | let one = cells |
| 2139 | .iter() |
| 2140 | .position(|&(l, t)| l == (c, r) && t == threads[0]) |
| 2141 | .map(|i| best[i].expect("cell").0.as_secs_f64()); |
| 2142 | let Some(one) = one else { continue }; |
| 2143 | for &t in &threads[1..] { |
| 2144 | let i = cells.iter().position(|&(l, tt)| l == (c, r) && tt == t).expect("cell"); |
| 2145 | let secs = best[i].expect("cell").0.as_secs_f64(); |
| 2146 | let workers = (t.min(1 << (c + r))) as f64 / threads[0] as f64; |
| 2147 | let speedup = one / secs; |
| 2148 | eprintln!( |
| 2149 | "{}x{} tiles, {} -> {t} threads: {speedup:.2}x of a possible {workers:.2}x, \ |
| 2150 | idle share {:.0}%", |
| 2151 | 1 << c, |
| 2152 | 1 << r, |
| 2153 | threads[0], |
| 2154 | 100.0 * (1.0 - speedup / workers).max(0.0), |
| 2155 | ); |
| 2156 | } |
| 2157 | } |
| 2158 | rav1e_wall_reference(width, height, frames, layouts, threads); |
| 2159 | } |
| 2160 | |
| 2161 | /// librav1e at the same sizes, layouts and thread counts, through ffmpeg |
| 2162 | /// -- the reference the wall table is read against. |
| 2163 | fn rav1e_wall_reference( |
| 2164 | width: usize, |
| 2165 | height: usize, |
| 2166 | frames: usize, |
| 2167 | layouts: &[(u32, u32)], |
| 2168 | threads: &[usize], |
| 2169 | ) { |
| 2170 | let clip = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) |
| 2171 | .join("../../fixtures/video/h264-1080p-23.976-8bit.mp4"); |
| 2172 | let listed = Command::new("ffmpeg").args(["-hide_banner", "-encoders"]).output(); |
| 2173 | let has_rav1e = listed |
| 2174 | .map(|o| String::from_utf8_lossy(&o.stdout).contains("librav1e")) |
| 2175 | .unwrap_or(false); |
| 2176 | if !has_rav1e || !clip.exists() { |
| 2177 | eprintln!("SKIP the rav1e reference: no librav1e or no fixture"); |
| 2178 | return; |
| 2179 | } |
| 2180 | eprintln!("| rav1e layout | threads | wall | fps | bytes |"); |
| 2181 | for &(c, r) in layouts { |
| 2182 | for &t in threads { |
| 2183 | let out = std::env::temp_dir().join(format!("ec-av1-rav1e-{}.ivf", std::process::id())); |
| 2184 | let params = format!( |
| 2185 | "speed=6:quantizer=100:tile_cols={}:tile_rows={}:threads={t}", |
| 2186 | 1 << c, |
| 2187 | 1 << r |
| 2188 | ); |
| 2189 | let start = std::time::Instant::now(); |
| 2190 | let status = Command::new("ffmpeg") |
| 2191 | .args(["-v", "error", "-y", "-i", clip.to_str().unwrap()]) |
| 2192 | .args(["-frames:v", &frames.to_string()]) |
| 2193 | .args(["-vf", &format!("scale={width}:{height}")]) |
| 2194 | .args(["-c:v", "librav1e", "-rav1e-params", ¶ms]) |
| 2195 | .arg(out.to_str().unwrap()) |
| 2196 | .output() |
| 2197 | .expect("ffmpeg failed to run"); |
| 2198 | let secs = start.elapsed().as_secs_f64(); |
| 2199 | if !status.status.success() { |
| 2200 | eprintln!("| {}x{} | {t} | FAILED: {} |", 1 << c, 1 << r, String::from_utf8_lossy(&status.stderr).lines().last().unwrap_or("")); |
| 2201 | continue; |
| 2202 | } |
| 2203 | let bytes = std::fs::metadata(&out).map(|m| m.len()).unwrap_or(0); |
| 2204 | let _ = std::fs::remove_file(&out); |
| 2205 | eprintln!( |
| 2206 | "| {}x{} | {t} | {secs:.2}s | {:.2} | {bytes} |", |
| 2207 | 1 << c, |
| 2208 | 1 << r, |
| 2209 | frames as f64 / secs |
| 2210 | ); |
| 2211 | } |
| 2212 | } |
| 2213 | } |
| 2214 | |
| 2215 | /// The same round trip at a real 1920x1080 crop of the gate's own clip |
| 2216 | /// -- the size the editor's export actually runs at, where a tile grid |
| 2217 | /// is worth having. Ignored by default only for its wall (a 1080p |
| 2218 | /// encode of three pictures), not for any weakness in the check. |
| 2219 | #[test] |
| 2220 | #[ignore = "1080p encode: minutes, run it with --ignored"] |
| 2221 | fn a_1080p_multi_tile_stream_decodes_sample_exact_through_both_decoders() { |
| 2222 | let (width, height) = (1920usize, 1080usize); |
| 2223 | let Some(sources) = h264_clip_frames(width, height, 3) else { |
| 2224 | eprintln!("SKIP the 1080p tile round trip: no fixture"); |
| 2225 | return; |
| 2226 | }; |
| 2227 | for (cols_log2, rows_log2) in [(1u32, 0u32), (1, 1), (2, 1)] { |
| 2228 | let config = EncoderConfig { |
| 2229 | width, |
| 2230 | height, |
| 2231 | base_q_idx: 120, |
| 2232 | gop: 3, |
| 2233 | colour: Colour::Bt709Limited, |
| 2234 | tile_cols_log2: cols_log2, |
| 2235 | tile_rows_log2: rows_log2, |
| 2236 | }; |
| 2237 | let layout = format!("{}x{} tiles", 1 << cols_log2, 1 << rows_log2); |
| 2238 | let mut enc = Av1Encoder::new(config).unwrap(); |
| 2239 | let mut stream = Vec::new(); |
| 2240 | for (i, picture) in sources.iter().enumerate() { |
| 2241 | let packet = enc |
| 2242 | .encode(picture) |
| 2243 | .unwrap_or_else(|e| panic!("{layout} frame {i}: {e}")); |
| 2244 | stream.extend_from_slice(&packet.data); |
| 2245 | } |
| 2246 | let ours = crate::stream::decode_stream(&stream).expect("our decoder"); |
| 2247 | assert_eq!(ours.len(), sources.len(), "{layout}: our decoder's frames"); |
| 2248 | if !have_ffmpeg() { |
| 2249 | eprintln!("SKIP the ffmpeg half of 1080p {layout}: no ffmpeg"); |
| 2250 | continue; |
| 2251 | } |
| 2252 | let theirs = ffmpeg_decode_luma(&stream, width, height); |
| 2253 | assert_eq!(theirs.len(), sources.len(), "{layout}: ffmpeg's frames"); |
| 2254 | for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() { |
| 2255 | let got: Vec<u8> = a.y.iter().map(|&v| v as u8).collect(); |
| 2256 | if let Some(at) = got.iter().zip(b).position(|(x, y)| x != y) { |
| 2257 | panic!( |
| 2258 | "1080p {layout} frame {i}: luma differs first at ({}, {})", |
| 2259 | at % width, |
| 2260 | at / width |
| 2261 | ); |
| 2262 | } |
| 2263 | } |
| 2264 | eprintln!("1080p {layout}: {} bytes, sample-exact", stream.len()); |
| 2265 | } |
| 2266 | } |
| 2267 | |
| 2268 | /// [`RateTarget::Quality`] is monotone: a higher quality dial never |
| 2269 | /// produces a smaller stream or a worse mean PSNR than a lower one, on |
| 2270 | /// the same real clip. |
| 2271 | #[test] |
| 2272 | fn quality_target_is_monotone_in_bytes_and_psnr() { |
| 2273 | if !have_ffmpeg() { |
| 2274 | eprintln!("SKIP quality_target_is_monotone_in_bytes_and_psnr: no ffmpeg"); |
| 2275 | return; |
| 2276 | } |
| 2277 | let (width, height) = (640, 384); |
| 2278 | let Some(pictures) = h264_clip_frames(width, height, 8) else { |
| 2279 | eprintln!("SKIP quality_target_is_monotone_in_bytes_and_psnr: no fixture"); |
| 2280 | return; |
| 2281 | }; |
| 2282 | let mut prev_bytes = 0usize; |
| 2283 | let mut prev_psnr = 0.0f64; |
| 2284 | for quality in [20u8, 50, 80] { |
| 2285 | let config = EncoderConfig { |
| 2286 | width, |
| 2287 | height, |
| 2288 | base_q_idx: 100, |
| 2289 | gop: 8, |
| 2290 | colour: Colour::Bt709Limited, |
| 2291 | tile_cols_log2: 0, |
| 2292 | tile_rows_log2: 0, |
| 2293 | }; |
| 2294 | let mut enc = |
| 2295 | Av1Encoder::with_rate_target(config, RateTarget::Quality(quality)).unwrap(); |
| 2296 | let mut stream = Vec::new(); |
| 2297 | let mut total_bytes = 0usize; |
| 2298 | for picture in &pictures { |
| 2299 | let packet = enc.encode(picture).unwrap(); |
| 2300 | total_bytes += packet.data.len(); |
| 2301 | stream.extend_from_slice(&packet.data); |
| 2302 | } |
| 2303 | let decoded = ffmpeg_decode_luma(&stream, width, height); |
| 2304 | assert_eq!( |
| 2305 | decoded.len(), |
| 2306 | pictures.len(), |
| 2307 | "quality {quality}: dav1d frame count" |
| 2308 | ); |
| 2309 | let mean_psnr: f64 = decoded |
| 2310 | .iter() |
| 2311 | .zip(&pictures) |
| 2312 | .map(|(d, p)| { |
| 2313 | let d16: Vec<u16> = d.iter().map(|&v| u16::from(v)).collect(); |
| 2314 | psnr(&d16, &p.y) |
| 2315 | }) |
| 2316 | .sum::<f64>() |
| 2317 | / decoded.len() as f64; |
| 2318 | assert!( |
| 2319 | total_bytes >= prev_bytes, |
| 2320 | "quality {quality}: {total_bytes} bytes not >= previous {prev_bytes}" |
| 2321 | ); |
| 2322 | assert!( |
| 2323 | mean_psnr >= prev_psnr - 0.01, // rounding slack, same-ish q_idx neighbours |
| 2324 | "quality {quality}: {mean_psnr:.2} dB not >= previous {prev_psnr:.2} dB" |
| 2325 | ); |
| 2326 | prev_bytes = total_bytes; |
| 2327 | prev_psnr = mean_psnr; |
| 2328 | } |
| 2329 | } |
| 2330 | } |