oxideav-cli-convert 0.0.8

ImageMagick-style convert engine for the oxideav CLI — translates IM arg syntax into an oxideav-pipeline Job
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
//! Translate an [`crate::op::ConvertPlan`] into an
//! [`oxideav_pipeline::Job`].
//!
//! The generated job has exactly one output keyed by the plan's
//! output path.  That output owns one or two tracks — an `all`
//! selector that pulls every stream through the filter chain in order.
//! The pipeline executor figures out which tracks actually exist in
//! the input (just a video stream for a PNG, both audio + video for
//! an MP4) and dispatches filters to the matching `FilterKind` at
//! DAG-build time.

use crate::frame_tap::{TapSpec, TAP_SINK};
use crate::image_sink::{self, LayoutHint};
use crate::op::{ConvertPlan, Dither, Mesh3DOptions, Mesh3DRenderMode, Op, ProjectionMode};
use indexmap::IndexMap;
use oxideav_core::{Error, MediaType, PixelFormat, RuntimeContext, StreamInfo};
use oxideav_pipeline::schema::{ConvertNode, StreamSelector};
use oxideav_pipeline::{select_streams, OutputKind};
use oxideav_pipeline::{
    FilterNode, Job, OutputSpec, Render3DNode, SourceRef, TrackInput, TrackSpec,
};
use serde_json::{json, Value};

/// Backend name handed to [`Render3DNode::backend`] for the auto-route
/// 3D→raster pipeline path.  Mirrors the only [`oxideav_render::RenderBackend`]
/// variant the workspace ships today (`Scanline`); the pipeline executor
/// hands this name to the user-installed
/// [`oxideav_pipeline::executor::RenderSourceFactory`] which deserialises
/// the opts JSON back into the renderer's typed
/// [`oxideav_render::RenderOptions`].
///
/// When future render backends (`raycast`, `pathtrace`, …) land, a new
/// `-render-backend NAME` arg on the CLI side will override this default.
pub const RENDER3D_DEFAULT_BACKEND: &str = "scanline";

/// Default raster canvas dimensions for the 3D→raster job when no
/// `-resize` op pins them.  Matches [`crate::mesh3d_render`]'s
/// in-tree default so the auto-route helper produces the same canvas
/// as the legacy side-channel runner.
const DEFAULT_RENDER3D_WIDTH: u32 = 1024;
const DEFAULT_RENDER3D_HEIGHT: u32 = 1024;

/// Default `-bg` for the 3D render canvas: transparent black, matching
/// [`crate::mesh3d_render`].  Composites cleanly against any downstream
/// `-alpha remove`.
const DEFAULT_RENDER3D_BG: [u8; 4] = [0, 0, 0, 0];

/// Default vertical FOV for perspective projection (degrees).
const DEFAULT_RENDER3D_FOV_DEG: f32 = 60.0;

/// Build a [`Job`] from a [`ConvertPlan`].
///
/// `ctx` is consulted via its [`ContainerRegistry`](oxideav_core::ContainerRegistry)
/// to map the output extension to a codec id — sibling crates that
/// register a container (e.g. `oxideav-png`, `oxideav-qoi`,
/// `oxideav-dds`) automatically extend the supported output set without
/// needing a hard-coded entry here.
///
/// When the plan needs `convert`'s own still-image writer (encoder
/// options, `%d` per-frame fan-out) the job's single output is the
/// reserved [`TAP_SINK`] (`@out`) with no codec: [`crate::run`] binds
/// it to [`crate::frame_tap`], which encodes and muxes.
pub fn plan_to_job(plan: &ConvertPlan, ctx: &RuntimeContext) -> Result<Job, Error> {
    plan_pipeline(plan, ctx).map(|p| p.job)
}

/// [`plan_to_job`] plus the planning notes and the frame-tap writer
/// spec [`crate::run`] needs. Kept separate so the public planner
/// stays side-effect free.
pub(crate) fn plan_pipeline(plan: &ConvertPlan, ctx: &RuntimeContext) -> Result<Planned, Error> {
    // Walk ops, distinguishing track-side filters from sink-side
    // metadata (format / quality / strip).  Filters are flattened
    // into the recursive `TrackInput` chain; the rest are deferred
    // to the sink.  Per-op lowering lives in [`lower_op`], shared
    // with [`plan_to_render3d_job`].
    let mut sink = SinkSide::default();

    // Starting input: the file itself.
    let mut chain: TrackInput = TrackInput::Source(SourceRef {
        from: plan.input.clone(),
    });

    for op in &plan.ops {
        chain = lower_op(chain, op, &mut sink, false);
    }

    finish_job(plan, ctx, chain, sink, true)
}

/// Build a 3D→raster [`Job`] from a [`ConvertPlan`] whose input is a
/// 3D-asset path (`.stl`/`.obj`/`.gltf`/`.glb`/`.usdz`/`.fbx`/`.mtl`).
///
/// Shape:
///
/// * The track input is [`TrackInput::Render3D`] — the pipeline
///   executor hands the `source` URI + `backend` name + opaque `opts`
///   JSON to the caller-installed
///   [`oxideav_pipeline::executor::RenderSourceFactory`].  That factory
///   is the layer that talks to [`oxideav_render`] and the
///   [`oxideav_mesh3d::Mesh3DRegistry`]; pipeline itself stays codec-
///   and render-agnostic.
/// * `Op::Resize` and `Op::Background` are absorbed by the renderer —
///   the resize dims seed `width` / `height` on the opts struct, and
///   the background seeds `background`.  Neither survives as a filter
///   node because the renderer produces the canvas at the requested
///   size directly (no downsample step, AA stays native to the raster
///   grid).
/// * `Mesh3DOptions::bg` wins over `Op::Background` so users can keep
///   the IM canvas-fill semantics separate from the renderer's clear
///   colour — mirrors [`crate::mesh3d_render`]'s `pick_render_bg`.
/// * Every other op (rotate / flip / negate / tonal / colour-grading
///   / strip / quality / …) is forwarded through the regular
///   [`plan_to_job`] filter chain on top of the Render3D source so the
///   post-rasterisation transforms keep their existing JSON dialect.
/// * The output codec is resolved by the same
///   [`ContainerRegistry`](oxideav_core::ContainerRegistry) lookup used
///   by [`plan_to_job`].
///
/// `opts` JSON mirrors the field shape of
/// [`oxideav_render::RenderOptions`] (one field per key, lowercase /
/// snake_case names) so the consumer's `RenderSourceFactory` can
/// deserialise it directly.  Keys: `width`, `height`, `background`
/// (RGBA `[u8; 4]`), `shading`, `projection`, `fov_deg`, `light` (object
/// with `azimuth_deg` / `elevation_deg` / `intensity`), `camera`
/// (object with `elevation_deg` / `azimuth_deg` / `distance`, or `null`),
/// `aa`.  Unset `Mesh3DOptions` fall back to the renderer's documented
/// defaults so a bare `convert in.gltf out.png` produces a sensible
/// canvas without any flag plumbing.
pub fn plan_to_render3d_job(plan: &ConvertPlan, ctx: &RuntimeContext) -> Result<Job, Error> {
    let (width, height) = pick_render3d_dims(&plan.ops);
    let bg = pick_render3d_bg(&plan.ops, &plan.mesh3d_options);
    let opts = build_render3d_opts(&plan.mesh3d_options, width, height, bg);

    // Source node: the renderer absorbs the file IO via the installed
    // RenderSourceFactory, so the source URI lives on Render3DNode
    // rather than on a SourceRef leaf.
    let mut chain = TrackInput::Render3D(Render3DNode {
        source: plan.input.clone(),
        backend: RENDER3D_DEFAULT_BACKEND.to_string(),
        opts,
    });

    let mut sink = SinkSide::default();
    for op in &plan.ops {
        chain = lower_op(chain, op, &mut sink, true);
    }

    finish_job(plan, ctx, chain, sink, false).map(|p| p.job)
}

/// Pull the render canvas dimensions from the op chain: the LAST
/// `-resize WxH` (any mode) seeds the canvas; otherwise the default
/// 1024×1024.  Mirrors [`crate::mesh3d_render::pick_dims`] so the
/// auto-route helper and the legacy side-channel runner agree on
/// canvas size for the same flag combination.
fn pick_render3d_dims(ops: &[Op]) -> (u32, u32) {
    for op in ops.iter().rev() {
        // `-thumbnail WxH` carries the same geometry request as
        // `-resize WxH` (plus Strip, handled by `lower_op`). Both are
        // absorbed by the renderer, so both must seed the canvas —
        // ignoring Thumbnail here silently produced the 1024×1024
        // default for `convert scene.gltf -thumbnail 256x256 out.png`.
        if let Op::Resize { width, height, .. } | Op::Thumbnail { width, height, .. } = op {
            return (*width, *height);
        }
    }
    (DEFAULT_RENDER3D_WIDTH, DEFAULT_RENDER3D_HEIGHT)
}

/// `-bg COLOR` (`Mesh3DOptions::bg`) wins over `-background COLOR`
/// (`Op::Background`); both fall back to transparent black.  Mirrors
/// [`crate::mesh3d_render::pick_render_bg`].
fn pick_render3d_bg(ops: &[Op], options: &Mesh3DOptions) -> [u8; 4] {
    if let Some(bg) = options.bg {
        return bg;
    }
    for op in ops.iter().rev() {
        if let Op::Background(c) = op {
            return *c;
        }
    }
    DEFAULT_RENDER3D_BG
}

/// Build the `opts` JSON payload that ships on
/// [`Render3DNode::opts`].  Field shape mirrors
/// [`oxideav_render::RenderOptions`] one-for-one so the consumer's
/// installed `RenderSourceFactory` can `serde_json::from_value` it
/// straight into the typed struct.  None-valued `Mesh3DOptions` fall
/// back to the renderer's documented defaults (Flat shading,
/// perspective projection, 60° FOV, default directional light at
/// 45°/45°/1.0, auto-frame camera, 1× AA).
fn build_render3d_opts(options: &Mesh3DOptions, width: u32, height: u32, bg: [u8; 4]) -> Value {
    let shading = options
        .render_mode
        .map(shading_tag_from_mode)
        .unwrap_or("flat");
    let projection = options
        .projection
        .map(projection_tag_from_mode)
        .unwrap_or("perspective");
    let fov_deg = f32j(options.fov_deg.unwrap_or(DEFAULT_RENDER3D_FOV_DEG));
    // The renderer's default light spec lives behind
    // `LightSpec::default_light()` on the oxideav-render side; mirror
    // the same defaults here so the JSON carries the same values the
    // typed struct would have produced.
    let light = options
        .light
        .map(|l| {
            json!({
                "azimuth_deg": f32j(l.azimuth_deg),
                "elevation_deg": f32j(l.elevation_deg),
                "intensity": f32j(l.intensity),
            })
        })
        .unwrap_or_else(|| {
            json!({
                "azimuth_deg": 45.0,
                "elevation_deg": 45.0,
                "intensity": 1.0,
            })
        });
    let camera = options.camera.map(|c| {
        json!({
            "elevation_deg": f32j(c.elevation_deg),
            "azimuth_deg": f32j(c.azimuth_deg),
            "distance": f32j(c.distance),
        })
    });
    let aa = options.aa.unwrap_or(1).clamp(1, 8);

    json!({
        "width": width,
        "height": height,
        "background": [bg[0], bg[1], bg[2], bg[3]],
        "shading": shading,
        "projection": projection,
        "fov_deg": fov_deg,
        "light": light,
        "camera": camera,
        "aa": aa,
    })
}

/// Stable lowercase tag for the JSON-side `shading` field.  Matches the
/// snake-case identifier scheme used by
/// [`oxideav_render::ShadingMode`]'s variants (Flat/Wireframe/Gouraud/
/// Phong are single-word, NormalDebug/DepthDebug become
/// `normal-debug` / `depth-debug` — same dash-cased shape as
/// `video.auto-gamma` etc. elsewhere in the JSON dialect).
fn shading_tag_from_mode(mode: Mesh3DRenderMode) -> &'static str {
    match mode {
        Mesh3DRenderMode::Flat => "flat",
        Mesh3DRenderMode::Wireframe => "wireframe",
        Mesh3DRenderMode::Gouraud => "gouraud",
        Mesh3DRenderMode::Phong => "phong",
        Mesh3DRenderMode::NormalDebug => "normal-debug",
        Mesh3DRenderMode::DepthDebug => "depth-debug",
    }
}

/// Stable lowercase tag for the JSON-side `projection` field.
fn projection_tag_from_mode(mode: ProjectionMode) -> &'static str {
    match mode {
        ProjectionMode::Perspective => "perspective",
        ProjectionMode::Orthographic => "orthographic",
    }
}

/// Sink-side (non-filter) state accumulated while walking ops:
/// the encoder params bag, metadata stripping, `-format` override.
struct SinkSide {
    codec_params: Value,
    strip_metadata: bool,
    format_override: Option<String>,
    /// `-depth N` — consumed by the still-image target selection.
    depth: Option<u8>,
    /// `--opt KEY=VALUE` pairs, in command-line order.
    encoder_opts: Vec<(String, String)>,
    /// `-threads N` → the job's `threads` key (`0` / unset = auto).
    threads: Option<usize>,
}

impl Default for SinkSide {
    fn default() -> Self {
        SinkSide {
            codec_params: json!({}),
            strip_metadata: false,
            format_override: None,
            depth: None,
            encoder_opts: Vec::new(),
            threads: None,
        }
    }
}

