still265 0.6.1

Pure-Rust HEVC/H.265 still-image encoder with BPG and HEIC support
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
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
//! Intra prediction for HEVC
//!
//! Implements the 35 intra prediction modes:
//! - Mode 0: Planar (smooth bilinear interpolation)
//! - Mode 1: DC (average of reference samples)
//! - Modes 2-34: Angular (directional prediction)

use super::picture::{DecodedFrame, UNINIT_SAMPLE};
use super::slice::IntraPredMode;

/// Maximum block size for intra prediction (HEVC max intra TU = 32)
pub const MAX_INTRA_PRED_BLOCK_SIZE: usize = 32;

/// Length of the reference-border arrays used by the intra predictor, and the
/// index of the top-left corner sample within them.
pub const INTRA_BORDER_LEN: usize = 4 * MAX_INTRA_PRED_BLOCK_SIZE + 1;
pub const INTRA_BORDER_CENTER: usize = 2 * MAX_INTRA_PRED_BLOCK_SIZE;

/// HEVC Table 8-3: chroma intra prediction mode mapping for `ChromaArrayType == 2`
/// (4:2:2). The chroma plane is horizontally subsampled but not vertically, so
/// angular modes are remapped to compensate for the 2:1 sample aspect. Indexed
/// by the derived `IntraPredModeC` (0..=34); Planar(0)/DC(1) are unchanged.
pub static CHROMA_MODE_MAP_422: [u8; 35] = [
    0, 1, 2, 2, 2, 2, 3, 5, 7, 8, 10, 12, 13, 15, 17, 18, 19, 20, 21, 22, 23, 23, 24, 24, 25, 25,
    26, 27, 27, 28, 28, 29, 29, 30, 31,
];

/// Apply the 4:2:2 chroma intra mode remap (Table 8-3) to a mode value.
pub fn map_chroma_mode_422(mode: u8) -> u8 {
    CHROMA_MODE_MAP_422
        .get(mode as usize)
        .copied()
        .unwrap_or(mode)
}

/// Intra prediction angle table (H.265 Table 8-4)
/// Index 0-1 are placeholders, modes 2-34 have actual angles
pub static INTRA_PRED_ANGLE: [i16; 35] = [
    0, 0, // modes 0, 1 (planar, DC)
    32, 26, 21, 17, 13, 9, 5, 2, // modes 2-9
    0, // mode 10 (horizontal)
    -2, -5, -9, -13, -17, -21, -26, // modes 11-17
    -32, // mode 18 (diagonal down-left)
    -26, -21, -17, -13, -9, -5, -2, // modes 19-25
    0,  // mode 26 (vertical)
    2, 5, 9, 13, 17, 21, 26, // modes 27-33
    32, // mode 34 (diagonal down-right)
];

/// Inverse angle table for negative angles (modes 11-17 and 19-25)
/// Used to extend reference samples for negative angle prediction
pub static INV_ANGLE: [i32; 15] = [
    -4096, -1638, -910, -630, -482, -390, -315, // modes 11-17
    -256, // mode 18
    -315, -390, -482, -630, -910, -1638, -4096, // modes 19-25
];

/// Get inverse angle for a mode (for negative angle modes only)
fn get_inv_angle(mode: u8) -> i32 {
    if (11..=25).contains(&mode) {
        INV_ANGLE[(mode - 11) as usize]
    } else {
        0
    }
}

/// Perform intra prediction for a block, writing the result into `frame`.
pub fn predict_intra(
    frame: &mut DecodedFrame,
    x: u32,
    y: u32,
    log2_size: u8,
    mode: IntraPredMode,
    c_idx: u8, // 0=Y, 1=Cb, 2=Cr
    strong_intra_smoothing_enabled: bool,
) {
    predict_intra_with_reader(
        frame,
        x,
        y,
        log2_size,
        mode,
        c_idx,
        strong_intra_smoothing_enabled,
        |_, _, _| None,
    );
}

/// Like [`predict_intra`] but lets the caller override reference-border reads.
/// Returning `Some(UNINIT_SAMPLE)` forces a reference sample unavailable — used
/// for tile boundaries (cross-tile reference samples are not available).
#[allow(clippy::too_many_arguments)]
pub fn predict_intra_with_reader<F>(
    frame: &mut DecodedFrame,
    x: u32,
    y: u32,
    log2_size: u8,
    mode: IntraPredMode,
    c_idx: u8,
    strong_intra_smoothing_enabled: bool,
    mut sample_reader: F,
) where
    F: FnMut(u8, u32, u32) -> Option<u16>,
{
    let (border, border_center, size, bit_depth) = collect_prediction_border_with_reader(
        frame,
        x,
        y,
        log2_size,
        mode,
        c_idx,
        strong_intra_smoothing_enabled,
        &mut sample_reader,
    );
    // Resolve plane once to avoid per-pixel match on c_idx
    let (plane, stride) = frame.plane_mut(c_idx);
    predict_intra_from_border(
        plane,
        stride,
        x,
        y,
        log2_size,
        mode,
        c_idx,
        size,
        bit_depth,
        &border,
        border_center,
    );
}

/// Perform intra prediction for a block into caller-owned storage.
///
/// Reference samples are read from `frame` at `(x, y)`, but predicted samples are
/// written to `dst` with local block origin `(0, 0)` and row stride `dst_stride`.
/// This is useful for analysis paths that need predictions without modifying the
/// reconstructed frame.
pub fn predict_intra_into(
    frame: &DecodedFrame,
    x: u32,
    y: u32,
    log2_size: u8,
    mode: IntraPredMode,
    c_idx: u8, // 0=Y, 1=Cb, 2=Cr
    strong_intra_smoothing_enabled: bool,
    dst: &mut [u16],
    dst_stride: usize,
) {
    predict_intra_into_with_reader(
        frame,
        x,
        y,
        log2_size,
        mode,
        c_idx,
        strong_intra_smoothing_enabled,
        dst,
        dst_stride,
        |_, _, _| None,
    );
}

