oxideav-pixfmt 0.1.11

Pure-Rust pixel-format conversions, palette quantisation, and dithering — the oxideav framework's shared pixfmt layer
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
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
//! High-level `convert()` entry point.
//!
//! Every supported conversion flows through [`convert`], which dispatches
//! on `(src_info.format, dst_format)` to the appropriate helper in
//! [`crate::rgb`], [`crate::yuv`], [`crate::gray`], [`crate::palette`],
//! or [`crate::pal8`]. Anything that isn't wired up yet returns
//! `Error::Unsupported`.
//!
//! Stream-level properties (pixel format, width, height) live on the
//! caller's [`oxideav_core::CodecParameters`], not on the [`VideoFrame`]
//! itself, so every entry point takes them as an explicit
//! [`FrameInfo`] argument alongside the frame.

use oxideav_core::{
    ColorRange, ColorSignal, Error, ExecutionContext, MatrixCoefficients, PixelFormat, Result,
    VideoFrame, VideoPlane,
};

use crate::cmyk;
use crate::float;
use crate::gray;
use crate::pal8;
use crate::palette::Palette;
use crate::planar8::{self, chroma_dims, tight_plane, Packed8, Planar8};
use crate::rgb;
use crate::yuv::{self, YuvMatrix};

/// Stream-level metadata that used to live on `VideoFrame`. Threaded
/// through every conversion so the helpers know how to interpret the
/// raw plane bytes.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct FrameInfo {
    pub format: PixelFormat,
    pub width: u32,
    pub height: u32,
}

impl FrameInfo {
    pub const fn new(format: PixelFormat, width: u32, height: u32) -> Self {
        Self {
            format,
            width,
            height,
        }
    }
}

/// Dither strategy selected when down-quantising to a palette.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum Dither {
    #[default]
    None,
    Bayer8x8,
    FloydSteinberg,
}

/// YUV / RGB matrix selection.
///
/// BT.2020 variants implement the non-constant-luminance Y'CbCr matrix
/// from ITU-R BT.2020-2 Table 4 (kr=0.2627, kb=0.0593). The same
/// coefficients are reused by ITU-R BT.2100-3 Table 6 for HDR video.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum ColorSpace {
    #[default]
    Bt601Limited,
    Bt601Full,
    Bt709Limited,
    Bt709Full,
    Bt2020Limited,
    Bt2020Full,
}

/// Options bundle passed to [`convert`].
///
/// `color_space` selects the matrix **primaries** for every hop that
/// crosses between YUV and RGB / gray / float when nothing more
/// specific is known; whether the YUV samples are limited (studio) or
/// full range is a property of the pixel format (`Yuv*` limited,
/// `YuvJ*` full) and the range half of the variant is not consulted
/// for those hops. A colour signal — the source frame's
/// [`VideoFrame::color_signal`] record, or a caller override in
/// [`ConvertContext::signal`] passed to [`convert_with`] — takes
/// precedence over both; see [`convert_with`].
#[derive(Clone, Debug, Default)]
pub struct ConvertOptions {
    pub dither: Dither,
    pub palette: Option<Palette>,
    pub color_space: ColorSpace,
}

/// Per-call context for [`convert_with`]: the pieces of a conversion
/// request that [`ConvertOptions`] cannot carry without breaking the
/// callers that build it as a struct literal.
///
/// The struct is `#[non_exhaustive]`: build it with
/// [`ConvertContext::new`] / `Default` and set fields through the
/// builder methods (or by assignment on a mutable binding). New fields
/// can then be added without a semver break.
///
/// ```
/// use oxideav_core::{ColorRange, ExecutionContext, MatrixCoefficients};
/// use oxideav_pixfmt::ConvertContext;
///
/// // A full-range BT.709 4:2:0 + alpha payload (as a HEIF `nclx` box
/// // can declare), converted on up to four row bands in parallel.
/// let ctx = ConvertContext::new()
///     .with_range(ColorRange::Full)
///     .with_matrix(MatrixCoefficients::BT709)
///     .with_execution(ExecutionContext::with_threads(4));
/// assert_eq!(ctx.signal.range, ColorRange::Full);
/// assert_eq!(ctx.execution.threads, 4);
/// ```
#[derive(Clone, Debug, Default)]
#[non_exhaustive]
pub struct ConvertContext {
    /// Colour-signal override for the YUV side of the conversion. Every
    /// *specified* field wins over the source frame's
    /// [`VideoFrame::color_signal`] record, which in turn wins over the
    /// pixel-format label and [`ConvertOptions::color_space`]. The
    /// default (fully unspecified) changes nothing. Only `range` and
    /// `matrix` affect sample values; `primaries` / `transfer` are
    /// descriptive and ignored.
    pub signal: ColorSignal,
    /// Thread budget for the conversion, under oxideav-core's threading
    /// contract: the default [`ExecutionContext::serial`] runs on the
    /// caller's thread; `threads > 1` lets the row-band engine convert
    /// up to `effective_workers(bands)` bands on scoped threads that
    /// are joined before the call returns. The output is byte-identical
    /// whatever the budget.
    pub execution: ExecutionContext,
}

impl ConvertContext {
    /// The defaults: no signal override, serial execution.
    pub fn new() -> Self {
        Self::default()
    }

    /// Replace the whole colour-signal override.
    pub fn with_signal(mut self, signal: ColorSignal) -> Self {
        self.signal = signal;
        self
    }

    /// Override the YUV sample range (`ColorRange::Unspecified` restores
    /// "from the frame / format").
    pub fn with_range(mut self, range: ColorRange) -> Self {
        self.signal.range = range;
        self
    }

    /// Override the YUV ↔ RGB matrix (`MatrixCoefficients::UNSPECIFIED`
    /// restores "from the frame / options").
    pub fn with_matrix(mut self, matrix: MatrixCoefficients) -> Self {
        self.signal.matrix = matrix;
        self
    }

    /// Set the thread budget.
    pub fn with_execution(mut self, execution: ExecutionContext) -> Self {
        self.execution = execution;
        self
    }

    /// Shorthand for `with_execution(ExecutionContext::with_threads(n))`.
    pub fn with_threads(self, threads: usize) -> Self {
        self.with_execution(ExecutionContext::with_threads(threads))
    }
}

/// A conversion request with its colour signal resolved (context
/// override, then frame record, then format label / options).
struct Resolved {
    /// Range of the YUV side; `Unspecified` defers to each op's format
    /// label.
    range: ColorRange,
    /// `(K_R, K_B)` from a signalled matrix; `None` defers to
    /// `ConvertOptions::color_space`.
    kr_kb: Option<(f32, f32)>,
    execution: ExecutionContext,
}

impl Resolved {
    /// `true` when limited range applies to a YUV side whose format
    /// label pins `format_limited`.
    fn limited(&self, format_limited: bool) -> bool {
        match self.range {
            ColorRange::Limited => true,
            ColorRange::Full => false,
            _ => format_limited,
        }
    }

    /// Worker count for a picture of `h` rows: the execution budget
    /// clamped to the number of bands worth spawning.
    fn workers(&self, h: usize) -> usize {
        self.execution
            .effective_workers(h.div_ceil(planar8::MIN_BAND_ROWS))
    }

    /// The matrix weights (range still to be chosen per op).
    fn primaries(&self, opts: &ConvertOptions) -> YuvMatrix {
        match self.kr_kb {
            Some((kr, kb)) => YuvMatrix {
                kr,
                kb,
                limited: true,
            },
            None => YuvMatrix::from_color_space(opts.color_space),
        }
    }
}

/// `(K_R, K_B)` for an H.273 `MatrixCoefficients` code point (Table 4 of
/// `docs/video/signal-metadata/T-REC-H.273-202407-I.pdf`): `Ok(None)`
/// for unspecified (2), the weights for the equation 45–47 matrices this
/// crate implements (1, 4, 5, 6, 7, 9), and `Error::Unsupported` for the
/// rest (identity (0) is routed separately by the caller).
fn matrix_weights(m: MatrixCoefficients) -> Result<Option<(f32, f32)>> {
    Ok(Some(match m.code_point() {
        2 => return Ok(None),
        1 => (0.2126, 0.0722),
        4 => (0.30, 0.11),
        5 | 6 => (0.299, 0.114),
        7 => (0.212, 0.087),
        9 => (0.2627, 0.0593),
        _ => {
            return Err(Error::unsupported(format!(
                "pixfmt: matrix coefficients {} ({}) are not implemented",
                m.code_point(),
                m.name().unwrap_or("reserved")
            )))
        }
    }))
}

/// Return `Some(src)` when the caller's destination format already
/// matches the source's format — useful to skip a pointless clone in
/// hot paths.
pub fn convert_in_place_if_same(
    src: &VideoFrame,
    src_info: FrameInfo,
    dst_format: PixelFormat,
) -> Option<&VideoFrame> {
    if src_info.format == dst_format {
        Some(src)
    } else {
        None
    }
}

/// Convert `src` to `dst_format`, producing a newly allocated frame.
///
/// Dispatch first looks for a direct `(src, dst)` entry in the coverage
/// table. When none exists, a **single-pivot staged conversion** is
/// attempted: the frame is converted to one intermediate format and
/// then to the destination, with pivot candidates tried in a fixed
/// fidelity-aware order (YUV pivots first when both endpoints are YUV
/// carriage so no colour matrix enters the path; RGB pivots first
/// otherwise, alpha-capable before alpha-less, deep before 8-bit where
/// it matters). Staged paths are exactly as correct as their two legs —
/// but they can round twice and, when the pivot is 8-bit, quantise a
/// deeper source; callers that care can check [`supports_direct`].
///
/// # Per-plane significant-bits side-channel
///
/// A source frame may carry the per-plane significant-bits record
/// defined by [`oxideav_core::VideoFrame::significant_bits`] (one
/// LSB-anchored byte per image plane — e.g. `[12, 10, 10]` for 12-bit
/// luma with 10-bit chroma on a `Yuv444P12Le` or `Yuv444P16Le`
/// surface). `convert()` honours it with one policy:
///
/// - **Input**: every covered plane is treated as having exactly its
///   recorded significant depth. Before dispatch, marked planes are
///   *normalised* to the surface format's nominal depth by the
///   crate-wide MSB-replicating widen (full-scale at `b` bits maps to
///   full-scale at the nominal depth), so a record-carrying frame
///   converts exactly like the equivalent frame whose samples were
///   materialised at the nominal depth up front.
/// - **Validation**: a record value of `0`, or one *greater than the
///   surface format's nominal depth* (a significant-bits record can
///   only refine a format's depth downward), rejects with
///   `Error::Invalid`. Record bytes beyond the image-plane count are
///   ignored; a shorter record leaves the uncovered planes at the
///   nominal depth, per the core semantics.
/// - **Output**: converted frames are always produced at the
///   destination format's nominal depth and never carry a
///   significant-bits record — a stale record is never propagated. The
///   `src == dst` passthrough clone is the one exception: the frame is
///   untouched, so its record still describes it and rides along.
/// - **`Pal8`**: palette indices are identifiers, not magnitudes, so a
///   significant-bits record on a `Pal8` source is meaningless for
///   conversion and is ignored (the palette side-channel composes with
///   it and is honoured as usual).
pub fn convert(
    src: &VideoFrame,
    src_info: FrameInfo,
    dst_format: PixelFormat,
    opts: &ConvertOptions,
) -> Result<VideoFrame> {
    convert_with(src, src_info, dst_format, opts, &ConvertContext::default())
}

/// [`convert`] with a per-call [`ConvertContext`]: an explicit YUV
/// sample range and a thread budget. `convert(..)` is exactly
/// `convert_with(.., &ConvertContext::default())`.
///
/// # Odd dimensions
///
/// Subsampled layouts accept any width and height. A 4:2:0 / 4:2:2 /
/// 4:4:0 chroma plane holds `ceil(w / wsub)` × `ceil(h / hsub)` samples
/// — the component-dimension rule of ITU-T T.81 A.1.1
/// (`x_i = ceil(X · H_i / H_max)`) and the geometry
/// [`oxideav_core::PixelFormat::plane_dimensions`] reports. Decoding
/// maps luma `(col, row)` to chroma `(col / wsub, row / hsub)`, so the
/// trailing odd column / row reuses the last chroma sample; encoding
/// and chroma downsampling average each chroma block's luma positions
/// with the missing ones replicating the last column / row (equivalent
/// to padding the picture to even dimensions by edge replication before
/// subsampling). Even dimensions are unaffected. The staged signal
/// texts (H.273 §8.7, the BT-series 4:2:0 definitions) define chroma
/// sample *positions* for pictures whose luma dimensions are multiples
/// of the subsampling factors and say nothing about a trailing partial
/// block; replication is this crate's documented choice. `Yuv411P`
/// keeps requiring a width that is a multiple of 4, and the packed
/// `Yuyv422` / `Uyvy422` layouts keep requiring an even width.
pub fn convert_with(
    src: &VideoFrame,
    src_info: FrameInfo,
    dst_format: PixelFormat,
    opts: &ConvertOptions,
    ctx: &ConvertContext,
) -> Result<VideoFrame> {
    if src_info.format == dst_format {
        return Ok(src.clone());
    }
    // Materialise any significant-bits side-channel to the surface
    // format's nominal depth (see the rustdoc above) so every converter
    // below sees plain nominal-depth planes.
    let normalized = normalize_significant_bits(src, src_info)?;
    let src = normalized.as_ref().unwrap_or(src);

    // Resolve the colour signal. A frame's record describes its own
    // samples, so it is consulted only when the source is YUV carriage
    // (an RGB frame tagged e.g. sRGB / identity says nothing about the
    // YUV the caller is encoding to); the context override applies to
    // whichever side is YUV.
    let src_yuv = is_yuv_carriage(src_info.format);
    let dst_yuv = is_yuv_carriage(dst_format);
    let frame_signal = if src_yuv {
        src.color_signal().unwrap_or_default()
    } else {
        ColorSignal::unspecified()
    };
    let signal = ctx.signal.or(frame_signal);
    let crosses = src_yuv != dst_yuv;
    if crosses && signal.matrix == MatrixCoefficients::IDENTITY {
        return identity_route(src, src_info, dst_format, opts, signal.range, ctx);
    }
    let kr_kb = if crosses {
        matrix_weights(signal.matrix)?
    } else {
        None
    };
    let resolved = Resolved {
        range: signal.range,
        kr_kb,
        execution: ctx.execution.clone(),
    };

    if let Some(op) = lookup_any(src_info.format, dst_format) {
        return op.apply(src, src_info, opts, &resolved);
    }
    if let Some((first, pivot, second)) = lookup_staged(src_info.format, dst_format) {
        let mid = first.apply(src, src_info, opts, &resolved)?;
        let mid_info = FrameInfo::new(pivot, src_info.width, src_info.height);
        return second.apply(&mid, mid_info, opts, &resolved);
    }
    Err(Error::unsupported(format!(
        "pixfmt: conversion {:?} → {:?} not implemented",
        src_info.format, dst_format
    )))
}

/// H.273 `MatrixCoefficients == 0` (identity): the "YUV" planes carry
/// G, B, R directly (equations 48–50: `Y = G`, `Cb = B`, `Cr = R`),
/// with limited range scaling all three components like luma
/// (equations 27–29) and full range using the whole code space
/// (equations 33–35). The route relabels the planes as the planar GBR
/// member of the same depth and alpha — the `Gbrp*` / `Gbrap*` plane
/// order is exactly G, B, R(, A) — after bringing the source to 4:4:4
/// and rescaling a limited-range signal to full; the encode direction
/// mirrors it. Subsampled identity sources (legal but unusual) are
/// upsampled nearest-neighbour like any other 4:2:0 / 4:2:2 chroma.
fn identity_route(
    src: &VideoFrame,
    src_info: FrameInfo,
    dst_format: PixelFormat,
    opts: &ConvertOptions,
    range: ColorRange,
    ctx: &ConvertContext,
) -> Result<VideoFrame> {
    // The legs below are carriage moves / plain RGB conversions: no
    // signal, same thread budget.
    let plain = ConvertContext::new().with_execution(ctx.execution.clone());
    let (w, h) = (src_info.width, src_info.height);
    if is_yuv_carriage(src_info.format) {
        let (f444, bits, alpha, full_label) = identity_carrier(src_info.format);
        let mut p444 = if src_info.format == f444 {
            src.clone()
        } else {
            convert_with(src, src_info, f444, opts, &plain)?
        };
        let limited = match range {
            ColorRange::Limited => true,
            ColorRange::Full => false,
            _ => !full_label,
        };
        let gbr = gbr_member(bits, alpha);
        let planes = identity_planes(
            &mut p444, w as usize, h as usize, bits, alpha, limited, true,
        )?;
        let gbr_frame = make_frame(src, planes);
        if gbr == dst_format {
            return Ok(gbr_frame);
        }
        return convert_with(
            &gbr_frame,
            FrameInfo::new(gbr, w, h),
            dst_format,
            opts,
            &plain,
        );
    }
    let (f444, bits, alpha, full_label) = identity_carrier(dst_format);
    let gbr = gbr_member(bits, alpha);
    let mut g = if src_info.format == gbr {
        src.clone()
    } else {
        convert_with(src, src_info, gbr, opts, &plain)?
    };
    let limited = match range {
        ColorRange::Limited => true,
        ColorRange::Full => false,
        _ => !full_label,
    };
    let planes = identity_planes(&mut g, w as usize, h as usize, bits, alpha, limited, false)?;
    let yuv = make_frame(src, planes);
    if f444 == dst_format {
        return Ok(yuv);
    }
    convert_with(&yuv, FrameInfo::new(f444, w, h), dst_format, opts, &plain)
}

/// The 4:4:4 carrier an identity-coded YUV format is relabelled
/// through: `(format, bits, alpha, full_range_label)`.
fn identity_carrier(f: PixelFormat) -> (PixelFormat, u32, bool, bool) {
    use PixelFormat as P;
    match f {
        P::YuvJ420P | P::YuvJ422P | P::YuvJ444P => (P::YuvJ444P, 8, false, true),
        _ => match planar_yuv_desc(f) {
            Some(d) => {
                let member = match (d.bits, d.alpha) {
                    (8, false) => P::Yuv444P,
                    (8, true) => P::Yuva444P,
                    (10, false) => P::Yuv444P10Le,
                    (10, true) => P::Yuva444P10Le,
                    (12, false) => P::Yuv444P12Le,
                    (12, true) => P::Yuva444P12Le,
                    (_, false) => P::Yuv444P16Le,
                    (_, true) => P::Yuva444P16Le,
                };
                (member, d.bits, d.alpha, false)
            }
            // Semi-planar / packed / 4:1:1 carriage: 8-bit, no alpha.
            None => (P::Yuv444P, 8, false, false),
        },
    }
}

/// The planar GBR(A) member at `bits` depth.
fn gbr_member(bits: u32, alpha: bool) -> PixelFormat {
    use PixelFormat as P;
    match (bits, alpha) {
        (8, false) => P::Gbrp8,
        (8, true) => P::Gbrap8,
        (10, false) => P::Gbrp10Le,
        (10, true) => P::Gbrap10Le,
        (12, false) => P::Gbrp12Le,
        (12, true) => P::Gbrap12Le,
        (_, false) => P::Gbrp16Le,
        (_, true) => P::Gbrap16Le,
    }
}

/// Tight colour (+ alpha) planes of a 4:4:4 frame at `bits`, with the
/// three colour planes range-moved: limited → full when `to_rgb` (the
/// decode direction), full → limited otherwise, and untouched when
/// `limited` is false. Alpha is copied.
fn identity_planes(
    frame: &mut VideoFrame,
    w: usize,
    h: usize,
    bits: u32,
    alpha: bool,
    limited: bool,
    to_rgb: bool,
) -> Result<Vec<VideoPlane>> {
    let sb = if bits > 8 { 2 } else { 1 };
    let n = if alpha { 4 } else { 3 };
    if frame.planes.len() < n {
        return Err(Error::invalid(
            "pixfmt: identity-coded frame is missing planes",
        ));
    }
    let mut out = Vec::with_capacity(n);
    for i in 0..n {
        let mut data = tight_plane(&frame.planes[i], w * sb, h)?.into_owned();
        if limited && i < 3 {
            if to_rgb {
                range_limited_to_full(&mut data, bits);
            } else {
                range_full_to_limited(&mut data, bits);
            }
        }
        out.push(VideoPlane {
            stride: w * sb,
            data,
        });
    }
    Ok(out)
}

/// Per-process range tables for the deep luma moves, one per
/// `(bits, direction)`: index `bits * 2 + to_full`. Built lazily with
/// the exact rounded-division formulas below, so a table lookup is
/// sample-for-sample the same as the division it replaces (which at
/// 64 bits costs more than the rest of a luma row put together).
static RANGE_TABLES: [std::sync::OnceLock<Box<[u16]>>; 34] =
    [const { std::sync::OnceLock::new() }; 34];

/// The `(bits, to_full)` range table: `2^bits` entries mapping every
/// luma code of that width.
fn range_table(bits: u32, to_full: bool) -> &'static [u16] {
    debug_assert!((9..=16).contains(&bits));
    RANGE_TABLES[bits as usize * 2 + to_full as usize].get_or_init(|| {
        let s = 1i64 << (bits - 8);
        let max = (1i64 << bits) - 1;
        let den = 219 * s;
        (0..=max)
            .map(|v| {
                if to_full {
                    let num = (v - 16 * s) * max;
                    if num <= 0 {
                        0
                    } else {
                        ((num + den / 2) / den).min(max) as u16
                    }
                } else {
                    ((219 * s * v + 16 * s * max + max / 2) / max).min(max) as u16
                }
            })
            .collect()
    })
}

/// Limited → full range on a luma-like plane at `bits` (H.273
/// equations 27–29 inverted): `round((v − 16·2^(n−8)) · (2^n − 1) /
/// (219·2^(n−8)))`, clamped. The 8-bit case is the crate's existing Q15
/// luma rescale; the deep widths go through [`range_table`].
fn range_limited_to_full(plane: &mut [u8], bits: u32) {
    if bits <= 8 {
        yuv::limited_to_full_luma(plane);
        return;
    }
    let table = range_table(bits, true);
    let mask = ((1u32 << bits) - 1) as u16;
    for word in plane.chunks_exact_mut(2) {
        let v = u16::from_le_bytes([word[0], word[1]]) & mask;
        word.copy_from_slice(&table[v as usize].to_le_bytes());
    }
}

/// Full → limited range on a luma-like plane at `bits` (H.273
/// equations 27–29): `round((219 · v / (2^n − 1) + 16) · 2^(n−8))`.
/// The 8-bit case is the crate's existing Q15 luma rescale; the deep
/// widths go through [`range_table`].
fn range_full_to_limited(plane: &mut [u8], bits: u32) {
    if bits <= 8 {
        yuv::full_to_limited_luma(plane);
        return;
    }
    let table = range_table(bits, false);
    let mask = ((1u32 << bits) - 1) as u16;
    for word in plane.chunks_exact_mut(2) {
        let v = u16::from_le_bytes([word[0], word[1]]) & mask;
        word.copy_from_slice(&table[v as usize].to_le_bytes());
    }
}

/// Widen an LSB-anchored `from`-bit value to `to` bits by repeating its
/// bit pattern into the freed low bits (full MSB replication). Zero
/// maps to zero, full-scale maps to full-scale, and the mapping is
/// strictly monotonic — the same rule as the crate's depth ladder,
/// generalised to widths below 8 bits (where the fill can be wider than
/// the source and the pattern repeats more than once).
fn widen_bits(v: u32, from: u32, to: u32) -> u32 {
    let mut out = v << (to - from);
    let mut fill = to - from;
    while fill > 0 {
        let take = fill.min(from);
        out |= (v >> (from - take)) << (fill - take);
        fill -= take;
    }
    out
}

/// Materialise a source frame's per-plane significant-bits side-channel
/// (see the policy on [`convert`]): validate the record against the
/// surface format and, when any covered plane is marked shallower than
/// the format's nominal depth, return a copy with those planes widened
/// (MSB replication) to the nominal depth and no side-channel records.
/// Returns `Ok(None)` when no work is needed (no record, an all-nominal
/// record, or a `Pal8` source, whose record is ignored).
fn normalize_significant_bits(src: &VideoFrame, src_info: FrameInfo) -> Result<Option<VideoFrame>> {
    let Some(record) = src.significant_bits() else {
        return Ok(None);
    };
    let fmt = src_info.format;
    // Palette indices are identifiers, not magnitudes — a record on a
    // Pal8 frame carries no meaning for conversion.
    if fmt == PixelFormat::Pal8 {
        return Ok(None);
    }
    // Float surfaces have no integer depth for a record to refine —
    // binary32 samples are magnitudes already — so a record there is
    // likewise ignored rather than interpreted as a word width.
    if fmt.is_float() {
        return Ok(None);
    }
    let nominal = crate::format_info::FormatInfo::of(fmt).bit_depth as u32;
    let plane_count = src.image_plane_count();
    // Validate the covered planes; bytes beyond the image-plane count
    // are ignored (the record is defined per image plane).
    let mut needs_work = false;
    for (i, &b) in record.iter().take(plane_count).enumerate() {
        let b = b as u32;
        if b == 0 || b > nominal {
            return Err(Error::invalid(format!(
                "pixfmt: significant-bits record byte {i} = {b} out of range 1..={nominal} for {fmt:?}"
            )));
        }
        if b < nominal {
            needs_work = true;
        }
    }
    if !needs_work {
        return Ok(None);
    }
    // `needs_work` implies nominal > 1, so this is a byte-sample or
    // LE16-word format (Mono's nominal of 1 pins every record value to
    // 1). Widen each marked plane in place on a copy; padding bytes
    // beyond the tight row width are widened too, harmlessly — no
    // converter reads them.
    let wide_words = nominal > 8;
    let mut planes = Vec::with_capacity(plane_count);
    for (i, plane) in src.image_planes().iter().enumerate() {
        let b = record.get(i).map(|&b| b as u32).unwrap_or(nominal);
        let mut data = plane.data.clone();
        if b < nominal {
            if wide_words {
                let mask = (1u32 << b) - 1;
                for word in data.chunks_exact_mut(2) {
                    let v = u16::from_le_bytes([word[0], word[1]]) as u32 & mask;
                    let out = widen_bits(v, b, nominal) as u16;
                    word.copy_from_slice(&out.to_le_bytes());
                }
            } else {
                let mask = (1u32 << b) - 1;
                for byte in data.iter_mut() {
                    let v = *byte as u32 & mask;
                    *byte = widen_bits(v, b, 8) as u8;
                }
            }
        }
        planes.push(VideoPlane {
            stride: plane.stride,
            data,
        });
    }
    Ok(Some(VideoFrame {
        pts: src.pts,
        planes,
    }))
}

/// True when `convert()` can carry out `src → dst` — directly or via a
/// single staged pivot. `src == dst` is always supported (passthrough).
pub fn supports(src: PixelFormat, dst: PixelFormat) -> bool {
    src == dst || lookup_any(src, dst).is_some() || lookup_staged(src, dst).is_some()
}

/// True when a *direct* (single-step) conversion exists for `src → dst`
/// — either an explicit coverage-table entry or a computed planar-family
/// op — i.e. `convert()` will not stage through an intermediate format.
/// `src == dst` counts as direct.
pub fn supports_direct(src: PixelFormat, dst: PixelFormat) -> bool {
    src == dst || lookup_any(src, dst).is_some()
}

/// The intermediate format `convert()` stages `src → dst` through, or
/// `None` when the pair converts directly (including `src == dst`) or
/// is not supported at all. The planner is deterministic, so this is
/// exactly the route a `convert()` call takes; it is what the
/// route-depth audit in the test suite inspects (every intermediate
/// must carry at least `min(src, dst)` bits per channel when both
/// endpoints are deeper than 8 bits, keep alpha when both endpoints
/// have it, and never be a palette).
pub fn staged_pivot(src: PixelFormat, dst: PixelFormat) -> Option<PixelFormat> {
    if supports_direct(src, dst) {
        return None;
    }
    lookup_staged(src, dst).map(|(_, pivot, _)| pivot)
}

/// Pivot preference for staged conversions. YUV carriage pivots keep
/// YUV → YUV moves free of any colour matrix; the RGB list is ordered
/// alpha-capable first (so alpha survives whenever both endpoints carry
/// it) and deep before nothing-deeper-available. `Gray8` rescues the
/// mono / gray ladders.
const YUV_PIVOTS: &[PixelFormat] = &[
    PixelFormat::Yuv444P,
    PixelFormat::Yuv422P,
    PixelFormat::Yuv420P,
];
/// YUV pivot order used when either endpoint carries more than 8
/// significant bits: the 16-bit planar tier comes first so a deep
/// YUV → YUV staged route (e.g. `Yuv420P16Le → Yuv422P`) resamples
/// chroma at full 16-bit precision and only quantises at the final leg,
/// instead of truncating to 8 bits before the resample. The
/// alpha-carrying 16-bit members lead the list: they are the only
/// pivots whose second leg reaches `Rgba64Le` through the deep matrix
/// with the alpha plane intact, so e.g. `Yuva420P10Le → Rgba64Le`
/// stages through `Yuva444P16Le` (exact alpha widen + full-precision
/// colour) rather than quantising alpha through an 8-bit `Rgba` hop.
const YUV_PIVOTS_DEEP: &[PixelFormat] = &[
    PixelFormat::Yuva444P16Le,
    PixelFormat::Yuva422P16Le,
    PixelFormat::Yuva420P16Le,
    PixelFormat::Yuv444P16Le,
    PixelFormat::Yuv422P16Le,
    PixelFormat::Yuv420P16Le,
    PixelFormat::Yuv444P,
    PixelFormat::Yuv422P,
    PixelFormat::Yuv420P,
];
const RGB_PIVOTS: &[PixelFormat] = &[
    PixelFormat::Rgba,
    PixelFormat::Rgb24,
    PixelFormat::Rgb48Le,
    PixelFormat::Rgba64Le,
    PixelFormat::Gray8,
];
/// RGB pivot order used when either endpoint carries more than 8
/// significant bits: the deep packed pivots come first so a
/// deep → deep staged route (e.g. `Gbrp10Le → Gbrp12Le`) never
/// quantises through an 8-bit intermediate when a lossless deep hop
/// exists.
const RGB_PIVOTS_DEEP: &[PixelFormat] = &[
    PixelFormat::Rgba64Le,
    PixelFormat::Rgb48Le,
    PixelFormat::Rgba,
    PixelFormat::Rgb24,
    PixelFormat::Gray8,
];
/// The deep pivot orders when **neither** endpoint carries alpha: the
/// alpha-less members lead, so a `Gbrp10Le → Yuv420P10Le` move pivots
/// through the three-plane `Rgb48Le` rather than synthesising and
/// dropping an opaque fourth plane / word. Same bytes as the
/// alpha-first order (the synthesised alpha never reaches the output).
const YUV_PIVOTS_DEEP_NO_ALPHA: &[PixelFormat] = &[
    PixelFormat::Yuv444P16Le,
    PixelFormat::Yuv422P16Le,
    PixelFormat::Yuv420P16Le,
    PixelFormat::Yuva444P16Le,
    PixelFormat::Yuva422P16Le,
    PixelFormat::Yuva420P16Le,
    PixelFormat::Yuv444P,
    PixelFormat::Yuv422P,
    PixelFormat::Yuv420P,
];
const RGB_PIVOTS_DEEP_NO_ALPHA: &[PixelFormat] = &[
    PixelFormat::Rgb48Le,
    PixelFormat::Rgba64Le,
    PixelFormat::Rgba,
    PixelFormat::Rgb24,
    PixelFormat::Gray8,
];

/// True for formats whose samples are YUV carriage (planar, semi-planar
/// or packed, any range or depth) — used to prefer matrix-free pivots.
fn is_yuv_carriage(f: PixelFormat) -> bool {
    use PixelFormat as P;
    matches!(
        f,
        P::Yuv420P
            | P::Yuv422P
            | P::Yuv444P
            | P::Yuv411P
            | P::Yuv420P10Le
            | P::Yuv422P10Le
            | P::Yuv444P10Le
            | P::Yuv420P12Le
            | P::Yuv422P12Le
            | P::Yuv444P12Le
            | P::Yuv420P16Le
            | P::Yuv422P16Le
            | P::Yuv444P16Le
            | P::YuvJ420P
            | P::YuvJ422P
            | P::YuvJ444P
            | P::Nv12
            | P::Nv21
            | P::Yuva420P
            | P::Yuva422P
            | P::Yuva444P
            | P::Yuva422P10Le
            | P::Yuva422P12Le
            | P::Yuva422P16Le
            | P::Yuva444P10Le
            | P::Yuva444P12Le
            | P::Yuva444P16Le
            | P::Yuva420P10Le
            | P::Yuva420P12Le
            | P::Yuva420P16Le
            | P::Yuyv422
            | P::Uyvy422
            | P::Yuv440P
            | P::Yuv440P10Le
            | P::Yuv440P12Le
            | P::Yuv440P16Le
    )
}

/// Layout descriptor for the *uniform planar YUV(A) family*: 3 planes
/// (Y, U, V) — or 4 with a full-resolution alpha plane — at 4:2:0 /
/// 4:2:2 / 4:4:4 / 4:4:0 chroma siting, every sample either one byte
/// (`bits == 8`) or a 16-bit LE word carrying `bits` significant low
/// bits (10 / 12 / 16), limited-range carriage.
///
/// Formats matching this shape are handled by a *computed* dispatch
/// tier (see [`lookup_computed`]) that generates the conversion
/// parametrically instead of enumerating hundreds of table rows: any
/// ordered pair inside the family (depth move + chroma resample +
/// alpha drop / carry / synthesis fused in one step), plus
/// `Rgb24` / `Rgba` / `Gray8` interop. Full-range `YuvJ*`, 4:1:1,
/// semi-planar NV and packed 4:2:2 layouts are deliberately *not* part
/// of the family — their extra semantics (range rescale, 4× siting,
/// interleaving) stay on the explicit table rows.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct PlanarYuv {
    /// Chroma horizontal subsample factor (1 or 2).
    wsub: usize,
    /// Chroma vertical subsample factor (1 or 2). `(wsub, hsub) ==
    /// (1, 2)` is the 4:4:0 siting — full-width, half-height chroma.
    hsub: usize,
    /// Significant bits per sample: 8 (byte storage) or 10 / 12 / 16
    /// (16-bit LE word storage).
    bits: u32,
    /// Whether a full-resolution alpha plane trails as plane 3, stored
    /// at the same depth as the colour planes.
    alpha: bool,
}

impl PlanarYuv {
    /// Bytes per sample word (1 for 8-bit storage, 2 for LE-16).
    const fn sample_bytes(&self) -> usize {
        if self.bits > 8 {
            2
        } else {
            1
        }
    }
}

/// The [`PlanarYuv`] descriptor for `f`, or `None` when `f` is not a
/// member of the uniform planar family.
fn planar_yuv_desc(f: PixelFormat) -> Option<PlanarYuv> {
    use PixelFormat as P;
    let (wsub, hsub, bits, alpha) = match f {
        P::Yuv420P => (2, 2, 8, false),
        P::Yuv422P => (2, 1, 8, false),
        P::Yuv444P => (1, 1, 8, false),
        P::Yuv420P10Le => (2, 2, 10, false),
        P::Yuv422P10Le => (2, 1, 10, false),
        P::Yuv444P10Le => (1, 1, 10, false),
        P::Yuv420P12Le => (2, 2, 12, false),
        P::Yuv422P12Le => (2, 1, 12, false),
        P::Yuv444P12Le => (1, 1, 12, false),
        P::Yuv420P16Le => (2, 2, 16, false),
        P::Yuv422P16Le => (2, 1, 16, false),
        P::Yuv444P16Le => (1, 1, 16, false),
        P::Yuva420P => (2, 2, 8, true),
        P::Yuva422P => (2, 1, 8, true),
        P::Yuva444P => (1, 1, 8, true),
        P::Yuva422P10Le => (2, 1, 10, true),
        P::Yuva422P12Le => (2, 1, 12, true),
        P::Yuva422P16Le => (2, 1, 16, true),
        P::Yuva444P10Le => (1, 1, 10, true),
        P::Yuva444P12Le => (1, 1, 12, true),
        P::Yuva444P16Le => (1, 1, 16, true),
        P::Yuva420P10Le => (2, 2, 10, true),
        P::Yuva420P12Le => (2, 2, 12, true),
        P::Yuva420P16Le => (2, 2, 16, true),
        // 4:4:0 (core 0.1.35): full-width, half-height chroma — the
        // transpose of 4:2:2. No alpha-carrying member exists.
        P::Yuv440P => (1, 2, 8, false),
        P::Yuv440P10Le => (1, 2, 10, false),
        P::Yuv440P12Le => (1, 2, 12, false),
        P::Yuv440P16Le => (1, 2, 16, false),
        _ => return None,
    };
    Some(PlanarYuv {
        wsub,
        hsub,
        bits,
        alpha,
    })
}

/// Component layout of a scene-referred float family member (core
/// 0.1.35). Every sample is a binary32 LE word; see [`crate::float`]
/// for the value semantics.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum FloatLayout {
    /// `GrayF32Le`: one packed plane, one word per pixel.
    Gray,
    /// `RgbF32Le`: one packed plane, R, G, B words per pixel.
    Rgb,
    /// `RgbaF32Le`: one packed plane, R, G, B, A words per pixel.
    Rgba,
    /// `GbrpF32Le`: three planes ordered G, B, R.
    Gbrp,
    /// `GbrapF32Le`: four planes ordered G, B, R, A.
    Gbrap,
}

impl FloatLayout {
    const fn has_alpha(self) -> bool {
        matches!(self, Self::Rgba | Self::Gbrap)
    }
    const fn is_planar(self) -> bool {
        matches!(self, Self::Gbrp | Self::Gbrap)
    }
    /// Words per pixel of the packed plane (planar layouts: per plane).
    const fn packed_words(self) -> usize {
        match self {
            Self::Gray => 1,
            Self::Rgb => 3,
            Self::Rgba => 4,
            Self::Gbrp | Self::Gbrap => 1,
        }
    }
    const fn plane_count(self) -> usize {
        match self {
            Self::Gbrp => 3,
            Self::Gbrap => 4,
            _ => 1,
        }
    }
}

