oxideav-vp8 0.2.2

Pure-Rust VP8 video 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
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
//! VP8 intra-prediction pixel kernels (RFC 6386 §12).
//!
//! This module implements the **pure pixel-shape** prediction kernels
//! from §12 of the spec:
//!
//! * The four 16×16 luma modes (`DC_PRED`, `V_PRED`, `H_PRED`,
//!   `TM_PRED`) of §12.3 — see [`predict_y16x16`].
//! * The four 8×8 chroma modes (the same four modes applied at 8×8) of
//!   §12.2 — see [`predict_uv8x8`].
//! * The ten 4×4 sub-block modes (`B_DC_PRED` … `B_HU_PRED`) of §12.3 —
//!   see [`predict_b4x4`].
//!
//! Each kernel takes its already-reconstructed neighbour pixels as
//! plain `&[u8]` inputs and writes the predicted block into a
//! caller-supplied flat output buffer. The kernels do **not** decode
//! the mode (that's [`crate::macroblock`]) and they do **not** consume
//! the DCT residue — adding residue is the IDCT stage, which is not yet
//! implemented.
//!
//! # Out-of-bounds neighbours
//!
//! Per §12 (page 50), when a macroblock sits on the top row or left
//! column of the frame, some of its neighbour pixels lie outside the
//! reconstructed image. The constants used in that case are:
//!
//! * 127 for pixels above the top row (including the corner pixel
//!   above-and-left of the top-left frame pixel);
//! * 129 for pixels to the left of the leftmost column.
//!
//! The DC mode of §12.2 has an exception: instead of averaging the
//! out-of-bounds defaults it falls back to averaging the genuinely
//! visible side, or — for the top-left macroblock — fills the block
//! with the constant 128 directly. [`predict_uv8x8_dc`] and
//! [`predict_y16x16_dc`] take explicit `above`/`left` `Option`s to
//! drive this branching: `None` means "this edge is off-frame", `Some`
//! means "use these pixels".
//!
//! # Sub-block "extra" pixels
//!
//! Per §12.3, sub-blocks 3, 7, 11, 15 along the right edge of the
//! macroblock would naturally reference pixels above-and-to-the-right
//! of themselves — but, because macroblocks are reconstructed in
//! raster order, those pixels haven't been built yet for sub-blocks 7,
//! 11, 15. The spec defines a fixup: all four right-edge sub-blocks
//! share the same `(-1, 16) .. (-1, 19)` pixels (i.e. the four pixels
//! immediately above and to the right of sub-block 3), and for the
//! rightmost macroblock in each row those four pixels are clamped to
//! the value at `(-1, 15)`. Computing that fixup is the caller's job;
//! the kernel takes an 8-pixel `above` row covering positions
//! `(-1, 0) .. (-1, 7)` of the sub-block frame of reference.
//!
//! # Reference
//!
//! RFC 6386 §12 (pages 50–59). The 16×16 and 8×8 modes are described
//! in §12.2 (for chroma) and at the top of §12.3 (which forwards luma
//! to the chroma description with `shf` bumped from 3/4 to 4/5). The
//! ten 4×4 modes are described in §12.3, listed as the body of
//! `subblock_intra_predict()`.
//!
//! ## Spec gap
//!
//! RFC 6386 page 58 (line in raw text containing the `B_HD_PRED` body)
//! has a typo: `svg2p(E + 1)` should read `avg2p(E + 1)`. There is no
//! `svg2p` function defined anywhere in the spec; `avg2p` is the
//! `(p[0] + p[1] + 1) >> 1` helper used throughout the surrounding
//! diagonal modes (B_HD_PRED's three siblings — B_VR_PRED, B_VL_PRED,
//! B_HU_PRED — all use `avg2p` at the analogous position with no
//! typo). We treat the `svg2p` token as `avg2p` here.

use crate::macroblock::{IntraBmode, IntraUvMode, IntraYMode};

/// Default pixel value used for above-row neighbour pixels that lie
/// outside the visible frame (RFC 6386 §12, page 50).
pub const DEFAULT_ABOVE_PIXEL: u8 = 127;

/// Default pixel value used for left-column neighbour pixels that lie
/// outside the visible frame (RFC 6386 §12, page 50).
pub const DEFAULT_LEFT_PIXEL: u8 = 129;

/// Default pixel value the DC chroma mode (§12.2) falls back to when
/// *both* neighbour edges are off-frame. (Note: this is **not** the
/// average of `DEFAULT_ABOVE_PIXEL` and `DEFAULT_LEFT_PIXEL` — the
/// spec explicitly fills the block with 128 in that case.)
pub const DEFAULT_TOPLEFT_DC: u8 = 128;

#[inline]
fn clamp255(v: i32) -> u8 {
    v.clamp(0, 255) as u8
}

#[inline]
fn avg3(x: u8, y: u8, z: u8) -> u8 {
    // RFC 6386 §12.3 page 55: avg3(x, y, z) = (x + y + y + z + 2) >> 2.
    let s = x as u32 + (y as u32) + (y as u32) + z as u32 + 2;
    (s >> 2) as u8
}

#[inline]
fn avg3p(p: &[u8], i: usize) -> u8 {
    // RFC 6386 §12.3: avg3p(p) = avg3(p[-1], p[0], p[1]). The caller
    // gives us a slice and a cursor `i` so that `i-1`, `i`, `i+1` are
    // all in bounds.
    avg3(p[i - 1], p[i], p[i + 1])
}

#[inline]
fn avg2(x: u8, y: u8) -> u8 {
    // RFC 6386 §12.3 page 55: avg2(x, y) = (x + y + 1) >> 1.
    ((x as u16 + y as u16 + 1) >> 1) as u8
}

#[inline]
fn avg2p(p: &[u8], i: usize) -> u8 {
    // RFC 6386 §12.3: avg2p(p) = avg2(p[0], p[1]).
    avg2(p[i], p[i + 1])
}

// ===========================================================================
// 16×16 luma modes (RFC 6386 §12.3) and 8×8 chroma modes (RFC 6386 §12.2)
// ===========================================================================

