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
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
//! `tile_info()` sub-syntax (§5.9.15) — round 6 of the clean-room
//! rebuild.
//!
//! The function takes the post-`compute_image_size()` `MiCols` /
//! `MiRows` derived in §5.9.9, plus the sequence-header
//! `use_128x128_superblock` bit (§5.5.1), and walks the per-frame tile
//! layout: either a uniform spacing path that reads
//! `increment_tile_cols_log2` / `increment_tile_rows_log2` until the
//! `TileColsLog2` / `TileRowsLog2` counts saturate against
//! `maxLog2TileCols` / `maxLog2TileRows`, or a non-uniform path that
//! reads `width_in_sbs_minus_1` / `height_in_sbs_minus_1` via the §4.10.7
//! `ns(n)` descriptor.
//!
//! ## Syntax / semantics references (all in `docs/video/av1/`)
//!
//!   * §3 — `MAX_TILE_WIDTH = 4096`, `MAX_TILE_AREA = 4096 * 2304`,
//!     `MAX_TILE_ROWS = 64`, `MAX_TILE_COLS = 64`, `MI_SIZE = 4`.
//!   * §4.7 — `FloorLog2(x)` helper.
//!   * §4.10.7 — `ns(n)` descriptor used for `width_in_sbs_minus_1`
//!     and `height_in_sbs_minus_1`.
//!   * §5.9.15 — `tile_info()` syntax (this file).
//!   * §5.9.16 — `tile_log2(blkSize, target)` helper function.
//!   * §6.8.14 — Tile info semantics + conformance constraints
//!     (`TileCols <= MAX_TILE_COLS`, `TileRows <= MAX_TILE_ROWS`,
//!     `tileWidthSb < maxTileWidthSb`,
//!     `tileWidthSb * tileHeightSb < maxTileAreaSb`,
//!     `context_update_tile_id < TileCols * TileRows`).

use crate::bitreader::BitReader;
use crate::Error;

// ---------------------------------------------------------------------
// §3 constants
// ---------------------------------------------------------------------

/// `MAX_TILE_WIDTH` per §3 — maximum tile width in luma samples.
pub const MAX_TILE_WIDTH: u32 = 4096;

/// `MAX_TILE_AREA` per §3 — maximum tile area in luma samples.
pub const MAX_TILE_AREA: u32 = 4096 * 2304;

/// `MAX_TILE_ROWS` per §3 — maximum number of tile rows in a frame.
pub const MAX_TILE_ROWS: u32 = 64;

/// `MAX_TILE_COLS` per §3 — maximum number of tile columns in a frame.
pub const MAX_TILE_COLS: u32 = 64;

// ---------------------------------------------------------------------
// §5.9.16 tile_log2 helper
// ---------------------------------------------------------------------

/// `tile_log2(blkSize, target)` per §5.9.16 — smallest `k` such that
/// `blkSize << k >= target`.
fn tile_log2(blk_size: u32, target: u32) -> u32 {
    let mut k = 0u32;
    while (blk_size << k) < target {
        k += 1;
    }
    k
}

// ---------------------------------------------------------------------
// TileInfo (§6.8.14)
// ---------------------------------------------------------------------

/// Parsed `tile_info()` per §5.9.15.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TileInfo {
    /// `uniform_tile_spacing_flag` per §6.8.14.
    pub uniform_tile_spacing_flag: bool,
    /// `TileCols` — number of tiles across the frame (`<= MAX_TILE_COLS`
    /// per §6.8.14 conformance).
    pub tile_cols: u32,
    /// `TileRows` — number of tiles down the frame (`<= MAX_TILE_ROWS`).
    pub tile_rows: u32,
    /// `TileColsLog2` — base-2 logarithm of the desired number of
    /// tiles across the frame. May exceed `log2(tile_cols)` when small
    /// frame sizes force the actual tile count to be smaller than the
    /// desired count (§6.8.14 note: "the tile size is rounded up to a
    /// multiple of the maximum superblock size").
    pub tile_cols_log2: u32,
    /// `TileRowsLog2` — base-2 logarithm of the desired number of
    /// tiles down the frame.
    pub tile_rows_log2: u32,
    /// `context_update_tile_id` per §6.8.14 — which tile's CDFs are
    /// snapshotted at the `disable_frame_end_update_cdf == 0` end-of-
    /// frame update. `0` when both `TileColsLog2 == 0 &&
    /// TileRowsLog2 == 0` (the `f(TileRowsLog2 + TileColsLog2)` read is
    /// skipped because the field has zero bit width).
    pub context_update_tile_id: u32,
    /// `TileSizeBytes` per §6.8.14 — the number of bytes used to code
    /// each tile size in the §5.11 tile group OBU. `1` when both
    /// `TileColsLog2 == 0 && TileRowsLog2 == 0` (the
    /// `tile_size_bytes_minus_1` field is skipped and the spec leaves
    /// `TileSizeBytes` undefined; we surface the no-read default of `1`
    /// — the value never matters because a single-tile frame has no
    /// inter-tile size fields).
    pub tile_size_bytes: u8,
    /// `MiColStarts[0..=TileCols]` per §6.8.14 — start column (in units
    /// of 4×4 luma samples) for each tile across the image plus the
    /// sentinel `MiColStarts[TileCols] == MiCols`.
    pub mi_col_starts: Vec<u32>,
    /// `MiRowStarts[0..=TileRows]` per §6.8.14 — start row for each
    /// tile down the image plus the sentinel `MiRowStarts[TileRows] ==
    /// MiRows`.
    pub mi_row_starts: Vec<u32>,
}

impl TileInfo {
    /// Convenience for the degenerate `tile_cols == 1 && tile_rows == 1`
    /// case — every fixture in `docs/video/av1/fixtures/` except
    /// `tile-cols-2-rows-1` lands here.
    pub fn is_single_tile(&self) -> bool {
        self.tile_cols == 1 && self.tile_rows == 1
    }

