oxideav-av1 0.1.21

Pure-Rust AV1 codec — orphan-rebuild scaffold pending clean-room re-implementation.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
//! r460 — the STILL-PICTURE entry point: one intra frame coded under a
//! §6.4.1 `still_picture = 1` / `reduced_still_picture_header = 1`
//! sequence header, with the same quality controls the KEY-frame
//! encoder has (`base_q_idx`, the elected §5.9.17 delta-q plan, the
//! §5.9.12 quantizer-matrix ladder, `base_q_idx = 0` lossless) — the
//! shape every AVIF / HEIF `av01` image item carries (av1-avif §2.1
//! recommends the reduced header "so that AV1 header overhead is
//! minimized"; every third-party AVIF producer measured in r460 emits
//! it).
//!
//! What the reduced header changes on the wire (§5.5.1 / §5.9.2):
//! one operating point (`seq_level_idx` only — no `operating_point_idc`
//! / tier / timing / decoder-model blocks), `frame_id_numbers_present_flag
//! = 0`, every inter tool gate (`enable_interintra_compound`,
//! `enable_masked_compound`, `enable_warped_motion`,
//! `enable_dual_filter`, `enable_order_hint`, `enable_jnt_comp`,
//! `enable_ref_frame_mvs`) inferred to 0 with `OrderHintBits = 0`,
//! `seq_force_screen_content_tools` / `seq_force_integer_mv` inferred
//! to SELECT, and a frame header that is KEY / shown / not showable /
//! error-resilient with `refresh_frame_flags = allFrames` and
//! `disable_frame_end_update_cdf = 1` — all derived, none coded. The
//! coded tile data is byte-identical to the KEY-frame encoder's for
//! the same decisions, so every §7 reconstruction guarantee carries
//! over: the decoder output equals [`EncodedStill::recon_y`] /
//! `recon_u` / `recon_v` sample for sample.
//!
//! The Annex A level (`seq_level_idx`) is elected from the picture
//! size ([`elect_seq_level_idx`]): the smallest level whose
//! `MaxPicSize` / `MaxHSize` / `MaxVSize` admit the frame (a still
//! has no display-rate / decode-rate / bit-rate constraint to meet),
//! `31` (maximum parameters) beyond level 6.3.

use crate::codec_config::Av1CodecConfig;
use crate::encoder::key_frame::{encode_key_frame_yuv_full, EncodedKeyFrameYuv, KeyExtras};
use crate::encoder::rate_twin::RateModel;
use crate::encoder::yuv_frame::{Yuv420Frame, YuvFrame};
use crate::frame_header::FrameHeader;
use crate::sequence_header::{SequenceHeader, SELECT_INTEGER_MV, SELECT_SCREEN_CONTENT_TOOLS};
use crate::Error;

/// Search-effort presets for [`StillOptions::speed`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum StillSpeed {
    /// r464 — the production point (the framework encoder's default):
    /// the largest transform size per leaf, the intra-mode pre-screen,
    /// proxy-priced transform-type choice, partition early
    /// termination, the reduced CDEF / restoration / deblock
    /// elections. A 12 MP 8-bit still in ~7 s single-thread / ~1.2 s
    /// on 8 threads at +7.9 % BD-rate against a third-party encoder's
    /// speed 6 (see the README's performance section).
    #[default]
    Fast,
    /// `Fast` plus the §5.11.4 rect partition arms, the refined
    /// deblock ladder, a fuller CDEF sweep and two restoration
    /// unit-size rungs: ~2.5× `Fast`'s wall clock for −0.7 % BD-rate
    /// on the same picture.
    Balanced,
    /// The exhaustive pre-r460 search (every transform size and type,
    /// 4×4 leaves, the full mode ladders, exact per-TU pricing, the
    /// full CDEF / restoration ladders) plus the §5.9.12 QM, §5.9.17
    /// delta-q and §5.9.8 superres elections. Minutes per 12 MP
    /// picture.
    Thorough,
}