fn float_layout(f: PixelFormat) -> Option<FloatLayout> {
    use PixelFormat as P;
    Some(match f {
        P::GrayF32Le => FloatLayout::Gray,
        P::RgbF32Le => FloatLayout::Rgb,
        P::RgbaF32Le => FloatLayout::Rgba,
        P::GbrpF32Le => FloatLayout::Gbrp,
        P::GbrapF32Le => FloatLayout::Gbrap,
        _ => return None,
    })
}

/// Shape of an integer format the float family converts to and from
/// directly: packed gray, packed RGB(A) in canonical R, G, B(, A)
/// order, or planar GBR(A).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum IntShape {
    Gray,
    PackedRgb,
    PlanarGbr,
}

/// Integer-side descriptor for the float ↔ integer computed rows:
/// `bits` significant bits per sample (byte storage at 8, LE-16 words
/// otherwise), with or without alpha.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct IntLayout {
    shape: IntShape,
    bits: u32,
    alpha: bool,
}

impl IntLayout {
    const fn sample_bytes(&self) -> usize {
        if self.bits > 8 {
            2
        } else {
            1
        }
    }
    const fn comps(&self) -> usize {
        match (self.shape, self.alpha) {
            (IntShape::Gray, _) => 1,
            (IntShape::PackedRgb, false) => 3,
            (IntShape::PackedRgb, true) => 4,
            (IntShape::PlanarGbr, _) => 1,
        }
    }
    const fn plane_count(&self) -> usize {
        match (self.shape, self.alpha) {
            (IntShape::PlanarGbr, false) => 3,
            (IntShape::PlanarGbr, true) => 4,
            _ => 1,
        }
    }
}

fn int_layout(f: PixelFormat) -> Option<IntLayout> {
    use PixelFormat as P;
    let (shape, bits, alpha) = match f {
        P::Gray8 => (IntShape::Gray, 8, false),
        P::Gray10Le => (IntShape::Gray, 10, false),
        P::Gray12Le => (IntShape::Gray, 12, false),
        P::Gray16Le => (IntShape::Gray, 16, false),
        P::Rgb24 => (IntShape::PackedRgb, 8, false),
        P::Rgba => (IntShape::PackedRgb, 8, true),
        P::Rgb48Le => (IntShape::PackedRgb, 16, false),
        P::Rgba64Le => (IntShape::PackedRgb, 16, true),
        P::Gbrp8 => (IntShape::PlanarGbr, 8, false),
        P::Gbrap8 => (IntShape::PlanarGbr, 8, true),
        P::Gbrp10Le => (IntShape::PlanarGbr, 10, false),
        P::Gbrap10Le => (IntShape::PlanarGbr, 10, true),
        P::Gbrp12Le => (IntShape::PlanarGbr, 12, false),
        P::Gbrap12Le => (IntShape::PlanarGbr, 12, true),
        P::Gbrp14Le => (IntShape::PlanarGbr, 14, false),
        P::Gbrap14Le => (IntShape::PlanarGbr, 14, true),
        P::Gbrp16Le => (IntShape::PlanarGbr, 16, false),
        P::Gbrap16Le => (IntShape::PlanarGbr, 16, true),
        _ => return None,
    };
    Some(IntLayout { shape, bits, alpha })
}

/// Computed dispatch tier: conversions derived from the [`PlanarYuv`]
/// family descriptors rather than enumerated as table rows. Consulted
/// only when [`lookup`] has no explicit entry, so every pair the table
/// names keeps its exact historical behaviour. A computed op is still a
/// *direct* (single-step) conversion for [`supports_direct`] purposes.
fn lookup_computed(src: PixelFormat, dst: PixelFormat) -> Option<ConvertOp> {
    use PixelFormat as P;
    // Scene-referred float family (core 0.1.35): float ↔ float, float ↔
    // the integer gray / packed RGB / planar GBR(A) shapes, and float ↔
    // the 16-bit planar YUV(A) tier (full-precision deep matrix).
    if let Some(fs) = float_layout(src) {
        if let Some(fd) = float_layout(dst) {
            return Some(ConvertOp::FloatToFloat { src: fs, dst: fd });
        }
        if let Some(il) = int_layout(dst) {
            return Some(ConvertOp::FloatToInt { src: fs, dst: il });
        }
        return match planar_yuv_desc(dst) {
            Some(d) if d.bits == 16 => Some(ConvertOp::FloatToDeepYuv { src: fs, dst: d }),
            _ => None,
        };
    }
    if let Some(fd) = float_layout(dst) {
        if let Some(il) = int_layout(src) {
            return Some(ConvertOp::IntToFloat { src: il, dst: fd });
        }
        return match planar_yuv_desc(src) {
            Some(s) if s.bits == 16 => Some(ConvertOp::DeepYuvToFloat { src: s, dst: fd }),
            _ => None,
        };
    }
    match (planar_yuv_desc(src), planar_yuv_desc(dst)) {
        // Anywhere-to-anywhere inside the planar family: depth move,
        // chroma resample and alpha handling fused into one step (the
        // chroma pair is resampled at the deeper of the two depths).
        (Some(s), Some(d)) => Some(ConvertOp::PlanarFamily { src: s, dst: d }),
        // Family member → packed RGB / Gray8.
        (Some(s), None) => match dst {
            P::Rgba => Some(ConvertOp::PlanarFamilyToRgb {
                src: s,
                alpha: true,
            }),
            P::Rgb24 => Some(ConvertOp::PlanarFamilyToRgb {
                src: s,
                alpha: false,
            }),
            P::Gray8 => Some(ConvertOp::PlanarFamilyToGray { src: s }),
            // Deep grey words via the luma plane, at every family depth.
            P::Gray10Le | P::Gray12Le | P::Gray16Le => Some(ConvertOp::PlanarFamilyToDeepGray {
                src: s,
                bits: deep_gray_bits(dst),
            }),
            P::Rgb48Le => Some(ConvertOp::FamilyToPacked16 {
                src: s,
                alpha: false,
            }),
            P::Rgba64Le => Some(ConvertOp::FamilyToPacked16 {
                src: s,
                alpha: true,
            }),
            _ => None,
        },
        // Packed RGB / Gray8 → family member.
        (None, Some(d)) => match src {
            P::Rgba => Some(ConvertOp::RgbToPlanarFamily {
                dst: d,
                alpha_in: true,
            }),
            P::Rgb24 => Some(ConvertOp::RgbToPlanarFamily {
                dst: d,
                alpha_in: false,
            }),
            P::Gray8 => Some(ConvertOp::GrayToPlanarFamily { dst: d }),
            P::Gray10Le | P::Gray12Le | P::Gray16Le => Some(ConvertOp::DeepGrayToPlanarFamily {
                bits: deep_gray_bits(src),
                dst: d,
            }),
            P::Rgb48Le => Some(ConvertOp::Packed16ToFamily {
                dst: d,
                alpha_in: false,
            }),
            P::Rgba64Le => Some(ConvertOp::Packed16ToFamily {
                dst: d,
                alpha_in: true,
            }),
            _ => None,
        },
        // Planar GBR(A) ↔ the deep grey words (the `Gray8` rows are
        // explicit table entries and take precedence).
        (None, None) => match (int_layout(src), int_layout(dst)) {
            (Some(il), _) if il.shape == IntShape::PlanarGbr => match dst {
                P::Gray10Le | P::Gray12Le | P::Gray16Le => Some(ConvertOp::GbrToDeepGray {
                    src: il,
                    bits: deep_gray_bits(dst),
                }),
                _ => None,
            },
            (_, Some(il)) if il.shape == IntShape::PlanarGbr => match src {
                P::Gray10Le | P::Gray12Le | P::Gray16Le => Some(ConvertOp::DeepGrayToGbr {
                    bits: deep_gray_bits(src),
                    dst: il,
                }),
                _ => None,
            },
            _ => None,
        },
    }
}

/// Single-step lookup across both dispatch tiers: the explicit coverage
/// table first (exact historical behaviour), then the computed planar
/// family tier.
fn lookup_any(src: PixelFormat, dst: PixelFormat) -> Option<ConvertOp> {
    lookup(src, dst)
        .copied()
        .or_else(|| lookup_computed(src, dst))
}

/// Find a single-pivot staged route `src → pivot → dst` where both legs
/// are direct (table or computed) ops. Returns the two ops and the
/// pivot format.
fn lookup_staged(
    src: PixelFormat,
    dst: PixelFormat,
) -> Option<(ConvertOp, PixelFormat, ConvertOp)> {
    let yuv_first = is_yuv_carriage(src) && is_yuv_carriage(dst);
    let deep = crate::format_info::FormatInfo::of(src).bit_depth > 8
        || crate::format_info::FormatInfo::of(dst).bit_depth > 8;
    let no_alpha = !crate::format_info::FormatInfo::of(src).has_alpha
        && !crate::format_info::FormatInfo::of(dst).has_alpha;
    let rgb_pivots = match (deep, no_alpha) {
        (true, true) => RGB_PIVOTS_DEEP_NO_ALPHA,
        (true, false) => RGB_PIVOTS_DEEP,
        (false, _) => RGB_PIVOTS,
    };
    let yuv_pivots = match (deep, no_alpha) {
        (true, true) => YUV_PIVOTS_DEEP_NO_ALPHA,
        (true, false) => YUV_PIVOTS_DEEP,
        (false, _) => YUV_PIVOTS,
    };
    // Deep moves with a YUV endpoint also try the YUV pivots first:
    // the 16-bit planar tier now has direct full-precision hops to the
    // packed deep RGB formats, so e.g. `Yuv444P10Le → Rgb48Le` should
    // stage through the exact widen to `Yuv444P16Le` and the deep
    // matrix rather than quantise through an 8-bit RGB pivot. Pairs
    // with no YUV-pivot route fall through to the RGB list exactly as
    // before.
    let (a, b) = if yuv_first || (deep && (is_yuv_carriage(src) || is_yuv_carriage(dst))) {
        (yuv_pivots, rgb_pivots)
    } else {
        (rgb_pivots, yuv_pivots)
    };
    for &pivot in a.iter().chain(b.iter()) {
        if pivot == src || pivot == dst {
            continue;
        }
        if let (Some(first), Some(second)) = (lookup_any(src, pivot), lookup_any(pivot, dst)) {
            return Some((first, pivot, second));
        }
    }
    None
}