    /// r431 — encoder-side §5.9.15 **uniform-spacing** layout builder:
    /// the exact `TileInfo` the parser's uniform path derives for the
    /// requested `(TileColsLog2, TileRowsLog2)` pair on a `mi_cols ×
    /// mi_rows` frame. The write side
    /// (`crate::encoder::frame_obu::encode_tile_info`) re-derives the
    /// increment-bit walk from these fields, so `parse(encode(ti)) ==
    /// ti` holds by construction.
    ///
    /// Returns `None` when the requested pair falls outside the
    /// §5.9.15 legal window:
    ///
    ///   * `tile_cols_log2` outside
    ///     `[minLog2TileCols, maxLog2TileCols]`, or
    ///   * `tile_rows_log2` outside
    ///     `[max(minLog2Tiles - tile_cols_log2, 0), maxLog2TileRows]`
    ///
    /// (the uniform path can only *reach* log2 values inside those
    /// windows — the increment bits saturate at the bounds).
    ///
    /// `tile_size_bytes` is seeded to `4` (§6.8.14 upper bound);
    /// multi-tile assemblers shrink it to the realized minimum once
    /// the per-tile payload sizes are known (the header's
    /// `tile_size_bytes_minus_1` is a fixed-width `f(2)`, so the
    /// header LENGTH is independent of the final value).
    /// `context_update_tile_id` is seeded to `0`.
    ///
    /// r460 — the smallest §5.9.15 uniform layout `(TileColsLog2,
    /// TileRowsLog2)` a `mi_cols × mi_rows` frame admits (the
    /// `MAX_TILE_WIDTH` / `MAX_TILE_AREA` floors: a 12 MP picture
    /// cannot be one tile), `None` for an empty frame.
    #[must_use]
    pub fn min_uniform_layout(
        mi_cols: u32,
        mi_rows: u32,
        use_128x128_superblock: bool,
    ) -> Option<(u32, u32)> {
        if mi_cols == 0 || mi_rows == 0 {
            return None;
        }
        let (sb_cols, sb_rows, sb_shift) = if use_128x128_superblock {
            ((mi_cols + 31) >> 5, (mi_rows + 31) >> 5, 5u32)
        } else {
            ((mi_cols + 15) >> 4, (mi_rows + 15) >> 4, 4u32)
        };
        let sb_size = sb_shift + 2;
        let max_tile_width_sb = MAX_TILE_WIDTH >> sb_size;
        let max_tile_area_sb = MAX_TILE_AREA >> (2 * sb_size);
        let min_log2_tile_cols = tile_log2(max_tile_width_sb, sb_cols);
        let min_log2_tiles = min_log2_tile_cols.max(tile_log2(max_tile_area_sb, sb_rows * sb_cols));
        Some((
            min_log2_tile_cols,
            min_log2_tiles.saturating_sub(min_log2_tile_cols),
        ))
    }

    /// §5.9.15 uniform tile layout for a `(TileColsLog2, TileRowsLog2)`
    /// pair inside the legal window (see the doc block above);
    /// `tile_size_bytes` is seeded to `1` and patched once the
    /// per-tile payload sizes are known, `context_update_tile_id` to
    /// `0`.
    #[must_use]
    pub fn uniform_layout(
        mi_cols: u32,
        mi_rows: u32,
        use_128x128_superblock: bool,
        tile_cols_log2: u32,
        tile_rows_log2: u32,
    ) -> Option<TileInfo> {
        if mi_cols == 0 || mi_rows == 0 {
            return None;
        }
        // §5.9.15 lead-in derivations (identical to `read_tile_info`).
        let (sb_cols, sb_rows, sb_shift) = if use_128x128_superblock {
            ((mi_cols + 31) >> 5, (mi_rows + 31) >> 5, 5u32)
        } else {
            ((mi_cols + 15) >> 4, (mi_rows + 15) >> 4, 4u32)
        };
        let sb_size = sb_shift + 2;
        let max_tile_width_sb = MAX_TILE_WIDTH >> sb_size;
        let max_tile_area_sb = MAX_TILE_AREA >> (2 * sb_size);
        let min_log2_tile_cols = tile_log2(max_tile_width_sb, sb_cols);
        let max_log2_tile_cols = tile_log2(1, sb_cols.min(MAX_TILE_COLS));
        let max_log2_tile_rows = tile_log2(1, sb_rows.min(MAX_TILE_ROWS));
        let min_log2_tiles = min_log2_tile_cols.max(tile_log2(max_tile_area_sb, sb_rows * sb_cols));

        if tile_cols_log2 < min_log2_tile_cols || tile_cols_log2 > max_log2_tile_cols {
            return None;
        }
        let min_log2_tile_rows = min_log2_tiles.saturating_sub(tile_cols_log2);
        if tile_rows_log2 < min_log2_tile_rows || tile_rows_log2 > max_log2_tile_rows {
            return None;
        }

        // §5.9.15 uniform column walk.
        let tile_width_sb = (sb_cols + (1u32 << tile_cols_log2) - 1) >> tile_cols_log2;
        let mut mi_col_starts: Vec<u32> = Vec::new();
        let mut start_sb: u32 = 0;
        while start_sb < sb_cols {
            mi_col_starts.push(start_sb << sb_shift);
            start_sb += tile_width_sb;
        }
        let tile_cols = mi_col_starts.len() as u32;
        mi_col_starts.push(mi_cols);

        // §5.9.15 uniform row walk.
        let tile_height_sb = (sb_rows + (1u32 << tile_rows_log2) - 1) >> tile_rows_log2;
        let mut mi_row_starts: Vec<u32> = Vec::new();
        let mut start_sb: u32 = 0;
        while start_sb < sb_rows {
            mi_row_starts.push(start_sb << sb_shift);
            start_sb += tile_height_sb;
        }
        let tile_rows = mi_row_starts.len() as u32;
        mi_row_starts.push(mi_rows);

        Some(TileInfo {
            uniform_tile_spacing_flag: true,
            tile_cols,
            tile_rows,
            tile_cols_log2,
            tile_rows_log2,
            context_update_tile_id: 0,
            tile_size_bytes: 4,
            mi_col_starts,
            mi_row_starts,
        })
    }