/// Generic "fill an N×N block with a single value" helper used by the
/// DC modes. `out` is a flat row-major buffer of `n * n` pixels.
fn fill(out: &mut [u8], n: usize, value: u8) {
    debug_assert_eq!(out.len(), n * n);
    for slot in out.iter_mut() {
        *slot = value;
    }
}

/// Generic vertical-prediction helper. `out` is `n * n` row-major;
/// `above` is `n` pixels.
fn predict_v(out: &mut [u8], n: usize, above: &[u8]) {
    debug_assert_eq!(out.len(), n * n);
    debug_assert_eq!(above.len(), n);
    for row in 0..n {
        let dst = &mut out[row * n..(row + 1) * n];
        dst.copy_from_slice(above);
    }
}

/// Generic horizontal-prediction helper. `left` is `n` pixels.
fn predict_h(out: &mut [u8], n: usize, left: &[u8]) {
    debug_assert_eq!(out.len(), n * n);
    debug_assert_eq!(left.len(), n);
    for row in 0..n {
        let dst = &mut out[row * n..(row + 1) * n];
        for slot in dst.iter_mut() {
            *slot = left[row];
        }
    }
}

/// Generic TM_PRED helper. `above[c] = A_c`, `left[r] = L_r`, `p` is
/// the single pixel above-and-left of the block (`P` in §12.2).
fn predict_tm(out: &mut [u8], n: usize, above: &[u8], left: &[u8], p: u8) {
    debug_assert_eq!(out.len(), n * n);
    debug_assert_eq!(above.len(), n);
    debug_assert_eq!(left.len(), n);
    let p = p as i32;
    for r in 0..n {
        for c in 0..n {
            // RFC 6386 §12.2: X_{ij} = clamp255(L_i + A_j - P).
            out[r * n + c] = clamp255(left[r] as i32 + above[c] as i32 - p);
        }
    }
}

/// Generic DC-prediction helper for the §12.2 / §12.3 rules.
///
/// * If both `above` and `left` are present, the DC value is the
///   rounded average of all `2n` pixels.
/// * If only one is present, it's the rounded average of those `n`
///   pixels.
/// * If neither is present, the block is filled with [`DEFAULT_TOPLEFT_DC`].
///
/// Rounding is per the spec's `(sum + (1 << (shf - 1))) >> shf`.
fn predict_dc_with_optional_edges(
    out: &mut [u8],
    n: usize,
    above: Option<&[u8]>,
    left: Option<&[u8]>,
) {
    debug_assert_eq!(out.len(), n * n);
    if let Some(a) = above {
        debug_assert_eq!(a.len(), n);
    }
    if let Some(l) = left {
        debug_assert_eq!(l.len(), n);
    }
    let dc = match (above, left) {
        (Some(a), Some(l)) => {
            // 2n summands, shf = log2(2n).
            let mut sum: u32 = 0;
            for &v in a {
                sum += v as u32;
            }
            for &v in l {
                sum += v as u32;
            }
            let shf = (2 * n).trailing_zeros();
            ((sum + (1 << (shf - 1))) >> shf) as u8
        }
        (Some(a), None) => {
            let mut sum: u32 = 0;
            for &v in a {
                sum += v as u32;
            }
            let shf = n.trailing_zeros();
            ((sum + (1 << (shf - 1))) >> shf) as u8
        }
        (None, Some(l)) => {
            let mut sum: u32 = 0;
            for &v in l {
                sum += v as u32;
            }
            let shf = n.trailing_zeros();
            ((sum + (1 << (shf - 1))) >> shf) as u8
        }
        (None, None) => DEFAULT_TOPLEFT_DC,
    };
    fill(out, n, dc);
}

/// 16×16 luma DC prediction (RFC 6386 §12.3 forwarding §12.2). `out`
/// is 256 pixels row-major.
pub fn predict_y16x16_dc(out: &mut [u8; 256], above: Option<&[u8; 16]>, left: Option<&[u8; 16]>) {
    predict_dc_with_optional_edges(
        out.as_mut_slice(),
        16,
        above.map(|a| a.as_slice()),
        left.map(|l| l.as_slice()),
    );
}

/// 16×16 luma vertical prediction (RFC 6386 §12.3 forwarding §12.2).
/// `above` must be supplied: if the macroblock is on the top row of
/// the frame the caller fills it with [`DEFAULT_ABOVE_PIXEL`].
pub fn predict_y16x16_v(out: &mut [u8; 256], above: &[u8; 16]) {
    predict_v(out.as_mut_slice(), 16, above);
}

/// 16×16 luma horizontal prediction (RFC 6386 §12.3 forwarding §12.2).
/// `left` must be supplied: if the macroblock is on the left column
/// the caller fills it with [`DEFAULT_LEFT_PIXEL`].
pub fn predict_y16x16_h(out: &mut [u8; 256], left: &[u8; 16]) {
    predict_h(out.as_mut_slice(), 16, left);
}

/// 16×16 luma TM_PRED (RFC 6386 §12.3 forwarding §12.2). Caller
/// supplies the standard out-of-bounds defaults when the macroblock
/// is on the top row or left column (this mode does use them per
/// §12.2 page 53).
pub fn predict_y16x16_tm(out: &mut [u8; 256], above: &[u8; 16], left: &[u8; 16], p: u8) {
    predict_tm(out.as_mut_slice(), 16, above, left, p);
}