/// Perform intra prediction for a block into caller-owned storage, allowing the
/// caller to override reference samples before falling back to `frame`.
///
/// The override is used only for reference-border reads. Returning
/// `Some(UNINIT_SAMPLE)` preserves normal unavailable-sample handling.
#[allow(clippy::too_many_arguments)]
pub fn predict_intra_into_with_reader<F>(
    frame: &DecodedFrame,
    x: u32,
    y: u32,
    log2_size: u8,
    mode: IntraPredMode,
    c_idx: u8,
    strong_intra_smoothing_enabled: bool,
    dst: &mut [u16],
    dst_stride: usize,
    mut sample_reader: F,
) where
    F: FnMut(u8, u32, u32) -> Option<u16>,
{
    let size_usize = 1usize << log2_size;
    assert!(dst_stride >= size_usize);
    assert!(dst.len() >= (size_usize - 1) * dst_stride + size_usize);

    let (border, border_center, size, bit_depth) = collect_prediction_border_with_reader(
        frame,
        x,
        y,
        log2_size,
        mode,
        c_idx,
        strong_intra_smoothing_enabled,
        &mut sample_reader,
    );
    predict_intra_from_border(
        dst,
        dst_stride,
        0,
        0,
        log2_size,
        mode,
        c_idx,
        size,
        bit_depth,
        &border,
        border_center,
    );
}

fn collect_prediction_border_with_reader<F>(
    frame: &DecodedFrame,
    x: u32,
    y: u32,
    log2_size: u8,
    mode: IntraPredMode,
    c_idx: u8,
    strong_intra_smoothing_enabled: bool,
    sample_reader: &mut F,
) -> ([i32; 4 * MAX_INTRA_PRED_BLOCK_SIZE + 1], usize, u32, u8)
where
    F: FnMut(u8, u32, u32) -> Option<u16>,
{
    let size = 1u32 << log2_size;
    let bit_depth = frame.bit_depth;
    let chroma_format = frame.chroma_format;

    let mut border = [0i32; 4 * MAX_INTRA_PRED_BLOCK_SIZE + 1];
    let border_center = 2 * MAX_INTRA_PRED_BLOCK_SIZE;
    fill_border_samples_with_reader(
        frame,
        x,
        y,
        size,
        c_idx,
        &mut border,
        border_center,
        sample_reader,
    );

    if c_idx == 0 || chroma_format == 3 {
        intra_prediction_sample_filtering(
            &mut border,
            border_center,
            size as usize,
            c_idx,
            mode.as_u8(),
            strong_intra_smoothing_enabled,
            bit_depth as usize,
        );
    }

    (border, border_center, size, bit_depth)
}

/// Build both the unfiltered and the smoothed reference borders for a block in
/// one neighbour scan, for an encoder-side batch predictor.
///
/// Returns `(unfiltered, filtered, center, bit_depth)`. The `filtered` border is
/// the reference-smoothing result applied unconditionally (for luma / 4:4:4
/// chroma, size > 4); callers select per mode via [`reference_filter_applies`]
/// so each angular prediction sees exactly the border [`predict_intra_into`]
/// would have built for that mode. For 4x4 (or chroma without smoothing)
/// `filtered == unfiltered`.
#[allow(clippy::type_complexity)]
pub fn build_reference_borders(
    frame: &DecodedFrame,
    x: u32,
    y: u32,
    log2_size: u8,
    c_idx: u8,
    strong_intra_smoothing_enabled: bool,
) -> ([i32; INTRA_BORDER_LEN], [i32; INTRA_BORDER_LEN], usize, u8) {
    let size = 1u32 << log2_size;
    let bit_depth = frame.bit_depth;
    let chroma_format = frame.chroma_format;
    let center = INTRA_BORDER_CENTER;

    let mut unfiltered = [0i32; INTRA_BORDER_LEN];
    fill_border_samples(frame, x, y, size, c_idx, &mut unfiltered, center);

    let mut filtered = unfiltered;
    if (c_idx == 0 || chroma_format == 3) && size > 4 {
        apply_reference_filter(
            &mut filtered,
            center,
            size as usize,
            c_idx,
            strong_intra_smoothing_enabled,
            bit_depth as usize,
        );
    }

    (unfiltered, filtered, center, bit_depth)
}

/// Overlay-aware variant of [`build_reference_borders`]: identical output, but
/// reference samples are read through `sample_reader` first (returning `None`
/// falls back to the committed frame, `Some(UNINIT_SAMPLE)` forces the
/// unavailable-edge path). This lets the encoder build the batch-predict borders
/// once from its CTU-local recon overlay, matching what repeated
/// [`predict_intra_into_with_reader`] calls would have seen per mode.
#[allow(clippy::type_complexity)]
pub fn build_reference_borders_with_reader<F>(
    frame: &DecodedFrame,
    x: u32,
    y: u32,
    log2_size: u8,
    c_idx: u8,
    strong_intra_smoothing_enabled: bool,
    mut sample_reader: F,
) -> ([i32; INTRA_BORDER_LEN], [i32; INTRA_BORDER_LEN], usize, u8)
where
    F: FnMut(u8, u32, u32) -> Option<u16>,
{
    let size = 1u32 << log2_size;
    let bit_depth = frame.bit_depth;
    let chroma_format = frame.chroma_format;
    let center = INTRA_BORDER_CENTER;

    let mut unfiltered = [0i32; INTRA_BORDER_LEN];
    fill_border_samples_with_reader(
        frame,
        x,
        y,
        size,
        c_idx,
        &mut unfiltered,
        center,
        &mut sample_reader,
    );

    let mut filtered = unfiltered;
    if (c_idx == 0 || chroma_format == 3) && size > 4 {
        apply_reference_filter(
            &mut filtered,
            center,
            size as usize,
            c_idx,
            strong_intra_smoothing_enabled,
            bit_depth as usize,
        );
    }

    (unfiltered, filtered, center, bit_depth)
}