    /// r433 — encoder-side §5.9.15 **non-uniform** (explicit) layout
    /// builder: the exact `TileInfo` the parser's
    /// `uniform_tile_spacing_flag = 0` path derives for the requested
    /// per-column widths / per-row heights (in superblock units). The
    /// write side (`crate::encoder::frame_obu::encode_tile_info`)
    /// re-derives the `width_in_sbs_minus_1` / `height_in_sbs_minus_1`
    /// `ns()` walk from the start arrays, so `parse(encode(ti)) == ti`
    /// holds by construction.
    ///
    /// Returns `None` when the layout falls outside the §5.9.15 legal
    /// window:
    ///
    ///   * `widths_sb` does not sum to the frame's superblock columns
    ///     (or `heights_sb` to its rows), an entry is zero, or a
    ///     count exceeds `MAX_TILE_COLS` / `MAX_TILE_ROWS`;
    ///   * a width exceeds `maxTileWidthSb`, or a height exceeds the
    ///     §5.9.15 `maxTileHeightSb = max( maxTileAreaSb /
    ///     widestTileSb, 1 )` bound (derived from the widest coded
    ///     column exactly as the parser derives it).
    ///
    /// `tile_size_bytes` / `context_update_tile_id` seed like
    /// [`TileInfo::uniform_layout`].
    #[must_use]
    pub fn explicit_layout(
        mi_cols: u32,
        mi_rows: u32,
        use_128x128_superblock: bool,
        widths_sb: &[u32],
        heights_sb: &[u32],
    ) -> Option<TileInfo> {
        if mi_cols == 0 || mi_rows == 0 || widths_sb.is_empty() || heights_sb.is_empty() {
            return None;
        }
        // §5.9.15 lead-in derivations (identical to `read_tile_info`).
        let (sb_cols, sb_rows, sb_shift) = if use_128x128_superblock {
            ((mi_cols + 31) >> 5, (mi_rows + 31) >> 5, 5u32)
        } else {
            ((mi_cols + 15) >> 4, (mi_rows + 15) >> 4, 4u32)
        };
        let sb_size = sb_shift + 2;
        let max_tile_width_sb = MAX_TILE_WIDTH >> sb_size;
        let max_tile_area_sb = MAX_TILE_AREA >> (2 * sb_size);
        let min_log2_tile_cols = tile_log2(max_tile_width_sb, sb_cols);
        let min_log2_tiles = min_log2_tile_cols.max(tile_log2(max_tile_area_sb, sb_rows * sb_cols));

        if widths_sb.len() as u32 > MAX_TILE_COLS || heights_sb.len() as u32 > MAX_TILE_ROWS {
            return None;
        }

        // §5.9.15 non-uniform column walk: each width must be codable
        // as `ns( min( sbCols - startSb, maxTileWidthSb ) )`.
        let mut mi_col_starts: Vec<u32> = Vec::with_capacity(widths_sb.len() + 1);
        let mut widest_tile_sb: u32 = 0;
        let mut start_sb: u32 = 0;
        for &w in widths_sb {
            if start_sb >= sb_cols {
                return None;
            }
            let max_width = (sb_cols - start_sb).min(max_tile_width_sb);
            if w == 0 || w > max_width {
                return None;
            }
            mi_col_starts.push(start_sb << sb_shift);
            widest_tile_sb = widest_tile_sb.max(w);
            start_sb += w;
        }
        if start_sb != sb_cols {
            return None;
        }
        mi_col_starts.push(mi_cols);
        let tile_cols = widths_sb.len() as u32;

        // §5.9.15 non-uniform row walk under the recomputed
        // `maxTileAreaSb` and the widest-column height bound.
        let max_tile_area_sb_local = if min_log2_tiles > 0 {
            (sb_rows * sb_cols) >> (min_log2_tiles + 1)
        } else {
            sb_rows * sb_cols
        };
        let max_tile_height_sb = (max_tile_area_sb_local / widest_tile_sb).max(1);
        let mut mi_row_starts: Vec<u32> = Vec::with_capacity(heights_sb.len() + 1);
        let mut start_sb: u32 = 0;
        for &h in heights_sb {
            if start_sb >= sb_rows {
                return None;
            }
            let max_height = (sb_rows - start_sb).min(max_tile_height_sb);
            if h == 0 || h > max_height {
                return None;
            }
            mi_row_starts.push(start_sb << sb_shift);
            start_sb += h;
        }
        if start_sb != sb_rows {
            return None;
        }
        mi_row_starts.push(mi_rows);
        let tile_rows = heights_sb.len() as u32;

        Some(TileInfo {
            uniform_tile_spacing_flag: false,
            tile_cols,
            tile_rows,
            tile_cols_log2: tile_log2(1, tile_cols),
            tile_rows_log2: tile_log2(1, tile_rows),
            context_update_tile_id: 0,
            tile_size_bytes: 4,
            mi_col_starts,
            mi_row_starts,
        })
    }