/// Coverage table — one entry per supported `(src, dst)` pair. The
/// associated [`ConvertOp`] captures any variant-specific parameters
/// (RGB byte positions, chroma subsampling, range direction, …) so the
/// dispatch below is a short match over ~20 arms instead of a 68-arm
/// cross-product.
#[rustfmt::skip]
const TABLE: &[(PixelFormat, PixelFormat, ConvertOp)] = {
    use ConvertOp::*;
    use PixelFormat as P;
    &[
        // RGB family: all-to-all packed swizzles.
        (P::Rgb24, P::Bgr24, Swizzle3 { src: rgb::RGB_POS, dst: rgb::BGR_POS }),
        (P::Bgr24, P::Rgb24, Swizzle3 { src: rgb::BGR_POS, dst: rgb::RGB_POS }),
        (P::Rgba, P::Bgra, Swizzle4 { src: rgb::RGBA_POS, dst: rgb::BGRA_POS }),
        (P::Bgra, P::Rgba, Swizzle4 { src: rgb::BGRA_POS, dst: rgb::RGBA_POS }),
        (P::Rgba, P::Argb, Swizzle4 { src: rgb::RGBA_POS, dst: rgb::ARGB_POS }),
        (P::Argb, P::Rgba, Swizzle4 { src: rgb::ARGB_POS, dst: rgb::RGBA_POS }),
        (P::Rgba, P::Abgr, Swizzle4 { src: rgb::RGBA_POS, dst: rgb::ABGR_POS }),
        (P::Abgr, P::Rgba, Swizzle4 { src: rgb::ABGR_POS, dst: rgb::RGBA_POS }),
        (P::Bgra, P::Argb, Swizzle4 { src: rgb::BGRA_POS, dst: rgb::ARGB_POS }),
        (P::Argb, P::Bgra, Swizzle4 { src: rgb::ARGB_POS, dst: rgb::BGRA_POS }),
        (P::Bgra, P::Abgr, Swizzle4 { src: rgb::BGRA_POS, dst: rgb::ABGR_POS }),
        (P::Abgr, P::Bgra, Swizzle4 { src: rgb::ABGR_POS, dst: rgb::BGRA_POS }),
        (P::Argb, P::Abgr, Swizzle4 { src: rgb::ARGB_POS, dst: rgb::ABGR_POS }),
        (P::Abgr, P::Argb, Swizzle4 { src: rgb::ABGR_POS, dst: rgb::ARGB_POS }),

        // 3 ↔ 4 promote (append opaque alpha) / demote (drop alpha).
        (P::Rgb24, P::Rgba, Promote3To4 { src: rgb::RGB_POS, dst: rgb::RGBA_POS }),
        (P::Rgb24, P::Bgra, Promote3To4 { src: rgb::RGB_POS, dst: rgb::BGRA_POS }),
        (P::Rgb24, P::Argb, Promote3To4 { src: rgb::RGB_POS, dst: rgb::ARGB_POS }),
        (P::Rgb24, P::Abgr, Promote3To4 { src: rgb::RGB_POS, dst: rgb::ABGR_POS }),
        (P::Bgr24, P::Rgba, Promote3To4 { src: rgb::BGR_POS, dst: rgb::RGBA_POS }),
        (P::Bgr24, P::Bgra, Promote3To4 { src: rgb::BGR_POS, dst: rgb::BGRA_POS }),
        (P::Bgr24, P::Argb, Promote3To4 { src: rgb::BGR_POS, dst: rgb::ARGB_POS }),
        (P::Bgr24, P::Abgr, Promote3To4 { src: rgb::BGR_POS, dst: rgb::ABGR_POS }),
        (P::Rgba, P::Rgb24, Demote4To3 { src: rgb::RGBA_POS, dst: rgb::RGB_POS }),
        (P::Rgba, P::Bgr24, Demote4To3 { src: rgb::RGBA_POS, dst: rgb::BGR_POS }),
        (P::Bgra, P::Rgb24, Demote4To3 { src: rgb::BGRA_POS, dst: rgb::RGB_POS }),
        (P::Bgra, P::Bgr24, Demote4To3 { src: rgb::BGRA_POS, dst: rgb::BGR_POS }),
        (P::Argb, P::Rgb24, Demote4To3 { src: rgb::ARGB_POS, dst: rgb::RGB_POS }),
        (P::Argb, P::Bgr24, Demote4To3 { src: rgb::ARGB_POS, dst: rgb::BGR_POS }),
        (P::Abgr, P::Rgb24, Demote4To3 { src: rgb::ABGR_POS, dst: rgb::RGB_POS }),
        (P::Abgr, P::Bgr24, Demote4To3 { src: rgb::ABGR_POS, dst: rgb::BGR_POS }),

        // Deeper packed RGB ↔ 8-bit.
        (P::Rgb48Le, P::Rgb24, Rgb48ToRgb24),
        (P::Rgb24, P::Rgb48Le, Rgb24ToRgb48),
        (P::Rgba64Le, P::Rgba, Rgba64ToRgba),
        (P::Rgba, P::Rgba64Le, RgbaToRgba64),

        // Gray ↔ RGB / Gray16 / Mono. A gray broadcast writes the same
        // value to every colour channel, so the Rgb24 emitter serves
        // Bgr24 verbatim and the Rgba emitter serves Bgra; the
        // alpha-first orders (Argb / Abgr) shift the opaque byte to the
        // front via `alpha_first`.
        (P::Gray8, P::Rgb24, Gray8ToPacked3),
        (P::Gray8, P::Bgr24, Gray8ToPacked3),
        (P::Gray8, P::Rgba, Gray8ToPacked4 { alpha_first: false }),
        (P::Gray8, P::Bgra, Gray8ToPacked4 { alpha_first: false }),
        (P::Gray8, P::Argb, Gray8ToPacked4 { alpha_first: true }),
        (P::Gray8, P::Abgr, Gray8ToPacked4 { alpha_first: true }),
        (P::Gray16Le, P::Gray8, Gray16ToGray8),
        (P::Gray8, P::Gray16Le, Gray8ToGray16),
        (P::MonoBlack, P::Gray8, MonoToGray { black_is_zero: true }),
        (P::MonoWhite, P::Gray8, MonoToGray { black_is_zero: false }),
        (P::Gray8, P::MonoBlack, GrayToMono { black_is_zero: true }),
        (P::Gray8, P::MonoWhite, GrayToMono { black_is_zero: false }),

        // Packed RGB → Gray8 luminance projection. Uses the Y' row of
        // the selected primaries at full range (Gray8 is a full-range
        // space); r = g = b inputs map to themselves exactly, so the
        // Gray8 → RGB broadcast round-trips gray content.
        (P::Rgb24, P::Gray8, RgbToGray { alpha_in: false }),
        (P::Rgba,  P::Gray8, RgbToGray { alpha_in: true }),

        // Ya8 (grey + alpha, 2 bytes/pixel) ↔ Gray8 / Rgb24 / Rgba.
        // Promote/demote helpers for icon / glyph / single-channel-mask
        // workflows that need to carry an alpha plane through the
        // pipeline without going through a full YUVA path.
        (P::Ya8,   P::Gray8, Ya8ToGray8),
        (P::Gray8, P::Ya8,   Gray8ToYa8),
        (P::Ya8,   P::Rgb24, Ya8ToRgb24),
        (P::Ya8,   P::Rgba,  Ya8ToRgba),
        (P::Rgb24, P::Ya8,   Rgb24ToYa8),
        (P::Rgba,  P::Ya8,   RgbaToYa8),

        // Ya16Le (packed 16-bit grey + alpha, core 0.1.34) — the deep
        // companion to Ya8. Both words are full-scale LE16 (the
        // Gray16Le convention). Depth moves follow the ladder rules:
        // high-byte truncation down, exact ×257 widen up (so the 8-bit
        // round-trips are lossless); the Gray16Le pair is bit-exact in
        // luma; the Rgba64Le pair is bit-exact out (broadcast + carry)
        // and recovers grey-on-alpha content exactly on the way back
        // (rounded-mean luma derivation, the Ya8 convention at depth).
        (P::Ya16Le,   P::Ya8,      Ya16ToYa8),
        (P::Ya8,      P::Ya16Le,   Ya8ToYa16),
        (P::Ya16Le,   P::Gray16Le, Ya16ToGray16),
        (P::Gray16Le, P::Ya16Le,   Gray16ToYa16),
        (P::Ya16Le,   P::Gray8,    Ya16ToGray8),
        (P::Gray8,    P::Ya16Le,   Gray8ToYa16),
        (P::Ya16Le,   P::Rgba64Le, Ya16ToRgba64),
        (P::Rgba64Le, P::Ya16Le,   Rgba64ToYa16),
        (P::Ya16Le,   P::Rgba,     Ya16ToPacked8 { alpha: true }),
        (P::Ya16Le,   P::Rgb24,    Ya16ToPacked8 { alpha: false }),
        (P::Rgba,     P::Ya16Le,   Packed8ToYa16 { alpha_in: true }),
        (P::Rgb24,    P::Ya16Le,   Packed8ToYa16 { alpha_in: false }),

        // YUV family → Gray8 (luma extraction) and Gray8 → YUV family
        // (neutral chroma synthesis). Both directions are pure luma-plane
        // operations: chroma is dropped on the way out and written as the
        // neutral code 128 on the way in, so no colour matrix applies —
        // only the range rescale between the limited-range `Yuv*` /
        // `Nv*` / `Yuva*` families (16..=235 luma) and the full-range
        // `Gray8` / `YuvJ*` sample space. The `Yuva*` → Gray8 rows also
        // drop the alpha plane.
        (P::Yuv420P,  P::Gray8, YuvLumaToGray { full_range: false }),
        (P::Yuv422P,  P::Gray8, YuvLumaToGray { full_range: false }),
        (P::Yuv444P,  P::Gray8, YuvLumaToGray { full_range: false }),
        (P::Yuv411P,  P::Gray8, YuvLumaToGray { full_range: false }),
        (P::Nv12,     P::Gray8, YuvLumaToGray { full_range: false }),
        (P::Nv21,     P::Gray8, YuvLumaToGray { full_range: false }),
        (P::Yuva420P, P::Gray8, YuvLumaToGray { full_range: false }),
        (P::Yuva422P, P::Gray8, YuvLumaToGray { full_range: false }),
        (P::Yuva444P, P::Gray8, YuvLumaToGray { full_range: false }),
        (P::YuvJ420P, P::Gray8, YuvLumaToGray { full_range: true }),
        (P::YuvJ422P, P::Gray8, YuvLumaToGray { full_range: true }),
        (P::YuvJ444P, P::Gray8, YuvLumaToGray { full_range: true }),
        (P::Gray8, P::Yuv420P,  GrayToYuvPlanar { wsub: 2, hsub: 2, full_range: false }),
        (P::Gray8, P::Yuv422P,  GrayToYuvPlanar { wsub: 2, hsub: 1, full_range: false }),
        (P::Gray8, P::Yuv444P,  GrayToYuvPlanar { wsub: 1, hsub: 1, full_range: false }),
        (P::Gray8, P::Yuv411P,  GrayToYuvPlanar { wsub: 4, hsub: 1, full_range: false }),
        (P::Gray8, P::YuvJ420P, GrayToYuvPlanar { wsub: 2, hsub: 2, full_range: true }),
        (P::Gray8, P::YuvJ422P, GrayToYuvPlanar { wsub: 2, hsub: 1, full_range: true }),
        (P::Gray8, P::YuvJ444P, GrayToYuvPlanar { wsub: 1, hsub: 1, full_range: true }),
        // The NV interleaved chroma plane is all-neutral (128, 128), so
        // NV12 and NV21 receive byte-identical output.
        (P::Gray8, P::Nv12, GrayToNv),
        (P::Gray8, P::Nv21, GrayToNv),

        // YUV planar → packed RGB.
        (P::Yuv420P, P::Rgb24, YuvToRgb { wsub: 2, hsub: 2, alpha: false, full_range: false }),
        (P::Yuv422P, P::Rgb24, YuvToRgb { wsub: 2, hsub: 1, alpha: false, full_range: false }),
        (P::Yuv444P, P::Rgb24, YuvToRgb { wsub: 1, hsub: 1, alpha: false, full_range: false }),
        (P::Yuv420P, P::Rgba,  YuvToRgb { wsub: 2, hsub: 2, alpha: true, full_range: false }),
        (P::Yuv422P, P::Rgba,  YuvToRgb { wsub: 2, hsub: 1, alpha: true, full_range: false }),
        (P::Yuv444P, P::Rgba,  YuvToRgb { wsub: 1, hsub: 1, alpha: true, full_range: false }),

        // Packed RGB → YUV planar.
        (P::Rgb24, P::Yuv420P, RgbToYuv { wsub: 2, hsub: 2, alpha_in: false, full_range: false }),
        (P::Rgb24, P::Yuv422P, RgbToYuv { wsub: 2, hsub: 1, alpha_in: false, full_range: false }),
        (P::Rgb24, P::Yuv444P, RgbToYuv { wsub: 1, hsub: 1, alpha_in: false, full_range: false }),
        (P::Rgba,  P::Yuv420P, RgbToYuv { wsub: 2, hsub: 2, alpha_in: true, full_range: false }),
        (P::Rgba,  P::Yuv422P, RgbToYuv { wsub: 2, hsub: 1, alpha_in: true, full_range: false }),
        (P::Rgba,  P::Yuv444P, RgbToYuv { wsub: 1, hsub: 1, alpha_in: true, full_range: false }),

        // Full-range "J" YUV planar ↔ packed RGB, direct (no staging
        // through the limited-range sibling). The YuvJ* families carry
        // full-range samples by definition, so these rows pin the matrix
        // to full range regardless of the `ColorSpace` range half —
        // `opts.color_space` still selects the primaries (601/709/2020).
        (P::YuvJ420P, P::Rgb24, YuvToRgb { wsub: 2, hsub: 2, alpha: false, full_range: true }),
        (P::YuvJ422P, P::Rgb24, YuvToRgb { wsub: 2, hsub: 1, alpha: false, full_range: true }),
        (P::YuvJ444P, P::Rgb24, YuvToRgb { wsub: 1, hsub: 1, alpha: false, full_range: true }),
        (P::YuvJ420P, P::Rgba,  YuvToRgb { wsub: 2, hsub: 2, alpha: true, full_range: true }),
        (P::YuvJ422P, P::Rgba,  YuvToRgb { wsub: 2, hsub: 1, alpha: true, full_range: true }),
        (P::YuvJ444P, P::Rgba,  YuvToRgb { wsub: 1, hsub: 1, alpha: true, full_range: true }),
        (P::Rgb24, P::YuvJ420P, RgbToYuv { wsub: 2, hsub: 2, alpha_in: false, full_range: true }),
        (P::Rgb24, P::YuvJ422P, RgbToYuv { wsub: 2, hsub: 1, alpha_in: false, full_range: true }),
        (P::Rgb24, P::YuvJ444P, RgbToYuv { wsub: 1, hsub: 1, alpha_in: false, full_range: true }),
        (P::Rgba,  P::YuvJ420P, RgbToYuv { wsub: 2, hsub: 2, alpha_in: true, full_range: true }),
        (P::Rgba,  P::YuvJ422P, RgbToYuv { wsub: 2, hsub: 1, alpha_in: true, full_range: true }),
        (P::Rgba,  P::YuvJ444P, RgbToYuv { wsub: 1, hsub: 1, alpha_in: true, full_range: true }),

        // YuvJ* ↔ Yuv* (range rescale only — same planar layout).
        (P::YuvJ420P, P::Yuv420P, RescaleRange { wsub: 2, hsub: 2, to_full: false }),
        (P::YuvJ422P, P::Yuv422P, RescaleRange { wsub: 2, hsub: 1, to_full: false }),
        (P::YuvJ444P, P::Yuv444P, RescaleRange { wsub: 1, hsub: 1, to_full: false }),
        (P::Yuv420P, P::YuvJ420P, RescaleRange { wsub: 2, hsub: 2, to_full: true }),
        (P::Yuv422P, P::YuvJ422P, RescaleRange { wsub: 2, hsub: 1, to_full: true }),
        (P::Yuv444P, P::YuvJ444P, RescaleRange { wsub: 1, hsub: 1, to_full: true }),

        // NV12 / NV21 ↔ Yuv420P.
        (P::Nv12, P::Yuv420P, NvToYuv420p { is_nv12: true }),
        (P::Nv21, P::Yuv420P, NvToYuv420p { is_nv12: false }),
        (P::Yuv420P, P::Nv12, Yuv420pToNv { is_nv12: true }),
        (P::Yuv420P, P::Nv21, Yuv420pToNv { is_nv12: false }),
        // NV12 / NV21 ↔ RGB direct. Fused path: walk the interleaved
        // UV plane once per row pair, split into a transient (U, V)
        // plane pair, then run the proven planar 4:2:0 → RGB decoder.
        // Avoids the caller having to stage through Yuv420P.
        (P::Nv12, P::Rgb24, NvToRgb { is_nv12: true, alpha: false }),
        (P::Nv21, P::Rgb24, NvToRgb { is_nv12: false, alpha: false }),
        (P::Nv12, P::Rgba,  NvToRgb { is_nv12: true, alpha: true }),
        (P::Nv21, P::Rgba,  NvToRgb { is_nv12: false, alpha: true }),
        (P::Rgb24, P::Nv12, RgbToNv { is_nv12: true, alpha_in: false }),
        (P::Rgb24, P::Nv21, RgbToNv { is_nv12: false, alpha_in: false }),
        (P::Rgba,  P::Nv12, RgbToNv { is_nv12: true, alpha_in: true }),
        (P::Rgba,  P::Nv21, RgbToNv { is_nv12: false, alpha_in: true }),

        // Direct planar YUV ↔ planar YUV (chroma resample only — luma
        // copied byte-for-byte). Limited-range BT.x carriage where the
        // YUV ↔ YUV step never visits RGB. Six entries cover every
        // ordered pair on (4:2:0, 4:2:2, 4:4:4).
        (P::Yuv420P, P::Yuv422P, ChromaResample { src_wsub: 2, src_hsub: 2, dst_wsub: 2, dst_hsub: 1 }),
        (P::Yuv420P, P::Yuv444P, ChromaResample { src_wsub: 2, src_hsub: 2, dst_wsub: 1, dst_hsub: 1 }),
        (P::Yuv422P, P::Yuv420P, ChromaResample { src_wsub: 2, src_hsub: 1, dst_wsub: 2, dst_hsub: 2 }),
        (P::Yuv422P, P::Yuv444P, ChromaResample { src_wsub: 2, src_hsub: 1, dst_wsub: 1, dst_hsub: 1 }),
        (P::Yuv444P, P::Yuv420P, ChromaResample { src_wsub: 1, src_hsub: 1, dst_wsub: 2, dst_hsub: 2 }),
        (P::Yuv444P, P::Yuv422P, ChromaResample { src_wsub: 1, src_hsub: 1, dst_wsub: 2, dst_hsub: 1 }),

        // Same six pairs on the full-range "J" planar family. The
        // matrix is the same as the limited-range op (no luma/chroma
        // rescale enters here — only chroma subsampling changes), so
        // these reuse `ChromaResample` directly.
        (P::YuvJ420P, P::YuvJ422P, ChromaResample { src_wsub: 2, src_hsub: 2, dst_wsub: 2, dst_hsub: 1 }),
        (P::YuvJ420P, P::YuvJ444P, ChromaResample { src_wsub: 2, src_hsub: 2, dst_wsub: 1, dst_hsub: 1 }),
        (P::YuvJ422P, P::YuvJ420P, ChromaResample { src_wsub: 2, src_hsub: 1, dst_wsub: 2, dst_hsub: 2 }),
        (P::YuvJ422P, P::YuvJ444P, ChromaResample { src_wsub: 2, src_hsub: 1, dst_wsub: 1, dst_hsub: 1 }),
        (P::YuvJ444P, P::YuvJ420P, ChromaResample { src_wsub: 1, src_hsub: 1, dst_wsub: 2, dst_hsub: 2 }),
        (P::YuvJ444P, P::YuvJ422P, ChromaResample { src_wsub: 1, src_hsub: 1, dst_wsub: 2, dst_hsub: 1 }),

        // Packed 4:2:2 (YUYV / UYVY) ↔ planar Yuv422P. Pure deinterleave
        // / interleave; no colour math.
        (P::Yuyv422, P::Yuv422P, Packed422ToYuv422p { is_yuyv: true }),
        (P::Uyvy422, P::Yuv422P, Packed422ToYuv422p { is_yuyv: false }),
        (P::Yuv422P, P::Yuyv422, Yuv422pToPacked422 { is_yuyv: true }),
        (P::Yuv422P, P::Uyvy422, Yuv422pToPacked422 { is_yuyv: false }),
        // YUYV ↔ UYVY: two byte-swaps per quad.
        (P::Yuyv422, P::Uyvy422, Packed422Swap),
        (P::Uyvy422, P::Yuyv422, Packed422Swap),
        // Packed 4:2:2 ↔ RGB. Fused path that walks the packed buffer
        // once per row, deinterleaves on the fly, and feeds the result
        // into the same colour math used by the planar 4:2:2 route.
        (P::Yuyv422, P::Rgb24, Packed422ToRgb { is_yuyv: true, alpha: false }),
        (P::Uyvy422, P::Rgb24, Packed422ToRgb { is_yuyv: false, alpha: false }),
        (P::Yuyv422, P::Rgba,  Packed422ToRgb { is_yuyv: true, alpha: true }),
        (P::Uyvy422, P::Rgba,  Packed422ToRgb { is_yuyv: false, alpha: true }),
        (P::Rgb24, P::Yuyv422, RgbToPacked422 { is_yuyv: true, alpha_in: false }),
        (P::Rgb24, P::Uyvy422, RgbToPacked422 { is_yuyv: false, alpha_in: false }),
        (P::Rgba,  P::Yuyv422, RgbToPacked422 { is_yuyv: true, alpha_in: true }),
        (P::Rgba,  P::Uyvy422, RgbToPacked422 { is_yuyv: false, alpha_in: true }),

        // Palette.
        (P::Pal8, P::Rgb24, Pal8ToRgb { alpha: false }),
        (P::Pal8, P::Rgba,  Pal8ToRgb { alpha: true }),
        (P::Rgb24, P::Pal8, RgbToPal8 { alpha_in: false }),
        (P::Rgba,  P::Pal8, RgbToPal8 { alpha_in: true }),

        // CMYK ↔ RGB. Uncalibrated device-CMYK approximation; pure
        // bit-manipulation (no matrix / ColorSpace knob applies).
        (P::Cmyk,  P::Rgb24, CmykToRgb { alpha: false, inverted: false }),
        (P::Cmyk,  P::Rgba,  CmykToRgb { alpha: true, inverted: false }),
        (P::Rgb24, P::Cmyk,  RgbToCmyk { alpha_in: false, inverted: false }),
        (P::Rgba,  P::Cmyk,  RgbToCmyk { alpha_in: true, inverted: false }),
        // CmykInverted (core 0.1.34): the inverted-ink convention
        // (stored byte = 255 − ink). RGB interop folds the complement
        // into the formula — byte-identical to complement-then-regular;
        // the Cmyk ↔ CmykInverted pair is the exact self-inverse
        // per-byte complement (lossless both ways).
        (P::CmykInverted, P::Rgb24, CmykToRgb { alpha: false, inverted: true }),
        (P::CmykInverted, P::Rgba,  CmykToRgb { alpha: true, inverted: true }),
        (P::Rgb24, P::CmykInverted, RgbToCmyk { alpha_in: false, inverted: true }),
        (P::Rgba,  P::CmykInverted, RgbToCmyk { alpha_in: true, inverted: true }),
        (P::Cmyk,  P::CmykInverted, CmykComplement),
        (P::CmykInverted, P::Cmyk,  CmykComplement),

        // Yuv411P (4:1:1 planar — luma full res, chroma horizontally
        // subsampled by 4). Native NTSC DV-25 layout and a legal JPEG
        // sampling pattern (`cjpeg -sample 4x1`). Six chroma-resample
        // pairs (411 ↔ 420 / 422 / 444 in both directions) plus
        // RGB encode/decode under any `ColorSpace`. Width must be a
        // multiple of 4; odd-by-4 widths reject with `Error::Invalid`.
        (P::Yuv411P, P::Yuv444P, ChromaResample { src_wsub: 4, src_hsub: 1, dst_wsub: 1, dst_hsub: 1 }),
        (P::Yuv411P, P::Yuv422P, ChromaResample { src_wsub: 4, src_hsub: 1, dst_wsub: 2, dst_hsub: 1 }),
        (P::Yuv411P, P::Yuv420P, ChromaResample { src_wsub: 4, src_hsub: 1, dst_wsub: 2, dst_hsub: 2 }),
        (P::Yuv444P, P::Yuv411P, ChromaResample { src_wsub: 1, src_hsub: 1, dst_wsub: 4, dst_hsub: 1 }),
        (P::Yuv422P, P::Yuv411P, ChromaResample { src_wsub: 2, src_hsub: 1, dst_wsub: 4, dst_hsub: 1 }),
        (P::Yuv420P, P::Yuv411P, ChromaResample { src_wsub: 2, src_hsub: 2, dst_wsub: 4, dst_hsub: 1 }),
        // Yuv411P ↔ Yuv440P (core 0.1.35): the two "one axis only"
        // sitings, composed through 4:4:4 inside the resampler.
        (P::Yuv411P, P::Yuv440P, ChromaResample { src_wsub: 4, src_hsub: 1, dst_wsub: 1, dst_hsub: 2 }),
        (P::Yuv440P, P::Yuv411P, ChromaResample { src_wsub: 1, src_hsub: 2, dst_wsub: 4, dst_hsub: 1 }),
        // Yuv411P ↔ RGB. The 4:1:1 ↔ 4:4:4 chroma step stages through
        // a transient full-resolution chroma pair before calling the
        // proven scalar 4:4:4 ↔ RGB matrix; no new colour math.
        (P::Yuv411P, P::Rgb24, YuvToRgb { wsub: 4, hsub: 1, alpha: false, full_range: false }),
        (P::Yuv411P, P::Rgba,  YuvToRgb { wsub: 4, hsub: 1, alpha: true, full_range: false }),
        (P::Rgb24,   P::Yuv411P, RgbToYuv { wsub: 4, hsub: 1, alpha_in: false, full_range: false }),
        (P::Rgba,    P::Yuv411P, RgbToYuv { wsub: 4, hsub: 1, alpha_in: true, full_range: false }),

        // Yuva420P / Yuva422P / Yuva444P (planar YUV + a full-resolution
        // alpha plane appended as plane 3 — the alpha plane is `w × h`
        // regardless of the chroma subsampling). The YUV planes match
        // the alpha-less sibling byte-for-byte; conversions reuse the
        // proven planar YUV ↔ RGB paths and either drop, synthesise
        // opaque, or carry the alpha plane through unchanged.
        (P::Yuv420P,  P::Yuva420P, YuvToYuva { wsub: 2, hsub: 2 }),
        (P::Yuv422P,  P::Yuva422P, YuvToYuva { wsub: 2, hsub: 1 }),
        (P::Yuv444P,  P::Yuva444P, YuvToYuva { wsub: 1, hsub: 1 }),
        (P::Yuva420P, P::Yuv420P,  YuvaToYuv { wsub: 2, hsub: 2 }),
        (P::Yuva422P, P::Yuv422P,  YuvaToYuv { wsub: 2, hsub: 1 }),
        (P::Yuva444P, P::Yuv444P,  YuvaToYuv { wsub: 1, hsub: 1 }),
        (P::Yuva420P, P::Rgb24,    YuvaToRgb { wsub: 2, hsub: 2, alpha: false }),
        (P::Yuva422P, P::Rgb24,    YuvaToRgb { wsub: 2, hsub: 1, alpha: false }),
        (P::Yuva444P, P::Rgb24,    YuvaToRgb { wsub: 1, hsub: 1, alpha: false }),
        (P::Yuva420P, P::Rgba,     YuvaToRgb { wsub: 2, hsub: 2, alpha: true }),
        (P::Yuva422P, P::Rgba,     YuvaToRgb { wsub: 2, hsub: 1, alpha: true }),
        (P::Yuva444P, P::Rgba,     YuvaToRgb { wsub: 1, hsub: 1, alpha: true }),
        (P::Rgb24,    P::Yuva420P, RgbToYuva { wsub: 2, hsub: 2, alpha_in: false }),
        (P::Rgb24,    P::Yuva422P, RgbToYuva { wsub: 2, hsub: 1, alpha_in: false }),
        (P::Rgb24,    P::Yuva444P, RgbToYuva { wsub: 1, hsub: 1, alpha_in: false }),
        (P::Rgba,     P::Yuva420P, RgbToYuva { wsub: 2, hsub: 2, alpha_in: true }),
        (P::Rgba,     P::Yuva422P, RgbToYuva { wsub: 2, hsub: 1, alpha_in: true }),
        (P::Rgba,     P::Yuva444P, RgbToYuva { wsub: 1, hsub: 1, alpha_in: true }),
        // Alpha-preserving moves inside the Yuva family: luma and the
        // full-resolution alpha plane are copied byte-for-byte, only
        // the chroma pair is resampled (same primitives and rounding
        // as the alpha-less `ChromaResample` rows — no colour matrix,
        // alpha bit-exact).
        (P::Yuva420P, P::Yuva422P, YuvaChromaResample { src_wsub: 2, src_hsub: 2, dst_wsub: 2, dst_hsub: 1 }),
        (P::Yuva420P, P::Yuva444P, YuvaChromaResample { src_wsub: 2, src_hsub: 2, dst_wsub: 1, dst_hsub: 1 }),
        (P::Yuva422P, P::Yuva420P, YuvaChromaResample { src_wsub: 2, src_hsub: 1, dst_wsub: 2, dst_hsub: 2 }),
        (P::Yuva422P, P::Yuva444P, YuvaChromaResample { src_wsub: 2, src_hsub: 1, dst_wsub: 1, dst_hsub: 1 }),
        (P::Yuva444P, P::Yuva420P, YuvaChromaResample { src_wsub: 1, src_hsub: 1, dst_wsub: 2, dst_hsub: 2 }),
        (P::Yuva444P, P::Yuva422P, YuvaChromaResample { src_wsub: 1, src_hsub: 1, dst_wsub: 2, dst_hsub: 1 }),

        // Planar GBR(A) ↔ packed deep RGB. GBR stores RGB as three (or
        // four with alpha) planes in G, B, R order, each sample a 16-bit
        // LE word carrying `bits` significant low bits (per the
        // oxideav-core `Gbrp*Le` / `Gbrap*Le` variant docs). The packed
        // `Rgb48Le` / `Rgba64Le` targets carry 16 significant bits in
        // R, G, B(, A) byte order. The conversion is a pure
        // deinterleave/interleave plus the ladder widen toward the
        // 16-bit container (MSB replication, peak → peak; round 476 —
        // it was a bare left shift before, 10-bit peak landing on 65472)
        // and the truncation on the way back — no colour matrix. No
        // `ColorSpace` knob applies.
        (P::Gbrp10Le,  P::Rgb48Le,  GbrToPackedDeep { bits: 10, alpha_in: false, alpha_out: false }),
        (P::Gbrp12Le,  P::Rgb48Le,  GbrToPackedDeep { bits: 12, alpha_in: false, alpha_out: false }),
        (P::Gbrp14Le,  P::Rgb48Le,  GbrToPackedDeep { bits: 14, alpha_in: false, alpha_out: false }),
        (P::Gbrap10Le, P::Rgba64Le, GbrToPackedDeep { bits: 10, alpha_in: true, alpha_out: true }),
        (P::Gbrap12Le, P::Rgba64Le, GbrToPackedDeep { bits: 12, alpha_in: true, alpha_out: true }),
        (P::Gbrap14Le, P::Rgba64Le, GbrToPackedDeep { bits: 14, alpha_in: true, alpha_out: true }),
        // Planar GBR(A) ↔ 8-bit packed RGB(A). Same plane reorder as the
        // deep rows with a bit-depth step folded in: narrowing keeps the
        // top 8 of the `bits` significant bits (truncation, matching the
        // depth ladder), widening replicates MSBs so 8-bit round-trips
        // are exact and peak maps to peak. These rows also make the GBR
        // families reachable from the whole 8-bit ecosystem (YUV, gray,
        // palette, …) through the staged fallback's Rgb24/Rgba pivots.
        (P::Gbrp10Le,  P::Rgb24, GbrToPacked8 { bits: 10, alpha: false }),
        (P::Gbrp12Le,  P::Rgb24, GbrToPacked8 { bits: 12, alpha: false }),
        (P::Gbrp14Le,  P::Rgb24, GbrToPacked8 { bits: 14, alpha: false }),
        (P::Gbrap10Le, P::Rgba,  GbrToPacked8 { bits: 10, alpha: true }),
        (P::Gbrap12Le, P::Rgba,  GbrToPacked8 { bits: 12, alpha: true }),
        (P::Gbrap14Le, P::Rgba,  GbrToPacked8 { bits: 14, alpha: true }),
        (P::Rgb24, P::Gbrp10Le,  Packed8ToGbr { bits: 10, alpha: false }),
        (P::Rgb24, P::Gbrp12Le,  Packed8ToGbr { bits: 12, alpha: false }),
        (P::Rgb24, P::Gbrp14Le,  Packed8ToGbr { bits: 14, alpha: false }),
        (P::Rgba,  P::Gbrap10Le, Packed8ToGbr { bits: 10, alpha: true }),
        (P::Rgba,  P::Gbrap12Le, Packed8ToGbr { bits: 12, alpha: true }),
        (P::Rgba,  P::Gbrap14Le, Packed8ToGbr { bits: 14, alpha: true }),

        (P::Rgb48Le,  P::Gbrp10Le,  PackedDeepToGbr { bits: 10, alpha_in: false, alpha_out: false }),
        (P::Rgb48Le,  P::Gbrp12Le,  PackedDeepToGbr { bits: 12, alpha_in: false, alpha_out: false }),
        (P::Rgb48Le,  P::Gbrp14Le,  PackedDeepToGbr { bits: 14, alpha_in: false, alpha_out: false }),
        (P::Rgba64Le, P::Gbrap10Le, PackedDeepToGbr { bits: 10, alpha_in: true, alpha_out: true }),
        (P::Rgba64Le, P::Gbrap12Le, PackedDeepToGbr { bits: 12, alpha_in: true, alpha_out: true }),
        (P::Rgba64Le, P::Gbrap14Le, PackedDeepToGbr { bits: 14, alpha_in: true, alpha_out: true }),

        // GBR(A) depth-ladder ends (core 0.1.33). The 16-bit members
        // reuse the shared GBR ops with `bits = 16`: the deep-packed
        // hop degenerates to a pure plane reorder (shift by 0 — exact
        // both ways), the 8-bit hops are the exact x257 widen /
        // top-byte truncation. `Gbrp8` stores byte samples, so it gets
        // dedicated byte-plane ops: Rgb24 interop is a zero-math plane
        // reorder (bit-exact, self-inverse), Rgb48Le interop widens
        // x257 / keeps the top byte, mirroring Rgb24 ↔ Rgb48Le.
        (P::Gbrp16Le,  P::Rgb48Le,  GbrToPackedDeep { bits: 16, alpha_in: false, alpha_out: false }),
        (P::Gbrap16Le, P::Rgba64Le, GbrToPackedDeep { bits: 16, alpha_in: true, alpha_out: true }),
        (P::Rgb48Le,  P::Gbrp16Le,  PackedDeepToGbr { bits: 16, alpha_in: false, alpha_out: false }),
        (P::Rgba64Le, P::Gbrap16Le, PackedDeepToGbr { bits: 16, alpha_in: true, alpha_out: true }),
        (P::Gbrp16Le,  P::Rgb24, GbrToPacked8 { bits: 16, alpha: false }),
        (P::Gbrap16Le, P::Rgba,  GbrToPacked8 { bits: 16, alpha: true }),
        (P::Rgb24, P::Gbrp16Le,  Packed8ToGbr { bits: 16, alpha: false }),
        (P::Rgba,  P::Gbrap16Le, Packed8ToGbr { bits: 16, alpha: true }),
        (P::Gbrp8,   P::Rgb24,   Gbr8ToPacked8 { alpha_in: false, alpha_out: false }),
        (P::Rgb24,   P::Gbrp8,   Packed8ToGbr8 { alpha_in: false, alpha_out: false }),
        (P::Gbrp8,   P::Rgb48Le, Gbr8ToPackedDeep { alpha_in: false, alpha_out: false }),
        (P::Rgb48Le, P::Gbrp8,   PackedDeepToGbr8 { alpha_in: false, alpha_out: false }),

        // Alpha-crossing deep-packed GBR rows: every GBR(A) member has a
        // direct hop to BOTH deep packed formats. Colour words keep the
        // family shift convention; a missing alpha is synthesised opaque
        // (full-scale 65535 on the packed side, `(1 << bits) - 1` on the
        // planar side) and a surplus alpha is dropped. These rows give
        // the staged fallback its alpha-crossing GBR pivot legs, closing
        // e.g. Gbrp8 -> Gbrap12Le and Gbrap16Le -> Gbrp10Le.
        (P::Gbrp10Le, P::Rgba64Le, GbrToPackedDeep { bits: 10, alpha_in: false, alpha_out: true }),
        (P::Gbrp12Le, P::Rgba64Le, GbrToPackedDeep { bits: 12, alpha_in: false, alpha_out: true }),
        (P::Gbrp14Le, P::Rgba64Le, GbrToPackedDeep { bits: 14, alpha_in: false, alpha_out: true }),
        (P::Gbrp16Le, P::Rgba64Le, GbrToPackedDeep { bits: 16, alpha_in: false, alpha_out: true }),
        (P::Gbrap10Le, P::Rgb48Le, GbrToPackedDeep { bits: 10, alpha_in: true, alpha_out: false }),
        (P::Gbrap12Le, P::Rgb48Le, GbrToPackedDeep { bits: 12, alpha_in: true, alpha_out: false }),
        (P::Gbrap14Le, P::Rgb48Le, GbrToPackedDeep { bits: 14, alpha_in: true, alpha_out: false }),
        (P::Gbrap16Le, P::Rgb48Le, GbrToPackedDeep { bits: 16, alpha_in: true, alpha_out: false }),
        (P::Rgba64Le, P::Gbrp10Le, PackedDeepToGbr { bits: 10, alpha_in: true, alpha_out: false }),
        (P::Rgba64Le, P::Gbrp12Le, PackedDeepToGbr { bits: 12, alpha_in: true, alpha_out: false }),
        (P::Rgba64Le, P::Gbrp14Le, PackedDeepToGbr { bits: 14, alpha_in: true, alpha_out: false }),
        (P::Rgba64Le, P::Gbrp16Le, PackedDeepToGbr { bits: 16, alpha_in: true, alpha_out: false }),
        (P::Rgb48Le, P::Gbrap10Le, PackedDeepToGbr { bits: 10, alpha_in: false, alpha_out: true }),
        (P::Rgb48Le, P::Gbrap12Le, PackedDeepToGbr { bits: 12, alpha_in: false, alpha_out: true }),
        (P::Rgb48Le, P::Gbrap14Le, PackedDeepToGbr { bits: 14, alpha_in: false, alpha_out: true }),
        (P::Rgb48Le, P::Gbrap16Le, PackedDeepToGbr { bits: 16, alpha_in: false, alpha_out: true }),
        (P::Gbrp8,    P::Rgba64Le, Gbr8ToPackedDeep { alpha_in: false, alpha_out: true }),
        (P::Rgba64Le, P::Gbrp8,    PackedDeepToGbr8 { alpha_in: true, alpha_out: false }),

        // Gbrap8 (core 0.1.34) — the byte-tier GBR + alpha member. The
        // packed-8 hops are pure plane reorders (bit-exact, and the
        // matched-alpha pair Gbrap8 ↔ Rgba is self-inverse); the deep
        // hops are the exact ×257 widen / top-byte truncation the rest
        // of the byte tier uses. Missing alpha is synthesised opaque
        // (255 on byte surfaces, 65535 on the packed-deep ones) and a
        // surplus alpha is dropped, matching the family convention.
        (P::Gbrap8, P::Rgba,     Gbr8ToPacked8 { alpha_in: true, alpha_out: true }),
        (P::Rgba,   P::Gbrap8,   Packed8ToGbr8 { alpha_in: true, alpha_out: true }),
        (P::Gbrap8, P::Rgb24,    Gbr8ToPacked8 { alpha_in: true, alpha_out: false }),
        (P::Rgb24,  P::Gbrap8,   Packed8ToGbr8 { alpha_in: false, alpha_out: true }),
        (P::Gbrp8,  P::Rgba,     Gbr8ToPacked8 { alpha_in: false, alpha_out: true }),
        (P::Rgba,   P::Gbrp8,    Packed8ToGbr8 { alpha_in: true, alpha_out: false }),
        (P::Gbrap8, P::Rgba64Le, Gbr8ToPackedDeep { alpha_in: true, alpha_out: true }),
        (P::Rgba64Le, P::Gbrap8, PackedDeepToGbr8 { alpha_in: true, alpha_out: true }),
        (P::Gbrap8, P::Rgb48Le,  Gbr8ToPackedDeep { alpha_in: true, alpha_out: false }),
        (P::Rgb48Le, P::Gbrap8,  PackedDeepToGbr8 { alpha_in: false, alpha_out: true }),
        // Alpha append / drop inside the byte tier (the same shape as
        // the YuvToYuva / YuvaToYuv rows): colour planes are carried
        // byte-for-byte, alpha is synthesised opaque or dropped.
        (P::Gbrp8,  P::Gbrap8,   Gbr8Alpha { add: true }),
        (P::Gbrap8, P::Gbrp8,    Gbr8Alpha { add: false }),

        // GBR(A) <-> Gray8 for the whole nine-member family: narrow to
        // 8 bits and project through the full-range Y' row of the
        // selected primaries on the way out (same kernel as the packed
        // RgbToGray rows, alpha dropped); broadcast the gray value into
        // G = B = R at depth on the way in (MSB-replicated widen, alpha
        // synthesised opaque). r = g = b content round-trips exactly,
        // and the Gray8 pivot now rescues the GBR <-> Mono and
        // GBR <-> deep-grayscale routes.
        (P::Gbrp8,     P::Gray8, GbrToGray { bits: 8,  alpha_in: false }),
        (P::Gbrap8,    P::Gray8, GbrToGray { bits: 8,  alpha_in: true }),
        (P::Gbrp10Le,  P::Gray8, GbrToGray { bits: 10, alpha_in: false }),
        (P::Gbrp12Le,  P::Gray8, GbrToGray { bits: 12, alpha_in: false }),
        (P::Gbrp14Le,  P::Gray8, GbrToGray { bits: 14, alpha_in: false }),
        (P::Gbrp16Le,  P::Gray8, GbrToGray { bits: 16, alpha_in: false }),
        (P::Gbrap10Le, P::Gray8, GbrToGray { bits: 10, alpha_in: true }),
        (P::Gbrap12Le, P::Gray8, GbrToGray { bits: 12, alpha_in: true }),
        (P::Gbrap14Le, P::Gray8, GbrToGray { bits: 14, alpha_in: true }),
        (P::Gbrap16Le, P::Gray8, GbrToGray { bits: 16, alpha_in: true }),
        (P::Gray8, P::Gbrp8,     GrayToGbr { bits: 8,  alpha_out: false }),
        (P::Gray8, P::Gbrap8,    GrayToGbr { bits: 8,  alpha_out: true }),
        (P::Gray8, P::Gbrp10Le,  GrayToGbr { bits: 10, alpha_out: false }),
        (P::Gray8, P::Gbrp12Le,  GrayToGbr { bits: 12, alpha_out: false }),
        (P::Gray8, P::Gbrp14Le,  GrayToGbr { bits: 14, alpha_out: false }),
        (P::Gray8, P::Gbrp16Le,  GrayToGbr { bits: 16, alpha_out: false }),
        (P::Gray8, P::Gbrap10Le, GrayToGbr { bits: 10, alpha_out: true }),
        (P::Gray8, P::Gbrap12Le, GrayToGbr { bits: 12, alpha_out: true }),
        (P::Gray8, P::Gbrap14Le, GrayToGbr { bits: 14, alpha_out: true }),
        (P::Gray8, P::Gbrap16Le, GrayToGbr { bits: 16, alpha_out: true }),

        // High-precision planar YUV (10/12-bit, 16-bit LE storage with the
        // value in the low `bits` bits) ↔ the 8-bit planar siblings. Pure
        // per-plane bit-depth scaling — luma and both chroma planes are
        // resized between 16-bit and 8-bit storage with no colour matrix
        // and no chroma resampling (the subsampling layout is preserved).
        // `wsub` / `hsub` describe the shared chroma division of both the
        // source and destination so the helper can size each plane.
        (P::Yuv420P10Le, P::Yuv420P, DepthDownYuv { wsub: 2, hsub: 2, bits: 10 }),
        (P::Yuv422P10Le, P::Yuv422P, DepthDownYuv { wsub: 2, hsub: 1, bits: 10 }),
        (P::Yuv444P10Le, P::Yuv444P, DepthDownYuv { wsub: 1, hsub: 1, bits: 10 }),
        (P::Yuv420P12Le, P::Yuv420P, DepthDownYuv { wsub: 2, hsub: 2, bits: 12 }),
        (P::Yuv422P12Le, P::Yuv422P, DepthDownYuv { wsub: 2, hsub: 1, bits: 12 }),
        (P::Yuv444P12Le, P::Yuv444P, DepthDownYuv { wsub: 1, hsub: 1, bits: 12 }),
        (P::Yuv420P, P::Yuv420P10Le, DepthUpYuv { wsub: 2, hsub: 2, bits: 10 }),
        (P::Yuv422P, P::Yuv422P10Le, DepthUpYuv { wsub: 2, hsub: 1, bits: 10 }),
        (P::Yuv444P, P::Yuv444P10Le, DepthUpYuv { wsub: 1, hsub: 1, bits: 10 }),
        (P::Yuv420P, P::Yuv420P12Le, DepthUpYuv { wsub: 2, hsub: 2, bits: 12 }),
        (P::Yuv422P, P::Yuv422P12Le, DepthUpYuv { wsub: 2, hsub: 1, bits: 12 }),
        (P::Yuv444P, P::Yuv444P12Le, DepthUpYuv { wsub: 1, hsub: 1, bits: 12 }),

        // Cross-depth planar YUV (10-bit ↔ 12-bit, same subsampling).
        // Pure per-plane storage-width rescale — widening replicates MSBs
        // into the new low bits (peak maps to peak, 10 → 12 → 10 is
        // exact); narrowing truncates. No colour math, no resampling.
        // Without these rows a 10 ↔ 12 move had to stage through the
        // 8-bit sibling and lose the low bits of both depths.
        (P::Yuv420P10Le, P::Yuv420P12Le, DepthRescaleYuv { wsub: 2, hsub: 2, src_bits: 10, dst_bits: 12 }),
        (P::Yuv422P10Le, P::Yuv422P12Le, DepthRescaleYuv { wsub: 2, hsub: 1, src_bits: 10, dst_bits: 12 }),
        (P::Yuv444P10Le, P::Yuv444P12Le, DepthRescaleYuv { wsub: 1, hsub: 1, src_bits: 10, dst_bits: 12 }),
        (P::Yuv420P12Le, P::Yuv420P10Le, DepthRescaleYuv { wsub: 2, hsub: 2, src_bits: 12, dst_bits: 10 }),
        (P::Yuv422P12Le, P::Yuv422P10Le, DepthRescaleYuv { wsub: 2, hsub: 1, src_bits: 12, dst_bits: 10 }),
        (P::Yuv444P12Le, P::Yuv444P10Le, DepthRescaleYuv { wsub: 1, hsub: 1, src_bits: 12, dst_bits: 10 }),

        // 16-bit planar YUV (`Yuv*P16Le`) — the full-width rung of the
        // depth ladder. Unlike the 10/12-bit variants every bit of the
        // LE word is significant (full-scale 65535), which the shared
        // primitives express as `bits = 16`: the mask covers the whole
        // word and the 8 → 16 widen becomes an exact ×257 (MSB
        // replication with an 8-bit period), so 8-bit content
        // round-trips losslessly and peak maps to peak. Narrowing
        // truncates (keeps the top bits) per the crate-wide
        // no-dither depth policy documented in [`crate::yuv`].
        // 16 ↔ 8 (same subsampling):
        (P::Yuv420P16Le, P::Yuv420P, DepthDownYuv { wsub: 2, hsub: 2, bits: 16 }),
        (P::Yuv422P16Le, P::Yuv422P, DepthDownYuv { wsub: 2, hsub: 1, bits: 16 }),
        (P::Yuv444P16Le, P::Yuv444P, DepthDownYuv { wsub: 1, hsub: 1, bits: 16 }),
        (P::Yuv420P, P::Yuv420P16Le, DepthUpYuv { wsub: 2, hsub: 2, bits: 16 }),
        (P::Yuv422P, P::Yuv422P16Le, DepthUpYuv { wsub: 2, hsub: 1, bits: 16 }),
        (P::Yuv444P, P::Yuv444P16Le, DepthUpYuv { wsub: 1, hsub: 1, bits: 16 }),
        // 16 ↔ 10 and 16 ↔ 12 (same subsampling): storage-width rescale,
        // exact inverses (widen replicates MSBs, narrow truncates).
        (P::Yuv420P10Le, P::Yuv420P16Le, DepthRescaleYuv { wsub: 2, hsub: 2, src_bits: 10, dst_bits: 16 }),
        (P::Yuv422P10Le, P::Yuv422P16Le, DepthRescaleYuv { wsub: 2, hsub: 1, src_bits: 10, dst_bits: 16 }),
        (P::Yuv444P10Le, P::Yuv444P16Le, DepthRescaleYuv { wsub: 1, hsub: 1, src_bits: 10, dst_bits: 16 }),
        (P::Yuv420P16Le, P::Yuv420P10Le, DepthRescaleYuv { wsub: 2, hsub: 2, src_bits: 16, dst_bits: 10 }),
        (P::Yuv422P16Le, P::Yuv422P10Le, DepthRescaleYuv { wsub: 2, hsub: 1, src_bits: 16, dst_bits: 10 }),
        (P::Yuv444P16Le, P::Yuv444P10Le, DepthRescaleYuv { wsub: 1, hsub: 1, src_bits: 16, dst_bits: 10 }),
        (P::Yuv420P12Le, P::Yuv420P16Le, DepthRescaleYuv { wsub: 2, hsub: 2, src_bits: 12, dst_bits: 16 }),
        (P::Yuv422P12Le, P::Yuv422P16Le, DepthRescaleYuv { wsub: 2, hsub: 1, src_bits: 12, dst_bits: 16 }),
        (P::Yuv444P12Le, P::Yuv444P16Le, DepthRescaleYuv { wsub: 1, hsub: 1, src_bits: 12, dst_bits: 16 }),
        (P::Yuv420P16Le, P::Yuv420P12Le, DepthRescaleYuv { wsub: 2, hsub: 2, src_bits: 16, dst_bits: 12 }),
        (P::Yuv422P16Le, P::Yuv422P12Le, DepthRescaleYuv { wsub: 2, hsub: 1, src_bits: 16, dst_bits: 12 }),
        (P::Yuv444P16Le, P::Yuv444P12Le, DepthRescaleYuv { wsub: 1, hsub: 1, src_bits: 16, dst_bits: 12 }),

        // Full-precision deep matrix (round 438): the 16-bit planar
        // tier ↔ the packed deep RGB formats without EVER narrowing to
        // 8 bits. The colour math runs the same k-coefficient
        // construction as the 8-bit rows in Q30/i64 over 16-bit
        // samples (limited-range offsets scale by 2^(n-8) per the
        // BT-series n-bit digital representation; chroma is centred on
        // the exact achromatic code 32768). Subsampled layouts
        // resample chroma at 16-bit precision through the proven
        // `chroma16le_*` helpers before/after the matrix. The Yuva
        // rows carry the full-resolution 16-bit alpha plane verbatim
        // into/out of the packed alpha word. The 10/12-bit family
        // reaches these rows losslessly through the exact
        // `DepthRescaleYuv` widen, so e.g. Yuv444P10Le → Rgb48Le now
        // stages at full precision instead of through an 8-bit pivot.
        (P::Yuv444P16Le, P::Rgb48Le, DeepYuvToRgb48 { wsub: 1, hsub: 1, alpha: false }),
        (P::Yuv422P16Le, P::Rgb48Le, DeepYuvToRgb48 { wsub: 2, hsub: 1, alpha: false }),
        (P::Yuv420P16Le, P::Rgb48Le, DeepYuvToRgb48 { wsub: 2, hsub: 2, alpha: false }),
        (P::Rgb48Le, P::Yuv444P16Le, Rgb48ToDeepYuv { wsub: 1, hsub: 1, alpha: false }),
        (P::Rgb48Le, P::Yuv422P16Le, Rgb48ToDeepYuv { wsub: 2, hsub: 1, alpha: false }),
        (P::Rgb48Le, P::Yuv420P16Le, Rgb48ToDeepYuv { wsub: 2, hsub: 2, alpha: false }),
        (P::Yuva444P16Le, P::Rgba64Le, DeepYuvToRgb48 { wsub: 1, hsub: 1, alpha: true }),
        (P::Yuva422P16Le, P::Rgba64Le, DeepYuvToRgb48 { wsub: 2, hsub: 1, alpha: true }),
        (P::Yuva420P16Le, P::Rgba64Le, DeepYuvToRgb48 { wsub: 2, hsub: 2, alpha: true }),
        (P::Rgba64Le, P::Yuva444P16Le, Rgb48ToDeepYuv { wsub: 1, hsub: 1, alpha: true }),
        (P::Rgba64Le, P::Yuva422P16Le, Rgb48ToDeepYuv { wsub: 2, hsub: 1, alpha: true }),
        (P::Rgba64Le, P::Yuva420P16Le, Rgb48ToDeepYuv { wsub: 2, hsub: 2, alpha: true }),
        // 4:4:0 member of the 16-bit tier (core 0.1.35): same deep
        // matrix, chroma upsampled / downsampled vertically at 16 bits.
        (P::Yuv440P16Le, P::Rgb48Le, DeepYuvToRgb48 { wsub: 1, hsub: 2, alpha: false }),
        (P::Rgb48Le, P::Yuv440P16Le, Rgb48ToDeepYuv { wsub: 1, hsub: 2, alpha: false }),

        // Direct 16-bit chroma resample — the six ordered pairs over
        // (4:2:0, 4:2:2, 4:4:4) on the 16-bit family, mirroring the
        // 8-bit `ChromaResample` rows. Luma is copied word-for-word;
        // chroma is resampled at full 16-bit precision with the same
        // rounding conventions as the 8-bit helpers. These rows also
        // give the deep staged fallback its lossless-resample pivot
        // tier (see `YUV_PIVOTS_DEEP`).
        (P::Yuv420P16Le, P::Yuv422P16Le, ChromaResample16 { src_wsub: 2, src_hsub: 2, dst_wsub: 2, dst_hsub: 1 }),
        (P::Yuv420P16Le, P::Yuv444P16Le, ChromaResample16 { src_wsub: 2, src_hsub: 2, dst_wsub: 1, dst_hsub: 1 }),
        (P::Yuv422P16Le, P::Yuv420P16Le, ChromaResample16 { src_wsub: 2, src_hsub: 1, dst_wsub: 2, dst_hsub: 2 }),
        (P::Yuv422P16Le, P::Yuv444P16Le, ChromaResample16 { src_wsub: 2, src_hsub: 1, dst_wsub: 1, dst_hsub: 1 }),
        (P::Yuv444P16Le, P::Yuv420P16Le, ChromaResample16 { src_wsub: 1, src_hsub: 1, dst_wsub: 2, dst_hsub: 2 }),
        (P::Yuv444P16Le, P::Yuv422P16Le, ChromaResample16 { src_wsub: 1, src_hsub: 1, dst_wsub: 2, dst_hsub: 1 }),

        // Deep grayscale wiring — Gray10Le / Gray12Le previously had NO
        // conversion entries at all (the only PixelFormat variants with
        // zero coverage). Same per-plane primitives as the YUV depth
        // ladder: 8-bit endpoints round-trip exactly through any deeper
        // width, and 16-bit storage acts as the common widest rung.
        // Matrix-closure rows (round 438): the Gray8 hub. Before these,
        // 92 ordered pairs were unreachable because one endpoint only
        // connects through Gray8 (Mono, deep grayscale) while the other
        // had no direct Gray8 hop. Each row below is the composition of
        // two proven kernels, byte-identical to the previously-staged
        // route where one existed, and together they make EVERY ordered
        // pair in the 61-format universe resolve. The deep-packed pair
        // also gets its exact direct hop so it never routes through a
        // luminance projection.
        (P::Rgb48Le,  P::Rgba64Le, Rgb48ToRgba64),
        (P::Rgba64Le, P::Rgb48Le,  Rgba64ToRgb48),
        (P::Bgr24, P::Gray8, PackedPosToGray { comps: 3, r: 2, g: 1, b: 0 }),
        (P::Bgra,  P::Gray8, PackedPosToGray { comps: 4, r: 2, g: 1, b: 0 }),
        (P::Argb,  P::Gray8, PackedPosToGray { comps: 4, r: 1, g: 2, b: 3 }),
        (P::Abgr,  P::Gray8, PackedPosToGray { comps: 4, r: 3, g: 2, b: 1 }),
        (P::Rgb48Le,  P::Gray8, DeepPackedToGray { alpha_in: false }),
        (P::Rgba64Le, P::Gray8, DeepPackedToGray { alpha_in: true }),
        (P::Gray8, P::Rgb48Le,  GrayToPackedDeep { alpha_out: false }),
        (P::Gray8, P::Rgba64Le, GrayToPackedDeep { alpha_out: true }),
        (P::Cmyk,         P::Gray8, CmykToGray { inverted: false }),
        (P::CmykInverted, P::Gray8, CmykToGray { inverted: true }),
        (P::Gray8, P::Cmyk,         GrayToCmyk { inverted: false }),
        (P::Gray8, P::CmykInverted, GrayToCmyk { inverted: true }),
        (P::Pal8,  P::Gray8, Pal8ToGray),
        (P::Gray8, P::Pal8,  GrayToPal8),
        (P::Yuyv422, P::Gray8, Packed422ToGray { is_yuyv: true }),
        (P::Uyvy422, P::Gray8, Packed422ToGray { is_yuyv: false }),
        (P::Gray8, P::Yuyv422, GrayToPacked422 { is_yuyv: true }),
        (P::Gray8, P::Uyvy422, GrayToPacked422 { is_yuyv: false }),

        (P::Gray10Le, P::Gray8, GrayDepthDown8 { bits: 10 }),
        (P::Gray12Le, P::Gray8, GrayDepthDown8 { bits: 12 }),
        (P::Gray8, P::Gray10Le, GrayDepthUp8 { bits: 10 }),
        (P::Gray8, P::Gray12Le, GrayDepthUp8 { bits: 12 }),
        (P::Gray10Le, P::Gray12Le, GrayDepthRescale { src_bits: 10, dst_bits: 12 }),
        (P::Gray12Le, P::Gray10Le, GrayDepthRescale { src_bits: 12, dst_bits: 10 }),
        (P::Gray10Le, P::Gray16Le, GrayDepthRescale { src_bits: 10, dst_bits: 16 }),
        (P::Gray16Le, P::Gray10Le, GrayDepthRescale { src_bits: 16, dst_bits: 10 }),
        (P::Gray12Le, P::Gray16Le, GrayDepthRescale { src_bits: 12, dst_bits: 16 }),
        (P::Gray16Le, P::Gray12Le, GrayDepthRescale { src_bits: 16, dst_bits: 12 }),

        // Deep grey ↔ packed deep RGB (round 476, the route-depth
        // audit): no 8-bit hop. Out: the grey word is widened to 16 bits
        // by the exact ladder rule (verbatim at 16) and broadcast into
        // R, G, B (+ opaque 65535). In: the Q30 full-range Y' row at
        // 16 bits, then narrowed (truncation) to the target width.
        (P::Gray16Le, P::Rgb48Le,  DeepGrayToPackedDeep { bits: 16, alpha_out: false }),
        (P::Gray16Le, P::Rgba64Le, DeepGrayToPackedDeep { bits: 16, alpha_out: true }),
        (P::Gray12Le, P::Rgb48Le,  DeepGrayToPackedDeep { bits: 12, alpha_out: false }),
        (P::Gray12Le, P::Rgba64Le, DeepGrayToPackedDeep { bits: 12, alpha_out: true }),
        (P::Gray10Le, P::Rgb48Le,  DeepGrayToPackedDeep { bits: 10, alpha_out: false }),
        (P::Gray10Le, P::Rgba64Le, DeepGrayToPackedDeep { bits: 10, alpha_out: true }),
        (P::Rgb48Le,  P::Gray16Le, PackedDeepToDeepGray { bits: 16, alpha_in: false }),
        (P::Rgba64Le, P::Gray16Le, PackedDeepToDeepGray { bits: 16, alpha_in: true }),
        (P::Rgb48Le,  P::Gray12Le, PackedDeepToDeepGray { bits: 12, alpha_in: false }),
        (P::Rgba64Le, P::Gray12Le, PackedDeepToDeepGray { bits: 12, alpha_in: true }),
        (P::Rgb48Le,  P::Gray10Le, PackedDeepToDeepGray { bits: 10, alpha_in: false }),
        (P::Rgba64Le, P::Gray10Le, PackedDeepToDeepGray { bits: 10, alpha_in: true }),
        // Ya16Le ↔ the 10 / 12-bit grey words: the Gray16Le rows plus
        // the ladder move (alpha dropped / synthesised opaque).
        (P::Ya16Le,   P::Gray12Le, Ya16ToDeepGray { bits: 12 }),
        (P::Ya16Le,   P::Gray10Le, Ya16ToDeepGray { bits: 10 }),
        (P::Gray12Le, P::Ya16Le,   DeepGrayToYa16 { bits: 12 }),
        (P::Gray10Le, P::Ya16Le,   DeepGrayToYa16 { bits: 10 }),
    ]
};

fn lookup(src: PixelFormat, dst: PixelFormat) -> Option<&'static ConvertOp> {
    TABLE
        .iter()
        .find(|(s, d, _)| *s == src && *d == dst)
        .map(|(_, _, op)| op)
}