#[allow(clippy::too_many_arguments)]
fn predict_intra_from_border(
    plane: &mut [u16],
    stride: usize,
    x: u32,
    y: u32,
    log2_size: u8,
    mode: IntraPredMode,
    c_idx: u8,
    size: u32,
    bit_depth: u8,
    border: &[i32],
    border_center: usize,
) {
    let max_val = (1i32 << bit_depth) - 1;

    // Apply prediction based on mode
    match mode {
        IntraPredMode::Planar => {
            predict_planar(
                plane,
                stride,
                x,
                y,
                size,
                log2_size,
                max_val,
                &border,
                border_center,
            );
        }
        IntraPredMode::Dc => {
            predict_dc(
                plane,
                stride,
                x,
                y,
                size,
                log2_size,
                c_idx,
                max_val,
                &border,
                border_center,
            );
        }
        _ => {
            let mode_val = mode.as_u8();
            predict_angular(
                plane,
                stride,
                x,
                y,
                size,
                c_idx,
                mode_val,
                max_val,
                &border,
                border_center,
            );
        }
    }
}

/// Planar intra prediction from an already-collected reference border.
///
/// This is the same scalar reference used by [`predict_intra_into`], exposed so
/// encoder-side primitive dispatch can build borders once and call exact
/// prediction kernels directly.
#[allow(clippy::too_many_arguments)]
pub fn predict_planar_from_border(
    plane: &mut [u16],
    stride: usize,
    log2_size: u8,
    bit_depth: u8,
    border: &[i32],
    center: usize,
) {
    let size = 1u32 << log2_size;
    let max_val = (1i32 << bit_depth) - 1;
    predict_planar(
        plane, stride, 0, 0, size, log2_size, max_val, border, center,
    );
}

/// DC intra prediction from an already-collected reference border.
///
/// This is the same scalar reference used by [`predict_intra_into`], exposed so
/// encoder-side primitive dispatch can build borders once and call exact
/// prediction kernels directly.
#[allow(clippy::too_many_arguments)]
pub fn predict_dc_from_border(
    plane: &mut [u16],
    stride: usize,
    log2_size: u8,
    c_idx: u8,
    bit_depth: u8,
    border: &[i32],
    center: usize,
) {
    let size = 1u32 << log2_size;
    let max_val = (1i32 << bit_depth) - 1;
    predict_dc(
        plane, stride, 0, 0, size, log2_size, c_idx, max_val, border, center,
    );
}

/// Intra prediction reference sample filtering (H.265 8.4.4.2.3)
///
/// Applies [1,2,1]/4 low-pass filter to reference samples before prediction.
/// For 32x32 luma blocks with strong_intra_smoothing, uses bilinear interpolation instead.
/// H.265 8.4.4.2.3 `filterFlag`: whether reference smoothing applies for a given
/// block size and intra mode (luma / 4:4:4-chroma reference). The *content* of
/// the smoothed border is mode-independent, so a batch predictor can precompute
/// one smoothed border and select it per mode via this predicate (mirrors x265's
/// `g_intraFilterFlags[mode] & size`).
pub fn reference_filter_applies(n_t: usize, intra_pred_mode: u8) -> bool {
    if intra_pred_mode == 1 || n_t == 4 {
        // DC mode or 4x4: no filtering
        return false;
    }
    let min_dist_ver_hor = (intra_pred_mode as i32 - 26)
        .abs()
        .min((intra_pred_mode as i32 - 10).abs());
    match n_t {
        8 => min_dist_ver_hor > 7,
        16 => min_dist_ver_hor > 1,
        32 => min_dist_ver_hor > 0,
        _ => false, // 64 or other sizes: no filtering
    }
}

fn intra_prediction_sample_filtering(
    border: &mut [i32],
    center: usize,
    n_t: usize, // block size (4, 8, 16, 32)
    c_idx: u8,  // 0=luma, 1/2=chroma
    intra_pred_mode: u8,
    strong_intra_smoothing_enabled: bool,
    bit_depth: usize,
) {
    if !reference_filter_applies(n_t, intra_pred_mode) {
        return;
    }
    apply_reference_filter(
        border,
        center,
        n_t,
        c_idx,
        strong_intra_smoothing_enabled,
        bit_depth,
    );
}