    /// The §5.11.51 [`crate::cdf::TileGeometry`] of tile number
    /// `tile_num` (row-major: `tile_row * TileCols + tile_col`), or
    /// `None` when out of range.
    #[must_use]
    pub fn tile_geometry(&self, tile_num: u32) -> Option<crate::cdf::TileGeometry> {
        if tile_num >= self.tile_cols * self.tile_rows {
            return None;
        }
        let tile_row = (tile_num / self.tile_cols) as usize;
        let tile_col = (tile_num % self.tile_cols) as usize;
        Some(crate::cdf::TileGeometry {
            mi_row_start: *self.mi_row_starts.get(tile_row)?,
            mi_row_end: *self.mi_row_starts.get(tile_row + 1)?,
            mi_col_start: *self.mi_col_starts.get(tile_col)?,
            mi_col_end: *self.mi_col_starts.get(tile_col + 1)?,
        })
    }
}

// ---------------------------------------------------------------------
// Parser
// ---------------------------------------------------------------------

/// Parse `tile_info()` per §5.9.15 from a bit-aligned byte slice.
///
/// `mi_cols` / `mi_rows` are the §5.9.9 `compute_image_size()`-derived
/// values (carried on [`crate::FrameSize::mi_cols`] /
/// [`crate::FrameSize::mi_rows`]). `use_128x128_superblock` is the
/// sequence-header bit (§5.5.1).
///
/// Returns `(TileInfo, bits_consumed)`. The caller is responsible for
/// positioning `payload` at the right bit — the standalone entry point
/// reads from bit 0.
///
/// ## Errors
///
///   * [`Error::UnexpectedEnd`] — payload exhausted mid-read.
pub fn parse_tile_info(
    payload: &[u8],
    mi_cols: u32,
    mi_rows: u32,
    use_128x128_superblock: bool,
) -> Result<(TileInfo, usize), Error> {
    let mut br = BitReader::new(payload);
    let ti = read_tile_info(&mut br, mi_cols, mi_rows, use_128x128_superblock)?;
    Ok((ti, br.position()))
}

pub(crate) fn read_tile_info(
    br: &mut BitReader<'_>,
    mi_cols: u32,
    mi_rows: u32,
    use_128x128_superblock: bool,
) -> Result<TileInfo, Error> {
    // §5.9.15 lead-in derivations.
    let (sb_cols, sb_rows, sb_shift) = if use_128x128_superblock {
        ((mi_cols + 31) >> 5, (mi_rows + 31) >> 5, 5u32)
    } else {
        ((mi_cols + 15) >> 4, (mi_rows + 15) >> 4, 4u32)
    };

    // §5.9.15 presupposes a conformant frame size: §5.9.5 frame_size()
    // requires FrameWidth/FrameHeight >= 1, so MiCols/MiRows >= 1 and
    // therefore sbCols/sbRows >= 1. The non-uniform branch leans on this
    // — `widestTileSb` is seeded to 0 and only raised inside the
    // `for (startSb = 0; startSb < sbCols; ...)` loop (spec lines
    // 3239-3253), then used as the divisor of `maxTileAreaSb /
    // widestTileSb` (line 3262). A malformed header that yields a zero
    // superblock dimension would skip the loop, leave widestTileSb == 0,
    // and divide by zero. Such a frame is not decodable, so reject it
    // with a typed error rather than allowing the panic.
    if sb_cols == 0 || sb_rows == 0 {
        return Err(Error::PartitionWalkOutOfRange);
    }
    let sb_size = sb_shift + 2;
    let max_tile_width_sb = MAX_TILE_WIDTH >> sb_size;
    let max_tile_area_sb = MAX_TILE_AREA >> (2 * sb_size);
    let min_log2_tile_cols = tile_log2(max_tile_width_sb, sb_cols);
    let max_log2_tile_cols = tile_log2(1, sb_cols.min(MAX_TILE_COLS));
    let max_log2_tile_rows = tile_log2(1, sb_rows.min(MAX_TILE_ROWS));
    let min_log2_tiles = min_log2_tile_cols.max(tile_log2(max_tile_area_sb, sb_rows * sb_cols));

    let uniform_tile_spacing_flag = br.f(1)? == 1;

    let mut mi_col_starts: Vec<u32> = Vec::new();
    let mut mi_row_starts: Vec<u32> = Vec::new();
    let tile_cols;
    let tile_rows;
    let tile_cols_log2;
    let tile_rows_log2;

    if uniform_tile_spacing_flag {
        // §5.9.15 uniform path.
        let mut tile_cols_log2_local = min_log2_tile_cols;
        while tile_cols_log2_local < max_log2_tile_cols {
            let increment = br.f(1)? == 1;
            if increment {
                tile_cols_log2_local += 1;
            } else {
                break;
            }
        }
        let tile_width_sb = (sb_cols + (1u32 << tile_cols_log2_local) - 1) >> tile_cols_log2_local;
        let mut i: u32 = 0;
        let mut start_sb: u32 = 0;
        while start_sb < sb_cols {
            mi_col_starts.push(start_sb << sb_shift);
            i += 1;
            start_sb += tile_width_sb;
        }
        mi_col_starts.push(mi_cols);
        tile_cols = i;

        let min_log2_tile_rows = min_log2_tiles.saturating_sub(tile_cols_log2_local);
        let mut tile_rows_log2_local = min_log2_tile_rows;
        while tile_rows_log2_local < max_log2_tile_rows {
            let increment = br.f(1)? == 1;
            if increment {
                tile_rows_log2_local += 1;
            } else {
                break;
            }
        }
        let tile_height_sb = (sb_rows + (1u32 << tile_rows_log2_local) - 1) >> tile_rows_log2_local;
        let mut i: u32 = 0;
        let mut start_sb: u32 = 0;
        while start_sb < sb_rows {
            mi_row_starts.push(start_sb << sb_shift);
            i += 1;
            start_sb += tile_height_sb;
        }
        mi_row_starts.push(mi_rows);
        tile_rows = i;

        tile_cols_log2 = tile_cols_log2_local;
        tile_rows_log2 = tile_rows_log2_local;
    } else {
        // §5.9.15 non-uniform path.
        let mut widest_tile_sb: u32 = 0;
        let mut start_sb: u32 = 0;
        let mut i: u32 = 0;
        while start_sb < sb_cols {
            mi_col_starts.push(start_sb << sb_shift);
            let max_width = (sb_cols - start_sb).min(max_tile_width_sb);
            // §4.10.7 ns(maxWidth).
            let width_in_sbs_minus_1 = br.ns(max_width.max(1))?;
            let size_sb = width_in_sbs_minus_1 + 1;
            widest_tile_sb = widest_tile_sb.max(size_sb);
            start_sb += size_sb;
            i += 1;
        }
        mi_col_starts.push(mi_cols);
        tile_cols = i;
        let tile_cols_log2_local = tile_log2(1, tile_cols);

        // Recompute maxTileAreaSb per §5.9.15 (it's overwritten in
        // the non-uniform branch).
        let max_tile_area_sb_local = if min_log2_tiles > 0 {
            (sb_rows * sb_cols) >> (min_log2_tiles + 1)
        } else {
            sb_rows * sb_cols
        };
        let max_tile_height_sb = (max_tile_area_sb_local / widest_tile_sb).max(1);

        let mut start_sb: u32 = 0;
        let mut i: u32 = 0;
        while start_sb < sb_rows {
            mi_row_starts.push(start_sb << sb_shift);
            let max_height = (sb_rows - start_sb).min(max_tile_height_sb);
            let height_in_sbs_minus_1 = br.ns(max_height.max(1))?;
            let size_sb = height_in_sbs_minus_1 + 1;
            start_sb += size_sb;
            i += 1;
        }
        mi_row_starts.push(mi_rows);
        tile_rows = i;
        let tile_rows_log2_local = tile_log2(1, tile_rows);

        tile_cols_log2 = tile_cols_log2_local;
        tile_rows_log2 = tile_rows_log2_local;
    }

    // §5.9.15 trailing fields: context_update_tile_id +
    // tile_size_bytes_minus_1 only when at least one of the log2
    // counts is > 0.
    let (context_update_tile_id, tile_size_bytes) = if tile_cols_log2 > 0 || tile_rows_log2 > 0 {
        let n = tile_rows_log2 + tile_cols_log2;
        let id = br.f(n)? as u32;
        // §6.8.14 (av1-spec p. ~378, semantic text): "It is a
        // requirement of bitstream conformance that
        // context_update_tile_id is less than TileCols * TileRows."
        // The field is coded with `f(TileRowsLog2 + TileColsLog2)`
        // bits, but `TileColsLog2` / `TileRowsLog2` are the *desired*
        // (ceil-log2) counts and may overshoot the realised
        // `TileCols` / `TileRows` (§6.8.14 note: small frames round
        // the tile size up to a whole superblock, so the actual tile
        // count can be smaller than `1 << TileColsLog2`). A malformed
        // header can therefore code an `id` in
        // `[TileCols * TileRows, 1 << n)` — a value that the §5.11
        // tile-group walk would later use to index a non-existent
        // tile. Reject it here with a typed error rather than carrying
        // an out-of-range tile id downstream.
        if id >= tile_cols * tile_rows {
            return Err(Error::PartitionWalkOutOfRange);
        }
        let tsb_minus_1 = br.f(2)? as u8;
        (id, tsb_minus_1 + 1)
    } else {
        (0, 1)
    };

    Ok(TileInfo {
        uniform_tile_spacing_flag,
        tile_cols,
        tile_rows,
        tile_cols_log2,
        tile_rows_log2,
        context_update_tile_id,
        tile_size_bytes,
        mi_col_starts,
        mi_row_starts,
    })
}