/// Convert an `f32` op value to a JSON number without widening noise.
///
/// A plain `json!(x)` widens f32→f64 bit-exactly, so `-light 10,20,0.9`
/// would emit `"intensity": 0.8999999761581421` into the job document.
/// Round-tripping through the f32's shortest decimal representation
/// keeps the number the user actually typed (`0.9`) — the JSON stays
/// snapshot-clean, and a consumer narrowing f64→f32 lands on the same
/// f32 either way (shortest-repr is round-trip-exact by definition).
fn f32j(v: f32) -> Value {
    json!(v.to_string().parse::<f64>().unwrap_or(f64::from(v)))
}

/// Lower one [`Op`] onto the recursive filter chain, or fold it into
/// the sink-side state.
///
/// Shared by [`plan_to_job`] and [`plan_to_render3d_job`].
/// `absorb_canvas` selects the 3D-render behaviour where the renderer
/// produces the canvas directly ([`pick_render3d_dims`] /
/// [`pick_render3d_bg`] already consumed `-resize` / `-background`,
/// and the resize half of `-thumbnail` is likewise absorbed) so those
/// ops must not ALSO survive as filter nodes — skipping them avoids a
/// redundant resize / background pass downstream of the Render3D
/// source.
fn lower_op(chain: TrackInput, op: &Op, sink: &mut SinkSide, absorb_canvas: bool) -> TrackInput {
    // A filter-chain step — wrap the current chain in a FilterNode.
    let wrap = |prev: TrackInput, filter: &str, params: Value| {
        TrackInput::Filter(FilterNode {
            filter: filter.to_string(),
            params,
            input: Box::new(prev),
        })
    };

    match op {
        Op::Resize {
            width,
            height,
            mode,
        } => {
            if absorb_canvas {
                // Renderer absorbs the dims — encoded directly onto
                // the RenderOptions payload, not as a filter node.
                return chain;
            }
            // The pipeline's resize factory takes literal target
            // dims today. We forward `width`/`height` along with
            // the geometry mode tag so a future executor pass can
            // resolve the source-aware variants (Fill/Shrink/Grow/
            // Percent/Area) against the actual frame size at
            // DAG-build time. Until that lands, only `Default` and
            // `Force` are pixel-accurate on the pipeline path —
            // the source-aware modes degrade to `Default` semantics
            // when the executor sees a mode it doesn't understand.
            // The PDF side-channel (which already knows the source
            // dims) honours every mode today.
            wrap(
                chain,
                "video.resize",
                json!({
                    "width": width,
                    "height": height,
                    "interpolation": "bilinear",
                    "mode": mode.as_tag(),
                }),
            )
        }
        Op::Thumbnail {
            width,
            height,
            mode,
        } => {
            // `-thumbnail` is sugar for `Resize + Strip` (and, on a
            // future pass, EXIF auto-orient). On the render path the
            // renderer already produced the canvas at the requested
            // size via `pick_render3d_dims`, so only the strip half
            // survives there.
            sink.strip_metadata = true;
            if absorb_canvas {
                return chain;
            }
            wrap(
                chain,
                "video.resize",
                json!({
                    "width": width,
                    "height": height,
                    "interpolation": "bilinear",
                    "mode": mode.as_tag(),
                }),
            )
        }
        Op::Define { key, value } => {
            // Forward the literal key (preserving any `:` namespace
            // separator) onto the codec params bag. Values that
            // parse as integers / floats / booleans still come
            // through as JSON strings — codecs that care about
            // type can re-parse from the string. Bare `-define KEY`
            // (no `=VALUE`) becomes `{"KEY": true}`.
            match value {
                Some(v) => sink.codec_params[key.clone()] = json!(v),
                None => sink.codec_params[key.clone()] = json!(true),
            }
            chain
        }
        Op::Blur { radius, sigma } => wrap(
            chain,
            "video.blur",
            json!({
                "radius": radius,
                "sigma": f32j(*sigma),
                "planes": "all"
            }),
        ),
        Op::Edge { radius } => wrap(chain, "video.edge", json!({ "radius": radius })),
        Op::Colors { count, dither } => {
            // Palette quantisation: rely on the pipeline's
            // ConvertNode (pixfmt) which already supports
            // `pal8` + dither via `oxideav-pixfmt`.  We nest
            // the palette step inline as a filter-shaped node
            // that the executor recognises by name.
            let dither_str = match dither {
                Dither::None => "none",
                Dither::Bayer => "bayer",
                Dither::FloydSteinberg => "floyd_steinberg",
            };
            wrap(
                chain,
                "video.pixfmt",
                json!({
                    "format": "pal8",
                    "dither": dither_str,
                    "colors": count,
                }),
            )
        }
        Op::Format(fmt) => {
            sink.format_override = Some(fmt.clone());
            chain
        }
        Op::Quality(q) => {
            // Codec-specific key; the encoder drops it when
            // unsupported.  Use `quality` for JPEG/WebP, `crf`
            // could be added by a later pass for h264/h265.
            sink.codec_params["quality"] = json!(q);
            chain
        }
        Op::Strip => {
            sink.strip_metadata = true;
            chain
        }
        Op::Depth(d) => {
            sink.depth = Some(*d);
            chain
        }
        Op::EncoderOpt { key, value } => {
            sink.encoder_opts.push((key.clone(), value.clone()));
            chain
        }
        Op::Threads(n) => {
            sink.threads = (*n >= 1).then_some(*n);
            chain
        }
        // Vector-input ops; dropped on both paths. Raster inputs have
        // no DPI, no composite-over-bg semantics that wouldn't
        // conflict with `-resize`/etc., and no alpha-channel grammar
        // to honour beyond what the encoder already does; on the
        // render path `-background` was already consumed by
        // `pick_render3d_bg` before the walk. The pdf_runner
        // side-channel applies them when reading PDFs.
        Op::Density(_) | Op::Background(_) | Op::Alpha(_) => chain,
        Op::Rotate { degrees } => wrap(chain, "video.rotate", json!({ "degrees": degrees })),
        Op::Flip => wrap(chain, "video.flip", json!({})),
        Op::Flop => wrap(chain, "video.flop", json!({})),
        Op::Crop { x, y, w, h } => wrap(
            chain,
            "video.crop",
            json!({ "x": x, "y": y, "width": w, "height": h }),
        ),
        Op::Extent {
            width,
            height,
            x,
            y,
            bg,
        } => {
            // The `oxideav-image-filter` `Extent` factory accepts
            // `width`/`height` plus optional signed `offset_x` /
            // `offset_y` and an RGBA `background` array. We forward
            // everything verbatim — the background was already
            // resolved against the source-order `-background` ops
            // at args-parse time so the plan walker stays
            // stateless.
            wrap(
                chain,
                "video.extent",
                json!({
                    "width": width,
                    "height": height,
                    "offset_x": x,
                    "offset_y": y,
                    "background": [bg[0], bg[1], bg[2], bg[3]],
                }),
            )
        }
        Op::Negate => wrap(chain, "video.negate", json!({})),
        Op::Sharpen { radius, sigma } => wrap(
            chain,
            "video.sharpen",
            json!({ "radius": radius, "sigma": f32j(*sigma) }),
        ),
        Op::Unsharp {
            radius,
            sigma,
            amount,
            threshold,
        } => wrap(
            chain,
            "video.unsharp",
            json!({
                "radius": radius,
                "sigma": f32j(*sigma),
                "amount": f32j(*amount),
                "threshold": threshold,
            }),
        ),
        Op::Gamma { value } => wrap(chain, "video.gamma", json!({ "value": f32j(*value) })),
        Op::BrightnessContrast {
            brightness,
            contrast,
        } => wrap(
            chain,
            "video.brightness-contrast",
            json!({ "brightness": f32j(*brightness), "contrast": f32j(*contrast) }),
        ),
        Op::Contrast { delta } => {
            // IM's bare `-contrast` flag bumps contrast by a single
            // 5%-of-range step. Multiple `-contrast` accumulate
            // linearly. Map to the brightness-contrast factory's
            // contrast-only knob so the executor can fold this into
            // a single LUT pass alongside any explicit
            // `-brightness-contrast` already in the chain.
            let pct = f64::from(*delta) * 5.0;
            wrap(chain, "video.contrast", json!({ "value": pct }))
        }
        Op::Sepia { threshold } => wrap(
            chain,
            "video.sepia",
            json!({ "threshold": f32j(*threshold) }),
        ),
        Op::Modulate {
            brightness,
            saturation,
            hue,
        } => {
            // IM's hue is "percent-of-base around 100" — 0 is
            // -180°, 100 is identity, 200 is +180°. The
            // image-filter factory accepts degrees directly via
            // `hue_degrees`, so translate. The subtract/scale runs
            // in f64 on the noise-free decimal value so round CLI
            // inputs produce round degree values (hue=150 → 90.0,
            // not 89.99999…).
            let hue_clean = f32j(*hue).as_f64().unwrap_or(f64::from(*hue));
            let hue_degrees = (hue_clean - 100.0) * 1.8;
            wrap(
                chain,
                "video.modulate",
                json!({
                    "brightness": f32j(*brightness),
                    "saturation": f32j(*saturation),
                    "hue_degrees": hue_degrees,
                }),
            )
        }
        Op::Level {
            black,
            gamma,
            white,
        } => wrap(
            chain,
            "video.level",
            json!({ "black": black, "gamma": f32j(*gamma), "white": white }),
        ),
        Op::Normalize => wrap(chain, "video.normalize", json!({})),
        Op::Threshold { value } => wrap(chain, "video.threshold", json!({ "value": value })),
        Op::Posterize { levels } => wrap(chain, "video.posterize", json!({ "levels": levels })),
        Op::Solarize { value } => wrap(chain, "video.solarize", json!({ "value": value })),
        Op::Colorspace(cs) => {
            let lower = cs.to_ascii_lowercase();
            if lower == "gray" || lower == "grey" {
                return wrap(chain, "video.grayscale", json!({ "preserve_alpha": true }));
            }
            // `rgb` / `srgb` are recorded no-ops — input keeps its
            // colourspace, downstream encoder converts as needed.
            chain
        }
        Op::Vignette {
            radius,
            sigma,
            x,
            y,
        } => wrap(
            chain,
            "video.vignette",
            json!({
                "x": f32j(*x),
                "y": f32j(*y),
                "radius": f32j(*radius),
                "sigma": f32j(*sigma),
            }),
        ),
        Op::Colorize { color, amount } => wrap(
            chain,
            "video.colorize",
            json!({
                "color": [color[0], color[1], color[2], color[3]],
                "amount": f32j(*amount),
            }),
        ),
        Op::Equalize => wrap(chain, "video.equalize", json!({})),
        Op::AutoGamma => wrap(chain, "video.auto-gamma", json!({})),
        Op::Trim { fuzz } => {
            // The image-filter `Trim` factory accepts `fuzz` as a
            // 0..=255 byte plus an optional `background` array. We
            // forward only `fuzz` here — the args parser doesn't
            // expose a per-`-trim` colour override yet, so the
            // factory falls back to its corner-pixel auto-detection
            // (matching IM's behaviour when neither `-bordercolor`
            // nor `-background` is set).
            wrap(chain, "video.trim", json!({ "fuzz": fuzz }))
        }
        Op::Roll { dx, dy } => {
            // Signed circular shift; the `oxideav-image-filter`
            // `Roll` factory accepts `dx`/`dy` (also `x`/`y`
            // aliases). Pixels that fall off one edge wrap around to
            // the opposite edge so the visible image translates as a
            // rigid block; width/height stay unchanged, so no shape
            // recovery is needed downstream.
            wrap(chain, "video.roll", json!({ "dx": dx, "dy": dy }))
        }
    }
}

/// Result of planning the regular pipeline route: the job, the
/// human-facing notes [`crate::run`] prints to stderr, and — when the
/// plan needs `convert`'s own still-image writer (encoder options,
/// `%d` fan-out) — the writer spec for the job's [`TAP_SINK`] output.
pub(crate) struct Planned {
    pub job: Job,
    pub notes: Vec<String>,
    pub tap: Option<TapSpec>,
}

/// What the still-image planning learned about the input.
struct StillInput {
    /// Video-stream ordinal the track is pinned to.
    ordinal: usize,
    /// The input's video streams (container order).
    streams: Vec<StreamInfo>,
    /// The output encoder's accepted layouts.
    accepted: Vec<PixelFormat>,
}

