pixon 0.8.0

SIMD-dispatched color conversion for the FFmpeg AVPixelFormat space: one-call decode of validated source frames to RGB / RGBA / Luma / HSV, fused resampling while converting, colorimetry-honest matrices and chroma siting, no_std-friendly.
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
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
//! Chroma-siting-aware fused-downscale coverage for the HIGH-BIT **planar**
//! 4:2:0 YUV family — `Yuv420p9` … `Yuv420p16` (RFC #238 S6a), the `u16` twin of
//! the 8-bit `chroma_siting_420_resample` suite and the 4:2:0 sibling of the
//! high-bit `chroma_siting_hibit_422_resample` suite.
//!
//! 4:2:0 subsamples chroma 2:1 horizontally AND vertically. S6a routes the
//! HORIZONTAL centered siting (`Center` / `Top` / `Bottom`,
//! [`chroma_420_center_sited_h`](super::super::chroma_420_center_sited_h))
//! through the resample; the VERTICAL chroma pairing stays co-sited
//! (`v_phase = 0`, today's box — `Bottom`'s vertical blend is a later high-bit
//! stage):
//!  - the **native fast tier** (`with_native(true)`) folds the #302 `1/4`–`3/4`
//!    triangle into the [`ResamplePlan::area_chroma_420`] chroma weights and
//!    bins the SUBSAMPLED `u16` chroma directly — its code-domain twin is
//!    [`bin_chroma_centered_u16`] (a single round over the ×4 reconstruction,
//!    HORIZONTAL over `2·cw`, VERTICAL a co-sited box over the `ch` chroma rows);
//!  - the **encoded row-stage tier** (`with_native(false)`) and the
//!    **single-kernel filter tier** reconstruct full-width `u16` chroma per
//!    source row (each luma row `r` takes chroma row `r / 2`, horizontally
//!    upsampled) then convert-then-bin — pinned against a `Yuv444pN` resample of
//!    the independently reconstructed planes.
//!
//! The co-sited / unspecified group is phase 0 and stays byte-identical to the
//! pre-siting resample (the folded plan at phase 0 = the plain box). Both `u8`
//! and native-`u16` colour are exercised; the wire endianness (`BE`) is siting-
//! independent (decode normalizes before the phase math), pinned by the BE↔LE
//! parity test. Representative depths `p10` (low-packed) and `p16` (full u16)
//! cover the family; every centered assertion is an EXACT match (single
//! rounding), never a tolerance. Source heights are EVEN so the plan's
//! luma-domain `area_halved(sh, oh)` V axis equals the co-sited box over the
//! `ch = sh / 2` chroma rows.

use crate::{
  ChromaLocation, KernelMatrix, PixelSink,
  frame::*,
  resample::{AreaResampler, FilteredResampler, Triangle},
  sinker::{MixedSinker, MixedSinkerError},
  source::*,
};

const M: KernelMatrix = KernelMatrix::Bt601;
const FR: bool = true;

/// Round-half-up integer divide.
fn rdhu(a: u64, d: u64) -> u64 {
  let q = a / d;
  let r = a % d;
  q + u64::from(r >= d - d / 2)
}

/// Exact box-overlap area weights for `src -> out`, mirroring
/// `resample::AxisSpans::area`. Returns per output `(first source cell, overlaps)`.
fn area_weights(src: usize, out: usize) -> Vec<(usize, Vec<u64>)> {
  let (src64, out64) = (src as u64, out as u64);
  (0..out)
    .map(|o| {
      let lo = o as u64 * src64;
      let hi = lo + src64;
      let start = (lo / out64) as usize;
      let mut w = Vec::new();
      let mut i = start as u64;
      loop {
        let clo = i * out64;
        if clo >= hi {
          break;
        }
        let chi = clo + out64;
        let ov = chi.min(hi) - clo.max(lo);
        if ov == 0 {
          break;
        }
        w.push(ov);
        if chi >= hi {
          break;
        }
        i += 1;
      }
      (start, w)
    })
    .collect()
}

/// Co-sited box-average of a full-resolution `sw x sh` `u16` plane to `ow x oh`
/// (round-half-up) — the reference for a phase-free plane (luma, co-sited chroma).
fn bin_cosited_u16(plane: &[u16], sw: usize, sh: usize, ow: usize, oh: usize) -> Vec<u16> {
  let hw = area_weights(sw, ow);
  let vw = area_weights(sh, oh);
  let denom = (sw * sh) as u64;
  let mut out = vec![0u16; ow * oh];
  for (oy, (vs, vwin)) in vw.iter().enumerate() {
    for (ox, (hs, hwin)) in hw.iter().enumerate() {
      let mut s = 0u64;
      for (dy, &vwt) in vwin.iter().enumerate() {
        let mut hsum = 0u64;
        for (dx, &hwt) in hwin.iter().enumerate() {
          hsum += hwt * u64::from(plane[(vs + dy) * sw + hs + dx]);
        }
        s += vwt * hsum;
      }
      out[oy * ow + ox] = rdhu(s, denom) as u16;
    }
  }
  out
}

/// The EXACT centered chroma oracle (`u16`) for the native tier: reconstruct the
/// half-width `cw x ch` chroma to full width with the #302 `1/4`–`3/4` triangle
/// kept UNROUNDED (scaled ×4 to stay integral), then box-average to `ow x oh` —
/// HORIZONTAL over `2·cw`, VERTICAL a co-sited box over the `ch` chroma rows
/// (4:2:0 vertical stays co-sited) — with a SINGLE round-half-up over
/// `4·(2·cw)·ch`. The code-domain twin the folded
/// [`ResamplePlan::area_chroma_420`] weights realize (EVEN `sh`, `ch = sh / 2`,
/// where the plan's luma-domain `area_halved(sh, oh)` V axis is exactly `2·` the
/// box over `ch`, cancelled by its `src_h = sh`).
fn bin_chroma_centered_u16(c: &[u16], cw: usize, ch: usize, ow: usize, oh: usize) -> Vec<u16> {
  let full = 2 * cw;
  let mut r4 = vec![0u64; full * ch];
  for r in 0..ch {
    let row = &c[r * cw..r * cw + cw];
    for j in 0..cw {
      let l = u64::from(row[j.saturating_sub(1)]);
      let m = u64::from(row[j]);
      let rt = u64::from(row[if j + 1 < cw { j + 1 } else { j }]);
      r4[r * full + 2 * j] = l + 3 * m;
      r4[r * full + 2 * j + 1] = 3 * m + rt;
    }
  }
  let hw = area_weights(full, ow);
  let vw = area_weights(ch, oh);
  let denom = (4 * full * ch) as u64;
  let mut out = vec![0u16; ow * oh];
  for (oy, (vs, vwin)) in vw.iter().enumerate() {
    for (ox, (hs, hwin)) in hw.iter().enumerate() {
      let mut s = 0u64;
      for (dy, &vwt) in vwin.iter().enumerate() {
        let mut hsum = 0u64;
        for (dx, &hwt) in hwin.iter().enumerate() {
          hsum += hwt * r4[(vs + dy) * full + hs + dx];
        }
        s += vwt * hsum;
      }
      out[oy * ow + ox] = rdhu(s, denom) as u16;
    }
  }
  out
}

/// Independent #302 centered horizontal upsample (`1/4`–`3/4`, edge clamp,
/// round-half-up to `u16`) — the RGB-domain oracle's reconstruction step.
fn recon_full_row_u16(c: &[u16], cw: usize) -> Vec<u16> {
  let mut out = vec![0u16; 2 * cw];
  for j in 0..cw {
    let l = u32::from(c[j.saturating_sub(1)]);
    let m = u32::from(c[j]);
    let r = u32::from(c[if j + 1 < cw { j + 1 } else { j }]);
    out[2 * j] = ((l + 3 * m + 2) >> 2) as u16;
    out[2 * j + 1] = ((3 * m + r + 2) >> 2) as u16;
  }
  out
}

/// The EXACT top-sited (`v = 0`, FORWARD fold) chroma oracle for the native
/// tier: the centered horizontal `1/4`–`3/4` triangle (×4) composed with the
/// vertical `v = 0` triangle (×2 — even luma row `2i` takes chroma row `i` with
/// weight 2, odd row `2i + 1` box-blends chroma rows `{i, i + 1}` with weights
/// `{1, 1}` and a BOTTOM-edge clamp), the combined ×8 UNROUNDED reconstruction
/// box-averaged to `ow x oh` (VERTICAL over the `sh = 2·ch` luma-domain rows)
/// with a SINGLE round-half-up. The vertical mirror of the bottom-sited native
/// oracle / the `u16` twin of the 8-bit `bin_chroma_top`.
fn bin_chroma_top_u16(c: &[u16], cw: usize, ch: usize, ow: usize, oh: usize) -> Vec<u16> {
  let full = 2 * cw;
  let sh = 2 * ch;
  let mut r8 = vec![0u64; full * sh];
  for r in 0..sh {
    let cr = r / 2;
    let next = if cr + 1 < ch { cr + 1 } else { cr }; // bottom-edge clamp
    let vrow: Vec<u64> = (0..cw)
      .map(|j| {
        if r & 1 == 0 {
          2 * u64::from(c[cr * cw + j]) // even: {2} co-sited
        } else {
          u64::from(c[cr * cw + j]) + u64::from(c[next * cw + j]) // odd: {1, 1} forward
        }
      })
      .collect();
    for j in 0..cw {
      let l = vrow[j.saturating_sub(1)];
      let m = vrow[j];
      let rt = vrow[if j + 1 < cw { j + 1 } else { j }];
      r8[r * full + 2 * j] = l + 3 * m;
      r8[r * full + 2 * j + 1] = 3 * m + rt;
    }
  }
  let hw = area_weights(full, ow);
  let vw = area_weights(sh, oh);
  let denom = (8 * full * sh) as u64;
  let mut out = vec![0u16; ow * oh];
  for (oy, (vs, vwin)) in vw.iter().enumerate() {
    for (ox, (hs, hwin)) in hw.iter().enumerate() {
      let mut s = 0u64;
      for (dy, &vwt) in vwin.iter().enumerate() {
        let mut hsum = 0u64;
        for (dx, &hwt) in hwin.iter().enumerate() {
          hsum += hwt * r8[(vs + dy) * full + hs + dx];
        }
        s += vwt * hsum;
      }
      out[oy * ow + ox] = rdhu(s, denom) as u16;
    }
  }
  out
}