/// Options for [`encode_still_yuv`] / [`encode_still_yuv420`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct StillOptions {
    /// §5.9.12 `base_q_idx` (0..=255). `0` codes the §5.9.2
    /// `CodedLossless` arm: the decoded picture equals the input
    /// sample for sample.
    pub base_q_idx: u8,
    /// §5.9.15 uniform tile layout `(TileColsLog2, TileRowsLog2)` —
    /// `(0, 0)` codes one tile. Must lie inside the §5.9.15 legal
    /// window for the picture size (see
    /// [`crate::tile_info::TileInfo::uniform_layout`]).
    pub tile_cols_log2: u32,
    /// See [`StillOptions::tile_cols_log2`].
    pub tile_rows_log2: u32,
    /// Search effort.
    pub speed: StillSpeed,
    /// §5.5.2 `color_range` — `true` signals full-range samples (an
    /// alpha auxiliary item is conventionally full range). Signalling
    /// only; the coding is unchanged.
    pub full_range: bool,
    /// `false` codes the same still picture under a FULL sequence
    /// header (`still_picture = 1`, `reduced_still_picture_header =
    /// 0`) — the shape a third-party producer's
    /// `--full-still-picture-hdr` emits. The frame header then carries
    /// the ordinary KEY-frame fields (`show_existing_frame`,
    /// `frame_type`, `show_frame`, ...).
    pub reduced_header: bool,
    /// §5.5.2 colour description `(color_primaries,
    /// transfer_characteristics, matrix_coefficients)` — H.273 code
    /// points, e.g. `(1, 13, 6)` for BT.709 primaries / sRGB transfer /
    /// BT.601 matrix, or `(1, 13, 0)` for identity-matrix RGB carried
    /// as 4:4:4. `None` codes the unspecified triple
    /// (`color_description_present_flag = 0`). Signalling only; a
    /// container's `colr` box should carry the same values.
    pub color_description: Option<(u8, u8, u8)>,
    /// Tile-search threads (r460). Tiles are independent by
    /// construction, so a multi-tile still is searched
    /// `threads`-wide and stitched in tile order — the stream is
    /// identical to the single-threaded encode of the same layout.
    /// `1` = sequential.
    pub threads: usize,
    /// Derive the §5.9.15 tile layout from `threads` and the picture
    /// size (tiles at least 256 px wide / 128 px tall, at most
    /// `threads.next_power_of_two()` of them) instead of
    /// `tile_cols_log2` / `tile_rows_log2`. Off by default (one tile).
    pub auto_tiles: bool,
}

impl StillOptions {
    /// Lossy still at `base_q_idx`, single tile, `Fast` effort (r464;
    /// `Balanced` before), studio range, reduced header.
    #[must_use]
    pub fn new(base_q_idx: u8) -> Self {
        Self {
            base_q_idx,
            tile_cols_log2: 0,
            tile_rows_log2: 0,
            speed: StillSpeed::Fast,
            full_range: false,
            reduced_header: true,
            color_description: None,
            threads: 1,
            auto_tiles: false,
        }
    }

    /// Search on `threads` threads over an automatically derived tile
    /// layout (see [`StillOptions::auto_tiles`]).
    #[must_use]
    pub fn threads(mut self, threads: usize) -> Self {
        self.threads = threads.max(1);
        self.auto_tiles = self.threads > 1;
        self
    }

    /// The lossless shape (`base_q_idx = 0`).
    #[must_use]
    pub fn lossless(mut self) -> Self {
        self.base_q_idx = 0;
        self
    }

    /// Map a 0..=100 quality dial (100 = lossless, 0 = coarsest) onto
    /// `base_q_idx`: `round((100 - quality) * 255 / 100)`.
    #[must_use]
    pub fn from_quality(quality: u8) -> Self {
        Self::new(quality_to_base_q_idx(quality))
    }
}

