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
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
/*
 * Copyright (c) Radzivon Bartoshyk 6/2026. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 * 1.  Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 *
 * 2.  Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 *
 * 3.  Neither the name of the copyright holder nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

use crate::ccso::{CcsoPrepArea, CcsoPrepCfg, CcsoPrepCtx, CcsoPrepSrc, ccso_add, ccso_prep};
use crate::intops::{apply_sign, iclip, imax, imin, ulog2};
use crate::pixel::{BitDepth, BitDepth8, Pixel};
use crate::tables::CDEF_DIRECTIONS;

pub(crate) const CDEF_HAVE_LEFT: u8 = 1 << 0;
pub(crate) const CDEF_HAVE_RIGHT: u8 = 1 << 1;
pub(crate) const CDEF_HAVE_TOP: u8 = 1 << 2;
pub(crate) const CDEF_HAVE_BOTTOM: u8 = 1 << 3;

#[allow(clippy::too_many_arguments)]
pub(crate) fn cdef_padding<BD: BitDepth>(
    _bd: BD,
    tmp: &mut [i16],
    tmp_stride: usize,
    src: &[BD::Pixel],
    src_stride: usize,
    src_off: usize,
    left: &[[BD::Pixel; 2]],
    top: &[BD::Pixel],
    top_off: usize,
    bottom: &[BD::Pixel],
    bottom_off: usize,
    bottom_stride: usize,
    w: usize,
    h: usize,
    edges: u8,
) {
    let o = 2 * tmp_stride + 2;

    let mut x_start: i32 = -2;
    let mut x_end: i32 = w as i32 + 2;
    let mut y_start: i32 = -2;
    let mut y_end: i32 = h as i32 + 2;

    if edges & CDEF_HAVE_TOP == 0 {
        let base = o.wrapping_sub(2).wrapping_sub(2 * tmp_stride);
        fill(&mut tmp[base..], tmp_stride, w + 4, 2);
        y_start = 0;
    }
    if edges & CDEF_HAVE_BOTTOM == 0 {
        let base = o + h * tmp_stride - 2;
        fill(&mut tmp[base..], tmp_stride, w + 4, 2);
        y_end -= 2;
    }
    if edges & CDEF_HAVE_LEFT == 0 {
        let base = (o as i32 + y_start * tmp_stride as i32 - 2) as usize;
        fill(&mut tmp[base..], tmp_stride, 2, (y_end - y_start) as usize);
        x_start = 0;
    }
    if edges & CDEF_HAVE_RIGHT == 0 {
        let base = (o as i32 + y_start * tmp_stride as i32 + w as i32) as usize;
        fill(&mut tmp[base..], tmp_stride, 2, (y_end - y_start) as usize);
        x_end -= 2;
    }

    let mut toff = top_off;
    let copy_w = (x_end - x_start) as usize;
    for y in y_start..0 {
        let ti = (o as i32 + x_start + y * tmp_stride as i32) as usize;
        let si = (toff as i32 + x_start) as usize;
        copy_pixels_to_i16(&mut tmp[ti..ti + copy_w], &top[si..si + copy_w]);
        toff += src_stride;
    }

    for y in 0..h as i32 {
        let ti = (o as i32 + x_start + y * tmp_stride as i32) as usize;
        for x in x_start..0 {
            tmp[ti + (x - x_start) as usize] =
                Into::<i32>::into(left[y as usize][(2 + x) as usize]) as i16;
        }
    }

    let mut soff = src_off;
    let copy_w = x_end as usize;
    for y in 0..h as i32 {
        let ti = (o as i32 + y * tmp_stride as i32) as usize;
        copy_pixels_to_i16(&mut tmp[ti..ti + copy_w], &src[soff..soff + copy_w]);
        soff += src_stride;
    }

    let mut boff = bottom_off;
    let copy_w = (x_end - x_start) as usize;
    for y in h as i32..y_end {
        let ti = (o as i32 + x_start + y * tmp_stride as i32) as usize;
        let si = (boff as i32 + x_start) as usize;
        copy_pixels_to_i16(&mut tmp[ti..ti + copy_w], &bottom[si..si + copy_w]);
        boff += bottom_stride;
    }
}

#[inline(always)]
pub(crate) fn constrain(diff: i32, threshold: i32, shift: i32) -> i32 {
    let adiff = diff.abs();
    apply_sign(imin(adiff, imax(0, threshold - (adiff >> shift))), diff)
}

pub(crate) fn fill(tmp: &mut [i16], stride: usize, w: usize, h: usize) {
    // `chunks_mut`, not `chunks_exact_mut`: a right-edge fill starts mid-row,
    // so its last row is a short tail chunk that must still be filled.
    for row in tmp.chunks_mut(stride).take(h) {
        row[..w].fill(i16::MIN);
    }
}

#[inline(always)]
fn copy_pixels_to_i16<P: Pixel>(dst: &mut [i16], src: &[P]) {
    debug_assert_eq!(dst.len(), src.len());
    for (d, &s) in dst.iter_mut().zip(src) {
        *d = Into::<i32>::into(s) as i16;
    }
}

#[inline(always)]
fn cast_left_u8<P: Pixel>(left: &[[P; 2]]) -> &[[u8; 2]] {
    debug_assert_eq!(P::BITDEPTH, 8);
    // SAFETY: the only 8-bit Pixel implementation is `u8`; the returned slice
    // has the same allocation, element count and lifetime as `left`.
    unsafe { core::slice::from_raw_parts(left.as_ptr().cast::<[u8; 2]>(), left.len()) }
}

#[inline(always)]
fn cast_left_u16<P: Pixel>(left: &[[P; 2]]) -> &[[u16; 2]] {
    debug_assert_eq!(P::BITDEPTH, 16);
    assert!(align_of::<P>() >= align_of::<u16>());
    // SAFETY: the only 16-bit Pixel implementation is `u16`; the returned slice
    // has the same allocation, element count and lifetime as `left`.
    unsafe { core::slice::from_raw_parts(left.as_ptr().cast::<[u16; 2]>(), left.len()) }
}

pub(crate) fn cdef_find_dir_bd<BD: BitDepth>(
    bd: BD,
    exec: &crate::exec_context::ExecContext,
    img: &[BD::Pixel],
    stride: usize,
    var: &mut u32,
) -> i32 {
    if let Some(img8) = <BD::Pixel as Pixel>::try_as_u8_slice(img) {
        return unsafe { (exec.cdef_dir_8bpc)(img8, stride, var) };
    }
    if let Some(imgh) = <BD::Pixel as Pixel>::try_as_u16_slice(img) {
        return unsafe { (exec.cdef_dir_hbd)(imgh, stride, bd.bitdepth_min_8(), var) };
    }

    unreachable!("unsupported CDEF pixel storage")
}

pub(crate) fn adjust_strength(strength: i32, var: u32) -> i32 {
    if var == 0 {
        return 0;
    }
    let i = if var >> 6 != 0 {
        imin(ulog2(var >> 6), 12)
    } else {
        0
    };
    (strength * (4 + i) + 8) >> 4
}

pub(crate) const BACKUP_2X8_Y: u8 = 1 << 0;
pub(crate) const BACKUP_2X8_UV: u8 = 1 << 1;

#[allow(clippy::too_many_arguments)]
pub(crate) fn cdef_filter_block<BD: BitDepth>(
    bd: BD,
    exec: &crate::exec_context::ExecContext,
    dst: &mut [BD::Pixel],
    dst_stride: usize,
    dst_off: usize,
    left: &[[BD::Pixel; 2]],
    top: &[BD::Pixel],
    top_off: usize,
    bottom: &[BD::Pixel],
    bottom_off: usize,
    bottom_stride: usize,
    pri_strength: i32,
    sec_strength: i32,
    dir: usize,
    damping: i32,
    w: usize,
    h: usize,
    edges: u8,
) {
    let tmp_stride: usize = 12;
    let mut tmp_buf = [0i16; 144];
    let o = 2 * tmp_stride + 2;

    let bitdepth_min_8 = bd.bitdepth_min_8();

    if BD::BPC == 8 {
        if let (Some(src8), Some(top8), Some(bottom8)) = (
            <BD::Pixel as Pixel>::try_as_u8_slice(&*dst),
            <BD::Pixel as Pixel>::try_as_u8_slice(top),
            <BD::Pixel as Pixel>::try_as_u8_slice(bottom),
        ) {
            unsafe {
                (exec.cdef_padding_8bpc)(
                    &mut tmp_buf,
                    tmp_stride,
                    src8,
                    dst_stride,
                    dst_off,
                    cast_left_u8(left),
                    top8,
                    top_off,
                    bottom8,
                    bottom_off,
                    bottom_stride,
                    w,
                    h,
                    edges,
                );
            }
            let d8 = <BD::Pixel as Pixel>::try_as_u8_slice_mut(dst)
                .expect("8-bit CDEF storage changed between padding and filter");
            let pri_tap = if pri_strength != 0 {
                4 - ((pri_strength >> bitdepth_min_8) & 1)
            } else {
                0
            };
            let pri_shift = if pri_strength != 0 {
                imax(0, damping - ulog2(pri_strength as u32))
            } else {
                0
            };
            let sec_shift = if sec_strength != 0 {
                damping - ulog2(sec_strength as u32)
            } else {
                0
            };
            if pri_strength != 0 || sec_strength != 0 {
                let shape = match (w, h) {
                    (8, 8) => Some(0),
                    (4, 8) => Some(1),
                    (4, 4) => Some(2),
                    (8, 4) => Some(3),
                    _ => None,
                };
                if let Some(shape) = shape {
                    unsafe {
                        (exec.cdef_filter_shapes[shape])(
                            d8,
                            dst_stride,
                            dst_off,
                            &tmp_buf,
                            tmp_stride,
                            o,
                            pri_strength,
                            sec_strength,
                            pri_shift,
                            sec_shift,
                            pri_tap,
                            dir,
                        )
                    };
                } else {
                    unsafe {
                        (exec.cdef_filter)(
                            d8,
                            dst_stride,
                            dst_off,
                            &tmp_buf,
                            tmp_stride,
                            o,
                            pri_strength,
                            sec_strength,
                            pri_shift,
                            sec_shift,
                            pri_tap,
                            dir,
                            w,
                            h,
                        )
                    };
                }
            }
            return;
        }
    }

    if BD::BPC == 16 {
        if let (Some(src16), Some(top16), Some(bottom16)) = (
            <BD::Pixel as Pixel>::try_as_u16_slice(&*dst),
            <BD::Pixel as Pixel>::try_as_u16_slice(top),
            <BD::Pixel as Pixel>::try_as_u16_slice(bottom),
        ) {
            unsafe {
                (exec.cdef_padding_hbd)(
                    &mut tmp_buf,
                    tmp_stride,
                    src16,
                    dst_stride,
                    dst_off,
                    cast_left_u16(left),
                    top16,
                    top_off,
                    bottom16,
                    bottom_off,
                    bottom_stride,
                    w,
                    h,
                    edges,
                );
            }
            let d16 = <BD::Pixel as Pixel>::try_as_u16_slice_mut(dst)
                .expect("HBD CDEF storage changed between padding and filter");
            let pri_tap = if pri_strength != 0 {
                4 - ((pri_strength >> bitdepth_min_8) & 1)
            } else {
                0
            };
            let pri_shift = if pri_strength != 0 {
                imax(0, damping - ulog2(pri_strength as u32))
            } else {
                0
            };
            let sec_shift = if sec_strength != 0 {
                damping - ulog2(sec_strength as u32)
            } else {
                0
            };
            if pri_strength != 0 || sec_strength != 0 {
                let shape = match (w, h) {
                    (8, 8) => Some(0),
                    (4, 8) => Some(1),
                    (4, 4) => Some(2),
                    (8, 4) => Some(3),
                    _ => None,
                };
                if let Some(shape) = shape {
                    unsafe {
                        (exec.cdef_filter_hbd_shapes[shape])(
                            d16,
                            dst_stride,
                            dst_off,
                            &tmp_buf,
                            tmp_stride,
                            o,
                            pri_strength,
                            sec_strength,
                            pri_shift,
                            sec_shift,
                            pri_tap,
                            dir,
                        )
                    };
                } else {
                    unsafe {
                        (exec.cdef_filter_hbd)(
                            d16,
                            dst_stride,
                            dst_off,
                            &tmp_buf,
                            tmp_stride,
                            o,
                            pri_strength,
                            sec_strength,
                            pri_shift,
                            sec_shift,
                            pri_tap,
                            dir,
                            w,
                            h,
                        )
                    };
                }
            }
            return;
        }
    }

    cdef_padding(
        bd,
        &mut tmp_buf,
        tmp_stride,
        &*dst,
        dst_stride,
        dst_off,
        left,
        top,
        top_off,
        bottom,
        bottom_off,
        bottom_stride,
        w,
        h,
        edges,
    );

    let mut dp = dst_off;
    let mut tp = o;

    if pri_strength != 0 {
        let pri_tap = 4 - ((pri_strength >> bitdepth_min_8) & 1);
        let pri_shift = imax(0, damping - ulog2(pri_strength as u32));
        if sec_strength != 0 {
            let sec_shift = damping - ulog2(sec_strength as u32);
            for _y in 0..h {
                for x in 0..w {
                    let px = Into::<i32>::into(dst[dp + x]);
                    let mut sum = 0i32;
                    let mut max_v = px;
                    let mut min_v = px;
                    let mut pri_tap_k = pri_tap;
                    for k in 0..2 {
                        let off1 = CDEF_DIRECTIONS[dir + 2][k] as isize;
                        let p0 = tmp_buf[((tp + x) as isize + off1) as usize] as i32;
                        let p1 = tmp_buf[((tp + x) as isize - off1) as usize] as i32;
                        sum += pri_tap_k * constrain(p0 - px, pri_strength, pri_shift);
                        sum += pri_tap_k * constrain(p1 - px, pri_strength, pri_shift);
                        pri_tap_k = (pri_tap_k & 3) | 2;
                        min_v = imin(p0, min_v);
                        max_v = imax(p0, max_v);
                        min_v = imin(p1, min_v);
                        max_v = imax(p1, max_v);
                        let off2 = CDEF_DIRECTIONS[dir + 4][k] as isize;
                        let off3 = CDEF_DIRECTIONS[dir][k] as isize;
                        let s0 = tmp_buf[((tp + x) as isize + off2) as usize] as i32;
                        let s1 = tmp_buf[((tp + x) as isize - off2) as usize] as i32;
                        let s2 = tmp_buf[((tp + x) as isize + off3) as usize] as i32;
                        let s3 = tmp_buf[((tp + x) as isize - off3) as usize] as i32;
                        let sec_tap = 2 - k as i32;
                        sum += sec_tap * constrain(s0 - px, sec_strength, sec_shift);
                        sum += sec_tap * constrain(s1 - px, sec_strength, sec_shift);
                        sum += sec_tap * constrain(s2 - px, sec_strength, sec_shift);
                        sum += sec_tap * constrain(s3 - px, sec_strength, sec_shift);
                        min_v = imin(s0, min_v);
                        max_v = imax(s0, max_v);
                        min_v = imin(s1, min_v);
                        max_v = imax(s1, max_v);
                        min_v = imin(s2, min_v);
                        max_v = imax(s2, max_v);
                        min_v = imin(s3, min_v);
                        max_v = imax(s3, max_v);
                    }
                    dst[dp + x] = BD::Pixel::from_i32(iclip(
                        px + ((sum - (sum < 0) as i32 + 8) >> 4),
                        min_v,
                        max_v,
                    ));
                }
                dp += dst_stride;
                tp += tmp_stride;
            }
        } else {
            for _y in 0..h {
                for x in 0..w {
                    let px = Into::<i32>::into(dst[dp + x]);
                    let mut sum = 0i32;
                    let mut pri_tap_k = pri_tap;
                    for k in 0..2 {
                        let off = CDEF_DIRECTIONS[dir + 2][k] as isize;
                        let p0 = tmp_buf[((tp + x) as isize + off) as usize] as i32;
                        let p1 = tmp_buf[((tp + x) as isize - off) as usize] as i32;
                        sum += pri_tap_k * constrain(p0 - px, pri_strength, pri_shift);
                        sum += pri_tap_k * constrain(p1 - px, pri_strength, pri_shift);
                        pri_tap_k = (pri_tap_k & 3) | 2;
                    }
                    dst[dp + x] = BD::Pixel::from_i32(px + ((sum - (sum < 0) as i32 + 8) >> 4));
                }
                dp += dst_stride;
                tp += tmp_stride;
            }
        }
    } else {
        let sec_shift = damping - ulog2(sec_strength as u32);
        for _y in 0..h {
            for x in 0..w {
                let px = Into::<i32>::into(dst[dp + x]);
                let mut sum = 0i32;
                for k in 0..2 {
                    let off1 = CDEF_DIRECTIONS[dir + 4][k] as isize;
                    let off2 = CDEF_DIRECTIONS[dir][k] as isize;
                    let s0 = tmp_buf[((tp + x) as isize + off1) as usize] as i32;
                    let s1 = tmp_buf[((tp + x) as isize - off1) as usize] as i32;
                    let s2 = tmp_buf[((tp + x) as isize + off2) as usize] as i32;
                    let s3 = tmp_buf[((tp + x) as isize - off2) as usize] as i32;
                    let sec_tap = 2 - k as i32;
                    sum += sec_tap * constrain(s0 - px, sec_strength, sec_shift);
                    sum += sec_tap * constrain(s1 - px, sec_strength, sec_shift);
                    sum += sec_tap * constrain(s2 - px, sec_strength, sec_shift);
                    sum += sec_tap * constrain(s3 - px, sec_strength, sec_shift);
                }
                dst[dp + x] = BD::Pixel::from_i32(px + ((sum - (sum < 0) as i32 + 8) >> 4));
            }
            dp += dst_stride;
            tp += tmp_stride;
        }
    }
}
/// Per-superblock-row CDEF parameters threaded from the filter driver.
/// Per-plane CCSO configuration (cross-component sample offset), from the frame
/// header's `ccso.p[pl]`. `quant_step` and `offset_lut` are resolved from the
/// scale/quant indices.
#[derive(Clone, Copy)]
pub(crate) struct CcsoPlaneCfg {
    pub(crate) max_band_log2: u32,
    pub(crate) ext_filter: usize,
    pub(crate) quant_step: i32,
    pub(crate) edge_clf: u32,
    pub(crate) bo_only: bool,
    pub(crate) scale_idx: usize,
    pub(crate) filter_off: [u8; 64],
}

/// CCSO configuration for a CDEF brow. Per-SB enable flags live in
/// `CdefBrowParams::mask`; this struct only carries the resolved header config.
pub(crate) struct CcsoCfg {
    pub(crate) p: [CcsoPlaneCfg; 3],
}

/// Interior tile seams that CDEF must not filter across
/// (`disable_loopfilters_across_tiles`). AVM's `cdef_prepare_fb` pads a tile
/// edge with `CDEF_VERY_LARGE` exactly like a frame edge, so a block touching a
/// seam loses the corresponding `CDEF_HAVE_*` flag. Starts are in superblocks.
#[derive(Clone, Copy)]
pub(crate) struct CdefTileEdges<'a> {
    /// `col_start_sb[1..cols]`: interior tile column starts.
    pub(crate) col_start_sb: &'a [u16],
    /// `row_start_sb[1..rows]`: interior tile row starts.
    pub(crate) row_start_sb: &'a [u16],
    /// Superblock size in 4px units (`16 << sb128`).
    pub(crate) sb_step: i32,
}

impl CdefTileEdges<'_> {
    #[inline]
    fn is_seam(starts: &[u16], sb_step: i32, pos_b4: i32) -> bool {
        pos_b4 % sb_step == 0 && starts.iter().any(|&s| s as i32 * sb_step == pos_b4)
    }

    /// `CDEF_HAVE_TOP`/`CDEF_HAVE_BOTTOM` bits to clear for the 8px block row at `by`.
    #[inline]
    fn row_mask(&self, by: i32) -> u8 {
        let mut m = 0;
        if Self::is_seam(self.row_start_sb, self.sb_step, by) {
            m |= CDEF_HAVE_TOP;
        }
        if Self::is_seam(self.row_start_sb, self.sb_step, by + 2) {
            m |= CDEF_HAVE_BOTTOM;
        }
        m
    }

    /// `CDEF_HAVE_LEFT`/`CDEF_HAVE_RIGHT` bits to clear for the 8px block at `bx`.
    #[inline]
    fn col_mask(&self, bx: i32) -> u8 {
        let mut m = 0;
        if Self::is_seam(self.col_start_sb, self.sb_step, bx) {
            m |= CDEF_HAVE_LEFT;
        }
        if Self::is_seam(self.col_start_sb, self.sb_step, bx + 2) {
            m |= CDEF_HAVE_RIGHT;
        }
        m
    }
}

pub(crate) struct CdefBrowParams<'a> {
    pub(crate) bw: i32,
    pub(crate) bh: i32,
    pub(crate) damping: i32,
    pub(crate) layout: crate::headers::PixelLayout,
    pub(crate) on_skip_tx: bool,
    pub(crate) cdef_on: bool,
    /// Per-SB256 filter masks for this CDEF row. The row is borrowed directly
    /// from `lf.mask`; CDEF no longer allocates per-field row Vecs.
    pub(crate) mask: &'a [crate::lf_mask::Av2Filter],
    /// Per-cdef-index raw strengths (0..n_strengths) for Y and UV.
    pub(crate) y_strength: &'a [u8],
    pub(crate) uv_strength: &'a [u8],
    /// Per-SB256 lossless masks; CDEF (and CCSO) skip losslessly-coded blocks.
    /// `any_lossless` is false unless the frame is segmented with a lossless seg.
    pub(crate) any_lossless: bool,
    /// CCSO config; `None` when CCSO is disabled for this frame.
    pub(crate) ccso: Option<CcsoCfg>,
    /// Tile seams CDEF treats as frame edges; `None` when filtering across tiles.
    pub(crate) tile_edges: Option<CdefTileEdges<'a>>,
}

pub(crate) struct CdefPlaneSetMut<'a, P: Pixel> {
    pub(crate) y: &'a mut [P],
    pub(crate) u: &'a mut [P],
    pub(crate) v: &'a mut [P],
}

pub(crate) struct CdefBrowScratch<'a, P: Pixel> {
    pub(crate) cdef_line: &'a mut [[Vec<P>; 3]],
    pub(crate) cdef_top: &'a mut [[Vec<P>; 3]],
    pub(crate) toggle: &'a mut usize,
    pub(crate) ccso_tmp_buf: &'a mut Vec<P>,
}

#[derive(Clone, Copy)]
pub(crate) struct CdefBrowRange {
    pub(crate) by_start: i32,
    pub(crate) by_end: i32,
    pub(crate) sby: i32,
    pub(crate) sbrow_start: bool,
    pub(crate) phase: u8,
}

impl<'a> CdefBrowParams<'a> {
    #[inline(always)]
    fn mask_at(&self, sb256x: usize) -> Option<&crate::lf_mask::Av2Filter> {
        self.mask.get(sb256x)
    }

    #[inline(always)]
    fn cdef_idx(&self, sb256x: usize, sb64_idx: usize) -> i8 {
        self.mask_at(sb256x)
            .map(|m| m.cdef_idx[sb64_idx])
            .unwrap_or(-1)
    }

    #[inline(always)]
    fn ccso_mask(&self, sb256x: usize, sbx: i32, by: i32) -> [u8; 3] {
        // `ccso_sb` holds one flag set per 64px slot of the 256px region (the
        // reader splats each CCSO unit over the slots it covers), so pick the
        // slot of this 64px filter unit whatever the unit / SB size.
        let sub = (((by & 63) >> 4) * 4 + (sbx & 3)) as usize;
        match self.mask_at(sb256x) {
            Some(m) => [
                m.ccso_sb[sub * 3],
                m.ccso_sb[sub * 3 + 1],
                m.ccso_sb[sub * 3 + 2],
            ],
            None => [0; 3],
        }
    }

    #[inline(always)]
    fn noskip_mask(&self, sb256x: usize, by_idx: usize, sb64x_idx: usize) -> u16 {
        if self.on_skip_tx {
            !0u16
        } else {
            self.mask_at(sb256x)
                .filter(|_| by_idx < 32 && sb64x_idx < 4)
                .map(|m| m.noskip_mask[by_idx][sb64x_idx])
                .unwrap_or(0)
        }
    }

    #[inline(always)]
    fn lossless_y(&self, sb256x: usize) -> Option<&[[u16; 4]; 64]> {
        self.mask_at(sb256x).map(|m| &m.lossless_mask_y)
    }

    #[inline(always)]
    fn lossless_uv(&self, sb256x: usize) -> Option<&[[u16; 4]; 64]> {
        self.mask_at(sb256x).map(|m| &m.lossless_mask_uv)
    }
}

static UV_DIRS: [[u8; 8]; 2] = [[0, 1, 2, 3, 4, 5, 6, 7], [7, 0, 2, 4, 5, 6, 6, 6]];

/// Backup the bottom 2 rows of the current 8-row band into a toggled CDEF line
/// bank (each plane bank is laid out with the plane's positive stride spacing so
/// CDEF pass phases: SAVE backs up the seam lines (runs in the deblock pass),
/// FILTER applies CDEF reading those saved lines (the parallel CDEF pass). Fused
/// callers pass both.
pub(crate) const CDEF_SAVE: u8 = 1;
pub(crate) const CDEF_FILTER: u8 = 2;

/// Back up the pre-CDEF *top* 2 rows of a unit (rows 0,1) for every plane. These
/// serve as the saved "bottom border" of the unit above, so CDEF reads stable
/// seam pixels instead of the live, being-filtered next band.
fn cdef_backup2lines_top<P: Pixel>(
    bank: &mut [Vec<P>; 3],
    src_y: &[P],
    src_u: &[P],
    src_v: &[P],
    y_off: usize,
    uv_off: usize,
    y_stride: usize,
    uv_stride: usize,
    layout: crate::headers::PixelLayout,
) {
    let n = (2 * y_stride)
        .min(src_y.len().saturating_sub(y_off))
        .min(bank[0].len());
    bank[0][..n].copy_from_slice(&src_y[y_off..y_off + n]);
    if layout != crate::headers::PixelLayout::I400 {
        let n = (2 * uv_stride)
            .min(src_u.len().saturating_sub(uv_off))
            .min(bank[1].len());
        bank[1][..n].copy_from_slice(&src_u[uv_off..uv_off + n]);
        let n = (2 * uv_stride)
            .min(src_v.len().saturating_sub(uv_off))
            .min(bank[2].len());
        bank[2][..n].copy_from_slice(&src_v[uv_off..uv_off + n]);
    }
}

/// Select the saved pre-CDEF bottom reference for a block. Interior blocks can
/// read the full-width saved line directly; no compact 12-byte scratch copy is
/// needed. When HAVE_BOTTOM is clear, cdef_padding() will not inspect the slice.
#[inline(always)]
fn saved_bottom_ref<P: Pixel>(
    cdef_top: &[[Vec<P>; 3]],
    ru: usize,
    plane: usize,
    block_col: usize,
    stride: usize,
    edges: u8,
) -> (&[P], usize, usize) {
    if edges & CDEF_HAVE_BOTTOM != 0 {
        debug_assert!(ru + 1 < cdef_top.len());
        (&cdef_top[ru + 1][plane], block_col, stride)
    } else {
        (&[], 0, 1)
    }
}

fn cdef_backup2lines_bank<P: Pixel>(
    bank: &mut [Vec<P>; 3],
    src_y: &[P],
    src_u: &[P],
    src_v: &[P],
    y_off: usize,
    uv_off: usize,
    y_stride: usize,
    uv_stride: usize,
    layout: crate::headers::PixelLayout,
) {
    // Luma: copy rows 6,7 of the band (`src + 6*stride`, 2*stride bytes).
    let s = y_off + 6 * y_stride;
    let n = (2 * y_stride)
        .min(src_y.len().saturating_sub(s))
        .min(bank[0].len());
    bank[0][..n].copy_from_slice(&src_y[s..s + n]);

    if layout != crate::headers::PixelLayout::I400 {
        let uv_off_rows = if layout == crate::headers::PixelLayout::I420 {
            2
        } else {
            6
        };
        let s = uv_off + uv_off_rows * uv_stride;
        let n = (2 * uv_stride)
            .min(src_u.len().saturating_sub(s))
            .min(bank[1].len());
        bank[1][..n].copy_from_slice(&src_u[s..s + n]);
        let n = (2 * uv_stride)
            .min(src_v.len().saturating_sub(s))
            .min(bank[2].len());
        bank[2][..n].copy_from_slice(&src_v[s..s + n]);
    }
}

/// Backup a pre-CDEF 2x8 left-column block from a plane into `dst[8]`
fn cdef_backup2x8<P: Pixel>(
    dst: &mut [[P; 2]; 8],
    src: &[P],
    base: usize,
    stride: usize,
    x_off: usize,
    rows: usize,
) {
    let mut off = base;
    for d in dst.iter_mut().take(rows) {
        let s = off + x_off - 2;
        d[0] = src[s];
        d[1] = src[s + 1];
        off += stride;
    }
}

/// `have_tt == 0` path). `cdef_line` is the toggled top-row backup whose `tf`
/// bank holds the previous band's bottom 2 rows; `*toggle` flips per 8-row band.
pub(crate) fn cdef_brow_8bpc(
    exec: &crate::exec_context::ExecContext,
    planes: CdefPlaneSetMut<'_, u8>,
    p: &CdefBrowParams,
    strides: [isize; 2],
    scratch: CdefBrowScratch<'_, u8>,
    range: CdefBrowRange,
) {
    cdef_brow(BitDepth8, exec, planes, p, strides, scratch, range);
}

pub(crate) fn cdef_brow<BD: BitDepth>(
    bd: BD,
    exec: &crate::exec_context::ExecContext,
    planes: CdefPlaneSetMut<'_, BD::Pixel>,
    p: &CdefBrowParams,
    strides: [isize; 2],
    scratch: CdefBrowScratch<'_, BD::Pixel>,
    range: CdefBrowRange,
) {
    let CdefPlaneSetMut { y, u, v } = planes;
    let [y_stride, uv_stride] = strides;
    let CdefBrowScratch {
        cdef_line,
        cdef_top,
        toggle,
        ccso_tmp_buf,
    } = scratch;
    let CdefBrowRange {
        by_start,
        by_end,
        sby,
        sbrow_start,
        phase: cdef_phase,
    } = range;
    // `cdef_line` is a frame-level, per-8px-row seam buffer indexed by the global
    // row unit `by/2`: unit `t` stores its own pre-CDEF bottom 2 rows in slot `t`,
    // and reads its top seam from slot `t-1` (the previous unit's saved bottom).
    // This replaces the old 2-bank toggle so that a band filtered by any worker
    // reads stable neighbor seam pixels by absolute position rather than relying
    // on one stream's rolling buffer. `toggle` is retained as an unused parameter
    // for call-site compatibility during the staged refactor.
    let _ = &mut *toggle;
    let _ = sby;
    let bitdepth_min_8 = bd.bitdepth_min_8();
    let damping = p.damping + bitdepth_min_8;
    let y_ls = y_stride.unsigned_abs();
    let uv_ls = uv_stride.unsigned_abs();
    let layout = p.layout;
    let ss_hor = (layout != crate::headers::PixelLayout::I444) as usize;
    let ss_ver = (layout == crate::headers::PixelLayout::I420) as usize;
    let uv_dir = &UV_DIRS[(layout == crate::headers::PixelLayout::I422) as usize];
    let sbsz = 16i32;
    let sb64w = (p.bw + sbsz - 1) >> 4;
    let have_chroma = layout != crate::headers::PixelLayout::I400;

    // Save pass: back up every unit's pre-CDEF bottom 2 rows before any CDEF
    // write in this band, so the filter pass below reads stable seam lines by
    // absolute row index. Separating save from filter is the prerequisite for
    // hoisting this into the deblock pass (where parallel CDEF will read it).
    if cdef_phase & CDEF_SAVE != 0 {
        let mut sby = by_start;
        let mut srs_y = by_start as usize * 4 * y_ls;
        let mut srs_uv = ((by_start as usize * 4) >> ss_ver) * uv_ls;
        // Save one unit past by_end so the last filtered unit's bottom border
        // (`cdef_top[ru+1]`) is available. `cdef_line[ru]` = unit ru's bottom 2
        // rows (top seam for unit below); `cdef_top[ru]` = unit ru's top 2 rows
        // (bottom seam for unit above). Both pre-CDEF.
        while sby <= by_end {
            let sru = (sby / 2) as usize;
            // Skip this band's OWN first unit: cdef_top[first_ru] is the bottom
            // border read only by the band ABOVE, and was already saved by that
            // band's "one-past" save at state post-deblock(k-1). Re-saving it here
            // (post-deblock(k)) would clobber the value the band above must read
            // once deblock and CDEF run as separate passes. CDEF for this band
            // reads cdef_top[ru+1] for ru in [first_ru..], i.e. [first_ru+1 ..
            // first_ru+8], so it never needs cdef_top[first_ru] itself.
            if sby > by_start && sby < p.bh {
                cdef_backup2lines_top(
                    &mut cdef_top[sru],
                    y,
                    u,
                    v,
                    srs_y,
                    srs_uv,
                    y_ls,
                    uv_ls,
                    layout,
                );
            }
            if sby < by_end && sby + 2 < p.bh {
                cdef_backup2lines_bank(
                    &mut cdef_line[sru],
                    y,
                    u,
                    v,
                    srs_y,
                    srs_uv,
                    y_ls,
                    uv_ls,
                    layout,
                );
            }
            srs_y += 8 * y_ls;
            srs_uv += (8 * uv_ls) >> ss_ver;
            sby += 2;
        }
    }

    if cdef_phase & CDEF_FILTER != 0 {
        // Plane base offset of the band's first row.
        let mut row_y = by_start as usize * 4 * y_ls;
        let mut row_uv = ((by_start as usize * 4) >> ss_ver) * uv_ls;
        let mut edge_top = if by_start > 0 { CDEF_HAVE_TOP } else { 0 };

        let mut by = by_start;
        while by < by_end {
            let ru = (by / 2) as usize;
            let ru_prev = ru.saturating_sub(1); // previous unit's saved bottom (top seam)
            let by_idx = ((by & 0x3e) >> 1) as usize;
            let mut edges = edge_top | CDEF_HAVE_BOTTOM;
            if by + 2 >= p.bh {
                edges &= !CDEF_HAVE_BOTTOM;
            }
            // Tile seams only narrow what the CDEF kernels may read; `edges`
            // itself keeps driving the 2x8 backups and CCSO, whose tile-edge
            // handling differs (AVM replicates the tile border for CCSO).
            let tile_row_mask = p.tile_edges.map_or(0, |t| t.row_mask(by));

            let _ = (sbrow_start, by_end);

            // Left 2x8 backups (toggled `bit`), one per plane, pre-CDEF.
            let mut lr_bak: [[[[BD::Pixel; 2]; 8]; 3]; 2] =
                [[[[BD::Pixel::default(); 2]; 8]; 3]; 2];
            let mut bit = 0usize;
            edges &= !CDEF_HAVE_LEFT;
            edges |= CDEF_HAVE_RIGHT;
            // the next SB's first block can reuse / skip the left-column backup.
            let mut prev_flag = 0u8;

            // Per-sb base offsets that advance with iptrs.
            let mut sb_y = row_y;
            let mut sb_uv = row_uv;

            // CCSO LUT-index scratch (per-SB, recomputed each sbx).  Keep the
            // zeroing out of the common no-CCSO path; most still-image CDEF
            // benchmarks should not pay a 1536-byte memset per SB row when CCSO
            // is disabled.
            let mut ccso_lut_idx = if p.ccso.is_some() {
                Some([[0u8; 64 * 8]; 3])
            } else {
                None
            };

            for sbx in 0..sb64w {
                let sb256x = (sbx >> 2) as usize;
                let sb64x_idx = (sbx & 3) as usize;
                let sb64_idx = (((by & 0x30) >> 2) + (sbx & 3)) as usize;
                let cdef_idx = p.cdef_idx(sb256x, sb64_idx);

                if let Some(cc) = &p.ccso {
                    let ccso_lut_idx = ccso_lut_idx
                        .as_mut()
                        .expect("CCSO scratch is allocated when CCSO is enabled");
                    let ccm = p.ccso_mask(sb256x, sbx, by);
                    let flag = ccm[0] | ccm[1] | ccm[2];
                    let do_left = flag & !prev_flag;
                    prev_flag |= flag;
                    if do_left != 0 && (edges & CDEF_HAVE_LEFT) != 0 {
                        if do_left & BACKUP_2X8_Y != 0 {
                            cdef_backup2x8(&mut lr_bak[bit][0], y, sb_y, y_ls, 0, 8);
                        }
                        if have_chroma && do_left & BACKUP_2X8_UV != 0 {
                            cdef_backup2x8(&mut lr_bak[bit][1], u, sb_uv, uv_ls, 0, 8 >> ss_ver);
                            cdef_backup2x8(&mut lr_bak[bit][2], v, sb_uv, uv_ls, 0, 8 >> ss_ver);
                        }
                    }
                    for pl in 0..3 {
                        if ccm[pl] == 0 {
                            continue;
                        }
                        let cfg = &cc.p[pl];
                        let pl_ss_hor = if pl != 0 { ss_hor } else { 0 };
                        let pl_ss_ver = if pl != 0 { ss_ver } else { 0 };
                        let mut sb_edges = edges;
                        if (sbx + 1) * sbsz >= p.bw {
                            sb_edges &= !CDEF_HAVE_RIGHT;
                        }
                        let w_full = imin(sbsz, p.bw - sbx * sbsz) * 4;
                        if w_full <= 0 {
                            continue;
                        }
                        // top/bottom luma lines. Bottom must come from the SAVED
                        // pre-CDEF edge, NOT the live plane: with data-parallel CDEF
                        // filtering, the next band's seam writes the rows just below
                        // this SB, so a live read there would race. When HAVE_BOTTOM
                        // is clear, ccso_padding never reads the bottom slice.
                        let top_off = sbx as usize * (sbsz as usize) * 4;
                        let (bottom, bottom_off, _) =
                            saved_bottom_ref(cdef_top, ru, 0, top_off, y_ls, sb_edges);
                        ccso_prep(
                            bd,
                            CcsoPrepCtx {
                                dst: &mut ccso_lut_idx[pl][..],
                                dst_stride: 64 >> pl_ss_hor,
                                src: CcsoPrepSrc {
                                    src: y,
                                    stride: y_ls,
                                    off: sb_y,
                                    left: &lr_bak[bit][0],
                                    top: &cdef_line[ru_prev][0],
                                    top_off,
                                    bottom,
                                    bottom_off,
                                },
                                tmp_buf: ccso_tmp_buf,
                                cfg: CcsoPrepCfg {
                                    max_band_log2: cfg.max_band_log2,
                                    ext_filter: cfg.ext_filter,
                                    quant_step: cfg.quant_step,
                                    edge_clf: cfg.edge_clf,
                                    bo_only: cfg.bo_only,
                                },
                                area: CcsoPrepArea {
                                    edges: sb_edges,
                                    w: (w_full >> pl_ss_hor) as usize,
                                    h: (8 >> pl_ss_ver) as usize,
                                    ss_hor: pl_ss_hor,
                                    ss_ver: pl_ss_ver,
                                },
                            },
                        );
                    }
                }

                let cdef_active = !(cdef_idx == -1
                    || !p.cdef_on
                    || ((p
                        .y_strength
                        .get(cdef_idx.max(0) as usize)
                        .copied()
                        .unwrap_or(0)
                        == 0)
                        && (p
                            .uv_strength
                            .get(cdef_idx.max(0) as usize)
                            .copied()
                            .unwrap_or(0)
                            == 0)));

                if cdef_active {
                    let noskip_full = p.noskip_mask(sb256x, by_idx, sb64x_idx);

                    let y_lvl = p.y_strength[cdef_idx as usize] as i32;
                    let uv_lvl = p.uv_strength[cdef_idx as usize] as i32;
                    let flag = (y_lvl != 0) as u8 + (((uv_lvl != 0) as u8) << 1);

                    let y_pri_lvl = (y_lvl >> 2) << bitdepth_min_8;
                    let mut y_sec_lvl = y_lvl & 3;
                    y_sec_lvl += (y_sec_lvl == 3) as i32;
                    y_sec_lvl <<= bitdepth_min_8;

                    let uv_pri_lvl = (uv_lvl >> 2) << bitdepth_min_8;
                    let mut uv_sec_lvl = uv_lvl & 3;
                    uv_sec_lvl += (uv_sec_lvl == 3) as i32;
                    uv_sec_lvl <<= bitdepth_min_8;

                    // adjacent 4px rows at column sb64x_idx for luma, subsampled for uv.
                    // Zero unless the frame is segmented-lossless.
                    let (y_ll0, y_ll1, uv_ll0, uv_ll1) = if p.any_lossless {
                        let yr = (2 * by_idx).min(63);
                        let yl = p.lossless_y(sb256x);
                        let ul = p.lossless_uv(sb256x);
                        let y0 = yl.map(|m| m[yr][sb64x_idx]).unwrap_or(0);
                        let y1 = yl.map(|m| m[(yr + 1).min(63)][sb64x_idx]).unwrap_or(0);
                        let uvr = ((2 * by_idx) >> ss_ver).min(63);
                        let u0 = ul.map(|m| m[uvr][sb64x_idx]).unwrap_or(0);
                        let u1 = ul
                            .map(|m| m[(uvr + (1 - ss_ver)).min(63)][sb64x_idx])
                            .unwrap_or(0);
                        (y0, y1, u0, u1)
                    } else {
                        (0, 0, 0, 0)
                    };

                    let mut b_y = sb_y;
                    let mut b_uv = sb_uv;
                    let mut bx = sbx * sbsz;
                    let sb_bx_end = imin((sbx + 1) * sbsz, p.bw);
                    while bx < sb_bx_end {
                        if bx + 2 >= p.bw {
                            edges &= !CDEF_HAVE_RIGHT;
                        }

                        let bx_mask = 3u16 << (bx & 14);
                        let y_lossless = ((y_ll0 | y_ll1) & bx_mask) != 0;
                        let uvbx_mask = (3u16 >> ss_hor) << ((bx & 14) >> ss_hor);
                        let uv_lossless = ((uv_ll0 | uv_ll1) & uvbx_mask) != 0;
                        if (noskip_full & bx_mask) == 0 || (y_lossless && uv_lossless) {
                            prev_flag = 0;
                            edges |= CDEF_HAVE_LEFT;
                            b_y += 8;
                            b_uv += 8 >> ss_hor;
                            bx += 2;
                            continue;
                        }

                        let do_left = flag & !prev_flag;
                        prev_flag = flag;
                        if do_left != 0 && (edges & CDEF_HAVE_LEFT) != 0 {
                            if do_left & BACKUP_2X8_Y != 0 {
                                cdef_backup2x8(&mut lr_bak[bit][0], y, b_y, y_ls, 0, 8);
                            }
                            if have_chroma && do_left & BACKUP_2X8_UV != 0 {
                                cdef_backup2x8(&mut lr_bak[bit][1], u, b_uv, uv_ls, 0, 8 >> ss_ver);
                                cdef_backup2x8(&mut lr_bak[bit][2], v, b_uv, uv_ls, 0, 8 >> ss_ver);
                            }
                        }
                        if (edges & CDEF_HAVE_RIGHT) != 0 {
                            let other = 1 - bit;
                            if flag & BACKUP_2X8_Y != 0 {
                                cdef_backup2x8(&mut lr_bak[other][0], y, b_y, y_ls, 8, 8);
                            }
                            if have_chroma && flag & BACKUP_2X8_UV != 0 {
                                cdef_backup2x8(
                                    &mut lr_bak[other][1],
                                    u,
                                    b_uv,
                                    uv_ls,
                                    8 >> ss_hor,
                                    8 >> ss_ver,
                                );
                                cdef_backup2x8(
                                    &mut lr_bak[other][2],
                                    v,
                                    b_uv,
                                    uv_ls,
                                    8 >> ss_hor,
                                    8 >> ss_ver,
                                );
                            }
                        }

                        let fedges =
                            edges & !(tile_row_mask | p.tile_edges.map_or(0, |t| t.col_mask(bx)));

                        let y_filter_active = !y_lossless && (y_pri_lvl != 0 || y_sec_lvl != 0);
                        let uv_filter_active = uv_lvl != 0 && have_chroma && !uv_lossless;
                        let need_dir = (y_pri_lvl != 0 && y_filter_active)
                            || (uv_pri_lvl != 0 && uv_filter_active);

                        let mut variance = 0u32;
                        let dir = if need_dir {
                            cdef_find_dir_bd(bd, exec, &y[b_y..], y_ls, &mut variance) as usize
                        } else {
                            0
                        };

                        // Luma top/bottom: both are saved pre-CDEF seam rows.  Pass
                        // the full-width bottom line directly, dav1d-style, instead of
                        // copying a compact per-block scratch buffer.
                        let top_col = bx as usize * 4;
                        if y_pri_lvl != 0 {
                            let adj = adjust_strength(y_pri_lvl, variance);
                            if y_filter_active && (adj != 0 || y_sec_lvl != 0) {
                                let (y_bottom, y_bottom_off, y_bottom_stride) =
                                    saved_bottom_ref(cdef_top, ru, 0, top_col, y_ls, fedges);
                                cdef_filter_block(
                                    bd,
                                    exec,
                                    y,
                                    y_ls,
                                    b_y,
                                    &lr_bak[bit][0],
                                    &cdef_line[ru_prev][0],
                                    top_col,
                                    y_bottom,
                                    y_bottom_off,
                                    y_bottom_stride,
                                    adj,
                                    y_sec_lvl,
                                    dir,
                                    damping,
                                    8,
                                    8,
                                    fedges,
                                );
                            }
                        } else if y_filter_active {
                            let (y_bottom, y_bottom_off, y_bottom_stride) =
                                saved_bottom_ref(cdef_top, ru, 0, top_col, y_ls, fedges);
                            cdef_filter_block(
                                bd,
                                exec,
                                y,
                                y_ls,
                                b_y,
                                &lr_bak[bit][0],
                                &cdef_line[ru_prev][0],
                                top_col,
                                y_bottom,
                                y_bottom_off,
                                y_bottom_stride,
                                0,
                                y_sec_lvl,
                                0,
                                damping,
                                8,
                                8,
                                fedges,
                            );
                        }

                        if uv_filter_active {
                            let uvdir = if uv_pri_lvl != 0 {
                                uv_dir[dir] as usize
                            } else {
                                0
                            };
                            let cw = 8 >> ss_hor;
                            let ch = 8 >> ss_ver;
                            let top_col_uv = (bx as usize * 4) >> ss_hor;
                            let (u_bottom, u_bottom_off, u_bottom_stride) =
                                saved_bottom_ref(cdef_top, ru, 1, top_col_uv, uv_ls, fedges);
                            let (v_bottom, v_bottom_off, v_bottom_stride) =
                                saved_bottom_ref(cdef_top, ru, 2, top_col_uv, uv_ls, fedges);
                            cdef_filter_block(
                                bd,
                                exec,
                                u,
                                uv_ls,
                                b_uv,
                                &lr_bak[bit][1],
                                &cdef_line[ru_prev][1],
                                top_col_uv,
                                u_bottom,
                                u_bottom_off,
                                u_bottom_stride,
                                uv_pri_lvl,
                                uv_sec_lvl,
                                uvdir,
                                damping - 1,
                                cw,
                                ch,
                                fedges,
                            );
                            cdef_filter_block(
                                bd,
                                exec,
                                v,
                                uv_ls,
                                b_uv,
                                &lr_bak[bit][2],
                                &cdef_line[ru_prev][2],
                                top_col_uv,
                                v_bottom,
                                v_bottom_off,
                                v_bottom_stride,
                                uv_pri_lvl,
                                uv_sec_lvl,
                                uvdir,
                                damping - 1,
                                cw,
                                ch,
                                fedges,
                            );
                        }

                        bit ^= 1;
                        edges |= CDEF_HAVE_LEFT;
                        b_y += 8;
                        b_uv += 8 >> ss_hor;
                        bx += 2;
                    }
                } else {
                    // prev_flag); CCSO add still runs below.
                    prev_flag = 0;
                    edges |= CDEF_HAVE_LEFT;
                }

                if let Some(cc) = &p.ccso {
                    let ccso_lut_idx = ccso_lut_idx
                        .as_ref()
                        .expect("CCSO scratch is allocated when CCSO is enabled");
                    let ccm = p.ccso_mask(sb256x, sbx, by);
                    let flag = ccm[0] | ((ccm[1] | ccm[2]) << 1);
                    let do_right = flag & !prev_flag;
                    if do_right != 0 && (sbx + 1) * sbsz < p.bw {
                        if do_right & BACKUP_2X8_Y != 0 {
                            cdef_backup2x8(
                                &mut lr_bak[bit][0],
                                y,
                                sb_y,
                                y_ls,
                                sbsz as usize * 4,
                                8,
                            );
                        }
                        if have_chroma && do_right & BACKUP_2X8_UV != 0 {
                            cdef_backup2x8(
                                &mut lr_bak[bit][1],
                                u,
                                sb_uv,
                                uv_ls,
                                (sbsz as usize * 4) >> ss_hor,
                                8 >> ss_ver,
                            );
                            cdef_backup2x8(
                                &mut lr_bak[bit][2],
                                v,
                                sb_uv,
                                uv_ls,
                                (sbsz as usize * 4) >> ss_hor,
                                8 >> ss_ver,
                            );
                        }
                        prev_flag |= do_right;
                    }
                    // lossless masks for the add (zero for non-segmented-lossless).
                    let by_idx_ll = (2 * by_idx) as usize;
                    for pl in 0..3 {
                        if ccm[pl] == 0 {
                            continue;
                        }
                        let cfg = &cc.p[pl];
                        let pl_ss_hor = if pl != 0 { ss_hor } else { 0 };
                        let pl_ss_ver = if pl != 0 { ss_ver } else { 0 };
                        let w_full = imin(sbsz, p.bw - sbx * sbsz) * 4;
                        let (dst, dst_off, dst_ls): (&mut [BD::Pixel], usize, usize) = if pl == 0 {
                            (y, sb_y, y_ls)
                        } else if pl == 1 {
                            (u, sb_uv, uv_ls)
                        } else {
                            (v, sb_uv, uv_ls)
                        };
                        // sb64x_idx] and the kernel reads [yy>>2][0]. Build a per-row
                        // view whose column 0 is the sb64x_idx column (all-zero unless
                        // segmented-lossless). 2 rows (8px) cover one CCSO band.
                        let mut ll_buf = [[0u16; 4]; 2];
                        if p.any_lossless {
                            let src = if pl == 0 {
                                p.lossless_y(sb256x)
                            } else {
                                p.lossless_uv(sb256x)
                            };
                            if let Some(m) = src {
                                let base = by_idx_ll >> pl_ss_ver;
                                for (r, slot) in ll_buf.iter_mut().enumerate() {
                                    let row = base + r;
                                    if row < 64 {
                                        slot[0] = m[row][sb64x_idx];
                                    }
                                }
                            }
                        }
                        let ll: &[[u16; 4]] = &ll_buf;
                        ccso_add(
                            bd,
                            &mut dst[dst_off..],
                            dst_ls,
                            &ccso_lut_idx[pl],
                            (64 >> pl_ss_hor) as usize,
                            &cfg.filter_off,
                            &crate::tables::CCSO_OFFSET[cfg.scale_idx],
                            (w_full >> pl_ss_hor) as usize,
                            (8 >> pl_ss_ver) as usize,
                            ll,
                        );
                    }
                }

                sb_y += (sbsz * 4) as usize;
                sb_uv += ((sbsz * 4) as usize) >> ss_hor;
            }

            row_y += 8 * y_ls;
            row_uv += (8 * uv_ls) >> ss_ver;
            edge_top = CDEF_HAVE_TOP;
            let _ = by_idx;
            by += 2;
        }
    }
}