/// The mode-independent body of reference smoothing (assumes the caller has
/// already decided it applies). Applies the [1,2,1]/4 low-pass filter, or
/// bilinear interpolation for 32x32 luma with strong intra smoothing.
pub fn apply_reference_filter(
    border: &mut [i32],
    center: usize,
    n_t: usize,
    c_idx: u8,
    strong_intra_smoothing_enabled: bool,
    bit_depth: usize,
) {
    // Check for strong intra smoothing (bilinear interpolation for 32x32 luma)
    let bi_int_flag = strong_intra_smoothing_enabled
        && c_idx == 0
        && n_t == 32
        && (border[center] + border[center + 64] - 2 * border[center + 32]).abs()
            < (1 << (bit_depth - 5))
        && (border[center] + border[center.wrapping_sub(64)] - 2 * border[center.wrapping_sub(32)])
            .abs()
            < (1 << (bit_depth - 5));

    // Temporary filtered array
    let mut pf = [0i32; 4 * MAX_INTRA_PRED_BLOCK_SIZE + 1];
    let pf_center = 2 * MAX_INTRA_PRED_BLOCK_SIZE;

    if bi_int_flag {
        // Strong intra smoothing: bilinear interpolation from corner samples
        pf[pf_center - 2 * n_t] = border[center - 2 * n_t]; // bottom-left
        pf[pf_center + 2 * n_t] = border[center + 2 * n_t]; // top-right
        pf[pf_center] = border[center]; // top-left

        let p0 = border[center];
        let p_neg64 = border[center - 64];
        let p_pos64 = border[center + 64];

        for i in 1..64i32 {
            pf[(pf_center as i32 - i) as usize] = p0 + ((i * (p_neg64 - p0) + 32) >> 6);
            pf[(pf_center as i32 + i) as usize] = p0 + ((i * (p_pos64 - p0) + 32) >> 6);
        }
    } else {
        // Normal [1,2,1]/4 filter
        // Keep endpoints unfiltered
        pf[pf_center - 2 * n_t] = border[center - 2 * n_t];
        pf[pf_center + 2 * n_t] = border[center + 2 * n_t];

        // Filter all samples from -(2*nT-1) to (2*nT-1)
        for i in -(2 * n_t as i32 - 1)..=(2 * n_t as i32 - 1) {
            let idx = (center as i32 + i) as usize;
            pf[(pf_center as i32 + i) as usize] =
                (border[idx + 1] + 2 * border[idx] + border[idx - 1] + 2) >> 2;
        }
    }

    // Copy filtered values back
    for i in 0..=(4 * n_t) {
        border[center - 2 * n_t + i] = pf[pf_center - 2 * n_t + i];
    }
}

/// Write a sample directly to a plane slice
#[inline(always)]
fn write_sample(plane: &mut [u16], stride: usize, x: u32, y: u32, value: u16) {
    let idx = y as usize * stride + x as usize;
    if idx < plane.len() {
        plane[idx] = value;
    }
}

/// Read a sample directly from a plane slice
#[inline(always)]
fn read_plane(plane: &[u16], stride: usize, x: u32, y: u32) -> u16 {
    let idx = y as usize * stride + x as usize;
    if idx < plane.len() { plane[idx] } else { 0 }
}

/// Fill border samples from neighboring pixels
fn fill_border_samples(
    frame: &DecodedFrame,
    x: u32,
    y: u32,
    size: u32,
    c_idx: u8,
    border: &mut [i32],
    center: usize,
) {
    fill_border_samples_with_reader(frame, x, y, size, c_idx, border, center, &mut |_, _, _| {
        None
    });
}