/// Shared tail for both planners: fold sink-side state into the codec
/// params, resolve the output codec, assemble the single-output
/// [`Job`], and enforce the schema-validation guarantee.
///
/// `probe_input` enables the still-image sink planning (see
/// [`crate::image_sink`]): when the output resolves to an image
/// encoder and the input's container header can be read, the track
/// is pinned to one video stream and — for a plain conversion — to
/// the encoder input layout that loses nothing the source carries.
/// Encoder options and `%d` fan-out additionally route the frames to
/// `convert`'s own writer ([`crate::frame_tap`]). The 3D-render
/// planner passes `false` (its source is a renderer, not a file with
/// streams).
fn finish_job(
    plan: &ConvertPlan,
    ctx: &RuntimeContext,
    chain: TrackInput,
    mut sink: SinkSide,
    probe_input: bool,
) -> Result<Planned, Error> {
    // Sink-side metadata handling.
    if sink.strip_metadata {
        sink.codec_params["strip_metadata"] = json!(true);
    }
    if let Some(ref f) = sink.format_override {
        sink.codec_params["format"] = json!(f);
    }

    // The pipeline insists every filter-terminated track carry an
    // output codec — frames can't be stream-copied.  Infer from the
    // output extension (or `-format` override) so the IM-style
    // `convert in.png -resize 64x64 out.jpg` works without the user
    // stating the obvious.
    let codec = codec_for_output(sink.format_override.as_deref(), &plan.output, ctx);

    // Encoder options: `--opt` (validated against the encoder's
    // declared schema) plus the extension-implied ones (`.avif` ⇒
    // `codec=av1`).
    let out_ext = sink
        .format_override
        .clone()
        .or_else(|| ext_of(&plan.output).map(str::to_string));
    let options = image_sink::encoder_options(
        ctx,
        codec.as_deref(),
        out_ext.as_deref(),
        &sink.encoder_opts,
    )?;
    let fanout = plan.output_template.is_some();
    let wants_tap = fanout || !options.is_empty();

    let mut notes = Vec::new();
    let still = if probe_input {
        still_input(plan, ctx, codec.as_deref(), fanout, &mut notes)
    } else {
        None
    };

    let (job, tap) = match (still, wants_tap) {
        (Some(si), false) => {
            let job = still_job(plan, chain, codec, sink, &si, &mut notes)?;
            (job, None)
        }
        (Some(si), true) => {
            let (job, tap) = tap_job(plan, ctx, chain, codec, sink, si, options)?;
            (job, Some(tap))
        }
        (None, true) => {
            let what = if fanout {
                format!(
                    "a `%d` output template ('{}') fans out one file per frame",
                    plan.output
                )
            } else {
                "encoder options (--opt, or ones the output extension implies)".to_string()
            };
            return Err(Error::unsupported(format!(
                "convert: {what} — that needs a still-image output format (png, ppm, heic, avif, …) and an input file whose streams can be read"
            )));
        }
        (None, false) => {
            if sink.depth.is_some() {
                notes.push(
                    "convert: note: -depth applies to still-image outputs only; ignored"
                        .to_string(),
                );
            }
            if probe_input {
                if let Some(out) =
                    container_default_output(plan, ctx, &chain, &sink, codec.as_deref(), &mut notes)
                {
                    let job = single_output_job(&plan.output, out, sink.threads)?;
                    return Ok(Planned {
                        job,
                        notes,
                        tap: None,
                    });
                }
            }
            let track = TrackSpec {
                input: chain,
                codec,
                params: sink.codec_params,
                stream_selector: None,
            };
            let out = OutputSpec {
                audio: vec![],
                video: vec![],
                subtitle: vec![],
                all: vec![track],
            };
            (single_output_job(&plan.output, out, sink.threads)?, None)
        }
    };
    Ok(Planned { job, notes, tap })
}

/// Per-stream tracks for an output that cannot take the input as a
/// whole:
///
/// * streams the output cannot hold are left out
///   ([`oxideav_pipeline::select_streams`]: a video + audio input
///   written to `.wav` / `.flac` keeps its best audio stream, to `.y4m`
///   its video), each with a `convert: note:` line;
/// * for a container whose extension names no codec (`.webm`, `.mkv`,
///   …), streams it cannot store as-is get the container's default
///   codec (see [`crate::container_defaults`]); the rest are
///   stream-copied. A single-codec output (`.flac`) encodes every kept
///   stream with that codec.
///
/// One track per kept audio / video stream, pinned by its kind ordinal
/// in the input. `None` keeps the single `all` track (nothing dropped,
/// nothing to re-encode, or the input could not be probed).
fn container_default_output(
    plan: &ConvertPlan,
    ctx: &RuntimeContext,
    chain: &TrackInput,
    sink: &SinkSide,
    codec: Option<&str>,
    notes: &mut Vec<String>,
) -> Option<OutputSpec> {
    let ext = sink
        .format_override
        .clone()
        .or_else(|| ext_of(&plan.output).map(str::to_string))?
        .to_ascii_lowercase();
    let container = ctx.containers.container_for_extension(&ext)?.to_string();
    let streams = image_sink::probe_streams(&plan.input, ctx)?;
    let output = match codec {
        Some(c) => OutputKind::SingleCodec(c),
        None => OutputKind::Container(&container),
    };
    let selection = select_streams(&ctx.containers, &ctx.codecs, output, &streams);
    // Nothing fits: keep the historical job so the muxer / encoder
    // reports why.
    if selection.keep.is_empty() {
        return None;
    }
    // A timed output takes the image-sequence tracks, not the cover
    // still: when a kept video stream is timed, the kept stills (one
    // tick of a 1/1 time base — how HEIF exposes its image items) are
    // skipped. Stream order is not relied on.
    let timed_video_kept = streams.iter().any(|s| {
        s.params.media_type == MediaType::Video
            && selection.keeps(s.index)
            && !image_sink::is_still(s)
    });
    let skipped_stills: Vec<u32> = if timed_video_kept {
        streams
            .iter()
            .filter(|s| {
                s.params.media_type == MediaType::Video
                    && selection.keeps(s.index)
                    && image_sink::is_still(s)
            })
            .map(|s| s.index)
            .collect()
    } else {
        Vec::new()
    };
    let kept = |idx: u32| selection.keeps(idx) && !skipped_stills.contains(&idx);
    // (kind, ordinal among the input's streams of that kind, codec).
    let tracks: Vec<(MediaType, u32, Option<String>)> = match codec {
        Some(c) => kind_ordinals(&streams)
            .into_iter()
            .map(|(idx, kind, ordinal)| (idx, kind, ordinal, Some(c.to_string())))
            .filter(|(idx, ..)| kept(*idx))
            .map(|(_, kind, ordinal, codec)| (kind, ordinal, codec))
            .collect(),
        None => {
            let planned = crate::container_defaults::plan_tracks(ctx, &container, &streams);
            if planned.is_none() && selection.dropped.is_empty() && skipped_stills.is_empty() {
                return None;
            }
            let ordinals = kind_ordinals(&streams);
            ordinals
                .into_iter()
                .filter(|(idx, ..)| kept(*idx))
                .map(|(_, kind, ordinal)| {
                    let codec = planned.as_ref().and_then(|p| {
                        p.iter()
                            .find(|(k, o, _)| *k == kind && *o == ordinal)
                            .and_then(|(_, _, c)| c.clone())
                    });
                    (kind, ordinal, codec)
                })
                .collect()
        }
    };
    if selection.dropped.is_empty() && skipped_stills.is_empty() && codec.is_some() {
        return None;
    }
    for idx in &skipped_stills {
        notes.push(format!(
            "convert: skipping still-image stream #{idx} of '{}' (the cover image); a timed output takes the image-sequence track",
            plan.input
        ));
    }
    notes.extend(
        selection
            .notes
            .iter()
            .map(|n| format!("convert: {n} ('{}')", plan.input)),
    );
    let mut out = OutputSpec {
        audio: vec![],
        video: vec![],
        subtitle: vec![],
        all: vec![],
    };
    for (kind, ordinal, codec) in tracks {
        let params = if codec.is_some() {
            sink.codec_params.clone()
        } else {
            json!({})
        };
        let track = TrackSpec {
            input: chain.clone(),
            codec,
            params,
            stream_selector: Some(StreamSelector {
                kind: Some(kind),
                index: Some(ordinal),
            }),
        };
        match kind {
            MediaType::Video => out.video.push(track),
            _ => out.audio.push(track),
        }
    }
    Some(out)
}

/// `(input stream index, kind, ordinal among that kind)` for every
/// audio / video stream — the shape a track's kind-relative stream
/// selector addresses.
fn kind_ordinals(streams: &[StreamInfo]) -> Vec<(u32, MediaType, u32)> {
    let (mut video, mut audio) = (0u32, 0u32);
    streams
        .iter()
        .filter_map(|s| {
            let counter = match s.params.media_type {
                MediaType::Video => &mut video,
                MediaType::Audio => &mut audio,
                _ => return None,
            };
            let ordinal = *counter;
            *counter += 1;
            Some((s.index, s.params.media_type, ordinal))
        })
        .collect()
}

/// Wrap one output spec into a validated [`Job`].
fn single_output_job(key: &str, out: OutputSpec, threads: Option<usize>) -> Result<Job, Error> {
    let mut outputs = IndexMap::new();
    outputs.insert(key.to_string(), out);
    let job = Job {
        outputs,
        aliases: IndexMap::new(),
        threads,
    };
    // Guarantee: every job this planner emits satisfies the pipeline
    // schema's own invariants (non-empty source, non-blank codec ids,
    // …). Validating here turns a planner bug into a typed error at
    // plan time instead of an opaque executor failure later.
    job.validate()?;
    Ok(job)
}

/// Probe the input for the still-image planning. `None` when the
/// output is not an image encoder or the input's stream list cannot
/// be read from its header (the caller then keeps the historical job
/// shape).
fn still_input(
    plan: &ConvertPlan,
    ctx: &RuntimeContext,
    codec: Option<&str>,
    fanout: bool,
    notes: &mut Vec<String>,
) -> Option<StillInput> {
    let accepted = image_sink::encoder_accepted_formats(ctx, codec?)?;
    let streams = image_sink::probe_video_streams(&plan.input, ctx)?;
    if streams.is_empty() {
        return None;
    }
    let ordinal = if fanout {
        image_sink::fanout_stream(&streams)
    } else {
        image_sink::still_stream(&streams)
    };
    if streams.len() > 1 {
        notes.push(if fanout {
            format!(
                "convert: note: '{}' has {} video streams; writing the frames of video stream #{ordinal}",
                plan.input,
                streams.len()
            )
        } else {
            format!(
                "convert: note: '{}' has {} video streams; writing video stream #{ordinal} (the primary still image); use a `%d` output template for the image-sequence frames",
                plan.input,
                streams.len()
            )
        });
    }
    Some(StillInput {
        ordinal,
        streams,
        accepted,
    })
}

fn video_selector(ordinal: usize) -> StreamSelector {
    StreamSelector {
        kind: Some(MediaType::Video),
        index: Some(ordinal as u32),
    }
}

fn wrap_convert(chain: TrackInput, target: PixelFormat) -> TrackInput {
    match pixfmt_name(target) {
        Some(name) => TrackInput::Convert(ConvertNode {
            convert: name,
            input: Box::new(chain),
        }),
        None => chain,
    }
}

/// Plain still-image job: the pipeline encodes and muxes; the planner
/// pins the stream and (for a plain conversion) the encoder layout.
fn still_job(
    plan: &ConvertPlan,
    mut chain: TrackInput,
    codec: Option<String>,
    sink: SinkSide,
    si: &StillInput,
    notes: &mut Vec<String>,
) -> Result<Job, Error> {
    // Only a plain conversion has a known encoder input layout: filter
    // ops may change it, and the pipeline tracks it no better.
    if matches!(chain, TrackInput::Source(_)) {
        let hint = LayoutHint::for_output(&plan.output);
        if let Some(target) = si.streams[si.ordinal]
            .params
            .pixel_format
            .and_then(|src| image_sink::pick_sink_format(src, &si.accepted, hint, sink.depth))
        {
            chain = wrap_convert(chain, target);
        }
    } else if sink.depth.is_some() {
        notes.push(
            "convert: note: -depth applies to plain conversions (no filter ops) unless encoder options are given; ignored"
                .to_string(),
        );
    }
    let track = TrackSpec {
        input: chain,
        codec,
        params: sink.codec_params,
        stream_selector: Some(video_selector(si.ordinal)),
    };
    single_output_job(
        &plan.output,
        OutputSpec {
            audio: vec![],
            video: vec![track],
            subtitle: vec![],
            all: vec![],
        },
        sink.threads,
    )
}

/// Frame-tap job: the executor decodes / filters / converts into the
/// reserved [`TAP_SINK`]; [`crate::frame_tap`] encodes and muxes.
fn tap_job(
    plan: &ConvertPlan,
    ctx: &RuntimeContext,
    chain: TrackInput,
    codec: Option<String>,
    sink: SinkSide,
    si: StillInput,
    options: Vec<(String, String)>,
) -> Result<(Job, TapSpec), Error> {
    let codec = codec.ok_or_else(|| Error::unsupported("convert: no output codec"))?;
    let stream = si.streams[si.ordinal].clone();
    let src = stream.params.pixel_format.ok_or_else(|| {
        Error::unsupported(format!(
            "convert: '{}' does not declare the pixel layout of video stream #{}",
            plan.input, si.ordinal
        ))
    })?;
    let hint = LayoutHint::for_output(&plan.output);
    // The layout the frames reach the writer in: the planner's pick,
    // else what the pipeline itself would pick (the source when the
    // encoder takes it, otherwise the encoder's first choice).
    let target =
        image_sink::pick_sink_format(src, &si.accepted, hint, sink.depth).unwrap_or_else(|| {
            if si.accepted.is_empty() || si.accepted.contains(&src) {
                src
            } else {
                si.accepted[0]
            }
        });
    let bare = matches!(chain, TrackInput::Source(_));
    let chain = if target != src {
        let wrapped = wrap_convert(chain, target);
        if !wrapped.is_convert() {
            return Err(Error::unsupported(format!(
                "convert: no job-schema name for the {target:?} layout"
            )));
        }
        wrapped
    } else {
        chain
    };
    let dims = if bare {
        stream.params.width.zip(stream.params.height)
    } else {
        None
    };
    let container_key = sink
        .format_override
        .clone()
        .or_else(|| ext_of(&plan.output).map(str::to_string))
        .map(|e| e.to_ascii_lowercase())
        .unwrap_or_default();
    let container = ctx
        .containers
        .container_for_extension(&container_key)
        .ok_or_else(|| {
            Error::format_not_found(format!(
                "convert: no container registered for '.{container_key}'"
            ))
        })?
        .to_string();
    let track = TrackSpec {
        input: chain,
        codec: None,
        params: json!({}),
        stream_selector: Some(video_selector(si.ordinal)),
    };
    let job = single_output_job(
        TAP_SINK,
        OutputSpec {
            audio: vec![],
            video: vec![track],
            subtitle: vec![],
            all: vec![],
        },
        sink.threads,
    )?;
    // The encoder's thread budget resolves exactly as the executor's:
    // the job's `threads` key, else the host's parallelism.
    let threads = sink
        .threads
        .unwrap_or_else(|| oxideav_core::ExecutionContext::auto().threads);
    let tap = TapSpec {
        codec,
        container,
        options,
        frame_format: target,
        dims,
        stream,
        output: plan.output.clone(),
        template: plan.output_template.clone(),
        threads,
    };
    Ok((job, tap))
}