/// Dispatch descriptor for each coverage-table row. The variant
/// discriminates on the conversion family, and embedded fields carry
/// the variant-specific parameters (swizzle positions, chroma
/// subsampling, range direction, …).
#[derive(Clone, Copy)]
enum ConvertOp {
    Swizzle3 {
        src: rgb::Rgb3,
        dst: rgb::Rgb3,
    },
    Swizzle4 {
        src: rgb::Rgba4,
        dst: rgb::Rgba4,
    },
    Promote3To4 {
        src: rgb::Rgb3,
        dst: rgb::Rgba4,
    },
    Demote4To3 {
        src: rgb::Rgba4,
        dst: rgb::Rgb3,
    },
    Rgb48ToRgb24,
    Rgb24ToRgb48,
    Rgba64ToRgba,
    RgbaToRgba64,
    Gray8ToPacked3,
    /// Gray broadcast into a 4-byte packed pixel. `alpha_first: false`
    /// emits (g, g, g, 255) — Rgba and Bgra alike; `true` emits
    /// (255, g, g, g) for the alpha-first orders Argb / Abgr.
    Gray8ToPacked4 {
        alpha_first: bool,
    },
    Gray16ToGray8,
    Gray8ToGray16,
    MonoToGray {
        black_is_zero: bool,
    },
    GrayToMono {
        black_is_zero: bool,
    },
    /// Packed RGB(A) → `Gray8`: full-range luminance projection under
    /// the Y' row of the selected primaries. Alpha (if present) is
    /// dropped.
    RgbToGray {
        alpha_in: bool,
    },
    Ya8ToGray8,
    Gray8ToYa8,
    Ya8ToRgb24,
    Ya8ToRgba,
    Rgb24ToYa8,
    RgbaToYa8,
    /// `Ya16Le` → `Ya8`: high-byte truncation of both words.
    Ya16ToYa8,
    /// `Ya8` → `Ya16Le`: exact ×257 widen of both components (the
    /// inverse of [`Self::Ya16ToYa8`] on 8-bit content).
    Ya8ToYa16,
    /// `Ya16Le` → `Gray16Le`: luma word carried verbatim, alpha
    /// dropped.
    Ya16ToGray16,
    /// `Gray16Le` → `Ya16Le`: luma word carried verbatim, alpha
    /// synthesised opaque 65535.
    Gray16ToYa16,
    /// `Ya16Le` → `Gray8`: high byte of the luma word, alpha dropped.
    Ya16ToGray8,
    /// `Gray8` → `Ya16Le`: ×257 widen, alpha opaque 65535.
    Gray8ToYa16,
    /// `Ya16Le` → `Rgba64Le`: luma word broadcast into R, G, B; alpha
    /// word carried verbatim (bit-exact).
    Ya16ToRgba64,
    /// `Rgba64Le` → `Ya16Le`: rounded-mean luma derivation over the R,
    /// G, B words (the 16-bit analogue of the Ya8 rule); alpha word
    /// carried verbatim.
    Rgba64ToYa16,
    /// `Ya16Le` → packed 8-bit RGB: high-byte broadcast; the alpha
    /// high byte is carried (`Rgba`) or dropped (`Rgb24`).
    Ya16ToPacked8 {
        alpha: bool,
    },
    /// Packed 8-bit RGB → `Ya16Le`: rounded-mean luma then the exact
    /// ×257 widen; alpha widened from the source (`Rgba`) or opaque
    /// 65535 (`Rgb24`).
    Packed8ToYa16 {
        alpha_in: bool,
    },
    /// Any YUV-family source (planar, semi-planar NV, or planar +
    /// alpha) → `Gray8` by extracting the full-resolution luma plane.
    /// Chroma (and alpha, for `Yuva420P`) is dropped. `full_range`
    /// mirrors the source family: limited-range sources are rescaled
    /// 16..=235 → 0..=255; `YuvJ*` luma is copied verbatim. Only the
    /// luma plane is touched, so odd dimensions are fine even on
    /// subsampled sources.
    YuvLumaToGray {
        full_range: bool,
    },
    /// `Gray8` → planar YUV: the gray plane becomes luma (rescaled to
    /// limited range unless the destination is a full-range `YuvJ*`),
    /// and the chroma planes are synthesised at the neutral code 128.
    GrayToYuvPlanar {
        wsub: usize,
        hsub: usize,
        full_range: bool,
    },
    /// `Gray8` → NV12 / NV21: limited-range luma plus an all-neutral
    /// interleaved chroma plane (identical bytes for both NV orders).
    GrayToNv,
    YuvToRgb {
        wsub: usize,
        hsub: usize,
        alpha: bool,
        /// `true` for the full-range `YuvJ*` source families: the matrix
        /// range is a property of the *format*, so it overrides the range
        /// half of `ConvertOptions::color_space` (which still picks the
        /// primaries).
        full_range: bool,
    },
    RgbToYuv {
        wsub: usize,
        hsub: usize,
        alpha_in: bool,
        /// `true` when the destination is a full-range `YuvJ*` family.
        full_range: bool,
    },
    RescaleRange {
        wsub: usize,
        hsub: usize,
        to_full: bool,
    },
    /// Planar YUV → planar YUV with the luma plane copied byte-for-byte
    /// and the chroma planes resampled between two subsampling layouts.
    /// `src_wsub` / `src_hsub` describe the source's chroma division;
    /// `dst_wsub` / `dst_hsub` the destination's. Equal sub factors on
    /// both sides would be a no-op and are not registered.
    ChromaResample {
        src_wsub: usize,
        src_hsub: usize,
        dst_wsub: usize,
        dst_hsub: usize,
    },
    NvToYuv420p {
        is_nv12: bool,
    },
    Yuv420pToNv {
        is_nv12: bool,
    },
    NvToRgb {
        is_nv12: bool,
        /// `true` to emit RGBA, `false` to emit Rgb24.
        alpha: bool,
    },
    RgbToNv {
        is_nv12: bool,
        /// `true` if source is RGBA (alpha consumed by skipping the 4th byte).
        alpha_in: bool,
    },
    Packed422ToYuv422p {
        /// `true` for YUYV byte order, `false` for UYVY.
        is_yuyv: bool,
    },
    Yuv422pToPacked422 {
        is_yuyv: bool,
    },
    Packed422Swap,
    Packed422ToRgb {
        is_yuyv: bool,
        /// `true` to emit RGBA, `false` to emit Rgb24.
        alpha: bool,
    },
    RgbToPacked422 {
        is_yuyv: bool,
        /// `true` if source is RGBA (alpha consumed by skipping the 4th byte).
        alpha_in: bool,
    },
    /// `Pal8` → packed RGB(A): expansion through the frame-attached
    /// palette (or `ConvertOptions::palette`). Per-entry alpha comes
    /// from the palette-alpha side-channel — a transparent entry lands
    /// as alpha 0 on the `Rgba` row, entries the record does not cover
    /// are opaque — and is dropped on the `Rgb24` row.
    Pal8ToRgb {
        /// `true` to emit RGBA, `false` to emit Rgb24.
        alpha: bool,
    },
    /// Packed RGB(A) → `Pal8`: nearest-colour quantisation against
    /// `ConvertOptions::palette`; the output carries the table as the
    /// palette side-channel and, when any entry is not opaque, the
    /// palette-alpha record.
    RgbToPal8 {
        alpha_in: bool,
    },
    CmykToRgb {
        /// When true, output is RGBA (opaque alpha). When false, Rgb24.
        alpha: bool,
        /// When true, the source is the inverted-ink convention
        /// (`CmykInverted`, stored byte = 255 − ink).
        inverted: bool,
    },
    RgbToCmyk {
        /// When true, source is RGBA (alpha ignored). When false, Rgb24.
        alpha_in: bool,
        /// When true, the destination is `CmykInverted` (regular
        /// separation followed by the per-byte complement).
        inverted: bool,
    },
    /// `Cmyk` ↔ `CmykInverted`: complement every byte — an exact,
    /// self-inverse bijection serving both directions.
    CmykComplement,
    /// Alpha-less planar YUV (3 planes) → the `Yuva*` sibling with the
    /// same chroma grid (4 planes) by appending an opaque
    /// full-resolution alpha plane. `wsub` / `hsub` are the shared
    /// chroma division.
    YuvToYuva {
        wsub: usize,
        hsub: usize,
    },
    /// `Yuva*` → the alpha-less planar sibling by dropping the trailing
    /// full-resolution alpha plane.
    YuvaToYuv {
        wsub: usize,
        hsub: usize,
    },
    /// `Yuva420P` / `Yuva422P` / `Yuva444P` → packed RGB. The YUV math
    /// runs through the existing planar decoder for the format's chroma
    /// grid; the full-resolution alpha plane is either dropped
    /// (`alpha = false`, emit `Rgb24`) or interleaved into the output
    /// (`alpha = true`, emit `Rgba`).
    YuvaToRgb {
        wsub: usize,
        hsub: usize,
        alpha: bool,
    },
    /// Packed RGB → `Yuva420P` / `Yuva422P` / `Yuva444P`. The YUV math
    /// runs through the existing planar encoder; the alpha plane is
    /// either synthesised opaque (`alpha_in = false`, source is
    /// `Rgb24`) or split out of the input (`alpha_in = true`, source is
    /// `Rgba`).
    RgbToYuva {
        wsub: usize,
        hsub: usize,
        alpha_in: bool,
    },
    /// `Yuva*` → `Yuva*`: luma and the full-resolution alpha plane are
    /// copied byte-for-byte; the chroma pair is resampled between the
    /// two subsampling layouts with the same primitives as
    /// [`Self::ChromaResample`]. Alpha survives bit-exact.
    YuvaChromaResample {
        src_wsub: usize,
        src_hsub: usize,
        dst_wsub: usize,
        dst_hsub: usize,
    },
    /// 16-bit planar YUV → 16-bit planar YUV (`Yuv*P16Le` family): luma
    /// copied word-for-word, chroma resampled between the two
    /// subsampling layouts at full 16-bit precision via the
    /// `yuv::chroma16le_*` helpers (rounding mirrors the 8-bit
    /// [`Self::ChromaResample`] exactly).
    ChromaResample16 {
        src_wsub: usize,
        src_hsub: usize,
        dst_wsub: usize,
        dst_hsub: usize,
    },
    /// Planar GBR(A) → packed deep RGB (`Rgb48Le` / `Rgba64Le`). Reorders
    /// the G, B, R(, A) planes into packed R, G, B(, A) 16-bit words and
    /// widens each `bits`-significant sample to 16 bits by the ladder
    /// rule (MSB replication: zero → 0, peak → 65535). `alpha_in` names the
    /// source's 4-plane shape, `alpha_out` the packed `Rgba64Le` target;
    /// when they differ the alpha plane is dropped (`Gbrap* → Rgb48Le`)
    /// or synthesised opaque full-scale 65535 (`Gbrp* → Rgba64Le`).
    GbrToPackedDeep {
        bits: u8,
        alpha_in: bool,
        alpha_out: bool,
    },
    /// Packed deep RGB (`Rgb48Le` / `Rgba64Le`) → planar GBR(A). The
    /// inverse of [`Self::GbrToPackedDeep`]: splits the packed R, G, B(, A)
    /// words into G, B, R(, A) planes and truncates each by `16 - bits`
    /// back into the `bits`-significant low range. Mismatched alpha
    /// flags drop the packed alpha word (`Rgba64Le → Gbrp*`) or
    /// synthesise an opaque `(1 << bits) - 1` plane (`Rgb48Le → Gbrap*`).
    PackedDeepToGbr {
        bits: u8,
        alpha_in: bool,
        alpha_out: bool,
    },
    /// High-precision planar YUV (`Yuv*P10Le` / `Yuv*P12Le` /
    /// `Yuv*P16Le`, 16-bit LE storage) → the 8-bit planar sibling
    /// (`Yuv*P`). Each of the three planes is reduced from a
    /// `bits`-significant 16-bit word to 8 bits by truncation (keep the
    /// top 8 significant bits). `wsub` / `hsub` are the shared chroma
    /// division; subsampling is preserved (no chroma resample).
    DepthDownYuv {
        wsub: usize,
        hsub: usize,
        bits: u32,
    },
    /// 8-bit planar YUV (`Yuv*P`) → the high-precision planar sibling
    /// (`Yuv*P10Le` / `Yuv*P12Le` / `Yuv*P16Le`). The inverse of
    /// [`Self::DepthDownYuv`]: each plane is widened to a
    /// `bits`-significant 16-bit LE word with the 8-bit value in the
    /// high bits and its MSBs replicated into the low slack so the
    /// down-conversion round-trips exactly (for `bits = 16` the widen
    /// is an exact ×257 and full-scale 255 maps to 65535).
    DepthUpYuv {
        wsub: usize,
        hsub: usize,
        bits: u32,
    },
    /// Planar GBR(A) → 8-bit packed `Rgb24` / `Rgba`: plane reorder plus
    /// a `bits` → 8 narrowing (keep the top 8 significant bits).
    GbrToPacked8 {
        bits: u32,
        alpha: bool,
    },
    /// 8-bit packed `Rgb24` / `Rgba` → planar GBR(A): plane split plus an
    /// 8 → `bits` MSB-replicated widen (exact inverse of
    /// [`Self::GbrToPacked8`], so 8-bit content round-trips losslessly).
    Packed8ToGbr {
        bits: u32,
        alpha: bool,
    },
    /// Byte-tier planar GBR(A) (`Gbrp8` / `Gbrap8`) → packed `Rgb24` /
    /// `Rgba`: pure plane reorder, no depth math — bit-exact, and the
    /// matched-alpha pairs are self-inverse with
    /// [`Self::Packed8ToGbr8`]. When the alpha flags differ the alpha
    /// is synthesised opaque 255 (`alpha_out` without `alpha_in`) or
    /// dropped (`alpha_in` without `alpha_out`).
    Gbr8ToPacked8 {
        alpha_in: bool,
        alpha_out: bool,
    },
    /// Packed `Rgb24` / `Rgba` → byte-tier planar GBR(A): the inverse
    /// plane split of [`Self::Gbr8ToPacked8`], same alpha convention.
    Packed8ToGbr8 {
        alpha_in: bool,
        alpha_out: bool,
    },
    /// Byte-tier planar GBR(A) → packed deep RGB: plane reorder plus
    /// the exact ×257 widen into full-width 16-bit words (peak maps to
    /// peak), mirroring `Rgb24 → Rgb48Le`. A carried alpha
    /// (`alpha_in && alpha_out`) is widened like the colour bytes; a
    /// missing one is synthesised opaque 65535 and a surplus one is
    /// dropped.
    Gbr8ToPackedDeep {
        alpha_in: bool,
        alpha_out: bool,
    },
    /// Packed deep RGB (`Rgb48Le` / `Rgba64Le`) → byte-tier planar
    /// GBR(A): plane split keeping the top byte of each word
    /// (truncation — the exact inverse of the ×257 widen). Alpha is
    /// carried truncated, synthesised opaque 255, or dropped per the
    /// flag pair.
    PackedDeepToGbr8 {
        alpha_in: bool,
        alpha_out: bool,
    },
    /// `Gbrp8` ↔ `Gbrap8`: colour planes copied byte-for-byte; `add`
    /// appends an opaque 255 full-resolution alpha plane, `!add` drops
    /// plane 3 (the byte-tier mirror of [`Self::YuvToYuva`] /
    /// [`Self::YuvaToYuv`]).
    Gbr8Alpha {
        add: bool,
    },
    /// Planar GBR(A) → `Gray8`: narrow each colour plane to 8 bits
    /// (top-bits truncation, crate depth policy) and project through
    /// the full-range Y' row of the selected primaries — the same
    /// kernel as the packed [`Self::RgbToGray`] rows, so `r = g = b`
    /// content maps to itself exactly. Alpha (when present) is dropped.
    GbrToGray {
        bits: u32,
        alpha_in: bool,
    },
    /// `Gray8` → planar GBR(A): broadcast the gray value into the G, B
    /// and R planes at the family depth (MSB-replicated widen — peak
    /// maps to peak, and [`Self::GbrToGray`] recovers the original
    /// exactly). `alpha_out` appends an opaque full-scale alpha plane.
    GrayToGbr {
        bits: u32,
        alpha_out: bool,
    },
    /// Cross-depth planar YUV: rescale every plane between two
    /// `bits`-significant 16-bit LE storage widths (10 ↔ 12 ↔ 16) with
    /// the subsampling layout preserved. Widening replicates MSBs into
    /// the new low bits; narrowing truncates them (exact inverses).
    DepthRescaleYuv {
        wsub: usize,
        hsub: usize,
        src_bits: u32,
        dst_bits: u32,
    },
    /// Deep grayscale (`Gray10Le` / `Gray12Le`) → `Gray8`: keep the top
    /// 8 of the `bits` significant bits (same primitive as the YUV depth
    /// ladder).
    GrayDepthDown8 {
        bits: u32,
    },
    /// `Gray8` → deep grayscale: value in the high bits with MSB
    /// replication into the low slack, so `GrayDepthDown8` recovers the
    /// original exactly.
    GrayDepthUp8 {
        bits: u32,
    },
    /// Deep grayscale ↔ deep grayscale storage-width rescale
    /// (10 ↔ 12 ↔ 16), single plane.
    GrayDepthRescale {
        src_bits: u32,
        dst_bits: u32,
    },
    /// 16-bit planar YUV(A) → packed deep RGB at full precision: the
    /// Q30/i64 deep matrix decodes 16-bit samples directly (no 8-bit
    /// narrowing anywhere on the path). Subsampled chroma is upsampled
    /// to 4:4:4 at 16-bit precision first; with `alpha` the source's
    /// full-resolution 16-bit alpha plane is carried verbatim into the
    /// `Rgba64Le` alpha word.
    DeepYuvToRgb48 {
        wsub: usize,
        hsub: usize,
        alpha: bool,
    },
    /// Computed: any planar family member → `Rgb48Le` (`alpha == false`)
    /// / `Rgba64Le` (`alpha == true`) through the deep matrix in one
    /// banded pass — every sample widened to 16 bits (MSB replication),
    /// chroma read nearest, alpha widened or synthesised opaque. The
    /// same bytes as the widen-to-`Yuva444P16Le` staged route it
    /// replaces.
    FamilyToPacked16 {
        src: PlanarYuv,
        alpha: bool,
    },
    /// Packed deep RGB → 16-bit planar YUV(A) at full precision: the
    /// inverse of [`Self::DeepYuvToRgb48`] — encode at 4:4:4, then
    /// downsample chroma at 16-bit precision; with `alpha` the packed
    /// alpha word becomes the full-resolution alpha plane verbatim.
    Rgb48ToDeepYuv {
        wsub: usize,
        hsub: usize,
        alpha: bool,
    },
    /// `Rgb48Le` → `Rgba64Le`: colour words verbatim + opaque 65535
    /// alpha word (exact; inverse of [`Self::Rgba64ToRgb48`]).
    Rgb48ToRgba64,
    /// `Rgba64Le` → `Rgb48Le`: colour words verbatim, alpha dropped.
    Rgba64ToRgb48,
    /// Any 8-bit packed RGB order → `Gray8`: gather the pixel through
    /// the `(comps, r, g, b)` byte positions into canonical R, G, B
    /// order and run the same full-range luminance projection as
    /// [`Self::RgbToGray`] — byte-identical to the previously-staged
    /// swizzle + project route.
    PackedPosToGray {
        comps: usize,
        r: usize,
        g: usize,
        b: usize,
    },
    /// `Rgb48Le` / `Rgba64Le` → `Gray8`: keep the top byte of each
    /// colour word (crate depth policy), then project. Alpha dropped.
    DeepPackedToGray {
        alpha_in: bool,
    },
    /// `Gray8` → `Rgb48Le` / `Rgba64Le`: exact ×257 broadcast (peak
    /// maps to peak; the projection recovers the original exactly),
    /// with an opaque 65535 alpha word when the target carries one.
    GrayToPackedDeep {
        alpha_out: bool,
    },
    /// `Gray10Le` / `Gray12Le` / `Gray16Le` → `Rgb48Le` / `Rgba64Le`:
    /// the grey word widened to 16 bits by the exact ladder rule (MSB
    /// replication; verbatim at 16) and broadcast into R, G, B, with an
    /// opaque 65535 alpha word when the target carries one. Row-banded.
    DeepGrayToPackedDeep {
        bits: u32,
        alpha_out: bool,
    },
    /// `Rgb48Le` / `Rgba64Le` → `Gray10Le` / `Gray12Le` / `Gray16Le`:
    /// the Q30 full-range Y' row evaluated at 16 bits (within 1 LSB of
    /// the f64 projection; `r = g = b = v` gives `v` exactly), then
    /// narrowed to the target width by truncation. Alpha dropped.
    /// Row-banded.
    PackedDeepToDeepGray {
        bits: u32,
        alpha_in: bool,
    },
    /// `Ya16Le` → `Gray10Le` / `Gray12Le`: luma word narrowed
    /// (truncation), alpha dropped.
    Ya16ToDeepGray {
        bits: u32,
    },
    /// `Gray10Le` / `Gray12Le` → `Ya16Le`: grey word widened to 16 bits
    /// (MSB replication), alpha opaque 65535.
    DeepGrayToYa16 {
        bits: u32,
    },
    /// `Cmyk` / `CmykInverted` → `Gray8`: device decode to RGB, then
    /// the full-range luminance projection.
    CmykToGray {
        inverted: bool,
    },
    /// `Gray8` → `Cmyk` / `CmykInverted`: the separation of
    /// `r = g = b = v` is pure black ink `(0, 0, 0, 255 − v)` (or its
    /// complement) — byte-identical to broadcast + separation.
    GrayToCmyk {
        inverted: bool,
    },
    /// `Pal8` → `Gray8`: palette expansion (side-channel or
    /// `ConvertOptions` table, as for [`Self::Pal8ToRgb`]) followed by
    /// the luminance projection.
    Pal8ToGray,
    /// `Gray8` → `Pal8`: grey broadcast followed by the quantiser —
    /// same palette/dither handling as [`Self::RgbToPal8`].
    GrayToPal8,
    /// Packed 4:2:2 → `Gray8`: extract the luma bytes and rescale
    /// limited → full range (chroma never read). Mirrors
    /// [`Self::YuvLumaToGray`] for the packed carriers.
    Packed422ToGray {
        is_yuyv: bool,
    },
    /// `Gray8` → packed 4:2:2: full → limited luma plus neutral 128
    /// chroma, interleaved in the requested byte order. Mirrors
    /// [`Self::GrayToYuvPlanar`] for the packed carriers.
    GrayToPacked422 {
        is_yuyv: bool,
    },
    /// Computed tier (see [`lookup_computed`]): any ordered pair inside
    /// the uniform planar YUV(A) family. Fuses the depth move, the
    /// chroma resample (performed at the deeper of the two depths) and
    /// the alpha handling (carry with depth move / drop / synthesise
    /// opaque full-scale) into one step. Luma — and a carried alpha
    /// plane — never touch the resampler, so they survive bit-exact
    /// whenever the depths match.
    PlanarFamily {
        src: PlanarYuv,
        dst: PlanarYuv,
    },
    /// Computed tier: planar family member → packed `Rgb24` / `Rgba`.
    /// Deep planes are reduced to 8 bits (truncation, per the crate
    /// depth policy) before the proven 8-bit scalar/SIMD decode; alpha
    /// is carried (reduced to 8 bits), synthesised opaque, or dropped.
    PlanarFamilyToRgb {
        src: PlanarYuv,
        alpha: bool,
    },
    /// Computed tier: packed `Rgb24` / `Rgba` → planar family member.
    /// Encodes through the proven 8-bit path, then widens every plane
    /// (MSB replication) to the destination depth; alpha is split out
    /// of an `Rgba` source or synthesised opaque full-scale.
    RgbToPlanarFamily {
        dst: PlanarYuv,
        alpha_in: bool,
    },
    /// Computed tier: planar family member → `Gray8` luma extraction
    /// (deep luma truncated to 8 bits, then limited → full range
    /// rescale; chroma and alpha dropped).
    PlanarFamilyToGray {
        src: PlanarYuv,
    },
    /// Computed tier: `Gray8` → planar family member. The gray plane
    /// becomes luma (full → limited range, then widened to the family
    /// depth); chroma is synthesised at the exact neutral mid-code
    /// `1 << (bits - 1)` (512 at 10 bits, 32768 at 16 — not the
    /// widened 8-bit 128, which lands a couple of codes off neutral);
    /// alpha (when present) is synthesised opaque full-scale.
    GrayToPlanarFamily {
        dst: PlanarYuv,
    },
    /// Computed tier: packed `Rgb48Le` / `Rgba64Le` → any planar family
    /// member. One banded 16-bit encode through the Q30 deep matrix
    /// with the chroma subsampled at 16 bits, then every plane narrowed
    /// to the member's depth (truncation). Alpha carried / dropped /
    /// synthesised opaque full-scale.
    Packed16ToFamily {
        dst: PlanarYuv,
        alpha_in: bool,
    },
    /// Computed tier: `Gray10Le` / `Gray12Le` / `Gray16Le` → any planar
    /// family member. The grey plane becomes luma: widened to
    /// the deeper of the two depths (exact ladder rule), moved full →
    /// limited range there (H.273 equations 27–29 at that depth) unless
    /// the signal is full range, then narrowed to the member's depth;
    /// chroma is the exact neutral mid-code `1 << (bits − 1)`; alpha
    /// (when carried) is opaque full-scale. No colour matrix.
    DeepGrayToPlanarFamily {
        bits: u32,
        dst: PlanarYuv,
    },
    /// Computed tier: any planar family member → `Gray10Le` /
    /// `Gray12Le` / `Gray16Le` via the luma plane: widened to the
    /// deeper of the two depths, limited → full range there unless the
    /// signal is full range, then narrowed to the grey width. Chroma
    /// and alpha are never read.
    PlanarFamilyToDeepGray {
        src: PlanarYuv,
        bits: u32,
    },
    /// Computed tier: planar GBR(A) at any ladder depth → `Gray10Le` /
    /// `Gray12Le` / `Gray16Le`: every sample widened to 16 bits (ladder
    /// rule), the Q30 full-range Y' row at 16 bits, then narrowed to
    /// the grey width. Alpha never read. Row-banded.
    GbrToDeepGray {
        src: IntLayout,
        bits: u32,
    },
    /// Computed tier: `Gray10Le` / `Gray12Le` / `Gray16Le` → planar
    /// GBR(A) at any ladder depth: the grey word rescaled to the GBR
    /// depth (ladder rule) and broadcast into the G, B, R planes; alpha
    /// opaque full-scale when the target carries it. Row-banded.
    DeepGrayToGbr {
        bits: u32,
        dst: IntLayout,
    },
    /// Computed tier: any ordered pair inside the scene-referred float
    /// family. Gray broadcasts to colour, colour projects to gray
    /// through the linear-light luminance row of the selected
    /// primaries, alpha is carried / dropped / synthesised `1.0`, and
    /// packed ↔ planar is a pure reorder. Sample values are never
    /// clamped — out-of-range light survives.
    FloatToFloat {
        src: FloatLayout,
        dst: FloatLayout,
    },
    /// Computed tier: float family member → integer gray / packed RGB
    /// / planar GBR(A) format (see [`crate::float`] for the saturating
    /// quantisation rule).
    FloatToInt {
        src: FloatLayout,
        dst: IntLayout,
    },
    /// Computed tier: integer gray / packed RGB / planar GBR(A) format
    /// → float family member (exact normalisation, no transfer).
    IntToFloat {
        src: IntLayout,
        dst: FloatLayout,
    },
    /// Computed tier: float family member → 16-bit planar YUV(A)
    /// tier: quantise to a packed 16-bit RGB(A) intermediate, then the
    /// Q30 deep matrix + 16-bit chroma resample — no 8-bit stage.
    FloatToDeepYuv {
        src: FloatLayout,
        dst: PlanarYuv,
    },
    /// Computed tier: 16-bit planar YUV(A) tier → float family member
    /// through the Q30 deep matrix at 16 bits, then the exact
    /// normalisation.
    DeepYuvToFloat {
        src: PlanarYuv,
        dst: FloatLayout,
    },
}

impl ConvertOp {
    fn apply(
        &self,
        src: &VideoFrame,
        src_info: FrameInfo,
        opts: &ConvertOptions,
        ctx: &Resolved,
    ) -> Result<VideoFrame> {
        // The plain `Yuv*` paths use the limited-range matrix and the
        // full-range `YuvJ*` paths the full-range matrix — range is a
        // property of the pixel format, so only the primaries half of
        // `ConvertOptions::color_space` is honoured here; the YuvToRgb /
        // RgbToYuv / gray arms below carry their format's range in a
        // `full_range` field. A resolved colour signal (context override
        // or the source frame's record) overrides the format's range on
        // every arm that has a YUV side, and a signalled matrix replaces
        // the `color_space` weights on the hops that cross YUV ↔ RGB.
        let primaries = ctx.primaries(opts);
        // Matrix for an arm whose YUV format pins limited range.
        let matrix = primaries.with_range(ctx.limited(true));
        // Matrix for an arm whose YUV format pins `full_range`.
        let ranged = |full_range: bool| primaries.with_range(ctx.limited(!full_range));
        let workers = ctx.workers(src_info.height as usize);
        match *self {
            Self::Swizzle3 { src: sp, dst: dp } => swizzle3(src, src_info, sp, dp),
            Self::Swizzle4 { src: sp, dst: dp } => swizzle4(src, src_info, sp, dp),
            Self::Promote3To4 { src: sp, dst: dp } => promote3_to_4(src, src_info, sp, dp),
            Self::Demote4To3 { src: sp, dst: dp } => demote4_to_3(src, src_info, sp, dp),
            Self::Rgb48ToRgb24 => do_rgb48_to_rgb24(src, src_info),
            Self::Rgb24ToRgb48 => do_rgb24_to_rgb48(src, src_info),
            Self::Rgba64ToRgba => do_rgba64_to_rgba(src, src_info),
            Self::RgbaToRgba64 => do_rgba_to_rgba64(src, src_info),
            Self::Gray8ToPacked3 => gray_to_packed3(src, src_info),
            Self::Gray8ToPacked4 { alpha_first } => gray_to_packed4(src, src_info, alpha_first),
            Self::Gray16ToGray8 => do_gray16_to_gray8(src, src_info),
            Self::Gray8ToGray16 => do_gray8_to_gray16(src, src_info),
            Self::MonoToGray { black_is_zero } => do_mono_to_gray(src, src_info, black_is_zero),
            Self::GrayToMono { black_is_zero } => do_gray_to_mono(src, src_info, black_is_zero),
            Self::RgbToGray { alpha_in } => {
                do_rgb_to_gray(src, src_info, matrix.with_range(false), alpha_in)
            }
            Self::Ya8ToGray8 => do_ya8_to_gray8(src, src_info),
            Self::Gray8ToYa8 => do_gray8_to_ya8(src, src_info),
            Self::Ya8ToRgb24 => do_ya8_to_rgb24(src, src_info),
            Self::Ya8ToRgba => do_ya8_to_rgba(src, src_info),
            Self::Rgb24ToYa8 => do_rgb24_to_ya8(src, src_info),
            Self::RgbaToYa8 => do_rgba_to_ya8(src, src_info),
            Self::Ya16ToYa8 => packed_map(src, src_info, 4, 2, gray::ya16le_to_ya8),
            Self::Ya8ToYa16 => packed_map(src, src_info, 2, 4, gray::ya8_to_ya16le),
            Self::Ya16ToGray16 => packed_map(src, src_info, 4, 2, gray::ya16le_to_gray16le),
            Self::Gray16ToYa16 => packed_map(src, src_info, 2, 4, gray::gray16le_to_ya16le),
            Self::Ya16ToGray8 => packed_map(src, src_info, 4, 1, gray::ya16le_to_gray8),
            Self::Gray8ToYa16 => packed_map(src, src_info, 1, 4, gray::gray8_to_ya16le),
            Self::Ya16ToRgba64 => packed_map(src, src_info, 4, 8, gray::ya16le_to_rgba64le),
            Self::Rgba64ToYa16 => packed_map(src, src_info, 8, 4, gray::rgba64le_to_ya16le),
            Self::Ya16ToPacked8 { alpha } => {
                if alpha {
                    packed_map(src, src_info, 4, 4, gray::ya16le_to_rgba)
                } else {
                    packed_map(src, src_info, 4, 3, gray::ya16le_to_rgb24)
                }
            }
            Self::Packed8ToYa16 { alpha_in } => {
                if alpha_in {
                    packed_map(src, src_info, 4, 4, gray::rgba_to_ya16le)
                } else {
                    packed_map(src, src_info, 3, 4, gray::rgb24_to_ya16le)
                }
            }
            Self::YuvLumaToGray { full_range } => {
                do_yuv_luma_to_gray(src, src_info, !ctx.limited(!full_range))
            }
            Self::GrayToYuvPlanar {
                wsub,
                hsub,
                full_range,
            } => do_gray_to_yuv_planar(src, src_info, wsub, hsub, !ctx.limited(!full_range)),
            Self::GrayToNv => do_gray_to_nv(src, src_info, !ctx.limited(true)),
            Self::YuvToRgb {
                wsub,
                hsub,
                alpha,
                full_range,
            } => do_yuv_to_rgb(
                src,
                src_info,
                ranged(full_range),
                wsub,
                hsub,
                alpha,
                workers,
            ),
            Self::RgbToYuv {
                wsub,
                hsub,
                alpha_in,
                full_range,
            } => do_rgb_to_yuv(
                src,
                src_info,
                ranged(full_range),
                wsub,
                hsub,
                alpha_in,
                workers,
            ),
            Self::RescaleRange {
                wsub,
                hsub,
                to_full,
            } => {
                // The source's label is limited when rescaling to full
                // (and full otherwise); a signal that already puts the
                // samples in the destination's range makes the move a
                // plain copy.
                let src_limited = ctx.limited(to_full);
                let rescale = src_limited == to_full;
                rescale_range(src, src_info, wsub, hsub, to_full, rescale)
            }
            Self::ChromaResample {
                src_wsub,
                src_hsub,
                dst_wsub,
                dst_hsub,
            } => chroma_resample(src, src_info, src_wsub, src_hsub, dst_wsub, dst_hsub),
            Self::NvToYuv420p { is_nv12 } => nv_to_yuv420p(src, src_info, is_nv12),
            Self::Yuv420pToNv { is_nv12 } => yuv420p_to_nv(src, src_info, is_nv12),
            Self::NvToRgb { is_nv12, alpha } => {
                nv_to_rgb(src, src_info, matrix, is_nv12, alpha, workers)
            }
            Self::RgbToNv { is_nv12, alpha_in } => {
                rgb_to_nv(src, src_info, matrix, is_nv12, alpha_in, workers)
            }
            Self::Packed422ToYuv422p { is_yuyv } => packed422_to_yuv422p(src, src_info, is_yuyv),
            Self::Yuv422pToPacked422 { is_yuyv } => yuv422p_to_packed422(src, src_info, is_yuyv),
            Self::Packed422Swap => packed422_swap(src, src_info),
            Self::Packed422ToRgb { is_yuyv, alpha } => {
                packed422_to_rgb(src, src_info, matrix, is_yuyv, alpha)
            }
            Self::RgbToPacked422 { is_yuyv, alpha_in } => {
                rgb_to_packed422(src, src_info, matrix, is_yuyv, alpha_in)
            }
            Self::Pal8ToRgb { alpha } => pal8_to_rgb(src, src_info, opts, alpha),
            Self::RgbToPal8 { alpha_in } => rgb_to_pal8(src, src_info, opts, alpha_in),
            Self::CmykToRgb { alpha, inverted } => {
                let f = match (alpha, inverted) {
                    (false, false) => cmyk::cmyk_to_rgb24,
                    (true, false) => cmyk::cmyk_to_rgba,
                    (false, true) => cmyk::cmyk_inverted_to_rgb24,
                    (true, true) => cmyk::cmyk_inverted_to_rgba,
                };
                packed_map(src, src_info, 4, if alpha { 4 } else { 3 }, f)
            }
            Self::RgbToCmyk { alpha_in, inverted } => {
                let f = match (alpha_in, inverted) {
                    (false, false) => cmyk::rgb24_to_cmyk,
                    (true, false) => cmyk::rgba_to_cmyk,
                    (false, true) => cmyk::rgb24_to_cmyk_inverted,
                    (true, true) => cmyk::rgba_to_cmyk_inverted,
                };
                packed_map(src, src_info, if alpha_in { 4 } else { 3 }, 4, f)
            }
            Self::CmykComplement => packed_map(src, src_info, 4, 4, cmyk::cmyk_complement),
            Self::YuvToYuva { wsub, hsub } => do_yuv_to_yuva(src, src_info, wsub, hsub),
            Self::YuvaToYuv { wsub, hsub } => do_yuva_to_yuv(src, src_info, wsub, hsub),
            Self::YuvaToRgb { wsub, hsub, alpha } => {
                do_yuva_to_rgb(src, src_info, matrix, wsub, hsub, alpha, workers)
            }
            Self::RgbToYuva {
                wsub,
                hsub,
                alpha_in,
            } => do_rgb_to_yuva(src, src_info, matrix, wsub, hsub, alpha_in, workers),
            Self::YuvaChromaResample {
                src_wsub,
                src_hsub,
                dst_wsub,
                dst_hsub,
            } => yuva_chroma_resample(src, src_info, src_wsub, src_hsub, dst_wsub, dst_hsub),
            Self::ChromaResample16 {
                src_wsub,
                src_hsub,
                dst_wsub,
                dst_hsub,
            } => chroma_resample16(src, src_info, src_wsub, src_hsub, dst_wsub, dst_hsub),
            Self::GbrToPackedDeep {
                bits,
                alpha_in,
                alpha_out,
            } => do_gbr_to_packed_deep(src, src_info, bits, alpha_in, alpha_out, workers),
            Self::PackedDeepToGbr {
                bits,
                alpha_in,
                alpha_out,
            } => do_packed_deep_to_gbr(src, src_info, bits, alpha_in, alpha_out, workers),
            Self::Gbr8ToPackedDeep {
                alpha_in,
                alpha_out,
            } => do_gbr8_to_packed_deep(src, src_info, alpha_in, alpha_out),
            Self::PackedDeepToGbr8 {
                alpha_in,
                alpha_out,
            } => do_packed_deep_to_gbr8(src, src_info, alpha_in, alpha_out),
            Self::Gbr8Alpha { add } => do_gbr8_alpha(src, src_info, add),
            Self::GbrToGray { bits, alpha_in } => {
                // Gray8 is a full-range space — like the packed RgbToGray
                // rows, the projection always uses the full-range Y' row
                // (the ColorSpace knob still picks the primaries).
                do_gbr_to_gray(src, src_info, matrix.with_range(false), bits, alpha_in)
            }
            Self::GrayToGbr { bits, alpha_out } => do_gray_to_gbr(src, src_info, bits, alpha_out),
            Self::DepthDownYuv { wsub, hsub, bits } => {
                do_yuv_depth_down(src, src_info, wsub, hsub, bits)
            }
            Self::DepthUpYuv { wsub, hsub, bits } => {
                do_yuv_depth_up(src, src_info, wsub, hsub, bits)
            }
            Self::GbrToPacked8 { bits, alpha } => do_gbr_to_packed8(src, src_info, bits, alpha),
            Self::Packed8ToGbr { bits, alpha } => do_packed8_to_gbr(src, src_info, bits, alpha),
            Self::Gbr8ToPacked8 {
                alpha_in,
                alpha_out,
            } => do_gbr8_to_packed8(src, src_info, alpha_in, alpha_out),
            Self::Packed8ToGbr8 {
                alpha_in,
                alpha_out,
            } => do_packed8_to_gbr8(src, src_info, alpha_in, alpha_out),
            Self::DepthRescaleYuv {
                wsub,
                hsub,
                src_bits,
                dst_bits,
            } => do_yuv_depth_rescale(src, src_info, wsub, hsub, src_bits, dst_bits),
            Self::GrayDepthDown8 { bits } => do_gray_depth_down8(src, src_info, bits),
            Self::GrayDepthUp8 { bits } => do_gray_depth_up8(src, src_info, bits),
            Self::GrayDepthRescale { src_bits, dst_bits } => {
                do_gray_depth_rescale(src, src_info, src_bits, dst_bits)
            }
            Self::DeepYuvToRgb48 { wsub, hsub, alpha } => {
                do_deep_yuv_to_rgb48(src, src_info, matrix, wsub, hsub, alpha, workers)
            }
            Self::FamilyToPacked16 { src: s, alpha } => {
                deep_family_to_packed16(src, src_info, matrix, s, alpha, workers)
            }
            Self::Rgb48ToDeepYuv { wsub, hsub, alpha } => {
                do_rgb48_to_deep_yuv(src, src_info, matrix, wsub, hsub, alpha, workers)
            }
            Self::Packed16ToFamily { dst: d, alpha_in } => {
                packed16_to_family(src, src_info, matrix, d, alpha_in, workers)
            }
            Self::GbrToDeepGray { src: il, bits } => {
                gbr_to_deep_gray(src, src_info, matrix.with_range(false), il, bits, workers)
            }
            Self::DeepGrayToGbr { bits, dst: il } => {
                deep_gray_to_gbr(src, src_info, bits, il, workers)
            }
            Self::DeepGrayToPlanarFamily { bits, dst: d } => {
                deep_gray_to_planar_family(src, src_info, bits, d, ctx.limited(true), workers)
            }
            Self::PlanarFamilyToDeepGray { src: s, bits } => {
                planar_family_to_deep_gray(src, src_info, s, bits, ctx.limited(true), workers)
            }
            Self::Rgb48ToRgba64 => packed_map(src, src_info, 6, 8, rgb::rgb48_to_rgba64),
            Self::Rgba64ToRgb48 => packed_map(src, src_info, 8, 6, rgb::rgba64_to_rgb48),
            Self::PackedPosToGray { comps, r, g, b } => {
                do_packed_pos_to_gray(src, src_info, matrix.with_range(false), comps, r, g, b)
            }
            Self::DeepPackedToGray { alpha_in } => {
                do_deep_packed_to_gray(src, src_info, matrix.with_range(false), alpha_in)
            }
            Self::GrayToPackedDeep { alpha_out } => {
                if alpha_out {
                    packed_map(src, src_info, 1, 8, gray::gray8_to_rgba64le)
                } else {
                    packed_map(src, src_info, 1, 6, gray::gray8_to_rgb48le)
                }
            }
            Self::DeepGrayToPackedDeep { bits, alpha_out } => {
                do_deep_gray_to_packed_deep(src, src_info, bits, alpha_out, workers)
            }
            Self::PackedDeepToDeepGray { bits, alpha_in } => do_packed_deep_to_deep_gray(
                src,
                src_info,
                matrix.with_range(false),
                bits,
                alpha_in,
                workers,
            ),
            Self::Ya16ToDeepGray { bits } => do_ya16_to_deep_gray(src, src_info, bits),
            Self::DeepGrayToYa16 { bits } => do_deep_gray_to_ya16(src, src_info, bits),
            Self::CmykToGray { inverted } => {
                let f = if inverted {
                    cmyk::cmyk_inverted_to_rgb24
                } else {
                    cmyk::cmyk_to_rgb24
                };
                let rgb = packed_map(src, src_info, 4, 3, f)?;
                let rgb_info = FrameInfo::new(PixelFormat::Rgb24, src_info.width, src_info.height);
                do_rgb_to_gray(&rgb, rgb_info, matrix.with_range(false), false)
            }
            Self::GrayToCmyk { inverted } => {
                let f = if inverted {
                    cmyk::gray8_to_cmyk_inverted
                } else {
                    cmyk::gray8_to_cmyk
                };
                packed_map(src, src_info, 1, 4, f)
            }
            Self::Pal8ToGray => {
                let rgb = pal8_to_rgb(src, src_info, opts, false)?;
                let rgb_info = FrameInfo::new(PixelFormat::Rgb24, src_info.width, src_info.height);
                do_rgb_to_gray(&rgb, rgb_info, matrix.with_range(false), false)
            }
            Self::GrayToPal8 => {
                let rgb = gray_to_packed3(src, src_info)?;
                let rgb_info = FrameInfo::new(PixelFormat::Rgb24, src_info.width, src_info.height);
                rgb_to_pal8(&rgb, rgb_info, opts, false)
            }
            Self::Packed422ToGray { is_yuyv } => do_packed422_to_gray(src, src_info, is_yuyv),
            Self::GrayToPacked422 { is_yuyv } => do_gray_to_packed422(src, src_info, is_yuyv),
            Self::PlanarFamily { src: s, dst: d } => planar_family(src, src_info, s, d),
            Self::PlanarFamilyToRgb { src: s, alpha } => {
                planar_family_to_rgb(src, src_info, matrix, s, alpha, workers)
            }
            Self::RgbToPlanarFamily { dst: d, alpha_in } => {
                rgb_to_planar_family(src, src_info, matrix, d, alpha_in, workers)
            }
            Self::PlanarFamilyToGray { src: s } => {
                planar_family_to_gray(src, src_info, s, ctx.limited(true))
            }
            Self::GrayToPlanarFamily { dst: d } => {
                gray_to_planar_family(src, src_info, d, ctx.limited(true))
            }
            Self::FloatToFloat { src: s, dst: d } => {
                float_to_float(src, src_info, matrix.with_range(false), s, d)
            }
            Self::FloatToInt { src: s, dst: d } => {
                float_to_int(src, src_info, matrix.with_range(false), s, d)
            }
            Self::IntToFloat { src: s, dst: d } => {
                int_to_float(src, src_info, matrix.with_range(false), s, d)
            }
            Self::FloatToDeepYuv { src: s, dst: d } => {
                float_to_deep_yuv(src, src_info, matrix, s, d)
            }
            Self::DeepYuvToFloat { src: s, dst: d } => {
                deep_yuv_to_float(src, src_info, matrix, s, d)
            }
        }
    }
}