/// Fill border samples from neighboring pixels, consulting `sample_reader`
/// before reading the committed frame.
fn fill_border_samples_with_reader<F>(
    frame: &DecodedFrame,
    x: u32,
    y: u32,
    size: u32,
    c_idx: u8,
    border: &mut [i32],
    center: usize,
    sample_reader: &mut F,
) where
    F: FnMut(u8, u32, u32) -> Option<u16>,
{
    // Border layout (indexed from center):
    //   border[-2*size .. -1] = left samples (bottom to top): p[-1][2*nTbS-1] .. p[-1][0]
    //   border[0] = top-left corner: p[-1][-1]
    //   border[1 .. 2*size] = top samples (left to right): p[0][-1] .. p[2*nTbS-1][-1]
    //
    // Availability tracking: avail[] parallel array, same layout as border
    // avail[i] = true means the reference sample was read from a decoded block
    let mut avail = [false; 4 * MAX_INTRA_PRED_BLOCK_SIZE + 1];
    let mut avail_count = 0u32;
    let total_samples = 4 * size + 1;

    // Resolve plane once to avoid per-pixel match dispatch
    let (plane, stride) = frame.plane(c_idx);

    // Component-plane dimensions: luma is full-res; chroma depends on the
    // subsampling (4:2:0 -> W/2xH/2, 4:2:2 -> W/2xH, 4:4:4 -> WxH).
    let (frame_w, frame_h) = frame.component_dims(c_idx);

    let avail_left = x > 0;
    let avail_top = y > 0;
    let avail_top_left = avail_left && avail_top;

    // Fill with default value if no neighbors available
    let default_val = 1i32 << (frame.bit_depth - 1);

    // Top-left corner
    let mut corner_avail = false;
    if avail_top_left {
        let raw = sample_reader(c_idx, x - 1, y - 1)
            .unwrap_or_else(|| read_plane(plane, stride, x - 1, y - 1));
        if raw != UNINIT_SAMPLE {
            border[center] = raw as i32;
            corner_avail = true;
            avail_count += 1;
        }
    }
    if !corner_avail && avail_top {
        let raw =
            sample_reader(c_idx, x, y - 1).unwrap_or_else(|| read_plane(plane, stride, x, y - 1));
        if raw != UNINIT_SAMPLE {
            border[center] = raw as i32;
            corner_avail = true;
            avail_count += 1;
        }
    }
    if !corner_avail && avail_left {
        let raw =
            sample_reader(c_idx, x - 1, y).unwrap_or_else(|| read_plane(plane, stride, x - 1, y));
        if raw != UNINIT_SAMPLE {
            border[center] = raw as i32;
            corner_avail = true;
            avail_count += 1;
        }
    }
    if !corner_avail {
        border[center] = default_val;
    }
    avail[center] = corner_avail;

    // Top samples p[0][-1] .. p[2*nTbS-1][-1]
    // Merged loop for top and above-right (both read from row y-1)
    if avail_top {
        let top_row_start = (y - 1) as usize * stride;
        // Hoist bounds: compute how many valid top samples exist
        let top_count = (2 * size).min(frame_w.saturating_sub(x)) as usize;
        let top_row_end = top_row_start + x as usize + top_count;
        if top_row_end <= plane.len() {
            // Fast path: all valid top samples are in-bounds
            let row_base = top_row_start + x as usize;
            for i in 0..top_count {
                let rx = x + i as u32;
                let raw = sample_reader(c_idx, rx, y - 1).unwrap_or(plane[row_base + i]);
                if raw != UNINIT_SAMPLE {
                    let idx = center + 1 + i;
                    border[idx] = raw as i32;
                    avail[idx] = true;
                    avail_count += 1;
                }
            }
        } else {
            // Slow path: consult the reader first — it may cover positions
            // the backing plane does not (encoder-side canvas readers over
            // planeless worker frames); an out-of-bounds plane fallback is
            // unavailable (UNINIT), exactly like the old skip.
            for i in 0..top_count {
                let plane_idx = top_row_start + x as usize + i;
                let rx = x + i as u32;
                let raw = sample_reader(c_idx, rx, y - 1)
                    .unwrap_or_else(|| plane.get(plane_idx).copied().unwrap_or(UNINIT_SAMPLE));
                if raw != UNINIT_SAMPLE {
                    let idx = center + 1 + i;
                    border[idx] = raw as i32;
                    avail[idx] = true;
                    avail_count += 1;
                }
            }
        }
    }

    // Left + bottom-left samples p[-1][0] .. p[-1][2*nTbS-1]
    // All read from column x-1, merged into one loop
    if avail_left {
        let left_x = (x - 1) as usize;
        // Hoist bounds: compute how many valid left samples exist
        let left_count = (2 * size).min(frame_h.saturating_sub(y)) as usize;
        let last_left_idx = (y as usize + left_count.saturating_sub(1)) * stride + left_x;
        if last_left_idx < plane.len() {
            // Fast path: all valid left samples are in-bounds
            for i in 0..left_count {
                let ry = y + i as u32;
                let raw = sample_reader(c_idx, x - 1, ry)
                    .unwrap_or(plane[(y as usize + i) * stride + left_x]);
                if raw != UNINIT_SAMPLE {
                    let idx = center - 1 - i;
                    border[idx] = raw as i32;
                    avail[idx] = true;
                    avail_count += 1;
                }
            }
        } else {
            // Slow path: reader-first, bounded plane fallback (see the top
            // branch above).
            for i in 0..left_count {
                let plane_idx = (y as usize + i) * stride + left_x;
                let ry = y + i as u32;
                let raw = sample_reader(c_idx, x - 1, ry)
                    .unwrap_or_else(|| plane.get(plane_idx).copied().unwrap_or(UNINIT_SAMPLE));
                if raw != UNINIT_SAMPLE {
                    let idx = center - 1 - i;
                    border[idx] = raw as i32;
                    avail[idx] = true;
                    avail_count += 1;
                }
            }
        }
    }

    // Reference sample substitution (H.265 8.4.4.2.2)
    // Skip entirely when all samples are available (O(1) check vs O(n) scan)
    if avail_count < total_samples {
        reference_sample_substitution(border, &avail, center, size as usize, default_val);
    }
}

/// Substitute unavailable reference samples (H.265 8.4.4.2.2)
///
/// Scans from p[-1][2*nTbS-1] (bottom-left) to p[2*nTbS-1][-1] (top-right).
/// First finds any available sample, then propagates forward:
/// each unavailable sample gets the value of the most recently seen
/// available (or previously substituted) sample.
fn reference_sample_substitution(
    border: &mut [i32],
    avail: &[bool],
    center: usize,
    size: usize,
    default_val: i32,
) {
    // Total reference samples: 4*size + 1 (2*size left + corner + 2*size top)
    // Layout in border array: center-2*size .. center+2*size
    // (Caller already skips this function when all samples are available)

    // Step 1: Find first available sample (scan from bottom-left to top-right)
    let mut first_avail_val = None;

    // Scan left column (bottom-left to top): p[-1][2*nTbS-1] .. p[-1][0]
    for i in (0..(2 * size)).rev() {
        let idx = center - 1 - i;
        if avail[idx] {
            first_avail_val = Some(border[idx]);
            break;
        }
    }

    // Corner: p[-1][-1]
    if first_avail_val.is_none() && avail[center] {
        first_avail_val = Some(border[center]);
    }

    // Top row: p[0][-1] .. p[2*nTbS-1][-1]
    if first_avail_val.is_none() {
        for i in 0..(2 * size) {
            let idx = center + 1 + i;
            if avail[idx] {
                first_avail_val = Some(border[idx]);
                break;
            }
        }
    }

    let first_val = first_avail_val.unwrap_or(default_val);

    // Step 2: Forward propagation from bottom-left to top-right
    // Each unavailable sample gets the last propagated value
    let mut current = first_val;

    // Left column (bottom to top): p[-1][2*nTbS-1] .. p[-1][0]
    for i in (0..(2 * size)).rev() {
        let idx = center - 1 - i;
        if avail[idx] {
            current = border[idx];
        } else {
            border[idx] = current;
        }
    }

    // Corner
    if avail[center] {
        current = border[center];
    } else {
        border[center] = current;
    }

    // Top row (left to right): p[0][-1] .. p[2*nTbS-1][-1]
    for i in 0..(2 * size) {
        let idx = center + 1 + i;
        if avail[idx] {
            current = border[idx];
        } else {
            border[idx] = current;
        }
    }
}