impl Default for StillOptions {
    fn default() -> Self {
        Self::new(DEFAULT_STILL_BASE_Q_IDX)
    }
}

/// The `base_q_idx` [`StillOptions::default`] codes at — the middle of
/// the useful photographic range (a third-party producer's quality 50
/// lands near it).
pub const DEFAULT_STILL_BASE_Q_IDX: u8 = 120;

/// The [`StillOptions::from_quality`] mapping.
#[must_use]
pub fn quality_to_base_q_idx(quality: u8) -> u8 {
    let q = u32::from(quality.min(100));
    (((100 - q) * 255 + 50) / 100) as u8
}

/// Result of [`encode_still_yuv`] / [`encode_still_yuv420`].
#[derive(Debug, Clone)]
pub struct EncodedStill {
    /// The bare §7.5 temporal unit (TD + SH + `OBU_FRAME`) — the AV1
    /// Image Item Data / ISOBMFF sample payload.
    pub temporal_unit_bytes: Vec<u8>,
    /// Complete IVF v0 file (header + one frame record) around the
    /// same temporal unit.
    pub ivf_bytes: Vec<u8>,
    /// Encoder reconstruction of the luma plane (row-major, `u16` at
    /// the input's bit depth). The decoded output equals these sample
    /// for sample; at `base_q_idx == 0` they additionally equal the
    /// input.
    pub recon_y: Vec<u16>,
    /// U plane reconstruction (subsampled extent; empty on
    /// monochrome).
    pub recon_u: Vec<u16>,
    /// V plane reconstruction.
    pub recon_v: Vec<u16>,
    /// The emitted sequence header descriptor.
    pub seq: SequenceHeader,
    /// The emitted frame header descriptor.
    pub fh: FrameHeader,
    /// The `av1C` record fields a container needs, derived from
    /// `seq` (`config_obus` empty, per av1-avif §2.2.1).
    pub codec_config: Av1CodecConfig,
}

impl EncodedStill {
    fn from_key(k: EncodedKeyFrameYuv) -> Self {
        let codec_config = Av1CodecConfig::from_sequence_header(&k.seq);
        Self {
            temporal_unit_bytes: k.temporal_unit_bytes,
            ivf_bytes: k.ivf_bytes,
            recon_y: k.recon_y,
            recon_u: k.recon_u,
            recon_v: k.recon_v,
            seq: k.seq,
            fh: k.fh,
            codec_config,
        }
    }
}

/// Annex A.3 level limits `(seq_level_idx, MaxPicSize, MaxHSize,
/// MaxVSize)` in ascending order — one row per level GROUP (the x.1
/// / x.2 / x.3 siblings share the picture-size limits and differ only
/// in the rate limits a still never meets).
const LEVEL_PIC_LIMITS: [(u8, u64, u32, u32); 6] = [
    (0, 147_456, 2048, 1152),    // 2.0
    (1, 278_784, 2816, 1584),    // 2.1
    (4, 665_856, 4352, 2448),    // 3.0
    (5, 1_065_024, 5504, 3096),  // 3.1
    (8, 2_359_296, 6144, 3456),  // 4.0
    (12, 8_912_896, 8192, 4352), // 5.0
];

/// Level 6.0 — `MaxPicSize 35651584`, `MaxHSize 16384`, `MaxVSize
/// 8704`.
const LEVEL_6_0: (u8, u64, u32, u32) = (16, 35_651_584, 16384, 8704);

/// `seq_level_idx = 31`: the "maximum parameters" level (§6.4.1 / A.3
/// — no limits apply).
pub const SEQ_LEVEL_IDX_MAX_PARAMETERS: u8 = 31;