// -------------------------------------------------------------------------
// Frame helpers.

fn make_frame(src: &VideoFrame, planes: Vec<VideoPlane>) -> VideoFrame {
    VideoFrame {
        pts: src.pts,
        planes,
    }
}

fn tight_row(src: &[u8], stride: usize, row: usize, row_bytes: usize) -> &[u8] {
    let off = row * stride;
    &src[off..off + row_bytes]
}

/// Row-wise map between two single-plane packed layouts: gather each
/// tight source row (`src_bpp` bytes/pixel) and let `f` emit the
/// corresponding destination row (`dst_bpp` bytes/pixel). The kernel
/// signature matches the low-level `(src, dst, pixels)` helpers in
/// [`crate::gray`] / [`crate::rgb`].
fn packed_map(
    src: &VideoFrame,
    src_info: FrameInfo,
    src_bpp: usize,
    dst_bpp: usize,
    f: fn(&[u8], &mut [u8], usize),
) -> Result<VideoFrame> {
    let w = src_info.width as usize;
    let h = src_info.height as usize;
    let in_plane = &src.planes[0];
    let mut out = vec![0u8; w * h * dst_bpp];
    for row in 0..h {
        let sr = tight_row(&in_plane.data, in_plane.stride, row, w * src_bpp);
        f(sr, &mut out[row * w * dst_bpp..(row + 1) * w * dst_bpp], w);
    }
    Ok(make_frame(
        src,
        vec![VideoPlane {
            stride: w * dst_bpp,
            data: out,
        }],
    ))
}

/// Gather a plane's `w_bytes × h` payload into a tight buffer. A plane
/// too short for the geometry is `Error::Invalid`, never a panic — the
/// same rules as [`tight_plane`], which the hot paths use to avoid the
/// copy altogether.
fn gather_tight(src: &[u8], stride: usize, w_bytes: usize, h: usize) -> Result<Vec<u8>> {
    if h == 0 || w_bytes == 0 {
        return Ok(Vec::new());
    }
    if stride < w_bytes {
        return Err(Error::invalid(format!(
            "pixfmt: plane stride {stride} shorter than its {w_bytes}-byte rows"
        )));
    }
    let need = stride
        .checked_mul(h - 1)
        .and_then(|v| v.checked_add(w_bytes))
        .ok_or_else(|| Error::invalid("pixfmt: plane geometry overflows usize"))?;
    if src.len() < need {
        return Err(Error::invalid(format!(
            "pixfmt: plane holds {} bytes, geometry needs {need}",
            src.len()
        )));
    }
    if stride == w_bytes {
        return Ok(src[..need].to_vec());
    }
    let mut out = Vec::with_capacity(w_bytes * h);
    for row in 0..h {
        out.extend_from_slice(tight_row(src, stride, row, w_bytes));
    }
    Ok(out)
}

// -------------------------------------------------------------------------
// RGB family.

fn swizzle3(
    src: &VideoFrame,
    src_info: FrameInfo,
    src_pos: rgb::Rgb3,
    dst_pos: rgb::Rgb3,
) -> Result<VideoFrame> {
    let w = src_info.width as usize;
    let h = src_info.height as usize;
    let in_plane = &src.planes[0];
    let mut out = vec![0u8; w * h * 3];
    for row in 0..h {
        let sr = tight_row(&in_plane.data, in_plane.stride, row, w * 3);
        rgb::swizzle3(
            sr,
            src_pos,
            &mut out[row * w * 3..row * w * 3 + w * 3],
            dst_pos,
            w,
        );
    }
    Ok(make_frame(
        src,
        vec![VideoPlane {
            stride: w * 3,
            data: out,
        }],
    ))
}

fn swizzle4(
    src: &VideoFrame,
    src_info: FrameInfo,
    src_pos: rgb::Rgba4,
    dst_pos: rgb::Rgba4,
) -> Result<VideoFrame> {
    let w = src_info.width as usize;
    let h = src_info.height as usize;
    let in_plane = &src.planes[0];
    let mut out = vec![0u8; w * h * 4];
    for row in 0..h {
        let sr = tight_row(&in_plane.data, in_plane.stride, row, w * 4);
        rgb::swizzle4(
            sr,
            src_pos,
            &mut out[row * w * 4..row * w * 4 + w * 4],
            dst_pos,
            w,
        );
    }
    Ok(make_frame(
        src,
        vec![VideoPlane {
            stride: w * 4,
            data: out,
        }],
    ))
}

fn promote3_to_4(
    src: &VideoFrame,
    src_info: FrameInfo,
    src_pos: rgb::Rgb3,
    dst_pos: rgb::Rgba4,
) -> Result<VideoFrame> {
    let w = src_info.width as usize;
    let h = src_info.height as usize;
    let in_plane = &src.planes[0];
    let mut out = vec![0u8; w * h * 4];
    for row in 0..h {
        let sr = tight_row(&in_plane.data, in_plane.stride, row, w * 3);
        rgb::rgb3_to_rgba4(
            sr,
            src_pos,
            &mut out[row * w * 4..row * w * 4 + w * 4],
            dst_pos,
            w,
        );
    }
    Ok(make_frame(
        src,
        vec![VideoPlane {
            stride: w * 4,
            data: out,
        }],
    ))
}

fn demote4_to_3(
    src: &VideoFrame,
    src_info: FrameInfo,
    src_pos: rgb::Rgba4,
    dst_pos: rgb::Rgb3,
) -> Result<VideoFrame> {
    let w = src_info.width as usize;
    let h = src_info.height as usize;
    let in_plane = &src.planes[0];
    let mut out = vec![0u8; w * h * 3];
    for row in 0..h {
        let sr = tight_row(&in_plane.data, in_plane.stride, row, w * 4);
        rgb::rgba4_to_rgb3(
            sr,
            src_pos,
            &mut out[row * w * 3..row * w * 3 + w * 3],
            dst_pos,
            w,
        );
    }
    Ok(make_frame(
        src,
        vec![VideoPlane {
            stride: w * 3,
            data: out,
        }],
    ))
}

// -------------------------------------------------------------------------
// Deep RGB.

fn do_rgb48_to_rgb24(src: &VideoFrame, src_info: FrameInfo) -> Result<VideoFrame> {
    let w = src_info.width as usize;
    let h = src_info.height as usize;
    let in_plane = &src.planes[0];
    let mut out = vec![0u8; w * h * 3];
    for row in 0..h {
        let sr = tight_row(&in_plane.data, in_plane.stride, row, w * 6);
        rgb::rgb48_to_rgb24(sr, &mut out[row * w * 3..row * w * 3 + w * 3], w);
    }
    Ok(make_frame(
        src,
        vec![VideoPlane {
            stride: w * 3,
            data: out,
        }],
    ))
}

fn do_rgb24_to_rgb48(src: &VideoFrame, src_info: FrameInfo) -> Result<VideoFrame> {
    let w = src_info.width as usize;
    let h = src_info.height as usize;
    let in_plane = &src.planes[0];
    let mut out = vec![0u8; w * h * 6];
    for row in 0..h {
        let sr = tight_row(&in_plane.data, in_plane.stride, row, w * 3);
        rgb::rgb24_to_rgb48(sr, &mut out[row * w * 6..row * w * 6 + w * 6], w);
    }
    Ok(make_frame(
        src,
        vec![VideoPlane {
            stride: w * 6,
            data: out,
        }],
    ))
}

fn do_rgba64_to_rgba(src: &VideoFrame, src_info: FrameInfo) -> Result<VideoFrame> {
    let w = src_info.width as usize;
    let h = src_info.height as usize;
    let in_plane = &src.planes[0];
    let mut out = vec![0u8; w * h * 4];
    for row in 0..h {
        let sr = tight_row(&in_plane.data, in_plane.stride, row, w * 8);
        rgb::rgba64_to_rgba(sr, &mut out[row * w * 4..row * w * 4 + w * 4], w);
    }
    Ok(make_frame(
        src,
        vec![VideoPlane {
            stride: w * 4,
            data: out,
        }],
    ))
}

fn do_rgba_to_rgba64(src: &VideoFrame, src_info: FrameInfo) -> Result<VideoFrame> {
    let w = src_info.width as usize;
    let h = src_info.height as usize;
    let in_plane = &src.planes[0];
    let mut out = vec![0u8; w * h * 8];
    for row in 0..h {
        let sr = tight_row(&in_plane.data, in_plane.stride, row, w * 4);
        rgb::rgba_to_rgba64(sr, &mut out[row * w * 8..row * w * 8 + w * 8], w);
    }
    Ok(make_frame(
        src,
        vec![VideoPlane {
            stride: w * 8,
            data: out,
        }],
    ))
}

// -------------------------------------------------------------------------
// Gray / Mono.

fn gray_to_packed3(src: &VideoFrame, src_info: FrameInfo) -> Result<VideoFrame> {
    let w = src_info.width as usize;
    let h = src_info.height as usize;
    let in_plane = &src.planes[0];
    let mut out = vec![0u8; w * h * 3];
    for row in 0..h {
        let sr = tight_row(&in_plane.data, in_plane.stride, row, w);
        gray::gray8_to_rgb24(sr, &mut out[row * w * 3..row * w * 3 + w * 3], w);
    }
    Ok(make_frame(
        src,
        vec![VideoPlane {
            stride: w * 3,
            data: out,
        }],
    ))
}

fn gray_to_packed4(src: &VideoFrame, src_info: FrameInfo, alpha_first: bool) -> Result<VideoFrame> {
    let w = src_info.width as usize;
    let h = src_info.height as usize;
    let in_plane = &src.planes[0];
    let mut out = vec![0u8; w * h * 4];
    for row in 0..h {
        let sr = tight_row(&in_plane.data, in_plane.stride, row, w);
        let dr = &mut out[row * w * 4..row * w * 4 + w * 4];
        if alpha_first {
            for (i, &g) in sr.iter().enumerate().take(w) {
                dr[i * 4] = 255;
                dr[i * 4 + 1] = g;
                dr[i * 4 + 2] = g;
                dr[i * 4 + 3] = g;
            }
        } else {
            gray::gray8_to_rgba(sr, dr, w);
        }
    }
    Ok(make_frame(
        src,
        vec![VideoPlane {
            stride: w * 4,
            data: out,
        }],
    ))
}

fn do_gray16_to_gray8(src: &VideoFrame, src_info: FrameInfo) -> Result<VideoFrame> {
    let w = src_info.width as usize;
    let h = src_info.height as usize;
    let in_plane = &src.planes[0];
    let mut out = vec![0u8; w * h];
    for row in 0..h {
        let sr = tight_row(&in_plane.data, in_plane.stride, row, w * 2);
        gray::gray16le_to_gray8(sr, &mut out[row * w..row * w + w], w);
    }
    Ok(make_frame(
        src,
        vec![VideoPlane {
            stride: w,
            data: out,
        }],
    ))
}

fn do_gray8_to_gray16(src: &VideoFrame, src_info: FrameInfo) -> Result<VideoFrame> {
    let w = src_info.width as usize;
    let h = src_info.height as usize;
    let in_plane = &src.planes[0];
    let mut out = vec![0u8; w * h * 2];
    for row in 0..h {
        let sr = tight_row(&in_plane.data, in_plane.stride, row, w);
        gray::gray8_to_gray16le(sr, &mut out[row * w * 2..row * w * 2 + w * 2], w);
    }
    Ok(make_frame(
        src,
        vec![VideoPlane {
            stride: w * 2,
            data: out,
        }],
    ))
}

fn do_mono_to_gray(
    src: &VideoFrame,
    src_info: FrameInfo,
    black_is_zero: bool,
) -> Result<VideoFrame> {
    let w = src_info.width as usize;
    let h = src_info.height as usize;
    let in_plane = &src.planes[0];
    let mut out = vec![0u8; w * h];
    // Mono strides are often `(w + 7) / 8`, but honour the provided
    // stride if it differs.
    let src_stride = in_plane.stride;
    let compact = gather_mono_rows(&in_plane.data, src_stride, w.div_ceil(8), h);
    gray::mono_to_gray8(&compact, &mut out, w, h, black_is_zero);
    Ok(make_frame(
        src,
        vec![VideoPlane {
            stride: w,
            data: out,
        }],
    ))
}

fn do_gray_to_mono(
    src: &VideoFrame,
    src_info: FrameInfo,
    black_is_zero: bool,
) -> Result<VideoFrame> {
    let w = src_info.width as usize;
    let h = src_info.height as usize;
    let in_plane = &src.planes[0];
    let packed_stride = w.div_ceil(8);
    let src_tight = gather_tight(&in_plane.data, in_plane.stride, w, h)?;
    let mut out = vec![0u8; packed_stride * h];
    gray::gray8_to_mono(&src_tight, &mut out, w, h, black_is_zero);
    Ok(make_frame(
        src,
        vec![VideoPlane {
            stride: packed_stride,
            data: out,
        }],
    ))
}

fn gather_mono_rows(src: &[u8], stride: usize, packed: usize, h: usize) -> Vec<u8> {
    if stride == packed {
        return src[..packed * h].to_vec();
    }
    let mut out = Vec::with_capacity(packed * h);
    for row in 0..h {
        out.extend_from_slice(&src[row * stride..row * stride + packed]);
    }
    out
}

/// Packed RGB(A) → Gray8 luminance projection (full-range Y' row of the
/// selected primaries; alpha dropped).
fn do_rgb_to_gray(
    src: &VideoFrame,
    src_info: FrameInfo,
    matrix: YuvMatrix,
    alpha_in: bool,
) -> Result<VideoFrame> {
    let w = src_info.width as usize;
    let h = src_info.height as usize;
    let in_plane = &src.planes[0];
    let rgb24: Vec<u8> = if alpha_in {
        let mut out = Vec::with_capacity(w * h * 3);
        for row in 0..h {
            let sr = tight_row(&in_plane.data, in_plane.stride, row, w * 4);
            for i in 0..w {
                out.push(sr[i * 4]);
                out.push(sr[i * 4 + 1]);
                out.push(sr[i * 4 + 2]);
            }
        }
        out
    } else {
        gather_tight(&in_plane.data, in_plane.stride, w * 3, h)?
    };
    let mut gray = vec![0u8; w * h];
    yuv::rgb24_to_gray8(&rgb24, &mut gray, w * h, matrix);
    Ok(make_frame(
        src,
        vec![VideoPlane {
            stride: w,
            data: gray,
        }],
    ))
}

/// 16-bit planar YUV(A) → packed deep RGB at full precision (Q30 deep
/// matrix; see [`crate::yuv::yuv444p16_to_rgb48`]). Chroma is
/// upsampled to 4:4:4 at 16-bit precision first; the alpha plane (when
/// carried) lands verbatim in the packed alpha word.
fn do_deep_yuv_to_rgb48(
    src: &VideoFrame,
    src_info: FrameInfo,
    matrix: YuvMatrix,
    wsub: usize,
    hsub: usize,
    alpha: bool,
    workers: usize,
) -> Result<VideoFrame> {
    let s = PlanarYuv {
        wsub,
        hsub,
        bits: 16,
        alpha,
    };
    deep_family_to_packed16(src, src_info, matrix, s, alpha, workers)
}

/// Any planar family member (8 / 10 / 12 / 16 bits, any siting, alpha
/// or not) → packed `Rgb48Le` / `Rgba64Le` through the full-precision
/// deep matrix, in one banded pass (see [`planar8::decode_deep`]).
fn deep_family_to_packed16(
    src: &VideoFrame,
    src_info: FrameInfo,
    matrix: YuvMatrix,
    s: PlanarYuv,
    alpha_out: bool,
    workers: usize,
) -> Result<VideoFrame> {
    let need = if s.alpha { 4 } else { 3 };
    if src.planes.len() < need {
        return Err(Error::invalid(
            "pixfmt: deep YUV source needs Y, U, V(, A) planes",
        ));
    }
    let w = src_info.width as usize;
    let h = src_info.height as usize;
    let (cw, ch) = chroma_dims(w, h, s.wsub, s.hsub);
    let sb = s.sample_bytes();
    let yp = tight_plane(&src.planes[0], w * sb, h)?;
    let up = tight_plane(&src.planes[1], cw * sb, ch)?;
    let vp = tight_plane(&src.planes[2], cw * sb, ch)?;
    let ap = if s.alpha && alpha_out {
        Some(tight_plane(&src.planes[3], w * sb, h)?)
    } else {
        None
    };
    let out = planar8::decode_deep(
        &planar8::PlanarDeep {
            y: &yp,
            u: &up,
            v: &vp,
            a: ap.as_deref(),
            w,
            h,
            wsub: s.wsub,
            hsub: s.hsub,
            bits: s.bits,
        },
        alpha_out,
        matrix,
        workers,
    );
    let bpp = if alpha_out { 8 } else { 6 };
    Ok(make_frame(
        src,
        vec![VideoPlane {
            stride: w * bpp,
            data: out,
        }],
    ))
}

/// Packed deep RGB → 16-bit planar YUV(A) at full precision: encode at
/// 4:4:4 through the Q30 deep matrix, then downsample chroma at 16-bit
/// precision; the packed alpha word (when present on both sides)
/// becomes the full-resolution alpha plane verbatim. The 16-bit case
/// of [`packed16_to_family`].
fn do_rgb48_to_deep_yuv(
    src: &VideoFrame,
    src_info: FrameInfo,
    matrix: YuvMatrix,
    wsub: usize,
    hsub: usize,
    alpha: bool,
    workers: usize,
) -> Result<VideoFrame> {
    let d = PlanarYuv {
        wsub,
        hsub,
        bits: 16,
        alpha,
    };
    packed16_to_family(src, src_info, matrix, d, alpha, workers)
}

/// Computed `Packed16ToFamily` op: packed `Rgb48Le` / `Rgba64Le` → any
/// planar family member. The picture is encoded at 16 bits through the
/// Q30 deep matrix and the chroma subsampled at 16 bits (one banded
/// pass, see [`planar8::encode_deep`]); every plane is then narrowed to
/// the member's depth by the ladder rule (truncation; nothing to do at
/// 16). Alpha is carried verbatim (narrowed with the rest), dropped, or
/// synthesised opaque full-scale per the two shapes.
fn packed16_to_family(
    src: &VideoFrame,
    src_info: FrameInfo,
    matrix: YuvMatrix,
    d: PlanarYuv,
    alpha_in: bool,
    workers: usize,
) -> Result<VideoFrame> {
    if src.planes.is_empty() {
        return Err(Error::invalid("pixfmt: packed RGB source needs a plane"));
    }
    let w = src_info.width as usize;
    let h = src_info.height as usize;
    let comps = if alpha_in { 4 } else { 3 };
    let packed = tight_plane(&src.planes[0], w * comps * 2, h)?;
    let out = planar8::encode_deep(
        &planar8::PackedDeep {
            data: &packed,
            comps,
            w,
            h,
        },
        d.wsub,
        d.hsub,
        d.alpha,
        matrix,
        workers,
    );
    let (cw, ch) = (out.cw, out.ch);
    let sb = d.sample_bytes();
    let narrow = |plane: Vec<u8>, count: usize| -> Vec<u8> {
        if d.bits >= 16 {
            plane
        } else {
            plane_to_depth(&plane, count, 16, d.bits)
        }
    };
    let mut planes = vec![
        VideoPlane {
            stride: w * sb,
            data: narrow(out.y, w * h),
        },
        VideoPlane {
            stride: cw * sb,
            data: narrow(out.u, cw * ch),
        },
        VideoPlane {
            stride: cw * sb,
            data: narrow(out.v, cw * ch),
        },
    ];
    if let Some(a) = out.a {
        planes.push(VideoPlane {
            stride: w * sb,
            data: narrow(a, w * h),
        });
    }
    Ok(make_frame(src, planes))
}

/// Any 8-bit packed RGB order → `Gray8`: gather each pixel's R, G, B
/// bytes from their `(comps, r, g, b)` positions into a canonical
/// Rgb24 scratch row and run the shared full-range projection kernel —
/// byte-identical to swizzling to Rgb24 first.
fn do_packed_pos_to_gray(
    src: &VideoFrame,
    src_info: FrameInfo,
    matrix: YuvMatrix,
    comps: usize,
    r: usize,
    g: usize,
    b: usize,
) -> Result<VideoFrame> {
    let w = src_info.width as usize;
    let h = src_info.height as usize;
    let in_plane = &src.planes[0];
    let mut rgb24 = Vec::with_capacity(w * h * 3);
    for row in 0..h {
        let sr = tight_row(&in_plane.data, in_plane.stride, row, w * comps);
        for i in 0..w {
            rgb24.push(sr[i * comps + r]);
            rgb24.push(sr[i * comps + g]);
            rgb24.push(sr[i * comps + b]);
        }
    }
    let mut gray = vec![0u8; w * h];
    yuv::rgb24_to_gray8(&rgb24, &mut gray, w * h, matrix);
    Ok(make_frame(
        src,
        vec![VideoPlane {
            stride: w,
            data: gray,
        }],
    ))
}

/// `Rgb48Le` / `Rgba64Le` → `Gray8`: keep the top byte of each colour
/// word (truncation, the crate depth policy) and project. The alpha
/// word (when present) is dropped.
fn do_deep_packed_to_gray(
    src: &VideoFrame,
    src_info: FrameInfo,
    matrix: YuvMatrix,
    alpha_in: bool,
) -> Result<VideoFrame> {
    let w = src_info.width as usize;
    let h = src_info.height as usize;
    let comps = if alpha_in { 4 } else { 3 };
    let in_plane = &src.planes[0];
    let mut rgb24 = Vec::with_capacity(w * h * 3);
    for row in 0..h {
        let sr = tight_row(&in_plane.data, in_plane.stride, row, w * comps * 2);
        for i in 0..w {
            // LE words: the high byte sits at offset 1 of each pair.
            rgb24.push(sr[i * comps * 2 + 1]);
            rgb24.push(sr[i * comps * 2 + 3]);
            rgb24.push(sr[i * comps * 2 + 5]);
        }
    }
    let mut gray = vec![0u8; w * h];
    yuv::rgb24_to_gray8(&rgb24, &mut gray, w * h, matrix);
    Ok(make_frame(
        src,
        vec![VideoPlane {
            stride: w,
            data: gray,
        }],
    ))
}

/// Packed 4:2:2 → `Gray8`: extract the luma bytes (even offsets for
/// YUYV, odd for UYVY) and rescale limited → full range. Chroma is
/// never read; like the planar luma extraction this accepts any even
/// width the packed layout itself can represent.
fn do_packed422_to_gray(
    src: &VideoFrame,
    src_info: FrameInfo,
    is_yuyv: bool,
) -> Result<VideoFrame> {
    let w = src_info.width as usize;
    let h = src_info.height as usize;
    if w % 2 != 0 {
        return Err(Error::invalid("pixfmt: packed 4:2:2 requires even width"));
    }
    let in_plane = &src.planes[0];
    let packed = gather_tight(&in_plane.data, in_plane.stride, w * 2, h)?;
    let luma_off = if is_yuyv { 0 } else { 1 };
    let mut yp: Vec<u8> = (0..w * h).map(|i| packed[i * 2 + luma_off]).collect();
    yuv::limited_to_full_luma(&mut yp);
    Ok(make_frame(
        src,
        vec![VideoPlane {
            stride: w,
            data: yp,
        }],
    ))
}

/// `Gray8` → packed 4:2:2: rescale the grey plane full → limited range
/// for the luma slots and interleave with the neutral chroma code 128
/// in the requested byte order.
fn do_gray_to_packed422(
    src: &VideoFrame,
    src_info: FrameInfo,
    is_yuyv: bool,
) -> Result<VideoFrame> {
    let w = src_info.width as usize;
    let h = src_info.height as usize;
    if w % 2 != 0 {
        return Err(Error::invalid("pixfmt: packed 4:2:2 requires even width"));
    }
    let in_plane = &src.planes[0];
    let mut yp = gather_tight(&in_plane.data, in_plane.stride, w, h)?;
    yuv::full_to_limited_luma(&mut yp);
    let mut out = vec![128u8; w * h * 2];
    let luma_off = if is_yuyv { 0 } else { 1 };
    for (i, &y) in yp.iter().enumerate() {
        out[i * 2 + luma_off] = y;
    }
    Ok(make_frame(
        src,
        vec![VideoPlane {
            stride: w * 2,
            data: out,
        }],
    ))
}

/// `Gray10Le` / `Gray12Le` / `Gray16Le` → packed `Rgb48Le` /
/// `Rgba64Le`: widen to 16 bits (exact ladder rule, a copy at 16) and
/// broadcast, one row band at a time.
fn do_deep_gray_to_packed_deep(
    src: &VideoFrame,
    src_info: FrameInfo,
    bits: u32,
    alpha_out: bool,
    workers: usize,
) -> Result<VideoFrame> {
    if src.planes.is_empty() {
        return Err(Error::invalid("pixfmt: grey source needs a plane"));
    }
    let w = src_info.width as usize;
    let h = src_info.height as usize;
    let tight = tight_plane(&src.planes[0], w * 2, h)?;
    let bpp = if alpha_out { 8 } else { 6 };
    let kernel = if alpha_out {
        gray::gray16le_to_rgba64le
    } else {
        gray::gray16le_to_rgb48le
    };
    let out = planar8::map_packed_banded(&tight, w * 2, w * bpp, h, workers, |s, d| {
        let n = d.len() / bpp;
        if bits >= 16 {
            kernel(s, d, n);
        } else {
            let mut wide = vec![0u8; n * 2];
            yuv::depth_rescale_le16_plane(s, &mut wide, n, bits, 16);
            kernel(&wide, d, n);
        }
    });
    Ok(make_frame(
        src,
        vec![VideoPlane {
            stride: w * bpp,
            data: out,
        }],
    ))
}

/// Packed `Rgb48Le` / `Rgba64Le` → `Gray10Le` / `Gray12Le` /
/// `Gray16Le`: the 16-bit Y' projection, then the ladder narrow when
/// the target is shallower, one row band at a time.
fn do_packed_deep_to_deep_gray(
    src: &VideoFrame,
    src_info: FrameInfo,
    matrix: YuvMatrix,
    bits: u32,
    alpha_in: bool,
    workers: usize,
) -> Result<VideoFrame> {
    if src.planes.is_empty() {
        return Err(Error::invalid("pixfmt: packed RGB source needs a plane"));
    }
    let w = src_info.width as usize;
    let h = src_info.height as usize;
    let bpp = if alpha_in { 8 } else { 6 };
    let tight = tight_plane(&src.planes[0], w * bpp, h)?;
    let kernel = if alpha_in {
        yuv::rgba64le_to_gray16le
    } else {
        yuv::rgb48le_to_gray16le
    };
    let out = planar8::map_packed_banded(&tight, w * bpp, w * 2, h, workers, |s, d| {
        let n = d.len() / 2;
        if bits >= 16 {
            kernel(s, d, n, matrix);
        } else {
            let mut luma = vec![0u8; n * 2];
            kernel(s, &mut luma, n, matrix);
            yuv::depth_rescale_le16_plane(&luma, d, n, 16, bits);
        }
    });
    Ok(make_frame(
        src,
        vec![VideoPlane {
            stride: w * 2,
            data: out,
        }],
    ))
}

/// `Ya16Le` → `Gray10Le` / `Gray12Le`: luma word, narrowed.
fn do_ya16_to_deep_gray(src: &VideoFrame, src_info: FrameInfo, bits: u32) -> Result<VideoFrame> {
    let g16 = packed_map(src, src_info, 4, 2, gray::ya16le_to_gray16le)?;
    let g16_info = FrameInfo::new(PixelFormat::Gray16Le, src_info.width, src_info.height);
    do_gray_depth_rescale(&g16, g16_info, 16, bits)
}

/// `Gray10Le` / `Gray12Le` → `Ya16Le`: widened grey word + opaque alpha.
fn do_deep_gray_to_ya16(src: &VideoFrame, src_info: FrameInfo, bits: u32) -> Result<VideoFrame> {
    let g16 = do_gray_depth_rescale(src, src_info, bits, 16)?;
    let g16_info = FrameInfo::new(PixelFormat::Gray16Le, src_info.width, src_info.height);
    packed_map(&g16, g16_info, 2, 4, gray::gray16le_to_ya16le)
}

/// Significant bits of a deep grey word format.
fn deep_gray_bits(f: PixelFormat) -> u32 {
    match f {
        PixelFormat::Gray10Le => 10,
        PixelFormat::Gray12Le => 12,
        _ => 16,
    }
}

/// One luma code through the grey ↔ YUV move: masked to `src_bits`
/// (samples above the nominal depth are legal input — padding bits,
/// hostile frames — and are masked, never trusted as an index), widened
/// to the deeper of the two depths by the ladder rule, range-moved
/// there through the static [`range_table`] when `limited`, then
/// narrowed to `dst_bits` by truncation. Exactly the composition of
/// `plane_to_depth` / `range_*_to_*` the planes went through before.
#[inline]
fn luma_move_code(v: u32, src_bits: u32, dst_bits: u32, limited: bool, to_yuv: bool) -> u32 {
    let work = src_bits.max(dst_bits);
    let v = v & ((1u32 << src_bits) - 1);
    let wide = if work == src_bits {
        v
    } else {
        widen_bits(v, src_bits, work)
    };
    let moved = if limited {
        range_table(work, !to_yuv)[wide as usize] as u32
    } else {
        wide
    };
    moved >> (work - dst_bits)
}

/// Move one luma plane between `src_bits` and `dst_bits` (bytes at 8,
/// LE16 words above; at least one side is deep) with the range move
/// (`limited`: full → limited when `to_yuv`, limited → full otherwise)
/// applied at the deeper of the two depths, band by band. Widening
/// before the move keeps every source code distinct through the
/// rescale; narrowing after it is the ladder truncation.
///
/// Every sample goes through [`luma_move_code`]; a picture with at
/// least as many samples as source codes composes it once into a
/// `2^src_bits`-entry table (one masked lookup per sample), a smaller
/// picture evaluates it per sample — same bytes either way.
#[allow(clippy::too_many_arguments)]
fn luma_depth_range_banded(
    src: &[u8],
    w: usize,
    h: usize,
    src_bits: u32,
    dst_bits: u32,
    limited: bool,
    to_yuv: bool,
    workers: usize,
) -> Vec<u8> {
    debug_assert!(src_bits.max(dst_bits) > 8);
    let ssb = if src_bits > 8 { 2 } else { 1 };
    let dsb = if dst_bits > 8 { 2 } else { 1 };
    let codes = 1usize << src_bits;
    let mask = (codes - 1) as u32;
    let table: Vec<u16> = if w * h >= codes {
        (0..codes as u32)
            .map(|v| luma_move_code(v, src_bits, dst_bits, limited, to_yuv) as u16)
            .collect()
    } else {
        Vec::new()
    };
    let map = |v: u32| -> u16 {
        if table.is_empty() {
            luma_move_code(v, src_bits, dst_bits, limited, to_yuv) as u16
        } else {
            table[(v & mask) as usize]
        }
    };
    planar8::map_packed_banded(src, w * ssb, w * dsb, h, workers, |s, d| {
        let n = d.len() / dsb;
        match (ssb, dsb) {
            (1, 2) => {
                for (o, &v) in d.chunks_exact_mut(2).zip(s[..n].iter()) {
                    o.copy_from_slice(&map(v as u32).to_le_bytes());
                }
            }
            (2, 1) => {
                for (o, i) in d.iter_mut().zip(s[..n * 2].chunks_exact(2)) {
                    *o = map(u16::from_le_bytes([i[0], i[1]]) as u32) as u8;
                }
            }
            _ => {
                for (o, i) in d.chunks_exact_mut(2).zip(s[..n * 2].chunks_exact(2)) {
                    let v = u16::from_le_bytes([i[0], i[1]]) as u32;
                    o.copy_from_slice(&map(v).to_le_bytes());
                }
            }
        }
    })
}

/// Computed `GbrToDeepGray` op (see the variant docs).
fn gbr_to_deep_gray(
    src: &VideoFrame,
    src_info: FrameInfo,
    matrix: YuvMatrix,
    il: IntLayout,
    bits: u32,
    workers: usize,
) -> Result<VideoFrame> {
    if src.planes.len() < 3 {
        return Err(Error::invalid(
            "pixfmt: GBR(A) source needs G, B, R(, A) planes",
        ));
    }
    let w = src_info.width as usize;
    let h = src_info.height as usize;
    let sb = il.sample_bytes();
    let g = tight_plane(&src.planes[0], w * sb, h)?;
    let b = tight_plane(&src.planes[1], w * sb, h)?;
    let r = tight_plane(&src.planes[2], w * sb, h)?;
    let p = matrix.encode_params16();
    let src_bits = il.bits;
    // Band over the luma output; the three colour planes are read at
    // the same rows.
    let out = planar8::map_packed_banded(&r, w * sb, w * 2, h, workers, |rb, d| {
        let n = d.len() / 2;
        // Offset of this band inside the planes (the band's R slice
        // starts at the same byte offset in G and B).
        let off = rb.as_ptr() as usize - r.as_ptr() as usize;
        let gb = &g[off..off + n * sb];
        let bb = &b[off..off + n * sb];
        let mut r16 = vec![0u16; n];
        let mut g16 = vec![0u16; n];
        let mut b16 = vec![0u16; n];
        planar8::widen_row16(rb, &mut r16, src_bits);
        planar8::widen_row16(gb, &mut g16, src_bits);
        planar8::widen_row16(bb, &mut b16, src_bits);
        let shift = 16 - bits;
        for (i, o) in d.chunks_exact_mut(2).enumerate() {
            let y = yuv::rgb16_to_luma16_fp(r16[i], g16[i], b16[i], &p) >> shift;
            o.copy_from_slice(&y.to_le_bytes());
        }
    });
    Ok(make_frame(
        src,
        vec![VideoPlane {
            stride: w * 2,
            data: out,
        }],
    ))
}