/// Planar prediction (mode 0) - H.265 8.4.4.2.4
#[allow(clippy::too_many_arguments)]
fn predict_planar(
    plane: &mut [u16],
    stride: usize,
    x: u32,
    y: u32,
    size: u32,
    log2_size: u8,
    max_val: i32,
    border: &[i32],
    center: usize,
) {
    let n = size as usize;
    let n_i = size as i32;
    let right = border[center + 1 + n]; // border[nT+1]
    let bottom = border[center - 1 - n]; // border[-1-nT]

    // Check if entire block fits in plane for unchecked inner loop
    let last_row_end = (y as usize + n - 1) * stride + x as usize + n;
    let block_fits = last_row_end <= plane.len();

    for py in 0..n {
        let py_i = py as i32;
        let left = border[center - 1 - py];
        let row_start = (y as usize + py) * stride + x as usize;

        if block_fits {
            let row = &mut plane[row_start..row_start + n];
            for px in 0..n {
                let px_i = px as i32;
                let top = border[center + 1 + px];
                let pred = ((n_i - 1 - px_i) * left
                    + (px_i + 1) * right
                    + (n_i - 1 - py_i) * top
                    + (py_i + 1) * bottom
                    + n_i)
                    >> (log2_size + 1);
                row[px] = pred.clamp(0, max_val) as u16;
            }
        } else {
            for px in 0..n {
                let idx = row_start + px;
                if idx < plane.len() {
                    let px_i = px as i32;
                    let top = border[center + 1 + px];
                    let pred = ((n_i - 1 - px_i) * left
                        + (px_i + 1) * right
                        + (n_i - 1 - py_i) * top
                        + (py_i + 1) * bottom
                        + n_i)
                        >> (log2_size + 1);
                    plane[idx] = pred.clamp(0, max_val) as u16;
                }
            }
        }
    }
}

/// DC prediction (mode 1) - H.265 8.4.4.2.5
#[allow(clippy::too_many_arguments)]
fn predict_dc(
    plane: &mut [u16],
    stride: usize,
    x: u32,
    y: u32,
    size: u32,
    log2_size: u8,
    c_idx: u8,
    max_val: i32,
    border: &[i32],
    center: usize,
) {
    let n = size as i32;

    // Calculate DC value as average of top and left samples
    let mut dc_val = 0i32;
    for i in 0..size {
        dc_val += border[center + 1 + i as usize]; // top
        dc_val += border[center - 1 - i as usize]; // left
    }
    dc_val = (dc_val + n) >> (log2_size + 1);

    // Apply DC filtering for luma and small blocks
    if c_idx == 0 && size < 32 {
        // Corner pixel: average of corner neighbors and 2*DC
        let corner = (border[center - 1] + 2 * dc_val + border[center + 1] + 2) >> 2;
        write_sample(plane, stride, x, y, corner.clamp(0, max_val) as u16);

        // Top edge: blend top border with DC
        let row_start = y as usize * stride + x as usize;
        let top_row = &mut plane[row_start + 1..row_start + size as usize];
        for px in 1..size as usize {
            let pred = (border[center + 1 + px] + 3 * dc_val + 2) >> 2;
            top_row[px - 1] = pred.clamp(0, max_val) as u16;
        }

        // Left edge: blend left border with DC
        for py in 1..size {
            let pred = (border[center - 1 - py as usize] + 3 * dc_val + 2) >> 2;
            write_sample(plane, stride, x, y + py, pred.clamp(0, max_val) as u16);
        }

        // Interior: pure DC — fill rows directly
        let dc_u16 = dc_val.clamp(0, max_val) as u16;
        for py in 1..size {
            let row_start = (y + py) as usize * stride + (x as usize + 1);
            let row_end = row_start + (size as usize - 1);
            if row_end <= plane.len() {
                plane[row_start..row_end].fill(dc_u16);
            }
        }
    } else {
        // No filtering: fill entire block with DC value using row fills
        let dc_u16 = dc_val.clamp(0, max_val) as u16;
        for py in 0..size {
            let row_start = (y + py) as usize * stride + x as usize;
            let row_end = row_start + size as usize;
            if row_end <= plane.len() {
                plane[row_start..row_end].fill(dc_u16);
            }
        }
    }
}