/// Elect the smallest Annex A level whose `MaxPicSize` / `MaxHSize` /
/// `MaxVSize` admit a `width × height` picture (the still-picture
/// election — no rate terms). Returns
/// [`SEQ_LEVEL_IDX_MAX_PARAMETERS`] when even level 6.0's limits are
/// exceeded.
#[must_use]
pub fn elect_seq_level_idx(width: u32, height: u32) -> u8 {
    let pic = u64::from(width) * u64::from(height);
    LEVEL_PIC_LIMITS
        .iter()
        .chain(core::iter::once(&LEVEL_6_0))
        .find(|&&(_, max_pic, max_h, max_v)| pic <= max_pic && width <= max_h && height <= max_v)
        .map_or(SEQ_LEVEL_IDX_MAX_PARAMETERS, |&(idx, _, _, _)| idx)
}

/// Turn an intra-capable sequence header (as
/// [`crate::encoder::yuv_frame::build_intra_only_seq_yuv`] builds it)
/// into the reduced still-picture shape: every field §5.5.1 infers
/// under `reduced_still_picture_header = 1` is set to its inferred
/// value so the encoder's own derivations match the decoder's, and
/// operating point 0 carries the Annex A level elected from the
/// maximum frame size.
pub fn apply_still_picture_shape(seq: &mut SequenceHeader) {
    seq.still_picture = true;
    seq.reduced_still_picture_header = true;
    seq.timing_info_present_flag = false;
    seq.timing_info = None;
    seq.decoder_model_info_present_flag = false;
    seq.decoder_model_info = None;
    seq.initial_display_delay_present_flag = false;
    seq.operating_points_cnt_minus_1 = 0;
    seq.operating_points.truncate(1);
    if let Some(op) = seq.operating_points.first_mut() {
        op.operating_point_idc = 0;
        op.seq_level_idx = elect_seq_level_idx(
            seq.max_frame_width_minus_1 + 1,
            seq.max_frame_height_minus_1 + 1,
        );
        op.seq_tier = 0;
        op.decoder_model_present_for_this_op = false;
        op.operating_parameters_info = None;
        op.initial_display_delay_present_for_this_op = false;
        op.initial_display_delay_minus_1 = None;
    }
    seq.frame_id_numbers_present_flag = false;
    seq.delta_frame_id_length_minus_2 = 0;
    seq.additional_frame_id_length_minus_1 = 0;
    seq.enable_interintra_compound = false;
    seq.enable_masked_compound = false;
    seq.enable_warped_motion = false;
    seq.enable_dual_filter = false;
    seq.enable_order_hint = false;
    seq.enable_jnt_comp = false;
    seq.enable_ref_frame_mvs = false;
    seq.seq_force_screen_content_tools = SELECT_SCREEN_CONTENT_TOOLS;
    seq.seq_force_integer_mv = SELECT_INTEGER_MV;
    seq.order_hint_bits = 0;
}

/// Encode one still picture at any §6.4.1 (bit depth, chroma format)
/// pairing — 8/10/12-bit × 4:2:0 / 4:2:2 / 4:4:4 / monochrome (an
/// alpha auxiliary item is a monochrome still).
///
/// ## Errors
///
/// * [`YuvFrame::validate`] failures (shape / depth / sample range)
///   and a tile layout outside the §5.9.15 legal window —
///   [`Error::PartitionWalkOutOfRange`].
/// * Internal writer overflow surfaces the underlying [`Error`].
pub fn encode_still_yuv(input: &YuvFrame, opts: &StillOptions) -> Result<EncodedStill, Error> {
    encode_intra_yuv(input, opts, true)
}

/// r464 — the KEY-frame twin of [`encode_still_yuv`]: the same picture
/// coded as a KEY frame under a FULL, non-still sequence header
/// (`still_picture = 0` — one sync sample of an all-intra AV1 video)
/// with the same quality / speed / tile / thread controls. The
/// framework encoder's `still = false` arm.
///
/// ## Errors
///
/// As [`encode_still_yuv`].
pub fn encode_key_frame_yuv_with_options(
    input: &YuvFrame,
    opts: &StillOptions,
) -> Result<EncodedStill, Error> {
    encode_intra_yuv(input, opts, false)
}