/// Computed `DeepGrayToGbr` op (see the variant docs).
fn deep_gray_to_gbr(
    src: &VideoFrame,
    src_info: FrameInfo,
    bits: u32,
    il: IntLayout,
    workers: usize,
) -> Result<VideoFrame> {
    if src.planes.is_empty() {
        return Err(Error::invalid("pixfmt: grey source needs a plane"));
    }
    let w = src_info.width as usize;
    let h = src_info.height as usize;
    let tight = tight_plane(&src.planes[0], w * 2, h)?;
    let sb = il.sample_bytes();
    // The equal-width case is still a masked copy (`depth_rescale` with
    // equal widths), so over-range source words never reach the planes.
    let plane = if il.bits == bits && bits == 16 {
        tight.into_owned()
    } else {
        planar8::map_packed_banded(&tight, w * 2, w * sb, h, workers, |s, d| {
            let n = d.len() / sb;
            if il.bits > 8 {
                yuv::depth_rescale_le16_plane(s, d, n, bits, il.bits);
            } else {
                yuv::depth_down_le16_plane(s, d, n, bits);
            }
        })
    };
    let mut planes = vec![
        VideoPlane {
            stride: w * sb,
            data: plane.clone(),
        },
        VideoPlane {
            stride: w * sb,
            data: plane.clone(),
        },
        VideoPlane {
            stride: w * sb,
            data: plane,
        },
    ];
    if il.alpha {
        planes.push(VideoPlane {
            stride: w * sb,
            data: opaque_plane(w * h, il.bits),
        });
    }
    Ok(make_frame(src, planes))
}

/// Computed `DeepGrayToPlanarFamily` op (see the variant docs).
fn deep_gray_to_planar_family(
    src: &VideoFrame,
    src_info: FrameInfo,
    bits: u32,
    d: PlanarYuv,
    limited: bool,
    workers: usize,
) -> Result<VideoFrame> {
    if src.planes.is_empty() {
        return Err(Error::invalid("pixfmt: grey source needs a plane"));
    }
    let w = src_info.width as usize;
    let h = src_info.height as usize;
    let (cw, ch) = chroma_dims(w, h, d.wsub, d.hsub);
    let sb = d.sample_bytes();
    let tight = tight_plane(&src.planes[0], w * 2, h)?;
    let luma = luma_depth_range_banded(&tight, w, h, bits, d.bits, limited, true, workers);
    let mut planes = vec![
        VideoPlane {
            stride: w * sb,
            data: luma,
        },
        VideoPlane {
            stride: cw * sb,
            data: neutral_chroma_plane(cw * ch, d.bits),
        },
        VideoPlane {
            stride: cw * sb,
            data: neutral_chroma_plane(cw * ch, d.bits),
        },
    ];
    if d.alpha {
        planes.push(VideoPlane {
            stride: w * sb,
            data: opaque_plane(w * h, d.bits),
        });
    }
    Ok(make_frame(src, planes))
}

/// Computed `PlanarFamilyToDeepGray` op (see the variant docs).
fn planar_family_to_deep_gray(
    src: &VideoFrame,
    src_info: FrameInfo,
    s: PlanarYuv,
    bits: u32,
    limited: bool,
    workers: usize,
) -> Result<VideoFrame> {
    if src.planes.is_empty() {
        return Err(Error::invalid("pixfmt: YUV source needs a luma plane"));
    }
    let w = src_info.width as usize;
    let h = src_info.height as usize;
    let tight = tight_plane(&src.planes[0], w * s.sample_bytes(), h)?;
    let out = luma_depth_range_banded(&tight, w, h, s.bits, bits, limited, false, workers);
    Ok(make_frame(
        src,
        vec![VideoPlane {
            stride: w * 2,
            data: out,
        }],
    ))
}

// -------------------------------------------------------------------------
// Ya8 (grey + alpha, 2 bytes/pixel).

fn do_ya8_to_gray8(src: &VideoFrame, src_info: FrameInfo) -> Result<VideoFrame> {
    let w = src_info.width as usize;
    let h = src_info.height as usize;
    let in_plane = &src.planes[0];
    let mut out = vec![0u8; w * h];
    for row in 0..h {
        let sr = tight_row(&in_plane.data, in_plane.stride, row, w * 2);
        gray::ya8_to_gray8(sr, &mut out[row * w..row * w + w], w);
    }
    Ok(make_frame(
        src,
        vec![VideoPlane {
            stride: w,
            data: out,
        }],
    ))
}

fn do_gray8_to_ya8(src: &VideoFrame, src_info: FrameInfo) -> Result<VideoFrame> {
    let w = src_info.width as usize;
    let h = src_info.height as usize;
    let in_plane = &src.planes[0];
    let mut out = vec![0u8; w * h * 2];
    for row in 0..h {
        let sr = tight_row(&in_plane.data, in_plane.stride, row, w);
        gray::gray8_to_ya8(sr, &mut out[row * w * 2..row * w * 2 + w * 2], w);
    }
    Ok(make_frame(
        src,
        vec![VideoPlane {
            stride: w * 2,
            data: out,
        }],
    ))
}

fn do_ya8_to_rgb24(src: &VideoFrame, src_info: FrameInfo) -> Result<VideoFrame> {
    let w = src_info.width as usize;
    let h = src_info.height as usize;
    let in_plane = &src.planes[0];
    let mut out = vec![0u8; w * h * 3];
    for row in 0..h {
        let sr = tight_row(&in_plane.data, in_plane.stride, row, w * 2);
        gray::ya8_to_rgb24(sr, &mut out[row * w * 3..row * w * 3 + w * 3], w);
    }
    Ok(make_frame(
        src,
        vec![VideoPlane {
            stride: w * 3,
            data: out,
        }],
    ))
}

fn do_ya8_to_rgba(src: &VideoFrame, src_info: FrameInfo) -> Result<VideoFrame> {
    let w = src_info.width as usize;
    let h = src_info.height as usize;
    let in_plane = &src.planes[0];
    let mut out = vec![0u8; w * h * 4];
    for row in 0..h {
        let sr = tight_row(&in_plane.data, in_plane.stride, row, w * 2);
        gray::ya8_to_rgba(sr, &mut out[row * w * 4..row * w * 4 + w * 4], w);
    }
    Ok(make_frame(
        src,
        vec![VideoPlane {
            stride: w * 4,
            data: out,
        }],
    ))
}

fn do_rgb24_to_ya8(src: &VideoFrame, src_info: FrameInfo) -> Result<VideoFrame> {
    let w = src_info.width as usize;
    let h = src_info.height as usize;
    let in_plane = &src.planes[0];
    let mut out = vec![0u8; w * h * 2];
    for row in 0..h {
        let sr = tight_row(&in_plane.data, in_plane.stride, row, w * 3);
        gray::rgb24_to_ya8(sr, &mut out[row * w * 2..row * w * 2 + w * 2], w);
    }
    Ok(make_frame(
        src,
        vec![VideoPlane {
            stride: w * 2,
            data: out,
        }],
    ))
}

fn do_rgba_to_ya8(src: &VideoFrame, src_info: FrameInfo) -> Result<VideoFrame> {
    let w = src_info.width as usize;
    let h = src_info.height as usize;
    let in_plane = &src.planes[0];
    let mut out = vec![0u8; w * h * 2];
    for row in 0..h {
        let sr = tight_row(&in_plane.data, in_plane.stride, row, w * 4);
        gray::rgba_to_ya8(sr, &mut out[row * w * 2..row * w * 2 + w * 2], w);
    }
    Ok(make_frame(
        src,
        vec![VideoPlane {
            stride: w * 2,
            data: out,
        }],
    ))
}

// -------------------------------------------------------------------------
// YUV ↔ Gray8 (luma extraction / neutral-chroma synthesis).

/// Any YUV-family source → `Gray8`: gather the full-resolution luma
/// plane, rescale limited → full range unless the source is a `YuvJ*`
/// family, and drop everything else. Chroma is never read, so this path
/// accepts odd dimensions even on subsampled layouts.
fn do_yuv_luma_to_gray(
    src: &VideoFrame,
    src_info: FrameInfo,
    full_range: bool,
) -> Result<VideoFrame> {
    if src.planes.is_empty() {
        return Err(Error::invalid("pixfmt: YUV source needs a luma plane"));
    }
    let w = src_info.width as usize;
    let h = src_info.height as usize;
    let mut yp = gather_tight(&src.planes[0].data, src.planes[0].stride, w, h)?;
    if !full_range {
        yuv::limited_to_full_luma(&mut yp);
    }
    Ok(make_frame(
        src,
        vec![VideoPlane {
            stride: w,
            data: yp,
        }],
    ))
}

/// `Gray8` → planar YUV: gray becomes luma (compressed to the limited
/// 16..=235 range unless the destination is full-range `YuvJ*`), chroma
/// planes are synthesised at the neutral code 128. Dimensions must
/// divide by the destination's chroma grid so the U/V planes are
/// representable.
fn do_gray_to_yuv_planar(
    src: &VideoFrame,
    src_info: FrameInfo,
    wsub: usize,
    hsub: usize,
    full_range: bool,
) -> Result<VideoFrame> {
    let w = src_info.width as usize;
    let h = src_info.height as usize;
    let (cw, ch) = chroma_grid(w, h, wsub, hsub)?;
    let mut yp = gather_tight(&src.planes[0].data, src.planes[0].stride, w, h)?;
    if !full_range {
        yuv::full_to_limited_luma(&mut yp);
    }
    Ok(make_frame(
        src,
        vec![
            VideoPlane {
                stride: w,
                data: yp,
            },
            VideoPlane {
                stride: cw,
                data: vec![128u8; cw * ch],
            },
            VideoPlane {
                stride: cw,
                data: vec![128u8; cw * ch],
            },
        ],
    ))
}

/// `Gray8` → NV12 / NV21: limited-range luma + one interleaved chroma
/// plane holding the neutral code 128 in every byte — U and V are equal,
/// so NV12 and NV21 receive identical bytes.
fn do_gray_to_nv(src: &VideoFrame, src_info: FrameInfo, full_range: bool) -> Result<VideoFrame> {
    let w = src_info.width as usize;
    let h = src_info.height as usize;
    let (cw, ch) = chroma_dims(w, h, 2, 2);
    let mut yp = gather_tight(&src.planes[0].data, src.planes[0].stride, w, h)?;
    if !full_range {
        yuv::full_to_limited_luma(&mut yp);
    }
    Ok(make_frame(
        src,
        vec![
            VideoPlane {
                stride: w,
                data: yp,
            },
            VideoPlane {
                stride: cw * 2,
                data: vec![128u8; cw * ch * 2],
            },
        ],
    ))
}

// -------------------------------------------------------------------------
// YUV ↔ RGB.

fn do_yuv_to_rgb(
    src: &VideoFrame,
    src_info: FrameInfo,
    matrix: YuvMatrix,
    wsub: usize,
    hsub: usize,
    alpha: bool,
    workers: usize,
) -> Result<VideoFrame> {
    let w = src_info.width as usize;
    let h = src_info.height as usize;
    let (yp, up, vp, _) = planar8_source(src, w, h, wsub, hsub, false)?;
    let bpp = if alpha { 4 } else { 3 };
    let out = planar8::decode(
        &Planar8 {
            y: &yp,
            u: &up,
            v: &vp,
            a: None,
            w,
            h,
            wsub,
            hsub,
        },
        bpp,
        matrix,
        workers,
    );
    Ok(make_frame(
        src,
        vec![VideoPlane {
            stride: w * bpp,
            data: out,
        }],
    ))
}

fn do_rgb_to_yuv(
    src: &VideoFrame,
    src_info: FrameInfo,
    matrix: YuvMatrix,
    wsub: usize,
    hsub: usize,
    alpha_in: bool,
    workers: usize,
) -> Result<VideoFrame> {
    let w = src_info.width as usize;
    let h = src_info.height as usize;
    let (cw, _ch) = chroma_grid(w, h, wsub, hsub)?;
    let packed = packed8_source(src, w, h, if alpha_in { 4 } else { 3 })?;
    // 4:1:1: encode at 4:4:4 (luma byte-for-byte from R/G/B, full-
    // resolution chroma from the same per-pixel matrix), then box-
    // average chroma horizontally to one sample per four luma columns —
    // what a 4:1:1 JPEG encoder produces from `cjpeg -sample 4x1`.
    let (out_wsub, out_hsub) = if wsub == 4 { (1, 1) } else { (wsub, hsub) };
    let enc = planar8::encode(&packed, out_wsub, out_hsub, matrix, false, workers);
    let (up, vp) = if wsub == 4 {
        let mut u = vec![0u8; cw * h];
        let mut v = vec![0u8; cw * h];
        yuv::chroma_444_to_411(&enc.u, &mut u, w, h);
        yuv::chroma_444_to_411(&enc.v, &mut v, w, h);
        (u, v)
    } else {
        (enc.u, enc.v)
    };
    Ok(make_frame(
        src,
        vec![
            VideoPlane {
                stride: w,
                data: enc.y,
            },
            VideoPlane {
                stride: cw,
                data: up,
            },
            VideoPlane {
                stride: cw,
                data: vp,
            },
        ],
    ))
}

/// Chroma plane dimensions for `w × h` under `(wsub, hsub)`, rejecting
/// the one geometry the kernels cannot express: 4:1:1 needs a width
/// that is a multiple of 4 (no representation for a 1-, 2- or 3-luma
/// trailing column). Every other siting rounds up per the odd-dimension
/// rule on [`convert_with`].
fn chroma_grid(w: usize, h: usize, wsub: usize, hsub: usize) -> Result<(usize, usize)> {
    if wsub == 4 && w % 4 != 0 {
        return Err(Error::invalid(
            "pixfmt: 4:1:1 YUV requires width divisible by 4",
        ));
    }
    Ok(chroma_dims(w, h, wsub, hsub))
}

/// Borrow (or gather) the tight Y / U / V (/ A) byte planes of an 8-bit
/// planar YUV(A) source at `w × h`.
#[allow(clippy::type_complexity)]
fn planar8_source<'a>(
    src: &'a VideoFrame,
    w: usize,
    h: usize,
    wsub: usize,
    hsub: usize,
    alpha: bool,
) -> Result<(
    std::borrow::Cow<'a, [u8]>,
    std::borrow::Cow<'a, [u8]>,
    std::borrow::Cow<'a, [u8]>,
    Option<std::borrow::Cow<'a, [u8]>>,
)> {
    let need = if alpha { 4 } else { 3 };
    if src.planes.len() < need {
        return Err(Error::invalid(format!(
            "pixfmt: planar YUV source needs {need} planes"
        )));
    }
    let (cw, ch) = chroma_grid(w, h, wsub, hsub)?;
    let yp = tight_plane(&src.planes[0], w, h)?;
    let up = tight_plane(&src.planes[1], cw, ch)?;
    let vp = tight_plane(&src.planes[2], cw, ch)?;
    let ap = if alpha {
        Some(tight_plane(&src.planes[3], w, h)?)
    } else {
        None
    };
    Ok((yp, up, vp, ap))
}

/// Describe a packed 8-bit RGB(A) source plane for the row-band
/// encoder, validating its length.
fn packed8_source(src: &VideoFrame, w: usize, h: usize, bpp: usize) -> Result<Packed8<'_>> {
    let Some(plane) = src.planes.first() else {
        return Err(Error::invalid("pixfmt: packed RGB source needs a plane"));
    };
    // Validate through the tight-plane rules (stride / length), but hand
    // the engine the stride-aware view so no gather copy is made.
    let _ = tight_plane(plane, w * bpp, h)?;
    Ok(Packed8 {
        data: &plane.data,
        stride: plane.stride,
        bpp,
        w,
        h,
    })
}

fn rescale_range(
    src: &VideoFrame,
    src_info: FrameInfo,
    wsub: usize,
    hsub: usize,
    to_full: bool,
    rescale: bool,
) -> Result<VideoFrame> {
    if src.planes.len() < 3 {
        return Err(Error::invalid("pixfmt: YuvJ source needs 3 planes"));
    }
    let w = src_info.width as usize;
    let h = src_info.height as usize;
    let (cw, ch) = chroma_grid(w, h, wsub, hsub)?;
    let mut yp = gather_tight(&src.planes[0].data, src.planes[0].stride, w, h)?;
    let mut up = gather_tight(&src.planes[1].data, src.planes[1].stride, cw, ch)?;
    let mut vp = gather_tight(&src.planes[2].data, src.planes[2].stride, cw, ch)?;
    if !rescale {
        // Samples already in the destination's range: carriage copy.
    } else if to_full {
        yuv::limited_to_full_luma(&mut yp);
        yuv::limited_to_full_chroma(&mut up);
        yuv::limited_to_full_chroma(&mut vp);
    } else {
        yuv::full_to_limited_luma(&mut yp);
        yuv::full_to_limited_chroma(&mut up);
        yuv::full_to_limited_chroma(&mut vp);
    }
    Ok(make_frame(
        src,
        vec![
            VideoPlane {
                stride: w,
                data: yp,
            },
            VideoPlane {
                stride: cw,
                data: up,
            },
            VideoPlane {
                stride: cw,
                data: vp,
            },
        ],
    ))
}

/// Planar YUV → planar YUV with the luma plane copied byte-for-byte and
/// the chroma planes resampled between two subsampling layouts. Caller
/// supplies the source and destination chroma division factors; the
/// helper routes them through the appropriate `yuv::chroma_*` primitive
/// (`444 ↔ 422`, `444 ↔ 420`, `422 ↔ 420`).
///
/// Dimensions are rejected when the source's chroma-width or height
/// does not divide cleanly into the destination's chroma grid (e.g.
/// odd width on a `4:2:2` source). The dispatch table only registers
/// six pairs — every combination on `(4:2:0, 4:2:2, 4:4:4)` — so the
/// match arms below are total.
fn chroma_resample(
    src: &VideoFrame,
    src_info: FrameInfo,
    src_wsub: usize,
    src_hsub: usize,
    dst_wsub: usize,
    dst_hsub: usize,
) -> Result<VideoFrame> {
    if src.planes.len() < 3 {
        return Err(Error::invalid(
            "pixfmt: planar YUV source needs 3 planes (Y, U, V)",
        ));
    }
    let w = src_info.width as usize;
    let h = src_info.height as usize;
    // Both chroma grids round up per the odd-dimension rule; only the
    // 4:1:1 grid pins the width (multiple of 4).
    let (src_cw, src_ch) = chroma_grid(w, h, src_wsub, src_hsub)?;
    let (dst_cw, _) = chroma_grid(w, h, dst_wsub, dst_hsub)?;

    // Luma plane: byte-for-byte copy (gather_tight already drops stride
    // padding).
    let yp = gather_tight(&src.planes[0].data, src.planes[0].stride, w, h)?;
    // Chroma planes: gather then route through the appropriate
    // resampler. `u_src` and `v_src` are independent so the helper is
    // invoked twice with identical parameters.
    let u_src = gather_tight(&src.planes[1].data, src.planes[1].stride, src_cw, src_ch)?;
    let v_src = gather_tight(&src.planes[2].data, src.planes[2].stride, src_cw, src_ch)?;
    let (u_dst, v_dst) =
        resample_chroma_pair(&u_src, &v_src, w, h, src_wsub, src_hsub, dst_wsub, dst_hsub)?;

    Ok(make_frame(
        src,
        vec![
            VideoPlane {
                stride: w,
                data: yp,
            },
            VideoPlane {
                stride: dst_cw,
                data: u_dst,
            },
            VideoPlane {
                stride: dst_cw,
                data: v_dst,
            },
        ],
    ))
}

/// Resample a tightly-packed 8-bit chroma pair between two subsampling
/// layouts. Shared core of [`chroma_resample`] (alpha-less planar YUV)
/// and [`yuva_chroma_resample`] (`Yuva*` family, where luma and alpha
/// are copied and only the chroma pair goes through here).
#[allow(clippy::too_many_arguments)]
fn resample_chroma_pair(
    u_src: &[u8],
    v_src: &[u8],
    w: usize,
    h: usize,
    src_wsub: usize,
    src_hsub: usize,
    dst_wsub: usize,
    dst_hsub: usize,
) -> Result<(Vec<u8>, Vec<u8>)> {
    let (dst_cw, dst_ch) = chroma_dims(w, h, dst_wsub, dst_hsub);
    let mut u_dst = vec![0u8; dst_cw * dst_ch];
    let mut v_dst = vec![0u8; dst_cw * dst_ch];

    // 4:4:0 on either side: compose through a 4:4:4 intermediate at
    // the same depth. Vertical duplicate-then-average (and the
    // horizontal mirror) is arithmetically the identity on the
    // duplicated axis, so the composition produces exactly the bytes a
    // fused kernel would — one rounded pair-average per subsampled
    // axis — while reusing the existing kernels for the other siting.
    if (src_wsub, src_hsub) == (1, 2) || (dst_wsub, dst_hsub) == (1, 2) {
        let (u444, v444) = if (src_wsub, src_hsub) == (1, 2) {
            let mut u = vec![0u8; w * h];
            let mut v = vec![0u8; w * h];
            yuv::chroma_440_to_444(u_src, &mut u, w, h);
            yuv::chroma_440_to_444(v_src, &mut v, w, h);
            (u, v)
        } else if (src_wsub, src_hsub) == (1, 1) {
            (u_src[..w * h].to_vec(), v_src[..w * h].to_vec())
        } else {
            resample_chroma_pair(u_src, v_src, w, h, src_wsub, src_hsub, 1, 1)?
        };
        if (dst_wsub, dst_hsub) == (1, 2) {
            yuv::chroma_444_to_440(&u444, &mut u_dst, w, h);
            yuv::chroma_444_to_440(&v444, &mut v_dst, w, h);
            return Ok((u_dst, v_dst));
        }
        if (dst_wsub, dst_hsub) == (1, 1) {
            return Ok((u444, v444));
        }
        return resample_chroma_pair(&u444, &v444, w, h, 1, 1, dst_wsub, dst_hsub);
    }

    // The dispatch table registers ordered pairs over `(4:2:0, 4:2:2,
    // 4:4:4, 4:1:1)` — every combination not equal to the identity.
    // Anything else is a registry bug so we route through
    // `Error::unsupported`.
    match (src_wsub, src_hsub, dst_wsub, dst_hsub) {
        // 4:4:4 → 4:2:2  (horizontal pair-average)
        (1, 1, 2, 1) => {
            yuv::chroma_444_to_422(u_src, &mut u_dst, w, h);
            yuv::chroma_444_to_422(v_src, &mut v_dst, w, h);
        }
        // 4:2:2 → 4:4:4  (horizontal duplicate)
        (2, 1, 1, 1) => {
            yuv::chroma_422_to_444(u_src, &mut u_dst, w, h);
            yuv::chroma_422_to_444(v_src, &mut v_dst, w, h);
        }
        // 4:4:4 → 4:2:0  (2×2 box average)
        (1, 1, 2, 2) => {
            yuv::chroma_444_to_420(u_src, &mut u_dst, w, h);
            yuv::chroma_444_to_420(v_src, &mut v_dst, w, h);
        }
        // 4:2:0 → 4:4:4  (2×2 nearest)
        (2, 2, 1, 1) => {
            yuv::chroma_420_to_444(u_src, &mut u_dst, w, h);
            yuv::chroma_420_to_444(v_src, &mut v_dst, w, h);
        }
        // 4:2:2 → 4:2:0  (vertical pair-average; chroma width unchanged)
        (2, 1, 2, 2) => {
            yuv::chroma_422_to_420(u_src, &mut u_dst, w, h);
            yuv::chroma_422_to_420(v_src, &mut v_dst, w, h);
        }
        // 4:2:0 → 4:2:2  (vertical duplicate; chroma width unchanged)
        (2, 2, 2, 1) => {
            yuv::chroma_420_to_422(u_src, &mut u_dst, w, h);
            yuv::chroma_420_to_422(v_src, &mut v_dst, w, h);
        }
        // 4:4:4 → 4:1:1  (horizontal 4-sample box average)
        (1, 1, 4, 1) => {
            yuv::chroma_444_to_411(u_src, &mut u_dst, w, h);
            yuv::chroma_444_to_411(v_src, &mut v_dst, w, h);
        }
        // 4:1:1 → 4:4:4  (horizontal 4× duplicate)
        (4, 1, 1, 1) => {
            yuv::chroma_411_to_444(u_src, &mut u_dst, w, h);
            yuv::chroma_411_to_444(v_src, &mut v_dst, w, h);
        }
        // 4:2:2 → 4:1:1  (horizontal pair-average; vertical unchanged)
        (2, 1, 4, 1) => {
            yuv::chroma_422_to_411(u_src, &mut u_dst, w, h);
            yuv::chroma_422_to_411(v_src, &mut v_dst, w, h);
        }
        // 4:1:1 → 4:2:2  (horizontal pair-duplicate; vertical unchanged)
        (4, 1, 2, 1) => {
            yuv::chroma_411_to_422(u_src, &mut u_dst, w, h);
            yuv::chroma_411_to_422(v_src, &mut v_dst, w, h);
        }
        // 4:2:0 → 4:1:1  (horizontal pair-average + vertical duplicate)
        (2, 2, 4, 1) => {
            yuv::chroma_420_to_411(u_src, &mut u_dst, w, h);
            yuv::chroma_420_to_411(v_src, &mut v_dst, w, h);
        }
        // 4:1:1 → 4:2:0  (horizontal duplicate to 4:2:2 wsub + vertical
        // pair-average)
        (4, 1, 2, 2) => {
            yuv::chroma_411_to_420(u_src, &mut u_dst, w, h);
            yuv::chroma_411_to_420(v_src, &mut v_dst, w, h);
        }
        _ => {
            return Err(Error::unsupported(
                "pixfmt: unregistered planar YUV chroma resample pair",
            ))
        }
    }

    Ok((u_dst, v_dst))
}

/// `Yuva*` → `Yuva*` chroma resample: luma (plane 0) and the
/// full-resolution alpha plane (plane 3) are copied byte-for-byte; the
/// chroma pair is resampled via [`resample_chroma_pair`]. No colour
/// matrix — alpha and luma survive bit-exact.
fn yuva_chroma_resample(
    src: &VideoFrame,
    src_info: FrameInfo,
    src_wsub: usize,
    src_hsub: usize,
    dst_wsub: usize,
    dst_hsub: usize,
) -> Result<VideoFrame> {
    if src.planes.len() < 4 {
        return Err(Error::invalid(
            "pixfmt: Yuva source needs 4 planes (Y, U, V, A)",
        ));
    }
    let w = src_info.width as usize;
    let h = src_info.height as usize;
    let (src_cw, src_ch) = chroma_grid(w, h, src_wsub, src_hsub)?;
    let (dst_cw, _) = chroma_grid(w, h, dst_wsub, dst_hsub)?;

    let yp = gather_tight(&src.planes[0].data, src.planes[0].stride, w, h)?;
    let u_src = gather_tight(&src.planes[1].data, src.planes[1].stride, src_cw, src_ch)?;
    let v_src = gather_tight(&src.planes[2].data, src.planes[2].stride, src_cw, src_ch)?;
    let ap = gather_tight(&src.planes[3].data, src.planes[3].stride, w, h)?;
    let (u_dst, v_dst) =
        resample_chroma_pair(&u_src, &v_src, w, h, src_wsub, src_hsub, dst_wsub, dst_hsub)?;

    Ok(make_frame(
        src,
        vec![
            VideoPlane {
                stride: w,
                data: yp,
            },
            VideoPlane {
                stride: dst_cw,
                data: u_dst,
            },
            VideoPlane {
                stride: dst_cw,
                data: v_dst,
            },
            VideoPlane {
                stride: w,
                data: ap,
            },
        ],
    ))
}

/// 16-bit planar YUV → 16-bit planar YUV: luma copied word-for-word,
/// chroma resampled at full 16-bit precision through the
/// `yuv::chroma16le_*` primitives. Only the pairs over (4:2:0, 4:2:2,
/// 4:4:4) are registered.
fn chroma_resample16(
    src: &VideoFrame,
    src_info: FrameInfo,
    src_wsub: usize,
    src_hsub: usize,
    dst_wsub: usize,
    dst_hsub: usize,
) -> Result<VideoFrame> {
    if src.planes.len() < 3 {
        return Err(Error::invalid(
            "pixfmt: planar YUV source needs 3 planes (Y, U, V)",
        ));
    }
    let w = src_info.width as usize;
    let h = src_info.height as usize;
    let (src_cw, src_ch) = chroma_dims(w, h, src_wsub, src_hsub);
    let (dst_cw, _) = chroma_dims(w, h, dst_wsub, dst_hsub);

    // All planes are 16-bit LE: two bytes per sample.
    let yp = gather_tight(&src.planes[0].data, src.planes[0].stride, w * 2, h)?;
    let u_src = gather_tight(
        &src.planes[1].data,
        src.planes[1].stride,
        src_cw * 2,
        src_ch,
    )?;
    let v_src = gather_tight(
        &src.planes[2].data,
        src.planes[2].stride,
        src_cw * 2,
        src_ch,
    )?;
    let (u_dst, v_dst) =
        resample_chroma16_pair(&u_src, &v_src, w, h, src_wsub, src_hsub, dst_wsub, dst_hsub)?;

    Ok(make_frame(
        src,
        vec![
            VideoPlane {
                stride: w * 2,
                data: yp,
            },
            VideoPlane {
                stride: dst_cw * 2,
                data: u_dst,
            },
            VideoPlane {
                stride: dst_cw * 2,
                data: v_dst,
            },
        ],
    ))
}

/// Resample a tightly-packed 16-bit LE chroma pair between two
/// subsampling layouts over (4:2:0, 4:2:2, 4:4:4). The `chroma16le_*`
/// primitives operate on whole LE words, so the same code path serves
/// every LSB-anchored significant width (10 / 12 / 16 bits). Shared by
/// [`chroma_resample16`] and the computed [`planar_family`] op.
#[allow(clippy::too_many_arguments)]
fn resample_chroma16_pair(
    u_src: &[u8],
    v_src: &[u8],
    w: usize,
    h: usize,
    src_wsub: usize,
    src_hsub: usize,
    dst_wsub: usize,
    dst_hsub: usize,
) -> Result<(Vec<u8>, Vec<u8>)> {
    let (dst_cw, dst_ch) = chroma_dims(w, h, dst_wsub, dst_hsub);
    let mut u_dst = vec![0u8; dst_cw * dst_ch * 2];
    let mut v_dst = vec![0u8; dst_cw * dst_ch * 2];

    // 4:4:0 on either side composes through 4:4:4 exactly as the 8-bit
    // pair above (same rounding, one pair-average per subsampled axis).
    if (src_wsub, src_hsub) == (1, 2) || (dst_wsub, dst_hsub) == (1, 2) {
        let (u444, v444) = if (src_wsub, src_hsub) == (1, 2) {
            let mut u = vec![0u8; w * h * 2];
            let mut v = vec![0u8; w * h * 2];
            yuv::chroma16le_440_to_444(u_src, &mut u, w, h);
            yuv::chroma16le_440_to_444(v_src, &mut v, w, h);
            (u, v)
        } else if (src_wsub, src_hsub) == (1, 1) {
            (u_src[..w * h * 2].to_vec(), v_src[..w * h * 2].to_vec())
        } else {
            resample_chroma16_pair(u_src, v_src, w, h, src_wsub, src_hsub, 1, 1)?
        };
        if (dst_wsub, dst_hsub) == (1, 2) {
            yuv::chroma16le_444_to_440(&u444, &mut u_dst, w, h);
            yuv::chroma16le_444_to_440(&v444, &mut v_dst, w, h);
            return Ok((u_dst, v_dst));
        }
        if (dst_wsub, dst_hsub) == (1, 1) {
            return Ok((u444, v444));
        }
        return resample_chroma16_pair(&u444, &v444, w, h, 1, 1, dst_wsub, dst_hsub);
    }

    match (src_wsub, src_hsub, dst_wsub, dst_hsub) {
        (1, 1, 2, 1) => {
            yuv::chroma16le_444_to_422(u_src, &mut u_dst, w, h);
            yuv::chroma16le_444_to_422(v_src, &mut v_dst, w, h);
        }
        (2, 1, 1, 1) => {
            yuv::chroma16le_422_to_444(u_src, &mut u_dst, w, h);
            yuv::chroma16le_422_to_444(v_src, &mut v_dst, w, h);
        }
        (1, 1, 2, 2) => {
            yuv::chroma16le_444_to_420(u_src, &mut u_dst, w, h);
            yuv::chroma16le_444_to_420(v_src, &mut v_dst, w, h);
        }
        (2, 2, 1, 1) => {
            yuv::chroma16le_420_to_444(u_src, &mut u_dst, w, h);
            yuv::chroma16le_420_to_444(v_src, &mut v_dst, w, h);
        }
        (2, 1, 2, 2) => {
            yuv::chroma16le_422_to_420(u_src, &mut u_dst, w, h);
            yuv::chroma16le_422_to_420(v_src, &mut v_dst, w, h);
        }
        (2, 2, 2, 1) => {
            yuv::chroma16le_420_to_422(u_src, &mut u_dst, w, h);
            yuv::chroma16le_420_to_422(v_src, &mut v_dst, w, h);
        }
        _ => {
            return Err(Error::unsupported(
                "pixfmt: unregistered 16-bit planar YUV chroma resample pair",
            ))
        }
    }

    Ok((u_dst, v_dst))
}

// -------------------------------------------------------------------------
// Computed planar-family ops (see `PlanarYuv` / `lookup_computed`).

/// Move one gathered (tight) plane of `count` samples between two
/// planar-family storage depths: 8-bit planes are a byte per sample,
/// deeper planes 16-bit LE words with `bits` significant low bits.
/// Equal depths degrade to a copy (masked for the deep widths); the
/// widen / narrow legs follow the crate-wide MSB-replicate / truncate
/// policy via the shared `yuv::depth_*` primitives.
fn plane_to_depth(src: &[u8], count: usize, src_bits: u32, dst_bits: u32) -> Vec<u8> {
    match (src_bits > 8, dst_bits > 8) {
        (false, false) => src[..count].to_vec(),
        (false, true) => {
            let mut out = vec![0u8; count * 2];
            yuv::depth_up_8_to_le16_plane(src, &mut out, count, dst_bits);
            out
        }
        (true, false) => {
            let mut out = vec![0u8; count];
            yuv::depth_down_le16_plane(src, &mut out, count, src_bits);
            out
        }
        (true, true) => {
            let mut out = vec![0u8; count * 2];
            yuv::depth_rescale_le16_plane(src, &mut out, count, src_bits, dst_bits);
            out
        }
    }
}

/// Resample a tightly-packed chroma pair at the storage depth implied
/// by `bits`: byte planes route through the 8-bit primitives, LE-word
/// planes through the 16-bit ones (identical rounding conventions).
#[allow(clippy::too_many_arguments)]
fn resample_pair_at_depth(
    u_src: &[u8],
    v_src: &[u8],
    w: usize,
    h: usize,
    src_wsub: usize,
    src_hsub: usize,
    dst_wsub: usize,
    dst_hsub: usize,
    bits: u32,
) -> Result<(Vec<u8>, Vec<u8>)> {
    if bits > 8 {
        resample_chroma16_pair(u_src, v_src, w, h, src_wsub, src_hsub, dst_wsub, dst_hsub)
    } else {
        resample_chroma_pair(u_src, v_src, w, h, src_wsub, src_hsub, dst_wsub, dst_hsub)
    }
}

/// A plane of `count` opaque (full-scale) alpha samples at `bits`
/// depth: `0xFF` bytes for 8-bit storage, LE words of `(1 << bits) - 1`
/// for the deep widths.
fn opaque_plane(count: usize, bits: u32) -> Vec<u8> {
    if bits > 8 {
        let full = ((1u32 << bits) - 1) as u16;
        let [lo, hi] = full.to_le_bytes();
        let mut out = vec![0u8; count * 2];
        for word in out.chunks_exact_mut(2) {
            word[0] = lo;
            word[1] = hi;
        }
        out
    } else {
        vec![0xFF; count]
    }
}

/// A plane of `count` neutral chroma samples at `bits` depth: the exact
/// mid-code `1 << (bits - 1)` (128 / 512 / 2048 / 32768).
fn neutral_chroma_plane(count: usize, bits: u32) -> Vec<u8> {
    if bits > 8 {
        let mid = (1u32 << (bits - 1)) as u16;
        let [lo, hi] = mid.to_le_bytes();
        let mut out = vec![0u8; count * 2];
        for word in out.chunks_exact_mut(2) {
            word[0] = lo;
            word[1] = hi;
        }
        out
    } else {
        vec![128; count]
    }
}