/// Reconstruct `Yuv420pN` chroma to full resolution (`sw x sh`) for the top-sited
/// (`v = 0`) decode — the identity forward-delay top kernel at source width: per
/// luma row the even rows take chroma row `i` co-sited, the odd rows FORWARD
/// box-blend chroma rows `i` and `i + 1` (round-half-up, bottom-edge clamp), each
/// then horizontally upsampled with the #302 centered `1/4`–`3/4` kernel. The
/// RGB-domain oracle's reconstruction step (mirror of the co-sited-vertical
/// reconstruction in [`rgb_domain_oracle`]).
fn recon_full_chroma_top_u16(u: &[u16], v: &[u16], sw: usize, sh: usize) -> (Vec<u16>, Vec<u16>) {
  let cw = sw / 2;
  let ch = sh.div_ceil(2);
  let vblend = |plane: &[u16], a: usize, b: usize| -> Vec<u16> {
    (0..cw)
      .map(|c| {
        let x = u32::from(plane[a * cw + c]);
        let z = u32::from(plane[b * cw + c]);
        ((x + z + 1) >> 1) as u16
      })
      .collect::<Vec<u16>>()
  };
  let mut uf = vec![0u16; sw * sh];
  let mut vf = vec![0u16; sw * sh];
  for r in 0..sh {
    let cr = r / 2;
    let (uh, vh) = if r & 1 == 0 {
      (
        u[cr * cw..cr * cw + cw].to_vec(),
        v[cr * cw..cr * cw + cw].to_vec(),
      )
    } else {
      let next = if cr + 1 < ch { cr + 1 } else { cr };
      (vblend(u, cr, next), vblend(v, cr, next))
    };
    uf[r * sw..r * sw + sw].copy_from_slice(&recon_full_row_u16(&uh, cw));
    vf[r * sw..r * sw + sw].copy_from_slice(&recon_full_row_u16(&vh, cw));
  }
  (uf, vf)
}

/// Re-encode a host-native `u16` slice as host-independent BE-wire storage.
fn as_be(host: &[u16]) -> Vec<u16> {
  host.iter().map(|v| v.to_be()).collect()
}

/// The geometries the oracle-equality tests sweep: clean 2:1 and fractional
/// ratios, EVEN source heights only (so the vertical luma-domain pairing equals
/// the co-sited chroma box). Widths are even (Yuv420p requires it).
const GEOMS: [(usize, usize, usize, usize); 4] =
  [(8, 8, 4, 4), (8, 8, 5, 3), (12, 8, 4, 4), (16, 8, 6, 5)];