// =====================================================================
// Tests
// =====================================================================

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn tile_log2_smallest_k() {
        // tile_log2(1, 1) = 0  ( (1 << 0) >= 1 )
        assert_eq!(tile_log2(1, 1), 0);
        // tile_log2(1, 2) = 1
        assert_eq!(tile_log2(1, 2), 1);
        // tile_log2(1, 3) = 2  ( (1 << 1) = 2 < 3, (1 << 2) = 4 >= 3 )
        assert_eq!(tile_log2(1, 3), 2);
        // tile_log2(4, 8) = 1 ( (4 << 1) = 8 >= 8 )
        assert_eq!(tile_log2(4, 8), 1);
        // tile_log2(64, 4) = 0 ( (64 << 0) = 64 >= 4 )
        assert_eq!(tile_log2(64, 4), 0);
    }

    /// A 16×16 frame with `use_128x128_superblock = 0`: sbCols = 1,
    /// sbRows = 1 ⇒ `minLog2TileCols = 0`, `maxLog2TileCols = 0`,
    /// `maxLog2TileRows = 0`. The uniform-spacing path reads
    /// `uniform_tile_spacing_flag` and immediately falls through with
    /// `TileColsLog2 = 0`, `TileRowsLog2 = 0`. No
    /// `context_update_tile_id` / `tile_size_bytes_minus_1` is read.
    /// Total bits consumed: 1.
    #[test]
    fn tiny_16x16_single_tile() {
        // MiCols = MiRows = 4 (per round-4 derivation for 16×16).
        // bits: uniform_tile_spacing_flag = 1.  ⇒ first bit set.
        let payload = [0b1000_0000u8];
        let (ti, bits) = parse_tile_info(&payload, 4, 4, false).expect("parses");
        assert!(ti.uniform_tile_spacing_flag);
        assert_eq!(ti.tile_cols, 1);
        assert_eq!(ti.tile_rows, 1);
        assert_eq!(ti.tile_cols_log2, 0);
        assert_eq!(ti.tile_rows_log2, 0);
        assert_eq!(ti.context_update_tile_id, 0);
        assert_eq!(ti.tile_size_bytes, 1);
        assert_eq!(bits, 1);
        assert!(ti.is_single_tile());
        // MiColStarts = [0, MiCols], MiRowStarts = [0, MiRows].
        assert_eq!(ti.mi_col_starts, vec![0, 4]);
        assert_eq!(ti.mi_row_starts, vec![0, 4]);
    }

    /// A 256×64 frame with `use_128x128_superblock = 0` and
    /// `uniform_tile_spacing_flag = 1` matching the `tile-cols-2-rows-1`
    /// fixture's trace (`tile_cols = 2, tile_rows = 1`). Verifies the
    /// `increment_tile_cols_log2` bit walks the desired column count up
    /// to log2(2) = 1.
    #[test]
    fn synthetic_256x64_two_tile_columns() {
        // MiCols = 2 * ((256+7) >> 3) = 64, MiRows = 2 * ((64+7) >> 3) = 16.
        // sbCols = (64 + 15) >> 4 = 79 >> 4 = 4 (since 64 in MI units = 256
        //   luma samples; 79/16 = 4 with remainder, so 4 superblocks).
        // Actually (64+15)>>4 = 79>>4 = 4. sb_shift=4. sb_size=6.
        // maxTileWidthSb = 4096 >> 6 = 64. maxTileAreaSb = (4096*2304) >> 12 = 2304.
        // sbRows = (16+15) >> 4 = 1.
        // minLog2TileCols = tile_log2(64, 4) = 0.
        // maxLog2TileCols = tile_log2(1, min(4, 64)) = tile_log2(1, 4) = 2.
        // maxLog2TileRows = tile_log2(1, min(1, 64)) = 0.
        // minLog2Tiles = max(0, tile_log2(2304, 4)) = max(0, 0) = 0.
        //
        // Uniform path: TileColsLog2 starts at 0. While 0 < 2, read
        // increment. To reach TileColsLog2 = 1 we read 1 (increment),
        // then 0 (stop). 2 bits.
        // tileWidthSb = (4 + (1<<1) - 1) >> 1 = 5 >> 1 = 2. So:
        //   startSb=0 ⇒ MiColStarts[0] = 0; i=1; startSb=2.
        //   startSb=2 ⇒ MiColStarts[1] = 2<<4 = 32; i=2; startSb=4.
        //   startSb=4 stops. MiColStarts[2] = 64. TileCols = 2.
        // minLog2TileRows = max(0 - 1, 0) = 0. TileRowsLog2 = 0;
        // 0 < 0 is false. No row increments. tileHeightSb = 1.
        //   startSb=0 ⇒ MiRowStarts[0] = 0; i=1; startSb=1.
        //   startSb=1 stops. MiRowStarts[1] = 16. TileRows = 1.
        // TileColsLog2 = 1, TileRowsLog2 = 0 ⇒ read context_update_tile_id
        // as f(1) and tile_size_bytes_minus_1 as f(2). For tile_cols=2,
        // context_update_tile_id < 2 ⇒ legal values 0 or 1.
        //
        // Bits: uniform_tile_spacing=1; increment_cols=1; increment_cols_stop=0;
        //       context_update_tile_id(1)=0; tile_size_bytes_minus_1(2)=00
        //       (⇒ TileSizeBytes = 1).
        // Total: 1+1+1+1+2 = 6 bits. = 0b110_0_00_00 = 0xC0.
        let payload = [0b1100_0000u8];
        let (ti, bits) = parse_tile_info(&payload, 64, 16, false).expect("parses");
        assert!(ti.uniform_tile_spacing_flag);
        assert_eq!(ti.tile_cols, 2);
        assert_eq!(ti.tile_rows, 1);
        assert_eq!(ti.tile_cols_log2, 1);
        assert_eq!(ti.tile_rows_log2, 0);
        assert_eq!(ti.context_update_tile_id, 0);
        assert_eq!(ti.tile_size_bytes, 1);
        assert_eq!(bits, 6);
        // MiColStarts = [0, 32, 64], MiRowStarts = [0, 16].
        assert_eq!(ti.mi_col_starts, vec![0, 32, 64]);
        assert_eq!(ti.mi_row_starts, vec![0, 16]);
    }

    /// 64×64 with `use_128x128_superblock = 0`, uniform spacing.
    /// sbCols = sbRows = 1 ⇒ everything collapses to a single tile,
    /// just like 16×16. 1 bit consumed.
    #[test]
    fn frame_64x64_single_superblock() {
        // MiCols = MiRows = 16. sbCols = (16+15)>>4 = 1; sbRows similarly.
        // Only 1 bit consumed (uniform_tile_spacing).
        let payload = [0b1000_0000u8];
        let (ti, bits) = parse_tile_info(&payload, 16, 16, false).expect("parses");
        assert_eq!(ti.tile_cols, 1);
        assert_eq!(ti.tile_rows, 1);
        assert_eq!(bits, 1);
        assert_eq!(ti.mi_col_starts, vec![0, 16]);
        assert_eq!(ti.mi_row_starts, vec![0, 16]);
    }

    /// 128×128 superblock mode: ensure the `sb_shift = 5` path is
    /// exercised. With a 128×128 frame and use_128x128_superblock = 1:
    /// MiCols = MiRows = 32. sbCols = (32+31)>>5 = 1.
    #[test]
    fn frame_128x128_with_128_superblock() {
        let payload = [0b1000_0000u8];
        let (ti, bits) = parse_tile_info(&payload, 32, 32, true).expect("parses");
        assert_eq!(ti.tile_cols, 1);
        assert_eq!(ti.tile_rows, 1);
        assert_eq!(bits, 1);
        // sb_shift = 5 ⇒ mi_col_starts[0] = 0 (single tile).
        assert_eq!(ti.mi_col_starts, vec![0, 32]);
        assert_eq!(ti.mi_row_starts, vec![0, 32]);
    }

    /// Non-uniform tile spacing. Construct a 2-column layout on a
    /// 256-luma-wide frame (MiCols = 64, sbCols = 4), with
    /// `width_in_sbs_minus_1` values 1 (⇒ tile #0 = 2 SBs) then 1
    /// (⇒ tile #1 = 2 SBs), then a single-row layout
    /// `height_in_sbs_minus_1 = 0` (⇒ tile = 1 SB).
    ///
    /// `max_width` on the first iteration = min(4, 64) = 4 ⇒ ns(4) ⇒
    /// `value = 1` encoded as `01` (2 bits).
    /// Second iteration `max_width = min(4-2, 64) = 2` ⇒ ns(2):
    /// w = 2, m = (1 << 2) - 2 = 2. v = f(1). Possible v in {0, 1};
    /// v < m for both ⇒ no extra bit. v = 1 encodes value 1, 1 bit.
    /// Loop stops at start_sb=4=sb_cols.
    /// TileCols = 2. TileColsLog2 = tile_log2(1, 2) = 1.
    /// max_tile_area_sb_local: min_log2_tiles is recomputed via local
    /// = 0 here (sbCols=4, sbRows=1 ⇒ sbRows*sbCols=4; min_log2_tiles is
    /// computed early as max(minLog2TileCols, tile_log2(maxTileAreaSb,
    /// sbRows*sbCols)) = max(0, tile_log2(2304, 4)) = 0; since
    /// min_log2_tiles == 0, max_tile_area_sb_local = 4).
    /// widest_tile_sb = 2. max_tile_height_sb = max(4/2, 1) = 2.
    /// Row loop: max_height = min(1-0, 2) = 1 ⇒ ns(1) reads 0 bits and
    /// returns 0. size_sb = 1. start_sb = 1. Loop exits.
    /// TileRows = 1. TileRowsLog2 = tile_log2(1, 1) = 0.
    /// Trailing: TileColsLog2=1, TileRowsLog2=0 ⇒ read context(1) +
    /// tile_size_bytes_minus_1(2).
    /// Bit string: uniform=0, col0 ns=01, col1 ns=1, [row: 0 bits],
    /// context(1)=0, tsb(2)=00.
    /// = 0 01 1 0 00 = 7 bits = 0b0011_0000 = 0x30.
    #[test]
    fn non_uniform_two_tile_columns() {
        let payload = [0b0011_0000u8];
        let (ti, bits) = parse_tile_info(&payload, 64, 16, false).expect("parses");
        assert!(!ti.uniform_tile_spacing_flag);
        assert_eq!(ti.tile_cols, 2);
        assert_eq!(ti.tile_rows, 1);
        assert_eq!(ti.tile_cols_log2, 1);
        assert_eq!(ti.tile_rows_log2, 0);
        assert_eq!(ti.context_update_tile_id, 0);
        assert_eq!(ti.tile_size_bytes, 1);
        assert_eq!(bits, 7);
        // sb_shift = 4. First tile starts at 0 ⇒ mi 0; second starts at
        // 2 SB = 2 << 4 = 32; sentinel = 64.
        assert_eq!(ti.mi_col_starts, vec![0, 32, 64]);
        assert_eq!(ti.mi_row_starts, vec![0, 16]);
    }

    #[test]
    fn truncated_payload_returns_unexpected_end() {
        let err = parse_tile_info(&[], 4, 4, false).expect_err("empty payload");
        assert_eq!(err, Error::UnexpectedEnd);
    }

    /// §6.8.14: `context_update_tile_id` must be `< TileCols *
    /// TileRows`. The field is coded with `f(TileRowsLog2 +
    /// TileColsLog2)` bits, and `TileColsLog2` can overshoot the
    /// realised `TileCols` (§6.8.14 small-frame note), so an attacker
    /// can code an id in `[TileCols * TileRows, 1 << n)`. Such a value
    /// must be rejected before it can index a non-existent tile in the
    /// §5.11 tile-group walk.
    ///
    /// Construct the overshoot: a 48×16-MI frame
    /// (`use_128x128_superblock = 0`) has `sbCols = (48+15)>>4 = 3`,
    /// `sbRows = (16+15)>>4 = 1`, `sb_size = 6`, `maxTileWidthSb =
    /// 4096>>6 = 64`. `minLog2TileCols = tile_log2(64, 3) = 0`,
    /// `maxLog2TileCols = tile_log2(1, 3) = 2`, `maxLog2TileRows =
    /// tile_log2(1, 1) = 0`. Driving `TileColsLog2` up to 2
    /// (`increment = 1, 1`) gives `tileWidthSb = ceil(3 / 4) = 1`, so
    /// the column loop realises `TileCols = 3` while `TileColsLog2 =
    /// 2`. `TileRows = 1`, `TileRowsLog2 = 0`, so the trailing field
    /// is `f(2)` — id `3` (binary `11`) is `>= TileCols * TileRows =
    /// 3` and must be rejected; id `2` is the largest legal value.
    #[test]
    fn context_update_tile_id_out_of_range_rejected() {
        // Bits: uniform=1, inc_col=1, inc_col=1 (log2 saturates at 2),
        // no row reads, context_update_tile_id = f(2) = 11 = 3.
        // = 1 1 1 11 = 0b1111_1000 = 0xF8. The fifth bit completes the
        // illegal id read; the conformance guard fires before the
        // tile_size_bytes_minus_1 read, so no further bits are needed.
        let payload = [0b1111_1000u8];
        let err = parse_tile_info(&payload, 48, 16, false)
            .expect_err("context_update_tile_id == 3 must be rejected (TileCols*TileRows == 3)");
        assert_eq!(err, Error::PartitionWalkOutOfRange);
    }

    /// Companion to [`context_update_tile_id_out_of_range_rejected`]:
    /// the same layout with the largest *legal* id (`2 < 3`) parses
    /// cleanly. Confirms the guard does not over-reject in-range ids.
    #[test]
    fn context_update_tile_id_max_in_range_accepted() {
        // Bits: uniform=1, inc_col=1, inc_col=1, id = f(2) = 10 = 2,
        // tile_size_bytes_minus_1 = f(2) = 00 (TileSizeBytes = 1).
        // = 1 1 1 10 00 = 0b1111_0000 = 0xF0.
        let payload = [0b1111_0000u8];
        let (ti, bits) = parse_tile_info(&payload, 48, 16, false).expect("id == 2 < 3 parses");
        assert_eq!(ti.tile_cols, 3);
        assert_eq!(ti.tile_rows, 1);
        assert_eq!(ti.tile_cols_log2, 2);
        assert_eq!(ti.tile_rows_log2, 0);
        assert_eq!(ti.context_update_tile_id, 2);
        assert_eq!(ti.tile_size_bytes, 1);
        assert_eq!(bits, 7);
    }

    /// r431 — [`TileInfo::uniform_layout`] must agree with the parser
    /// on every legal `(cols_log2, rows_log2)` pair of a 256×128 frame
    /// (`MiCols = 64`, `MiRows = 32`, 64-pel superblocks ⇒ `sbCols =
    /// 4`, `sbRows = 2`): the builder's realized layout equals what
    /// `parse_tile_info` derives from the matching increment bits.
    #[test]
    fn uniform_layout_matches_parser_on_256x128() {
        // sbCols = 4 ⇒ maxLog2TileCols = 2; sbRows = 2 ⇒ maxLog2TileRows = 1.
        // minLog2TileCols = tile_log2(64, 4) = 0; minLog2Tiles = 0.
        for cols_log2 in 0..=2u32 {
            for rows_log2 in 0..=1u32 {
                let ti = TileInfo::uniform_layout(64, 32, false, cols_log2, rows_log2)
                    .expect("legal pair");
                assert!(ti.uniform_tile_spacing_flag);
                assert_eq!(ti.tile_cols_log2, cols_log2);
                assert_eq!(ti.tile_rows_log2, rows_log2);
                assert_eq!(ti.tile_cols, 1 << cols_log2.min(2));
                assert_eq!(ti.tile_rows, 1 << rows_log2.min(1));
                // Sentinels close the start lists.
                assert_eq!(*ti.mi_col_starts.last().unwrap(), 64);
                assert_eq!(*ti.mi_row_starts.last().unwrap(), 32);
                // Tile geometries tile the mi grid exactly.
                let mut covered = vec![false; 64 * 32];
                for t in 0..ti.tile_cols * ti.tile_rows {
                    let g = ti.tile_geometry(t).expect("in range");
                    for r in g.mi_row_start..g.mi_row_end {
                        for c in g.mi_col_start..g.mi_col_end {
                            let cell = &mut covered[(r * 64 + c) as usize];
                            assert!(!*cell, "tile {t} overlaps at ({r},{c})");
                            *cell = true;
                        }
                    }
                }
                assert!(covered.iter().all(|&b| b), "tiles must cover the frame");
            }
        }
        // Out-of-window pairs are rejected.
        assert!(TileInfo::uniform_layout(64, 32, false, 3, 0).is_none());
        assert!(TileInfo::uniform_layout(64, 32, false, 0, 2).is_none());
    }

    /// r431 — builder × parser lockstep: encode the builder's layout
    /// through the §5.9.15 writer and re-parse it; every field the
    /// parser derives must equal the builder's (the `tile_size_bytes`
    /// seed is normalised to the coded value first).
    #[test]
    fn uniform_layout_round_trips_through_the_writer() {
        use crate::encoder::bitwriter::BitWriter;
        for (mi_cols, mi_rows, cl2, rl2) in
            [(64u32, 32u32, 1u32, 1u32), (64, 32, 2, 0), (32, 32, 1, 1)]
        {
            let ti = TileInfo::uniform_layout(mi_cols, mi_rows, false, cl2, rl2).expect("legal");
            let mut bw = BitWriter::new();
            crate::encoder::frame_obu::encode_tile_info(&mut bw, &ti);
            bw.byte_align();
            let bytes = bw.finish();
            let (parsed, _) = parse_tile_info(&bytes, mi_cols, mi_rows, false).expect("parses");
            assert_eq!(parsed, ti, "layout ({mi_cols}x{mi_rows}, {cl2},{rl2})");
        }
    }

    #[test]
    fn zero_frame_dimensions_rejected_not_divide_by_zero() {
        // §5.9.15 presupposes a conformant frame size (MiCols/MiRows >=
        // 1). A malformed header carrying a zero dimension yields a zero
        // superblock count, which previously divided by zero at
        // `maxTileAreaSb / widestTileSb` (spec line 3262) in the
        // non-uniform branch. It must now surface a typed error. The
        // single `0` byte selects `uniform_tile_spacing_flag = 0` so the
        // non-uniform branch is the one under test; the guard fires
        // before any branch, so the dimension check is what's exercised.
        for (mi_cols, mi_rows) in [(0u32, 4u32), (4, 0), (0, 0)] {
            for sb128 in [false, true] {
                let err = parse_tile_info(&[0x00], mi_cols, mi_rows, sb128)
                    .expect_err("zero-dimension frame must be rejected");
                assert_eq!(err, Error::PartitionWalkOutOfRange);
            }
        }
    }
}