/// Canonical short name the job schema parses back into `fmt`
/// (`Rgb48Le` → `rgb48le`), or `None` when the schema has no name for
/// it — the planner then leaves the choice to the pipeline.
fn pixfmt_name(fmt: PixelFormat) -> Option<String> {
    let name = format!("{fmt:?}").to_ascii_lowercase();
    (oxideav_pipeline::schema::parse_pixel_format(&name).ok() == Some(fmt)).then_some(name)
}

fn ext_of(path: &str) -> Option<&str> {
    let last = path.rsplit('/').next().unwrap_or(path);
    let last = last.split('?').next().unwrap_or(last);
    let dot = last.rfind('.')?;
    Some(&last[dot + 1..])
}

/// Guess the output codec from the extension, honouring `-format`
/// override.
///
/// Resolution order:
///
/// 1. Consult [`ContainerRegistry::container_for_extension`]
///    (`oxideav_core::ContainerRegistry`). For image-format crates the
///    container name doubles as the codec id (e.g. `png` → `png`,
///    `qoi` → `qoi`, `dds` → `dds`), so a registered extension Just
///    Works without any hard-coded knowledge here. New sibling crates
///    extend the supported set the moment the umbrella registers them.
/// 2. Otherwise return `None` and let the pipeline infer per-track
///    (the right answer for video containers like MP4/MKV that don't
///    pin a single codec, and the prompt to add `-format CODEC` for
///    extensions nobody has registered yet).
fn codec_for_output(
    format_override: Option<&str>,
    output: &str,
    ctx: &RuntimeContext,
) -> Option<String> {
    image_sink::resolve_output_codec(format_override, output, ctx)
}

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

    #[test]
    fn kind_ordinals_count_per_media_type_in_input_order() {
        use oxideav_core::{CodecId, CodecParameters, TimeBase};
        let mk = |index: u32, params: CodecParameters| StreamInfo {
            index,
            time_base: TimeBase::new(1, 25),
            duration: None,
            start_time: Some(0),
            params,
        };
        let streams = [
            mk(0, CodecParameters::video(CodecId::new("h264"))),
            mk(1, CodecParameters::audio(CodecId::new("aac"))),
            mk(2, CodecParameters::subtitle(CodecId::new("srt"))),
            mk(3, CodecParameters::audio(CodecId::new("flac"))),
        ];
        assert_eq!(
            kind_ordinals(&streams),
            vec![
                (0, MediaType::Video, 0),
                (1, MediaType::Audio, 0),
                (3, MediaType::Audio, 1),
            ]
        );
    }
    use crate::op::ResizeMode;

    fn plan_with(ops: Vec<Op>) -> ConvertPlan {
        ConvertPlan {
            input: "in.png".into(),
            input_pages: None,
            ops,
            output: "out.jpg".into(),
            output_template: None,
            help: false,
            ping: false,
            probe: false,
            probe_json: false,
            probe_watch: false,
            mesh3d_options: Default::default(),
        }
    }

    /// Empty context — every extension resolves to `None` since no
    /// crates have registered any extension/codec pairs yet.
    fn empty_ctx() -> RuntimeContext {
        RuntimeContext::new()
    }

    #[test]
    fn empty_plan_is_passthrough() {
        let job = plan_to_job(&plan_with(vec![]), &empty_ctx()).unwrap();
        assert_eq!(job.outputs.len(), 1);
        let (key, out) = job.outputs.iter().next().unwrap();
        assert_eq!(key, "out.jpg");
        assert_eq!(out.all.len(), 1);
        match &out.all[0].input {
            TrackInput::Source(s) => assert_eq!(s.from, "in.png"),
            other => panic!("expected direct source, got {other:?}"),
        }
    }

    #[test]
    fn resize_produces_filter_wrapper() {
        let job = plan_to_job(
            &plan_with(vec![Op::Resize {
                width: 64,
                height: 32,
                mode: ResizeMode::Default,
            }]),
            &empty_ctx(),
        )
        .unwrap();
        let out = job.outputs.values().next().unwrap();
        match &out.all[0].input {
            TrackInput::Filter(f) => {
                // `video.` prefix — the pipeline's dag uses it to
                // route to FilterKind::Video.
                assert_eq!(f.filter, "video.resize");
                assert_eq!(f.params["width"], 64);
                assert_eq!(f.params["height"], 32);
            }
            other => panic!("expected filter, got {other:?}"),
        }
    }

    #[test]
    fn chain_order_preserved() {
        let job = plan_to_job(
            &plan_with(vec![
                Op::Resize {
                    width: 64,
                    height: 64,
                    mode: ResizeMode::Default,
                },
                Op::Blur {
                    radius: 2,
                    sigma: 1.0,
                },
            ]),
            &empty_ctx(),
        )
        .unwrap();
        let out = job.outputs.values().next().unwrap();
        // Ops apply outside-in on the recursive TrackInput: the
        // innermost node is the source; the outermost filter is the
        // last op in source order (blur).
        let outer = match &out.all[0].input {
            TrackInput::Filter(f) => f,
            other => panic!("expected outer filter, got {other:?}"),
        };
        assert_eq!(outer.filter, "video.blur");
        let inner = match outer.input.as_ref() {
            TrackInput::Filter(f) => f,
            other => panic!("expected inner filter, got {other:?}"),
        };
        assert_eq!(inner.filter, "video.resize");
    }

    #[test]
    fn quality_and_strip_land_in_codec_params() {
        let job = plan_to_job(&plan_with(vec![Op::Quality(85), Op::Strip]), &empty_ctx()).unwrap();
        let track = &job.outputs.values().next().unwrap().all[0];
        assert_eq!(track.params["quality"], 85);
        assert_eq!(track.params["strip_metadata"], true);
    }

    #[test]
    fn resize_mode_tag_emitted_in_filter_params() {
        // Each ResizeMode round-trips through the JSON params as a
        // stable lowercase tag. Future executor passes can branch off
        // these without us re-shaping the IR.
        for (mode, tag) in [
            (ResizeMode::Default, "default"),
            (ResizeMode::Force, "force"),
            (ResizeMode::Fill, "fill"),
            (ResizeMode::Shrink, "shrink"),
            (ResizeMode::Grow, "grow"),
            (ResizeMode::Percent, "percent"),
            (ResizeMode::Area, "area"),
        ] {
            let job = plan_to_job(
                &plan_with(vec![Op::Resize {
                    width: 100,
                    height: 100,
                    mode,
                }]),
                &empty_ctx(),
            )
            .unwrap();
            let track = &job.outputs.values().next().unwrap().all[0];
            let f = match &track.input {
                TrackInput::Filter(f) => f,
                other => panic!("expected resize filter, got {other:?}"),
            };
            assert_eq!(f.params["mode"], tag, "mode={mode:?}");
        }
    }

    #[test]
    fn thumbnail_unrolls_into_resize_plus_strip() {
        let job = plan_to_job(
            &plan_with(vec![Op::Thumbnail {
                width: 200,
                height: 200,
                mode: ResizeMode::Fill,
            }]),
            &empty_ctx(),
        )
        .unwrap();
        let track = &job.outputs.values().next().unwrap().all[0];
        // Resize node present with mode=fill.
        let f = match &track.input {
            TrackInput::Filter(f) => f,
            other => panic!("expected outer resize filter, got {other:?}"),
        };
        assert_eq!(f.filter, "video.resize");
        assert_eq!(f.params["mode"], "fill");
        // And strip_metadata also set on the codec params side.
        assert_eq!(track.params["strip_metadata"], true);
    }

    #[test]
    fn define_with_value_lands_in_codec_params() {
        let job = plan_to_job(
            &plan_with(vec![Op::Define {
                key: "jpeg:dct-method".into(),
                value: Some("float".into()),
            }]),
            &empty_ctx(),
        )
        .unwrap();
        let track = &job.outputs.values().next().unwrap().all[0];
        assert_eq!(track.params["jpeg:dct-method"], "float");
    }

    #[test]
    fn define_bare_key_becomes_json_true() {
        let job = plan_to_job(
            &plan_with(vec![Op::Define {
                key: "png:strip-comments".into(),
                value: None,
            }]),
            &empty_ctx(),
        )
        .unwrap();
        let track = &job.outputs.values().next().unwrap().all[0];
        assert_eq!(track.params["png:strip-comments"], true);
    }

    #[test]
    fn multiple_defines_all_preserved() {
        // Ensures sequential `-define` flags don't shadow each other.
        let job = plan_to_job(
            &plan_with(vec![
                Op::Define {
                    key: "jpeg:dct-method".into(),
                    value: Some("float".into()),
                },
                Op::Define {
                    key: "jpeg:optimize-coding".into(),
                    value: Some("true".into()),
                },
                Op::Define {
                    key: "webp:lossless".into(),
                    value: None,
                },
            ]),
            &empty_ctx(),
        )
        .unwrap();
        let track = &job.outputs.values().next().unwrap().all[0];
        assert_eq!(track.params["jpeg:dct-method"], "float");
        assert_eq!(track.params["jpeg:optimize-coding"], "true");
        assert_eq!(track.params["webp:lossless"], true);
    }

    // ---- codec_for_output coverage ----

    #[test]
    fn unknown_extension_returns_none() {
        // Empty context — no registrations, so every lookup is None.
        let ctx = empty_ctx();
        assert!(codec_for_output(None, "out.jpg", &ctx).is_none());
        assert!(codec_for_output(None, "out.mkv", &ctx).is_none());
        assert!(codec_for_output(None, "out.unknown_ext_xyz", &ctx).is_none());
    }

    #[test]
    fn registry_hit_returns_container_name() {
        // Register a synthetic container under an extension and
        // confirm the resolver picks it up. This is the path every
        // image-format crate rides (qoi, dds, exr, icer, pict, jxs,
        // jxl, jp2, png, qoi, …) once their `register_containers`
        // call lands and the umbrella wires them in.
        let mut ctx = RuntimeContext::new();
        ctx.containers.register_extension("foo", "foo_codec");
        assert_eq!(
            codec_for_output(None, "out.foo", &ctx).as_deref(),
            Some("foo_codec")
        );
        // Case-insensitive on the input filename.
        assert_eq!(
            codec_for_output(None, "OUT.FOO", &ctx).as_deref(),
            Some("foo_codec")
        );
    }

    /// Walk the recursive TrackInput chain and collect every filter
    /// node's name in source order (innermost first → applied first).
    fn collect_filter_names(input: &TrackInput) -> Vec<String> {
        let mut names = Vec::new();
        let mut cur = input;
        while let TrackInput::Filter(f) = cur {
            names.push(f.filter.clone());
            cur = f.input.as_ref();
        }
        names.reverse();
        names
    }

    /// Pull out the filter node matching `name` (first match found).
    fn find_filter<'a>(input: &'a TrackInput, name: &str) -> Option<&'a FilterNode> {
        let mut cur = input;
        while let TrackInput::Filter(f) = cur {
            if f.filter == name {
                return Some(f);
            }
            cur = f.input.as_ref();
        }
        None
    }

    #[test]
    fn sharpen_wires_to_video_sharpen_factory() {
        let job = plan_to_job(
            &plan_with(vec![Op::Sharpen {
                radius: 2,
                sigma: 1.0,
            }]),
            &empty_ctx(),
        )
        .unwrap();
        let track = &job.outputs.values().next().unwrap().all[0];
        let f = find_filter(&track.input, "video.sharpen").expect("video.sharpen node");
        assert_eq!(f.params["radius"], 2);
        assert!((f.params["sigma"].as_f64().unwrap() - 1.0).abs() < 1e-6);
    }

    #[test]
    fn unsharp_wires_full_params() {
        let job = plan_to_job(
            &plan_with(vec![Op::Unsharp {
                radius: 3,
                sigma: 1.5,
                amount: 0.8,
                threshold: 7,
            }]),
            &empty_ctx(),
        )
        .unwrap();
        let track = &job.outputs.values().next().unwrap().all[0];
        let f = find_filter(&track.input, "video.unsharp").expect("video.unsharp node");
        assert_eq!(f.params["radius"], 3);
        assert!((f.params["sigma"].as_f64().unwrap() - 1.5).abs() < 1e-6);
        assert!((f.params["amount"].as_f64().unwrap() - 0.8).abs() < 1e-6);
        assert_eq!(f.params["threshold"], 7);
    }

    #[test]
    fn gamma_wires_value_key() {
        let job = plan_to_job(&plan_with(vec![Op::Gamma { value: 2.2 }]), &empty_ctx()).unwrap();
        let track = &job.outputs.values().next().unwrap().all[0];
        let f = find_filter(&track.input, "video.gamma").expect("video.gamma node");
        assert!((f.params["value"].as_f64().unwrap() - 2.2).abs() < 1e-6);
    }

    #[test]
    fn brightness_contrast_wires_both_keys() {
        let job = plan_to_job(
            &plan_with(vec![Op::BrightnessContrast {
                brightness: 10.0,
                contrast: -5.0,
            }]),
            &empty_ctx(),
        )
        .unwrap();
        let track = &job.outputs.values().next().unwrap().all[0];
        let f = find_filter(&track.input, "video.brightness-contrast")
            .expect("video.brightness-contrast node");
        assert!((f.params["brightness"].as_f64().unwrap() - 10.0).abs() < 1e-6);
        assert!((f.params["contrast"].as_f64().unwrap() - (-5.0)).abs() < 1e-6);
    }

    #[test]
    fn contrast_step_translates_to_factor() {
        let job = plan_to_job(&plan_with(vec![Op::Contrast { delta: 1 }]), &empty_ctx()).unwrap();
        let track = &job.outputs.values().next().unwrap().all[0];
        let f = find_filter(&track.input, "video.contrast").expect("video.contrast node");
        // delta=1 → 5% contrast bump.
        assert!((f.params["value"].as_f64().unwrap() - 5.0).abs() < 1e-6);
    }

    #[test]
    fn modulate_translates_hue_to_degrees() {
        // IM hue=200 (max) → +180°; hue=0 → -180°; hue=100 → 0°.
        let job = plan_to_job(
            &plan_with(vec![Op::Modulate {
                brightness: 100.0,
                saturation: 100.0,
                hue: 200.0,
            }]),
            &empty_ctx(),
        )
        .unwrap();
        let track = &job.outputs.values().next().unwrap().all[0];
        let f = find_filter(&track.input, "video.modulate").expect("video.modulate node");
        assert!((f.params["brightness"].as_f64().unwrap() - 100.0).abs() < 1e-6);
        assert!((f.params["saturation"].as_f64().unwrap() - 100.0).abs() < 1e-6);
        assert!((f.params["hue_degrees"].as_f64().unwrap() - 180.0).abs() < 1e-6);
    }

    #[test]
    fn level_wires_all_three_endpoints() {
        let job = plan_to_job(
            &plan_with(vec![Op::Level {
                black: 16,
                gamma: 1.2,
                white: 235,
            }]),
            &empty_ctx(),
        )
        .unwrap();
        let track = &job.outputs.values().next().unwrap().all[0];
        let f = find_filter(&track.input, "video.level").expect("video.level node");
        assert_eq!(f.params["black"], 16);
        assert!((f.params["gamma"].as_f64().unwrap() - 1.2).abs() < 1e-6);
        assert_eq!(f.params["white"], 235);
    }

    #[test]
    fn normalize_wires_empty_params() {
        let job = plan_to_job(&plan_with(vec![Op::Normalize]), &empty_ctx()).unwrap();
        let track = &job.outputs.values().next().unwrap().all[0];
        let f = find_filter(&track.input, "video.normalize").expect("video.normalize node");
        // Defaults — empty object.
        assert!(f.params.as_object().unwrap().is_empty());
    }

    #[test]
    fn threshold_wires_value() {
        let job =
            plan_to_job(&plan_with(vec![Op::Threshold { value: 200 }]), &empty_ctx()).unwrap();
        let track = &job.outputs.values().next().unwrap().all[0];
        let f = find_filter(&track.input, "video.threshold").expect("video.threshold node");
        assert_eq!(f.params["value"], 200);
    }

    #[test]
    fn posterize_wires_levels() {
        let job = plan_to_job(&plan_with(vec![Op::Posterize { levels: 6 }]), &empty_ctx()).unwrap();
        let track = &job.outputs.values().next().unwrap().all[0];
        let f = find_filter(&track.input, "video.posterize").expect("video.posterize node");
        assert_eq!(f.params["levels"], 6);
    }

    #[test]
    fn solarize_wires_value() {
        let job = plan_to_job(&plan_with(vec![Op::Solarize { value: 100 }]), &empty_ctx()).unwrap();
        let track = &job.outputs.values().next().unwrap().all[0];
        let f = find_filter(&track.input, "video.solarize").expect("video.solarize node");
        assert_eq!(f.params["value"], 100);
    }

    #[test]
    fn sepia_wires_threshold() {
        let job =
            plan_to_job(&plan_with(vec![Op::Sepia { threshold: 0.8 }]), &empty_ctx()).unwrap();
        let track = &job.outputs.values().next().unwrap().all[0];
        let f = find_filter(&track.input, "video.sepia").expect("video.sepia node");
        assert!((f.params["threshold"].as_f64().unwrap() - 0.8).abs() < 1e-6);
    }

    #[test]
    fn colorspace_gray_wires_grayscale_factory() {
        let job = plan_to_job(
            &plan_with(vec![Op::Colorspace("Gray".into())]),
            &empty_ctx(),
        )
        .unwrap();
        let track = &job.outputs.values().next().unwrap().all[0];
        let f = find_filter(&track.input, "video.grayscale").expect("video.grayscale node");
        assert_eq!(f.params["preserve_alpha"], true);
    }

    #[test]
    fn colorspace_rgb_is_pure_passthrough() {
        let job =
            plan_to_job(&plan_with(vec![Op::Colorspace("RGB".into())]), &empty_ctx()).unwrap();
        let track = &job.outputs.values().next().unwrap().all[0];
        // No filter wrapping the source — `Op::Colorspace("rgb")` is
        // a recorded no-op.
        match &track.input {
            TrackInput::Source(_) => {}
            other => panic!("expected raw source, got {other:?}"),
        }
    }

    #[test]
    fn rotate_wires_video_rotate_factory() {
        let job = plan_to_job(&plan_with(vec![Op::Rotate { degrees: 90 }]), &empty_ctx()).unwrap();
        let track = &job.outputs.values().next().unwrap().all[0];
        let f = find_filter(&track.input, "video.rotate").expect("video.rotate node");
        assert_eq!(f.params["degrees"], 90);
    }

    #[test]
    fn flip_flop_wire_independent_factories() {
        let job = plan_to_job(&plan_with(vec![Op::Flip, Op::Flop]), &empty_ctx()).unwrap();
        let track = &job.outputs.values().next().unwrap().all[0];
        let names = collect_filter_names(&track.input);
        assert_eq!(
            names,
            vec!["video.flip".to_string(), "video.flop".to_string()]
        );
    }

    #[test]
    fn crop_wires_xywh() {
        let job = plan_to_job(
            &plan_with(vec![Op::Crop {
                x: 1,
                y: 2,
                w: 10,
                h: 20,
            }]),
            &empty_ctx(),
        )
        .unwrap();
        let track = &job.outputs.values().next().unwrap().all[0];
        let f = find_filter(&track.input, "video.crop").expect("video.crop node");
        assert_eq!(f.params["x"], 1);
        assert_eq!(f.params["y"], 2);
        assert_eq!(f.params["width"], 10);
        assert_eq!(f.params["height"], 20);
    }

    #[test]
    fn negate_wires_video_negate_factory() {
        let job = plan_to_job(&plan_with(vec![Op::Negate]), &empty_ctx()).unwrap();
        let track = &job.outputs.values().next().unwrap().all[0];
        find_filter(&track.input, "video.negate").expect("video.negate node");
    }

    /// `Op::Extent` lowers to a `video.extent` FilterNode carrying
    /// width / height / signed offsets / RGBA background — the four
    /// keys the `oxideav-image-filter` `Extent` factory consumes.
    #[test]
    fn extent_wires_width_height_offsets_background() {
        let job = plan_to_job(
            &plan_with(vec![Op::Extent {
                width: 200,
                height: 150,
                x: -10,
                y: 20,
                bg: [12, 34, 56, 200],
            }]),
            &empty_ctx(),
        )
        .unwrap();
        let track = &job.outputs.values().next().unwrap().all[0];
        let f = find_filter(&track.input, "video.extent").expect("video.extent node");
        assert_eq!(f.params["width"], 200);
        assert_eq!(f.params["height"], 150);
        assert_eq!(f.params["offset_x"], -10);
        assert_eq!(f.params["offset_y"], 20);
        let bg = f.params["background"].as_array().expect("background array");
        assert_eq!(bg.len(), 4);
        assert_eq!(bg[0], 12);
        assert_eq!(bg[1], 34);
        assert_eq!(bg[2], 56);
        assert_eq!(bg[3], 200);
    }

    /// End-to-end shape check: build a plan with a sharpen op,
    /// translate to a Job, then take the JSON params we emitted and
    /// hand them to the **real** image-filter factory (registered in
    /// the test ctx). The factory must accept them — confirming the
    /// CLI side speaks the same JSON dialect the registry expects.
    ///
    /// NOTE: this verifies the JSON-dialect contract once the new
    /// image-filter factories land in the published registry. The
    /// published 0.1.1 image-filter only registers `blur`, `edge`,
    /// `resize`; the round-next factories (sharpen / gamma / etc.)
    /// are on master and pending publish. We skip the assertion in
    /// the standalone-published path to avoid flapping; inside the
    /// workspace (where image-filter is path-patched to in-tree),
    /// the assertion runs and proves the contract.
    #[test]
    fn sharpen_emitted_params_are_accepted_by_image_filter_registry() {
        use oxideav_core::{PixelFormat, PortSpec, TimeBase};

        let job = plan_to_job(
            &plan_with(vec![Op::Sharpen {
                radius: 1,
                sigma: 0.5,
            }]),
            &empty_ctx(),
        )
        .unwrap();
        let track = &job.outputs.values().next().unwrap().all[0];
        let f = find_filter(&track.input, "video.sharpen").expect("video.sharpen node");

        // Stand up a real ctx with the image-filter factories wired.
        let mut filter_ctx = RuntimeContext::new();
        oxideav_image_filter::register(&mut filter_ctx);

        // Skip the registry assertion when the build saw an older
        // image-filter that hasn't published the round-next factories
        // yet. The `wrap()`-produced JSON is the same in either case.
        if !filter_ctx.filters.contains("sharpen") {
            return;
        }

        // Pretend we're the executor: ask the registry to build a
        // StreamFilter from the JSON params we just emitted.
        let inputs = [PortSpec::video(
            "in",
            4,
            4,
            PixelFormat::Rgba,
            TimeBase::new(1, 30),
        )];
        filter_ctx
            .filters
            .make("video.sharpen", &f.params, &inputs)
            .expect("registry must accept the JSON params we emit");
    }

    /// Same shape check for every newly-wired round-next factory.
    /// Driving them all through one test keeps the test count modest
    /// while still catching the "we emitted a key the factory doesn't
    /// recognise" class of bugs.
    ///
    /// Same caveat as `sharpen_emitted_params_…`: skipped on
    /// standalone-published until image-filter publishes the new
    /// factories.
    #[test]
    fn every_round_next_op_round_trips_through_image_filter_registry() {
        use oxideav_core::{PixelFormat, PortSpec, TimeBase};

        // A representative input port; most factories ignore the dim
        // values but Crop reads `width`/`height` so we use 16x16.
        let make_inputs = |w: u32, h: u32, fmt: PixelFormat| {
            [PortSpec::video("in", w, h, fmt, TimeBase::new(1, 30))]
        };

        let mut filter_ctx = RuntimeContext::new();
        oxideav_image_filter::register(&mut filter_ctx);

        // Skip the registry-build assertion when the linked image-filter
        // pre-dates the round-next factories. JSON-shape coverage (the
        // other tests) still runs.
        if !filter_ctx.filters.contains("sharpen") {
            return;
        }

        // (op, expected filter-id, inputs)
        let cases: Vec<(Op, &str, [PortSpec; 1])> = vec![
            (
                Op::Sharpen {
                    radius: 1,
                    sigma: 0.5,
                },
                "video.sharpen",
                make_inputs(4, 4, PixelFormat::Rgba),
            ),
            (
                Op::Unsharp {
                    radius: 1,
                    sigma: 0.5,
                    amount: 1.0,
                    threshold: 0,
                },
                "video.unsharp",
                make_inputs(4, 4, PixelFormat::Rgba),
            ),
            (
                Op::Gamma { value: 1.8 },
                "video.gamma",
                make_inputs(4, 4, PixelFormat::Rgba),
            ),
            (
                Op::BrightnessContrast {
                    brightness: 10.0,
                    contrast: -5.0,
                },
                "video.brightness-contrast",
                make_inputs(4, 4, PixelFormat::Rgba),
            ),
            (
                Op::Contrast { delta: 1 },
                "video.contrast",
                make_inputs(4, 4, PixelFormat::Rgba),
            ),
            (
                Op::Sepia { threshold: 0.8 },
                "video.sepia",
                make_inputs(4, 4, PixelFormat::Rgb24),
            ),
            (
                Op::Modulate {
                    brightness: 100.0,
                    saturation: 100.0,
                    hue: 100.0,
                },
                "video.modulate",
                make_inputs(4, 4, PixelFormat::Rgba),
            ),
            (
                Op::Level {
                    black: 16,
                    gamma: 1.2,
                    white: 235,
                },
                "video.level",
                make_inputs(4, 4, PixelFormat::Gray8),
            ),
            (
                Op::Normalize,
                "video.normalize",
                make_inputs(4, 4, PixelFormat::Gray8),
            ),
            (
                Op::Threshold { value: 128 },
                "video.threshold",
                make_inputs(4, 4, PixelFormat::Gray8),
            ),
            (
                Op::Posterize { levels: 4 },
                "video.posterize",
                make_inputs(4, 4, PixelFormat::Gray8),
            ),
            (
                Op::Solarize { value: 100 },
                "video.solarize",
                make_inputs(4, 4, PixelFormat::Gray8),
            ),
            (
                Op::Colorspace("Gray".into()),
                "video.grayscale",
                make_inputs(4, 4, PixelFormat::Rgba),
            ),
            (
                Op::Rotate { degrees: 90 },
                "video.rotate",
                make_inputs(4, 4, PixelFormat::Rgba),
            ),
            (Op::Flip, "video.flip", make_inputs(4, 4, PixelFormat::Rgba)),
            (Op::Flop, "video.flop", make_inputs(4, 4, PixelFormat::Rgba)),
            (
                Op::Crop {
                    x: 1,
                    y: 1,
                    w: 2,
                    h: 2,
                },
                "video.crop",
                make_inputs(16, 16, PixelFormat::Rgba),
            ),
            (
                Op::Negate,
                "video.negate",
                make_inputs(4, 4, PixelFormat::Rgba),
            ),
        ];

        // Round-after-next factories. Skip them as a group when the
        // linked image-filter pre-dates the vignette/colorize/equalize/
        // auto-gamma additions (published 0.1.1 only registers up to the
        // round-prev set). We piggy-back on the same skip pattern as
        // above — if `vignette` isn't in the registry, none of the new
        // four are.
        let mut later_cases: Vec<(Op, &str, [PortSpec; 1])> = Vec::new();
        if filter_ctx.filters.contains("vignette") {
            later_cases.push((
                Op::Vignette {
                    radius: 50.0,
                    sigma: 25.0,
                    x: 0.5,
                    y: 0.5,
                },
                "video.vignette",
                make_inputs(4, 4, PixelFormat::Rgba),
            ));
            later_cases.push((
                Op::Colorize {
                    color: [200, 100, 50, 255],
                    amount: 0.4,
                },
                "video.colorize",
                make_inputs(4, 4, PixelFormat::Rgba),
            ));
            later_cases.push((
                Op::Equalize,
                "video.equalize",
                make_inputs(4, 4, PixelFormat::Gray8),
            ));
            later_cases.push((
                Op::AutoGamma,
                "video.auto-gamma",
                make_inputs(4, 4, PixelFormat::Gray8),
            ));
        }
        let cases: Vec<(Op, &str, [PortSpec; 1])> = cases.into_iter().chain(later_cases).collect();

        for (op, expected_name, inputs) in cases {
            let job = plan_to_job(&plan_with(vec![op.clone()]), &empty_ctx()).unwrap();
            let track = &job.outputs.values().next().unwrap().all[0];
            let f = find_filter(&track.input, expected_name)
                .unwrap_or_else(|| panic!("expected node {expected_name} for {op:?}"));
            filter_ctx
                .filters
                .make(expected_name, &f.params, &inputs)
                .unwrap_or_else(|e| {
                    panic!(
                        "registry rejected emitted params for {op:?}: {e:?} \
                         (json: {})",
                        f.params
                    )
                });
        }
    }

    /// True end-to-end on a 4x4 RGBA fixture: synthesise a frame, run
    /// it through `image_filter::Sharpen` directly to get the expected
    /// output bytes, then walk the same JSON params through the
    /// registry-built filter and compare. This locks down the
    /// "factory takes the same params we emit" contract at a pixel
    /// level, not just at a build-success level.
    ///
    /// Skipped on standalone-published until the image-filter sharpen
    /// factory publishes (today's published 0.1.1 doesn't have it).
    #[test]
    fn sharpen_4x4_pixel_match_through_registry() {
        use oxideav_core::{
            filter::FilterContext, Frame, PixelFormat, PortSpec, Result as CoreResult, TimeBase,
            VideoFrame, VideoPlane,
        };
        use oxideav_image_filter::{ImageFilter, Sharpen, VideoStreamParams};

        // 4x4 RGBA fixture with an obvious horizontal edge so sharpen
        // produces a visible delta.
        let make_frame = || {
            let mut data = Vec::with_capacity(4 * 4 * 4);
            for _y in 0..4 {
                for x in 0..4 {
                    let v = if x < 2 { 60 } else { 200 };
                    data.extend_from_slice(&[v, v, v, 255]);
                }
            }
            VideoFrame {
                pts: None,
                planes: vec![VideoPlane { stride: 16, data }],
            }
        };

        // Reference: call the library directly with the same params
        // the CLI translates `-sharpen 1x0.5` to.
        let reference = Sharpen::new(1, 0.5)
            .apply(
                &make_frame(),
                VideoStreamParams {
                    format: PixelFormat::Rgba,
                    width: 4,
                    height: 4,
                },
            )
            .expect("library Sharpen apply");

        // Through the registry: build the plan, translate to a Job,
        // grab the JSON, build the filter via the registry, run.
        let plan = ConvertPlan {
            input: "in.png".into(),
            input_pages: None,
            ops: vec![Op::Sharpen {
                radius: 1,
                sigma: 0.5,
            }],
            output: "out.png".into(),
            output_template: None,
            help: false,
            ping: false,
            probe: false,
            probe_json: false,
            probe_watch: false,
            mesh3d_options: Default::default(),
        };
        let job = plan_to_job(&plan, &empty_ctx()).unwrap();
        let track = &job.outputs.values().next().unwrap().all[0];
        let f = find_filter(&track.input, "video.sharpen").expect("video.sharpen node");

        let mut filter_ctx = RuntimeContext::new();
        oxideav_image_filter::register(&mut filter_ctx);

        // Skip when the linked image-filter pre-dates the sharpen
        // factory (published 0.1.1 only registers blur/edge/resize).
        if !filter_ctx.filters.contains("sharpen") {
            return;
        }

        let inputs = [PortSpec::video(
            "in",
            4,
            4,
            PixelFormat::Rgba,
            TimeBase::new(1, 30),
        )];
        let mut built = filter_ctx
            .filters
            .make("video.sharpen", &f.params, &inputs)
            .expect("factory build");

        struct Collect {
            out: Vec<Frame>,
        }
        impl FilterContext for Collect {
            fn emit(&mut self, _port: usize, frame: Frame) -> CoreResult<()> {
                self.out.push(frame);
                Ok(())
            }
        }
        let mut col = Collect { out: Vec::new() };
        built
            .push(&mut col, 0, &Frame::Video(make_frame()))
            .expect("filter push");
        let registry_out = match col.out.into_iter().next().unwrap() {
            Frame::Video(v) => v,
            other => panic!("expected video frame, got {other:?}"),
        };

        // Pixel-exact match: same params, same input → same output.
        assert_eq!(
            registry_out.planes[0].data, reference.planes[0].data,
            "registry-built sharpen must match library Sharpen byte-for-byte"
        );
    }

    #[test]
    fn vignette_wires_centre_radius_sigma() {
        let job = plan_to_job(
            &plan_with(vec![Op::Vignette {
                radius: 50.0,
                sigma: 25.0,
                x: 0.5,
                y: 0.5,
            }]),
            &empty_ctx(),
        )
        .unwrap();
        let track = &job.outputs.values().next().unwrap().all[0];
        let f = find_filter(&track.input, "video.vignette").expect("video.vignette node");
        assert!((f.params["x"].as_f64().unwrap() - 0.5).abs() < 1e-6);
        assert!((f.params["y"].as_f64().unwrap() - 0.5).abs() < 1e-6);
        assert!((f.params["radius"].as_f64().unwrap() - 50.0).abs() < 1e-6);
        assert!((f.params["sigma"].as_f64().unwrap() - 25.0).abs() < 1e-6);
    }

    #[test]
    fn colorize_wires_color_array_and_amount() {
        let job = plan_to_job(
            &plan_with(vec![Op::Colorize {
                color: [200, 100, 50, 255],
                amount: 0.4,
            }]),
            &empty_ctx(),
        )
        .unwrap();
        let track = &job.outputs.values().next().unwrap().all[0];
        let f = find_filter(&track.input, "video.colorize").expect("video.colorize node");
        let arr = f.params["color"].as_array().expect("color is array");
        assert_eq!(arr.len(), 4);
        assert_eq!(arr[0], 200);
        assert_eq!(arr[1], 100);
        assert_eq!(arr[2], 50);
        assert_eq!(arr[3], 255);
        assert!((f.params["amount"].as_f64().unwrap() - 0.4).abs() < 1e-6);
    }

    #[test]
    fn equalize_wires_empty_params() {
        let job = plan_to_job(&plan_with(vec![Op::Equalize]), &empty_ctx()).unwrap();
        let track = &job.outputs.values().next().unwrap().all[0];
        let f = find_filter(&track.input, "video.equalize").expect("video.equalize node");
        assert!(f.params.as_object().unwrap().is_empty());
    }

    #[test]
    fn auto_gamma_wires_empty_params() {
        let job = plan_to_job(&plan_with(vec![Op::AutoGamma]), &empty_ctx()).unwrap();
        let track = &job.outputs.values().next().unwrap().all[0];
        let f = find_filter(&track.input, "video.auto-gamma").expect("video.auto-gamma node");
        assert!(f.params.as_object().unwrap().is_empty());
    }

    #[test]
    fn long_chain_preserves_source_order() {
        // Sanity that all the new filters interleave with existing
        // ones in source order (innermost = first parsed).
        let job = plan_to_job(
            &plan_with(vec![
                Op::Resize {
                    width: 64,
                    height: 64,
                    mode: ResizeMode::Default,
                },
                Op::Sharpen {
                    radius: 1,
                    sigma: 0.5,
                },
                Op::Gamma { value: 1.8 },
                Op::Negate,
            ]),
            &empty_ctx(),
        )
        .unwrap();
        let track = &job.outputs.values().next().unwrap().all[0];
        let names = collect_filter_names(&track.input);
        assert_eq!(
            names,
            vec![
                "video.resize".to_string(),
                "video.sharpen".to_string(),
                "video.gamma".to_string(),
                "video.negate".to_string(),
            ]
        );
    }

    /// `Op::Trim` lowers to a `video.trim` FilterNode carrying the
    /// captured fuzz tolerance. The factory infers the reference
    /// background from the input's `(0, 0)` pixel when no explicit
    /// `background` array is forwarded (IM's default behaviour).
    #[test]
    fn trim_wires_fuzz_value() {
        let job = plan_to_job(&plan_with(vec![Op::Trim { fuzz: 17 }]), &empty_ctx()).unwrap();
        let track = &job.outputs.values().next().unwrap().all[0];
        let f = find_filter(&track.input, "video.trim").expect("video.trim node");
        assert_eq!(f.params["fuzz"], 17);
        // No background override → factory falls back to corner pixel.
        assert!(f.params.get("background").is_none());
    }

    /// Default `Op::Trim { fuzz: 0 }` is the canonical no-fuzz exact-
    /// match shape — pin it explicitly so a future refactor that
    /// switches the default representation surfaces here, not on the
    /// pipeline executor.
    #[test]
    fn trim_default_fuzz_lowers_to_zero() {
        let job = plan_to_job(&plan_with(vec![Op::Trim { fuzz: 0 }]), &empty_ctx()).unwrap();
        let track = &job.outputs.values().next().unwrap().all[0];
        let f = find_filter(&track.input, "video.trim").expect("video.trim node");
        assert_eq!(f.params["fuzz"], 0);
    }

    /// `Op::Roll` lowers to a `video.roll` FilterNode carrying the
    /// signed `dx`/`dy` shift values. The image-filter factory
    /// recognises both `dx`/`dy` and the `x`/`y` aliases; we forward
    /// the canonical pair.
    #[test]
    fn roll_lowers_to_video_roll() {
        let job = plan_to_job(&plan_with(vec![Op::Roll { dx: 5, dy: -10 }]), &empty_ctx()).unwrap();
        let track = &job.outputs.values().next().unwrap().all[0];
        let f = find_filter(&track.input, "video.roll").expect("video.roll node");
        assert_eq!(f.params["dx"], 5);
        assert_eq!(f.params["dy"], -10);
    }

    #[test]
    fn format_override_uses_registry() {
        let mut ctx = RuntimeContext::new();
        ctx.containers.register_extension("bar", "bar_codec");
        // -format BAR with output that ends in something else still
        // lands on bar_codec.
        assert_eq!(
            codec_for_output(Some("BAR"), "out.unrelated", &ctx).as_deref(),
            Some("bar_codec")
        );
        // -format with no matching registration → None (caller can
        // surface a "use -format CODEC" hint).
        assert!(codec_for_output(Some("nothing"), "out.unrelated", &ctx).is_none());
    }

    // ---- plan_to_render3d_job coverage (Phase C-3b) ----

    use crate::op::{CameraSpec as OpCameraSpec, LightSpec as OpLightSpec};

    fn render3d_plan(input: &str, output: &str, ops: Vec<Op>, opts: Mesh3DOptions) -> ConvertPlan {
        ConvertPlan {
            input: input.into(),
            input_pages: None,
            ops,
            output: output.into(),
            output_template: None,
            help: false,
            ping: false,
            probe: false,
            probe_json: false,
            probe_watch: false,
            mesh3d_options: opts,
        }
    }

    /// Bare `convert cube.stl out.png` lowers to a single Render3D
    /// source with the scanline backend, no surrounding filters, and
    /// the default 1024×1024 canvas with transparent black background.
    /// `opts` carries every key the renderer needs at default values.
    #[test]
    fn render3d_defaults_emit_scanline_source_at_1024x1024() {
        let plan = render3d_plan("cube.stl", "out.png", vec![], Mesh3DOptions::default());
        let job = plan_to_render3d_job(&plan, &empty_ctx()).unwrap();
        assert_eq!(job.outputs.len(), 1);
        let out = job.outputs.values().next().unwrap();
        assert_eq!(out.all.len(), 1);
        let track = &out.all[0];
        let node = match &track.input {
            TrackInput::Render3D(n) => n,
            other => panic!("expected Render3D, got {other:?}"),
        };
        assert_eq!(node.source, "cube.stl");
        assert_eq!(node.backend, RENDER3D_DEFAULT_BACKEND);
        assert_eq!(node.backend, "scanline");
        assert_eq!(node.opts["width"], 1024);
        assert_eq!(node.opts["height"], 1024);
        let bg = node.opts["background"]
            .as_array()
            .expect("background array");
        assert_eq!(bg.len(), 4);
        for c in bg {
            assert_eq!(c.as_u64(), Some(0));
        }
        assert_eq!(node.opts["shading"], "flat");
        assert_eq!(node.opts["projection"], "perspective");
        assert!((node.opts["fov_deg"].as_f64().unwrap() - 60.0).abs() < 1e-6);
        assert_eq!(node.opts["aa"], 1);
        // Default light spec: 45°/45°/1.0 — matches LightSpec::default_light
        // on the renderer side.
        let l = &node.opts["light"];
        assert!((l["azimuth_deg"].as_f64().unwrap() - 45.0).abs() < 1e-6);
        assert!((l["elevation_deg"].as_f64().unwrap() - 45.0).abs() < 1e-6);
        assert!((l["intensity"].as_f64().unwrap() - 1.0).abs() < 1e-6);
        // Auto-frame camera = null.
        assert!(node.opts["camera"].is_null());
    }

    /// `-resize WxH` seeds the render canvas dims on the opts struct
    /// and does NOT survive as a `video.resize` filter node — the
    /// renderer produces the canvas at the requested size directly.
    #[test]
    fn resize_is_absorbed_into_render_dims_not_emitted_as_filter() {
        let plan = render3d_plan(
            "scene.gltf",
            "out.png",
            vec![Op::Resize {
                width: 800,
                height: 600,
                mode: ResizeMode::Default,
            }],
            Mesh3DOptions::default(),
        );
        let job = plan_to_render3d_job(&plan, &empty_ctx()).unwrap();
        let track = &job.outputs.values().next().unwrap().all[0];
        let node = match &track.input {
            TrackInput::Render3D(n) => n,
            other => panic!("expected Render3D directly (resize absorbed), got {other:?}"),
        };
        assert_eq!(node.opts["width"], 800);
        assert_eq!(node.opts["height"], 600);
    }

    /// `-background COLOR` seeds the render canvas clear colour on the
    /// opts struct and does NOT survive as a separate node.
    #[test]
    fn background_op_is_absorbed_into_render_bg() {
        let plan = render3d_plan(
            "cube.stl",
            "out.png",
            vec![Op::Background([12, 34, 56, 200])],
            Mesh3DOptions::default(),
        );
        let job = plan_to_render3d_job(&plan, &empty_ctx()).unwrap();
        let track = &job.outputs.values().next().unwrap().all[0];
        let node = match &track.input {
            TrackInput::Render3D(n) => n,
            other => panic!("expected Render3D directly, got {other:?}"),
        };
        let bg = node.opts["background"]
            .as_array()
            .expect("background array");
        assert_eq!(bg[0], 12);
        assert_eq!(bg[1], 34);
        assert_eq!(bg[2], 56);
        assert_eq!(bg[3], 200);
    }

    /// `-bg` on `Mesh3DOptions` wins over a preceding `-background`
    /// op (mirrors `mesh3d_render::pick_render_bg`'s precedence).
    #[test]
    fn bg_option_overrides_background_op() {
        let opts = Mesh3DOptions {
            bg: Some([10, 20, 30, 255]),
            ..Mesh3DOptions::default()
        };
        let plan = render3d_plan(
            "cube.stl",
            "out.png",
            vec![Op::Background([99, 99, 99, 255])],
            opts,
        );
        let job = plan_to_render3d_job(&plan, &empty_ctx()).unwrap();
        let node = match &job.outputs.values().next().unwrap().all[0].input {
            TrackInput::Render3D(n) => n,
            other => panic!("expected Render3D, got {other:?}"),
        };
        let bg = node.opts["background"].as_array().unwrap();
        assert_eq!(bg[0], 10);
        assert_eq!(bg[1], 20);
        assert_eq!(bg[2], 30);
        assert_eq!(bg[3], 255);
    }

    /// Every `Mesh3DRenderMode` round-trips through the opts JSON via a
    /// stable lowercase tag.
    #[test]
    fn render_mode_round_trips_through_opts() {
        let cases = [
            (Mesh3DRenderMode::Flat, "flat"),
            (Mesh3DRenderMode::Wireframe, "wireframe"),
            (Mesh3DRenderMode::Gouraud, "gouraud"),
            (Mesh3DRenderMode::Phong, "phong"),
            (Mesh3DRenderMode::NormalDebug, "normal-debug"),
            (Mesh3DRenderMode::DepthDebug, "depth-debug"),
        ];
        for (mode, tag) in cases {
            let opts = Mesh3DOptions {
                render_mode: Some(mode),
                ..Mesh3DOptions::default()
            };
            let plan = render3d_plan("cube.stl", "out.png", vec![], opts);
            let job = plan_to_render3d_job(&plan, &empty_ctx()).unwrap();
            let node = match &job.outputs.values().next().unwrap().all[0].input {
                TrackInput::Render3D(n) => n,
                other => panic!("expected Render3D, got {other:?}"),
            };
            assert_eq!(node.opts["shading"], tag, "mode={mode:?}");
        }
    }

    /// Projection mode round-trips between `Mesh3DOptions::projection`
    /// and the opts JSON.
    #[test]
    fn projection_mode_round_trips_through_opts() {
        for (mode, tag) in [
            (ProjectionMode::Perspective, "perspective"),
            (ProjectionMode::Orthographic, "orthographic"),
        ] {
            let opts = Mesh3DOptions {
                projection: Some(mode),
                ..Mesh3DOptions::default()
            };
            let plan = render3d_plan("cube.stl", "out.png", vec![], opts);
            let job = plan_to_render3d_job(&plan, &empty_ctx()).unwrap();
            let node = match &job.outputs.values().next().unwrap().all[0].input {
                TrackInput::Render3D(n) => n,
                other => panic!("expected Render3D, got {other:?}"),
            };
            assert_eq!(node.opts["projection"], tag, "mode={mode:?}");
        }
    }

    /// `-light A,E,I` lands on opts as a three-key sub-object.
    #[test]
    fn light_override_round_trips_through_opts() {
        let opts = Mesh3DOptions {
            light: Some(OpLightSpec {
                azimuth_deg: 12.0,
                elevation_deg: 34.0,
                intensity: 0.75,
            }),
            ..Mesh3DOptions::default()
        };
        let plan = render3d_plan("cube.stl", "out.png", vec![], opts);
        let job = plan_to_render3d_job(&plan, &empty_ctx()).unwrap();
        let node = match &job.outputs.values().next().unwrap().all[0].input {
            TrackInput::Render3D(n) => n,
            other => panic!("expected Render3D, got {other:?}"),
        };
        let l = &node.opts["light"];
        assert!((l["azimuth_deg"].as_f64().unwrap() - 12.0).abs() < 1e-6);
        assert!((l["elevation_deg"].as_f64().unwrap() - 34.0).abs() < 1e-6);
        assert!((l["intensity"].as_f64().unwrap() - 0.75).abs() < 1e-6);
    }

    /// `-camera E,A,D` lands on opts as a three-key sub-object; absence
    /// stays `null`.
    #[test]
    fn camera_override_round_trips_through_opts() {
        let opts = Mesh3DOptions {
            camera: Some(OpCameraSpec {
                elevation_deg: 30.0,
                azimuth_deg: 45.0,
                distance: 1.5,
            }),
            ..Mesh3DOptions::default()
        };
        let plan = render3d_plan("cube.stl", "out.png", vec![], opts);
        let job = plan_to_render3d_job(&plan, &empty_ctx()).unwrap();
        let node = match &job.outputs.values().next().unwrap().all[0].input {
            TrackInput::Render3D(n) => n,
            other => panic!("expected Render3D, got {other:?}"),
        };
        let c = &node.opts["camera"];
        assert!((c["elevation_deg"].as_f64().unwrap() - 30.0).abs() < 1e-6);
        assert!((c["azimuth_deg"].as_f64().unwrap() - 45.0).abs() < 1e-6);
        assert!((c["distance"].as_f64().unwrap() - 1.5).abs() < 1e-6);
    }

    /// `-fov DEGREES` round-trips through opts as a float.
    #[test]
    fn fov_override_round_trips_through_opts() {
        let opts = Mesh3DOptions {
            fov_deg: Some(35.0),
            ..Mesh3DOptions::default()
        };
        let plan = render3d_plan("cube.stl", "out.png", vec![], opts);
        let job = plan_to_render3d_job(&plan, &empty_ctx()).unwrap();
        let node = match &job.outputs.values().next().unwrap().all[0].input {
            TrackInput::Render3D(n) => n,
            other => panic!("expected Render3D, got {other:?}"),
        };
        assert!((node.opts["fov_deg"].as_f64().unwrap() - 35.0).abs() < 1e-6);
    }

    /// `-aa N` round-trips through opts; the helper clamps to `1..=8`
    /// to match the renderer's documented range.
    #[test]
    fn aa_round_trips_through_opts_and_clamps_to_range() {
        for in_aa in [1_u32, 2, 4, 8] {
            let opts = Mesh3DOptions {
                aa: Some(in_aa),
                ..Mesh3DOptions::default()
            };
            let plan = render3d_plan("cube.stl", "out.png", vec![], opts);
            let job = plan_to_render3d_job(&plan, &empty_ctx()).unwrap();
            let node = match &job.outputs.values().next().unwrap().all[0].input {
                TrackInput::Render3D(n) => n,
                other => panic!("expected Render3D, got {other:?}"),
            };
            assert_eq!(node.opts["aa"], in_aa, "in_aa={in_aa}");
        }
        // Out-of-range values clamp to the [1, 8] window: 0 → 1, 9 → 8.
        for (in_aa, expected) in [(0_u32, 1_u32), (9, 8), (100, 8)] {
            let opts = Mesh3DOptions {
                aa: Some(in_aa),
                ..Mesh3DOptions::default()
            };
            let plan = render3d_plan("cube.stl", "out.png", vec![], opts);
            let job = plan_to_render3d_job(&plan, &empty_ctx()).unwrap();
            let node = match &job.outputs.values().next().unwrap().all[0].input {
                TrackInput::Render3D(n) => n,
                other => panic!("expected Render3D, got {other:?}"),
            };
            assert_eq!(
                node.opts["aa"], expected,
                "in_aa={in_aa} expected clamp→{expected}"
            );
        }
    }

    /// Post-rasterisation ops (rotate / flip / negate / sharpen / strip
    /// / quality) survive as filter nodes wrapping the Render3D source,
    /// preserving source order from innermost (= first parsed) to
    /// outermost (= last parsed).
    #[test]
    fn post_raster_ops_wrap_the_render3d_source_in_source_order() {
        let plan = render3d_plan(
            "scene.gltf",
            "out.png",
            vec![
                Op::Rotate { degrees: 90 },
                Op::Negate,
                Op::Sharpen {
                    radius: 1,
                    sigma: 0.5,
                },
                Op::Strip,
                Op::Quality(85),
            ],
            Mesh3DOptions::default(),
        );
        let job = plan_to_render3d_job(&plan, &empty_ctx()).unwrap();
        let track = &job.outputs.values().next().unwrap().all[0];
        // Quality + strip land on codec params, not as filter nodes.
        assert_eq!(track.params["quality"], 85);
        assert_eq!(track.params["strip_metadata"], true);
        // Walk the chain: outermost (last in source order) is sharpen,
        // then negate, then rotate, then the Render3D leaf.
        let outer = match &track.input {
            TrackInput::Filter(f) => f,
            other => panic!("expected outer filter, got {other:?}"),
        };
        assert_eq!(outer.filter, "video.sharpen");
        let mid = match outer.input.as_ref() {
            TrackInput::Filter(f) => f,
            other => panic!("expected mid filter, got {other:?}"),
        };
        assert_eq!(mid.filter, "video.negate");
        let inner = match mid.input.as_ref() {
            TrackInput::Filter(f) => f,
            other => panic!("expected inner filter, got {other:?}"),
        };
        assert_eq!(inner.filter, "video.rotate");
        assert_eq!(inner.params["degrees"], 90);
        // The recursion bottoms out at a Render3D node (not Source).
        match inner.input.as_ref() {
            TrackInput::Render3D(n) => {
                assert_eq!(n.source, "scene.gltf");
                assert_eq!(n.backend, "scanline");
            }
            other => panic!("expected Render3D leaf, got {other:?}"),
        }
    }

    /// `Op::Thumbnail` strips metadata and lets the renderer absorb the
    /// resize half — no `video.resize` filter survives on a 3D→raster
    /// job.
    #[test]
    fn thumbnail_absorbs_resize_and_sets_strip_metadata() {
        let plan = render3d_plan(
            "cube.stl",
            "out.png",
            vec![Op::Thumbnail {
                width: 256,
                height: 256,
                mode: ResizeMode::Fill,
            }],
            Mesh3DOptions::default(),
        );
        let job = plan_to_render3d_job(&plan, &empty_ctx()).unwrap();
        let track = &job.outputs.values().next().unwrap().all[0];
        // No video.resize filter because thumbnail absorbed. Strip
        // metadata lands on codec params per IM's contract, AND the
        // requested geometry seeds the render canvas — previously the
        // dims were dropped and the canvas silently stayed at the
        // 1024×1024 default.
        assert_eq!(track.params["strip_metadata"], true);
        match &track.input {
            TrackInput::Render3D(node) => {
                assert_eq!(node.opts["width"], 256);
                assert_eq!(node.opts["height"], 256);
            }
            other => panic!("expected Render3D (no surviving filters), got {other:?}"),
        }
    }

    /// Mixed `-resize` / `-thumbnail` geometry: the LAST one in source
    /// order wins the canvas, mirroring the last-resize-wins rule.
    #[test]
    fn last_geometry_op_wins_render_canvas() {
        let plan = render3d_plan(
            "cube.stl",
            "out.png",
            vec![
                Op::Resize {
                    width: 512,
                    height: 512,
                    mode: ResizeMode::Default,
                },
                Op::Thumbnail {
                    width: 256,
                    height: 128,
                    mode: ResizeMode::Fill,
                },
            ],
            Mesh3DOptions::default(),
        );
        let job = plan_to_render3d_job(&plan, &empty_ctx()).unwrap();
        let node = match &job.outputs.values().next().unwrap().all[0].input {
            TrackInput::Render3D(n) => n,
            other => panic!("expected Render3D, got {other:?}"),
        };
        assert_eq!(node.opts["width"], 256);
        assert_eq!(node.opts["height"], 128);
    }

    /// The output codec resolves through the same `ContainerRegistry`
    /// lookup `plan_to_job` uses — register an extension, observe the
    /// resolved codec id on the track.
    #[test]
    fn render3d_output_codec_resolves_via_registry() {
        let mut ctx = RuntimeContext::new();
        ctx.containers.register_extension("png", "png_codec");
        let plan = render3d_plan("scene.gltf", "out.png", vec![], Mesh3DOptions::default());
        let job = plan_to_render3d_job(&plan, &ctx).unwrap();
        let track = &job.outputs.values().next().unwrap().all[0];
        assert_eq!(track.codec.as_deref(), Some("png_codec"));
    }

    /// `-format FMT` override seeds the codec params bag plus the
    /// registry-resolved codec; mirrors `plan_to_job`'s shape.
    #[test]
    fn render3d_format_override_threads_through_to_codec_params() {
        let mut ctx = RuntimeContext::new();
        ctx.containers.register_extension("jpg", "jpeg_codec");
        let plan = render3d_plan(
            "scene.gltf",
            "out.unrelated",
            vec![Op::Format("jpg".into())],
            Mesh3DOptions::default(),
        );
        let job = plan_to_render3d_job(&plan, &ctx).unwrap();
        let track = &job.outputs.values().next().unwrap().all[0];
        assert_eq!(track.codec.as_deref(), Some("jpeg_codec"));
        assert_eq!(track.params["format"], "jpg");
    }

    /// `-define KEY=VALUE` lands on codec params on the 3D path same as
    /// on the regular pipeline path.
    #[test]
    fn render3d_define_lands_on_codec_params() {
        let plan = render3d_plan(
            "cube.stl",
            "out.png",
            vec![
                Op::Define {
                    key: "png:strip-comments".into(),
                    value: None,
                },
                Op::Define {
                    key: "jpeg:dct-method".into(),
                    value: Some("float".into()),
                },
            ],
            Mesh3DOptions::default(),
        );
        let job = plan_to_render3d_job(&plan, &empty_ctx()).unwrap();
        let track = &job.outputs.values().next().unwrap().all[0];
        assert_eq!(track.params["png:strip-comments"], true);
        assert_eq!(track.params["jpeg:dct-method"], "float");
    }

    /// The full opts struct round-trips through `serde_json` (every
    /// field is present, every field is a value the consumer's typed
    /// deserialiser can read).
    #[test]
    fn render3d_opts_carry_every_documented_field() {
        let plan = render3d_plan("cube.stl", "out.png", vec![], Mesh3DOptions::default());
        let job = plan_to_render3d_job(&plan, &empty_ctx()).unwrap();
        let node = match &job.outputs.values().next().unwrap().all[0].input {
            TrackInput::Render3D(n) => n,
            other => panic!("expected Render3D, got {other:?}"),
        };
        for key in [
            "width",
            "height",
            "background",
            "shading",
            "projection",
            "fov_deg",
            "light",
            "camera",
            "aa",
        ] {
            assert!(
                node.opts.get(key).is_some(),
                "opts is missing documented field {key:?} — full opts: {}",
                node.opts
            );
        }
    }

    // ---- schema-validation + JSON round-trip guarantees ----

    /// Every op the planner knows how to lower, exercised once. Kept
    /// as a function so both the validation sweep and the round-trip
    /// sweep iterate the same corpus — adding an `Op` variant without
    /// extending this list is caught by the exhaustive `match` in
    /// `plan_to_job` going non-exhaustive, and adding it HERE keeps
    /// the guarantees covering it.
    fn representative_op_corpus() -> Vec<Vec<Op>> {
        vec![
            vec![],
            vec![Op::Resize {
                width: 64,
                height: 32,
                mode: ResizeMode::Fill,
            }],
            vec![Op::Thumbnail {
                width: 128,
                height: 128,
                mode: ResizeMode::Default,
            }],
            vec![Op::Define {
                key: "jpeg:dct-method".into(),
                value: Some("float".into()),
            }],
            vec![Op::Blur {
                radius: 2,
                sigma: 1.0,
            }],
            vec![Op::Edge { radius: 1 }],
            vec![Op::Colors {
                count: 16,
                dither: Dither::FloydSteinberg,
            }],
            vec![Op::Format("png".into()), Op::Quality(85), Op::Strip],
            vec![Op::Density(300), Op::Background([1, 2, 3, 4])],
            vec![Op::Alpha(crate::op::AlphaOp::Remove)],
            vec![Op::Rotate { degrees: -270 }, Op::Flip, Op::Flop],
            vec![Op::Crop {
                x: 1,
                y: 2,
                w: 3,
                h: 4,
            }],
            vec![Op::Extent {
                width: 10,
                height: 20,
                x: -1,
                y: 1,
                bg: [0, 0, 0, 255],
            }],
            vec![Op::Negate],
            vec![Op::Sharpen {
                radius: 1,
                sigma: 0.5,
            }],
            vec![Op::Unsharp {
                radius: 2,
                sigma: 1.0,
                amount: 0.8,
                threshold: 3,
            }],
            vec![Op::Gamma { value: 2.2 }],
            vec![Op::BrightnessContrast {
                brightness: 10.0,
                contrast: -5.0,
            }],
            vec![Op::Contrast { delta: 2 }],
            vec![Op::Sepia { threshold: 0.8 }],
            vec![Op::Modulate {
                brightness: 110.0,
                saturation: 90.0,
                hue: 150.0,
            }],
            vec![Op::Level {
                black: 16,
                gamma: 1.1,
                white: 235,
            }],
            vec![Op::Normalize, Op::Equalize, Op::AutoGamma],
            vec![Op::Threshold { value: 128 }],
            vec![Op::Posterize { levels: 4 }],
            vec![Op::Solarize { value: 200 }],
            vec![Op::Colorspace("gray".into())],
            vec![Op::Colorspace("srgb".into())],
            vec![Op::Vignette {
                radius: 50.0,
                sigma: 25.0,
                x: 0.5,
                y: 0.5,
            }],
            vec![Op::Colorize {
                color: [200, 100, 50, 255],
                amount: 0.4,
            }],
            vec![Op::Trim { fuzz: 12 }],
            vec![Op::Roll { dx: -3, dy: 7 }],
            // A deep mixed chain — closest to real-world flag soup.
            vec![
                Op::Density(150),
                Op::Resize {
                    width: 800,
                    height: 600,
                    mode: ResizeMode::Shrink,
                },
                Op::Background([255, 255, 255, 255]),
                Op::Alpha(crate::op::AlphaOp::Off),
                Op::Sharpen {
                    radius: 1,
                    sigma: 0.5,
                },
                Op::Colorspace("gray".into()),
                Op::Colors {
                    count: 2,
                    dither: Dither::FloydSteinberg,
                },
                Op::Quality(92),
                Op::Strip,
                Op::Define {
                    key: "png:compression-level".into(),
                    value: Some("9".into()),
                },
            ],
        ]
    }

    /// GUARANTEE: every job the planner emits passes the pipeline
    /// schema's own `Job::validate()`. `plan_to_job` also enforces
    /// this at runtime now — the test documents the invariant and
    /// keeps the corpus honest.
    #[test]
    fn every_emitted_job_passes_pipeline_validation() {
        for (i, ops) in representative_op_corpus().into_iter().enumerate() {
            let job = plan_to_job(&plan_with(ops.clone()), &empty_ctx())
                .unwrap_or_else(|e| panic!("corpus[{i}] {ops:?} failed to plan: {e}"));
            job.validate()
                .unwrap_or_else(|e| panic!("corpus[{i}] {ops:?} emitted invalid job: {e}"));
        }
    }

    /// GUARANTEE: every emitted job survives a full trip through the
    /// pipeline's JSON dialect — serialise, re-parse, re-serialise,
    /// byte-identical. This is what makes `convert`-planned jobs
    /// storable / replayable as `oxideav run` documents.
    #[test]
    fn every_emitted_job_round_trips_through_job_json() {
        let mut ctx = RuntimeContext::new();
        ctx.containers.register_extension("jpg", "mjpeg");
        for (i, ops) in representative_op_corpus().into_iter().enumerate() {
            let job = plan_to_job(&plan_with(ops.clone()), &ctx).unwrap();
            let first = job.to_json_pretty();
            let reparsed = Job::from_json(&first).unwrap_or_else(|e| {
                panic!("corpus[{i}] {ops:?} JSON did not re-parse: {e}\n{first}")
            });
            reparsed
                .validate()
                .unwrap_or_else(|e| panic!("corpus[{i}] re-parsed job invalid: {e}"));
            let second = reparsed.to_json_pretty();
            assert_eq!(
                first, second,
                "corpus[{i}] {ops:?}: JSON round-trip not stable"
            );
        }
    }

    /// Same two guarantees for the 3D→raster planner: validation +
    /// byte-stable JSON round-trip, across default and fully-specified
    /// `Mesh3DOptions` plus post-raster op chains.
    #[test]
    fn every_emitted_render3d_job_validates_and_round_trips() {
        let option_corpus = vec![
            Mesh3DOptions::default(),
            Mesh3DOptions {
                render_mode: Some(Mesh3DRenderMode::Phong),
                projection: Some(ProjectionMode::Orthographic),
                fov_deg: Some(35.0),
                light: Some(crate::op::LightSpec {
                    azimuth_deg: 12.0,
                    elevation_deg: 34.0,
                    intensity: 0.75,
                }),
                camera: Some(crate::op::CameraSpec {
                    elevation_deg: 30.0,
                    azimuth_deg: 45.0,
                    distance: 1.5,
                }),
                bg: Some([10, 20, 30, 255]),
                aa: Some(4),
                ..Mesh3DOptions::default()
            },
        ];
        let op_corpus = vec![
            vec![],
            vec![
                Op::Resize {
                    width: 800,
                    height: 600,
                    mode: ResizeMode::Default,
                },
                Op::Background([255, 255, 255, 255]),
                Op::Rotate { degrees: 90 },
                Op::Negate,
                Op::Quality(85),
                Op::Strip,
            ],
        ];
        for opts in &option_corpus {
            for ops in &op_corpus {
                let plan = render3d_plan("scene.gltf", "out.png", ops.clone(), opts.clone());
                let job = plan_to_render3d_job(&plan, &empty_ctx()).unwrap();
                job.validate()
                    .unwrap_or_else(|e| panic!("render3d job invalid: {e} (ops={ops:?})"));
                let first = job.to_json_pretty();
                let reparsed = Job::from_json(&first)
                    .unwrap_or_else(|e| panic!("render3d JSON did not re-parse: {e}\n{first}"));
                let second = reparsed.to_json_pretty();
                assert_eq!(first, second, "render3d JSON round-trip not stable");
                // The Render3D node itself must survive structurally:
                // source / backend / opts equal after the trip.
                let orig = match &job.outputs.values().next().unwrap().all[0].input.leaf() {
                    TrackInput::Render3D(n) => (*n).clone(),
                    other => panic!("expected Render3D leaf, got {other:?}"),
                };
                let back = match &reparsed.outputs.values().next().unwrap().all[0]
                    .input
                    .leaf()
                {
                    TrackInput::Render3D(n) => (*n).clone(),
                    other => panic!("expected Render3D leaf after re-parse, got {other:?}"),
                };
                assert_eq!(orig, back, "Render3D node changed across the round-trip");
            }
        }
    }

    /// An empty input path can never reach the executor: the planner's
    /// validation hook rejects it with the pipeline's typed error
    /// instead of letting an unopenable "" source fail deep inside a
    /// run.
    #[test]
    fn empty_input_path_is_rejected_at_plan_time() {
        let mut plan = plan_with(vec![]);
        plan.input = String::new();
        let err = plan_to_job(&plan, &empty_ctx()).expect_err("empty source must not plan");
        let msg = format!("{err}");
        assert!(msg.contains("empty `from`"), "got: {msg}");
    }
}