/// Angular prediction (modes 2-34) - H.265 8.4.4.2.6
#[allow(clippy::too_many_arguments)]
/// Angular intra prediction (modes 2..=34) into `plane` at `(x, y)`.
///
/// Exposed so an encoder-side batch predictor can reuse the exact decoder math
/// (predicting into a `size`-stride slot at `(0, 0)`), guaranteeing bit-identity
/// with [`predict_intra_into`]. `border` must already be the unfiltered /
/// smoothed reference selected per [`reference_filter_applies`].
pub fn predict_angular(
    plane: &mut [u16],
    stride: usize,
    x: u32,
    y: u32,
    size: u32,
    c_idx: u8,
    mode: u8,
    max_val: i32,
    border: &[i32],
    center: usize,
) {
    let n = size as i32;
    let n_u = n as usize;
    let intra_pred_angle = INTRA_PRED_ANGLE[mode as usize] as i32;

    // Check if entire block fits in plane for unchecked inner loop
    let last_row_end = (y as usize + n_u - 1) * stride + x as usize + n_u;
    let block_fits = last_row_end <= plane.len();

    // Build reference array
    let mut ref_arr = [0i32; 4 * MAX_INTRA_PRED_BLOCK_SIZE + 1];
    let ref_center = 2 * MAX_INTRA_PRED_BLOCK_SIZE;

    if mode >= 18 {
        // Horizontal-ish modes (18-34)
        // Reference is top samples

        // Copy top samples to ref[0..nT]
        ref_arr[ref_center..ref_center + n as usize + 1]
            .copy_from_slice(&border[center..center + n as usize + 1]);

        if intra_pred_angle < 0 {
            // Negative angle: need to extend reference to the left
            let inv_angle = get_inv_angle(mode);
            let ext = (n * intra_pred_angle) >> 5;

            if ext < -1 {
                for xx in ext..=-1 {
                    let idx = (xx * inv_angle + 128) >> 8;
                    if idx >= 0 && idx <= (2 * n) {
                        ref_arr[(ref_center as i32 + xx) as usize] =
                            border[(center as i32 - idx) as usize];
                    }
                }
            }
        } else {
            // Positive angle: extend reference to the right
            let src_start = center + n as usize + 1;
            let dst_start = ref_center + n as usize + 1;
            let count = n as usize;
            ref_arr[dst_start..dst_start + count]
                .copy_from_slice(&border[src_start..src_start + count]);
        }

        // Generate prediction
        for py in 0..n {
            let i_idx = ((py + 1) * intra_pred_angle) >> 5;
            let i_fact = ((py + 1) * intra_pred_angle) & 31;
            let row_start = (y as i32 + py) as usize * stride + x as usize;
            // Hoist row-constant base index
            let base_idx = (ref_center as i32 + i_idx + 1) as usize;

            if block_fits {
                let row = &mut plane[row_start..row_start + n_u];
                if i_fact != 0 {
                    let w0 = 32 - i_fact;
                    for (px, out) in row.iter_mut().enumerate() {
                        let idx = base_idx + px;
                        let pred = (w0 * ref_arr[idx] + i_fact * ref_arr[idx + 1] + 16) >> 5;
                        *out = pred.clamp(0, max_val) as u16;
                    }
                } else {
                    for (px, out) in row.iter_mut().enumerate() {
                        *out = ref_arr[base_idx + px].clamp(0, max_val) as u16;
                    }
                }
            } else {
                let w0 = 32 - i_fact;
                for px in 0..n_u {
                    let out_idx = row_start + px;
                    if out_idx < plane.len() {
                        let idx = base_idx + px;
                        let pred = if i_fact != 0 {
                            (w0 * ref_arr[idx] + i_fact * ref_arr[idx + 1] + 16) >> 5
                        } else {
                            ref_arr[idx]
                        };
                        plane[out_idx] = pred.clamp(0, max_val) as u16;
                    }
                }
            }
        }

        // Boundary filter for mode 26 (vertical)
        if mode == 26 && c_idx == 0 && size < 32 {
            for py in 0..n {
                let pred =
                    border[center + 1] + ((border[center - 1 - py as usize] - border[center]) >> 1);
                write_sample(
                    plane,
                    stride,
                    x,
                    y + py as u32,
                    pred.clamp(0, max_val) as u16,
                );
            }
        }
    } else {
        // Vertical-ish modes (2-17)
        // Reference is left samples (mirrored)

        // Copy left samples (negated indices) to ref[0..nT]
        for i in 0..=n {
            ref_arr[ref_center + i as usize] = border[center - i as usize];
        }

        if intra_pred_angle < 0 {
            // Negative angle: extend reference
            let inv_angle = get_inv_angle(mode);
            let ext = (n * intra_pred_angle) >> 5;

            if ext < -1 {
                for xx in ext..=-1 {
                    let idx = (xx * inv_angle + 128) >> 8;
                    if idx >= 0 && idx <= (2 * n) {
                        ref_arr[(ref_center as i32 + xx) as usize] =
                            border[(center as i32 + idx) as usize];
                    }
                }
            }
        } else {
            // Positive angle: extend reference
            for xx in (n + 1)..=(2 * n) {
                ref_arr[ref_center + xx as usize] = border[center - xx as usize];
            }
        }

        // Generate prediction (transposed compared to mode >= 18)
        for py in 0..n {
            let row_start = (y as i32 + py) as usize * stride + x as usize;
            // Hoist row-constant base index
            let row_base = (ref_center as i32 + py + 1) as usize;

            if block_fits {
                let row = &mut plane[row_start..row_start + n_u];
                for (px, out) in row.iter_mut().enumerate() {
                    let i_idx = ((px as i32 + 1) * intra_pred_angle) >> 5;
                    let i_fact = ((px as i32 + 1) * intra_pred_angle) & 31;
                    let idx = (row_base as i32 + i_idx) as usize;
                    let pred = if i_fact != 0 {
                        ((32 - i_fact) * ref_arr[idx] + i_fact * ref_arr[idx + 1] + 16) >> 5
                    } else {
                        ref_arr[idx]
                    };
                    *out = pred.clamp(0, max_val) as u16;
                }
            } else {
                for px in 0..n_u {
                    let out_idx = row_start + px;
                    if out_idx < plane.len() {
                        let i_idx = ((px as i32 + 1) * intra_pred_angle) >> 5;
                        let i_fact = ((px as i32 + 1) * intra_pred_angle) & 31;
                        let idx = (row_base as i32 + i_idx) as usize;
                        let pred = if i_fact != 0 {
                            ((32 - i_fact) * ref_arr[idx] + i_fact * ref_arr[idx + 1] + 16) >> 5
                        } else {
                            ref_arr[idx]
                        };
                        plane[out_idx] = pred.clamp(0, max_val) as u16;
                    }
                }
            }
        }

        // Boundary filter for mode 10 (horizontal)
        if mode == 10 && c_idx == 0 && size < 32 {
            for px in 0..n {
                let pred =
                    border[center - 1] + ((border[center + 1 + px as usize] - border[center]) >> 1);
                write_sample(
                    plane,
                    stride,
                    x + px as u32,
                    y,
                    pred.clamp(0, max_val) as u16,
                );
            }
        }
    }
}