fn encode_intra_yuv(
    input: &YuvFrame,
    opts: &StillOptions,
    still_picture: bool,
) -> Result<EncodedStill, Error> {
    // r464 — the §5.9.17 delta-q election is `Thorough`-only: on the
    // 12 MP photograph it cost 0.26 % BD-rate and doubled the
    // `Balanced` wall clock (a second complete tile search).
    let elections = opts.speed == StillSpeed::Thorough && opts.base_q_idx > 0;
    let tiles = if opts.auto_tiles {
        auto_tile_layout(input.width, input.height, opts.threads)
    } else {
        (opts.tile_cols_log2, opts.tile_rows_log2)
    };
    let mut search = match opts.speed {
        StillSpeed::Fast => crate::encoder::key_frame::SearchLimits::fast(),
        StillSpeed::Balanced => crate::encoder::key_frame::SearchLimits::balanced(),
        StillSpeed::Thorough => crate::encoder::key_frame::SearchLimits::default(),
    };
    search.threads = opts.threads.max(1);
    let extras = KeyExtras {
        tiles,
        delta_q: elections,
        // The §5.9.12 quantizer-matrix election trades PSNR for bytes
        // (a perceptual shaping); it stays a `Thorough`-only arm.
        qm: opts.speed == StillSpeed::Thorough && opts.base_q_idx > 0,
        superres_elect: opts.speed == StillSpeed::Thorough && opts.base_q_idx > 0,
        still: still_picture && opts.reduced_header,
        full_range: opts.full_range,
        still_full_header: still_picture && !opts.reduced_header,
        color_description: opts.color_description,
        search,
        ..KeyExtras::default()
    };
    let (k, _carry) = encode_key_frame_yuv_full(
        input,
        opts.base_q_idx,
        RateModel::Twin,
        &[],
        None,
        true,
        true,
        true,
        &extras,
    )?;
    Ok(EncodedStill::from_key(k))
}

/// The [`StillOptions::auto_tiles`] layout: `(TileColsLog2,
/// TileRowsLog2)` for a `width × height` picture searched on
/// `threads` threads — columns first (tiles ≥ 256 px wide), then rows
/// (tiles ≥ 128 px tall), never more tiles than
/// `threads.next_power_of_two()`.
#[must_use]
pub fn auto_tile_layout(width: u32, height: u32, threads: usize) -> (u32, u32) {
    let target = threads.max(1).next_power_of_two();
    let sb_cols = width.div_ceil(64);
    let sb_rows = height.div_ceil(64);
    let (mut cols_log2, mut rows_log2) = (0u32, 0u32);
    while (1usize << (cols_log2 + 1)) <= target && (sb_cols >> (cols_log2 + 1)) >= 4 {
        cols_log2 += 1;
    }
    while (1usize << (cols_log2 + rows_log2 + 1)) <= target && (sb_rows >> (rows_log2 + 1)) >= 2 {
        rows_log2 += 1;
    }
    (cols_log2, rows_log2)
}