/// Computed `PlanarFamily` op: any ordered pair inside the uniform
/// planar YUV(A) family. Luma (and a carried alpha plane) go through a
/// straight depth move; the chroma pair is resampled at the **deeper**
/// of the two depths — widen-then-resample when the destination is
/// deeper, resample-then-narrow otherwise — so no precision is thrown
/// away before an average is taken. Alpha is carried (depth-moved),
/// dropped, or synthesised opaque full-scale per the two descriptors.
fn planar_family(
    src: &VideoFrame,
    src_info: FrameInfo,
    s: PlanarYuv,
    d: PlanarYuv,
) -> Result<VideoFrame> {
    let need = if s.alpha { 4 } else { 3 };
    if src.planes.len() < need {
        return Err(Error::invalid(
            "pixfmt: planar YUV(A) source is missing planes",
        ));
    }
    let w = src_info.width as usize;
    let h = src_info.height as usize;
    let (scw, sch) = chroma_dims(w, h, s.wsub, s.hsub);
    let (dcw, dch) = chroma_dims(w, h, d.wsub, d.hsub);
    let sb_src = s.sample_bytes();
    let sb_dst = d.sample_bytes();

    let y_src = gather_tight(&src.planes[0].data, src.planes[0].stride, w * sb_src, h)?;
    let u_src = gather_tight(&src.planes[1].data, src.planes[1].stride, scw * sb_src, sch)?;
    let v_src = gather_tight(&src.planes[2].data, src.planes[2].stride, scw * sb_src, sch)?;

    // Luma: straight depth move, never resampled.
    let yp = plane_to_depth(&y_src, w * h, s.bits, d.bits);

    // Chroma: resample at the deeper of the two depths.
    let (up, vp) = if (s.wsub, s.hsub) == (d.wsub, d.hsub) {
        (
            plane_to_depth(&u_src, scw * sch, s.bits, d.bits),
            plane_to_depth(&v_src, scw * sch, s.bits, d.bits),
        )
    } else if d.bits >= s.bits {
        let u_mid = plane_to_depth(&u_src, scw * sch, s.bits, d.bits);
        let v_mid = plane_to_depth(&v_src, scw * sch, s.bits, d.bits);
        resample_pair_at_depth(&u_mid, &v_mid, w, h, s.wsub, s.hsub, d.wsub, d.hsub, d.bits)?
    } else {
        let (u_mid, v_mid) =
            resample_pair_at_depth(&u_src, &v_src, w, h, s.wsub, s.hsub, d.wsub, d.hsub, s.bits)?;
        (
            plane_to_depth(&u_mid, dcw * dch, s.bits, d.bits),
            plane_to_depth(&v_mid, dcw * dch, s.bits, d.bits),
        )
    };

    let mut planes = vec![
        VideoPlane {
            stride: w * sb_dst,
            data: yp,
        },
        VideoPlane {
            stride: dcw * sb_dst,
            data: up,
        },
        VideoPlane {
            stride: dcw * sb_dst,
            data: vp,
        },
    ];
    if d.alpha {
        let ap = if s.alpha {
            let a_src = gather_tight(&src.planes[3].data, src.planes[3].stride, w * sb_src, h)?;
            plane_to_depth(&a_src, w * h, s.bits, d.bits)
        } else {
            opaque_plane(w * h, d.bits)
        };
        planes.push(VideoPlane {
            stride: w * sb_dst,
            data: ap,
        });
    }
    Ok(make_frame(src, planes))
}

/// Computed `PlanarFamilyToRgb` op: family member → `Rgb24` / `Rgba`.
/// Deep planes are truncated to 8 bits (crate depth policy) and decoded
/// through the proven 8-bit scalar/SIMD matrix for the source's chroma
/// grid; alpha is interleaved (reduced to 8 bits), synthesised opaque,
/// or dropped.
fn planar_family_to_rgb(
    src: &VideoFrame,
    src_info: FrameInfo,
    matrix: YuvMatrix,
    s: PlanarYuv,
    alpha: bool,
    workers: usize,
) -> Result<VideoFrame> {
    let need = if s.alpha { 4 } else { 3 };
    if src.planes.len() < need {
        return Err(Error::invalid(
            "pixfmt: planar YUV(A) source is missing planes",
        ));
    }
    let w = src_info.width as usize;
    let h = src_info.height as usize;
    let (cw, ch) = chroma_dims(w, h, s.wsub, s.hsub);
    let sb = s.sample_bytes();
    let y_src = tight_plane(&src.planes[0], w * sb, h)?;
    let u_src = tight_plane(&src.planes[1], cw * sb, ch)?;
    let v_src = tight_plane(&src.planes[2], cw * sb, ch)?;
    // Deep planes are narrowed to bytes (crate depth policy); 8-bit
    // planes are borrowed as they are.
    let yp = plane_to_depth_cow(y_src, w * h, s.bits, workers);
    let up = plane_to_depth_cow(u_src, cw * ch, s.bits, workers);
    let vp = plane_to_depth_cow(v_src, cw * ch, s.bits, workers);
    let ap = if alpha && s.alpha {
        let a_src = tight_plane(&src.planes[3], w * sb, h)?;
        Some(plane_to_depth_cow(a_src, w * h, s.bits, workers))
    } else {
        None
    };
    let bpp = if alpha { 4 } else { 3 };
    let out = planar8::decode(
        &Planar8 {
            y: &yp,
            u: &up,
            v: &vp,
            a: ap.as_deref(),
            w,
            h,
            wsub: s.wsub,
            hsub: s.hsub,
        },
        bpp,
        matrix,
        workers,
    );
    Ok(make_frame(
        src,
        vec![VideoPlane {
            stride: w * bpp,
            data: out,
        }],
    ))
}

/// [`plane_to_depth`] to 8 bits, without copying a plane that is
/// already byte storage.
fn plane_to_depth_cow(
    src: std::borrow::Cow<'_, [u8]>,
    count: usize,
    src_bits: u32,
    workers: usize,
) -> std::borrow::Cow<'_, [u8]> {
    if src_bits > 8 {
        std::borrow::Cow::Owned(planar8::narrow_to_8(&src, count, src_bits, workers))
    } else {
        src
    }
}

/// Computed `RgbToPlanarFamily` op: `Rgb24` / `Rgba` → family member.
/// Encodes through the proven 8-bit path for the destination's chroma
/// grid, then widens every plane to the family depth (MSB replication —
/// identical bytes to the historical encode-then-`DepthUpYuv` staged
/// route). Alpha is split out of an `Rgba` source (widened) or
/// synthesised opaque full-scale.
fn rgb_to_planar_family(
    src: &VideoFrame,
    src_info: FrameInfo,
    matrix: YuvMatrix,
    d: PlanarYuv,
    alpha_in: bool,
    workers: usize,
) -> Result<VideoFrame> {
    let w = src_info.width as usize;
    let h = src_info.height as usize;
    let sb = d.sample_bytes();
    let packed = packed8_source(src, w, h, if alpha_in { 4 } else { 3 })?;
    // 4:4:0: encode at 4:4:4, then vertical pair-average the chroma
    // (rounded to nearest, like the 4:2:2 → 4:2:0 step).
    let (enc_wsub, enc_hsub) = if (d.wsub, d.hsub) == (1, 2) {
        (1, 1)
    } else {
        (d.wsub, d.hsub)
    };
    let enc = planar8::encode(&packed, enc_wsub, enc_hsub, matrix, d.alpha, workers);
    let (cw, ch) = chroma_dims(w, h, d.wsub, d.hsub);
    let (up8, vp8) = if (d.wsub, d.hsub) == (1, 2) {
        let mut u = vec![0u8; cw * ch];
        let mut v = vec![0u8; cw * ch];
        yuv::chroma_444_to_440(&enc.u, &mut u, w, h);
        yuv::chroma_444_to_440(&enc.v, &mut v, w, h);
        (u, v)
    } else {
        (enc.u, enc.v)
    };

    let mut planes = vec![
        VideoPlane {
            stride: w * sb,
            data: plane_to_depth(&enc.y, w * h, 8, d.bits),
        },
        VideoPlane {
            stride: cw * sb,
            data: plane_to_depth(&up8, cw * ch, 8, d.bits),
        },
        VideoPlane {
            stride: cw * sb,
            data: plane_to_depth(&vp8, cw * ch, 8, d.bits),
        },
    ];
    if d.alpha {
        let ap = match enc.a {
            Some(alpha8) => plane_to_depth(&alpha8, w * h, 8, d.bits),
            None => opaque_plane(w * h, d.bits),
        };
        planes.push(VideoPlane {
            stride: w * sb,
            data: ap,
        });
    }
    Ok(make_frame(src, planes))
}

/// Computed `PlanarFamilyToGray` op: luma extraction from any family
/// member. Deep luma is truncated to 8 bits, then rescaled from the
/// family's limited range to full-range `Gray8`; chroma and alpha are
/// dropped. Only the luma plane is touched, so odd dimensions are fine
/// even on subsampled sources (mirrors the 8-bit `YuvLumaToGray` rows).
fn planar_family_to_gray(
    src: &VideoFrame,
    src_info: FrameInfo,
    s: PlanarYuv,
    limited: bool,
) -> Result<VideoFrame> {
    if src.planes.is_empty() {
        return Err(Error::invalid("pixfmt: YUV source needs a luma plane"));
    }
    let w = src_info.width as usize;
    let h = src_info.height as usize;
    let sb = s.sample_bytes();
    let y_src = gather_tight(&src.planes[0].data, src.planes[0].stride, w * sb, h)?;
    let mut yp = plane_to_depth(&y_src, w * h, s.bits, 8);
    if limited {
        yuv::limited_to_full_luma(&mut yp);
    }
    Ok(make_frame(
        src,
        vec![VideoPlane {
            stride: w,
            data: yp,
        }],
    ))
}

/// Computed `GrayToPlanarFamily` op: `Gray8` → any family member. The
/// gray plane becomes luma (full → limited range at 8 bits, then
/// widened); chroma is synthesised at the exact neutral mid-code
/// `1 << (bits - 1)`; alpha (when the destination carries it) is
/// synthesised opaque full-scale.
fn gray_to_planar_family(
    src: &VideoFrame,
    src_info: FrameInfo,
    d: PlanarYuv,
    limited: bool,
) -> Result<VideoFrame> {
    let w = src_info.width as usize;
    let h = src_info.height as usize;
    let (cw, ch) = chroma_dims(w, h, d.wsub, d.hsub);
    let sb = d.sample_bytes();
    let mut luma8 = gather_tight(&src.planes[0].data, src.planes[0].stride, w, h)?;
    if limited {
        yuv::full_to_limited_luma(&mut luma8);
    }
    let mut planes = vec![
        VideoPlane {
            stride: w * sb,
            data: plane_to_depth(&luma8, w * h, 8, d.bits),
        },
        VideoPlane {
            stride: cw * sb,
            data: neutral_chroma_plane(cw * ch, d.bits),
        },
        VideoPlane {
            stride: cw * sb,
            data: neutral_chroma_plane(cw * ch, d.bits),
        },
    ];
    if d.alpha {
        planes.push(VideoPlane {
            stride: w * sb,
            data: opaque_plane(w * h, d.bits),
        });
    }
    Ok(make_frame(src, planes))
}

/// High-precision planar YUV (16-bit LE, `bits` significant) → 8-bit
/// planar YUV. Luma and both chroma planes are reduced by
/// [`yuv::depth_down_le16_plane`]; the chroma subsampling layout
/// (`wsub` / `hsub`) is preserved unchanged. Width / height must divide
/// cleanly into the chroma grid, else `Error::invalid`.
fn do_yuv_depth_down(
    src: &VideoFrame,
    src_info: FrameInfo,
    wsub: usize,
    hsub: usize,
    bits: u32,
) -> Result<VideoFrame> {
    if src.planes.len() < 3 {
        return Err(Error::invalid(
            "pixfmt: high-bit YUV source needs 3 planes (Y, U, V)",
        ));
    }
    let w = src_info.width as usize;
    let h = src_info.height as usize;
    let (cw, ch) = chroma_dims(w, h, wsub, hsub);
    // Source planes are 16-bit LE: each sample is two bytes wide.
    let y_src = gather_tight(&src.planes[0].data, src.planes[0].stride, w * 2, h)?;
    let u_src = gather_tight(&src.planes[1].data, src.planes[1].stride, cw * 2, ch)?;
    let v_src = gather_tight(&src.planes[2].data, src.planes[2].stride, cw * 2, ch)?;
    let mut yp = vec![0u8; w * h];
    let mut up = vec![0u8; cw * ch];
    let mut vp = vec![0u8; cw * ch];
    yuv::depth_down_le16_plane(&y_src, &mut yp, w * h, bits);
    yuv::depth_down_le16_plane(&u_src, &mut up, cw * ch, bits);
    yuv::depth_down_le16_plane(&v_src, &mut vp, cw * ch, bits);
    Ok(make_frame(
        src,
        vec![
            VideoPlane {
                stride: w,
                data: yp,
            },
            VideoPlane {
                stride: cw,
                data: up,
            },
            VideoPlane {
                stride: cw,
                data: vp,
            },
        ],
    ))
}

/// 8-bit planar YUV → high-precision planar YUV (16-bit LE, `bits`
/// significant). The inverse of [`do_yuv_depth_down`]: each plane is
/// widened by [`yuv::depth_up_8_to_le16_plane`] (8-bit value in the high
/// bits with MSB replication into the low slack). Subsampling preserved.
fn do_yuv_depth_up(
    src: &VideoFrame,
    src_info: FrameInfo,
    wsub: usize,
    hsub: usize,
    bits: u32,
) -> Result<VideoFrame> {
    if src.planes.len() < 3 {
        return Err(Error::invalid(
            "pixfmt: planar YUV source needs 3 planes (Y, U, V)",
        ));
    }
    let w = src_info.width as usize;
    let h = src_info.height as usize;
    let (cw, ch) = chroma_dims(w, h, wsub, hsub);
    let y_src = gather_tight(&src.planes[0].data, src.planes[0].stride, w, h)?;
    let u_src = gather_tight(&src.planes[1].data, src.planes[1].stride, cw, ch)?;
    let v_src = gather_tight(&src.planes[2].data, src.planes[2].stride, cw, ch)?;
    let mut yp = vec![0u8; w * h * 2];
    let mut up = vec![0u8; cw * ch * 2];
    let mut vp = vec![0u8; cw * ch * 2];
    yuv::depth_up_8_to_le16_plane(&y_src, &mut yp, w * h, bits);
    yuv::depth_up_8_to_le16_plane(&u_src, &mut up, cw * ch, bits);
    yuv::depth_up_8_to_le16_plane(&v_src, &mut vp, cw * ch, bits);
    Ok(make_frame(
        src,
        vec![
            VideoPlane {
                stride: w * 2,
                data: yp,
            },
            VideoPlane {
                stride: cw * 2,
                data: up,
            },
            VideoPlane {
                stride: cw * 2,
                data: vp,
            },
        ],
    ))
}

/// Cross-depth planar YUV (10 ↔ 12 bit, 16-bit LE storage on both
/// sides): every plane goes through [`yuv::depth_rescale_le16_plane`];
/// subsampling is preserved.
fn do_yuv_depth_rescale(
    src: &VideoFrame,
    src_info: FrameInfo,
    wsub: usize,
    hsub: usize,
    src_bits: u32,
    dst_bits: u32,
) -> Result<VideoFrame> {
    if src.planes.len() < 3 {
        return Err(Error::invalid(
            "pixfmt: high-bit YUV source needs 3 planes (Y, U, V)",
        ));
    }
    let w = src_info.width as usize;
    let h = src_info.height as usize;
    let (cw, ch) = chroma_dims(w, h, wsub, hsub);
    let y_src = gather_tight(&src.planes[0].data, src.planes[0].stride, w * 2, h)?;
    let u_src = gather_tight(&src.planes[1].data, src.planes[1].stride, cw * 2, ch)?;
    let v_src = gather_tight(&src.planes[2].data, src.planes[2].stride, cw * 2, ch)?;
    let mut yp = vec![0u8; w * h * 2];
    let mut up = vec![0u8; cw * ch * 2];
    let mut vp = vec![0u8; cw * ch * 2];
    yuv::depth_rescale_le16_plane(&y_src, &mut yp, w * h, src_bits, dst_bits);
    yuv::depth_rescale_le16_plane(&u_src, &mut up, cw * ch, src_bits, dst_bits);
    yuv::depth_rescale_le16_plane(&v_src, &mut vp, cw * ch, src_bits, dst_bits);
    Ok(make_frame(
        src,
        vec![
            VideoPlane {
                stride: w * 2,
                data: yp,
            },
            VideoPlane {
                stride: cw * 2,
                data: up,
            },
            VideoPlane {
                stride: cw * 2,
                data: vp,
            },
        ],
    ))
}

// -------------------------------------------------------------------------
// Deep grayscale (Gray10Le / Gray12Le / Gray16Le) storage-width ladder.

/// `Gray10Le` / `Gray12Le` → `Gray8` (keep the top 8 significant bits).
fn do_gray_depth_down8(src: &VideoFrame, src_info: FrameInfo, bits: u32) -> Result<VideoFrame> {
    let w = src_info.width as usize;
    let h = src_info.height as usize;
    let in_plane = &src.planes[0];
    let tight = gather_tight(&in_plane.data, in_plane.stride, w * 2, h)?;
    let mut out = vec![0u8; w * h];
    yuv::depth_down_le16_plane(&tight, &mut out, w * h, bits);
    Ok(make_frame(
        src,
        vec![VideoPlane {
            stride: w,
            data: out,
        }],
    ))
}

/// `Gray8` → `Gray10Le` / `Gray12Le` (MSB-replicated widen; exact
/// inverse of [`do_gray_depth_down8`]).
fn do_gray_depth_up8(src: &VideoFrame, src_info: FrameInfo, bits: u32) -> Result<VideoFrame> {
    let w = src_info.width as usize;
    let h = src_info.height as usize;
    let in_plane = &src.planes[0];
    let tight = gather_tight(&in_plane.data, in_plane.stride, w, h)?;
    let mut out = vec![0u8; w * h * 2];
    yuv::depth_up_8_to_le16_plane(&tight, &mut out, w * h, bits);
    Ok(make_frame(
        src,
        vec![VideoPlane {
            stride: w * 2,
            data: out,
        }],
    ))
}

/// Deep grayscale ↔ deep grayscale (10 ↔ 12 ↔ 16) storage rescale.
fn do_gray_depth_rescale(
    src: &VideoFrame,
    src_info: FrameInfo,
    src_bits: u32,
    dst_bits: u32,
) -> Result<VideoFrame> {
    let w = src_info.width as usize;
    let h = src_info.height as usize;
    let in_plane = &src.planes[0];
    let tight = gather_tight(&in_plane.data, in_plane.stride, w * 2, h)?;
    let mut out = vec![0u8; w * h * 2];
    yuv::depth_rescale_le16_plane(&tight, &mut out, w * h, src_bits, dst_bits);
    Ok(make_frame(
        src,
        vec![VideoPlane {
            stride: w * 2,
            data: out,
        }],
    ))
}

fn nv_to_yuv420p(src: &VideoFrame, src_info: FrameInfo, is_nv12: bool) -> Result<VideoFrame> {
    let w = src_info.width as usize;
    let h = src_info.height as usize;
    let (yp, up, vp) = nv_source(src, w, h, is_nv12)?;
    let cw = w.div_ceil(2);
    Ok(make_frame(
        src,
        vec![
            VideoPlane {
                stride: w,
                data: yp.into_owned(),
            },
            VideoPlane {
                stride: cw,
                data: up,
            },
            VideoPlane {
                stride: cw,
                data: vp,
            },
        ],
    ))
}

fn yuv420p_to_nv(src: &VideoFrame, src_info: FrameInfo, is_nv12: bool) -> Result<VideoFrame> {
    let w = src_info.width as usize;
    let h = src_info.height as usize;
    let (yp, up, vp, _) = planar8_source(src, w, h, 2, 2, false)?;
    let (cw, ch) = chroma_dims(w, h, 2, 2);
    let mut uv = vec![0u8; cw * ch * 2];
    if is_nv12 {
        yuv::nv12_uv_merge(&up, &vp, &mut uv, cw, ch);
    } else {
        yuv::nv21_vu_merge(&up, &vp, &mut uv, cw, ch);
    }
    Ok(make_frame(
        src,
        vec![
            VideoPlane {
                stride: w,
                data: yp.into_owned(),
            },
            VideoPlane {
                stride: cw * 2,
                data: uv,
            },
        ],
    ))
}

/// NV12 / NV21 → packed RGB. Fused path: deinterleave the UV plane
/// into transient U / V planes, then run the proven planar 4:2:0 →
/// RGB decoder. Saves the caller a `Nv → Yuv420P → Rgb` two-step.
///
/// 4:2:0 subsampling pins width and height to multiples of 2; an odd
/// dimension is rejected with `Error::Invalid` (the format has no
/// representation for a half-pixel row or column).
fn nv_to_rgb(
    src: &VideoFrame,
    src_info: FrameInfo,
    matrix: YuvMatrix,
    is_nv12: bool,
    alpha: bool,
    workers: usize,
) -> Result<VideoFrame> {
    let w = src_info.width as usize;
    let h = src_info.height as usize;
    let (yp, up, vp) = nv_source(src, w, h, is_nv12)?;
    let bpp = if alpha { 4 } else { 3 };
    let out = planar8::decode(
        &Planar8 {
            y: &yp,
            u: &up,
            v: &vp,
            a: None,
            w,
            h,
            wsub: 2,
            hsub: 2,
        },
        bpp,
        matrix,
        workers,
    );
    Ok(make_frame(
        src,
        vec![VideoPlane {
            stride: w * bpp,
            data: out,
        }],
    ))
}

/// Tight luma plane plus the interleaved chroma plane of an NV12 / NV21
/// source split into U and V planes (`ceil(w / 2)` × `ceil(h / 2)`).
#[allow(clippy::type_complexity)]
fn nv_source(
    src: &VideoFrame,
    w: usize,
    h: usize,
    is_nv12: bool,
) -> Result<(std::borrow::Cow<'_, [u8]>, Vec<u8>, Vec<u8>)> {
    if src.planes.len() < 2 {
        return Err(Error::invalid("pixfmt: NV source needs 2 planes"));
    }
    let (cw, ch) = chroma_dims(w, h, 2, 2);
    let yp = tight_plane(&src.planes[0], w, h)?;
    let uv = tight_plane(&src.planes[1], cw * 2, ch)?;
    let mut up = vec![0u8; cw * ch];
    let mut vp = vec![0u8; cw * ch];
    if is_nv12 {
        yuv::nv12_uv_split(&uv, &mut up, &mut vp, cw, ch);
    } else {
        yuv::nv21_vu_split(&uv, &mut up, &mut vp, cw, ch);
    }
    Ok((yp, up, vp))
}

/// Packed RGB → NV12 / NV21. Reuses the planar 4:2:0 encoder, then
/// interleaves the resulting (U, V) planes back into the NV layout.
fn rgb_to_nv(
    src: &VideoFrame,
    src_info: FrameInfo,
    matrix: YuvMatrix,
    is_nv12: bool,
    alpha_in: bool,
    workers: usize,
) -> Result<VideoFrame> {
    let w = src_info.width as usize;
    let h = src_info.height as usize;
    let packed = packed8_source(src, w, h, if alpha_in { 4 } else { 3 })?;
    let enc = planar8::encode(&packed, 2, 2, matrix, false, workers);
    let (cw, ch) = (enc.cw, enc.ch);
    let mut uv = vec![0u8; cw * ch * 2];
    if is_nv12 {
        yuv::nv12_uv_merge(&enc.u, &enc.v, &mut uv, cw, ch);
    } else {
        yuv::nv21_vu_merge(&enc.u, &enc.v, &mut uv, cw, ch);
    }
    Ok(make_frame(
        src,
        vec![
            VideoPlane {
                stride: w,
                data: enc.y,
            },
            VideoPlane {
                stride: cw * 2,
                data: uv,
            },
        ],
    ))
}

// -------------------------------------------------------------------------
// Packed 4:2:2 (YUYV / UYVY).
//
// Even-width frames are a hard requirement: the format pairs two luma
// samples per chroma pair, so an odd width has no representation. We
// return Error::Invalid rather than silently truncating.

fn packed422_to_yuv422p(
    src: &VideoFrame,
    src_info: FrameInfo,
    is_yuyv: bool,
) -> Result<VideoFrame> {
    let w = src_info.width as usize;
    let h = src_info.height as usize;
    if w % 2 != 0 {
        return Err(Error::invalid("pixfmt: packed 4:2:2 requires even width"));
    }
    let cw = w / 2;
    let in_plane = &src.planes[0];
    let packed = gather_tight(&in_plane.data, in_plane.stride, w * 2, h)?;
    let mut yp = vec![0u8; w * h];
    let mut up = vec![0u8; cw * h];
    let mut vp = vec![0u8; cw * h];
    if is_yuyv {
        yuv::yuyv422_to_yuv422p(&packed, &mut yp, &mut up, &mut vp, w, h);
    } else {
        yuv::uyvy422_to_yuv422p(&packed, &mut yp, &mut up, &mut vp, w, h);
    }
    Ok(make_frame(
        src,
        vec![
            VideoPlane {
                stride: w,
                data: yp,
            },
            VideoPlane {
                stride: cw,
                data: up,
            },
            VideoPlane {
                stride: cw,
                data: vp,
            },
        ],
    ))
}

fn yuv422p_to_packed422(
    src: &VideoFrame,
    src_info: FrameInfo,
    is_yuyv: bool,
) -> Result<VideoFrame> {
    if src.planes.len() < 3 {
        return Err(Error::invalid("pixfmt: Yuv422P source needs 3 planes"));
    }
    let w = src_info.width as usize;
    let h = src_info.height as usize;
    if w % 2 != 0 {
        return Err(Error::invalid("pixfmt: packed 4:2:2 requires even width"));
    }
    let cw = w / 2;
    let yp = gather_tight(&src.planes[0].data, src.planes[0].stride, w, h)?;
    let up = gather_tight(&src.planes[1].data, src.planes[1].stride, cw, h)?;
    let vp = gather_tight(&src.planes[2].data, src.planes[2].stride, cw, h)?;
    let mut packed = vec![0u8; w * h * 2];
    if is_yuyv {
        yuv::yuv422p_to_yuyv422(&yp, &up, &vp, &mut packed, w, h);
    } else {
        yuv::yuv422p_to_uyvy422(&yp, &up, &vp, &mut packed, w, h);
    }
    Ok(make_frame(
        src,
        vec![VideoPlane {
            stride: w * 2,
            data: packed,
        }],
    ))
}

fn packed422_swap(src: &VideoFrame, src_info: FrameInfo) -> Result<VideoFrame> {
    let w = src_info.width as usize;
    let h = src_info.height as usize;
    if w % 2 != 0 {
        return Err(Error::invalid("pixfmt: packed 4:2:2 requires even width"));
    }
    let in_plane = &src.planes[0];
    let mut packed = gather_tight(&in_plane.data, in_plane.stride, w * 2, h)?;
    yuv::yuyv_uyvy_swap(&mut packed);
    Ok(make_frame(
        src,
        vec![VideoPlane {
            stride: w * 2,
            data: packed,
        }],
    ))
}

fn packed422_to_rgb(
    src: &VideoFrame,
    src_info: FrameInfo,
    matrix: YuvMatrix,
    is_yuyv: bool,
    alpha: bool,
) -> Result<VideoFrame> {
    let w = src_info.width as usize;
    let h = src_info.height as usize;
    if w % 2 != 0 {
        return Err(Error::invalid("pixfmt: packed 4:2:2 requires even width"));
    }
    let cw = w / 2;
    let in_plane = &src.planes[0];
    let packed = gather_tight(&in_plane.data, in_plane.stride, w * 2, h)?;
    // Reuse the planar 4:2:2 → RGB path: deinterleave first, then go
    // through the proven scalar/SIMD planar decoder.
    let mut yp = vec![0u8; w * h];
    let mut up = vec![0u8; cw * h];
    let mut vp = vec![0u8; cw * h];
    if is_yuyv {
        yuv::yuyv422_to_yuv422p(&packed, &mut yp, &mut up, &mut vp, w, h);
    } else {
        yuv::uyvy422_to_yuv422p(&packed, &mut yp, &mut up, &mut vp, w, h);
    }
    let mut rgb_buf = vec![0u8; w * h * 3];
    yuv::yuv422_to_rgb24(&yp, &up, &vp, &mut rgb_buf, w, h, matrix);
    if !alpha {
        return Ok(make_frame(
            src,
            vec![VideoPlane {
                stride: w * 3,
                data: rgb_buf,
            }],
        ));
    }
    let mut rgba = vec![0u8; w * h * 4];
    for i in 0..w * h {
        rgba[i * 4] = rgb_buf[i * 3];
        rgba[i * 4 + 1] = rgb_buf[i * 3 + 1];
        rgba[i * 4 + 2] = rgb_buf[i * 3 + 2];
        rgba[i * 4 + 3] = 255;
    }
    Ok(make_frame(
        src,
        vec![VideoPlane {
            stride: w * 4,
            data: rgba,
        }],
    ))
}

fn rgb_to_packed422(
    src: &VideoFrame,
    src_info: FrameInfo,
    matrix: YuvMatrix,
    is_yuyv: bool,
    alpha_in: bool,
) -> Result<VideoFrame> {
    let w = src_info.width as usize;
    let h = src_info.height as usize;
    if w % 2 != 0 {
        return Err(Error::invalid("pixfmt: packed 4:2:2 requires even width"));
    }
    let cw = w / 2;
    let in_plane = &src.planes[0];
    // Project the source to a tight RGB24 buffer first — matches the
    // existing planar 4:2:2 encode path.
    let rgb24: Vec<u8> = if alpha_in {
        let mut out = Vec::with_capacity(w * h * 3);
        for row in 0..h {
            let row_bytes = w * 4;
            let sr = tight_row(&in_plane.data, in_plane.stride, row, row_bytes);
            for i in 0..w {
                out.push(sr[i * 4]);
                out.push(sr[i * 4 + 1]);
                out.push(sr[i * 4 + 2]);
            }
        }
        out
    } else {
        gather_tight(&in_plane.data, in_plane.stride, w * 3, h)?
    };
    let mut yp = vec![0u8; w * h];
    let mut up = vec![0u8; cw * h];
    let mut vp = vec![0u8; cw * h];
    yuv::rgb24_to_yuv422(&rgb24, &mut yp, &mut up, &mut vp, w, h, matrix);
    let mut packed = vec![0u8; w * h * 2];
    if is_yuyv {
        yuv::yuv422p_to_yuyv422(&yp, &up, &vp, &mut packed, w, h);
    } else {
        yuv::yuv422p_to_uyvy422(&yp, &up, &vp, &mut packed, w, h);
    }
    Ok(make_frame(
        src,
        vec![VideoPlane {
            stride: w * 2,
            data: packed,
        }],
    ))
}

// -------------------------------------------------------------------------
// Palette.

/// `Pal8` → packed RGB(A). The colour table is resolved in priority
/// order:
///
/// 1. the frame's own **palette side-channel** (a trailing `stride == 0`
///    plane attached via `VideoFrame::set_palette` — packed 3-byte RGB
///    entries, expanded here with opaque alpha), which is per-frame
///    ground truth from a decoder;
/// 2. the caller-supplied `ConvertOptions::palette` as before;
/// 3. neither present → `Error::Invalid`.
fn pal8_to_rgb(
    src: &VideoFrame,
    src_info: FrameInfo,
    opts: &ConvertOptions,
    alpha: bool,
) -> Result<VideoFrame> {
    // Frame-attached palette wins over the options bundle: it travels
    // with the frame it describes. Per-entry alpha comes from the
    // palette-alpha side-channel (core 0.1.40): a covered entry's byte,
    // opaque 255 for every entry the record does not cover (or when
    // there is no record / a malformed one, which core reads as none).
    let side_channel = src.palette().map(|raw| {
        let alpha = src.palette_alpha();
        Palette {
            colors: raw
                .chunks_exact(3)
                .enumerate()
                .map(|(i, c)| {
                    let a = alpha.and_then(|a| a.get(i).copied()).unwrap_or(255);
                    [c[0], c[1], c[2], a]
                })
                .collect(),
        }
    });
    let palette =
        match (&side_channel, &opts.palette) {
            (Some(p), _) => p,
            (None, Some(p)) => p,
            (None, None) => return Err(Error::invalid(
                "pixfmt: Pal8 → RGB requires a frame-attached palette or ConvertOptions.palette",
            )),
        };
    let w = src_info.width as usize;
    let h = src_info.height as usize;
    let in_plane = &src.planes[0];
    if alpha {
        let mut out = vec![0u8; w * h * 4];
        for row in 0..h {
            let sr = tight_row(&in_plane.data, in_plane.stride, row, w);
            pal8::expand_row_to_rgba(sr, &mut out[row * w * 4..row * w * 4 + w * 4], palette, w);
        }
        Ok(make_frame(
            src,
            vec![VideoPlane {
                stride: w * 4,
                data: out,
            }],
        ))
    } else {
        let mut out = vec![0u8; w * h * 3];
        for row in 0..h {
            let sr = tight_row(&in_plane.data, in_plane.stride, row, w);
            pal8::expand_row_to_rgb24(sr, &mut out[row * w * 3..row * w * 3 + w * 3], palette, w);
        }
        Ok(make_frame(
            src,
            vec![VideoPlane {
                stride: w * 3,
                data: out,
            }],
        ))
    }
}

/// Packed RGB(A) → `Pal8`. Quantises against `ConvertOptions::palette`
/// (required) and **attaches the colour table to the output frame** as
/// the palette side-channel (`VideoFrame::set_palette`, packed 3-byte
/// RGB entries), so the produced `Pal8` frame is self-describing: a
/// later `Pal8 → RGB` expansion needs no options bundle.
fn rgb_to_pal8(
    src: &VideoFrame,
    src_info: FrameInfo,
    opts: &ConvertOptions,
    alpha_in: bool,
) -> Result<VideoFrame> {
    let palette = opts
        .palette
        .as_ref()
        .ok_or_else(|| Error::invalid("pixfmt: RGB → Pal8 requires ConvertOptions.palette"))?;
    let w = src_info.width as usize;
    let h = src_info.height as usize;
    let in_plane = &src.planes[0];
    let mut out = vec![0u8; w * h];
    if alpha_in {
        let tight = gather_tight(&in_plane.data, in_plane.stride, w * 4, h)?;
        pal8::quantise_rgba_to_pal8(&tight, &mut out, w, h, palette, opts.dither);
    } else {
        let tight = gather_tight(&in_plane.data, in_plane.stride, w * 3, h)?;
        pal8::quantise_rgb24_to_pal8(&tight, &mut out, w, h, palette, opts.dither);
    }
    // Attach the table that was actually used so the frame carries its
    // own colour meaning (side-channel format: 3-byte RGB per entry),
    // plus the palette-alpha record when any entry is not opaque
    // (one byte per entry up to the last non-opaque one; uncovered
    // entries read as opaque), so a later `Pal8 → Rgba` expansion
    // reproduces the Palette's alpha column without the options bundle.
    let side_channel: Vec<u8> = palette
        .colors
        .iter()
        .flat_map(|c| [c[0], c[1], c[2]])
        .collect();
    let mut alpha: Vec<u8> = palette.colors.iter().map(|c| c[3]).collect();
    while alpha.last() == Some(&255) {
        alpha.pop();
    }
    let frame = make_frame(
        src,
        vec![VideoPlane {
            stride: w,
            data: out,
        }],
    )
    .with_palette(side_channel);
    Ok(if alpha.is_empty() {
        frame
    } else {
        frame.with_palette_alpha(alpha)
    })
}

// -------------------------------------------------------------------------
// CMYK.

// -------------------------------------------------------------------------
// Yuva420P / Yuva422P / Yuva444P — planar YUV with an additional
// full-resolution alpha plane (plane 3 is `w × h` regardless of the
// chroma grid). The YUV planes (Y, U, V) are byte-identical to the
// alpha-less sibling, so every conversion path here borrows the
// existing planar encoder/decoder for the format's chroma grid and only
// differs in how the trailing alpha plane is created, dropped, or
// carried through.

/// Alpha-less planar YUV → the `Yuva*` sibling: copy Y / U / V verbatim
/// and append a full `w × h` plane of `0xFF` (opaque) alpha.
/// Tight-strided output.
fn do_yuv_to_yuva(
    src: &VideoFrame,
    src_info: FrameInfo,
    wsub: usize,
    hsub: usize,
) -> Result<VideoFrame> {
    if src.planes.len() < 3 {
        return Err(Error::invalid(
            "pixfmt: planar YUV source needs 3 planes (Y, U, V)",
        ));
    }
    let w = src_info.width as usize;
    let h = src_info.height as usize;
    let (cw, ch) = chroma_dims(w, h, wsub, hsub);
    let yp = gather_tight(&src.planes[0].data, src.planes[0].stride, w, h)?;
    let up = gather_tight(&src.planes[1].data, src.planes[1].stride, cw, ch)?;
    let vp = gather_tight(&src.planes[2].data, src.planes[2].stride, cw, ch)?;
    let ap = vec![0xFFu8; w * h];
    Ok(make_frame(
        src,
        vec![
            VideoPlane {
                stride: w,
                data: yp,
            },
            VideoPlane {
                stride: cw,
                data: up,
            },
            VideoPlane {
                stride: cw,
                data: vp,
            },
            VideoPlane {
                stride: w,
                data: ap,
            },
        ],
    ))
}

/// `Yuva*` → the alpha-less planar sibling: copy the leading three
/// planes; drop alpha.
fn do_yuva_to_yuv(
    src: &VideoFrame,
    src_info: FrameInfo,
    wsub: usize,
    hsub: usize,
) -> Result<VideoFrame> {
    if src.planes.len() < 4 {
        return Err(Error::invalid(
            "pixfmt: Yuva source needs 4 planes (Y, U, V, A)",
        ));
    }
    let w = src_info.width as usize;
    let h = src_info.height as usize;
    let (cw, ch) = chroma_dims(w, h, wsub, hsub);
    let yp = gather_tight(&src.planes[0].data, src.planes[0].stride, w, h)?;
    let up = gather_tight(&src.planes[1].data, src.planes[1].stride, cw, ch)?;
    let vp = gather_tight(&src.planes[2].data, src.planes[2].stride, cw, ch)?;
    Ok(make_frame(
        src,
        vec![
            VideoPlane {
                stride: w,
                data: yp,
            },
            VideoPlane {
                stride: cw,
                data: up,
            },
            VideoPlane {
                stride: cw,
                data: vp,
            },
        ],
    ))
}