macro_rules! hibit_420_resample_siting {
  (
    $mod:ident, $bits:expr,
    $M420:ident, $F420:ident, $w420:ident,
    $M420be:ty, $F420be:ident, $w420be:ident,
    $M444:ident, $F444:ident, $w444:ident,
    $Row:ident
  ) => {
    mod $mod {
      use super::*;

      const MASK: u16 = ((1u32 << $bits) - 1) as u16;
      const MID: u16 = 1u16 << ($bits - 1);

      /// A `Yuv420pN` fixture (`cw = sw / 2`, `ch = sh / 2`) with a strong
      /// HORIZONTAL chroma ramp (so the centered triangle genuinely differs from
      /// the co-sited nearest decode) plus a per-row tilt (a vertical mistake
      /// would show). Low-packed native codes so every kernel sees real math.
      fn ramp(sw: usize, sh: usize) -> (Vec<u16>, Vec<u16>, Vec<u16>) {
        let (cw, ch) = (sw / 2, sh / 2);
        let step = (MASK as u32 / 16).max(1);
        let mut y = vec![0u16; sw * sh];
        let mut u = vec![0u16; cw * ch];
        let mut v = vec![0u16; cw * ch];
        for (i, p) in y.iter_mut().enumerate() {
          *p = ((40 + i as u32 * 37) & MASK as u32) as u16;
        }
        for r in 0..ch {
          for c in 0..cw {
            u[r * cw + c] = (step * c as u32 + step + r as u32 * 5).min(MASK as u32) as u16;
            v[r * cw + c] = (MASK as u32).saturating_sub(step * c as u32).max(step) as u16;
          }
        }
        (y, u, v)
      }

      /// Flat chroma: the centered triangle of a constant is that constant, so
      /// centered must equal co-sited. Luma still varies.
      fn flat(sw: usize, sh: usize) -> (Vec<u16>, Vec<u16>, Vec<u16>) {
        let (cw, ch) = (sw / 2, sh / 2);
        let mut y = vec![0u16; sw * sh];
        for (i, p) in y.iter_mut().enumerate() {
          *p = ((40 + i as u32 * 29) & MASK as u32) as u16;
        }
        (y, vec![MID; cw * ch], vec![MID; cw * ch])
      }

      /// Drive an LE `Yuv420pN` area resample for `rgb` (u8) + `rgb_u16`.
      #[allow(clippy::too_many_arguments)]
      fn run(
        y: &[u16],
        u: &[u16],
        v: &[u16],
        sw: usize,
        sh: usize,
        ow: usize,
        oh: usize,
        loc: ChromaLocation,
        native: bool,
        simd: bool,
      ) -> (Vec<u8>, Vec<u16>) {
        let cw = sw / 2;
        let mut rgb = vec![0u8; ow * oh * 3];
        let mut rgb16 = vec![0u16; ow * oh * 3];
        {
          let mut sink =
            MixedSinker::<$M420, AreaResampler>::with_resampler(sw, sh, AreaResampler::to(ow, oh))
              .unwrap()
              .with_native(native)
              .with_chroma_location(loc.clone())
              .with_simd(simd)
              .with_rgb(&mut rgb)
              .unwrap()
              .with_rgb_u16(&mut rgb16)
              .unwrap();
          let f = $F420::new(
            y, u, v, sw as u32, sh as u32, sw as u32, cw as u32, cw as u32,
          );
          $w420(&f, FR, sink.set_kernel_matrix(M)).unwrap();
        }
        (rgb, rgb16)
      }

      /// Drive an LE `Yuv420pN` single-kernel filter resample (Triangle).
      #[allow(clippy::too_many_arguments)]
      fn run_filter(
        y: &[u16],
        u: &[u16],
        v: &[u16],
        sw: usize,
        sh: usize,
        ow: usize,
        oh: usize,
        loc: ChromaLocation,
        simd: bool,
      ) -> (Vec<u8>, Vec<u16>) {
        let cw = sw / 2;
        let mut rgb = vec![0u8; ow * oh * 3];
        let mut rgb16 = vec![0u16; ow * oh * 3];
        {
          let mut sink = MixedSinker::<$M420, FilteredResampler<Triangle>>::with_resampler(
            sw,
            sh,
            FilteredResampler::new(ow, oh, Triangle),
          )
          .unwrap()
          .with_chroma_location(loc.clone())
          .with_simd(simd)
          .with_rgb(&mut rgb)
          .unwrap()
          .with_rgb_u16(&mut rgb16)
          .unwrap();
          let f = $F420::new(
            y, u, v, sw as u32, sh as u32, sw as u32, cw as u32, cw as u32,
          );
          $w420(&f, FR, sink.set_kernel_matrix(M)).unwrap();
        }
        (rgb, rgb16)
      }

      /// Drive a BE `Yuv420pN` area resample (planes re-encoded BE-wire).
      #[allow(clippy::too_many_arguments)]
      fn run_be(
        y: &[u16],
        u: &[u16],
        v: &[u16],
        sw: usize,
        sh: usize,
        ow: usize,
        oh: usize,
        loc: ChromaLocation,
        native: bool,
      ) -> (Vec<u8>, Vec<u16>) {
        let cw = sw / 2;
        let (yb, ub, vb) = (as_be(y), as_be(u), as_be(v));
        let mut rgb = vec![0u8; ow * oh * 3];
        let mut rgb16 = vec![0u16; ow * oh * 3];
        {
          let mut sink = MixedSinker::<$M420be, AreaResampler>::with_resampler(
            sw,
            sh,
            AreaResampler::to(ow, oh),
          )
          .unwrap()
          .with_native(native)
          .with_chroma_location(loc.clone())
          .with_rgb(&mut rgb)
          .unwrap()
          .with_rgb_u16(&mut rgb16)
          .unwrap();
          let f = $F420be::try_new(
            &yb, &ub, &vb, sw as u32, sh as u32, sw as u32, cw as u32, cw as u32,
          )
          .unwrap();
          $w420be(&f, FR, sink.set_kernel_matrix(M)).unwrap();
        }
        (rgb, rgb16)
      }

      /// The centered NATIVE code-domain oracle: bin Y co-sited and U / V through
      /// the exact centered chroma oracle to `ow x oh`, then convert ONCE at
      /// output width via an identity `Yuv444pN` sink.
      #[allow(clippy::too_many_arguments)]
      fn native_oracle(
        y: &[u16],
        u: &[u16],
        v: &[u16],
        sw: usize,
        sh: usize,
        ow: usize,
        oh: usize,
        simd: bool,
      ) -> (Vec<u8>, Vec<u16>) {
        let (cw, ch) = (sw / 2, sh / 2);
        let yb = bin_cosited_u16(y, sw, sh, ow, oh);
        let ub = bin_chroma_centered_u16(u, cw, ch, ow, oh);
        let vb = bin_chroma_centered_u16(v, cw, ch, ow, oh);
        let mut rgb = vec![0u8; ow * oh * 3];
        let mut rgb16 = vec![0u16; ow * oh * 3];
        {
          let mut sink = MixedSinker::<$M444>::new(ow, oh)
            .with_simd(simd)
            .with_rgb(&mut rgb)
            .unwrap()
            .with_rgb_u16(&mut rgb16)
            .unwrap();
          let f = $F444::new(
            &yb, &ub, &vb, ow as u32, oh as u32, ow as u32, ow as u32, ow as u32,
          );
          $w444(&f, FR, sink.set_kernel_matrix(M)).unwrap();
        }
        (rgb, rgb16)
      }

      /// The centered RGB-domain oracle: reconstruct U / V to full width (u16)
      /// with the #302 kernel — each luma row `r` taking chroma row `r / 2` (the
      /// co-sited vertical replication) — then run that full-resolution
      /// `Yuv444pN` frame through the given resampler (convert-each-row-then-bin,
      /// exactly what the row-stage / filter arms do). `filter = true` uses the
      /// Triangle filter tier.
      #[allow(clippy::too_many_arguments)]
      fn rgb_domain_oracle(
        y: &[u16],
        u: &[u16],
        v: &[u16],
        sw: usize,
        sh: usize,
        ow: usize,
        oh: usize,
        simd: bool,
        filter: bool,
      ) -> (Vec<u8>, Vec<u16>) {
        let cw = sw / 2;
        let mut uf = vec![0u16; sw * sh];
        let mut vf = vec![0u16; sw * sh];
        for r in 0..sh {
          let cr = r / 2;
          uf[r * sw..r * sw + sw]
            .copy_from_slice(&recon_full_row_u16(&u[cr * cw..cr * cw + cw], cw));
          vf[r * sw..r * sw + sw]
            .copy_from_slice(&recon_full_row_u16(&v[cr * cw..cr * cw + cw], cw));
        }
        let mut rgb = vec![0u8; ow * oh * 3];
        let mut rgb16 = vec![0u16; ow * oh * 3];
        let f = $F444::new(
          y, &uf, &vf, sw as u32, sh as u32, sw as u32, sw as u32, sw as u32,
        );
        if filter {
          let mut sink = MixedSinker::<$M444, FilteredResampler<Triangle>>::with_resampler(
            sw,
            sh,
            FilteredResampler::new(ow, oh, Triangle),
          )
          .unwrap()
          .with_simd(simd)
          .with_rgb(&mut rgb)
          .unwrap()
          .with_rgb_u16(&mut rgb16)
          .unwrap();
          $w444(&f, FR, sink.set_kernel_matrix(M)).unwrap();
        } else {
          let mut sink =
            MixedSinker::<$M444, AreaResampler>::with_resampler(sw, sh, AreaResampler::to(ow, oh))
              .unwrap()
              .with_native(false)
              .with_simd(simd)
              .with_rgb(&mut rgb)
              .unwrap()
              .with_rgb_u16(&mut rgb16)
              .unwrap();
          $w444(&f, FR, sink.set_kernel_matrix(M)).unwrap();
        }
        (rgb, rgb16)
      }

      // ---- co-sited byte-identity (the regression contract) ----------------

      #[test]
      #[cfg_attr(miri, ignore = "SIMD row kernels use intrinsics unsupported by Miri")]
      fn cosited_group_is_byte_identical_across_tiers() {
        for (sw, sh, ow, oh) in GEOMS {
          let (y, u, v) = ramp(sw, sh);
          for native in [true, false] {
            let base = run(
              &y,
              &u,
              &v,
              sw,
              sh,
              ow,
              oh,
              ChromaLocation::Unspecified,
              native,
              true,
            );
            // `TopLeft` (`v = 0`) now folds the forward vertical triangle (RFC
            // #238 Top), so it LEAVES the co-sited byte-identity group.
            for loc in [ChromaLocation::Left, ChromaLocation::other("unassigned-7")] {
              assert_eq!(
                run(&y, &u, &v, sw, sh, ow, oh, loc.clone(), native, true),
                base,
                "co-sited {loc:?} must keep the byte-identical decode \
                 (native={native}, {sw}x{sh}->{ow}x{oh})"
              );
            }
          }
          // The filter tier too.
          let base = run_filter(
            &y,
            &u,
            &v,
            sw,
            sh,
            ow,
            oh,
            ChromaLocation::Unspecified,
            true,
          );
          assert_eq!(
            run_filter(&y, &u, &v, sw, sh, ow, oh, ChromaLocation::Left, true),
            base,
            "co-sited filter must stay byte-identical ({sw}x{sh}->{ow}x{oh})"
          );
        }
      }

      // ---- centered native == the exact code-domain oracle -----------------

      #[test]
      #[cfg_attr(miri, ignore = "SIMD row kernels use intrinsics unsupported by Miri")]
      fn centered_native_equals_code_domain_oracle() {
        for (sw, sh, ow, oh) in GEOMS {
          let (y, u, v) = ramp(sw, sh);
          let want = native_oracle(&y, &u, &v, sw, sh, ow, oh, true);
          // `Center`: horizontal centered phase, vertical co-sited. (`Top` now
          // folds the `v = 0` forward triangle — see `top_native_equals_*`.)
          for loc in [ChromaLocation::Center] {
            assert_eq!(
              run(&y, &u, &v, sw, sh, ow, oh, loc.clone(), true, true),
              want,
              "centered native {loc:?} must equal the code-domain oracle \
               ({sw}x{sh}->{ow}x{oh})"
            );
          }
        }
      }

      // ---- centered row-stage / filter == RGB-domain reconstruct-then-bin --

      #[test]
      #[cfg_attr(miri, ignore = "SIMD row kernels use intrinsics unsupported by Miri")]
      fn centered_row_stage_equals_rgb_reconstruct_then_bin() {
        for (sw, sh, ow, oh) in GEOMS {
          let (y, u, v) = ramp(sw, sh);
          let want = rgb_domain_oracle(&y, &u, &v, sw, sh, ow, oh, true, false);
          // `Top` now folds the forward vertical triangle — see
          // `top_row_stage_equals_rgb_reconstruct_then_bin`.
          for loc in [ChromaLocation::Center] {
            assert_eq!(
              run(&y, &u, &v, sw, sh, ow, oh, loc.clone(), false, true),
              want,
              "centered row-stage {loc:?} must equal the RGB-domain oracle \
               ({sw}x{sh}->{ow}x{oh})"
            );
          }
        }
      }

      #[test]
      #[cfg_attr(miri, ignore = "SIMD row kernels use intrinsics unsupported by Miri")]
      fn centered_filter_equals_rgb_reconstruct_then_bin() {
        for (sw, sh, ow, oh) in GEOMS {
          let (y, u, v) = ramp(sw, sh);
          let want = rgb_domain_oracle(&y, &u, &v, sw, sh, ow, oh, true, true);
          assert_eq!(
            run_filter(&y, &u, &v, sw, sh, ow, oh, ChromaLocation::Center, true),
            want,
            "centered filter must equal the RGB-domain Triangle oracle \
             ({sw}x{sh}->{ow}x{oh})"
          );
        }
      }

      // ---- SIMD == scalar --------------------------------------------------

      #[test]
      #[cfg_attr(miri, ignore = "SIMD row kernels use intrinsics unsupported by Miri")]
      fn centered_simd_matches_scalar() {
        let (y, u, v) = ramp(8, 8);
        for native in [true, false] {
          assert_eq!(
            run(&y, &u, &v, 8, 8, 4, 4, ChromaLocation::Center, native, true),
            run(
              &y,
              &u,
              &v,
              8,
              8,
              4,
              4,
              ChromaLocation::Center,
              native,
              false
            ),
            "centered SIMD vs scalar must agree (native={native})"
          );
        }
        assert_eq!(
          run_filter(&y, &u, &v, 8, 8, 4, 4, ChromaLocation::Center, true),
          run_filter(&y, &u, &v, 8, 8, 4, 4, ChromaLocation::Center, false),
          "centered filter SIMD vs scalar must agree"
        );
      }

      // ---- centered differs from co-sited on a ramp, equals it on flat -----

      #[test]
      #[cfg_attr(miri, ignore = "SIMD row kernels use intrinsics unsupported by Miri")]
      fn centered_differs_from_cosited_on_a_chroma_ramp() {
        let (y, u, v) = ramp(8, 8);
        for native in [true, false] {
          let cos = run(&y, &u, &v, 8, 8, 4, 4, ChromaLocation::Left, native, true);
          let cen = run(&y, &u, &v, 8, 8, 4, 4, ChromaLocation::Center, native, true);
          assert_ne!(
            cos, cen,
            "centered must differ from co-sited on a chroma ramp (native={native})"
          );
        }
      }

      #[test]
      #[cfg_attr(miri, ignore = "SIMD row kernels use intrinsics unsupported by Miri")]
      fn centered_equals_cosited_on_flat_chroma() {
        let (y, u, v) = flat(8, 8);
        for native in [true, false] {
          assert_eq!(
            run(&y, &u, &v, 8, 8, 4, 4, ChromaLocation::Left, native, true),
            run(&y, &u, &v, 8, 8, 4, 4, ChromaLocation::Center, native, true),
            "centered must equal co-sited on flat chroma (native={native})"
          );
        }
      }

      // ---- wire endianness is siting-independent ---------------------------

      #[test]
      #[cfg_attr(miri, ignore = "SIMD row kernels use intrinsics unsupported by Miri")]
      fn be_centered_matches_le() {
        let (y, u, v) = ramp(8, 8);
        for native in [true, false] {
          assert_eq!(
            run_be(&y, &u, &v, 8, 8, 4, 4, ChromaLocation::Center, native),
            run(&y, &u, &v, 8, 8, 4, 4, ChromaLocation::Center, native, true),
            "BE centered decode must equal LE for the same logical planes (native={native})"
          );
        }
      }

      // ---- mid-frame siting change is rejected across tiers ----------------

      /// Accept row 0 at `loc1` (freezes the phase), flip to `loc2`, feed the
      /// IN-SEQUENCE row 1 (chroma row `1 / 2 = 0`), and return its result.
      fn flip_row1<R>(
        mut sink: MixedSinker<'_, $M420, R>,
        y: &[u16],
        u: &[u16],
        v: &[u16],
        loc1: ChromaLocation,
        loc2: ChromaLocation,
      ) -> Result<(), MixedSinkerError> {
        sink.set_chroma_location(loc1.clone());
        PixelSink::begin_frame(&mut sink, 8, 8).unwrap();
        let row0 = $Row::for_tests(&y[0..8], &u[0..4], &v[0..4], 0, M, FR);
        PixelSink::process(&mut sink, row0).unwrap();
        sink.set_chroma_location(loc2.clone());
        let row1 = $Row::for_tests(&y[8..16], &u[0..4], &v[0..4], 1, M, FR);
        PixelSink::process(&mut sink, row1)
      }

      #[test]
      #[cfg_attr(miri, ignore = "SIMD row kernels use intrinsics unsupported by Miri")]
      fn mid_frame_siting_change_rejected() {
        let (y, u, v) = ramp(8, 8);
        for (loc1, loc2) in [
          (ChromaLocation::Center, ChromaLocation::Left),
          (ChromaLocation::Left, ChromaLocation::Center),
        ] {
          // Native fast tier.
          let mut rgb = vec![0u8; 4 * 4 * 3];
          let sink =
            MixedSinker::<$M420, AreaResampler>::with_resampler(8, 8, AreaResampler::to(4, 4))
              .unwrap()
              .with_native(true)
              .with_rgb(&mut rgb)
              .unwrap();
          let err = flip_row1(sink, &y, &u, &v, loc1.clone(), loc2.clone()).unwrap_err();
          assert!(
            matches!(err, MixedSinkerError::ChromaSitingChanged(_)),
            "native {loc1:?}->{loc2:?}: want ChromaSitingChanged, got {err:?}"
          );

          // Encoded row-stage tier.
          let mut rgb = vec![0u8; 4 * 4 * 3];
          let sink =
            MixedSinker::<$M420, AreaResampler>::with_resampler(8, 8, AreaResampler::to(4, 4))
              .unwrap()
              .with_native(false)
              .with_rgb(&mut rgb)
              .unwrap();
          let err = flip_row1(sink, &y, &u, &v, loc1.clone(), loc2.clone()).unwrap_err();
          assert!(
            matches!(err, MixedSinkerError::ChromaSitingChanged(_)),
            "row-stage {loc1:?}->{loc2:?}: want ChromaSitingChanged, got {err:?}"
          );

          // Filter tier.
          let mut rgb = vec![0u8; 4 * 4 * 3];
          let sink = MixedSinker::<$M420, FilteredResampler<Triangle>>::with_resampler(
            8,
            8,
            FilteredResampler::new(4, 4, Triangle),
          )
          .unwrap()
          .with_rgb(&mut rgb)
          .unwrap();
          let err = flip_row1(sink, &y, &u, &v, loc1.clone(), loc2.clone()).unwrap_err();
          assert!(
            matches!(err, MixedSinkerError::ChromaSitingChanged(_)),
            "filter {loc1:?}->{loc2:?}: want ChromaSitingChanged, got {err:?}"
          );
        }
      }

      // ==== RFC #238 S6d: bottom-sited (v = 1) VERTICAL fold ================

      /// Flat-luma fixture with a strong per-ROW chroma step (flat across
      /// columns), so the vertical `Bottom` fold is observable in isolation: a
      /// horizontal-only siting leaves it untouched, the `v = 1` blend visibly
      /// moves it. `sw` / `sh` must be even.
      fn vramp(sw: usize, sh: usize) -> (Vec<u16>, Vec<u16>, Vec<u16>) {
        let (cw, ch) = (sw / 2, sh / 2);
        let step = (MASK as u32 / 8).max(1);
        let y = vec![MID; sw * sh];
        let mut u = vec![0u16; cw * ch];
        let mut v = vec![0u16; cw * ch];
        for r in 0..ch {
          for c in 0..cw {
            u[r * cw + c] = (step + r as u32 * step).min(MASK as u32) as u16;
            v[r * cw + c] = (MASK as u32).saturating_sub(r as u32 * step).max(step) as u16;
          }
        }
        (y, u, v)
      }

      /// The EXACT bottom-sited (`v = 1`) chroma oracle for the native tier: the
      /// centered horizontal `1/4`–`3/4` triangle (×4) composed with the vertical
      /// `v = 1` triangle (×2 — even luma row `2i` box-blends chroma rows
      /// `{i-1, i}` with weights `{1, 1}`, odd row `2i+1` takes chroma row `i`
      /// with weight 2, top-edge clamp), the combined ×8 UNROUNDED reconstruction
      /// box-averaged to `ow x oh` with a SINGLE round-half-up — the code-domain
      /// twin the folded `area_chroma_phased_v` V axis realizes (EVEN `sh`,
      /// `ch = sh / 2`).
      fn bin_chroma_bottom_u16(c: &[u16], cw: usize, ch: usize, ow: usize, oh: usize) -> Vec<u16> {
        let full = 2 * cw;
        let sh = 2 * ch;
        let mut r8 = vec![0u64; full * sh];
        for r in 0..sh {
          let cr = r / 2;
          let prev = cr.saturating_sub(1);
          let vrow: Vec<u32> = (0..cw)
            .map(|j| {
              if r & 1 == 0 {
                u32::from(c[prev * cw + j]) + u32::from(c[cr * cw + j]) // even: {1, 1}
              } else {
                2 * u32::from(c[cr * cw + j]) // odd: {2}
              }
            })
            .collect();
          for j in 0..cw {
            let l = vrow[j.saturating_sub(1)];
            let m = vrow[j];
            let rt = vrow[if j + 1 < cw { j + 1 } else { j }];
            r8[r * full + 2 * j] = u64::from(l + 3 * m);
            r8[r * full + 2 * j + 1] = u64::from(3 * m + rt);
          }
        }
        let hw = area_weights(full, ow);
        let vw = area_weights(sh, oh);
        let denom = (8 * full * sh) as u64; // ×8 (×2 V, ×4 H) × the box normalization
        let mut out = vec![0u16; ow * oh];
        for (oy, (vs, vwin)) in vw.iter().enumerate() {
          for (ox, (hs, hwin)) in hw.iter().enumerate() {
            let mut s = 0u64;
            for (dy, &vwt) in vwin.iter().enumerate() {
              let mut hsum = 0u64;
              for (dx, &hwt) in hwin.iter().enumerate() {
                hsum += hwt * r8[(vs + dy) * full + hs + dx];
              }
              s += vwt * hsum;
            }
            out[oy * ow + ox] = rdhu(s, denom) as u16;
          }
        }
        out
      }

      /// The bottom-sited NATIVE oracle: bin Y co-sited and U / V through the
      /// exact bottom V-fold oracle to `ow x oh`, then convert ONCE at output
      /// width via an identity `Yuv444pN` sink.
      #[allow(clippy::too_many_arguments)]
      fn bottom_native_oracle(
        y: &[u16],
        u: &[u16],
        v: &[u16],
        sw: usize,
        sh: usize,
        ow: usize,
        oh: usize,
        simd: bool,
      ) -> (Vec<u8>, Vec<u16>) {
        let (cw, ch) = (sw / 2, sh / 2);
        let yb = bin_cosited_u16(y, sw, sh, ow, oh);
        let ub = bin_chroma_bottom_u16(u, cw, ch, ow, oh);
        let vb = bin_chroma_bottom_u16(v, cw, ch, ow, oh);
        let mut rgb = vec![0u8; ow * oh * 3];
        let mut rgb16 = vec![0u16; ow * oh * 3];
        {
          let mut sink = MixedSinker::<$M444>::new(ow, oh)
            .with_simd(simd)
            .with_rgb(&mut rgb)
            .unwrap()
            .with_rgb_u16(&mut rgb16)
            .unwrap();
          let f = $F444::new(
            &yb, &ub, &vb, ow as u32, oh as u32, ow as u32, ow as u32, ow as u32,
          );
          $w444(&f, FR, sink.set_kernel_matrix(M)).unwrap();
        }
        (rgb, rgb16)
      }

      /// Reconstruct `Yuv420pN` chroma to full resolution (`sw x sh`, `u16`) for
      /// the bottom-sited decode — the identity bottom kernel at source width:
      /// even rows box-blend chroma rows `i - 1` (clamped) and `i` (round-half-up),
      /// odd rows take chroma row `i`, each then horizontally upsampled with the
      /// #302 centered kernel. The shared reconstruction step for every
      /// reconstruct-then-bin bottom oracle.
      fn recon_full_bottom_u16(u: &[u16], v: &[u16], sw: usize, sh: usize) -> (Vec<u16>, Vec<u16>) {
        let cw = sw / 2;
        let vblend = |plane: &[u16], cr: usize, prev: usize| -> Vec<u16> {
          (0..cw)
            .map(|c| {
              let a = u32::from(plane[prev * cw + c]);
              let b = u32::from(plane[cr * cw + c]);
              ((a + b + 1) >> 1) as u16
            })
            .collect::<Vec<u16>>()
        };
        let mut uf = vec![0u16; sw * sh];
        let mut vf = vec![0u16; sw * sh];
        for r in 0..sh {
          let cr = r / 2;
          let (uh, vh) = if r & 1 == 0 {
            let prev = cr.saturating_sub(1);
            (vblend(u, cr, prev), vblend(v, cr, prev))
          } else {
            (
              u[cr * cw..cr * cw + cw].to_vec(),
              v[cr * cw..cr * cw + cw].to_vec(),
            )
          };
          uf[r * sw..r * sw + sw].copy_from_slice(&recon_full_row_u16(&uh, cw));
          vf[r * sw..r * sw + sw].copy_from_slice(&recon_full_row_u16(&vh, cw));
        }
        (uf, vf)
      }

      /// The bottom-sited RGB-domain oracle: reconstruct U / V to full width with
      /// the vertical bottom blend then run that `Yuv444pN` frame through the
      /// given resampler (convert-each-row-then-bin) — exactly what the row-stage
      /// / filter arms do for `Bottom`. `filter = true` uses the Triangle tier.
      #[allow(clippy::too_many_arguments)]
      fn bottom_rgb_domain_oracle(
        y: &[u16],
        u: &[u16],
        v: &[u16],
        sw: usize,
        sh: usize,
        ow: usize,
        oh: usize,
        simd: bool,
        filter: bool,
      ) -> (Vec<u8>, Vec<u16>) {
        let (uf, vf) = recon_full_bottom_u16(u, v, sw, sh);
        let mut rgb = vec![0u8; ow * oh * 3];
        let mut rgb16 = vec![0u16; ow * oh * 3];
        let f = $F444::new(
          y, &uf, &vf, sw as u32, sh as u32, sw as u32, sw as u32, sw as u32,
        );
        if filter {
          let mut sink = MixedSinker::<$M444, FilteredResampler<Triangle>>::with_resampler(
            sw,
            sh,
            FilteredResampler::new(ow, oh, Triangle),
          )
          .unwrap()
          .with_simd(simd)
          .with_rgb(&mut rgb)
          .unwrap()
          .with_rgb_u16(&mut rgb16)
          .unwrap();
          $w444(&f, FR, sink.set_kernel_matrix(M)).unwrap();
        } else {
          let mut sink =
            MixedSinker::<$M444, AreaResampler>::with_resampler(sw, sh, AreaResampler::to(ow, oh))
              .unwrap()
              .with_native(false)
              .with_simd(simd)
              .with_rgb(&mut rgb)
              .unwrap()
              .with_rgb_u16(&mut rgb16)
              .unwrap();
          $w444(&f, FR, sink.set_kernel_matrix(M)).unwrap();
        }
        (rgb, rgb16)
      }

      /// Direct (non-resample, identity dims) `Yuv420pN` `Bottom` decode — the
      /// delay-line kernel path, the already-validated identity reference the
      /// resample path must match at identity dimensions.
      fn direct_bottom(
        y: &[u16],
        u: &[u16],
        v: &[u16],
        sw: usize,
        sh: usize,
        simd: bool,
      ) -> (Vec<u8>, Vec<u16>) {
        let cw = sw / 2;
        let mut rgb = vec![0u8; sw * sh * 3];
        let mut rgb16 = vec![0u16; sw * sh * 3];
        {
          let mut sink = MixedSinker::<$M420>::new(sw, sh)
            .with_chroma_location(ChromaLocation::Bottom)
            .with_simd(simd)
            .with_rgb(&mut rgb)
            .unwrap()
            .with_rgb_u16(&mut rgb16)
            .unwrap();
          let f = $F420::new(
            y, u, v, sw as u32, sh as u32, sw as u32, cw as u32, cw as u32,
          );
          $w420(&f, FR, sink.set_kernel_matrix(M)).unwrap();
        }
        (rgb, rgb16)
      }

      /// The EXACT bottom-LEFT-sited (`h = 0`, `v = 1`) chroma oracle for the
      /// native tier: the CO-SITED horizontal box (a plain `cw`-wide area, NOT the
      /// centered `1/4`–`3/4` reconstruction of [`bin_chroma_bottom_u16`]) composed
      /// with the same vertical `v = 1` triangle (×2), box-averaged to `ow x oh`
      /// with a SINGLE round-half-up — the code-domain twin the folded
      /// `area_chroma_420(h = 0, v = 1)` realizes (EVEN `sh`).
      fn bin_chroma_bottomleft_u16(
        c: &[u16],
        cw: usize,
        ch: usize,
        ow: usize,
        oh: usize,
      ) -> Vec<u16> {
        let sh = 2 * ch;
        let mut r2 = vec![0u64; cw * sh];
        for r in 0..sh {
          let cr = r / 2;
          let prev = cr.saturating_sub(1);
          for j in 0..cw {
            r2[r * cw + j] = if r & 1 == 0 {
              u64::from(c[prev * cw + j]) + u64::from(c[cr * cw + j]) // even: {1, 1}
            } else {
              2 * u64::from(c[cr * cw + j]) // odd: {2}
            };
          }
        }
        let hw = area_weights(cw, ow);
        let vw = area_weights(sh, oh);
        let denom = (2 * cw * sh) as u64; // ×2 V × the box normalization (H co-sited)
        let mut out = vec![0u16; ow * oh];
        for (oy, (vs, vwin)) in vw.iter().enumerate() {
          for (ox, (hs, hwin)) in hw.iter().enumerate() {
            let mut s = 0u64;
            for (dy, &vwt) in vwin.iter().enumerate() {
              let mut hsum = 0u64;
              for (dx, &hwt) in hwin.iter().enumerate() {
                hsum += hwt * r2[(vs + dy) * cw + hs + dx];
              }
              s += vwt * hsum;
            }
            out[oy * ow + ox] = rdhu(s, denom) as u16;
          }
        }
        out
      }

      /// The bottom-left-sited NATIVE oracle: bin Y co-sited and U / V through the
      /// exact bottom-left fold to `ow x oh`, then convert ONCE via an identity
      /// `Yuv444pN` sink.
      #[allow(clippy::too_many_arguments)]
      fn bottomleft_native_oracle(
        y: &[u16],
        u: &[u16],
        v: &[u16],
        sw: usize,
        sh: usize,
        ow: usize,
        oh: usize,
        simd: bool,
      ) -> (Vec<u8>, Vec<u16>) {
        let (cw, ch) = (sw / 2, sh / 2);
        let yb = bin_cosited_u16(y, sw, sh, ow, oh);
        let ub = bin_chroma_bottomleft_u16(u, cw, ch, ow, oh);
        let vb = bin_chroma_bottomleft_u16(v, cw, ch, ow, oh);
        let mut rgb = vec![0u8; ow * oh * 3];
        let mut rgb16 = vec![0u16; ow * oh * 3];
        {
          let mut sink = MixedSinker::<$M444>::new(ow, oh)
            .with_simd(simd)
            .with_rgb(&mut rgb)
            .unwrap()
            .with_rgb_u16(&mut rgb16)
            .unwrap();
          let f = $F444::new(
            &yb, &ub, &vb, ow as u32, oh as u32, ow as u32, ow as u32, ow as u32,
          );
          $w444(&f, FR, sink.set_kernel_matrix(M)).unwrap();
        }
        (rgb, rgb16)
      }

      /// Reconstruct `Yuv420pN` chroma to full resolution for the bottom-left
      /// decode: [`recon_full_bottom_u16`]'s vertical box blend, but the co-sited
      /// horizontal 2× replicate instead of the centered kernel.
      fn recon_full_bottomleft_u16(
        u: &[u16],
        v: &[u16],
        sw: usize,
        sh: usize,
      ) -> (Vec<u16>, Vec<u16>) {
        let cw = sw / 2;
        let vblend = |plane: &[u16], cr: usize, prev: usize| -> Vec<u16> {
          (0..cw)
            .map(|c| {
              let a = u32::from(plane[prev * cw + c]);
              let b = u32::from(plane[cr * cw + c]);
              ((a + b + 1) >> 1) as u16
            })
            .collect::<Vec<u16>>()
        };
        let replicate = |half: &[u16]| -> Vec<u16> {
          let mut out = vec![0u16; 2 * cw];
          for j in 0..cw {
            out[2 * j] = half[j];
            out[2 * j + 1] = half[j];
          }
          out
        };
        let mut uf = vec![0u16; sw * sh];
        let mut vf = vec![0u16; sw * sh];
        for r in 0..sh {
          let cr = r / 2;
          let (uh, vh) = if r & 1 == 0 {
            let prev = cr.saturating_sub(1);
            (vblend(u, cr, prev), vblend(v, cr, prev))
          } else {
            (
              u[cr * cw..cr * cw + cw].to_vec(),
              v[cr * cw..cr * cw + cw].to_vec(),
            )
          };
          uf[r * sw..r * sw + sw].copy_from_slice(&replicate(&uh));
          vf[r * sw..r * sw + sw].copy_from_slice(&replicate(&vh));
        }
        (uf, vf)
      }

      /// The bottom-left-sited RGB-domain oracle: reconstruct U / V to full width
      /// (co-sited + vertical blend) then run through the given resampler — what
      /// the row-stage / filter arms do for `BottomLeft`. `filter = true` uses the
      /// Triangle tier.
      #[allow(clippy::too_many_arguments)]
      fn bottomleft_rgb_domain_oracle(
        y: &[u16],
        u: &[u16],
        v: &[u16],
        sw: usize,
        sh: usize,
        ow: usize,
        oh: usize,
        simd: bool,
        filter: bool,
      ) -> (Vec<u8>, Vec<u16>) {
        let (uf, vf) = recon_full_bottomleft_u16(u, v, sw, sh);
        let mut rgb = vec![0u8; ow * oh * 3];
        let mut rgb16 = vec![0u16; ow * oh * 3];
        let f = $F444::new(
          y, &uf, &vf, sw as u32, sh as u32, sw as u32, sw as u32, sw as u32,
        );
        if filter {
          let mut sink = MixedSinker::<$M444, FilteredResampler<Triangle>>::with_resampler(
            sw,
            sh,
            FilteredResampler::new(ow, oh, Triangle),
          )
          .unwrap()
          .with_simd(simd)
          .with_rgb(&mut rgb)
          .unwrap()
          .with_rgb_u16(&mut rgb16)
          .unwrap();
          $w444(&f, FR, sink.set_kernel_matrix(M)).unwrap();
        } else {
          let mut sink =
            MixedSinker::<$M444, AreaResampler>::with_resampler(sw, sh, AreaResampler::to(ow, oh))
              .unwrap()
              .with_native(false)
              .with_simd(simd)
              .with_rgb(&mut rgb)
              .unwrap()
              .with_rgb_u16(&mut rgb16)
              .unwrap();
          $w444(&f, FR, sink.set_kernel_matrix(M)).unwrap();
        }
        (rgb, rgb16)
      }

      #[test]
      #[cfg_attr(miri, ignore = "SIMD row kernels use intrinsics unsupported by Miri")]
      fn bottomleft_native_equals_code_domain_oracle() {
        for (sw, sh, ow, oh) in GEOMS {
          let (y, u, v) = vramp(sw, sh);
          let o = bottomleft_native_oracle(&y, &u, &v, sw, sh, ow, oh, true);
          assert_eq!(
            run(
              &y,
              &u,
              &v,
              sw,
              sh,
              ow,
              oh,
              ChromaLocation::BottomLeft,
              true,
              true
            ),
            o,
            "bottom-left native must equal the co-sited V-fold code-domain oracle \
             ({sw}x{sh}->{ow}x{oh})"
          );
        }
      }

      #[test]
      #[cfg_attr(miri, ignore = "SIMD row kernels use intrinsics unsupported by Miri")]
      fn bottomleft_row_stage_and_filter_equal_rgb_reconstruct_then_bin() {
        for (sw, sh, ow, oh) in GEOMS {
          let (y, u, v) = vramp(sw, sh);
          assert_eq!(
            run(
              &y,
              &u,
              &v,
              sw,
              sh,
              ow,
              oh,
              ChromaLocation::BottomLeft,
              false,
              true
            ),
            bottomleft_rgb_domain_oracle(&y, &u, &v, sw, sh, ow, oh, true, false),
            "bottom-left row-stage == RGB reconstruct-then-bin ({sw}x{sh}->{ow}x{oh})"
          );
          assert_eq!(
            run_filter(&y, &u, &v, sw, sh, ow, oh, ChromaLocation::BottomLeft, true),
            bottomleft_rgb_domain_oracle(&y, &u, &v, sw, sh, ow, oh, true, true),
            "bottom-left filter == RGB reconstruct-then-Triangle ({sw}x{sh}->{ow}x{oh})"
          );
        }
      }

      #[test]
      #[cfg_attr(miri, ignore = "SIMD row kernels use intrinsics unsupported by Miri")]
      fn bottomleft_be_and_simd_agree_and_fold_the_phase() {
        let (y, u, v) = vramp(8, 8);
        for native in [true, false] {
          let le = run(
            &y,
            &u,
            &v,
            8,
            8,
            4,
            4,
            ChromaLocation::BottomLeft,
            native,
            true,
          );
          assert_eq!(
            run_be(&y, &u, &v, 8, 8, 4, 4, ChromaLocation::BottomLeft, native),
            le,
            "BE bottom-left must equal LE (native={native})"
          );
          assert_eq!(
            run(
              &y,
              &u,
              &v,
              8,
              8,
              4,
              4,
              ChromaLocation::BottomLeft,
              native,
              false
            ),
            le,
            "bottom-left SIMD vs scalar must agree (native={native})"
          );
          assert_ne!(
            le,
            run(&y, &u, &v, 8, 8, 4, 4, ChromaLocation::Left, native, true),
            "bottom-left must differ from co-sited on a vertical ramp (native={native})"
          );
        }
        assert_eq!(
          run_filter(&y, &u, &v, 8, 8, 4, 4, ChromaLocation::BottomLeft, true),
          run_filter(&y, &u, &v, 8, 8, 4, 4, ChromaLocation::BottomLeft, false),
          "bottom-left filter SIMD vs scalar must agree"
        );
      }

      #[test]
      #[cfg_attr(miri, ignore = "SIMD row kernels use intrinsics unsupported by Miri")]
      fn bottomleft_differs_from_bottom_on_a_horizontal_ramp() {
        // Bottom (h=0.5) vs BottomLeft (h=0): identical vertical fold, differing
        // horizontal phase — visible only on a horizontally-varying ramp.
        let (y, u, v) = ramp(8, 8);
        for native in [true, false] {
          assert_ne!(
            run(
              &y,
              &u,
              &v,
              8,
              8,
              4,
              4,
              ChromaLocation::BottomLeft,
              native,
              true
            ),
            run(&y, &u, &v, 8, 8, 4, 4, ChromaLocation::Bottom, native, true),
            "bottom-left must differ from bottom on a horizontal ramp (native={native})"
          );
        }
      }

      #[test]
      #[cfg_attr(miri, ignore = "SIMD row kernels use intrinsics unsupported by Miri")]
      fn bottom_native_equals_code_domain_oracle() {
        for (sw, sh, ow, oh) in GEOMS {
          let (y, u, v) = vramp(sw, sh);
          let o = bottom_native_oracle(&y, &u, &v, sw, sh, ow, oh, true);
          assert_eq!(
            run(
              &y,
              &u,
              &v,
              sw,
              sh,
              ow,
              oh,
              ChromaLocation::Bottom,
              true,
              true
            ),
            o,
            "bottom native must equal the V-fold code-domain oracle \
             ({sw}x{sh}->{ow}x{oh})"
          );
        }
      }

      #[test]
      #[cfg_attr(miri, ignore = "SIMD row kernels use intrinsics unsupported by Miri")]
      fn bottom_row_stage_equals_rgb_reconstruct_then_bin() {
        for (sw, sh, ow, oh) in GEOMS {
          let (y, u, v) = vramp(sw, sh);
          let o = bottom_rgb_domain_oracle(&y, &u, &v, sw, sh, ow, oh, true, false);
          assert_eq!(
            run(
              &y,
              &u,
              &v,
              sw,
              sh,
              ow,
              oh,
              ChromaLocation::Bottom,
              false,
              true
            ),
            o,
            "bottom row-stage must equal the RGB-domain reconstruct-then-bin \
             oracle ({sw}x{sh}->{ow}x{oh})"
          );
        }
      }

      #[test]
      #[cfg_attr(miri, ignore = "SIMD row kernels use intrinsics unsupported by Miri")]
      fn bottom_filter_equals_rgb_reconstruct_then_bin() {
        for (sw, sh, ow, oh) in GEOMS {
          let (y, u, v) = vramp(sw, sh);
          let o = bottom_rgb_domain_oracle(&y, &u, &v, sw, sh, ow, oh, true, true);
          assert_eq!(
            run_filter(&y, &u, &v, sw, sh, ow, oh, ChromaLocation::Bottom, true),
            o,
            "bottom filter must equal the RGB-domain Triangle oracle \
             ({sw}x{sh}->{ow}x{oh})"
          );
        }
      }

      #[test]
      #[cfg_attr(miri, ignore = "SIMD row kernels use intrinsics unsupported by Miri")]
      fn bottom_simd_matches_scalar() {
        let (y, u, v) = vramp(8, 8);
        for native in [true, false] {
          assert_eq!(
            run(&y, &u, &v, 8, 8, 4, 4, ChromaLocation::Bottom, native, true),
            run(
              &y,
              &u,
              &v,
              8,
              8,
              4,
              4,
              ChromaLocation::Bottom,
              native,
              false
            ),
            "bottom SIMD vs scalar must agree (native={native})"
          );
        }
        assert_eq!(
          run_filter(&y, &u, &v, 8, 8, 4, 4, ChromaLocation::Bottom, true),
          run_filter(&y, &u, &v, 8, 8, 4, 4, ChromaLocation::Bottom, false),
          "bottom filter SIMD vs scalar must agree"
        );
      }

      #[test]
      #[cfg_attr(miri, ignore = "SIMD row kernels use intrinsics unsupported by Miri")]
      fn bottom_be_matches_le() {
        let (y, u, v) = vramp(8, 8);
        for native in [true, false] {
          assert_eq!(
            run_be(&y, &u, &v, 8, 8, 4, 4, ChromaLocation::Bottom, native),
            run(&y, &u, &v, 8, 8, 4, 4, ChromaLocation::Bottom, native, true),
            "BE bottom decode must equal LE (native={native})"
          );
        }
      }

      #[test]
      #[cfg_attr(miri, ignore = "SIMD row kernels use intrinsics unsupported by Miri")]
      fn bottom_differs_from_center_on_a_vertical_chroma_ramp() {
        let (y, u, v) = vramp(8, 8);
        for native in [true, false] {
          let cen = run(&y, &u, &v, 8, 8, 4, 4, ChromaLocation::Center, native, true);
          let bot = run(&y, &u, &v, 8, 8, 4, 4, ChromaLocation::Bottom, native, true);
          assert_ne!(
            cen, bot,
            "bottom must differ from center on a vertical chroma ramp (native={native})"
          );
        }
      }

      #[test]
      #[cfg_attr(miri, ignore = "SIMD row kernels use intrinsics unsupported by Miri")]
      fn bottom_equals_cosited_on_flat_chroma() {
        let (y, u, v) = flat(8, 8);
        for native in [true, false] {
          assert_eq!(
            run(&y, &u, &v, 8, 8, 4, 4, ChromaLocation::Left, native, true),
            run(&y, &u, &v, 8, 8, 4, 4, ChromaLocation::Bottom, native, true),
            "bottom must equal co-sited on flat chroma (native={native})"
          );
        }
      }

      #[test]
      #[cfg_attr(miri, ignore = "SIMD row kernels use intrinsics unsupported by Miri")]
      fn bottom_identity_resample_matches_direct_decode() {
        // Identity dims (ow=sw, oh=sh): the resample reconstructs full-width
        // chroma with the SAME bottom kernel as the direct (non-resample) decode
        // and bins with pass-through area weights, so routing Bottom through the
        // resample preserves the decode byte-for-byte.
        let (y, u, v) = vramp(8, 8);
        assert_eq!(
          run(&y, &u, &v, 8, 8, 8, 8, ChromaLocation::Bottom, false, true),
          direct_bottom(&y, &u, &v, 8, 8, true),
          "identity resample bottom == direct decode"
        );
      }

      // ---- top-sited (v = 0, FORWARD fold) resample ======================

      /// The top-sited NATIVE oracle: bin Y co-sited and U / V through the exact
      /// top V-fold oracle ([`bin_chroma_top_u16`]), then convert ONCE at output
      /// width via an identity `Yuv444pN` sink.
      #[allow(clippy::too_many_arguments)]
      fn top_native_oracle(
        y: &[u16],
        u: &[u16],
        v: &[u16],
        sw: usize,
        sh: usize,
        ow: usize,
        oh: usize,
        simd: bool,
      ) -> (Vec<u8>, Vec<u16>) {
        let (cw, ch) = (sw / 2, sh / 2);
        let yb = bin_cosited_u16(y, sw, sh, ow, oh);
        let ub = bin_chroma_top_u16(u, cw, ch, ow, oh);
        let vb = bin_chroma_top_u16(v, cw, ch, ow, oh);
        let mut rgb = vec![0u8; ow * oh * 3];
        let mut rgb16 = vec![0u16; ow * oh * 3];
        {
          let mut sink = MixedSinker::<$M444>::new(ow, oh)
            .with_simd(simd)
            .with_rgb(&mut rgb)
            .unwrap()
            .with_rgb_u16(&mut rgb16)
            .unwrap();
          let f = $F444::new(
            &yb, &ub, &vb, ow as u32, oh as u32, ow as u32, ow as u32, ow as u32,
          );
          $w444(&f, FR, sink.set_kernel_matrix(M)).unwrap();
        }
        (rgb, rgb16)
      }

      /// The top-sited RGB-domain oracle: reconstruct U / V to full width with the
      /// forward vertical blend ([`recon_full_chroma_top_u16`]) then run that
      /// `Yuv444pN` frame through the given resampler (convert-each-row-then-bin)
      /// — exactly what the row-stage / filter arms do for `Top`.
      #[allow(clippy::too_many_arguments)]
      fn top_rgb_domain_oracle(
        y: &[u16],
        u: &[u16],
        v: &[u16],
        sw: usize,
        sh: usize,
        ow: usize,
        oh: usize,
        simd: bool,
        filter: bool,
      ) -> (Vec<u8>, Vec<u16>) {
        let (uf, vf) = recon_full_chroma_top_u16(u, v, sw, sh);
        let mut rgb = vec![0u8; ow * oh * 3];
        let mut rgb16 = vec![0u16; ow * oh * 3];
        let f = $F444::new(
          y, &uf, &vf, sw as u32, sh as u32, sw as u32, sw as u32, sw as u32,
        );
        if filter {
          let mut sink = MixedSinker::<$M444, FilteredResampler<Triangle>>::with_resampler(
            sw,
            sh,
            FilteredResampler::new(ow, oh, Triangle),
          )
          .unwrap()
          .with_simd(simd)
          .with_rgb(&mut rgb)
          .unwrap()
          .with_rgb_u16(&mut rgb16)
          .unwrap();
          $w444(&f, FR, sink.set_kernel_matrix(M)).unwrap();
        } else {
          let mut sink =
            MixedSinker::<$M444, AreaResampler>::with_resampler(sw, sh, AreaResampler::to(ow, oh))
              .unwrap()
              .with_native(false)
              .with_simd(simd)
              .with_rgb(&mut rgb)
              .unwrap()
              .with_rgb_u16(&mut rgb16)
              .unwrap();
          $w444(&f, FR, sink.set_kernel_matrix(M)).unwrap();
        }
        (rgb, rgb16)
      }

      /// Direct (non-resample, identity dims) `Yuv420pN` `Top` decode — the
      /// forward-delay-line kernel path, the already-validated identity reference
      /// the resample path must match at identity dimensions.
      fn direct_top(
        y: &[u16],
        u: &[u16],
        v: &[u16],
        sw: usize,
        sh: usize,
        simd: bool,
      ) -> (Vec<u8>, Vec<u16>) {
        let cw = sw / 2;
        let mut rgb = vec![0u8; sw * sh * 3];
        let mut rgb16 = vec![0u16; sw * sh * 3];
        {
          let mut sink = MixedSinker::<$M420>::new(sw, sh)
            .with_chroma_location(ChromaLocation::Top)
            .with_simd(simd)
            .with_rgb(&mut rgb)
            .unwrap()
            .with_rgb_u16(&mut rgb16)
            .unwrap();
          let f = $F420::new(
            y, u, v, sw as u32, sh as u32, sw as u32, cw as u32, cw as u32,
          );
          $w420(&f, FR, sink.set_kernel_matrix(M)).unwrap();
        }
        (rgb, rgb16)
      }

      #[test]
      #[cfg_attr(miri, ignore = "SIMD row kernels use intrinsics unsupported by Miri")]
      fn top_native_equals_code_domain_oracle() {
        // Native folds the vertical v=0 FORWARD triangle into the chroma area
        // weights; its output is the EXACT code-domain box-average of the UNROUNDED
        // H⊗V reconstruction (single rounding). Includes ODD output heights so the
        // trailing-odd bottom-edge clamp is exercised.
        for (sw, sh, ow, oh) in GEOMS {
          let (y, u, v) = vramp(sw, sh);
          let o = top_native_oracle(&y, &u, &v, sw, sh, ow, oh, true);
          assert_eq!(
            run(&y, &u, &v, sw, sh, ow, oh, ChromaLocation::Top, true, true),
            o,
            "top native must equal the V-fold code-domain oracle ({sw}x{sh}->{ow}x{oh})"
          );
        }
      }

      #[test]
      #[cfg_attr(miri, ignore = "SIMD row kernels use intrinsics unsupported by Miri")]
      fn top_row_stage_equals_rgb_reconstruct_then_bin() {
        // The row-stage tier reconstructs full-width chroma with the FORWARD
        // one-row delay then bins in RGB — the reconstruct-then-bin oracle.
        for (sw, sh, ow, oh) in GEOMS {
          let (y, u, v) = vramp(sw, sh);
          let o = top_rgb_domain_oracle(&y, &u, &v, sw, sh, ow, oh, true, false);
          assert_eq!(
            run(&y, &u, &v, sw, sh, ow, oh, ChromaLocation::Top, false, true),
            o,
            "top row-stage must equal the RGB-domain reconstruct-then-bin oracle \
             ({sw}x{sh}->{ow}x{oh})"
          );
        }
      }

      #[test]
      #[cfg_attr(miri, ignore = "SIMD row kernels use intrinsics unsupported by Miri")]
      fn top_filter_equals_rgb_reconstruct_then_bin() {
        for (sw, sh, ow, oh) in GEOMS {
          let (y, u, v) = vramp(sw, sh);
          let o = top_rgb_domain_oracle(&y, &u, &v, sw, sh, ow, oh, true, true);
          assert_eq!(
            run_filter(&y, &u, &v, sw, sh, ow, oh, ChromaLocation::Top, true),
            o,
            "top filter must equal the RGB-domain Triangle oracle ({sw}x{sh}->{ow}x{oh})"
          );
        }
      }

      #[test]
      #[cfg_attr(miri, ignore = "SIMD row kernels use intrinsics unsupported by Miri")]
      fn top_all_tiers_simd_matches_scalar_and_be_matches_le() {
        let (y, u, v) = vramp(8, 8);
        for native in [true, false] {
          assert_eq!(
            run(&y, &u, &v, 8, 8, 4, 4, ChromaLocation::Top, native, true),
            run(&y, &u, &v, 8, 8, 4, 4, ChromaLocation::Top, native, false),
            "top SIMD vs scalar must agree (native={native})"
          );
          assert_eq!(
            run_be(&y, &u, &v, 8, 8, 4, 4, ChromaLocation::Top, native),
            run(&y, &u, &v, 8, 8, 4, 4, ChromaLocation::Top, native, true),
            "BE top decode must equal LE (native={native})"
          );
        }
        assert_eq!(
          run_filter(&y, &u, &v, 8, 8, 4, 4, ChromaLocation::Top, true),
          run_filter(&y, &u, &v, 8, 8, 4, 4, ChromaLocation::Top, false),
          "top filter SIMD vs scalar must agree"
        );
      }

      #[test]
      #[cfg_attr(miri, ignore = "SIMD row kernels use intrinsics unsupported by Miri")]
      fn top_identity_all_tiers_match_direct_decode() {
        // At identity dims every tier's kernel is pass-through, so native,
        // row-stage AND filter must ALL equal the direct forward-delay decode —
        // the cross-tier consistency bar. `vramp` makes the forward vertical fold
        // visibly move the delayed rows.
        let (y, u, v) = vramp(8, 8);
        let direct = direct_top(&y, &u, &v, 8, 8, true);
        assert_eq!(
          run(&y, &u, &v, 8, 8, 8, 8, ChromaLocation::Top, true, true),
          direct,
          "identity native top == direct decode"
        );
        assert_eq!(
          run(&y, &u, &v, 8, 8, 8, 8, ChromaLocation::Top, false, true),
          direct,
          "identity row-stage top == direct decode"
        );
        assert_eq!(
          run_filter(&y, &u, &v, 8, 8, 8, 8, ChromaLocation::Top, true),
          direct,
          "identity filter top == direct decode"
        );
      }

      #[test]
      #[cfg_attr(miri, ignore = "SIMD row kernels use intrinsics unsupported by Miri")]
      fn top_two_row_final_flush_odd_height_matches_direct_decode() {
        // ODD source height => the FINAL luma row is EVEN, so the reconstruction
        // tiers emit TWO output rows on that call (the held odd predecessor + the
        // last even row). At identity dims the row-stage AND filter resamples must
        // still equal the direct decode, proving the two-row final flush writes the
        // last two rows correctly. Non-vacuous: Top must differ from Center.
        for sh in [5usize, 7] {
          // ODD height: chroma has `ceil(sh / 2)` rows (`vramp` floors, so build
          // explicitly). A strong per-ROW chroma step so the forward vertical
          // blend visibly moves the delayed rows.
          let (sw, cw, ch) = (8usize, 4usize, sh.div_ceil(2));
          let y = vec![MID; sw * sh];
          let mut u = vec![0u16; cw * ch];
          let mut v = vec![0u16; cw * ch];
          let step = (MASK as u32 / 8).max(1);
          for r in 0..ch {
            for c in 0..cw {
              u[r * cw + c] = (step + r as u32 * step).min(MASK as u32) as u16;
              v[r * cw + c] = (MASK as u32).saturating_sub(r as u32 * step).max(step) as u16;
            }
          }
          let direct = direct_top(&y, &u, &v, sw, sh, true);
          assert_eq!(
            run(&y, &u, &v, sw, sh, sw, sh, ChromaLocation::Top, false, true),
            direct,
            "odd-height two-row final flush (row-stage) sh={sh}"
          );
          assert_eq!(
            run_filter(&y, &u, &v, sw, sh, sw, sh, ChromaLocation::Top, true),
            direct,
            "odd-height two-row final flush (filter) sh={sh}"
          );
          let center = run(
            &y,
            &u,
            &v,
            sw,
            sh,
            sw,
            sh,
            ChromaLocation::Center,
            false,
            true,
          );
          assert_ne!(
            direct.0, center.0,
            "top must fold vertically vs center sh={sh}"
          );
        }
      }

      #[test]
      #[cfg_attr(miri, ignore = "SIMD row kernels use intrinsics unsupported by Miri")]
      fn top_differs_from_bottom_and_center_and_equals_cosited_on_flat() {
        let (y, u, v) = vramp(8, 8);
        for native in [true, false] {
          let top = run(&y, &u, &v, 8, 8, 4, 4, ChromaLocation::Top, native, true);
          let bot = run(&y, &u, &v, 8, 8, 4, 4, ChromaLocation::Bottom, native, true);
          let cen = run(&y, &u, &v, 8, 8, 4, 4, ChromaLocation::Center, native, true);
          assert_ne!(top, cen, "top must differ from center (native={native})");
          assert_ne!(
            top, bot,
            "top (v=0) must differ from bottom (v=1) (native={native})"
          );
        }
        // On flat chroma the forward blend is inert, so Top == co-sited-h Center.
        let (y, u, v) = flat(8, 8);
        for native in [true, false] {
          assert_eq!(
            run(&y, &u, &v, 8, 8, 4, 4, ChromaLocation::Top, native, true),
            run(&y, &u, &v, 8, 8, 4, 4, ChromaLocation::Center, native, true),
            "top must equal centered-h on flat chroma (native={native})"
          );
        }
      }

      #[test]
      #[cfg_attr(miri, ignore = "SIMD row kernels use intrinsics unsupported by Miri")]
      fn topleft_differs_from_top_on_a_horizontal_ramp() {
        // TopLeft (h=0) rides the co-sited horizontal replicate; Top (h=0.5) the
        // centered triangle — so on a horizontal ramp they must diverge, while both
        // fold the same v=0 forward vertical phase.
        let (y, u, v) = ramp(8, 8);
        for native in [true, false] {
          assert_ne!(
            run(
              &y,
              &u,
              &v,
              8,
              8,
              4,
              4,
              ChromaLocation::TopLeft,
              native,
              true
            ),
            run(&y, &u, &v, 8, 8, 4, 4, ChromaLocation::Top, native, true),
            "TopLeft (h=0) must differ from Top (h=0.5) on a horizontal ramp (native={native})"
          );
          assert_eq!(
            run(
              &y,
              &u,
              &v,
              8,
              8,
              4,
              4,
              ChromaLocation::TopLeft,
              native,
              true
            ),
            run(
              &y,
              &u,
              &v,
              8,
              8,
              4,
              4,
              ChromaLocation::TopLeft,
              native,
              false
            ),
            "topleft SIMD vs scalar must agree (native={native})"
          );
        }
      }

      #[test]
      #[cfg_attr(miri, ignore = "SIMD row kernels use intrinsics unsupported by Miri")]
      fn bottom_final_even_row_reserve_alloc_failure_retries_with_blend() {
        // ODD source height => the FINAL luma row is EVEN, so its Bottom vertical
        // blend reads the PREDECESSOR chroma row. If the `chroma_prev` reserve
        // fails on that final row, the retry must STILL blend with the predecessor
        // (not clamp): the reconstruction reads the lookback only AFTER the
        // reserve, and the resample arms DEFER the stage until the commit accepts
        // the row (#180), so a rejected row leaves the lookback untouched.
        use super::super::MixedSinkerError;
        use crate::resample::ResampleError;
        let (sw, sh, ow, oh) = (8usize, 7usize, 4usize, 3usize);
        let cw = sw / 2;
        let ch = sh.div_ceil(2);
        let step = (MASK as u32 / 8).max(1);
        let y = vec![MID; sw * sh];
        let mut u = vec![0u16; cw * ch];
        let mut v = vec![0u16; cw * ch];
        for r in 0..ch {
          for c in 0..cw {
            u[r * cw + c] = (step + r as u32 * step).min(MASK as u32) as u16;
            v[r * cw + c] = (MASK as u32).saturating_sub(r as u32 * step).max(step) as u16;
          }
        }
        let run_frame = |arm_fail: bool, loc: ChromaLocation| -> Vec<u8> {
          let mut rgb = vec![0u8; ow * oh * 3];
          {
            let mut sink = MixedSinker::<$M420, AreaResampler>::with_resampler(
              sw,
              sh,
              AreaResampler::to(ow, oh),
            )
            .unwrap()
            .with_native(false)
            .with_chroma_location(loc.clone())
            .with_rgb(&mut rgb)
            .unwrap();
            sink.begin_frame(sw as u32, sh as u32).unwrap();
            let feed = |sink: &mut MixedSinker<'_, $M420, AreaResampler>, r: usize| {
              let yr = &y[r * sw..(r + 1) * sw];
              let cr = r / 2;
              let ur = &u[cr * cw..(cr + 1) * cw];
              let vr = &v[cr * cw..(cr + 1) * cw];
              sink.process($Row::for_tests(yr, ur, vr, r, M, FR))
            };
            for r in 0..sh - 1 {
              feed(&mut sink, r).unwrap();
            }
            if arm_fail {
              super::super::arm_chroma_prev_alloc_failure();
              let err = feed(&mut sink, sh - 1).unwrap_err();
              assert!(
                matches!(
                  err,
                  MixedSinkerError::Resample(ResampleError::AllocationFailed(_))
                ),
                "armed final-row chroma_prev reserve must surface AllocationFailed, got {err:?}"
              );
            }
            // Retry the SAME final row (the failpoint is one-shot, already taken).
            feed(&mut sink, sh - 1).unwrap();
          }
          rgb
        };
        let reference = run_frame(false, ChromaLocation::Bottom);
        let retried = run_frame(true, ChromaLocation::Bottom);
        assert_eq!(
          retried, reference,
          "the post-failure retry of the final EVEN row must blend with the predecessor (not clamp)"
        );
        // Non-vacuous: the bottom vertical blend genuinely moves the final even
        // row vs the vertically-co-sited Center decode.
        assert_ne!(
          reference,
          run_frame(false, ChromaLocation::Center),
          "the bottom vertical blend must move the final even row vs co-sited Center"
        );
      }

      #[test]
      #[cfg_attr(miri, ignore = "SIMD row kernels use intrinsics unsupported by Miri")]
      fn mid_frame_center_bottom_flip_rejected() {
        // Center and Bottom are BOTH horizontally centered, so the centered flag
        // alone cannot tell them apart; the frozen VERTICAL phase rejects the flip.
        let (y, u, v) = vramp(8, 8);
        for (loc1, loc2) in [
          (ChromaLocation::Center, ChromaLocation::Bottom),
          (ChromaLocation::Bottom, ChromaLocation::Center),
        ] {
          for native in [true, false] {
            let mut rgb = vec![0u8; 4 * 4 * 3];
            let sink =
              MixedSinker::<$M420, AreaResampler>::with_resampler(8, 8, AreaResampler::to(4, 4))
                .unwrap()
                .with_native(native)
                .with_rgb(&mut rgb)
                .unwrap();
            let err = flip_row1(sink, &y, &u, &v, loc1.clone(), loc2.clone()).unwrap_err();
            assert!(
              matches!(err, MixedSinkerError::ChromaSitingChanged(_)),
              "native={native} {loc1:?}->{loc2:?}: want ChromaSitingChanged, got {err:?}"
            );
          }
          let mut rgb = vec![0u8; 4 * 4 * 3];
          let sink = MixedSinker::<$M420, FilteredResampler<Triangle>>::with_resampler(
            8,
            8,
            FilteredResampler::new(4, 4, Triangle),
          )
          .unwrap()
          .with_rgb(&mut rgb)
          .unwrap();
          let err = flip_row1(sink, &y, &u, &v, loc1.clone(), loc2.clone()).unwrap_err();
          assert!(
            matches!(err, MixedSinkerError::ChromaSitingChanged(_)),
            "filter {loc1:?}->{loc2:?}: want ChromaSitingChanged, got {err:?}"
          );
        }
      }
    }
  };
}

hibit_420_resample_siting!(
  p10,
  10,
  Yuv420p10,
  Yuv420p10Frame,
  yuv420p10_to,
  Yuv420p10<true>,
  Yuv420p10BeFrame,
  yuv420p10_to_endian,
  Yuv444p10,
  Yuv444p10Frame,
  yuv444p10_to,
  Yuv420p10Row
);
hibit_420_resample_siting!(
  p12,
  12,
  Yuv420p12,
  Yuv420p12Frame,
  yuv420p12_to,
  Yuv420p12<true>,
  Yuv420p12BeFrame,
  yuv420p12_to_endian,
  Yuv444p12,
  Yuv444p12Frame,
  yuv444p12_to,
  Yuv420p12Row
);
hibit_420_resample_siting!(
  p16,
  16,
  Yuv420p16,
  Yuv420p16Frame,
  yuv420p16_to,
  Yuv420p16<true>,
  Yuv420p16BeFrame,
  yuv420p16_to_endian,
  Yuv444p16,
  Yuv444p16Frame,
  yuv444p16_to,
  Yuv420p16Row
);