/// Dispatch the 16×16 luma mode to the appropriate kernel. Each
/// kernel takes the inputs it actually uses; this dispatcher ignores
/// inputs that the selected mode doesn't read (e.g. `left` for
/// `V_PRED`).
///
/// Returns `None` if `mode == IntraYMode::B`, since `B_PRED`
/// macroblocks are predicted sub-block by sub-block via
/// [`predict_b4x4`] and this dispatcher has no opinion on that.
pub fn predict_y16x16(
    out: &mut [u8; 256],
    mode: IntraYMode,
    above: Option<&[u8; 16]>,
    left: Option<&[u8; 16]>,
    p: u8,
) -> Option<()> {
    match mode {
        IntraYMode::Dc => {
            predict_y16x16_dc(out, above, left);
            Some(())
        }
        IntraYMode::V => {
            // V_PRED uses out-of-bounds default 127 when `above` is
            // None.
            let buf = above.copied().unwrap_or([DEFAULT_ABOVE_PIXEL; 16]);
            predict_y16x16_v(out, &buf);
            Some(())
        }
        IntraYMode::H => {
            let buf = left.copied().unwrap_or([DEFAULT_LEFT_PIXEL; 16]);
            predict_y16x16_h(out, &buf);
            Some(())
        }
        IntraYMode::Tm => {
            let a = above.copied().unwrap_or([DEFAULT_ABOVE_PIXEL; 16]);
            let l = left.copied().unwrap_or([DEFAULT_LEFT_PIXEL; 16]);
            predict_y16x16_tm(out, &a, &l, p);
            Some(())
        }
        IntraYMode::B => None,
    }
}

/// 8×8 chroma DC prediction (RFC 6386 §12.2). `out` is 64 pixels
/// row-major.
pub fn predict_uv8x8_dc(out: &mut [u8; 64], above: Option<&[u8; 8]>, left: Option<&[u8; 8]>) {
    predict_dc_with_optional_edges(
        out.as_mut_slice(),
        8,
        above.map(|a| a.as_slice()),
        left.map(|l| l.as_slice()),
    );
}

/// 8×8 chroma vertical prediction (RFC 6386 §12.2).
pub fn predict_uv8x8_v(out: &mut [u8; 64], above: &[u8; 8]) {
    predict_v(out.as_mut_slice(), 8, above);
}

/// 8×8 chroma horizontal prediction (RFC 6386 §12.2).
pub fn predict_uv8x8_h(out: &mut [u8; 64], left: &[u8; 8]) {
    predict_h(out.as_mut_slice(), 8, left);
}

/// 8×8 chroma TM_PRED (RFC 6386 §12.2).
pub fn predict_uv8x8_tm(out: &mut [u8; 64], above: &[u8; 8], left: &[u8; 8], p: u8) {
    predict_tm(out.as_mut_slice(), 8, above, left, p);
}

/// Dispatch the 8×8 chroma mode to the appropriate kernel. Per §12.2,
/// `V_PRED` / `H_PRED` / `TM_PRED` use the [`DEFAULT_ABOVE_PIXEL`] /
/// [`DEFAULT_LEFT_PIXEL`] defaults when the corresponding edge is
/// off-frame; `DC_PRED` follows the §12.2 averaging rules with
/// `predict_dc_with_optional_edges`.
pub fn predict_uv8x8(
    out: &mut [u8; 64],
    mode: IntraUvMode,
    above: Option<&[u8; 8]>,
    left: Option<&[u8; 8]>,
    p: u8,
) {
    match mode {
        IntraUvMode::Dc => predict_uv8x8_dc(out, above, left),
        IntraUvMode::V => {
            let buf = above.copied().unwrap_or([DEFAULT_ABOVE_PIXEL; 8]);
            predict_uv8x8_v(out, &buf);
        }
        IntraUvMode::H => {
            let buf = left.copied().unwrap_or([DEFAULT_LEFT_PIXEL; 8]);
            predict_uv8x8_h(out, &buf);
        }
        IntraUvMode::Tm => {
            let a = above.copied().unwrap_or([DEFAULT_ABOVE_PIXEL; 8]);
            let l = left.copied().unwrap_or([DEFAULT_LEFT_PIXEL; 8]);
            predict_uv8x8_tm(out, &a, &l, p);
        }
    }
}

// ===========================================================================
// 4×4 sub-block modes (RFC 6386 §12.3 `subblock_intra_predict`)
// ===========================================================================