/// 8-bit 4:2:0 sibling of [`encode_still_yuv`].
pub fn encode_still_yuv420(
    input: &Yuv420Frame,
    opts: &StillOptions,
) -> Result<EncodedStill, Error> {
    encode_still_yuv(&YuvFrame::from_yuv420_8bit(input), opts)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::decoder::decode_av1_spec;
    use crate::encoder::yuv_frame::ChromaFormat;

    fn textured(width: u32, height: u32, bit_depth: u8, format: ChromaFormat) -> YuvFrame {
        let mut f = YuvFrame::filled(width, height, bit_depth, format, 0);
        let max = (1u32 << bit_depth) - 1;
        for y in 0..height {
            for x in 0..width {
                let v = (x * 37 + y * 91 + (x * y) % 23) * max / (width * 37 + height * 91 + 23);
                f.y[(y * width + x) as usize] = v as u16;
            }
        }
        let (cw, ch) = (f.chroma_width(), f.chroma_height());
        for y in 0..ch {
            for x in 0..cw {
                f.u[(y * cw + x) as usize] = ((x * 53 + y * 7) % max) as u16;
                f.v[(y * cw + x) as usize] = ((x * 11 + y * 61) % max) as u16;
            }
        }
        f
    }

    fn assert_decodes_to_recon(still: &EncodedStill, bit_depth: u8) {
        let frames = decode_av1_spec(&still.ivf_bytes).expect("still decodes");
        assert_eq!(frames.len(), 1);
        let f = &frames[0];
        let widen = |p: &[u8]| -> Vec<u16> {
            if bit_depth > 8 {
                p.chunks(2)
                    .map(|c| u16::from_le_bytes([c[0], c[1]]))
                    .collect()
            } else {
                p.iter().map(|&b| u16::from(b)).collect()
            }
        };
        assert_eq!(widen(&f.planes[0]), still.recon_y, "luma");
        if f.planes.len() > 1 {
            assert_eq!(widen(&f.planes[1]), still.recon_u, "u");
            assert_eq!(widen(&f.planes[2]), still.recon_v, "v");
        } else {
            assert!(still.recon_u.is_empty());
        }
    }

    #[test]
    fn level_election_follows_annex_a_picture_limits() {
        assert_eq!(elect_seq_level_idx(426, 240), 0);
        assert_eq!(elect_seq_level_idx(640, 480), 4);
        assert_eq!(elect_seq_level_idx(1280, 720), 5);
        assert_eq!(elect_seq_level_idx(1920, 1080), 8);
        assert_eq!(elect_seq_level_idx(3840, 2160), 12);
        assert_eq!(elect_seq_level_idx(4032, 3024), 16);
        assert_eq!(elect_seq_level_idx(2048, 1152), 8);
        assert_eq!(elect_seq_level_idx(512, 288), 0);
        assert_eq!(elect_seq_level_idx(2049, 8), 1);
        assert_eq!(elect_seq_level_idx(16385, 8), SEQ_LEVEL_IDX_MAX_PARAMETERS);
        assert_eq!(elect_seq_level_idx(8, 8705), SEQ_LEVEL_IDX_MAX_PARAMETERS);
    }

    #[test]
    fn quality_dial_endpoints() {
        assert_eq!(quality_to_base_q_idx(100), 0);
        assert_eq!(quality_to_base_q_idx(0), 255);
        assert_eq!(quality_to_base_q_idx(50), 128);
        assert_eq!(quality_to_base_q_idx(200), 0);
    }

    #[test]
    fn reduced_still_round_trips_every_format_pairing() {
        for &(bd, fmt) in &[
            (8u8, ChromaFormat::Yuv420),
            (8, ChromaFormat::Monochrome),
            (10, ChromaFormat::Yuv422),
            (12, ChromaFormat::Yuv444),
        ] {
            let input = textured(48, 40, bd, fmt);
            let still = encode_still_yuv(&input, &StillOptions::new(96)).expect("still encodes");
            assert!(still.seq.still_picture && still.seq.reduced_still_picture_header);
            assert_eq!(still.seq.operating_points.len(), 1);
            assert_eq!(still.seq.operating_points[0].seq_level_idx, 0);
            assert!(!still.seq.enable_order_hint && still.seq.order_hint_bits == 0);
            assert!(still.fh.disable_frame_end_update_cdf);
            assert_eq!(still.codec_config.bit_depth(), bd);
            assert_eq!(
                still.codec_config.monochrome,
                fmt == ChromaFormat::Monochrome
            );
            assert!(still.codec_config.matches_sequence_header(&still.seq));
            assert_decodes_to_recon(&still, bd);
        }
    }

    #[test]
    fn lossless_still_reproduces_the_input() {
        let input = textured(40, 24, 8, ChromaFormat::Yuv420);
        let still =
            encode_still_yuv(&input, &StillOptions::new(0)).expect("lossless still encodes");
        assert_eq!(still.recon_y, input.y);
        assert_eq!(still.recon_u, input.u);
        assert_eq!(still.recon_v, input.v);
        assert_decodes_to_recon(&still, 8);
    }

    #[test]
    fn full_header_still_and_options_round_trip() {
        let input = textured(64, 32, 8, ChromaFormat::Yuv420);
        let mut opts = StillOptions::new(140);
        opts.reduced_header = false;
        opts.full_range = true;
        opts.speed = StillSpeed::Fast;
        opts.color_description = Some((1, 13, 6));
        let still = encode_still_yuv(&input, &opts).expect("full-header still encodes");
        assert!(still.seq.still_picture && !still.seq.reduced_still_picture_header);
        assert!(still.seq.color_config.color_range);
        let cc = &still.seq.color_config;
        assert!(cc.color_description_present_flag);
        assert_eq!(
            (
                cc.color_primaries,
                cc.transfer_characteristics,
                cc.matrix_coefficients
            ),
            (1, 13, 6)
        );
        let reparsed = crate::sequence_header::parse_sequence_header(
            crate::obu::ObuIter::new(&still.temporal_unit_bytes)
                .filter_map(Result::ok)
                .find(|d| d.obu_type == crate::obu::ObuType::SequenceHeader)
                .expect("sequence header")
                .payload,
        )
        .expect("parses");
        assert_eq!(reparsed.color_config, still.seq.color_config);
        assert_eq!(still.seq.operating_points[0].seq_level_idx, 0);
        assert_decodes_to_recon(&still, 8);

        let yuv420 = Yuv420Frame::filled(16, 16, 77);
        let s2 = encode_still_yuv420(&yuv420, &StillOptions::default()).expect("encodes");
        assert_eq!(s2.recon_y.len(), 256);
        assert_decodes_to_recon(&s2, 8);
    }

    /// r460 — any extent: non-multiple-of-8 / tiny pictures code
    /// their true `frame_size` (padded to the mi grid internally),
    /// decode to the cropped reconstruction, and reproduce the input
    /// losslessly.
    #[test]
    fn arbitrary_extent_stills_round_trip() {
        for &(w, h, bd, fmt, q) in &[
            (37u32, 19u32, 8u8, ChromaFormat::Yuv420, 0u8),
            (37, 19, 8, ChromaFormat::Yuv420, 110),
            (1, 1, 8, ChromaFormat::Yuv420, 90),
            (3, 5, 8, ChromaFormat::Monochrome, 0),
            (7, 3, 10, ChromaFormat::Yuv444, 60),
            (65, 9, 12, ChromaFormat::Yuv422, 140),
            (16, 13, 8, ChromaFormat::Yuv420, 200),
            (9, 7, 8, ChromaFormat::Yuv420, 0),
            (9, 7, 8, ChromaFormat::Yuv420, 120),
        ] {
            let input = textured(w, h, bd, fmt);
            assert_eq!(
                input.chroma_width(),
                if fmt == ChromaFormat::Monochrome {
                    0
                } else {
                    (w + u32::from(fmt.subsampling().0)) >> fmt.subsampling().0
                }
            );
            let mut opts = StillOptions::new(q);
            opts.speed = StillSpeed::Fast;
            let still = encode_still_yuv(&input, &opts)
                .unwrap_or_else(|e| panic!("{w}x{h} {bd}-bit {fmt:?} q{q}: {e:?}"));
            let fs = still.fh.frame_size.as_ref().expect("frame size");
            assert_eq!((fs.frame_width, fs.frame_height), (w, h));
            assert_eq!(still.seq.max_frame_width_minus_1 + 1, w);
            assert_eq!(still.recon_y.len(), (w * h) as usize);
            assert_eq!(
                still.recon_u.len(),
                (input.chroma_width() * input.chroma_height()) as usize
            );
            if q == 0 {
                assert_eq!(still.recon_y, input.y, "{w}x{h}: lossless luma");
                assert_eq!(still.recon_u, input.u, "{w}x{h}: lossless u");
            }
            assert_decodes_to_recon(&still, bd);
        }
    }

    /// r460 — the threaded tile search is bit-identical to the
    /// sequential walk of the same layout.
    #[test]
    fn threaded_tile_search_is_bit_identical() {
        let input = textured(320, 192, 8, ChromaFormat::Yuv420);
        let mut seq_opts = StillOptions::new(120);
        seq_opts.speed = StillSpeed::Fast;
        seq_opts.tile_cols_log2 = 1;
        seq_opts.tile_rows_log2 = 1;
        let mut par_opts = seq_opts;
        par_opts.threads = 4;
        let a = encode_still_yuv(&input, &seq_opts).expect("sequential");
        let b = encode_still_yuv(&input, &par_opts).expect("threaded");
        assert_eq!(a.temporal_unit_bytes, b.temporal_unit_bytes);
        assert_eq!(a.recon_y, b.recon_y);
        assert_eq!(a.recon_u, b.recon_u);
        assert_decodes_to_recon(&b, 8);
        assert_eq!(auto_tile_layout(4032, 3024, 8), (3, 0));
        assert_eq!(auto_tile_layout(4032, 3024, 4), (2, 0));
        assert_eq!(auto_tile_layout(640, 480, 8), (1, 2));
        assert_eq!(auto_tile_layout(64, 64, 8), (0, 0));
        let auto = StillOptions::new(120).threads(4);
        assert!(auto.auto_tiles && auto.threads == 4);
    }

    /// r460 — a picture above `MAX_TILE_AREA` (12 MP) cannot be one
    /// tile: the requested `(0, 0)` layout is raised to the §5.9.15
    /// legal minimum instead of being refused. (Flat content keeps
    /// the witness fast; the geometry is what is pinned.)
    #[test]
    fn oversize_pictures_take_the_minimum_legal_tile_layout() {
        assert_eq!(
            crate::tile_info::TileInfo::min_uniform_layout(2 * 4032 / 8, 2 * 3024 / 8, false),
            Some((0, 1))
        );
        assert_eq!(
            crate::tile_info::TileInfo::min_uniform_layout(2 * 640 / 8, 2 * 480 / 8, false),
            Some((0, 0))
        );
        let input = YuvFrame::filled(4096, 2432, 8, ChromaFormat::Monochrome, 90);
        let mut opts = StillOptions::new(200);
        opts.speed = StillSpeed::Fast;
        let still = encode_still_yuv(&input, &opts).expect("12 MP still encodes");
        let ti = still.fh.tile_info.as_ref().expect("tile info");
        assert!(
            ti.tile_cols * ti.tile_rows >= 2,
            "{}x{}",
            ti.tile_cols,
            ti.tile_rows
        );
        assert_eq!(still.seq.operating_points[0].seq_level_idx, 16);
    }

    #[test]
    fn tiled_still_round_trips() {
        let input = textured(256, 128, 8, ChromaFormat::Yuv420);
        let mut opts = StillOptions::new(110);
        opts.tile_cols_log2 = 1;
        opts.tile_rows_log2 = 1;
        opts.speed = StillSpeed::Fast;
        let still = encode_still_yuv(&input, &opts).expect("tiled still encodes");
        let ti = still.fh.tile_info.as_ref().expect("tile info");
        assert_eq!((ti.tile_cols, ti.tile_rows), (2, 2));
        assert_decodes_to_recon(&still, 8);
    }
}