/// `Yuva*` → `Rgb24` / `Rgba`: decode the YUV part through the existing
/// planar scalar/SIMD path for the format's chroma grid, then either
/// drop the source's alpha plane (`alpha = false`, output `Rgb24`) or
/// interleave it into the destination's fourth byte (`alpha = true`,
/// output `Rgba`).
fn do_yuva_to_rgb(
    src: &VideoFrame,
    src_info: FrameInfo,
    matrix: YuvMatrix,
    wsub: usize,
    hsub: usize,
    alpha: bool,
    workers: usize,
) -> Result<VideoFrame> {
    let w = src_info.width as usize;
    let h = src_info.height as usize;
    let (yp, up, vp, ap) = planar8_source(src, w, h, wsub, hsub, true)?;
    let bpp = if alpha { 4 } else { 3 };
    let out = planar8::decode(
        &Planar8 {
            y: &yp,
            u: &up,
            v: &vp,
            a: ap.as_deref(),
            w,
            h,
            wsub,
            hsub,
        },
        bpp,
        matrix,
        workers,
    );
    Ok(make_frame(
        src,
        vec![VideoPlane {
            stride: w * bpp,
            data: out,
        }],
    ))
}

/// `Rgb24` / `Rgba` → `Yuva*`: encode planar YUV through the existing
/// path for the destination's chroma grid, then either synthesise an
/// opaque alpha plane (`alpha_in = false`, source is `Rgb24`) or split
/// the source's alpha out into the trailing plane (`alpha_in = true`,
/// source is `Rgba`).
fn do_rgb_to_yuva(
    src: &VideoFrame,
    src_info: FrameInfo,
    matrix: YuvMatrix,
    wsub: usize,
    hsub: usize,
    alpha_in: bool,
    workers: usize,
) -> Result<VideoFrame> {
    let w = src_info.width as usize;
    let h = src_info.height as usize;
    let packed = packed8_source(src, w, h, if alpha_in { 4 } else { 3 })?;
    let enc = planar8::encode(&packed, wsub, hsub, matrix, true, workers);
    // `Rgb24` sources have no alpha: synthesise opaque.
    let ap = enc.a.unwrap_or_else(|| vec![0xFFu8; w * h]);
    Ok(make_frame(
        src,
        vec![
            VideoPlane {
                stride: w,
                data: enc.y,
            },
            VideoPlane {
                stride: enc.cw,
                data: enc.u,
            },
            VideoPlane {
                stride: enc.cw,
                data: enc.v,
            },
            VideoPlane {
                stride: w,
                data: ap,
            },
        ],
    ))
}

// -------------------------------------------------------------------------
// Planar GBR(A) ↔ packed deep RGB.
//
// GBR(A) carries RGB as separate planes in G, B, R(, A) order (the plane
// ordering documented on the oxideav-core `Gbrp*Le` / `Gbrap*Le`
// variants). Each sample is a 16-bit little-endian word with only the
// low `bits` (10 / 12 / 14) significant; the high bits are zero. The
// packed `Rgb48Le` / `Rgba64Le` targets store R, G, B(, A) as
// consecutive 16-bit little-endian words using the full 16-bit range.
//
// The conversion is therefore a pure plane reorder + a bit-significance
// rescale: shift each `bits`-significant sample left by `16 - bits` on
// the way to the 16-bit packed word, and right by `16 - bits` on the way
// back. This is bit-layout normalisation only — there is no colour
// matrix and no `ColorSpace` knob applies.

/// Read a little-endian 16-bit word at byte offset `off`.
#[inline]
fn rd16le(buf: &[u8], off: usize) -> u16 {
    (buf[off] as u16) | ((buf[off + 1] as u16) << 8)
}

/// Write `v` as a little-endian 16-bit word at byte offset `off`.
#[inline]
fn wr16le(buf: &mut [u8], off: usize, v: u16) {
    buf[off] = (v & 0xFF) as u8;
    buf[off + 1] = (v >> 8) as u8;
}

/// Planar GBR(A) → packed `Rgb48Le` / `Rgba64Le`, one row band at a
/// time (see [`planar8::map_packed_banded`]).
fn do_gbr_to_packed_deep(
    src: &VideoFrame,
    src_info: FrameInfo,
    bits: u8,
    alpha_in: bool,
    alpha_out: bool,
    workers: usize,
) -> Result<VideoFrame> {
    let need = if alpha_in { 4 } else { 3 };
    if src.planes.len() < need {
        return Err(Error::invalid(
            "pixfmt: GBR(A) source needs G, B, R(, A) planes",
        ));
    }
    let w = src_info.width as usize;
    let h = src_info.height as usize;
    // Ladder widen to the 16-bit container: MSB replication (peak maps
    // to peak), the exact inverse of the truncation on the way back.
    let bits = bits as u32;
    let shift = 16 - bits;
    let mask = ((1u32 << bits) - 1) as u16;
    let widen = |v: u16| -> u16 {
        let v = v & mask;
        if shift == 0 {
            v
        } else {
            (v << shift) | (v >> (bits - shift))
        }
    };
    // GBR plane order: G=0, B=1, R=2, A=3. Each plane is `w` 16-bit words
    // per row (2 bytes each).
    let g = tight_plane(&src.planes[0], w * 2, h)?;
    let b = tight_plane(&src.planes[1], w * 2, h)?;
    let r = tight_plane(&src.planes[2], w * 2, h)?;
    // The alpha plane is only consulted when the packed target carries
    // it; a surplus source alpha is dropped.
    let a = if alpha_in && alpha_out {
        Some(tight_plane(&src.planes[3], w * 2, h)?)
    } else {
        None
    };
    let comps = if alpha_out { 4 } else { 3 };
    let out = planar8::map_packed_banded(&r, w * 2, w * comps * 2, h, workers, |rb, d| {
        let n = d.len() / (comps * 2);
        // The band's byte offset inside the planes (same for G, B, A).
        let off = rb.as_ptr() as usize - r.as_ptr() as usize;
        let gb = &g[off..off + n * 2];
        let bb = &b[off..off + n * 2];
        let ab = a.as_deref().map(|a| &a[off..off + n * 2]);
        for (i, px) in d.chunks_exact_mut(comps * 2).enumerate() {
            wr16le(px, 0, widen(rd16le(rb, i * 2)));
            wr16le(px, 2, widen(rd16le(gb, i * 2)));
            wr16le(px, 4, widen(rd16le(bb, i * 2)));
            if alpha_out {
                // Carry the source alpha (widened like the colour words)
                // or synthesise the packed format's opaque full-scale.
                let av = match ab {
                    Some(a) => widen(rd16le(a, i * 2)),
                    None => 0xFFFF,
                };
                wr16le(px, 6, av);
            }
        }
    });
    Ok(make_frame(
        src,
        vec![VideoPlane {
            stride: w * comps * 2,
            data: out,
        }],
    ))
}

/// Planar GBR(A) → 8-bit packed `Rgb24` / `Rgba`: reorder the G, B, R(, A)
/// planes into packed byte order while keeping the top 8 of each sample's
/// `bits` significant bits (truncation, consistent with the depth ladder).
fn do_gbr_to_packed8(
    src: &VideoFrame,
    src_info: FrameInfo,
    bits: u32,
    alpha: bool,
) -> Result<VideoFrame> {
    let need = if alpha { 4 } else { 3 };
    if src.planes.len() < need {
        return Err(Error::invalid(
            "pixfmt: GBR(A) source needs G, B, R(, A) planes",
        ));
    }
    let w = src_info.width as usize;
    let h = src_info.height as usize;
    let shift = bits - 8;
    let mask: u16 = ((1u32 << bits) - 1) as u16;
    let g = gather_tight(&src.planes[0].data, src.planes[0].stride, w * 2, h)?;
    let b = gather_tight(&src.planes[1].data, src.planes[1].stride, w * 2, h)?;
    let r = gather_tight(&src.planes[2].data, src.planes[2].stride, w * 2, h)?;
    let a = if alpha {
        Some(gather_tight(
            &src.planes[3].data,
            src.planes[3].stride,
            w * 2,
            h,
        )?)
    } else {
        None
    };
    let comps = if alpha { 4 } else { 3 };
    let mut out = vec![0u8; w * h * comps];
    for i in 0..w * h {
        let base = i * comps;
        out[base] = ((rd16le(&r, i * 2) & mask) >> shift) as u8;
        out[base + 1] = ((rd16le(&g, i * 2) & mask) >> shift) as u8;
        out[base + 2] = ((rd16le(&b, i * 2) & mask) >> shift) as u8;
        if let Some(a) = &a {
            out[base + 3] = ((rd16le(a, i * 2) & mask) >> shift) as u8;
        }
    }
    Ok(make_frame(
        src,
        vec![VideoPlane {
            stride: w * comps,
            data: out,
        }],
    ))
}

/// 8-bit packed `Rgb24` / `Rgba` → planar GBR(A): split into planes and
/// widen each byte to `bits` significant bits with MSB replication (the
/// exact inverse of [`do_gbr_to_packed8`]).
fn do_packed8_to_gbr(
    src: &VideoFrame,
    src_info: FrameInfo,
    bits: u32,
    alpha: bool,
) -> Result<VideoFrame> {
    let w = src_info.width as usize;
    let h = src_info.height as usize;
    let shift = bits - 8;
    let comps = if alpha { 4 } else { 3 };
    let in_plane = &src.planes[0];
    let packed = gather_tight(&in_plane.data, in_plane.stride, w * comps, h)?;
    let widen = |v: u8| -> u16 {
        let v = v as u32;
        (((v << shift) | (v >> (8 - shift))) & ((1u32 << bits) - 1)) as u16
    };
    let mut g = vec![0u8; w * h * 2];
    let mut b = vec![0u8; w * h * 2];
    let mut r = vec![0u8; w * h * 2];
    let mut a = if alpha {
        vec![0u8; w * h * 2]
    } else {
        Vec::new()
    };
    for i in 0..w * h {
        let base = i * comps;
        wr16le(&mut r, i * 2, widen(packed[base]));
        wr16le(&mut g, i * 2, widen(packed[base + 1]));
        wr16le(&mut b, i * 2, widen(packed[base + 2]));
        if alpha {
            wr16le(&mut a, i * 2, widen(packed[base + 3]));
        }
    }
    let mut planes = vec![
        VideoPlane {
            stride: w * 2,
            data: g,
        },
        VideoPlane {
            stride: w * 2,
            data: b,
        },
        VideoPlane {
            stride: w * 2,
            data: r,
        },
    ];
    if alpha {
        planes.push(VideoPlane {
            stride: w * 2,
            data: a,
        });
    }
    Ok(make_frame(src, planes))
}

/// Byte-tier planar GBR(A) (`Gbrp8` / `Gbrap8`) → packed `Rgb24` /
/// `Rgba`: a pure plane reorder — the G, B, R(, A) byte planes
/// interleave into packed R, G, B(, A) order with no depth math, so the
/// conversion is bit-exact and (for matched alpha flags) self-inverse
/// with [`do_packed8_to_gbr8`]. A missing alpha is synthesised opaque
/// 255; a surplus source alpha plane is dropped.
fn do_gbr8_to_packed8(
    src: &VideoFrame,
    src_info: FrameInfo,
    alpha_in: bool,
    alpha_out: bool,
) -> Result<VideoFrame> {
    let need = if alpha_in { 4 } else { 3 };
    if src.planes.len() < need {
        return Err(Error::invalid(
            "pixfmt: GBR(A) source needs G, B, R(, A) planes",
        ));
    }
    let w = src_info.width as usize;
    let h = src_info.height as usize;
    let g = gather_tight(&src.planes[0].data, src.planes[0].stride, w, h)?;
    let b = gather_tight(&src.planes[1].data, src.planes[1].stride, w, h)?;
    let r = gather_tight(&src.planes[2].data, src.planes[2].stride, w, h)?;
    let a = if alpha_in && alpha_out {
        Some(gather_tight(
            &src.planes[3].data,
            src.planes[3].stride,
            w,
            h,
        )?)
    } else {
        None
    };
    let comps = if alpha_out { 4 } else { 3 };
    let mut out = vec![0u8; w * h * comps];
    for i in 0..w * h {
        let base = i * comps;
        out[base] = r[i];
        out[base + 1] = g[i];
        out[base + 2] = b[i];
        if alpha_out {
            out[base + 3] = a.as_ref().map_or(255, |a| a[i]);
        }
    }
    Ok(make_frame(
        src,
        vec![VideoPlane {
            stride: w * comps,
            data: out,
        }],
    ))
}

/// Packed `Rgb24` / `Rgba` → byte-tier planar GBR(A): the inverse plane
/// split of [`do_gbr8_to_packed8`] — zero-math, bit-exact, same alpha
/// synthesis / drop convention.
fn do_packed8_to_gbr8(
    src: &VideoFrame,
    src_info: FrameInfo,
    alpha_in: bool,
    alpha_out: bool,
) -> Result<VideoFrame> {
    let w = src_info.width as usize;
    let h = src_info.height as usize;
    let comps = if alpha_in { 4 } else { 3 };
    let in_plane = &src.planes[0];
    let packed = gather_tight(&in_plane.data, in_plane.stride, w * comps, h)?;
    let mut g = vec![0u8; w * h];
    let mut b = vec![0u8; w * h];
    let mut r = vec![0u8; w * h];
    let mut a = if alpha_out {
        opaque_plane(w * h, 8)
    } else {
        Vec::new()
    };
    for i in 0..w * h {
        let base = i * comps;
        r[i] = packed[base];
        g[i] = packed[base + 1];
        b[i] = packed[base + 2];
        if alpha_in && alpha_out {
            a[i] = packed[base + 3];
        }
    }
    let mut planes = vec![
        VideoPlane { stride: w, data: g },
        VideoPlane { stride: w, data: b },
        VideoPlane { stride: w, data: r },
    ];
    if alpha_out {
        planes.push(VideoPlane { stride: w, data: a });
    }
    Ok(make_frame(src, planes))
}

/// `Gbrp8` ↔ `Gbrap8` alpha append / drop: the G, B, R byte planes are
/// copied verbatim; `add` appends an opaque 255 full-resolution alpha
/// plane, `!add` drops plane 3.
fn do_gbr8_alpha(src: &VideoFrame, src_info: FrameInfo, add: bool) -> Result<VideoFrame> {
    let need = if add { 3 } else { 4 };
    if src.planes.len() < need {
        return Err(Error::invalid(
            "pixfmt: GBR(A) source needs G, B, R(, A) planes",
        ));
    }
    let w = src_info.width as usize;
    let h = src_info.height as usize;
    let mut planes: Vec<VideoPlane> = src.planes[..3]
        .iter()
        .map(|p| {
            Ok(VideoPlane {
                stride: w,
                data: gather_tight(&p.data, p.stride, w, h)?,
            })
        })
        .collect::<Result<_>>()?;
    if add {
        planes.push(VideoPlane {
            stride: w,
            data: opaque_plane(w * h, 8),
        });
    }
    Ok(make_frame(src, planes))
}

/// Byte-tier planar GBR(A) (`Gbrp8` / `Gbrap8`) → packed deep RGB
/// (`Rgb48Le` / `Rgba64Le`): plane reorder plus the exact ×257 widen
/// (the 8 → 16 MSB replication — zero maps to zero, 255 to 65535), the
/// same rule as `Rgb24 → Rgb48Le`. A carried alpha plane is widened
/// like the colour bytes; a missing one is synthesised opaque 65535
/// and a surplus one is dropped.
fn do_gbr8_to_packed_deep(
    src: &VideoFrame,
    src_info: FrameInfo,
    alpha_in: bool,
    alpha_out: bool,
) -> Result<VideoFrame> {
    let need = if alpha_in { 4 } else { 3 };
    if src.planes.len() < need {
        return Err(Error::invalid(
            "pixfmt: GBR(A) source needs G, B, R(, A) planes",
        ));
    }
    let w = src_info.width as usize;
    let h = src_info.height as usize;
    let g = gather_tight(&src.planes[0].data, src.planes[0].stride, w, h)?;
    let b = gather_tight(&src.planes[1].data, src.planes[1].stride, w, h)?;
    let r = gather_tight(&src.planes[2].data, src.planes[2].stride, w, h)?;
    let a = if alpha_in && alpha_out {
        Some(gather_tight(
            &src.planes[3].data,
            src.planes[3].stride,
            w,
            h,
        )?)
    } else {
        None
    };
    let comps = if alpha_out { 4 } else { 3 };
    let mut out = vec![0u8; w * h * comps * 2];
    for i in 0..w * h {
        let base = i * comps * 2;
        wr16le(&mut out, base, r[i] as u16 * 257);
        wr16le(&mut out, base + 2, g[i] as u16 * 257);
        wr16le(&mut out, base + 4, b[i] as u16 * 257);
        if alpha_out {
            let av = a.as_ref().map_or(0xFFFF, |a| a[i] as u16 * 257);
            wr16le(&mut out, base + 6, av);
        }
    }
    Ok(make_frame(
        src,
        vec![VideoPlane {
            stride: w * comps * 2,
            data: out,
        }],
    ))
}

/// Packed deep RGB (`Rgb48Le` / `Rgba64Le`) → byte-tier planar GBR(A):
/// plane split keeping the top byte of each 16-bit word (truncation —
/// the exact inverse of the ×257 widen, so 8-bit content round-trips
/// losslessly). Alpha is carried truncated, synthesised opaque 255, or
/// dropped per the flag pair.
fn do_packed_deep_to_gbr8(
    src: &VideoFrame,
    src_info: FrameInfo,
    alpha_in: bool,
    alpha_out: bool,
) -> Result<VideoFrame> {
    let w = src_info.width as usize;
    let h = src_info.height as usize;
    let comps = if alpha_in { 4 } else { 3 };
    let in_plane = &src.planes[0];
    let packed = gather_tight(&in_plane.data, in_plane.stride, w * comps * 2, h)?;
    let mut g = vec![0u8; w * h];
    let mut b = vec![0u8; w * h];
    let mut r = vec![0u8; w * h];
    let mut a = if alpha_out {
        opaque_plane(w * h, 8)
    } else {
        Vec::new()
    };
    for i in 0..w * h {
        let base = i * comps * 2;
        r[i] = (rd16le(&packed, base) >> 8) as u8;
        g[i] = (rd16le(&packed, base + 2) >> 8) as u8;
        b[i] = (rd16le(&packed, base + 4) >> 8) as u8;
        if alpha_in && alpha_out {
            a[i] = (rd16le(&packed, base + 6) >> 8) as u8;
        }
    }
    let mut planes = vec![
        VideoPlane { stride: w, data: g },
        VideoPlane { stride: w, data: b },
        VideoPlane { stride: w, data: r },
    ];
    if alpha_out {
        planes.push(VideoPlane { stride: w, data: a });
    }
    Ok(make_frame(src, planes))
}

/// Planar GBR(A) → `Gray8`: narrow each colour plane to 8 bits (top
/// bits — the crate depth policy) and run the full-range luminance
/// projection under the Y' row of the selected primaries, exactly like
/// the packed `RgbToGray` rows. Alpha (when present) is dropped.
fn do_gbr_to_gray(
    src: &VideoFrame,
    src_info: FrameInfo,
    matrix: YuvMatrix,
    bits: u32,
    alpha_in: bool,
) -> Result<VideoFrame> {
    let need = if alpha_in { 4 } else { 3 };
    if src.planes.len() < need {
        return Err(Error::invalid(
            "pixfmt: GBR(A) source needs G, B, R(, A) planes",
        ));
    }
    let w = src_info.width as usize;
    let h = src_info.height as usize;
    let sb = if bits > 8 { 2 } else { 1 };
    let g = gather_tight(&src.planes[0].data, src.planes[0].stride, w * sb, h)?;
    let b = gather_tight(&src.planes[1].data, src.planes[1].stride, w * sb, h)?;
    let r = gather_tight(&src.planes[2].data, src.planes[2].stride, w * sb, h)?;
    // Interleave the top 8 bits of each sample into an R, G, B byte
    // triple and reuse the proven packed projection kernel.
    let mut rgb24 = vec![0u8; w * h * 3];
    if bits > 8 {
        let mask: u16 = (((1u32 << bits) - 1) & 0xFFFF) as u16;
        let shift = bits - 8;
        for i in 0..w * h {
            rgb24[i * 3] = ((rd16le(&r, i * 2) & mask) >> shift) as u8;
            rgb24[i * 3 + 1] = ((rd16le(&g, i * 2) & mask) >> shift) as u8;
            rgb24[i * 3 + 2] = ((rd16le(&b, i * 2) & mask) >> shift) as u8;
        }
    } else {
        for i in 0..w * h {
            rgb24[i * 3] = r[i];
            rgb24[i * 3 + 1] = g[i];
            rgb24[i * 3 + 2] = b[i];
        }
    }
    let mut gray = vec![0u8; w * h];
    yuv::rgb24_to_gray8(&rgb24, &mut gray, w * h, matrix);
    Ok(make_frame(
        src,
        vec![VideoPlane {
            stride: w,
            data: gray,
        }],
    ))
}

/// `Gray8` → planar GBR(A): broadcast the gray byte into the G, B and R
/// planes at the family depth (MSB-replicated widen — peak maps to
/// peak, and [`do_gbr_to_gray`] recovers the original exactly because
/// the projection of `r = g = b = v` is `v`). `alpha_out` appends an
/// opaque full-scale alpha plane.
fn do_gray_to_gbr(
    src: &VideoFrame,
    src_info: FrameInfo,
    bits: u32,
    alpha_out: bool,
) -> Result<VideoFrame> {
    let w = src_info.width as usize;
    let h = src_info.height as usize;
    let gray = gather_tight(&src.planes[0].data, src.planes[0].stride, w, h)?;
    let plane = if bits > 8 {
        let shift = bits - 8;
        let mask = (1u32 << bits) - 1;
        let mut out = vec![0u8; w * h * 2];
        for (i, &v) in gray.iter().enumerate() {
            let v = v as u32;
            wr16le(
                &mut out,
                i * 2,
                (((v << shift) | (v >> (8 - shift))) & mask) as u16,
            );
        }
        out
    } else {
        gray
    };
    let sb = if bits > 8 { 2 } else { 1 };
    let mut planes = vec![
        VideoPlane {
            stride: w * sb,
            data: plane.clone(),
        },
        VideoPlane {
            stride: w * sb,
            data: plane.clone(),
        },
        VideoPlane {
            stride: w * sb,
            data: plane,
        },
    ];
    if alpha_out {
        planes.push(VideoPlane {
            stride: w * sb,
            data: opaque_plane(w * h, bits),
        });
    }
    Ok(make_frame(src, planes))
}

/// One [`do_packed_deep_to_gbr`] band: `(first row, G, B, R, A)`.
type GbrBand<'a> = (
    usize,
    &'a mut [u8],
    &'a mut [u8],
    &'a mut [u8],
    Option<&'a mut [u8]>,
);

/// Packed `Rgb48Le` / `Rgba64Le` → planar GBR(A), one row band at a
/// time: each band owns a disjoint row range of every output plane.
fn do_packed_deep_to_gbr(
    src: &VideoFrame,
    src_info: FrameInfo,
    bits: u8,
    alpha_in: bool,
    alpha_out: bool,
    workers: usize,
) -> Result<VideoFrame> {
    if src.planes.is_empty() {
        return Err(Error::invalid("pixfmt: packed RGB source needs a plane"));
    }
    let w = src_info.width as usize;
    let h = src_info.height as usize;
    let shift = 16 - bits as u32;
    let comps = if alpha_in { 4 } else { 3 };
    let packed = tight_plane(&src.planes[0], w * comps * 2, h)?;
    let mut g = vec![0u8; w * h * 2];
    let mut b = vec![0u8; w * h * 2];
    let mut r = vec![0u8; w * h * 2];
    let mut a = alpha_out.then(|| vec![0u8; w * h * 2]);
    // Synthesised opaque alpha at the planar depth (used when the
    // packed source has no alpha word to carry).
    let opaque = ((1u32 << bits) - 1) as u16;
    if w > 0 && h > 0 {
        let bands = planar8::row_bands(h, 1, workers);
        let mut jobs: Vec<GbrBand<'_>> = Vec::with_capacity(bands.len());
        let (mut gr, mut br, mut rr): (&mut [u8], &mut [u8], &mut [u8]) = (&mut g, &mut b, &mut r);
        let mut ar: Option<&mut [u8]> = a.as_deref_mut();
        for &(r0, r1) in &bands {
            let n = (r1 - r0) * w * 2;
            let (gb, gt) = gr.split_at_mut(n);
            gr = gt;
            let (bb, bt) = br.split_at_mut(n);
            br = bt;
            let (rb, rt) = rr.split_at_mut(n);
            rr = rt;
            let ab = ar.take().map(|rest| {
                let (band, tail) = rest.split_at_mut(n);
                ar = Some(tail);
                band
            });
            jobs.push((r0, gb, bb, rb, ab));
        }
        let row_bytes = w * comps * 2;
        planar8::run_bands(jobs, |(r0, gb, bb, rb, ab): GbrBand<'_>| {
            let n = gb.len() / 2;
            let band = &packed[r0 * row_bytes..r0 * row_bytes + n * comps * 2];
            let mut ab = ab;
            for (i, px) in band.chunks_exact(comps * 2).enumerate() {
                wr16le(rb, i * 2, rd16le(px, 0) >> shift);
                wr16le(gb, i * 2, rd16le(px, 2) >> shift);
                wr16le(bb, i * 2, rd16le(px, 4) >> shift);
                if let Some(a) = ab.as_deref_mut() {
                    let av = if alpha_in {
                        rd16le(px, 6) >> shift
                    } else {
                        opaque
                    };
                    wr16le(a, i * 2, av);
                }
            }
        });
    }
    let mut planes = vec![
        VideoPlane {
            stride: w * 2,
            data: g,
        },
        VideoPlane {
            stride: w * 2,
            data: b,
        },
        VideoPlane {
            stride: w * 2,
            data: r,
        },
    ];
    if let Some(a) = a {
        planes.push(VideoPlane {
            stride: w * 2,
            data: a,
        });
    }
    Ok(make_frame(src, planes))
}

// -------------------------------------------------------------------------
// Scene-referred float family (computed tier; see `FloatLayout`).

/// Canonical float intermediate: `w × h` pixels of straight R, G, B, A
/// (`A = 1.0` when the source carries none; gray sources broadcast).
struct FloatPixels {
    w: usize,
    h: usize,
    rgba: Vec<f32>,
}

/// Gather a float-family source frame into the canonical intermediate.
fn gather_float(src: &VideoFrame, src_info: FrameInfo, s: FloatLayout) -> Result<FloatPixels> {
    let w = src_info.width as usize;
    let h = src_info.height as usize;
    if src.planes.len() < s.plane_count() {
        return Err(Error::invalid("pixfmt: float source is missing planes"));
    }
    let n = w * h;
    let mut rgba = vec![1.0f32; n * 4];
    if s.is_planar() {
        let g = gather_tight(&src.planes[0].data, src.planes[0].stride, w * 4, h)?;
        let b = gather_tight(&src.planes[1].data, src.planes[1].stride, w * 4, h)?;
        let r = gather_tight(&src.planes[2].data, src.planes[2].stride, w * 4, h)?;
        let a = if s.has_alpha() {
            Some(gather_tight(
                &src.planes[3].data,
                src.planes[3].stride,
                w * 4,
                h,
            )?)
        } else {
            None
        };
        for i in 0..n {
            rgba[i * 4] = float::read_f32le(&r, i);
            rgba[i * 4 + 1] = float::read_f32le(&g, i);
            rgba[i * 4 + 2] = float::read_f32le(&b, i);
            if let Some(a) = &a {
                rgba[i * 4 + 3] = float::read_f32le(a, i);
            }
        }
    } else {
        let words = s.packed_words();
        let packed = gather_tight(&src.planes[0].data, src.planes[0].stride, w * words * 4, h)?;
        for i in 0..n {
            match s {
                FloatLayout::Gray => {
                    let v = float::read_f32le(&packed, i);
                    rgba[i * 4] = v;
                    rgba[i * 4 + 1] = v;
                    rgba[i * 4 + 2] = v;
                }
                _ => {
                    for c in 0..words {
                        rgba[i * 4 + c] = float::read_f32le(&packed, i * words + c);
                    }
                }
            }
        }
    }
    Ok(FloatPixels { w, h, rgba })
}

/// Gather an integer gray / packed RGB(A) / planar GBR(A) source into
/// the canonical float intermediate (exact normalisation).
fn gather_int(src: &VideoFrame, src_info: FrameInfo, s: IntLayout) -> Result<FloatPixels> {
    let w = src_info.width as usize;
    let h = src_info.height as usize;
    if src.planes.len() < s.plane_count() {
        return Err(Error::invalid("pixfmt: integer source is missing planes"));
    }
    let n = w * h;
    let sb = s.sample_bytes();
    let bits = s.bits;
    let mask = ((1u32 << bits) - 1) as u16;
    let read = |buf: &[u8], i: usize| -> f32 {
        let code = if sb == 2 {
            (u16::from_le_bytes([buf[i * 2], buf[i * 2 + 1]]) & mask) as u32
        } else {
            buf[i] as u32
        };
        float::unorm_to_f32(code, bits)
    };
    let mut rgba = vec![1.0f32; n * 4];
    match s.shape {
        IntShape::PlanarGbr => {
            let g = gather_tight(&src.planes[0].data, src.planes[0].stride, w * sb, h)?;
            let b = gather_tight(&src.planes[1].data, src.planes[1].stride, w * sb, h)?;
            let r = gather_tight(&src.planes[2].data, src.planes[2].stride, w * sb, h)?;
            let a = if s.alpha {
                Some(gather_tight(
                    &src.planes[3].data,
                    src.planes[3].stride,
                    w * sb,
                    h,
                )?)
            } else {
                None
            };
            for i in 0..n {
                rgba[i * 4] = read(&r, i);
                rgba[i * 4 + 1] = read(&g, i);
                rgba[i * 4 + 2] = read(&b, i);
                if let Some(a) = &a {
                    rgba[i * 4 + 3] = read(a, i);
                }
            }
        }
        IntShape::Gray => {
            let packed = gather_tight(&src.planes[0].data, src.planes[0].stride, w * sb, h)?;
            for i in 0..n {
                let v = read(&packed, i);
                rgba[i * 4] = v;
                rgba[i * 4 + 1] = v;
                rgba[i * 4 + 2] = v;
            }
        }
        IntShape::PackedRgb => {
            let comps = s.comps();
            let packed =
                gather_tight(&src.planes[0].data, src.planes[0].stride, w * comps * sb, h)?;
            for i in 0..n {
                for c in 0..comps {
                    rgba[i * 4 + c] = read(&packed, i * comps + c);
                }
            }
        }
    }
    Ok(FloatPixels { w, h, rgba })
}

/// Emit the canonical intermediate as a float-family frame.
fn emit_float(src: &VideoFrame, px: &FloatPixels, d: FloatLayout, matrix: YuvMatrix) -> VideoFrame {
    let (w, h) = (px.w, px.h);
    let n = w * h;
    let planes = if d.is_planar() {
        let mut g = vec![0u8; n * 4];
        let mut b = vec![0u8; n * 4];
        let mut r = vec![0u8; n * 4];
        let mut a = if d.has_alpha() {
            Some(vec![0u8; n * 4])
        } else {
            None
        };
        for i in 0..n {
            let p = &px.rgba[i * 4..i * 4 + 4];
            float::write_f32le(&mut r, i, p[0]);
            float::write_f32le(&mut g, i, p[1]);
            float::write_f32le(&mut b, i, p[2]);
            if let Some(a) = a.as_mut() {
                float::write_f32le(a, i, p[3]);
            }
        }
        let mut planes = vec![
            VideoPlane {
                stride: w * 4,
                data: g,
            },
            VideoPlane {
                stride: w * 4,
                data: b,
            },
            VideoPlane {
                stride: w * 4,
                data: r,
            },
        ];
        if let Some(a) = a {
            planes.push(VideoPlane {
                stride: w * 4,
                data: a,
            });
        }
        planes
    } else {
        let words = d.packed_words();
        let mut out = vec![0u8; n * words * 4];
        for i in 0..n {
            let p = &px.rgba[i * 4..i * 4 + 4];
            match d {
                FloatLayout::Gray => {
                    let y = float::luminance_linear(p[0], p[1], p[2], matrix);
                    float::write_f32le(&mut out, i, y);
                }
                _ => {
                    for (c, &v) in p.iter().enumerate().take(words) {
                        float::write_f32le(&mut out, i * words + c, v);
                    }
                }
            }
        }
        vec![VideoPlane {
            stride: w * words * 4,
            data: out,
        }]
    };
    make_frame(src, planes)
}

/// Emit the canonical intermediate as an integer gray / packed RGB(A) /
/// planar GBR(A) frame (saturating quantisation; gray targets take the
/// linear-light luminance first; alpha synthesised opaque when the
/// source carried none).
fn emit_int(src: &VideoFrame, px: &FloatPixels, d: IntLayout, matrix: YuvMatrix) -> VideoFrame {
    let (w, h) = (px.w, px.h);
    let n = w * h;
    let sb = d.sample_bytes();
    let bits = d.bits;
    let put = |buf: &mut [u8], i: usize, v: f32| {
        let code = float::f32_to_unorm(v, bits);
        if sb == 2 {
            buf[i * 2..i * 2 + 2].copy_from_slice(&(code as u16).to_le_bytes());
        } else {
            buf[i] = code as u8;
        }
    };
    let planes = match d.shape {
        IntShape::PlanarGbr => {
            let mut g = vec![0u8; n * sb];
            let mut b = vec![0u8; n * sb];
            let mut r = vec![0u8; n * sb];
            let mut a = if d.alpha {
                Some(vec![0u8; n * sb])
            } else {
                None
            };
            for i in 0..n {
                let p = &px.rgba[i * 4..i * 4 + 4];
                put(&mut r, i, p[0]);
                put(&mut g, i, p[1]);
                put(&mut b, i, p[2]);
                if let Some(a) = a.as_mut() {
                    put(a, i, p[3]);
                }
            }
            let mut planes = vec![
                VideoPlane {
                    stride: w * sb,
                    data: g,
                },
                VideoPlane {
                    stride: w * sb,
                    data: b,
                },
                VideoPlane {
                    stride: w * sb,
                    data: r,
                },
            ];
            if let Some(a) = a {
                planes.push(VideoPlane {
                    stride: w * sb,
                    data: a,
                });
            }
            planes
        }
        IntShape::Gray => {
            let mut out = vec![0u8; n * sb];
            for i in 0..n {
                let p = &px.rgba[i * 4..i * 4 + 4];
                put(
                    &mut out,
                    i,
                    float::luminance_linear(p[0], p[1], p[2], matrix),
                );
            }
            vec![VideoPlane {
                stride: w * sb,
                data: out,
            }]
        }
        IntShape::PackedRgb => {
            let comps = d.comps();
            let mut out = vec![0u8; n * comps * sb];
            for i in 0..n {
                let p = &px.rgba[i * 4..i * 4 + 4];
                for (c, &v) in p.iter().enumerate().take(comps) {
                    put(&mut out, i * comps + c, v);
                }
            }
            vec![VideoPlane {
                stride: w * comps * sb,
                data: out,
            }]
        }
    };
    make_frame(src, planes)
}

fn float_to_float(
    src: &VideoFrame,
    src_info: FrameInfo,
    matrix: YuvMatrix,
    s: FloatLayout,
    d: FloatLayout,
) -> Result<VideoFrame> {
    let px = gather_float(src, src_info, s)?;
    Ok(emit_float(src, &px, d, matrix))
}

fn float_to_int(
    src: &VideoFrame,
    src_info: FrameInfo,
    matrix: YuvMatrix,
    s: FloatLayout,
    d: IntLayout,
) -> Result<VideoFrame> {
    let px = gather_float(src, src_info, s)?;
    Ok(emit_int(src, &px, d, matrix))
}

fn int_to_float(
    src: &VideoFrame,
    src_info: FrameInfo,
    matrix: YuvMatrix,
    s: IntLayout,
    d: FloatLayout,
) -> Result<VideoFrame> {
    let px = gather_int(src, src_info, s)?;
    Ok(emit_float(src, &px, d, matrix))
}

/// Float → 16-bit planar YUV(A): quantise to a packed 16-bit RGB(A)
/// intermediate (`Rgba64Le` when the destination carries alpha, else
/// `Rgb48Le`), then the full-precision deep matrix.
fn float_to_deep_yuv(
    src: &VideoFrame,
    src_info: FrameInfo,
    matrix: YuvMatrix,
    s: FloatLayout,
    d: PlanarYuv,
) -> Result<VideoFrame> {
    let px = gather_float(src, src_info, s)?;
    let packed = emit_int(
        src,
        &px,
        IntLayout {
            shape: IntShape::PackedRgb,
            bits: 16,
            alpha: d.alpha,
        },
        matrix,
    );
    let mid = if d.alpha {
        PixelFormat::Rgba64Le
    } else {
        PixelFormat::Rgb48Le
    };
    let mid_info = FrameInfo::new(mid, src_info.width, src_info.height);
    do_rgb48_to_deep_yuv(&packed, mid_info, matrix, d.wsub, d.hsub, d.alpha, 1)
}

/// 16-bit planar YUV(A) → float: the full-precision deep matrix into a
/// packed 16-bit RGB(A) intermediate, then the exact normalisation.
/// Float alpha comes from the source alpha plane when it has one, else
/// `1.0`.
fn deep_yuv_to_float(
    src: &VideoFrame,
    src_info: FrameInfo,
    matrix: YuvMatrix,
    s: PlanarYuv,
    d: FloatLayout,
) -> Result<VideoFrame> {
    let packed = do_deep_yuv_to_rgb48(src, src_info, matrix, s.wsub, s.hsub, s.alpha, 1)?;
    let mid = if s.alpha {
        PixelFormat::Rgba64Le
    } else {
        PixelFormat::Rgb48Le
    };
    let mid_info = FrameInfo::new(mid, src_info.width, src_info.height);
    let px = gather_int(
        &packed,
        mid_info,
        IntLayout {
            shape: IntShape::PackedRgb,
            bits: 16,
            alpha: s.alpha,
        },
    )?;
    Ok(emit_float(src, &px, d, matrix.with_range(false)))
}