/// Fill MPM (Most Probable Mode) candidate list
pub fn fill_mpm_candidates(
    cand_a: IntraPredMode, // left neighbor mode
    cand_b: IntraPredMode, // above neighbor mode
) -> [IntraPredMode; 3] {
    if cand_a == cand_b {
        if cand_a.as_u8() < 2 {
            // DC or Planar
            [
                IntraPredMode::Planar,
                IntraPredMode::Dc,
                IntraPredMode::Angular26, // Vertical
            ]
        } else {
            // Angular mode
            let mode = cand_a.as_u8();
            let left = 2 + ((mode - 2).wrapping_sub(1) % 32);
            let right = 2 + ((mode - 2) + 1) % 32;
            [
                cand_a,
                IntraPredMode::from_u8(left).unwrap_or(IntraPredMode::Dc),
                IntraPredMode::from_u8(right).unwrap_or(IntraPredMode::Dc),
            ]
        }
    } else {
        // Different modes
        let third = if cand_a != IntraPredMode::Planar && cand_b != IntraPredMode::Planar {
            IntraPredMode::Planar
        } else if cand_a != IntraPredMode::Dc && cand_b != IntraPredMode::Dc {
            IntraPredMode::Dc
        } else {
            IntraPredMode::Angular26
        };
        [cand_a, cand_b, third]
    }
}

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

    #[test]
    fn test_mpm_candidates_same_dc() {
        let mpm = fill_mpm_candidates(IntraPredMode::Dc, IntraPredMode::Dc);
        assert_eq!(mpm[0], IntraPredMode::Planar);
        assert_eq!(mpm[1], IntraPredMode::Dc);
        assert_eq!(mpm[2], IntraPredMode::Angular26);
    }

    #[test]
    fn test_mpm_candidates_different() {
        let mpm = fill_mpm_candidates(IntraPredMode::Dc, IntraPredMode::Planar);
        assert_eq!(mpm[0], IntraPredMode::Dc);
        assert_eq!(mpm[1], IntraPredMode::Planar);
        assert_eq!(mpm[2], IntraPredMode::Angular26);
    }

    #[test]
    fn test_intra_angles() {
        // Mode 10 should be horizontal (angle 0)
        assert_eq!(INTRA_PRED_ANGLE[10], 0);
        // Mode 26 should be vertical (angle 0)
        assert_eq!(INTRA_PRED_ANGLE[26], 0);
        // Mode 2 should have positive angle
        assert_eq!(INTRA_PRED_ANGLE[2], 32);
        // Mode 34 should have positive angle
        assert_eq!(INTRA_PRED_ANGLE[34], 32);
    }

    fn fill_test_frame(frame: &mut DecodedFrame) {
        let max_val = (1u32 << frame.bit_depth) - 1;
        for c_idx in 0..=2 {
            let (width, height) = frame.component_dims(c_idx);
            let (plane, stride) = frame.plane_mut(c_idx);
            if stride == 0 {
                continue;
            }
            for y in 0..height as usize {
                for x in 0..width as usize {
                    let idx = y * stride + x;
                    let seed = x as u32 * 37 + y as u32 * 17 + c_idx as u32 * 101;
                    plane[idx] = if (x as u32 * 3 + y as u32 * 5 + c_idx as u32 * 7) % 13 == 0 {
                        UNINIT_SAMPLE
                    } else {
                        (seed % (max_val + 1)) as u16
                    };
                }
            }
        }
    }

    fn assert_predict_into_matches_frame_write(
        bit_depth: u8,
        chroma_format: u8,
        c_idx: u8,
        x: u32,
        y: u32,
        log2_size: u8,
        mode: IntraPredMode,
    ) {
        let mut frame = DecodedFrame::with_params(96, 96, bit_depth, chroma_format);
        fill_test_frame(&mut frame);
        let original = frame.clone();
        let mut written = frame.clone();
        let size = 1usize << log2_size;
        let mut pred = Vec::new();
        pred.resize(size * size, 0);

        predict_intra_into(&frame, x, y, log2_size, mode, c_idx, true, &mut pred, size);
        predict_intra(&mut written, x, y, log2_size, mode, c_idx, true);

        let (plane, stride) = written.plane(c_idx);
        for row in 0..size {
            let start = (y as usize + row) * stride + x as usize;
            assert_eq!(
                &pred[row * size..row * size + size],
                &plane[start..start + size],
                "mismatch for bit_depth={bit_depth}, chroma_format={chroma_format}, c_idx={c_idx}, pos=({x},{y}), log2_size={log2_size}, mode={:?}",
                mode
            );
        }

        assert_eq!(frame.y_plane, original.y_plane);
        assert_eq!(frame.cb_plane, original.cb_plane);
        assert_eq!(frame.cr_plane, original.cr_plane);
    }

    #[test]
    fn predict_into_matches_frame_write_across_modes_sizes_and_formats() {
        let modes = [
            IntraPredMode::Planar,
            IntraPredMode::Dc,
            IntraPredMode::Angular2,
            IntraPredMode::Angular10,
            IntraPredMode::Angular18,
            IntraPredMode::Angular26,
            IntraPredMode::Angular34,
        ];
        let positions = [(0, 0), (8, 0), (0, 8), (8, 8)];

        for bit_depth in [8, 10] {
            for chroma_format in [1, 2, 3] {
                for c_idx in [0, 1, 2] {
                    for log2_size in [2, 3, 4, 5] {
                        for mode in modes {
                            for (x, y) in positions {
                                assert_predict_into_matches_frame_write(
                                    bit_depth,
                                    chroma_format,
                                    c_idx,
                                    x,
                                    y,
                                    log2_size,
                                    mode,
                                );
                            }
                        }
                    }
                }
            }
        }
    }
}