/// Predict a single 4×4 luma sub-block (RFC 6386 §12.3).
///
/// * `out` — destination block, row-major (16 pixels).
/// * `above` — eight pixels at `(-1, 0)..=(-1, 7)` of the sub-block's
///   own coordinate frame. The lower 4 pixels (`above[0..4]`) are
///   directly above the sub-block; the upper 4 (`above[4..8]`) are the
///   "extra" pixels that some diagonal modes reference, per the §12.3
///   right-edge-sub-block rules.
/// * `left` — four pixels at `(0, -1)..=(3, -1)` of the sub-block's
///   own coordinate frame.
/// * `p` — the single pixel at `(-1, -1)`, sitting just above-and-left
///   of the sub-block. Per §12.3 this is the value of `A[-1]` /
///   `L[-1]` in the spec's helper function.
pub fn predict_b4x4(out: &mut [u8; 16], mode: IntraBmode, above: &[u8; 8], left: &[u8; 4], p: u8) {
    // Build the `E[0..=8]` array described in §12.3:
    //   E[0] = L[3], E[1] = L[2], E[2] = L[1], E[3] = L[0],
    //   E[4] = P (== A[-1] == L[-1]),
    //   E[5] = A[0], E[6] = A[1], E[7] = A[2], E[8] = A[3].
    let e: [u8; 9] = [
        left[3], left[2], left[1], left[0], p, above[0], above[1], above[2], above[3],
    ];

    // Convenience accessor that matches the spec's array indexing.
    let b = |r: usize, c: usize| r * 4 + c;
    // Buffer to fill, then memcpy at the end. We use a local fixed
    // array so all writes are bounds-checked at compile time.
    let mut buf = [0u8; 16];

    match mode {
        IntraBmode::Dc => {
            // §12.3 B_DC_PRED: v = (sum(A[0..4]) + sum(L[0..4]) + 4) >> 3.
            // 8 summands, rounding by 4 = 1 << (3 - 1).
            let mut v: u32 = 4;
            for i in 0..4 {
                v += above[i] as u32 + left[i] as u32;
            }
            v >>= 3;
            for slot in buf.iter_mut() {
                *slot = v as u8;
            }
        }
        IntraBmode::Tm => {
            // §12.3 B_TM_PRED: same shape as the 16×16 TM at 4×4.
            for r in 0..4 {
                for c in 0..4 {
                    buf[b(r, c)] = clamp255(left[r] as i32 + above[c] as i32 - p as i32);
                }
            }
        }
        IntraBmode::Ve => {
            // §12.3 B_VE_PRED: each column c gets avg3p(A + c) i.e.
            // avg3(A[c-1], A[c], A[c+1]) for c = 0..3. A[-1] is P (== E[4]),
            // A[4] is above[4] (the right-extension).
            let extended: [u8; 6] = [p, above[0], above[1], above[2], above[3], above[4]];
            for c in 0..4 {
                let v = avg3(extended[c], extended[c + 1], extended[c + 2]);
                for r in 0..4 {
                    buf[b(r, c)] = v;
                }
            }
        }
        IntraBmode::He => {
            // §12.3 B_HE_PRED: each row r gets a smoothed value from
            // L. r=3 is special (uses avg3(L[2], L[3], L[3]));
            // r=0..=2 use avg3p(L + r) i.e. avg3(L[r-1], L[r], L[r+1]).
            // L[-1] is P (== E[4]).
            let extended: [u8; 5] = [p, left[0], left[1], left[2], left[3]];
            // r = 3: avg3(L[2], L[3], L[3]).
            let v3 = avg3(left[2], left[3], left[3]);
            for c in 0..4 {
                buf[b(3, c)] = v3;
            }
            for r in 0..3 {
                let v = avg3(extended[r], extended[r + 1], extended[r + 2]);
                for c in 0..4 {
                    buf[b(r, c)] = v;
                }
            }
        }
        IntraBmode::Ld => {
            // §12.3 B_LD_PRED: lines of slope -1, smoothed from A.
            // Note: this mode only references A (not E), so positions
            // are: avg3p(A + j) for j=1..=6, with B[3][3] using the
            // synthetic avg3(A[6], A[7], A[7]) (A[8] does not exist).
            buf[b(0, 0)] = avg3p(above, 1);
            buf[b(0, 1)] = avg3p(above, 2);
            buf[b(1, 0)] = avg3p(above, 2);
            buf[b(0, 2)] = avg3p(above, 3);
            buf[b(1, 1)] = avg3p(above, 3);
            buf[b(2, 0)] = avg3p(above, 3);
            buf[b(0, 3)] = avg3p(above, 4);
            buf[b(1, 2)] = avg3p(above, 4);
            buf[b(2, 1)] = avg3p(above, 4);
            buf[b(3, 0)] = avg3p(above, 4);
            buf[b(1, 3)] = avg3p(above, 5);
            buf[b(2, 2)] = avg3p(above, 5);
            buf[b(3, 1)] = avg3p(above, 5);
            buf[b(2, 3)] = avg3p(above, 6);
            buf[b(3, 2)] = avg3p(above, 6);
            buf[b(3, 3)] = avg3(above[6], above[7], above[7]);
        }
        IntraBmode::Rd => {
            // §12.3 B_RD_PRED: lines of slope +1, smoothed from E.
            buf[b(3, 0)] = avg3p(&e, 1);
            buf[b(3, 1)] = avg3p(&e, 2);
            buf[b(2, 0)] = avg3p(&e, 2);
            buf[b(3, 2)] = avg3p(&e, 3);
            buf[b(2, 1)] = avg3p(&e, 3);
            buf[b(1, 0)] = avg3p(&e, 3);
            buf[b(3, 3)] = avg3p(&e, 4);
            buf[b(2, 2)] = avg3p(&e, 4);
            buf[b(1, 1)] = avg3p(&e, 4);
            buf[b(0, 0)] = avg3p(&e, 4);
            buf[b(2, 3)] = avg3p(&e, 5);
            buf[b(1, 2)] = avg3p(&e, 5);
            buf[b(0, 1)] = avg3p(&e, 5);
            buf[b(1, 3)] = avg3p(&e, 6);
            buf[b(0, 2)] = avg3p(&e, 6);
            buf[b(0, 3)] = avg3p(&e, 7);
        }
        IntraBmode::Vr => {
            // §12.3 B_VR_PRED: SSE diagonals (slope +2), mixing
            // avg2p / avg3p over E.
            buf[b(3, 0)] = avg3p(&e, 2);
            buf[b(2, 0)] = avg3p(&e, 3);
            buf[b(3, 1)] = avg3p(&e, 4);
            buf[b(1, 0)] = avg3p(&e, 4);
            buf[b(2, 1)] = avg2p(&e, 4);
            buf[b(0, 0)] = avg2p(&e, 4);
            buf[b(3, 2)] = avg3p(&e, 5);
            buf[b(1, 1)] = avg3p(&e, 5);
            buf[b(2, 2)] = avg2p(&e, 5);
            buf[b(0, 1)] = avg2p(&e, 5);
            buf[b(3, 3)] = avg3p(&e, 6);
            buf[b(1, 2)] = avg3p(&e, 6);
            buf[b(2, 3)] = avg2p(&e, 6);
            buf[b(0, 2)] = avg2p(&e, 6);
            buf[b(1, 3)] = avg3p(&e, 7);
            buf[b(0, 3)] = avg2p(&e, 7);
        }
        IntraBmode::Vl => {
            // §12.3 B_VL_PRED: SSW diagonals (slope -2), reading from
            // A and the right-extension `above[4..=7]`. The spec's
            // listing references A[0..=6]; we pass `above` directly.
            buf[b(0, 0)] = avg2p(above, 0);
            buf[b(1, 0)] = avg3p(above, 1);
            buf[b(2, 0)] = avg2p(above, 1);
            buf[b(0, 1)] = avg2p(above, 1);
            buf[b(1, 1)] = avg3p(above, 2);
            buf[b(3, 0)] = avg3p(above, 2);
            buf[b(2, 1)] = avg2p(above, 2);
            buf[b(0, 2)] = avg2p(above, 2);
            buf[b(3, 1)] = avg3p(above, 3);
            buf[b(1, 2)] = avg3p(above, 3);
            buf[b(2, 2)] = avg2p(above, 3);
            buf[b(0, 3)] = avg2p(above, 3);
            buf[b(3, 2)] = avg3p(above, 4);
            buf[b(1, 3)] = avg3p(above, 4);
            // The last two values explicitly do not follow the
            // pattern per §12.3 page 58.
            buf[b(2, 3)] = avg3p(above, 5);
            buf[b(3, 3)] = avg3p(above, 6);
        }
        IntraBmode::Hd => {
            // §12.3 B_HD_PRED: ESE diagonals (slope +1/2). Note: the
            // spec listing on page 58 has a typo `svg2p(E + 1)` for
            // the second row-3 pixel — we treat it as `avg2p`, the
            // function used by all three sibling diagonal modes at
            // the analogous position.
            buf[b(3, 0)] = avg2p(&e, 0);
            buf[b(3, 1)] = avg3p(&e, 1);
            buf[b(2, 0)] = avg2p(&e, 1);
            buf[b(3, 2)] = avg2p(&e, 1);
            buf[b(2, 1)] = avg3p(&e, 2);
            buf[b(3, 3)] = avg3p(&e, 2);
            buf[b(2, 2)] = avg2p(&e, 2);
            buf[b(1, 0)] = avg2p(&e, 2);
            buf[b(2, 3)] = avg3p(&e, 3);
            buf[b(1, 1)] = avg3p(&e, 3);
            buf[b(1, 2)] = avg2p(&e, 3);
            buf[b(0, 0)] = avg2p(&e, 3);
            buf[b(1, 3)] = avg3p(&e, 4);
            buf[b(0, 1)] = avg3p(&e, 4);
            buf[b(0, 2)] = avg3p(&e, 5);
            buf[b(0, 3)] = avg3p(&e, 6);
        }
        IntraBmode::Hu => {
            // §12.3 B_HU_PRED: ENE diagonals (slope -1/2), reading
            // from L only. The spec listing assigns:
            //   B[0][0] = avg2p(L);            // (1/2, -1)
            //   B[0][1] = avg3p(L + 1);        // (1,   -1)
            //   B[0][2] = B[1][0] = avg2p(L + 1);   // (3/2, -1)
            //   B[0][3] = B[1][1] = avg3p(L + 2);   // (2,   -1)
            //   B[1][2] = B[2][0] = avg2p(L + 2);   // (5/2, -1)
            //   B[1][3] = B[2][1] = avg3(L[2], L[3], L[3]); // (3, -1)
            //   B[2][2] = B[2][3] = B[3][0]..[3][3] = L[3];
            buf[b(0, 0)] = avg2p(left, 0);
            buf[b(0, 1)] = avg3p(left, 1);
            buf[b(0, 2)] = avg2p(left, 1);
            buf[b(1, 0)] = avg2p(left, 1);
            buf[b(0, 3)] = avg3p(left, 2);
            buf[b(1, 1)] = avg3p(left, 2);
            // B[1][2] = B[2][0] = avg2p(L + 2):
            let mid = avg2p(left, 2);
            buf[b(1, 2)] = mid;
            buf[b(2, 0)] = mid;
            // B[1][3] = B[2][1] = avg3(L[2], L[3], L[3]):
            let v = avg3(left[2], left[3], left[3]);
            buf[b(1, 3)] = v;
            buf[b(2, 1)] = v;
            // Bottom-right corner + a few clones — all = L[3]:
            buf[b(2, 2)] = left[3];
            buf[b(2, 3)] = left[3];
            buf[b(3, 0)] = left[3];
            buf[b(3, 1)] = left[3];
            buf[b(3, 2)] = left[3];
            buf[b(3, 3)] = left[3];
        }
    }

    out.copy_from_slice(&buf);
}

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

    // ---------------------------------------------------------------
    // 16×16 luma kernels
    // ---------------------------------------------------------------

    #[test]
    fn y16x16_dc_full_neighbours_rounds_half_up() {
        // 16 above-pixels all 100, 16 left-pixels all 200. Sum = 4800,
        // shf = 5, rounding adjust = 16 → (4800 + 16) >> 5 = 150.
        let mut out = [0u8; 256];
        let above = [100u8; 16];
        let left = [200u8; 16];
        predict_y16x16_dc(&mut out, Some(&above), Some(&left));
        assert!(out.iter().all(|&v| v == 150));
    }

    #[test]
    fn y16x16_dc_top_row_uses_left_only() {
        // Only `left` (n=16, shf=4, round=8). 16 × 50 = 800; (800 +
        // 8) >> 4 = 50.
        let mut out = [0u8; 256];
        let left = [50u8; 16];
        predict_y16x16_dc(&mut out, None, Some(&left));
        assert!(out.iter().all(|&v| v == 50));
    }

    #[test]
    fn y16x16_dc_topleft_uses_default_128() {
        let mut out = [99u8; 256];
        predict_y16x16_dc(&mut out, None, None);
        assert!(out.iter().all(|&v| v == DEFAULT_TOPLEFT_DC));
        assert_eq!(out[0], 128);
    }

    #[test]
    fn y16x16_v_copies_above_row() {
        let mut out = [0u8; 256];
        let above: [u8; 16] = core::array::from_fn(|i| (i * 7) as u8);
        predict_y16x16_v(&mut out, &above);
        for r in 0..16 {
            for c in 0..16 {
                assert_eq!(out[r * 16 + c], above[c]);
            }
        }
    }

    #[test]
    fn y16x16_h_copies_left_column() {
        let mut out = [0u8; 256];
        let left: [u8; 16] = core::array::from_fn(|i| (i * 11 + 5) as u8);
        predict_y16x16_h(&mut out, &left);
        for r in 0..16 {
            for c in 0..16 {
                assert_eq!(out[r * 16 + c], left[r]);
            }
        }
    }

    #[test]
    fn y16x16_tm_matches_spec_formula() {
        // Pick A, L, P with at least one wrap-or-clamp case.
        let above: [u8; 16] = core::array::from_fn(|i| 10 + i as u8);
        let left: [u8; 16] = core::array::from_fn(|i| 200 - i as u8);
        let p = 50u8;
        let mut out = [0u8; 256];
        predict_y16x16_tm(&mut out, &above, &left, p);
        for r in 0..16 {
            for c in 0..16 {
                let want = (left[r] as i32 + above[c] as i32 - p as i32).clamp(0, 255) as u8;
                assert_eq!(out[r * 16 + c], want, "tm mismatch at ({r}, {c})");
            }
        }
    }

    #[test]
    fn y16x16_tm_clamp_floor_and_ceiling() {
        // L = 0, A = 0, P = 250 → -250 → clamped to 0.
        let above = [0u8; 16];
        let left = [0u8; 16];
        let mut out = [42u8; 256];
        predict_y16x16_tm(&mut out, &above, &left, 250);
        assert!(out.iter().all(|&v| v == 0));

        // L = 255, A = 255, P = 0 → 510 → clamped to 255.
        let above = [255u8; 16];
        let left = [255u8; 16];
        let mut out = [42u8; 256];
        predict_y16x16_tm(&mut out, &above, &left, 0);
        assert!(out.iter().all(|&v| v == 255));
    }

    #[test]
    fn y16x16_dispatch_routes_each_mode() {
        let above = [200u8; 16];
        let left = [100u8; 16];
        let p = 150u8;

        // DC: (16*200 + 16*100 + 16) >> 5 = (4800+16)>>5 = 150.
        let mut out = [0u8; 256];
        assert!(predict_y16x16(&mut out, IntraYMode::Dc, Some(&above), Some(&left), p).is_some());
        assert!(out.iter().all(|&v| v == 150));

        // V copies above.
        let mut out = [0u8; 256];
        predict_y16x16(&mut out, IntraYMode::V, Some(&above), Some(&left), p);
        assert!(out.iter().all(|&v| v == 200));

        // H copies left.
        let mut out = [0u8; 256];
        predict_y16x16(&mut out, IntraYMode::H, Some(&above), Some(&left), p);
        assert!(out.iter().all(|&v| v == 100));

        // TM: every cell = 100 + 200 - 150 = 150.
        let mut out = [0u8; 256];
        predict_y16x16(&mut out, IntraYMode::Tm, Some(&above), Some(&left), p);
        assert!(out.iter().all(|&v| v == 150));

        // B returns None — caller handles sub-blocks.
        let mut out = [0u8; 256];
        assert!(predict_y16x16(&mut out, IntraYMode::B, Some(&above), Some(&left), p).is_none());
    }

    #[test]
    fn y16x16_dispatch_v_uses_default_when_top_row() {
        let mut out = [0u8; 256];
        predict_y16x16(&mut out, IntraYMode::V, None, None, 0);
        assert!(out.iter().all(|&v| v == DEFAULT_ABOVE_PIXEL));
    }

    #[test]
    fn y16x16_dispatch_h_uses_default_when_left_column() {
        let mut out = [0u8; 256];
        predict_y16x16(&mut out, IntraYMode::H, None, None, 0);
        assert!(out.iter().all(|&v| v == DEFAULT_LEFT_PIXEL));
    }

    // ---------------------------------------------------------------
    // 8×8 chroma kernels
    // ---------------------------------------------------------------

    #[test]
    fn uv8x8_dc_full_neighbours_rounds_half_up() {
        // 8 above-pixels = 100, 8 left-pixels = 200. Sum = 2400,
        // shf = 4, round = 8 → (2400 + 8) >> 4 = 150.
        let mut out = [0u8; 64];
        let above = [100u8; 8];
        let left = [200u8; 8];
        predict_uv8x8_dc(&mut out, Some(&above), Some(&left));
        assert!(out.iter().all(|&v| v == 150));
    }

    #[test]
    fn uv8x8_dc_left_column_uses_above_only() {
        // n=8, shf=3, round=4. 8 × 100 = 800 → (800+4)>>3 = 100.
        let mut out = [0u8; 64];
        let above = [100u8; 8];
        predict_uv8x8_dc(&mut out, Some(&above), None);
        assert!(out.iter().all(|&v| v == 100));
    }

    #[test]
    fn uv8x8_dc_topleft_uses_128() {
        let mut out = [7u8; 64];
        predict_uv8x8_dc(&mut out, None, None);
        assert!(out.iter().all(|&v| v == 128));
    }

    #[test]
    fn uv8x8_dispatch_v_h_tm() {
        let above = [10u8; 8];
        let left = [20u8; 8];
        let p = 5u8;

        let mut out = [0u8; 64];
        predict_uv8x8(&mut out, IntraUvMode::V, Some(&above), Some(&left), p);
        assert!(out.iter().all(|&v| v == 10));

        let mut out = [0u8; 64];
        predict_uv8x8(&mut out, IntraUvMode::H, Some(&above), Some(&left), p);
        assert!(out.iter().all(|&v| v == 20));

        // TM: 20 + 10 - 5 = 25 for every cell since both rows /
        // columns are flat.
        let mut out = [0u8; 64];
        predict_uv8x8(&mut out, IntraUvMode::Tm, Some(&above), Some(&left), p);
        assert!(out.iter().all(|&v| v == 25));
    }

    // ---------------------------------------------------------------
    // 4×4 sub-block kernels
    // ---------------------------------------------------------------

    #[test]
    fn b4x4_dc_averages_eight_pixels() {
        // A[0..4] = {4,4,4,4}, L[0..4] = {12,12,12,12}; sum = 64.
        // (64 + 4) >> 3 = 8.
        let above = [4, 4, 4, 4, 0, 0, 0, 0];
        let left = [12, 12, 12, 12];
        let mut out = [0u8; 16];
        predict_b4x4(&mut out, IntraBmode::Dc, &above, &left, 99);
        assert!(out.iter().all(|&v| v == 8));
    }

    #[test]
    fn b4x4_tm_matches_clamped_formula() {
        let above = [10, 20, 30, 40, 0, 0, 0, 0];
        let left = [5, 15, 25, 35];
        let p = 8u8;
        let mut out = [0u8; 16];
        predict_b4x4(&mut out, IntraBmode::Tm, &above, &left, p);
        for r in 0..4 {
            for c in 0..4 {
                let want = (left[r] as i32 + above[c] as i32 - p as i32).clamp(0, 255) as u8;
                assert_eq!(out[r * 4 + c], want);
            }
        }
    }

    #[test]
    fn b4x4_ve_smooths_above_row() {
        // A row = [10, 20, 30, 40, 50, 60, 70, 80], P = 0.
        let above = [10, 20, 30, 40, 50, 60, 70, 80];
        let left = [0; 4];
        let p = 0u8;
        let mut out = [0u8; 16];
        predict_b4x4(&mut out, IntraBmode::Ve, &above, &left, p);
        // For c=0: avg3(P, A[0], A[1]) = avg3(0, 10, 20) =
        //   (0 + 10 + 10 + 20 + 2) >> 2 = 42 >> 2 = 10.
        // For c=1: avg3(A[0], A[1], A[2]) = avg3(10, 20, 30) =
        //   (10 + 20 + 20 + 30 + 2) >> 2 = 82 >> 2 = 20.
        // For c=2: avg3(20, 30, 40) = (20 + 30 + 30 + 40 + 2) >> 2 = 30.
        // For c=3: avg3(30, 40, 50) = (30 + 40 + 40 + 50 + 2) >> 2 = 40.
        for r in 0..4 {
            assert_eq!(out[r * 4], 10);
            assert_eq!(out[r * 4 + 1], 20);
            assert_eq!(out[r * 4 + 2], 30);
            assert_eq!(out[r * 4 + 3], 40);
        }
    }

    #[test]
    fn b4x4_he_smooths_left_column_with_bottom_special_case() {
        // L = [10, 20, 30, 40], P = 0.
        let above = [0; 8];
        let left = [10, 20, 30, 40];
        let p = 0u8;
        let mut out = [0u8; 16];
        predict_b4x4(&mut out, IntraBmode::He, &above, &left, p);
        // r=0: avg3(P, L[0], L[1]) = avg3(0, 10, 20) = 10.
        // r=1: avg3(10, 20, 30) = 20.
        // r=2: avg3(20, 30, 40) = 30.
        // r=3: avg3(L[2], L[3], L[3]) = avg3(30, 40, 40) =
        //   (30 + 40 + 40 + 40 + 2) >> 2 = 152 >> 2 = 38.
        for c in 0..4 {
            assert_eq!(out[c], 10);
            assert_eq!(out[4 + c], 20);
            assert_eq!(out[8 + c], 30);
            assert_eq!(out[12 + c], 38);
        }
    }

    #[test]
    fn b4x4_ld_top_left_uses_a1_and_bottom_right_uses_a7_clone() {
        // A = [0, 100, 100, 100, 100, 100, 100, 100], all-100 from
        // index 1 onwards, so avg3p anywhere from i=2 onwards is 100.
        let above = [0, 100, 100, 100, 100, 100, 100, 100];
        let left = [0; 4];
        let mut out = [0u8; 16];
        predict_b4x4(&mut out, IntraBmode::Ld, &above, &left, 0);
        // B[0][0] = avg3p(A + 1) = avg3(A[0], A[1], A[2]) =
        //   (0 + 100 + 100 + 100 + 2) >> 2 = 75.
        assert_eq!(out[0], 75);
        // B[3][3] = avg3(A[6], A[7], A[7]) = avg3(100, 100, 100) = 100.
        assert_eq!(out[15], 100);
    }

    #[test]
    fn b4x4_rd_anti_diagonal_propagates() {
        // Build E with a single non-zero element so we can trace.
        // E = [L[3], L[2], L[1], L[0], P, A[0], A[1], A[2], A[3]].
        // Set everything to 100 except E[4] = P = 4. Then:
        //   avg3p(E + 4) = avg3(E[3], E[4], E[5]) =
        //     avg3(100, 4, 100) = (100 + 4 + 4 + 100 + 2) >> 2 = 52.
        let above = [100, 100, 100, 100, 0, 0, 0, 0];
        let left = [100, 100, 100, 100];
        let p = 4u8;
        let mut out = [0u8; 16];
        predict_b4x4(&mut out, IntraBmode::Rd, &above, &left, p);
        // The main diagonal (B[0][0], B[1][1], B[2][2], B[3][3]) all
        // sample avg3p(E + 4).
        assert_eq!(out[0], 52);
        assert_eq!(out[5], 52);
        assert_eq!(out[10], 52);
        assert_eq!(out[15], 52);
    }

    #[test]
    fn b4x4_vr_mixes_avg2_and_avg3() {
        // Use a sparse E to verify the formula. Set everything to
        // 100 except E[5] = 4 (A[0] = 4).
        let above = [4, 100, 100, 100, 100, 100, 100, 100];
        let left = [100, 100, 100, 100];
        let p = 100u8;
        let mut out = [0u8; 16];
        predict_b4x4(&mut out, IntraBmode::Vr, &above, &left, p);
        // B[3][2] = B[1][1] = avg3p(E + 5) = avg3(E[4], E[5], E[6]) =
        //   avg3(100, 4, 100) = 52.
        assert_eq!(out[3 * 4 + 2], 52);
        assert_eq!(out[4 + 1], 52);
        // B[2][2] = B[0][1] = avg2p(E + 5) = avg2(E[5], E[6]) =
        //   avg2(4, 100) = (4 + 100 + 1) >> 1 = 52.
        assert_eq!(out[2 * 4 + 2], 52);
        assert_eq!(out[1], 52);
    }

    #[test]
    fn b4x4_vl_handles_right_extension() {
        // Reads above[0..=6]. Use a ramp.
        let above = [10, 20, 30, 40, 50, 60, 70, 80];
        let left = [0; 4];
        let mut out = [0u8; 16];
        predict_b4x4(&mut out, IntraBmode::Vl, &above, &left, 99);
        // B[0][0] = avg2p(A) = avg2(A[0], A[1]) = avg2(10, 20) = 15.
        assert_eq!(out[0], 15);
        // B[3][3] = avg3p(A + 6) = avg3(A[5], A[6], A[7]) =
        //   avg3(60, 70, 80) = (60 + 70 + 70 + 80 + 2) >> 2 = 70.
        assert_eq!(out[15], 70);
        // B[2][3] = avg3p(A + 5) = avg3(A[4], A[5], A[6]) =
        //   avg3(50, 60, 70) = 60.
        assert_eq!(out[2 * 4 + 3], 60);
    }

    #[test]
    fn b4x4_hd_treats_svg2p_typo_as_avg2p() {
        // E = [L[3], L[2], L[1], L[0], P, A[0], A[1], A[2], A[3]].
        // We want to exercise the position the spec wrote `svg2p`:
        //   B[2][0] = B[3][2] = svg2p(E + 1) → avg2p(E + 1).
        // Set everything to 100 except E[1] = L[2] = 4. Then
        //   avg2p(E + 1) = avg2(E[1], E[2]) = avg2(4, 100) = 52.
        let above = [100, 100, 100, 100, 100, 100, 100, 100];
        let left = [100, 4, 100, 100];
        let p = 100u8;
        let mut out = [0u8; 16];
        predict_b4x4(&mut out, IntraBmode::Hd, &above, &left, p);
        // Both positions should be 52, confirming we used avg2p
        // (avg3p(E + 1) = avg3(E[0], E[1], E[2]) = avg3(100, 4, 100)
        // = (100 + 4 + 4 + 100 + 2) >> 2 = 52 *also*, so we add a
        // disambiguating test below.)
        assert_eq!(out[2 * 4], 52);
        assert_eq!(out[3 * 4 + 2], 52);
    }

    #[test]
    fn b4x4_hd_avg2p_vs_avg3p_disambiguator() {
        // To prove we're using avg2p (not avg3p), make a case where
        // they differ. E[1] = 4, E[2] = 100, E[0] = 200 →
        //   avg2p(E + 1) = avg2(4, 100) = 52.
        //   avg3p(E + 1) = avg3(200, 4, 100) = (200 + 4 + 4 + 100 + 2) >> 2 = 77.
        // E = [L[3], L[2], L[1], L[0], P, ...]. So E[0] = L[3] = 200,
        // E[1] = L[2] = 4, E[2] = L[1] = 100.
        let above = [200, 200, 200, 200, 200, 200, 200, 200];
        let left = [200, 100, 4, 200];
        let p = 200u8;
        let mut out = [0u8; 16];
        predict_b4x4(&mut out, IntraBmode::Hd, &above, &left, p);
        // svg2p / avg2p of (E[1], E[2]) = avg2(4, 100) = 52.
        // If we accidentally compiled it as avg3p we'd see 77.
        assert_eq!(out[2 * 4], 52, "B[2][0] should be avg2p(E+1) = 52");
        assert_eq!(out[3 * 4 + 2], 52, "B[3][2] should be avg2p(E+1) = 52");
    }

    #[test]
    fn b4x4_hu_bottom_rows_collapse_to_left_3() {
        // L[3] = 200, rest of L = 0.
        let above = [0; 8];
        let left = [0, 0, 0, 200];
        let p = 0u8;
        let mut out = [0u8; 16];
        predict_b4x4(&mut out, IntraBmode::Hu, &above, &left, p);
        // Bottom row is L[3] = 200 everywhere.
        for c in 0..4 {
            assert_eq!(out[3 * 4 + c], 200);
        }
        // B[2][2] = B[2][3] = L[3] = 200.
        assert_eq!(out[2 * 4 + 2], 200);
        assert_eq!(out[2 * 4 + 3], 200);
    }

    #[test]
    fn b4x4_hu_top_row_uses_left() {
        // L = [10, 20, 30, 40].
        let above = [0; 8];
        let left = [10, 20, 30, 40];
        let p = 0u8;
        let mut out = [0u8; 16];
        predict_b4x4(&mut out, IntraBmode::Hu, &above, &left, p);
        // B[0][0] = avg2p(L) = avg2(L[0], L[1]) = avg2(10, 20) = 15.
        assert_eq!(out[0], 15);
        // B[0][1] = avg3p(L + 1) = avg3(L[0], L[1], L[2]) =
        //   avg3(10, 20, 30) = (10 + 20 + 20 + 30 + 2) >> 2 = 20.
        assert_eq!(out[1], 20);
        // B[0][2] = B[1][0] = avg2p(L + 1) = avg2(L[1], L[2]) =
        //   avg2(20, 30) = (20 + 30 + 1) >> 1 = 25.
        assert_eq!(out[2], 25);
        assert_eq!(out[4], 25);
    }

    // ---------------------------------------------------------------
    // Cross-cutting sanity checks
    // ---------------------------------------------------------------

    #[test]
    fn flat_above_left_yields_flat_dc_for_all_modes() {
        // If above == left == P == 100 then every kernel produces
        // a flat block of 100. (TM: 100 + 100 - 100 = 100. DC: 100.
        // V/H: 100. Smoothing diagonals: 100 everywhere because every
        // input pixel is 100 and both avg2/avg3 are weighted averages
        // with integer-rounding behaviour that is identity on a
        // constant input.)
        let above = [100u8; 8];
        let left = [100u8; 4];
        let p = 100u8;
        for mode in [
            IntraBmode::Dc,
            IntraBmode::Tm,
            IntraBmode::Ve,
            IntraBmode::He,
            IntraBmode::Ld,
            IntraBmode::Rd,
            IntraBmode::Vr,
            IntraBmode::Vl,
            IntraBmode::Hd,
            IntraBmode::Hu,
        ] {
            let mut out = [0u8; 16];
            predict_b4x4(&mut out, mode, &above, &left, p);
            for (i, &v) in out.iter().enumerate() {
                assert_eq!(v, 100, "mode {mode:?} pixel {i} != 100");
            }
        }
    }
}