insta360-stitch-cli 0.0.4

A command-line tool that stitches Insta360 dual-fisheye photos and videos
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
use std::cell::RefCell;
use std::fs::File;
use std::io::{BufReader, BufWriter, Read, Write};
use std::path::{Path, PathBuf};
use std::process::{Command, ExitCode, Stdio};
use std::sync::mpsc::{channel, sync_channel, Receiver, RecvError, SendError, Sender, SyncSender};

use clap::{Parser, Subcommand, ValueEnum};
use image::{ImageFormat, ImageReader};
use insta360_stitch::math::{apply, cross, dot, mul, norm, normalize, transpose, Mat3, IDENTITY};
#[cfg(feature = "gpu")]
use insta360_stitch::GpuStitcher;
use insta360_stitch::{
    band_offset, check_different_files, check_photo_layout, frame_times_us, gps_track,
    merge_bracket, preview_rgb, read_imu, read_preview, read_trailer, stitch_photo_band_with,
    uses_recorded_frame_times, video_sample_times, write_spherical_mp4_file, DenoiseSettings,
    Denoiser, FrameFlow, FrameFusion, FrameRotation, GpuMode, Image, Imu, LensModel, PhotoSeam,
    Stabilization, Stitcher, Trailer, MAX_VIDEO_WIDTH,
};
use jpeg_encoder::{rgb_to_ycbcr, Encoder, ImageBuffer, JpegColorType};

mod bullet_time_cut;
use bullet_time_cut::bullet_time_cut;

type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;

/// Stitches Insta360 dual-fisheye photos (.insp) and videos (.insv) into equirectangular panoramas.
#[derive(Parser)]
#[command(version)]
struct Cli {
    /// The number of threads for the stitch. The default is one thread for each CPU core. Use fewer threads to keep
    /// CPU time for other services on the same computer. The seam flow and the colour fusion of a video use 1 or 2 of
    /// these threads (with 1 thread, the video uses 2). The JPEG encode of a photo uses one more thread
    #[arg(long, global = true, value_parser = clap::value_parser!(u16).range(1..))]
    threads: Option<u16>,
    /// The use of the GPU for the photo stitch, the video stitch and the denoise, as "Image Processing Acceleration" in
    /// Insta360 Studio. `auto` uses the GPU when there is one, and the processor when the GPU cannot do the work. `off`
    /// always uses the processor
    #[arg(long, global = true, value_enum, default_value_t = GpuArg::Auto)]
    gpu: GpuArg,
    #[command(subcommand)]
    command: Commands,
}

#[derive(Subcommand)]
// The video command has many options. The command is parsed one time, thus a large variant costs nothing.
#[allow(clippy::large_enum_variant)]
enum Commands {
    /// Writes the GPS track of a .insv or .insp file as a GPX file, one point for each second
    Gpx {
        input: PathBuf,
        output: PathBuf,
        /// Write the positions of the camera. By default, the positions are smoothed as in Insta360 Studio
        #[arg(long)]
        raw: bool,
    },
    /// Shows the data in the trailer of a file, as JSON
    Info { file: PathBuf },
    /// Stitches a .insp photo into an equirectangular JPEG
    Photo {
        input: PathBuf,
        output: PathBuf,
        #[arg(long, default_value_t = 95, value_parser = clap::value_parser!(u8).range(1..=100))]
        quality: u8,
        /// Take the level of the horizon (which way is down) from the IMU data of this other photo, and not from
        /// the IMU data of the input. For the photos of an HDR bracket, use the first photo for all of them (as
        /// Insta360 Studio did in our test): then the exposures line up
        #[arg(long, value_name = "PHOTO")]
        level_from: Option<PathBuf>,
        /// One more photo of the same HDR bracket (repeat it for each photo). The input and these photos are merged
        /// into one photo before the stitch, as the "Merged Photo" export of Insta360 Studio. A bracket of 2 photos
        /// is not supported
        #[arg(long = "bracket", value_name = "PHOTO")]
        bracket: Vec<PathBuf>,
    },
    /// Writes the small preview that the camera stitched, as a JPEG
    Preview { input: PathBuf, output: PathBuf },
    /// Stitches a .insv video into an equirectangular MP4 with 360 video metadata. This command needs ffmpeg and ffprobe
    Video {
        input: PathBuf,
        output: PathBuf,
        #[command(flatten)]
        options: VideoOptions,
    },
}

#[derive(clap::Args)]
struct VideoOptions {
    /// The output width in pixels, a multiple of 4 from 16 to 16384. The default is two times the width of one
    /// lens stream
    #[arg(long, value_parser = parse_width)]
    width: Option<usize>,
    /// lock: level horizon and fixed view direction (as Insta360 Studio, Direction Lock off). follow: level horizon,
    /// the view follows the smoothed heading of the camera (as Insta360 Studio, Direction Lock on). off: the
    /// orientation of the first frame for all frames. The default is lock, and follow for a TimeShift recording (as
    /// Insta360 Studio)
    #[arg(long, value_enum)]
    stabilization: Option<StabilizationArg>,
    /// For a Bullet Time clip: export it as Insta360 Studio does. A flat 16:9 view that looks along the stick (the view
    /// turns with the camera), and each frame at 29.97 fps (slow motion), without audio. `--width` sets the width of
    /// the flat video. The view has no seam flow: the stick is on the seam, and the flow pulls it into the image. Not
    /// with `--stabilization`
    #[arg(long, conflicts_with = "stabilization")]
    bullet_time_view: bool,
    /// Encode as the Insta360 Studio export does: HEVC at the bitrate of the .insv file, a key frame each second,
    /// and no B-frames. libx265 by default, `--studio-encode=hevc_nvenc` for the NVIDIA encoder of Studio.
    /// `--preset` sets the speed of libx265. Not with `--encoder` or `--crf`
    #[arg(long, num_args = 0..=1, default_missing_value = "libx265", conflicts_with_all = ["encoder", "crf"])]
    studio_encode: Option<StudioEncoder>,
    /// The ffmpeg video encoder, for example libx264, libx265, hevc_nvenc, hevc_vaapi or hevc_qsv. A hardware
    /// encoder is much faster at 8K, for example hevc_nvenc on an NVIDIA GPU (approximately 2 times faster).
    /// Give it the quality options of docs/hardware-encoding.md, else ffmpeg uses its low default bitrate
    #[arg(long, default_value = "libx264")]
    encoder: String,
    /// The quality for libx264 and libx265 (lower is better)
    #[arg(long, default_value_t = 20, value_parser = clap::value_parser!(u8).range(0..=51))]
    crf: u8,
    /// The speed preset for libx264 and libx265
    #[arg(long, default_value = "medium")]
    preset: String,
    /// One more ffmpeg output option for the encoder. Repeat it for each word, for example
    /// --encoder-arg=-b:v --encoder-arg=80M
    #[arg(long = "encoder-arg", allow_hyphen_values = true)]
    encoder_args: Vec<String>,
    /// The ffmpeg hardware decoder (-hwaccel), for example auto, vaapi, qsv, cuda or d3d11va. Use auto for a faster
    /// video: ffmpeg uses the CPU decoder when it finds no hardware decoder. `--decoder-arg` options (for example
    /// -hwaccel_device) apply to the decoder that ffmpeg selects
    #[arg(long)]
    hwaccel: Option<String>,
    /// The threads of the ffmpeg decoder for each lens stream. More threads use much more memory: at 8K,
    /// approximately 0.6 GB with 2 threads and 2 GB or more with the ffmpeg default
    #[arg(long, default_value_t = 2, value_parser = clap::value_parser!(u16).range(1..))]
    decoder_threads: u16,
    /// One more ffmpeg input option for the decoder. Repeat it for each word, for example
    /// --decoder-arg=-hwaccel_device --decoder-arg=/dev/dri/renderD129
    #[arg(long = "decoder-arg", allow_hyphen_values = true)]
    decoder_args: Vec<String>,
    /// Do not correct the rolling shutter. By default, each sensor row gets the rotation at its own time, as in
    /// Insta360 Studio
    #[arg(long)]
    no_rolling_shutter: bool,
    /// Do not align the two lenses at the seam with the seam flow. By default, each frame gets the DIS flow of the
    /// Insta360 photo export, as the mean of the frames t - 2 to t + 2 (Insta360 Studio uses a neural flow for
    /// videos). Without it, the stitch is faster and uses less memory
    #[arg(long)]
    no_seam_flow: bool,
    /// Do not match the colours of the two lenses at the seam. By default, each frame gets the colour fusion of the
    /// Insta360 export ("Chromatic Calibration"), calculated from that frame. Without it, the stitch is faster
    #[arg(long)]
    no_color_fusion: bool,
    /// The time of the first frame to stitch, in seconds. A frame is in the range when its time (frame number
    /// divided by the frame rate) is from `--start` to `--end`, with 1 ms of tolerance, as the Studio export of a
    /// time range. The default is the start of the video
    #[arg(long, value_parser = parse_seconds)]
    start: Option<f64>,
    /// The time of the last frame to stitch, in seconds (see `--start`). The default is the end of the video. The
    /// audio gets the same range
    #[arg(long, value_parser = parse_seconds)]
    end: Option<f64>,
    /// Do not cut the start and the end that the camera tells to cut. Some recordings give a time (for example 3 s)
    /// to remove at each end, and Insta360 Studio removes it by default. Thus, by default, the stitch does not
    /// include these frames at an end that has no `--start` or `--end`. For a Bullet Time clip, Studio cuts to the part
    /// in which the camera turns, and this option also keeps all frames of it
    #[arg(long)]
    no_camera_trim: bool,
    /// Filter the noise of the stitched video with the block denoise (the temporal filter of Insta360 Studio for
    /// videos of the cameras that do not filter in time). Each frame is averaged with the 3 frames before and after
    /// it, along the motion. It runs on the GPU when there is one, else on the processor, where it is slow at 8K. It
    /// needs approximately 7 frames of memory. As Studio, it does not filter a video that the camera chip already filtered
    /// in time (`mctf_process_type` 2)
    #[arg(long)]
    denoise: bool,
    /// The strength of `--denoise`, as a factor of the default (1.0). A larger factor filters more noise and changes
    /// the pixels more. Insta360 Studio filters a video with a high ISO more strongly: if you set the ISO by hand,
    /// the default grows with it (see docs/cli.md). From more than 0 up to 16
    #[arg(long, requires = "denoise", value_parser = parse_strength)]
    denoise_strength: Option<f32>,
    /// The ffmpeg program: a name on the PATH or a path
    #[arg(long, default_value = "ffmpeg")]
    ffmpeg: String,
    /// The ffprobe program: a name on the PATH or a path
    #[arg(long, default_value = "ffprobe")]
    ffprobe: String,
}

/// The encoder of `--studio-encode`.
#[derive(Clone, Copy, Debug, PartialEq, ValueEnum)]
enum StudioEncoder {
    #[value(name = "libx265")]
    Libx265,
    #[value(name = "hevc_nvenc")]
    HevcNvenc,
}

#[derive(Clone, Copy, ValueEnum)]
enum GpuArg {
    Auto,
    Off,
}

impl From<GpuArg> for GpuMode {
    fn from(value: GpuArg) -> Self {
        match value {
            GpuArg::Auto => GpuMode::Auto,
            GpuArg::Off => GpuMode::Off,
        }
    }
}

#[derive(Clone, Copy, ValueEnum)]
enum StabilizationArg {
    Lock,
    Follow,
    Off,
}

impl From<StabilizationArg> for Stabilization {
    fn from(value: StabilizationArg) -> Self {
        match value {
            StabilizationArg::Lock => Stabilization::Lock,
            StabilizationArg::Follow => Stabilization::Follow,
            StabilizationArg::Off => Stabilization::Off,
        }
    }
}

/// The threads of the stitch (`None`: one for each core) and of the work that runs beside it for a video: the seam
/// flow and the colour fusion. With `--threads`, that work gets its threads from that number: half, 1 or 2.
fn split_threads(threads: Option<u16>, side_work: bool) -> (Option<usize>, usize) {
    match (threads.map(usize::from), side_work) {
        (Some(n), true) => {
            let flow = (n / 2).clamp(1, 2);
            (Some((n - flow).max(1)), flow)
        }
        (threads, _) => (threads, 2),
    }
}

fn main() -> ExitCode {
    let cli = Cli::parse();
    let side_work = matches!(
        &cli.command,
        Commands::Video { options, .. } if !options.no_seam_flow || !options.no_color_fusion
    );
    let (threads, flow_threads) = split_threads(cli.threads, side_work);
    if let Some(threads) = threads {
        // The first use of the global pool is after this. Thus, this call cannot fail.
        rayon::ThreadPoolBuilder::new()
            .num_threads(threads)
            .build_global()
            .expect("the thread pool is not in use yet");
    }
    let gpu = GpuMode::from(cli.gpu);
    let result = match cli.command {
        Commands::Gpx { input, output, raw } => gpx(&input, &output, !raw),
        Commands::Info { file } => info(&file),
        Commands::Photo {
            input,
            output,
            quality,
            level_from,
            bracket,
        } => photo(
            &input,
            &output,
            quality,
            level_from.as_deref(),
            &bracket,
            gpu,
        ),
        Commands::Preview { input, output } => preview(&input, &output),
        Commands::Video {
            input,
            output,
            options,
        } => video(&input, &output, &options, flow_threads, gpu),
    };
    match result {
        Ok(()) => ExitCode::SUCCESS,
        Err(error) => {
            eprintln!("insta360-stitch: {error}");
            ExitCode::FAILURE
        }
    }
}

fn trailer_of(path: &Path) -> Result<Trailer> {
    Ok(read_trailer(&mut BufReader::new(File::open(path)?))?)
}

fn gpx(input: &Path, output: &Path, smooth: bool) -> Result<()> {
    check_output(input, output)?;
    let trailer = trailer_of(input)?;
    let fixes = trailer.gps.ok_or("the file has no GPS data")?;
    let track = gps_track(&fixes, trailer.gps_start_ms, smooth);
    // As Studio, which writes no GPX file then.
    if track.is_empty() {
        return Err("the file has no GPS position after the start of the recording".into());
    }
    let gpx = insta360_stitch::gpx(&track);
    write_atomically(output, |out| Ok(out.write_all(gpx.as_bytes())?))
}

fn info(path: &Path) -> Result<()> {
    let stitcher = Stitcher::new(trailer_of(path)?);
    let trailer = &stitcher.trailer;
    let offset = &trailer.offset;
    let json = serde_json::json!({
        "stitchable": stitcher.unsupported_reason().is_none(),
        "reason": stitcher.unsupported_reason(),
        "lensType": offset[15] as u32 & 0xff,
        "offsetState": u64::from(trailer.offset_state),
        "subMediaType": trailer.sub_media_type.map(u64::from),
        "iso": trailer.iso,
        "calibration": { "width": offset[13], "height": offset[14] },
        "localTime": trailer.local_time,
        "firstFrameUs": trailer.first_frame_us,
        "imuSamples": trailer.imu.as_ref().map_or(0, |imu| imu.len()),
        "flickerSpansMs": trailer.flicker_spans_ms(),
        "preview": trailer.preview_size().map(|(width, height)| serde_json::json!({ "width": width, "height": height })),
    });
    println!("{}", serde_json::to_string_pretty(&json)?);
    Ok(())
}

/// The number of output rows that the CLI stitches at one time on the processor.
const BAND_ROWS: usize = 64;
/// The number of output rows of a band on the GPU. Each band waits for the GPU: on a Mali GPU (Pixel 7), bands of 64
/// rows made the stitch of a 72 MP photo 1.3 s slower.
#[cfg(feature = "gpu")]
const GPU_BAND_ROWS: usize = 256;

/// The RGB rows that the JPEG encoder reads. The encoder reads the rows in sequence.
/// For a photo, a second thread stitches one band of rows at a time while the encoder writes the band before it.
/// Thus, the CLI does not keep the full output in memory.
enum Rows<'a> {
    Plain {
        rgb: &'a [u8],
        width: usize,
        height: usize,
    },
    Stitched {
        width: usize,
        height: usize,
        /// The stitched bands in sequence (the first row and the rows), or the stitch error.
        bands: Receiver<insta360_stitch::Result<(usize, Vec<u8>)>>,
        /// Gives the used band buffers back to the stitch thread.
        used: Sender<Vec<u8>>,
        /// The band that the encoder reads now.
        band: RefCell<(usize, Vec<u8>)>,
        /// The stitch error. After it, the encoder gets black rows, and the encode fails.
        error: RefCell<Option<Box<dyn std::error::Error>>>,
    },
}

impl<'a> Rows<'a> {
    fn size(&self) -> (usize, usize) {
        match self {
            Rows::Plain { width, height, .. } | Rows::Stitched { width, height, .. } => {
                (*width, *height)
            }
        }
    }

    /// Starts a thread in `scope` that stitches the RGB photo `source` on the processor in bands of BAND_ROWS
    /// rows, and gives the rows of these bands. The thread stops after the last band, after an error, or when the
    /// rows are dropped.
    fn stitched<'scope>(
        scope: &'scope std::thread::Scope<'scope, 'a>,
        source: Image<'a>,
        model: &'a LensModel,
        seam: &'a PhotoSeam,
    ) -> Self {
        Rows::bands(
            scope,
            source.width,
            source.height,
            BAND_ROWS,
            move |first, band| stitch_photo_band_with(&source, model, seam, first, band),
        )
    }

    /// As [`Rows::stitched`], with `stitch(first_row, band)` for each band of `band_rows` rows of a `width` x `height`
    /// RGB photo.
    fn bands<'scope>(
        scope: &'scope std::thread::Scope<'scope, 'a>,
        width: usize,
        height: usize,
        band_rows: usize,
        stitch: impl Fn(usize, &mut [u8]) -> insta360_stitch::Result<()> + Send + 'scope,
    ) -> Self {
        // One band in the channel, one band in the encoder and one band in the stitch: the stitch and the encode
        // run at the same time.
        let (send, bands) = sync_channel(1);
        let (used, free) = channel::<Vec<u8>>();
        scope.spawn(move || {
            let row_len = width * 3;
            for first in (0..height).step_by(band_rows) {
                let mut band = free.try_recv().unwrap_or_default();
                band.resize(band_rows.min(height - first) * row_len, 0);
                let result = stitch(first, &mut band);
                let failed = result.is_err();
                if send.send(result.map(|()| (first, band))).is_err() || failed {
                    return;
                }
            }
        });
        Rows::Stitched {
            width,
            height,
            bands,
            used,
            band: RefCell::new((0, Vec::new())),
            error: RefCell::new(None),
        }
    }

    /// The stitch error, if there was one.
    fn check(&self) -> Result<()> {
        match self {
            Rows::Stitched { error, .. } => error.take().map_or(Ok(()), Err),
            Rows::Plain { .. } => Ok(()),
        }
    }
}

impl ImageBuffer for &Rows<'_> {
    fn get_jpeg_color_type(&self) -> JpegColorType {
        JpegColorType::Ycbcr
    }

    fn width(&self) -> u16 {
        self.size().0 as u16
    }

    fn height(&self) -> u16 {
        self.size().1 as u16
    }

    fn fill_buffers(&self, y: u16, buffers: &mut [Vec<u8>; 4]) {
        let width = self.size().0;
        let (y, row_len) = (usize::from(y), width * 3);
        let mut push = |row: &[u8]| {
            for pixel in row.as_chunks::<3>().0 {
                let (luma, cb, cr) = rgb_to_ycbcr(pixel[0], pixel[1], pixel[2]);
                buffers[0].push(luma);
                buffers[1].push(cb);
                buffers[2].push(cr);
            }
        };
        match self {
            Rows::Plain { rgb, .. } => push(&rgb[y * row_len..][..row_len]),
            Rows::Stitched {
                bands,
                used,
                band,
                error,
                ..
            } => {
                let mut band = band.borrow_mut();
                // The encoder asks for the rows in sequence, then for the last row again at the bottom edge.
                while y >= band.0 + band.1.len() / row_len && error.borrow().is_none() {
                    match bands.recv() {
                        Ok(Ok(next)) => {
                            used.send(std::mem::replace(&mut *band, next).1).ok();
                        }
                        Ok(Err(stitch)) => *error.borrow_mut() = Some(stitch.into()),
                        Err(RecvError) => {
                            *error.borrow_mut() = Some("the stitch stopped before the end".into())
                        }
                    }
                }
                if error.borrow().is_some() {
                    push(&vec![0; row_len]);
                } else {
                    push(&band.1[(y - band.0) * row_len..][..row_len]);
                }
            }
        }
    }
}

/// Writes a JPEG with an XMP GPano packet. Other viewers then open it as a 360 panorama.
/// `exif` is the EXIF segment of the source photo (capture time, GPS), without its marker and length.
/// The JPEG goes to a temporary file first. Thus, a stop during the encode does not leave a part of a JPEG at
/// `output`.
fn write_panorama_jpeg(
    output: &Path,
    rows: Rows,
    quality: u8,
    exif: Option<Vec<u8>>,
) -> Result<()> {
    let (width, height) = rows.size();
    if width > usize::from(u16::MAX) || height > usize::from(u16::MAX) {
        return Err(format!(
            "a JPEG cannot be larger than 65535 pixels, the image is {width}x{height}"
        )
        .into());
    }
    write_atomically(output, |out| encode_panorama(out, &rows, quality, exif))
}

/// Encodes the JPEG of `write_panorama_jpeg` to `out`. When the stitch and the encode both fail, it gives the stitch
/// error.
fn encode_panorama(out: impl Write, rows: &Rows, quality: u8, exif: Option<Vec<u8>>) -> Result<()> {
    let (width, height) = rows.size();
    let xmp = format!(
        concat!(
            "http://ns.adobe.com/xap/1.0/\0",
            r#"<x:xmpmeta xmlns:x="adobe:ns:meta/"><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">"#,
            r#"<rdf:Description rdf:about="" xmlns:GPano="http://ns.google.com/photos/1.0/panorama/" "#,
            r#"GPano:ProjectionType="equirectangular" GPano:UsePanoramaViewer="True" "#,
            r#"GPano:FullPanoWidthPixels="{w}" GPano:FullPanoHeightPixels="{h}" "#,
            r#"GPano:CroppedAreaImageWidthPixels="{w}" GPano:CroppedAreaImageHeightPixels="{h}" "#,
            r#"GPano:CroppedAreaLeftPixels="0" GPano:CroppedAreaTopPixels="0" "#,
            // The initial view of the Insta360 Studio export.
            r#"GPano:InitialViewVerticalFOVDegrees="95" GPano:InitialHorizontalFOVDegrees="100" "#,
            r#"GPano:StitchingSoftware="insta360-stitch"/></rdf:RDF></x:xmpmeta>"#
        ),
        w = width,
        h = height
    );
    let mut encoder = Encoder::new(out, quality);
    if let Some(exif) = exif {
        encoder.add_app_segment(1, exif)?;
    }
    encoder.add_app_segment(1, xmp.into_bytes())?;
    let encoded = encoder.encode_image(rows);
    rows.check()?;
    Ok(encoded?)
}

/// Writes `output` with `write` through a temporary file next to it, then renames it. Thus, a stop or an error does
/// not leave a part of a file at `output`, and an older file stays until the new file is complete.
fn write_atomically(
    output: &Path,
    write: impl FnOnce(&mut BufWriter<File>) -> Result<()>,
) -> Result<()> {
    // A pipe or a device (for example /dev/stdout) has no directory for a temporary file: write to it directly.
    if output.exists() && !output.is_file() {
        let mut out = BufWriter::new(std::fs::OpenOptions::new().write(true).open(output)?);
        write(&mut out)?;
        return Ok(out.flush()?);
    }
    static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
    let mut part = output.as_os_str().to_owned();
    part.push(format!(
        ".{}-{}.part",
        std::process::id(),
        NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
    ));
    // `create_new`: a file or a link that is already at the temporary name is not written over or followed.
    let file = std::fs::OpenOptions::new()
        .write(true)
        .create_new(true)
        .open(&part)?;
    let result = (|| -> Result<()> {
        let mut out = BufWriter::new(file);
        write(&mut out)?;
        out.into_inner().map_err(|e| e.into_error())?.sync_all()?;
        Ok(std::fs::rename(&part, output)?)
    })();
    if result.is_err() {
        std::fs::remove_file(&part).ok();
    }
    result
}

/// The EXIF segment of a JPEG file (the APP1 segment that starts with "Exif\0\0"), without its marker and
/// length. `None` if the file has no EXIF segment before the image data.
fn exif_segment(jpeg: impl Read) -> Option<Vec<u8>> {
    let mut jpeg = BufReader::new(jpeg);
    let mut two = [0u8; 2];
    jpeg.read_exact(&mut two).ok()?;
    if two != [0xff, 0xd8] {
        return None;
    }
    loop {
        let mut marker = [0u8; 2];
        jpeg.read_exact(&mut marker).ok()?;
        // SOS (start of the image data) or not a marker: no more segments.
        if marker[0] != 0xff || marker[1] == 0xda {
            return None;
        }
        jpeg.read_exact(&mut two).ok()?;
        let len = usize::from(u16::from_be_bytes(two)).checked_sub(2)?;
        let mut data = vec![0u8; len];
        jpeg.read_exact(&mut data).ok()?;
        if marker[1] == 0xe1 && data.starts_with(b"Exif\0\0") {
            return Some(data);
        }
    }
}

/// Decodes the JPEG of a .insp file (a usual JPEG with the trailer at the end).
fn decode_photo(path: &Path) -> Result<image::RgbImage> {
    let decoded = ImageReader::with_format(BufReader::new(File::open(path)?), ImageFormat::Jpeg)
        .decode()?
        .into_rgb8();
    check_photo_layout(decoded.width() as usize, decoded.height() as usize)?;
    Ok(decoded)
}

/// Refuses an output that is the input, or that has the extension of a camera file: a slip of the keyboard must not
/// replace a recording.
fn check_output(input: &Path, output: &Path) -> Result<()> {
    check_different_files(input, output)?;
    let extension = output.extension().and_then(|e| e.to_str()).unwrap_or("");
    if ["insv", "insp", "lrv"]
        .iter()
        .any(|e| extension.eq_ignore_ascii_case(e))
    {
        return Err(format!(
            "the output {} has the extension of a camera file; give another output file",
            output.display()
        )
        .into());
    }
    Ok(())
}

fn photo(
    input: &Path,
    output: &Path,
    quality: u8,
    level_from: Option<&Path>,
    bracket: &[PathBuf],
    gpu: GpuMode,
) -> Result<()> {
    check_output(input, output)?;
    // The GPU starts while the photo is decoded: its setup can take half a second.
    #[cfg(feature = "gpu")]
    let gpu = (gpu == GpuMode::Auto).then(|| std::thread::spawn(GpuStitcher::new));
    #[cfg(not(feature = "gpu"))]
    let _ = gpu;
    for other in bracket {
        check_different_files(other, output)
            .map_err(|_| "the output must be a different file than the --bracket photos")?;
    }
    let level = match level_from {
        Some(reference) => {
            check_different_files(reference, output)
                .map_err(|_| "the output must be a different file than the --level-from photo")?;
            let reference = Stitcher::new(trailer_of(reference)?);
            if let Some(why) = reference.unsupported_reason() {
                return Err(format!("the photo for --level-from cannot be used: {why}").into());
            }
            Some(reference.trailer)
        }
        None => None,
    };
    let mut decoded = decode_photo(input)?;
    let mut trailer = trailer_of(input)?;
    let level = if bracket.is_empty() {
        level
    } else {
        Some(level.unwrap_or_else(|| trailer.clone()))
    };
    if !bracket.is_empty() {
        let mut photos = vec![(decoded, trailer)];
        for other in bracket {
            photos.push((decode_photo(other)?, trailer_of(other)?));
        }
        let size = (photos[0].0.width(), photos[0].0.height());
        if photos.iter().any(|(p, _)| (p.width(), p.height()) != size) {
            return Err("the photos of the bracket must have the same size".into());
        }
        let images: Vec<Image> = photos
            .iter()
            .map(|(p, _)| Image {
                width: size.0 as usize,
                height: size.1 as usize,
                channels: 3,
                data: p.as_raw(),
            })
            .collect();
        // The photos of one bracket come from one camera: the calibration of the first photo serves for all.
        let lens = LensModel::new(&photos[0].1, size.1 as usize, IDENTITY)?;
        let merged = merge_bracket(&images, Some(&lens))?;
        drop(images);
        let (_, reference) = photos.swap_remove(merged.reference);
        trailer = reference;
        decoded = image::RgbImage::from_raw(size.0, size.1, merged.data)
            .ok_or("the merged photo has a wrong size")?;
    }
    let mut stitcher = Stitcher::new(trailer);
    if let Some(level) = &level {
        stitcher = stitcher.with_level_of(level);
    }
    let (width, height) = (decoded.width() as usize, decoded.height() as usize);
    let model = stitcher.model(height)?;
    let source = Image {
        width,
        height,
        channels: 3,
        data: decoded.as_raw(),
    };
    let seam = PhotoSeam::new(&source, &model)?;
    // As the video keeps the metadata of its source, the photo keeps its EXIF (capture time, GPS).
    let exif = exif_segment(File::open(input)?);
    #[cfg(feature = "gpu")]
    {
        let gpu = match gpu {
            Some(setup) => setup.join().map_err(|_| "the setup of the GPU stopped")?,
            None => Err(insta360_stitch::Error::Unsupported("--gpu off".into())),
        };
        let on_gpu = gpu.as_ref().map_err(reason).and_then(|gpu| {
            Ok((
                gpu,
                gpu.upload(&source, &model, &seam).map_err(|e| reason(&e))?,
            ))
        });
        match on_gpu {
            Ok((gpu, photo)) => {
                eprintln!("insta360-stitch: photo stitch on the GPU ({})", gpu.name());
                // The GPU has the photo: release it on the processor.
                // shortcut: a GPU error after this point stops the photo (the decoded photo is freed); use --gpu off.
                drop(decoded);
                return std::thread::scope(|scope| {
                    let rows = Rows::bands(scope, width, height, GPU_BAND_ROWS, |first, band| {
                        photo.stitch_band(first, band)
                    });
                    write_panorama_jpeg(output, rows, quality, exif)
                });
            }
            Err(reason) => eprintln!("insta360-stitch: photo stitch on the processor ({reason})"),
        }
    }
    std::thread::scope(|scope| {
        let rows = Rows::stitched(scope, source, &model, &seam);
        write_panorama_jpeg(output, rows, quality, exif)
    })
}

/// Why the GPU does not stitch, on one line: a reason from the GPU driver can have more than one.
#[cfg(feature = "gpu")]
fn reason(error: &insta360_stitch::Error) -> String {
    match error {
        insta360_stitch::Error::Unsupported(reason) => reason.clone(),
        other => other.to_string(),
    }
    .replace(['\r', '\n'], " ")
}

fn preview(input: &Path, output: &Path) -> Result<()> {
    check_output(input, output)?;
    let mut reader = BufReader::new(File::open(input)?);
    let trailer = read_trailer(&mut reader)?;
    let preview = read_preview(&mut reader, &trailer)?;
    let rgb = preview_rgb(&preview);
    let rows = Rows::Plain {
        rgb: &rgb,
        width: preview.width as usize,
        height: preview.height as usize,
    };
    write_panorama_jpeg(output, rows, 92, None)
}

/// Makes a new, empty temporary folder with a unique name in `parent`.
/// `create_dir` fails if the path exists, also if it is a symbolic link. Thus, the CLI does not use a folder of a different process.
fn new_temp_folder(parent: &Path) -> Result<PathBuf> {
    let nanos = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map_or(0, |time| time.as_nanos());
    for attempt in 0..100 {
        // No leading dot: if the CLI stops before the cleanup, the user can see the folder and delete it.
        let name = format!("insta360-stitch-{}-{nanos}-{attempt}", std::process::id());
        let folder = parent.join(name);
        match std::fs::create_dir(&folder) {
            Ok(()) => return Ok(folder),
            Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue,
            Err(error) => return Err(error.into()),
        }
    }
    Err("cannot make a temporary folder".into())
}

/// Checks `--width`. A valid width also gives a valid lens size: an even number of at least 8 (width / 2).
fn parse_width(text: &str) -> std::result::Result<usize, String> {
    let width: usize = text
        .parse()
        .map_err(|_| format!("{text} is not a number"))?;
    if width < 16 || !width.is_multiple_of(4) || width > MAX_VIDEO_WIDTH {
        return Err(format!(
            "the width must be a multiple of 4 from 16 to {MAX_VIDEO_WIDTH}, not {width}"
        ));
    }
    Ok(width)
}

/// The lens streams of a .insv file, from ffprobe.
#[derive(Debug, PartialEq)]
struct Probe {
    lens_size: usize,
    /// The height of the lens streams: less than `lens_size` for the band streams of Bullet Time.
    lens_height: usize,
    /// The frame rate as ffprobe gives it (for example 60000/1001), and as a number.
    rate: String,
    fps: f64,
    frame_count: usize,
    /// The colour tags of the source, as ffmpeg options for the raw pipe input. A raw pipe does not keep them.
    colour_args: Vec<String>,
    /// The source is full range (pc), as the X5 records.
    full_range: bool,
    /// The bits each second of the whole .insv file. `probe` sets it; the parser leaves 0.
    file_bitrate: u64,
    /// The duration of the file in whole microseconds, as ffmpeg gives it. `probe` sets it; the parser leaves `None`.
    duration_us: Option<u64>,
}

fn parse_seconds(text: &str) -> std::result::Result<f64, String> {
    match text.parse::<f64>() {
        Ok(seconds) if seconds.is_finite() && seconds >= 0.0 => Ok(seconds),
        _ => Err(format!("`{text}` is not a time in seconds (0 or more)")),
    }
}

fn parse_strength(text: &str) -> std::result::Result<f32, String> {
    match text.parse::<f32>() {
        Ok(strength) if strength > 0.0 && strength <= 16.0 => Ok(strength),
        _ => Err(format!(
            "`{text}` is not a strength (more than 0, at most 16)"
        )),
    }
}

/// The denoise setting of Studio for the recording, with the knee and the limit multiplied by the strength that the
/// user asked for (default 1).
fn denoise_settings_for(
    requested: Option<f32>,
    trailer: &Trailer,
    lens_size: usize,
    fps: f64,
) -> DenoiseSettings {
    trailer
        .denoise_settings(lens_size, fps)
        .scaled(requested.unwrap_or(1.0))
}

/// The first frame before `end` where the step from the frame before it in the video (`video_s`, s) and in the camera
/// times (`camera_us`, µs) differ by more than half a frame. The frames of a video take the camera times in order,
/// thus a frame that only one of them has moves the times of all frames after it by one frame. A step at or after
/// `end` (the first frame that is not stitched) does not change the stitched frames.
fn first_unmatched_frame(
    video_s: &[f64],
    camera_us: &[f64],
    fps: f64,
    end: usize,
) -> Option<usize> {
    let half = 0.5e6 / fps;
    (1..video_s.len().min(camera_us.len()).min(end)).find(|&n| {
        let video = (video_s[n] - video_s[n - 1]) * 1e6;
        ((camera_us[n] - camera_us[n - 1]) - video).abs() > half
    })
}

/// The tolerance of the time range, in seconds. Studio uses the same value.
const RANGE_TOLERANCE: f64 = 0.001;

/// The frames of the time range `start` to `end` (seconds) of a video with `fps` and `frame_count`: the numbers of
/// the first frame and of the frames. Frame n is at the time n / fps. Studio keeps every frame with a time from
/// `start` to `end`, with a tolerance of 1 ms, and it does not resample.
fn frame_range(
    fps: f64,
    frame_count: usize,
    start: Option<f64>,
    end: Option<f64>,
) -> Result<(usize, usize)> {
    let first = start.map_or(0.0, |start| {
        ((start - RANGE_TOLERANCE) * fps).ceil().max(0.0)
    }) as usize;
    let last = end.map_or(f64::INFINITY, |end| ((end + RANGE_TOLERANCE) * fps).floor());
    let last = last.min(frame_count as f64 - 1.0);
    if first as f64 > last {
        return Err(format!(
            "the time range has no frame: the video has {frame_count} frames at {fps:.3} fps ({:.3} s)",
            frame_count as f64 / fps
        )
        .into());
    }
    Ok((first, last as usize - first + 1))
}

/// The frames to stitch, from the time range after the camera trim (`start`, `end`; `trimmed` if the trim changed it)
/// and the Bullet Time cut (`cut`: the first and the last frame), in this order: the cut fills only the ends that
/// have no time. Without an end time, Studio can export one frame more than the file has (`repeat_last`).
fn plan_range(
    probe: &Probe,
    (start, end): (Option<f64>, Option<f64>),
    trimmed: bool,
    cut: Option<(usize, usize)>,
) -> Result<FrameRange> {
    let (start, end) = match cut {
        Some((first, last)) => (
            start.or(Some(first as f64 / probe.fps)),
            end.or(Some(last as f64 / probe.fps)),
        ),
        None => (start, end),
    };
    let (first, count) =
        frame_range(probe.fps, probe.frame_count, start, end).map_err(|error| match trimmed {
            true => format!(
                "{error}. The camera trim of the file applies (--no-camera-trim keeps all frames)"
            )
            .into(),
            false => error,
        })?;
    let repeat_last = match end {
        // Studio adds at most one frame; a longer container (audio, the other lens) does not add more.
        None => studio_frame_count(probe)
            .saturating_sub(probe.frame_count)
            .min(1),
        Some(_) => 0,
    };
    Ok(FrameRange {
        first,
        count,
        repeat_last,
    })
}

/// The time range (`start`, `end`) with the trim of the camera (`trim_ms`, see `Trailer::trim_ms`) at each end that
/// has no time. As Insta360 Studio, the first frame is (int)(start trim * fps / 1000) and the last frame is
/// (int)((duration - end trim) * fps / 1000), with the times in ms. A trim that leaves no frame does not apply.
fn camera_trim(
    fps: f64,
    frame_count: usize,
    trim_ms: [u64; 2],
    start: Option<f64>,
    end: Option<f64>,
) -> (Option<f64>, Option<f64>) {
    let frame = |ms: f64| (ms * fps / 1000.0) as usize;
    let duration_ms = frame_count as f64 * 1000.0 / fps;
    let first = frame(trim_ms[0] as f64);
    // Studio keeps the frame at the end time too.
    let last = frame((duration_ms - trim_ms[1] as f64).max(0.0)).min(frame_count - 1);
    if first > last {
        return (start, end);
    }
    (
        start.or((trim_ms[0] > 0).then(|| first as f64 / fps)),
        end.or((trim_ms[1] > 0).then(|| last as f64 / fps)),
    )
}

/// The number of frames of a Studio export to the end of the video. Studio takes the duration of the file (whole
/// microseconds) and keeps each frame time n / fps up to it: floor(duration * fps) + 1 frames. When the duration is
/// exactly a whole number of frames (for example 90 frames of 1001/30000 s = 3003000 us), this is one frame more
/// than the file has, and the export repeats the last frame. We saw this on a timelapse (90 -> 91) and a TimeShift
/// (198 -> 199); the formula gave the frame count of the Studio exports of all 7 files that we checked.
fn studio_frame_count(probe: &Probe) -> usize {
    let Some(duration_us) = probe.duration_us else {
        return probe.frame_count;
    };
    let ticks = match probe.rate.split_once('/') {
        Some((n, d)) => match (n.parse::<u128>(), d.parse::<u128>()) {
            (Ok(n), Ok(d)) if d > 0 => (duration_us as u128 * n / (d * 1_000_000)) as usize,
            _ => (duration_us as f64 * probe.fps / 1e6) as usize,
        },
        None => (duration_us as f64 * probe.fps / 1e6) as usize,
    };
    ticks + 1
}

/// The times (s, from the first frame) of the first motion sample at or after the first frame and of the last motion
/// sample. shortcut: the trailer keeps the samples up to 120 s after the first frame; a Bullet Time clip is shorter.
fn gyro_span(trailer: &Trailer) -> Option<(f64, f64)> {
    let (imu, first_frame) = (trailer.imu.as_ref()?, trailer.first_frame_us?);
    let first = imu.ts.iter().find(|&&t| t >= first_frame)?;
    Some((
        (first - first_frame) / 1e6,
        (imu.ts.last()? - first_frame) / 1e6,
    ))
}

/// The frames that the command stitches: the number of the first frame, and the number of frames.
#[derive(Clone, Copy, Debug)]
struct FrameRange {
    first: usize,
    count: usize,
    /// The copies of the last frame after it (see `studio_frame_count`).
    repeat_last: usize,
}

impl FrameRange {
    /// All frames of a video.
    #[cfg(test)]
    fn whole(probe: &Probe) -> FrameRange {
        FrameRange {
            first: 0,
            count: probe.frame_count,
            repeat_last: 0,
        }
    }

    /// Tells if the range is shorter than the video.
    fn is_part_of(&self, probe: &Probe) -> bool {
        self.first > 0 || self.count < probe.frame_count
    }
}

/// Tells if an ffmpeg option sets the filters of the video output stream: `-vf`, `-filter` for all streams, or
/// `-filter` for the video streams or the first stream (the video).
fn is_video_filter(option: &str) -> bool {
    option == "-vf"
        || option.starts_with("-vf:")
        || option == "-filter"
        || option.starts_with("-filter:v")
        || option == "-filter:0"
        || option.starts_with("-filter:0:")
}

/// A path for ffmpeg: "file:" makes a path that starts with "-" a file and not an option, and a path with a colon
/// (`clip:1.insv`, `cache:x.mp4`) a file and not a protocol.
fn ffmpeg_file(path: &Path) -> std::ffi::OsString {
    let mut file = std::ffi::OsString::from("file:");
    file.push(path);
    file
}

/// Reads the size, the frame rate, the frame count and the colour tags of the lens streams.
/// A .insv file that the library can stitch has two square video streams, one for each lens.
fn probe(ffprobe: &str, input: &Path) -> Result<Probe> {
    let out = Command::new(ffprobe)
        .args(["-v", "error", "-select_streams", "v", "-show_entries"])
        .arg("stream=width,height,r_frame_rate,nb_frames,color_space,color_primaries,color_transfer,color_range:format=duration")
        .args(["-of", "compact=p=0"])
        .arg("-i")
        .arg(ffmpeg_file(input))
        .output()
        .map_err(|e| format!("cannot start {ffprobe}: {e}"))?;
    if !out.status.success() {
        return Err(format!(
            "ffprobe failed: {}",
            String::from_utf8_lossy(&out.stderr).trim()
        )
        .into());
    }
    let text = String::from_utf8_lossy(&out.stdout);
    let mut probe = parse_probe(&text)?;
    // The format line has only the duration (seconds with 6 decimals, thus whole microseconds).
    probe.duration_us = text
        .lines()
        .filter_map(|line| line.trim().strip_prefix("duration="))
        .find_map(|seconds| seconds.parse::<f64>().ok())
        .map(|seconds| (seconds * 1e6).round() as u64);
    probe.file_bitrate = file_bitrate(
        std::fs::metadata(input)?.len(),
        probe.frame_count,
        probe.fps,
    );
    Ok(probe)
}

/// The bits each second of a file: its size divided by the duration of its video. Studio takes the bitrate of
/// its HEVC export from the .insv file in this way (within 1.4% on four clips).
fn file_bitrate(bytes: u64, frame_count: usize, fps: f64) -> u64 {
    (bytes as f64 * 8.0 / (frame_count as f64 / fps)) as u64
}

/// Parses the ffprobe lines `key=value|key=value...`, one for each video stream.
fn parse_probe(text: &str) -> Result<Probe> {
    let streams: Vec<std::collections::HashMap<&str, &str>> = text
        .lines()
        .filter(|line| line.contains("width="))
        .map(|line| {
            line.trim()
                .split('|')
                .filter_map(|kv| kv.split_once('='))
                .collect()
        })
        .collect();
    let [first, second, ..] = streams.as_slice() else {
        return Err("expected one video stream per lens".into());
    };
    let number = |s: &std::collections::HashMap<&str, &str>, key: &str| -> Option<usize> {
        s.get(key).and_then(|v| v.parse().ok())
    };
    let size = |s| -> Result<(usize, usize)> {
        Ok((
            number(s, "width").ok_or("no stream width")?,
            number(s, "height").ok_or("no stream height")?,
        ))
    };
    let (width, height) = size(first)?;
    let other = size(second)?;
    if other != (width, height) || height > width {
        return Err(format!(
            "unsupported lens streams {width}x{height} and {}x{}",
            other.0, other.1
        )
        .into());
    }
    let rate = first.get("r_frame_rate").copied().unwrap_or("").to_string();
    let fps = match rate.split_once('/') {
        Some((n, d)) => n.parse::<f64>()? / d.parse::<f64>()?,
        None => rate.parse()?,
    };
    if !fps.is_finite() || fps <= 0.0 {
        return Err(format!("invalid frame rate {rate}").into());
    }
    // The two streams can differ by a frame. The CLI stitches the frames that both streams have.
    let frame_count = match (number(first, "nb_frames"), number(second, "nb_frames")) {
        (Some(a), Some(b)) => a.min(b),
        _ => return Err("ffprobe gives no frame count for the lens streams".into()),
    };
    if frame_count == 0 {
        return Err("the lens streams have no frames".into());
    }
    let mut colour_args = Vec::new();
    for (key, option) in [
        ("color_space", "-colorspace"),
        ("color_primaries", "-color_primaries"),
        ("color_transfer", "-color_trc"),
        ("color_range", "-color_range"),
    ] {
        if let Some(value) = first.get(key).filter(|v| !v.is_empty() && **v != "unknown") {
            colour_args.extend([option.to_string(), value.to_string()]);
        }
    }
    Ok(Probe {
        lens_size: width,
        lens_height: height,
        rate,
        fps,
        frame_count,
        colour_args,
        full_range: first.get("color_range") == Some(&"pc"),
        file_bitrate: 0,
        duration_us: None,
    })
}

/// The ffmpeg arguments of the encoder: the codec, then the quality options for libx264 and libx265,
/// then the options of the user. `--studio-encode` replaces the codec and the quality options.
fn encoder_args(options: &VideoOptions, probe: &Probe) -> Vec<String> {
    let mut args = Vec::new();
    // One key frame each second (a GOP of the rounded frame rate) and no B-frames, as the Studio export.
    // hvc1 is the sample tag that Apple players need.
    let gop = probe.fps.round().max(1.0);
    if options.studio_encode == Some(StudioEncoder::HevcNvenc) {
        // Studio sets only the bitrate, the B-frames and the GOP. The other settings are the ffmpeg defaults.
        args.extend([
            "-c:v".into(),
            "hevc_nvenc".into(),
            "-b:v".into(),
            probe.file_bitrate.to_string(),
            "-bf".into(),
            "0".into(),
            "-g".into(),
            gop.to_string(),
            "-pix_fmt".into(),
            "yuv420p".into(),
            "-tag:v".into(),
            "hvc1".into(),
        ]);
    } else if options.studio_encode.is_some() {
        args.extend([
            "-c:v".into(),
            "libx265".into(),
            "-preset".into(),
            options.preset.clone(),
            "-b:v".into(),
            probe.file_bitrate.to_string(),
            "-x265-params".into(),
            format!("keyint={gop}:min-keyint={gop}:scenecut=0:bframes=0"),
            "-pix_fmt".into(),
            "yuv420p".into(),
            "-tag:v".into(),
            "hvc1".into(),
        ]);
    } else {
        args.extend(["-c:v".to_string(), options.encoder.clone()]);
        if matches!(options.encoder.as_str(), "libx264" | "libx265") {
            args.extend([
                "-preset".into(),
                options.preset.clone(),
                "-crf".into(),
                options.crf.to_string(),
            ]);
            args.extend(["-pix_fmt".into(), "yuv420p".into()]);
        }
    }
    args.extend(options.encoder_args.iter().cloned());
    args
}

/// Reads frames of `bytes` from `source` into buffers from `free`, and sends each full buffer to `full`.
/// It stops at the end of the stream, after `limit` frames, or when the receiver stops.
fn read_frames(
    mut source: impl Read,
    bytes: usize,
    limit: usize,
    free: Receiver<Vec<u8>>,
    full: SyncSender<Vec<u8>>,
) -> std::io::Result<usize> {
    let mut count = 0;
    while count < limit {
        let Ok(mut buffer) = free.recv() else { break };
        buffer.resize(bytes, 0);
        match source.read_exact(&mut buffer) {
            Ok(()) => {}
            Err(error) if error.kind() == std::io::ErrorKind::UnexpectedEof => break,
            Err(error) => return Err(error),
        }
        if full.send(buffer).is_err() {
            break;
        }
        count += 1;
    }
    Ok(count)
}

/// The frames on each side of a video frame whose seam flows the CLI averages, as Insta360 (t - 2 to t + 2).
const FLOW_RADIUS: usize = 2;

/// What the pipeline prepares for each frame before its stitch: the seam flow and the colour fusion.
struct Prepared {
    flow: Option<FrameFlow>,
    fusion: Option<FrameFusion>,
}

/// Filters the frames that go to `inner` with the block denoise. Each frame is `frame_bytes` bytes, and `write` can
/// take any part of it. The frames come out later (see [`Denoiser`]); `flush` gives the last ones, thus call it
/// one time, when the last frame is written (the pipeline does).
struct DenoiseWriter<W: Write> {
    inner: W,
    denoiser: Denoiser,
    pending: Vec<u8>,
    filtered: Vec<u8>,
}

impl<W: Write> DenoiseWriter<W> {
    fn new(inner: W, denoiser: Denoiser) -> Self {
        DenoiseWriter {
            inner,
            denoiser,
            pending: Vec::new(),
            filtered: Vec::new(),
        }
    }
}

impl<W: Write> DenoiseWriter<W> {
    /// Pushes one frame and writes the filtered frame to `inner` when it is ready.
    fn push(&mut self, frame: &[u8]) -> std::io::Result<()> {
        if self
            .denoiser
            .push(frame, &mut self.filtered)
            .map_err(std::io::Error::other)?
        {
            self.inner.write_all(&self.filtered)?;
        }
        Ok(())
    }
}

impl<W: Write> Write for DenoiseWriter<W> {
    fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
        let size = self.denoiser.frame_bytes();
        let mut rest = bytes;
        if self.pending.is_empty() {
            // The usual case: whole frames. Push them from the write, without a copy into `pending`.
            while rest.len() >= size {
                self.push(&rest[..size])?;
                rest = &rest[size..];
            }
        }
        self.pending.extend_from_slice(rest);
        let mut pending = std::mem::take(&mut self.pending);
        let full = pending.len() / size * size;
        for frame in pending[..full].chunks_exact(size) {
            self.push(frame)?;
        }
        pending.drain(..full);
        self.pending = pending;
        Ok(bytes.len())
    }

    fn flush(&mut self) -> std::io::Result<()> {
        while self
            .denoiser
            .finish(&mut self.filtered)
            .map_err(std::io::Error::other)?
        {
            self.inner.write_all(&self.filtered)?;
        }
        self.inner.flush()
    }
}

/// Reads the stacked lens frames of `in_bytes` from `decoded`, stitches frame n with `stitch(n, frame, window, out)`
/// and writes each output of `out_bytes` to `encoded`. It stops after `limit` frames or at the end of
/// `decoded`, and gives the number of frames. Decode, stitch and encode overlap.
///
/// `prepare(frame)` makes the data of each frame (the seam flow). `window` has the data of the frames
/// n - `radius` to n + `radius` (fewer at the start and the end). With a radius, the data of frame n + radius + 1
/// is made on a second thread while frame n is stitched; thus, the pipeline keeps radius + 4 input frames, not 2.
/// `stitch` gets the output buffer of its frame and gives the output of the oldest frame that is done, if any: at most
/// `lag` calls later (the GPU stitch is one call late). After the last frame, `finish` gives the rest.
#[allow(clippy::too_many_arguments)]
fn pipeline<P: Send>(
    decoded: impl Read + Send,
    mut encoded: impl Write + Send,
    (in_bytes, out_bytes): (usize, usize),
    limit: usize,
    (radius, lag): (usize, usize),
    prepare: impl Fn(&[u8]) -> insta360_stitch::Result<P> + Sync,
    stitch: impl Fn(usize, &[u8], &[&P], Vec<u8>) -> Result<Option<Vec<u8>>>,
    finish: impl FnOnce() -> Result<Option<Vec<u8>>>,
) -> Result<usize> {
    // The frames after the frame that the pipeline stitches, and one buffer for each side in transfer.
    let lookahead = if radius == 0 { 0 } else { radius + 1 };
    let (free_in_tx, free_in) = sync_channel(2 + lookahead);
    let (full_tx, full) = sync_channel(2);
    let (free_out_tx, free_out) = sync_channel(2 + lag);
    let (done_tx, done) = sync_channel::<Vec<u8>>(2 + lag);
    for _ in 0..2 + lookahead {
        free_in_tx.send(Vec::new())?;
    }
    for _ in 0..2 + lag {
        free_out_tx.send(vec![0u8; out_bytes])?;
    }
    let started = std::time::Instant::now();
    std::thread::scope(|scope| -> Result<usize> {
        // Moved into the scope: an early return drops it, thus a reader that waits for a free buffer stops.
        let free_in_tx = free_in_tx;
        let reader = scope.spawn(move || read_frames(decoded, in_bytes, limit, free_in, full_tx));
        let writer = scope.spawn(move || -> std::io::Result<()> {
            for buffer in done {
                encoded.write_all(&buffer)?;
                if free_out_tx.send(buffer).is_err() {
                    break;
                }
            }
            encoded.flush()
        });
        // The frames from `index` (the next frame to stitch), and the data of the frames from `first`.
        let mut held = std::collections::VecDeque::new();
        let mut data = std::collections::VecDeque::new();
        let (mut index, mut first) = (0, 0);
        fn window<P>(
            data: &std::collections::VecDeque<P>,
            first: usize,
            n: usize,
            radius: usize,
        ) -> Vec<&P> {
            (n.saturating_sub(radius)..=n + radius)
                .filter_map(|i| i.checked_sub(first).and_then(|i| data.get(i)))
                .collect()
        }
        let send = |frame: Vec<u8>, out: Option<Vec<u8>>, index: usize| -> Result<()> {
            free_in_tx.send(frame).ok();
            if let Some(out) = out {
                done_tx.send(out)?;
            }
            if (index + 1).is_multiple_of(30) {
                let fps = (index + 1) as f64 / started.elapsed().as_secs_f64();
                eprint!("\rframe {}/{limit} ({fps:.1} fps)", index + 1);
            }
            Ok(())
        };
        for frame in full {
            held.push_back(frame);
            let newest = held.back().ok_or("no frame")?;
            let next = if lookahead > 0 && held.len() > lookahead {
                let out = free_out.recv()?;
                let near = window(&data, first, index, radius);
                let (next, stitched) = std::thread::scope(|threads| {
                    let next = threads.spawn(|| prepare(newest));
                    let stitched = stitch(index, &held[0], &near, out);
                    (next.join(), stitched)
                });
                let out = stitched?;
                send(held.pop_front().ok_or("no frame")?, out, index)?;
                index += 1;
                next.map_err(|_| "the seam flow thread panicked")??
            } else {
                prepare(newest)?
            };
            data.push_back(next);
            if lookahead == 0 {
                let out = free_out.recv()?;
                let out = stitch(index, &held[0], &window(&data, first, index, radius), out)?;
                send(held.pop_front().ok_or("no frame")?, out, index)?;
                index += 1;
            }
            while first + radius < index {
                data.pop_front();
                first += 1;
            }
        }
        // The end of the stream: the last frames have the data of all frames that exist.
        while let Some(frame) = held.pop_front() {
            let out = free_out.recv()?;
            let out = stitch(index, &frame, &window(&data, first, index, radius), out)?;
            send(frame, out, index)?;
            index += 1;
        }
        if let Some(out) = finish()? {
            done_tx.send(out)?;
        }
        drop(done_tx);
        let read = reader.join().map_err(|_| "the decoder thread panicked")??;
        writer.join().map_err(|_| "the encoder thread panicked")??;
        Ok(read.min(index))
    })
}

/// The item of frame `index` in its window `near` (from [`pipeline`]): the window has the `radius` frames before the
/// frame, fewer at the start of the video.
fn frame_itself<'a, P>(near: &[&'a P], index: usize, radius: usize) -> Option<&'a P> {
    near.get(index.min(radius)).copied()
}

/// Tells if `error` of [`pipeline`] comes from an encoder pipe that closed.
fn encoder_stopped(error: &(dyn std::error::Error + 'static)) -> bool {
    error.is::<RecvError>()
        || error.is::<SendError<Vec<u8>>>()
        || (error.downcast_ref::<std::io::Error>())
            .is_some_and(|e| e.kind() == std::io::ErrorKind::BrokenPipe)
}

/// The requested stabilization, else the default of Insta360 Studio: follow for a TimeShift recording, else lock.
fn stabilization_for(requested: Option<StabilizationArg>, time_shift: bool) -> Stabilization {
    match requested {
        Some(mode) => mode.into(),
        None if time_shift => Stabilization::Follow,
        None => Stabilization::Lock,
    }
}

/// Gives the frame rotations of `mode`. Lock and follow need orientations from the IMU stream. Without them,
/// the video uses off, with a warning.
/// The IMU data, or no data if the file has none (the "unsupported" error). Other errors stop the command.
fn imu_or_empty(imu: insta360_stitch::Result<Imu>) -> Result<Imu> {
    match imu {
        Err(insta360_stitch::Error::Unsupported(_)) => Ok(Imu::default()),
        imu => Ok(imu?),
    }
}

fn stabilize<T>(
    mode: Stabilization,
    rotations: impl Fn(Stabilization) -> insta360_stitch::Result<Vec<T>>,
) -> Result<(Stabilization, Vec<T>)> {
    match rotations(mode) {
        Err(insta360_stitch::Error::Unsupported(why)) if mode != Stabilization::Off => {
            eprintln!("insta360-stitch: {why}. The video is not stabilized");
            Ok((Stabilization::Off, rotations(Stabilization::Off)?))
        }
        rotations => Ok((mode, rotations?)),
    }
}

/// The decoder: lens 0 is the second video stream. ffmpeg stacks the two lenses into one frame, lens 0 on top.
fn decoder_command(
    options: &VideoOptions,
    probe: &Probe,
    lens_size: usize,
    band: Option<usize>,
    input: &Path,
    range: FrameRange,
) -> Command {
    // yuvj420p is the full-range form of yuv420p (the same bytes). Thus, no ffmpeg version changes the range of a
    // full-range source.
    let format = if probe.full_range {
        "yuvj420p"
    } else {
        "yuv420p"
    };
    let scale = if lens_size < probe.lens_size {
        format!("scale={lens_size}:{}:flags=area,", 2 * lens_size)
    } else {
        String::new()
    };
    // A band stream goes into a square at its row (see `band_offset`), lens 0 on top as for a square stream.
    let lenses = match band {
        Some(row) => {
            let size = probe.lens_size;
            format!("[0:v:1]pad={size}:{size}:0:{row}[l0];[0:v:0]pad={size}:{size}:0:{row}[l1];[l0][l1]")
        }
        None => "[0:v:1][0:v:0]".to_string(),
    };
    let mut command = Command::new(&options.ffmpeg);
    command.args(["-v", "error", "-nostdin"]);
    if let Some(hwaccel) = &options.hwaccel {
        command.args(["-hwaccel", hwaccel]);
    }
    // More decoder threads do not make an 8K lens stream faster (measured), but they use much more memory.
    // One filter thread is sufficient for vstack and the format change.
    let threads = options.decoder_threads.to_string();
    command.args(["-threads", &threads, "-filter_complex_threads", "1"]);
    // The first frame of the range is the first frame with a time of at least half a frame before it.
    if range.first > 0 {
        let seek = (range.first as f64 - 0.5) / probe.fps;
        command.args(["-ss", &format!("{seek:.6}")]);
    }
    command
        // After the defaults: thus an option of the user replaces a default.
        .args(&options.decoder_args)
        .arg("-i")
        .arg(ffmpeg_file(input))
        .arg("-filter_complex")
        .arg(format!("{lenses}vstack=inputs=2,{scale}format={format}[v]"))
        // passthrough: no frame is dropped or repeated, thus frame n keeps the rotation of frame n.
        .args(["-map", "[v]", "-fps_mode", "passthrough"]);
    // The decoder stops by itself after the last frame of the range. Else it writes errors to a closed pipe.
    if range.is_part_of(probe) {
        command.args(["-frames:v", &range.count.to_string()]);
    }
    command.args(["-f", "rawvideo", "-pix_fmt", format, "pipe:1"]);
    command
}

/// The encoder: raw stitched frames from the pipe (input 0), the audio and the metadata from the .insv
/// (input 1).
fn encoder_command(
    options: &VideoOptions,
    probe: &Probe,
    (width, height): (usize, usize),
    flat: Option<(usize, usize)>,
    input: &Path,
    stitched: &Path,
    range: FrameRange,
) -> Command {
    // A flat Bullet Time view shows each frame at 29.97 fps, as the Studio export (slow motion).
    let rate = if flat.is_some() {
        BULLET_TIME_RATE
    } else {
        &probe.rate
    };
    let mut command = Command::new(&options.ffmpeg);
    command
        .args(["-v", "error", "-y", "-f", "rawvideo", "-pix_fmt", "yuv420p"])
        .args(["-s", &format!("{width}x{height}"), "-framerate", rate])
        // The colour tags of the source on the pipe input. Thus, the output gets them, and ffmpeg does not
        // convert the frames: with the tags on the output only, ffmpeg changes full range to limited range.
        .args(&probe.colour_args)
        .args(["-i", "pipe:0"]);
    // The audio of the same range. ffmpeg cuts the copied audio at the packets (approximately 21 ms).
    if range.is_part_of(probe) {
        command.args([
            "-ss",
            &format!("{:.6}", range.first as f64 / probe.fps),
            "-t",
            &format!("{:.6}", range.count as f64 / probe.fps),
        ]);
    }
    command
        .arg("-i")
        .arg(ffmpeg_file(input))
        .args(["-map", "0:v:0"]);
    let mut filters = Vec::new();
    // The view of the stitched frame, which looks along the stick (see `BULLET_TIME_VIEW`).
    if let Some((w, h)) = flat {
        filters.push(format!(
            "v360=e:sg:h_fov={BULLET_TIME_H_FOV}:v_fov={:.2}:w={w}:h={h}",
            bullet_time_v_fov(w, h)
        ));
    }
    if range.repeat_last > 0 {
        filters.push(format!("tpad=stop={}:stop_mode=clone", range.repeat_last));
    }
    // ffmpeg uses only the last video filter of a stream: the last one of the user (for example -vf hwupload) gets
    // our filters first. A -filter_complex of the user is not changed.
    let mut args = encoder_args(options, probe);
    let user = args
        .iter()
        .rposition(|a| is_video_filter(a))
        .filter(|&at| at + 1 < args.len());
    match user {
        _ if filters.is_empty() => {}
        Some(at) => args[at + 1] = format!("{},{}", filters.join(","), args[at + 1]),
        None => {
            command.args(["-vf", &filters.join(",")]);
        }
    }
    match flat {
        // The audio does not fit the slow motion.
        Some(_) => command.arg("-an"),
        None => command.args(["-map", "1:a?", "-c:a", "copy"]),
    };
    command
        // The global metadata (for example creation_time) of the .insv. ffmpeg copies it from input 0 only.
        .args(["-map_metadata", "1"])
        .args(args)
        // ffmpeg writes moov at the end. finish_video moves it to the start and adds the 360 video metadata.
        .arg(ffmpeg_file(stitched));
    command
}

fn video(
    input: &Path,
    output: &Path,
    options: &VideoOptions,
    flow_threads: usize,
    gpu: GpuMode,
) -> Result<()> {
    check_output(input, output)?;
    let mut reader = BufReader::new(File::open(input)?);
    let trailer = read_trailer(&mut reader)?;
    let probe = probe(&options.ffprobe, input)?;
    let trim_ms = if options.no_camera_trim {
        [0, 0]
    } else {
        trailer.trim_ms
    };
    let (start, end) = camera_trim(
        probe.fps,
        probe.frame_count,
        trim_ms,
        options.start,
        options.end,
    );
    let stitcher = Stitcher::new(trailer);
    // Studio cuts a Bullet Time clip to the part where the camera turns (see `bullet_time_cut`).
    let cut_bullet_time = !options.no_camera_trim
        && stitcher.trailer.is_bullet_time()
        && (start.is_none() || end.is_none());
    // For an output that is narrower than two lens streams, ffmpeg scales the lenses down first (area filter).
    // Thus, the stitch does not alias, and the pipe moves less data.
    // The flat Bullet Time view comes from a stitch at the size of the lenses; --width is then the flat width.
    let flat = options.bullet_time_view.then(|| {
        let w = options.width.unwrap_or(2 * probe.lens_size);
        (w, (w * 9 / 16) & !1)
    });
    let width = match flat {
        Some(_) => 2 * probe.lens_size,
        None => options.width.unwrap_or(2 * probe.lens_size),
    };
    let lens_size = probe.lens_size.min(width / 2);
    let frames = stitcher.frame_stitcher(lens_size, Some(width))?;
    let band = band_offset(&stitcher.trailer, probe.lens_size, probe.lens_height)?;
    if options.bullet_time_view && !stitcher.trailer.is_bullet_time() {
        return Err("--bullet-time-view is only for a Bullet Time clip".into());
    }
    let mode = match options.bullet_time_view {
        true => Stabilization::Off,
        false => stabilization_for(options.stabilization, stitcher.trailer.is_time_shift()),
    };
    let rolling = !options.no_rolling_shutter;
    // Lock, follow and the rolling shutter correction need the full IMU stream. Off uses the IMU window of the
    // trailer for its orientation.
    let imu = match (mode, rolling) {
        // The Bullet Time view needs the level of each frame.
        _ if options.bullet_time_view => read_imu(&mut reader, &stitcher.trailer)?,
        (Stabilization::Off, false) if !cut_bullet_time => Imu::default(),
        // Without IMU data, the video has no stabilization (`stabilize` shows a warning), no rolling shutter
        // correction and no Bullet Time cut. A read error stops the command.
        _ => imu_or_empty(read_imu(&mut reader, &stitcher.trailer))?,
    };
    let (mode, mut rotations) = stabilize(mode, |mode| {
        stitcher.frame_motions(&imu, probe.frame_count, probe.fps, mode, rolling)
    })?;
    let levels = match flat.is_some() || cut_bullet_time {
        true => {
            match stitcher.frame_rotations(&imu, probe.frame_count, probe.fps, Stabilization::Lock)
            {
                // The cut is a default, not a request: without the level of the frames, the clip is not cut.
                Err(insta360_stitch::Error::Unsupported(why)) if flat.is_none() => {
                    eprintln!("insta360-stitch: {why}. The Bullet Time clip is not cut");
                    Vec::new()
                }
                levels => levels?,
            }
        }
        false => Vec::new(),
    };
    if flat.is_some() {
        bullet_time_rotations(&mut rotations, &levels, probe.fps);
    }
    let cut = cut_bullet_time
        .then(|| gyro_span(&stitcher.trailer))
        .flatten()
        .and_then(|span| bullet_time_cut(&levels, probe.fps, span));
    if let Some((first, last)) = cut {
        eprintln!("insta360-stitch: Bullet Time cut as Insta360 Studio: frames {first} to {last} (--no-camera-trim keeps all frames)");
    }
    let trimmed = (start, end) != (options.start, options.end);
    let range = plan_range(&probe, (start, end), trimmed, cut)?;
    // Only the frames of the range are stitched. A rotation with the rolling shutter rows needs approximately 840
    // bytes: 90 MB for each hour at 30 fps.
    let rotations = rotations_of_range(rotations, range);
    drop(levels);
    if mode != Stabilization::Off
        && !uses_recorded_frame_times(&stitcher.trailer, probe.frame_count)
    {
        eprintln!("insta360-stitch: the file does not have the time of all frames, the frame times use the frame rate");
    }
    // A TimeShift or timelapse has its own capture time for each frame, thus a step in the video is normal there.
    if mode != Stabilization::Off && stitcher.trailer.frame_times.is_none() {
        let video_times = File::open(input)
            .ok()
            .and_then(|file| video_sample_times(&mut BufReader::new(file)).ok().flatten());
        let camera_times = frame_times_us(&stitcher.trailer, probe.frame_count, probe.fps);
        if let Some(frame) = video_times.and_then(|video| {
            first_unmatched_frame(&video, &camera_times, probe.fps, range.first + range.count)
        }) {
            eprintln!("insta360-stitch: the time step before frame {frame} of the video is not in the camera frame times (a dropped frame?). The stabilization from this frame can be one frame early or late");
        }
    }
    drop(imu);
    let denoise = denoise_settings_for(
        options.denoise_strength,
        &stitcher.trailer,
        probe.lens_size,
        probe.fps,
    );
    // As Studio: no block denoise when the camera chip filtered the video in time.
    let denoise_on = options.denoise && stitcher.trailer.studio_denoises();
    if options.denoise && !denoise_on {
        eprintln!("insta360-stitch: no denoise: the camera already filtered this video in time (mctf_process_type 2), and Studio does not denoise it");
    }
    if denoise_on {
        eprintln!(
            "insta360-stitch: denoise as Studio: knee {:.1} levels, limit {} levels",
            denoise.knee, denoise.limit
        );
    }

    // The work folder is next to the output, not in the system temporary folder.
    // That folder can be in memory (tmpfs), and a long 8K encode can be larger than the memory.
    // Also, the stitched file can then become the output with a rename.
    let parent = output
        .parent()
        .filter(|parent| !parent.as_os_str().is_empty())
        .unwrap_or(Path::new("."));
    let folder = new_temp_folder(parent)?;
    let stitched = folder.join("stitched.mp4");
    let result = (|| -> Result<()> {
        // All the steps that can fail on the arguments run before ffmpeg starts: an error after the start leaves
        // the two processes running.
        let denoiser = denoise_on
            // The settings have the strength already: 1 keeps them.
            .then(|| Denoiser::with_gpu(frames.width(), frames.height(), 1.0, Some(denoise), gpu))
            .transpose()?;
        if let Some(denoiser) = &denoiser {
            match denoiser.gpu() {
                Some(name) => eprintln!("insta360-stitch: denoise on the GPU ({name})"),
                None => eprintln!(
                    "insta360-stitch: denoise on the processor ({})",
                    // A reason from the GPU driver can have more than one line.
                    denoiser
                        .gpu_reason()
                        .unwrap_or("no GPU")
                        .replace(['\r', '\n'], " ")
                ),
            }
        }
        #[cfg(feature = "gpu")]
        let on_gpu = match gpu {
            GpuMode::Auto => frames.gpu_video().map_err(|e| reason(&e)),
            GpuMode::Off => Err("--gpu off".to_string()),
        };
        #[cfg(feature = "gpu")]
        let on_gpu = match on_gpu {
            Ok(on_gpu) => {
                eprintln!(
                    "insta360-stitch: video stitch on the GPU ({})",
                    on_gpu.name()
                );
                Some(on_gpu)
            }
            Err(reason) => {
                eprintln!("insta360-stitch: video stitch on the processor ({reason})");
                None
            }
        };
        // The GPU gives the output of each frame one call later (see `pipeline`).
        #[cfg(feature = "gpu")]
        let lag = usize::from(on_gpu.is_some());
        #[cfg(not(feature = "gpu"))]
        let lag = 0;
        // The seam flow of the next frame runs on its own threads while the stitch uses the global pool. In one
        // pool, its work waits for the stitch, and the two steps do not overlap.
        let flow_pool = rayon::ThreadPoolBuilder::new()
            .num_threads(flow_threads)
            .build()?;
        let mut decoder = decoder_command(options, &probe, lens_size, band, input, range)
            .stdout(Stdio::piped())
            .spawn()
            .map_err(|e| format!("cannot start {}: {e}", options.ffmpeg))?;
        let mut encoder = encoder_command(
            options,
            &probe,
            (frames.width(), frames.height()),
            flat,
            input,
            &stitched,
            range,
        )
        .stdin(Stdio::piped())
        .spawn()
        .map_err(|e| format!("cannot start {}: {e}", options.ffmpeg))?;
        let decoded = decoder.stdout.take().ok_or("no decoder output")?;
        let encoded = BufWriter::new(encoder.stdin.take().ok_or("no encoder input")?);
        let encoded: Box<dyn Write + Send> = match denoiser {
            Some(denoiser) => Box::new(DenoiseWriter::new(encoded, denoiser)),
            None => Box::new(encoded),
        };

        // The colour fusion converts the frames to RGB as full-range BT.709, as the X5 records.
        let color_fusion = !options.no_color_fusion && probe.full_range;
        if !options.no_color_fusion && !probe.full_range {
            eprintln!(
                "insta360-stitch: the source is not full range. The video has no colour fusion"
            );
        }
        // In the Bullet Time view, the seam flow made the seam less like the Studio export (Y PSNR of the seam band
        // 17.5 dB with the flow, 18.1 dB without): it pulls the stick on the seam into the image.
        let no_seam_flow = options.no_seam_flow || options.bullet_time_view;
        let radius = if no_seam_flow { 0 } else { FLOW_RADIUS };
        // Studio carries the fusion solve from frame to frame. `pipeline` prepares the frames in order.
        let fusion_history = std::sync::Mutex::new(insta360_stitch::FusionHistory::default());
        let started = std::time::Instant::now();
        let count = pipeline(
            decoded,
            encoded,
            (frames.input_frame_bytes(), frames.output_frame_bytes()),
            range.count,
            (radius, lag),
            // Both run for the next frame beside the stitch of an earlier frame.
            |frame| {
                flow_pool.install(|| {
                    Ok(Prepared {
                        flow: match no_seam_flow {
                            true => None,
                            false => frames.frame_flow(frame)?,
                        },
                        fusion: match color_fusion {
                            true => Some(
                                frames.frame_fusion_after(
                                    frame,
                                    &mut fusion_history
                                        .lock()
                                        .unwrap_or_else(std::sync::PoisonError::into_inner),
                                )?,
                            ),
                            false => None,
                        },
                    })
                })
            },
            |index, frame, near, mut out| {
                let flows: Vec<&FrameFlow> = near.iter().filter_map(|p| p.flow.as_ref()).collect();
                let flow = (!flows.is_empty()).then(|| FrameFlow::mean(&flows));
                // The frame itself is in the window after the frames before it (fewer at the start).
                let fusion = frame_itself(near, index, radius).and_then(|p| p.fusion.as_ref());
                #[cfg(feature = "gpu")]
                if let Some(gpu) = &on_gpu {
                    return Ok(frames.stitch_yuv420_gpu(
                        gpu,
                        &rotations[index],
                        flow.as_ref(),
                        fusion,
                        frame,
                        out,
                    )?);
                }
                frames.stitch_yuv420_full(
                    &rotations[index],
                    flow.as_ref(),
                    fusion,
                    frame,
                    &mut out,
                )?;
                Ok(Some(out))
            },
            || {
                #[cfg(feature = "gpu")]
                if let Some(gpu) = &on_gpu {
                    return Ok(frames.finish_gpu(gpu)?);
                }
                Ok(None)
            },
        );
        // Stop the decoder if the stitch stopped early. Its exit status is then not an error.
        let count = match count {
            Ok(count) => count,
            Err(error) => {
                decoder.kill().ok();
                decoder.wait().ok();
                // An encoder that stopped is the cause, not the closed pipe that the stitch then sees.
                let status = encoder.wait()?;
                if !status.success() {
                    return Err(format!("the ffmpeg encoder exited with {status}").into());
                }
                if encoder_stopped(&*error) {
                    return Err("the ffmpeg encoder stopped before the last frame".into());
                }
                return Err(error);
            }
        };
        let decoder_status = if count < range.count {
            Some(decoder.wait()?)
        } else {
            decoder.kill().ok();
            decoder.wait().ok();
            None
        };
        let encoder_status = encoder.wait()?;
        eprintln!(
            "\rframe {count}/{} in {:.1} s",
            range.count,
            started.elapsed().as_secs_f64()
        );
        if let Some(status) = decoder_status.filter(|status| !status.success()) {
            // A decoder that the system stopped for lack of memory gives signal 9 (SIGKILL).
            return Err(format!("the ffmpeg decoder exited with {status}").into());
        }
        if !encoder_status.success() {
            return Err(format!("the ffmpeg encoder exited with {encoder_status}").into());
        }
        if count == 0 {
            return Err("the decoder gave no frames".into());
        }
        if count < range.count {
            eprintln!(
                "insta360-stitch: the decoder gave {count} of {} frames",
                range.count
            );
        }
        match flat {
            Some(_) => Ok(std::fs::rename(&stitched, output)?),
            None => finish_video(&stitched, output),
        }
    })();
    std::fs::remove_dir_all(&folder).ok();
    result
}

/// The output direction -> camera rotation of the Bullet Time view when the world up is camera -z: the centre of the
/// stitched frame (output -z) looks along the stick (camera -y), and its top (output +y) is camera -z. We fitted the
/// Studio export of a Bullet Time clip: its view was 0.4 degrees from camera -y. Its top is the world up as seen
/// along the stick (see `bullet_time_view`).
const BULLET_TIME_VIEW: Mat3 = [[1.0, 0.0, 0.0], [0.0, 0.0, 1.0], [0.0, -1.0, 0.0]];
/// The horizontal field of view of the flat Bullet Time view, a stereographic projection. The Studio view is a
/// virtual camera behind the centre of the sphere (its View panel shows 76.0 and 0.94). A fit of the Studio export:
/// the stereographic projection (camera at distance 1) with 143 degrees is 0.06 dB from the best distance (Y PSNR
/// 18.1 dB; a rectilinear view: 15.3 dB). ffmpeg v360 has no projection with other distances.
const BULLET_TIME_H_FOV: f64 = 143.0;
/// The frame rate of a flat Bullet Time video, as the Studio export.
const BULLET_TIME_RATE: &str = "30000/1001";
/// The Studio view follows a smoothed stick direction: a Gaussian with this sigma (seconds) fitted the direction of
/// the Studio export (pitch error 0.40 -> 0.15 degrees, correlation 0.92; yaw error 0.69 -> 0.53 degrees).
const BULLET_TIME_SMOOTHING_S: f64 = 0.11;

/// The vertical field of view of a stereographic view of `width` x `height` with `BULLET_TIME_H_FOV` (ffmpeg v360:
/// the image is tan(fov / 4) wide).
fn bullet_time_v_fov(width: usize, height: usize) -> f64 {
    let half = (BULLET_TIME_H_FOV / 4.0).to_radians().tan() * height as f64 / width as f64;
    4.0 * half.atan().to_degrees()
}

/// The Bullet Time view of a frame with the level rotation `level` (output -> camera, as `--stabilization lock`): it
/// looks along `forward` (camera coordinates, approximately the stick: camera -y), and its top is the world up as
/// seen along `forward`. Thus, the horizon does not turn in the image. In the Studio export of a Bullet Time clip,
/// the roll of the image followed the tilt of the camera with a factor of 0.98 (correlation 0.90 on 181 frames). If
/// the view is vertical, the top is camera -z.
fn bullet_time_view(level: &Mat3, forward: &[f64; 3]) -> Mat3 {
    let world_up = apply(level, &[0.0, 1.0, 0.0]);
    let along = dot(&world_up, forward);
    let up = std::array::from_fn(|i| world_up[i] - along * forward[i]);
    if norm(&up) < 1e-6 {
        return BULLET_TIME_VIEW;
    }
    let up = normalize(&up);
    let right = cross(forward, &up);
    std::array::from_fn(|i| [right[i], up[i], -forward[i]])
}

/// The view direction of each frame in camera coordinates: the stick direction (camera -y) in the world, smoothed
/// with a Gaussian of `sigma` frames (the ends repeat).
fn bullet_time_forwards(levels: &[Mat3], sigma: f64) -> Vec<[f64; 3]> {
    let stick: Vec<[f64; 3]> = levels
        .iter()
        .map(|level| apply(&transpose(level), &[0.0, -1.0, 0.0]))
        .collect();
    let reach = (4.0 * sigma).ceil() as isize;
    let last = stick.len() as isize - 1;
    levels
        .iter()
        .enumerate()
        .map(|(k, level)| {
            let mut sum = [0.0; 3];
            for d in -reach..=reach {
                let w = (-0.5 * (d as f64 / sigma.max(1e-9)).powi(2)).exp();
                let s = stick[(k as isize + d).clamp(0, last) as usize];
                (0..3).for_each(|i| sum[i] += w * s[i]);
            }
            apply(level, &normalize(&sum))
        })
        .collect()
}

/// Keeps only the rotations of the frames of `range`. The rotation of the frame `range.first + i` is then at `i`.
fn rotations_of_range<T>(mut rotations: Vec<T>, range: FrameRange) -> Vec<T> {
    rotations.truncate(range.first + range.count);
    rotations.drain(..range.first.min(rotations.len()));
    rotations.shrink_to_fit();
    rotations
}

/// Turns the rotations of `--stabilization off` into the Bullet Time view of each frame (`levels`: the rotations of
/// `--stabilization lock`, `fps`: the frame rate of the clip). The rolling shutter rotations keep their change in the
/// frame.
fn bullet_time_rotations(rotations: &mut [FrameRotation], levels: &[Mat3], fps: f64) {
    let forwards = bullet_time_forwards(levels, BULLET_TIME_SMOOTHING_S * fps);
    for ((rotation, level), forward) in rotations.iter_mut().zip(levels).zip(&forwards) {
        let view = bullet_time_view(level, forward);
        let fix = mul(&transpose(&rotation.centre), &view);
        rotation.centre = view;
        for rows in &mut rotation.rows {
            for row in rows.iter_mut() {
                *row = mul(row, &fix);
            }
        }
    }
}

/// Adds the 360 video metadata to the ffmpeg output `stitched` and writes it to `output`.
/// If that fails, the CLI keeps the encode: it moves `stitched` to `output` without the metadata.
/// Without the metadata, the video is correct, but players show it flat.
fn finish_video(stitched: &Path, output: &Path) -> Result<()> {
    if let Err(error) = write_spherical_mp4_file(stitched, output) {
        eprintln!("insta360-stitch: the output has no 360 video metadata: {error}");
        std::fs::rename(stitched, output)?;
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use insta360_stitch::math::IDENTITY;
    use insta360_stitch::{stitch_photo, Lens};

    /// [`pipeline`] with a stitch that gives each output at once.
    fn pipeline_at_once<P: Send>(
        decoded: impl Read + Send,
        encoded: impl Write + Send,
        bytes: (usize, usize),
        limit: usize,
        radius: usize,
        prepare: impl Fn(&[u8]) -> insta360_stitch::Result<P> + Sync,
        stitch: impl Fn(usize, &[u8], &[&P], &mut [u8]) -> Result<()>,
    ) -> Result<usize> {
        pipeline(
            decoded,
            encoded,
            bytes,
            limit,
            (radius, 0),
            prepare,
            |index, frame, near, mut out| {
                stitch(index, frame, near, &mut out)?;
                Ok(Some(out))
            },
            || Ok(None),
        )
    }

    /// A small test model with two identical lenses, and a photo of `width` x `height` pixels for it.
    fn test_photo(width: usize, height: usize) -> (LensModel, Vec<u8>) {
        let pixels: Vec<u8> = (0..width * height * 3)
            .map(|i| (i * 7 % 251) as u8)
            .collect();
        let lens = Lens {
            rotation: IDENTITY,
            cx: 64.0,
            cy: 64.0,
            radius: 64.0,
            mei: None,
        };
        let model = LensModel {
            lenses: [lens, lens],
            coefficients: [0.0, 0.03159, -8.415e-5, 2.201e-6, -1.284e-8],
            half_fov: 100.0,
            level: IDENTITY,
            blend: None,
        };
        (model, pixels)
    }

    #[test]
    fn only_the_rotations_of_the_range_stay() {
        let range = |first, count| FrameRange {
            first,
            count,
            repeat_last: 1,
        };
        let kept = rotations_of_range((0..10).collect::<Vec<u32>>(), range(3, 4));
        assert_eq!(
            (kept.as_slice(), kept.capacity()),
            ([3, 4, 5, 6].as_slice(), 4)
        );
        assert_eq!(
            rotations_of_range((0..10).collect::<Vec<u32>>(), range(0, 10)),
            (0..10).collect::<Vec<_>>()
        );
    }

    #[test]
    fn rows_give_the_encoder_the_stitched_rows_across_bands() {
        // 150 rows: two full bands of BAND_ROWS and a short band.
        let (width, height) = (300, 150);
        let (model, pixels) = test_photo(width, height);
        let source = Image {
            width,
            height,
            channels: 3,
            data: &pixels,
        };
        let expected = stitch_photo(&source, &model).unwrap();
        let seam = PhotoSeam::new(&source, &model).unwrap();
        std::thread::scope(|scope| {
            let rows = Rows::stitched(scope, source, &model, &seam);
            // The encoder asks for each row in sequence and then gives the last row again at the bottom edge.
            for y in (0..height).chain([height - 1, height - 1]) {
                let mut buffers: [Vec<u8>; 4] = Default::default();
                (&rows).fill_buffers(y as u16, &mut buffers);
                let want: Vec<u8> = expected[y * width * 3..][..width * 3]
                    .as_chunks::<3>()
                    .0
                    .iter()
                    .map(|p| rgb_to_ycbcr(p[0], p[1], p[2]).0)
                    .collect();
                assert_eq!(buffers[0], want, "row {y}");
            }
            rows.check().unwrap();
        });
    }

    #[test]
    fn a_stitch_error_stops_the_photo_and_leaves_no_file() {
        let (width, height) = (256, 128);
        let (model, pixels) = test_photo(width, height);
        let good = Image {
            width,
            height,
            channels: 3,
            data: &pixels,
        };
        let seam = PhotoSeam::new(&good, &model).unwrap();
        // One byte short: the stitch of the first band fails.
        let bad = Image {
            data: &pixels[1..],
            ..good
        };
        let folder = new_temp_folder(&std::env::temp_dir()).unwrap();
        let output = folder.join("pano.jpg");
        let result = std::thread::scope(|scope| {
            write_panorama_jpeg(&output, Rows::stitched(scope, bad, &model, &seam), 90, None)
        });
        let error = result.unwrap_err().to_string();
        assert!(error.contains("image data does not match"), "{error}");
        assert_eq!(std::fs::read_dir(&folder).unwrap().count(), 0);
        std::fs::remove_dir_all(&folder).ok();
    }

    #[test]
    fn a_stitch_error_comes_before_the_write_error_that_follows_it() {
        /// Fails each write after the SOS segment: the encoder has then read rows.
        struct FailsInTheScan(Vec<u8>);
        impl Write for FailsInTheScan {
            fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
                match self.0.windows(2).position(|w| w == [0xff, 0xda]) {
                    Some(sos) if self.0.len() >= sos + 14 => {
                        Err(std::io::Error::other("disk full"))
                    }
                    _ => {
                        self.0.extend_from_slice(bytes);
                        Ok(bytes.len())
                    }
                }
            }
            fn flush(&mut self) -> std::io::Result<()> {
                Ok(())
            }
        }
        let (width, height) = (256, 128);
        let (model, pixels) = test_photo(width, height);
        let good = Image {
            width,
            height,
            channels: 3,
            data: &pixels,
        };
        let seam = PhotoSeam::new(&good, &model).unwrap();
        let encode = |source| {
            std::thread::scope(|scope| {
                let rows = Rows::stitched(scope, source, &model, &seam);
                encode_panorama(FailsInTheScan(Vec::new()), &rows, 90, None)
                    .unwrap_err()
                    .to_string()
            })
        };
        // A good photo: the write error.
        let error = encode(good);
        assert!(error.contains("disk full"), "{error}");
        // One byte short: the stitch of the first band fails, then the write fails.
        let error = encode(Image {
            data: &pixels[1..],
            ..good
        });
        assert!(error.contains("image data does not match"), "{error}");
    }

    #[test]
    fn the_stitch_thread_stops_when_the_encoder_stops_early() {
        let (width, height) = (512, 256);
        let (model, pixels) = test_photo(width, height);
        let source = Image {
            width,
            height,
            channels: 3,
            data: &pixels,
        };
        let seam = PhotoSeam::new(&source, &model).unwrap();
        // The scope waits for the stitch thread. It must not wait for ever when the rows are dropped.
        std::thread::scope(|scope| {
            let rows = Rows::stitched(scope, source, &model, &seam);
            (&rows).fill_buffers(0, &mut Default::default());
        });
    }

    /// A new, empty folder for one test.
    fn test_folder(name: &str) -> PathBuf {
        let folder =
            std::env::temp_dir().join(format!("insta360-cli-{name}-{}", std::process::id()));
        std::fs::remove_dir_all(&folder).ok();
        std::fs::create_dir_all(&folder).unwrap();
        folder
    }

    fn make_box(kind: &[u8; 4], body: &[u8]) -> Vec<u8> {
        [&((8 + body.len()) as u32).to_be_bytes()[..], kind, body].concat()
    }

    /// A minimal MP4 file as ffmpeg writes it without faststart: ftyp, mdat, then moov with one video track.
    fn minimal_mp4() -> Vec<u8> {
        let full = |kind: &[u8; 4], body: &[u8]| make_box(kind, &[&[0u8; 4][..], body].concat());
        let ftyp = make_box(b"ftyp", b"isom\0\0\x02\0isomiso2");
        let mdat = make_box(b"mdat", b"VIDEO-ONE");
        let entry = make_box(b"avc1", &[0u8; 78]);
        let stsd = full(b"stsd", &[&1u32.to_be_bytes()[..], &entry].concat());
        let offset = (ftyp.len() as u32 + 8).to_be_bytes();
        let stco = full(b"stco", &[&1u32.to_be_bytes()[..], &offset].concat());
        let hdlr = full(b"hdlr", &[&[0u8; 4][..], b"vide", &[0u8; 13]].concat());
        let minf = make_box(b"minf", &make_box(b"stbl", &[stsd, stco].concat()));
        let trak = make_box(b"trak", &make_box(b"mdia", &[hdlr, minf].concat()));
        [ftyp, mdat, make_box(b"moov", &trak)].concat()
    }

    #[test]
    fn finish_video_keeps_the_encode_when_the_metadata_step_fails() {
        let folder = test_folder("finish");
        let (stitched, output) = (folder.join("stitched.mp4"), folder.join("out.mp4"));
        std::fs::write(&stitched, minimal_mp4()).unwrap();
        finish_video(&stitched, &output).unwrap();
        let out = std::fs::read(&output).unwrap();
        assert!(out.windows(4).any(|w| w == b"sv3d"));

        // The metadata step refuses this file. The encode must become the output, not disappear.
        std::fs::write(&stitched, b"an encode that is not a usual MP4 file").unwrap();
        finish_video(&stitched, &output).unwrap();
        assert_eq!(
            std::fs::read(&output).unwrap(),
            b"an encode that is not a usual MP4 file"
        );
        assert!(!stitched.exists());
        std::fs::remove_dir_all(&folder).unwrap();
    }

    #[test]
    fn a_bracket_of_three_photos_is_merged_and_a_bracket_of_two_is_refused() {
        let folder = test_folder("bracket");
        let photo_file = folder.join("IMG_1.insp");
        std::fs::write(
            &photo_file,
            include_bytes!("../../../tests/fixtures/synthetic_x5.insp"),
        )
        .unwrap();
        let out = folder.join("merged.jpg");
        let others = [photo_file.clone(), photo_file.clone()];
        photo(&photo_file, &out, 95, None, &others, GpuMode::Auto).unwrap();
        assert!(std::fs::metadata(&out).unwrap().len() > 0);
        let two = folder.join("two.jpg");
        let error = photo(&photo_file, &two, 95, None, &others[..1], GpuMode::Auto).unwrap_err();
        assert!(error.to_string().contains("2 exposures"), "{error}");
        assert!(!two.exists());
        let error = photo(
            &photo_file,
            &out,
            95,
            None,
            &[out.clone(), photo_file.clone()],
            GpuMode::Auto,
        )
        .unwrap_err();
        assert!(error.to_string().contains("--bracket"), "{error}");
        std::fs::remove_dir_all(&folder).unwrap();
    }

    #[test]
    fn the_level_from_photo_gives_the_level_and_must_be_a_usable_other_file() {
        let folder = test_folder("level-from");
        let photo_file = folder.join("IMG_1.insp");
        std::fs::write(
            &photo_file,
            include_bytes!("../../../tests/fixtures/synthetic_x5.insp"),
        )
        .unwrap();
        let (plain, same) = (folder.join("plain.jpg"), folder.join("same.jpg"));
        photo(&photo_file, &plain, 95, None, &[], GpuMode::Auto).unwrap();
        // The photo as its own reference gives its own level, thus the same output.
        photo(
            &photo_file,
            &same,
            95,
            Some(&photo_file),
            &[],
            GpuMode::Auto,
        )
        .unwrap();
        assert_eq!(
            std::fs::read(&plain).unwrap(),
            std::fs::read(&same).unwrap()
        );
        let not_a_photo = folder.join("note.txt");
        std::fs::write(&not_a_photo, b"not an Insta360 file").unwrap();
        let out = folder.join("out.jpg");
        assert!(photo(
            &photo_file,
            &out,
            95,
            Some(&not_a_photo),
            &[],
            GpuMode::Auto
        )
        .is_err());
        assert!(!out.exists());
        let error = photo(&photo_file, &out, 95, Some(&out), &[], GpuMode::Auto)
            .unwrap_err()
            .to_string();
        assert!(error.contains("--level-from"), "{error}");
        std::fs::remove_dir_all(&folder).unwrap();
    }

    #[test]
    fn a_band_stream_is_padded_to_a_square_at_its_row() {
        let line =
            |w: u32, h: u32| format!("width={w}|height={h}|r_frame_rate=120/1|nb_frames=9\n");
        let probe = parse_probe(&line(2880, 1440).repeat(2)).unwrap();
        assert_eq!((probe.lens_size, probe.lens_height), (2880, 1440));
        let args: Vec<String> = decoder_command(
            &test_video_options(),
            &probe,
            2880,
            Some(1440),
            Path::new("in.insv"),
            FrameRange::whole(&probe),
        )
        .get_args()
        .map(|a| a.to_string_lossy().into_owned())
        .collect();
        let filter = &args[args.iter().position(|a| a == "-filter_complex").unwrap() + 1];
        let pads = "[0:v:1]pad=2880:2880:0:1440[l0];[0:v:0]pad=2880:2880:0:1440[l1];[l0][l1]vstack";
        assert!(filter.starts_with(pads), "{filter}");
        // A stream that is higher than wide is not a band.
        assert!(parse_probe(&line(1440, 2880).repeat(2)).is_err());
    }

    #[test]
    fn the_bullet_time_view_looks_along_the_stick_with_the_world_up_on_top() {
        use insta360_stitch::math::{apply, axis_rotation, IDENTITY};
        let close = |x: &[f64], y: &[f64]| x.iter().zip(y).all(|(p, q)| (p - q).abs() < 1e-12);
        // World up along camera -z: the fixed view.
        let level_z = axis_rotation('x', -90.0);
        assert!(close(&apply(&level_z, &[0.0, 1.0, 0.0]), &[0.0, 0.0, -1.0]));
        assert!(close(
            bullet_time_view(&level_z, &[0.0, -1.0, 0.0]).as_flattened(),
            BULLET_TIME_VIEW.as_flattened()
        ));
        // A camera that rolls 10 degrees about the stick: the top of the view is the world up, not camera -z.
        let level = mul(&axis_rotation('y', 10.0), &level_z);
        let view = bullet_time_view(&level, &[0.0, -1.0, 0.0]);
        let world_up = apply(&level, &[0.0, 1.0, 0.0]);
        assert!(close(&apply(&view, &[0.0, 0.0, -1.0]), &[0.0, -1.0, 0.0]));
        assert!(close(&apply(&view, &[0.0, 1.0, 0.0]), &world_up));
        // A vertical stick has no world up in the image: camera -z is the top.
        assert!(close(
            bullet_time_view(&IDENTITY, &[0.0, -1.0, 0.0]).as_flattened(),
            BULLET_TIME_VIEW.as_flattened()
        ));
        // The rolling rows keep their change in the frame: a row that turns by A in Off turns by A in the view.
        let f = axis_rotation('x', 30.0);
        let a = axis_rotation('z', 2.0);
        let mut rotations = [FrameRotation {
            centre: f,
            rows: [vec![f, mul(&a, &f)], vec![]],
        }];
        bullet_time_rotations(&mut rotations, &[level], 120.0);
        assert!(close(
            rotations[0].centre.as_flattened(),
            view.as_flattened()
        ));
        assert!(close(
            rotations[0].rows[0][0].as_flattened(),
            view.as_flattened()
        ));
        assert!(close(
            rotations[0].rows[0][1].as_flattened(),
            mul(&a, &view).as_flattened()
        ));
        assert!(rotations[0].rows[1].is_empty());
    }

    #[test]
    fn the_bullet_time_view_follows_a_smoothed_stick() {
        use insta360_stitch::math::{apply, axis_rotation};
        let level_z = axis_rotation('x', -90.0);
        // The camera turns about the world up by +1 and -1 degree in turn: the smoothed view looks to the middle.
        let levels: Vec<Mat3> = (0..41)
            .map(|k| {
                mul(
                    &level_z,
                    &axis_rotation('y', if k % 2 == 0 { 1.0 } else { -1.0 }),
                )
            })
            .collect();
        let forwards = bullet_time_forwards(&levels, 5.0);
        let middle = apply(&transpose(&levels[20]), &forwards[20]);
        let stick = apply(&transpose(&levels[20]), &[0.0, -1.0, 0.0]);
        let level_stick = apply(&transpose(&level_z), &[0.0, -1.0, 0.0]);
        let angle = |a: &[f64; 3], b: &[f64; 3]| dot(a, b).clamp(-1.0, 1.0).acos().to_degrees();
        assert!((angle(&stick, &level_stick) - 1.0).abs() < 1e-9);
        assert!(
            angle(&middle, &level_stick) < 0.01,
            "{}",
            angle(&middle, &level_stick)
        );
        // A camera that does not turn keeps its stick direction, also at the ends.
        let still = bullet_time_forwards(&[level_z; 3], 5.0);
        assert!(still.iter().all(|f| angle(f, &[0.0, -1.0, 0.0]) < 1e-6));
    }

    #[test]
    fn a_bullet_time_view_is_flat_at_29_97_fps_without_audio() {
        let probe = parse_probe(
            &"width=64|height=32|r_frame_rate=120000/1001|nb_frames=9
"
            .repeat(2),
        )
        .unwrap();
        let args: Vec<String> = encoder_command(
            &test_video_options(),
            &probe,
            (128, 64),
            Some((1920, 1080)),
            Path::new("in.insv"),
            Path::new("out.mp4"),
            FrameRange::whole(&probe),
        )
        .get_args()
        .map(|a| a.to_string_lossy().into_owned())
        .collect();
        let after = |key: &str| &args[args.iter().position(|a| a == key).unwrap() + 1];
        assert_eq!(after("-framerate"), "30000/1001");
        assert!(
            after("-vf").starts_with("v360=e:sg:h_fov=143:v_fov=88."),
            "{args:?}"
        );
        assert!(after("-vf").ends_with(":w=1920:h=1080"), "{args:?}");
        assert!(args.contains(&"-an".to_string()) && !args.contains(&"1:a?".to_string()));
        assert!((bullet_time_v_fov(1920, 1080) - 88.17).abs() < 0.05);
    }

    #[test]
    fn each_command_refuses_to_write_over_its_input() {
        let folder = test_folder("same");
        let file = folder.join("VID_1.insv");
        std::fs::write(&file, b"original footage").unwrap();
        let results = [
            photo(&file, &file, 95, None, &[], GpuMode::Auto),
            preview(&file, &file),
            video(&file, &file, &test_video_options(), 2, GpuMode::Auto),
        ];
        for result in results {
            let error = result.unwrap_err().to_string();
            assert!(error.contains("different file"), "{error}");
        }
        assert_eq!(std::fs::read(&file).unwrap(), b"original footage");
        std::fs::remove_dir_all(&folder).unwrap();
    }

    fn test_video_options() -> VideoOptions {
        VideoOptions {
            width: None,
            stabilization: None,
            studio_encode: None,
            encoder: "libx264".into(),
            crf: 20,
            preset: "medium".into(),
            encoder_args: vec!["-tune".into(), "film".into()],
            hwaccel: None,
            decoder_threads: 2,
            decoder_args: Vec::new(),
            no_rolling_shutter: false,
            no_seam_flow: false,
            no_color_fusion: false,
            bullet_time_view: false,
            denoise: false,
            denoise_strength: None,
            start: None,
            end: None,
            no_camera_trim: false,
            ffmpeg: "ffmpeg".into(),
            ffprobe: "ffprobe".into(),
        }
    }

    #[test]
    fn probe_reads_square_lens_streams_the_smaller_frame_count_and_the_colour_tags() {
        let line = |frames: &str| {
            format!("width=3840|height=3840|r_frame_rate=24/1|nb_frames={frames}|color_range=tv|color_space=bt709|color_transfer=bt709|color_primaries=unknown\n")
        };
        let probe = parse_probe(&(line("80") + &line("81"))).unwrap();
        assert_eq!(
            probe,
            Probe {
                lens_size: 3840,
                lens_height: 3840,
                rate: "24/1".into(),
                fps: 24.0,
                frame_count: 80,
                colour_args: [
                    "-colorspace",
                    "bt709",
                    "-color_trc",
                    "bt709",
                    "-color_range",
                    "tv"
                ]
                .map(String::from)
                .to_vec(),
                full_range: false,
                file_bitrate: 0,
                duration_us: None,
            }
        );
        let ntsc = "width=2880|height=2880|r_frame_rate=60000/1001|nb_frames=233\n".repeat(2);
        assert!((parse_probe(&ntsc).unwrap().fps - 59.94).abs() < 0.01);
        for bad in [
            line("80"),
            "width=1920|height=3840|r_frame_rate=24/1|nb_frames=80\n".repeat(2),
            "width=64|height=64|r_frame_rate=0/1|nb_frames=5\n".repeat(2),
            "width=64|height=64|r_frame_rate=24/1|nb_frames=N/A\n".repeat(2),
            // An aborted recording: no frames.
            "width=64|height=64|r_frame_rate=24/1|nb_frames=0\n".repeat(2),
        ] {
            assert!(parse_probe(&bad).is_err(), "{bad}");
        }
    }

    fn probe_of(fps_rate: &str) -> Probe {
        let line = format!(
            "width=64|height=64|r_frame_rate={fps_rate}|nb_frames=5|color_range=pc
"
        );
        parse_probe(&line.repeat(2)).unwrap()
    }

    #[test]
    fn studio_exports_one_frame_more_when_the_duration_is_a_whole_number_of_frames() {
        // The durations (whole microseconds) and frame counts of 4 files and their Studio exports.
        for (frames, duration_us, studio) in [
            (90, 3_003_000, 91),
            (8, 266_933, 8),
            (198, 6_606_600, 199),
            (113, 3_770_433, 113),
        ] {
            let mut probe = probe_of("30000/1001");
            probe.frame_count = frames;
            probe.duration_us = Some(duration_us);
            assert_eq!(studio_frame_count(&probe), studio, "{frames} frames");
        }
        // Without a duration, the frames of the file.
        assert_eq!(studio_frame_count(&probe_of("30000/1001")), 5);
    }

    #[test]
    fn the_range_takes_the_cut_only_at_the_ends_without_a_time_and_repeats_only_to_the_end() {
        // 90 frames at 30 fps, and Studio exports 91 (a duration of exactly 90 frames).
        let mut probe = probe_of("30/1");
        (probe.frame_count, probe.duration_us) = (90, Some(3_000_000));
        let plan = |range, cut| plan_range(&probe, range, false, cut).unwrap();
        let of = |r: FrameRange| (r.first, r.count, r.repeat_last);
        // The whole file: the extra frame of Studio.
        assert_eq!(of(plan((None, None), None)), (0, 90, 1));
        // A Bullet Time cut with --start: the start stays, the end comes from the cut, no extra frame.
        assert_eq!(of(plan((Some(1.0), None), Some((10, 59)))), (30, 30, 0));
        // An end time (the user or the camera trim): no extra frame.
        assert_eq!(of(plan((None, Some(2.0)), None)), (0, 61, 0));
        // A container 2 frames longer than the lens streams (audio): still only one extra frame.
        probe.duration_us = Some(3_066_667);
        assert_eq!(
            of(plan_range(&probe, (None, None), false, None).unwrap()),
            (0, 90, 1)
        );
        probe.duration_us = Some(3_000_000);
        // A range that the camera trim emptied tells it.
        let error = plan_range(&probe, (Some(2.5), Some(0.5)), true, None).unwrap_err();
        assert!(error.to_string().contains("--no-camera-trim"), "{error}");
        let error = plan_range(&probe, (Some(2.5), Some(0.5)), false, None).unwrap_err();
        assert!(!error.to_string().contains("--no-camera-trim"), "{error}");
    }

    #[test]
    fn encoder_args_add_quality_only_for_x264_and_x265() {
        let probe = probe_of("24/1");
        let mut options = test_video_options();
        assert_eq!(
            encoder_args(&options, &probe),
            [
                "-c:v", "libx264", "-preset", "medium", "-crf", "20", "-pix_fmt", "yuv420p",
                "-tune", "film"
            ]
        );
        options.encoder = "hevc_vaapi".into();
        options.encoder_args = vec!["-vf".into(), "format=nv12,hwupload".into()];
        assert_eq!(
            encoder_args(&options, &probe),
            ["-c:v", "hevc_vaapi", "-vf", "format=nv12,hwupload"]
        );
    }

    #[test]
    fn studio_encode_gives_hevc_at_the_file_bitrate_with_a_key_frame_each_second() {
        let mut probe = probe_of("30000/1001");
        probe.file_bitrate = 153_314_373;
        let mut options = test_video_options();
        options.studio_encode = Some(StudioEncoder::Libx265);
        options.encoder_args = vec!["-threads".into(), "4".into()];
        assert_eq!(
            encoder_args(&options, &probe),
            [
                "-c:v",
                "libx265",
                "-preset",
                "medium",
                "-b:v",
                "153314373",
                "-x265-params",
                // 29.97 fps: a GOP of 30. scenecut=0 keeps the key frames at fixed places.
                "keyint=30:min-keyint=30:scenecut=0:bframes=0",
                "-pix_fmt",
                "yuv420p",
                "-tag:v",
                "hvc1",
                "-threads",
                "4"
            ]
        );
    }

    #[test]
    fn the_file_bitrate_is_the_size_over_the_video_duration() {
        // Studio clip 018: 1335808342 bytes, 2089 frames at 30000/1001 fps (69.703 s). ffprobe: 153314373.
        let bitrate = file_bitrate(1_335_808_342, 2089, 30000.0 / 1001.0);
        assert!(bitrate.abs_diff(153_314_373) < 1000, "{bitrate}");
    }

    #[test]
    fn studio_encode_does_not_go_with_an_encoder_or_a_crf() {
        use clap::Parser;
        let parse = |extra: &[&str]| {
            let mut args = vec!["insta360-stitch", "video", "in.insv", "out.mp4"];
            args.extend(extra);
            Cli::try_parse_from(args)
        };
        assert!(parse(&["--studio-encode", "--preset", "fast"]).is_ok());
        assert!(parse(&["--studio-encode=hevc_nvenc"]).is_ok());
        assert!(parse(&["--studio-encode=libx264"]).is_err());
        assert!(parse(&["--studio-encode", "--encoder", "libx264"]).is_err());
        assert!(parse(&["--studio-encode", "--crf", "18"]).is_err());
    }

    #[test]
    fn studio_encode_with_nvenc_has_the_encoder_settings_of_studio() {
        let mut probe = probe_of("30000/1001");
        probe.file_bitrate = 153_314_373;
        let mut options = test_video_options();
        options.studio_encode = Some(StudioEncoder::HevcNvenc);
        assert_eq!(
            encoder_args(&options, &probe),
            [
                "-c:v",
                "hevc_nvenc",
                "-b:v",
                "153314373",
                "-bf",
                "0",
                "-g",
                "30",
                "-pix_fmt",
                "yuv420p",
                "-tag:v",
                "hvc1",
                // The options of the user come last.
                "-tune",
                "film"
            ]
        );
    }

    #[test]
    fn a_file_at_the_temporary_name_is_not_written_over() {
        let folder = std::env::temp_dir().join(format!("insta360-cli-part-{}", std::process::id()));
        std::fs::create_dir_all(&folder).unwrap();
        let output = folder.join("out.gpx");
        // Files at the temporary names of the next calls of this process (pid and call counter). A link to
        // another file at the same name is the dangerous case: `create_new` refuses both.
        let parts: Vec<PathBuf> = (0..64)
            .map(|n| {
                let mut part = output.as_os_str().to_owned();
                part.push(format!(".{}-{n}.part", std::process::id()));
                std::fs::write(&part, b"keep").unwrap();
                part.into()
            })
            .collect();
        assert!(write_atomically(&output, |out| Ok(out.write_all(b"gpx")?)).is_err());
        assert!(!output.exists());
        for part in &parts {
            assert_eq!(std::fs::read(part).unwrap(), b"keep");
        }
        std::fs::remove_dir_all(&folder).unwrap();
    }

    #[test]
    fn a_program_that_does_not_start_is_named_in_the_error() {
        let error = probe("no-such-ffprobe-program", Path::new("in.insv")).unwrap_err();
        assert!(
            error.to_string().contains("no-such-ffprobe-program"),
            "{error}"
        );
    }

    #[test]
    fn only_the_video_filter_options_get_our_filters() {
        for option in [
            "-vf",
            "-vf:0",
            "-filter",
            "-filter:v",
            "-filter:v:0",
            "-filter:0",
        ] {
            assert!(is_video_filter(option), "{option}");
        }
        for option in [
            "-filter:a",
            "-filter:1",
            "-filter_complex",
            "-filter_script:v",
            "-af",
            "-vframes",
        ] {
            assert!(!is_video_filter(option), "{option}");
        }
    }

    #[cfg(unix)]
    #[test]
    fn an_output_that_is_a_device_gets_the_data_directly() {
        // A temporary file next to /dev/null cannot be made by a normal user.
        let result = write_atomically(Path::new("/dev/null"), |out| Ok(out.write_all(b"gpx")?));
        assert!(result.is_ok(), "{result:?}");
    }

    #[test]
    fn a_step_of_the_video_that_the_camera_times_do_not_have_is_found() {
        let fps = 30.0;
        let video: Vec<f64> = [0, 1, 2, 4, 5].iter().map(|&n| n as f64 / fps).collect();
        // The camera times have the same gap, with some jitter: the frames agree.
        let camera = [0.0, 33_400.0, 66_600.0, 133_300.0, 166_700.0];
        assert_eq!(first_unmatched_frame(&video, &camera, fps, 5), None);
        // The camera times have no gap: from frame 3, each frame gets the times of the frame before it.
        let camera = [0.0, 33_333.0, 66_667.0, 100_000.0, 133_333.0];
        assert_eq!(first_unmatched_frame(&video, &camera, fps, 5), Some(3));
        // A gap in the camera times only.
        let video = [0.0, 1.0 / fps, 2.0 / fps];
        assert_eq!(
            first_unmatched_frame(&video, &[0.0, 66_667.0, 100_000.0], fps, 3),
            Some(1)
        );
        // A step after the last stitched frame does not change the stitched frames.
        let video = [0.0, 1.0 / fps, 2.0 / fps, 4.0 / fps];
        let camera = [0.0, 33_333.0, 66_667.0, 100_000.0];
        assert_eq!(first_unmatched_frame(&video, &camera, fps, 3), None);
        assert_eq!(first_unmatched_frame(&video, &camera, fps, 4), Some(3));
    }

    #[test]
    fn the_denoise_strength_needs_the_denoise_and_is_more_than_0_and_at_most_16() {
        use clap::Parser;
        let parse = |extra: &[&str]| {
            let mut args = vec!["insta360-stitch", "video", "in.insv", "out.mp4"];
            args.extend(extra);
            Cli::try_parse_from(args)
        };
        assert!(parse(&["--denoise", "--denoise-strength", "1.5"]).is_ok());
        assert!(parse(&["--denoise", "--denoise-strength", "16"]).is_ok());
        assert!(parse(&["--denoise-strength", "1.5"]).is_err());
        for bad in ["0", "-1", "16.5", "nan", "inf", "much"] {
            assert!(
                parse(&["--denoise", "--denoise-strength", bad]).is_err(),
                "{bad}"
            );
        }
    }

    #[test]
    fn the_encoder_copies_the_metadata_and_the_colour_tags_and_keeps_all_frames() {
        let line = "width=64|height=64|r_frame_rate=24/1|nb_frames=5|color_range=pc\n";
        let probe = parse_probe(&line.repeat(2)).unwrap();
        let command = encoder_command(
            &test_video_options(),
            &probe,
            (128, 64),
            None,
            Path::new("in.insv"),
            Path::new("out.mp4"),
            FrameRange::whole(&probe),
        );
        let args: Vec<_> = command.get_args().map(|a| a.to_string_lossy()).collect();
        let at = |value: &str| args.iter().position(|a| a == value).unwrap();
        assert!(!args.iter().any(|a| a == "-ss" || a == "-t"), "{args:?}");
        // The metadata comes from the .insv, the second input. It is an output option: after the inputs.
        assert_eq!(args[at("file:in.insv") - 1], "-i");
        assert_eq!(args[at("-map_metadata") + 1], "1");
        assert!(at("-map_metadata") > at("file:in.insv"), "{args:?}");
        // The colour tags are input options of the pipe: ffmpeg then does not convert the frames.
        assert!(at("-color_range") < at("pipe:0"), "{args:?}");
        assert_eq!(args.iter().filter(|a| *a == "-color_range").count(), 1);
        // The audio of an X5 clip ends before the last frame: -shortest would remove the last frames.
        assert!(!args.iter().any(|a| a == "-shortest"), "{args:?}");
        // The output is the last argument, as a file: a folder name with "-" first is not an option.
        assert_eq!(args.last().unwrap(), "file:out.mp4");
    }

    #[test]
    fn the_output_must_not_be_the_input_or_a_camera_file() {
        let dir = std::env::temp_dir();
        let input = dir.join("VID_1_00_001.insv");
        assert!(check_output(&input, &dir.join("out.mp4")).is_ok());
        assert!(check_output(&input, &input).is_err());
        for other in ["VID_2_00_002.insv", "IMG_1.INSP", "LRV_1_01_001.lrv"] {
            assert!(check_output(&input, &dir.join(other)).is_err(), "{other}");
        }
    }

    #[test]
    fn the_time_range_keeps_the_frames_that_studio_keeps() {
        let ntsc = 30000.0 / 1001.0;
        // Studio exports of three clips: the trim of the project, the frames of the source, the frames that Studio wrote.
        assert_eq!(
            frame_range(ntsc, 2089, Some(2.96963), Some(66.7)).unwrap(),
            (89, 1911)
        );
        assert_eq!(
            frame_range(ntsc, 446, Some(2.96963), Some(11.8785)).unwrap(),
            (89, 268)
        );
        assert_eq!(
            frame_range(60000.0 / 1001.0, 233, Some(0.0), Some(3.88722)).unwrap(),
            (0, 233)
        );
        assert_eq!(
            frame_range(120000.0 / 1001.0, 392, None, Some(3.26159)).unwrap(),
            (0, 392)
        );
        // No range is the whole video; a range after the end is an error; an end before the start too.
        assert_eq!(frame_range(24.0, 80, None, None).unwrap(), (0, 80));
        assert_eq!(frame_range(24.0, 80, Some(1.0), None).unwrap(), (24, 56));
        assert!(frame_range(24.0, 80, Some(10.0), None).is_err());
        assert!(frame_range(24.0, 80, Some(2.0), Some(1.0)).is_err());
        // A frame a little before the start time (within 1 ms) is in the range.
        assert_eq!(
            frame_range(24.0, 80, Some(1.0004), Some(1.0)).unwrap(),
            (24, 1)
        );
    }

    #[test]
    fn the_camera_trim_cuts_the_frames_that_studio_cuts_by_default() {
        let range = |fps: f64, n: usize, trim: [u64; 2], start: Option<f64>, end: Option<f64>| {
            let (start, end) = camera_trim(fps, n, trim, start, end);
            frame_range(fps, n, start, end).unwrap()
        };
        // The frame counts of Studio exports of 3000/3000 ms clips: 451 frames at 25 fps give 302, 732 and 446
        // frames at 29.97 fps give 554 and 268.
        let ntsc = 30000.0 / 1001.0;
        assert_eq!(range(25.0, 451, [3000, 3000], None, None), (75, 302));
        assert_eq!(range(ntsc, 732, [3000, 3000], None, None), (89, 554));
        assert_eq!(range(ntsc, 446, [3000, 3000], None, None), (89, 268));
        assert_eq!(range(25.0, 750, [3000, 0], None, None), (75, 675));
        assert_eq!(range(25.0, 750, [0, 0], None, None), (0, 750));
        // A time that the user gives replaces the trim at that end.
        assert_eq!(range(25.0, 750, [3000, 3000], Some(1.0), None), (25, 651));
        assert_eq!(range(25.0, 750, [3000, 3000], None, Some(20.0)), (75, 426));
        // A trim that leaves no frame does not apply.
        assert_eq!(range(25.0, 100, [3000, 3000], None, None), (0, 100));
    }

    #[test]
    fn a_time_range_seeks_the_decoder_and_cuts_the_audio_to_the_same_frames() {
        let line = "width=64|height=64|r_frame_rate=24/1|nb_frames=240|color_range=pc
";
        let probe = parse_probe(&line.repeat(2)).unwrap();
        let range = FrameRange {
            first: 48,
            count: 24,
            repeat_last: 0,
        };
        let strings = |command: Command| -> Vec<String> {
            command
                .get_args()
                .map(|a| a.to_string_lossy().into_owned())
                .collect()
        };
        let decoder = strings(decoder_command(
            &test_video_options(),
            &probe,
            64,
            None,
            Path::new("in.insv"),
            range,
        ));
        let seek = decoder.iter().position(|a| a == "-ss").expect("no seek");
        let frames = decoder
            .iter()
            .position(|a| a == "-frames:v")
            .expect("no frame limit");
        assert_eq!(decoder[frames + 1], "24");
        // Half a frame before frame 48, and as an input option of the decoder.
        assert_eq!(decoder[seek + 1], "1.979167");
        assert!(
            seek < decoder.iter().position(|a| a == "file:in.insv").unwrap(),
            "{decoder:?}"
        );
        let encoder = strings(encoder_command(
            &test_video_options(),
            &probe,
            (128, 64),
            None,
            Path::new("in.insv"),
            Path::new("out.mp4"),
            range,
        ));
        let at = |value: &str| encoder.iter().position(|a| a == value).unwrap();
        assert_eq!(encoder[at("-ss") + 1], "2.000000");
        assert_eq!(encoder[at("-t") + 1], "1.000000");
        // The range options belong to the second input (the audio), not to the pipe.
        assert!(
            at("pipe:0") < at("-ss") && at("-ss") < at("file:in.insv"),
            "{encoder:?}"
        );
        assert!(!encoder.iter().any(|a| a == "-vf"), "{encoder:?}");
        // A copy of the last frame (see `studio_frame_count`) is a filter of the encoder.
        let repeat = FrameRange {
            repeat_last: 1,
            ..range
        };
        let encoder = strings(encoder_command(
            &test_video_options(),
            &probe,
            (128, 64),
            None,
            Path::new("in.insv"),
            Path::new("out.mp4"),
            repeat,
        ));
        let at = |value: &str| encoder.iter().position(|a| a == value).unwrap();
        assert_eq!(encoder[at("-vf") + 1], "tpad=stop=1:stop_mode=clone");
        // A -vf of the user gets the filter first, in the same -vf: ffmpeg uses only the last -vf.
        let mut options = test_video_options();
        options.encoder_args = vec!["-vf".into(), "hwupload".into()];
        let encoder = strings(encoder_command(
            &options,
            &probe,
            (128, 64),
            None,
            Path::new("in.insv"),
            Path::new("out.mp4"),
            repeat,
        ));
        assert_eq!(
            encoder.iter().filter(|a| *a == "-vf").count(),
            1,
            "{encoder:?}"
        );
        let at = |value: &str| encoder.iter().position(|a| a == value).unwrap();
        assert_eq!(
            encoder[at("-vf") + 1],
            "tpad=stop=1:stop_mode=clone,hwupload"
        );
        // ffmpeg uses the last one: only that one gets the filter. A last option with no value is not used.
        let tpad = "tpad=stop=1:stop_mode=clone";
        for (user, expected) in [
            (
                vec!["-vf", "a", "-filter:v:0", "b"],
                vec![vec![
                    "-vf",
                    "a",
                    "-filter:v:0",
                    "tpad=stop=1:stop_mode=clone,b",
                ]],
            ),
            (
                vec!["-vf", "a", "-vf"],
                vec![vec!["-vf", tpad], vec!["-vf", "a", "-vf"]],
            ),
        ] {
            let mut options = test_video_options();
            options.encoder_args = user.iter().map(|a| a.to_string()).collect();
            let encoder = strings(encoder_command(
                &options,
                &probe,
                (128, 64),
                None,
                Path::new("in.insv"),
                Path::new("out.mp4"),
                repeat,
            ));
            for args in expected {
                assert!(
                    encoder.windows(args.len()).any(|w| w == args),
                    "{encoder:?}"
                );
            }
        }
        // The whole video gets no range options.
        let whole = strings(decoder_command(
            &test_video_options(),
            &probe,
            64,
            None,
            Path::new("in.insv"),
            FrameRange::whole(&probe),
        ));
        assert!(
            !whole.iter().any(|a| a == "-ss" || a == "-frames:v"),
            "{whole:?}"
        );
    }

    #[test]
    fn the_range_options_are_times_of_0_seconds_or_more() {
        let parse = |args: &[&str]| {
            Cli::try_parse_from([&["insta360-stitch", "video", "a", "b"], args].concat())
        };
        let options = |cli: Cli| match cli.command {
            Commands::Video { options, .. } => options,
            _ => panic!("not the video command"),
        };
        let cli = options(parse(&["--start", "2.5", "--end", "10"]).unwrap());
        assert_eq!((cli.start, cli.end), (Some(2.5), Some(10.0)));
        let cli = options(parse(&[]).unwrap());
        assert_eq!((cli.start, cli.end), (None, None));
        assert!(parse(&["--start", "-1"]).is_err());
        assert!(parse(&["--end", "nan"]).is_err());
        assert!(parse(&["--start", "abc"]).is_err());
    }

    #[test]
    fn the_gpu_is_a_global_option_auto_or_off() {
        let gpu = |args: &[&str]| {
            Cli::try_parse_from([&["insta360-stitch"], args].concat())
                .map(|cli| GpuMode::from(cli.gpu))
        };
        assert_eq!(gpu(&["photo", "a", "b"]).unwrap(), GpuMode::Auto);
        assert_eq!(
            gpu(&["photo", "a", "b", "--gpu", "off"]).unwrap(),
            GpuMode::Off
        );
        assert_eq!(
            gpu(&["--gpu", "off", "video", "a", "b"]).unwrap(),
            GpuMode::Off
        );
        assert!(gpu(&["photo", "a", "b", "--gpu", "on"]).is_err());
    }

    #[test]
    fn a_photo_with_the_gpu_off_is_the_same_as_with_the_gpu() {
        let folder = test_folder("gpu-off");
        let photo_file = folder.join("IMG_1.insp");
        std::fs::write(
            &photo_file,
            include_bytes!("../../../tests/fixtures/synthetic_x5.insp"),
        )
        .unwrap();
        let (auto, off) = (folder.join("auto.jpg"), folder.join("off.jpg"));
        photo(&photo_file, &auto, 95, None, &[], GpuMode::Auto).unwrap();
        photo(&photo_file, &off, 95, None, &[], GpuMode::Off).unwrap();
        let decode = |path: &Path| image::open(path).unwrap().to_rgb8().into_raw();
        let (auto, off) = (decode(&auto), decode(&off));
        assert_eq!(auto.len(), off.len());
        // The GPU can be 1 level off on a few bytes; the JPEG encode can make that 2 or 3.
        assert!(auto.iter().zip(&off).all(|(a, b)| a.abs_diff(*b) <= 8));
    }

    #[test]
    fn threads_are_a_global_option_of_at_least_1() {
        let parse = |args: &[&str]| Cli::try_parse_from([&["insta360-stitch"], args].concat());
        let cli = parse(&["video", "in.insv", "out.mp4", "--threads", "4"]).unwrap();
        assert_eq!(cli.threads, Some(4));
        assert_eq!(
            parse(&["--threads", "2", "photo", "a", "b"])
                .unwrap()
                .threads,
            Some(2)
        );
        assert!(parse(&["photo", "a", "b", "--threads", "0"]).is_err());
        let Commands::Video { options, .. } = parse(&["video", "a", "b"]).unwrap().command else {
            panic!("not the video command")
        };
        assert_eq!(options.decoder_threads, 2);
        // The rolling shutter correction is on by default, as in Insta360 Studio.
        assert!(!options.no_rolling_shutter);
        let Commands::Video { options, .. } = parse(&["video", "a", "b", "--no-rolling-shutter"])
            .unwrap()
            .command
        else {
            panic!("not the video command")
        };
        assert!(options.no_rolling_shutter);
    }

    #[test]
    fn width_must_be_a_multiple_of_4_from_16() {
        for good in ["16", "3840", "16384"] {
            assert!(parse_width(good).is_ok(), "{good}");
        }
        // 3002 gives the odd lens size 1501, and 12 gives 6: the error must name the width.
        for bad in ["3002", "12", "0", "16388", "wide"] {
            assert!(parse_width(bad).is_err(), "{bad}");
        }
    }

    /// An encoder pipe that is slower than the stitch and stops after `0` writes, as an ffmpeg that exits.
    struct StoppingWriter(usize);

    impl Write for StoppingWriter {
        fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
            std::thread::sleep(std::time::Duration::from_millis(20));
            if self.0 == 0 {
                return Err(std::io::ErrorKind::BrokenPipe.into());
            }
            self.0 -= 1;
            Ok(buf.len())
        }

        fn flush(&mut self) -> std::io::Result<()> {
            Ok(())
        }
    }

    /// Runs `run` in a thread and fails if it does not end in 10 s: a pipeline that waits without end.
    fn in_time<T: Send + 'static>(run: impl FnOnce() -> T + Send + 'static) -> T {
        let (tx, rx) = std::sync::mpsc::channel();
        std::thread::spawn(move || tx.send(run()).ok());
        match rx.recv_timeout(std::time::Duration::from_secs(10)) {
            Ok(value) => value,
            Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {
                panic!("the pipeline waits without end")
            }
            Err(_) => panic!("the pipeline thread panicked"),
        }
    }

    #[test]
    fn a_frame_is_at_position_index_or_radius_in_its_window() {
        // The colour fusion of a frame is the item of the frame itself, at the start, in the middle and at the end.
        for radius in [0, 2] {
            let seen = in_time(move || {
                let input: Vec<u8> = (0..7u8).collect();
                let mut output = Vec::new();
                pipeline_at_once(
                    &input[..],
                    &mut output,
                    (1, 1),
                    10,
                    radius,
                    |frame| Ok(frame[0]),
                    |index, frame, near, out| {
                        let own = frame_itself(near, index, radius).copied();
                        out[0] = u8::from(own == Some(frame[0]));
                        Ok(())
                    },
                )
                .map_err(|e| e.to_string())
                .map(|_| output)
            });
            assert_eq!(seen, Ok(vec![1; 7]), "radius {radius}");
        }
    }

    #[test]
    fn the_denoise_writer_gives_the_bytes_of_the_denoiser_for_all_write_sizes() {
        let (w, h) = (64usize, 64usize);
        let size = w * h * 3 / 2;
        let count = 9;
        // Frames that are not flat, so that a frame in the wrong place gives other bytes.
        let stream: Vec<u8> = (0..count * size)
            .map(|i| (i * 7 + i / size * 31) as u8)
            .collect();
        let mut expected = Vec::new();
        let mut denoiser = Denoiser::new(w, h, 1.0).unwrap();
        let mut out = Vec::new();
        for frame in stream.chunks(size) {
            if denoiser.push(frame, &mut out).unwrap() {
                expected.extend_from_slice(&out);
            }
        }
        while denoiser.finish(&mut out).unwrap() {
            expected.extend_from_slice(&out);
        }
        assert_eq!(expected.len(), count * size);

        // Whole frames; 1000 bytes; odd sizes, where a write completes the pending frame and holds more full frames.
        let odd = [
            size / 2,
            size * 5 / 2,
            size + 1,
            size - 1,
            1,
            size * 2,
            0,
            size * 2 - 1,
        ];
        let ways: [&[usize]; 3] = [&[size], &[1000], &odd];
        for sizes in ways {
            let mut sink = Vec::new();
            let mut writer = DenoiseWriter::new(&mut sink, Denoiser::new(w, h, 1.0).unwrap());
            let mut rest = &stream[..];
            for &n in sizes.iter().cycle() {
                if rest.is_empty() {
                    break;
                }
                let (part, next) = rest.split_at(n.min(rest.len()));
                assert_eq!(writer.write(part).unwrap(), part.len());
                assert!(writer.pending.len() < size);
                if sizes == [size] {
                    // Whole frames never go into `pending`.
                    assert_eq!(writer.pending.capacity(), 0);
                }
                rest = next;
            }
            writer.flush().unwrap();
            drop(writer);
            assert!(sink == expected, "{sizes:?}");
        }
    }

    #[test]
    fn pipeline_stitches_each_frame_in_order_and_stops_when_the_encoder_stops() {
        let (count, output) = in_time(|| {
            let input: Vec<u8> = (0..5u8).flat_map(|i| [i; 4]).collect();
            let mut output = Vec::new();
            let count = pipeline_at_once(
                &input[..],
                &mut output,
                (4, 2),
                10,
                0,
                |_| Ok(()),
                |index, frame, _, out| {
                    out.copy_from_slice(&[frame[0], index as u8]);
                    Ok(())
                },
            );
            // The error type is not Send: give its text.
            (count.map_err(|e| e.to_string()), output)
        });
        assert_eq!(count, Ok(5));
        assert_eq!(output, [0, 0, 1, 1, 2, 2, 3, 3, 4, 4]);

        // The encoder or the stitch stops while the decoder still has frames: the pipeline must give an error,
        // not wait. The writer is slower than the stitch, thus the stitch waits for an output buffer.
        let stops = |writes: usize, stitch_error_at: usize| {
            in_time(move || {
                pipeline_at_once(
                    std::io::repeat(1),
                    StoppingWriter(writes),
                    (16, 16),
                    1000,
                    0,
                    |_| Ok(()),
                    |index, _, _, _| match index == stitch_error_at {
                        true => Err("stitch error".into()),
                        false => Ok(()),
                    },
                )
                // The error type is not Send: give if the encoder stopped, and the text.
                .map_err(|e| (encoder_stopped(&*e), e.to_string()))
            })
        };
        assert!(matches!(stops(3, usize::MAX), Err((true, _))));
        assert_eq!(stops(usize::MAX, 5), Err((false, "stitch error".into())));
        // The encoder stops at the last frame, after the stitch of all frames: the writer gives the error.
        let at_end = in_time(|| {
            let input = [7u8; 5 * 16];
            pipeline_at_once(
                &input[..],
                StoppingWriter(4),
                (16, 16),
                5,
                0,
                |_| Ok(()),
                |_, _, _, _| Ok(()),
            )
            .map_err(|e| encoder_stopped(&*e))
        });
        assert_eq!(at_end, Err(true));
    }

    #[test]
    fn lagged_pipeline_writes_the_late_outputs_in_order() {
        // The stitch gives the output of the frame before; `finish` gives the last. Radius 0 and 2.
        for radius in [0, 2] {
            let output = in_time(move || {
                let input: Vec<u8> = (0..6u8).collect();
                let mut output = Vec::new();
                let late = std::sync::Mutex::new(None::<Vec<u8>>);
                let count = pipeline(
                    &input[..],
                    &mut output,
                    (1, 1),
                    10,
                    (radius, 1),
                    |_| Ok(()),
                    |_, frame, _, mut out| {
                        out[0] = frame[0];
                        Ok(late.lock().unwrap().replace(out))
                    },
                    || Ok(late.lock().unwrap().take()),
                );
                (count.map_err(|e| e.to_string()), output)
            });
            assert_eq!(output, (Ok(6), vec![0, 1, 2, 3, 4, 5]), "radius {radius}");
        }
    }

    #[test]
    fn pipeline_gives_each_frame_the_data_of_its_neighbours() {
        // 7 frames, radius 2: frame n gets the data of frames n - 2 to n + 2 that exist, in order.
        let output = in_time(|| {
            let input: Vec<u8> = (0..7u8).collect();
            let mut output = Vec::new();
            let count = pipeline_at_once(
                &input[..],
                &mut output,
                (1, 6),
                10,
                2,
                |frame| Ok(frame[0]),
                |index, frame, near, out| {
                    let mut ids = [255u8; 5];
                    for (id, &&n) in ids.iter_mut().zip(near) {
                        *id = n;
                    }
                    out[0] = frame[0];
                    out[1..].copy_from_slice(&ids);
                    assert_eq!(index, frame[0] as usize);
                    Ok(())
                },
            );
            (count.map_err(|e| e.to_string()), output)
        });
        let want: Vec<u8> = (0..7i32)
            .flat_map(|n| {
                let near: Vec<u8> = ((n - 2).max(0)..=(n + 2).min(6)).map(|i| i as u8).collect();
                let mut row = vec![n as u8];
                row.extend(near.iter().copied().chain(std::iter::repeat(255)).take(5));
                row
            })
            .collect();
        assert_eq!(output, (Ok(7), want));
    }

    /// A JPEG start with the segments `(marker, data)`, then an image-data segment that has an APP1 in it.
    fn jpeg_head(segments: &[(u8, &[u8])]) -> Vec<u8> {
        let mut out = vec![0xff, 0xd8];
        for (marker, data) in segments {
            out.extend([0xff, *marker]);
            out.extend(((data.len() + 2) as u16).to_be_bytes());
            out.extend(*data);
        }
        out.extend([0xff, 0xda, 0, 2, 0xff, 0xe1, 0, 8]);
        out.extend(b"Exif\0\0");
        out
    }

    #[test]
    fn the_seam_flow_threads_come_out_of_the_thread_budget() {
        assert_eq!(split_threads(None, true), (None, 2));
        assert_eq!(split_threads(Some(6), false), (Some(6), 2));
        assert_eq!(split_threads(Some(6), true), (Some(4), 2));
        assert_eq!(split_threads(Some(3), true), (Some(2), 1));
        assert_eq!(split_threads(Some(2), true), (Some(1), 1));
        assert_eq!(split_threads(Some(1), true), (Some(1), 1));
    }

    #[test]
    fn exif_segment_finds_the_exif_app1_before_the_image_data() {
        let jfif: &[u8] = b"JFIF\0\x01\x01";
        let xmp: &[u8] = b"http://ns.adobe.com/xap/1.0/\0<x/>";
        let exif: &[u8] = b"Exif\0\0MM\0*";
        let file = jpeg_head(&[(0xe0, jfif), (0xe1, xmp), (0xe1, exif)]);
        assert_eq!(exif_segment(&file[..]), Some(exif.to_vec()));
        // No EXIF before the image data, not a JPEG, or a cut file: no segment.
        assert_eq!(
            exif_segment(&jpeg_head(&[(0xe0, jfif), (0xe1, xmp)])[..]),
            None
        );
        assert_eq!(exif_segment(&b"GIF89a"[..]), None);
        assert_eq!(exif_segment(&file[..12]), None);
    }

    #[test]
    fn the_panorama_jpeg_decodes_near_its_pixels_with_and_without_avx2() {
        // jpeg-encoder uses AVX2 when the processor has it, else its plain code. Both give a JPEG near the
        // pixels. To test the plain code, see the test below.
        let (width, height) = (64, 32);
        let rgb: Vec<u8> = (0..width * height)
            .flat_map(|i| {
                let (x, y) = (i % width, i / width);
                [(x * 4) as u8, (y * 8) as u8, ((x + y) * 3) as u8]
            })
            .collect();
        let rows = Rows::Plain {
            rgb: &rgb,
            width,
            height,
        };
        let mut jpeg = Vec::new();
        encode_panorama(&mut jpeg, &rows, 95, None).unwrap();
        let decoded = image::load_from_memory(&jpeg).unwrap().to_rgb8();
        assert_eq!(decoded.dimensions(), (width as u32, height as u32));
        let diffs: Vec<u32> = rgb
            .iter()
            .zip(decoded.as_raw())
            .map(|(&a, &b)| u32::from(a.abs_diff(b)))
            .collect();
        let mean = diffs.iter().sum::<u32>() as f64 / diffs.len() as f64;
        let max = *diffs.iter().max().unwrap();
        // The colour subsampling moves the sharp colour steps by up to approximately 20 levels.
        assert!(mean < 2.0 && max <= 32, "mean {mean:.2}, max {max}");
    }

    #[test]
    fn the_no_avx2_step_runs_without_avx2() {
        // To test the JPEG encoder without AVX2 on Linux, run the tests on an emulated processor (qemu 10 or later;
        // qemu 8.2 stops these tests with an illegal instruction):
        // INSTA360_EXPECT_NO_AVX2=1 CARGO_TARGET_X86_64_UNKNOWN_LINUX_GNU_RUNNER="qemu-x86_64 -cpu Westmere"
        // cargo test -p insta360-stitch-cli -- panorama_jpeg no_avx2_step
        // This test then makes sure that the emulated processor really has no AVX2, thus that the JPEG test above
        // used the plain code.
        if std::env::var_os("INSTA360_EXPECT_NO_AVX2").is_some() {
            #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
            assert!(
                !std::is_x86_feature_detected!("avx2"),
                "the processor has AVX2"
            );
        }
    }

    #[test]
    fn the_panorama_jpeg_has_the_exif_then_the_360_metadata_and_no_temporary_file() {
        let folder = new_temp_folder(&std::env::temp_dir()).unwrap();
        let output = folder.join("pano.jpg");
        let rgb = vec![128u8; 8 * 4 * 3];
        let rows = Rows::Plain {
            rgb: &rgb,
            width: 8,
            height: 4,
        };
        let exif = b"Exif\0\0MM\0*".to_vec();
        write_panorama_jpeg(&output, rows, 90, Some(exif.clone())).unwrap();
        let bytes = std::fs::read(&output).unwrap();
        let at = |needle: &[u8]| bytes.windows(needle.len()).position(|w| w == needle);
        let (e, x) = (at(&exif).unwrap(), at(b"GPano:ProjectionType").unwrap());
        assert!(e < x);
        // The initial view and the software, as the Insta360 Studio export.
        for field in [
            &b"GPano:InitialViewVerticalFOVDegrees=\"95\""[..],
            b"GPano:InitialHorizontalFOVDegrees=\"100\"",
            b"GPano:StitchingSoftware=\"insta360-stitch\"",
        ] {
            assert!(at(field).is_some());
        }
        assert_eq!(exif_segment(&bytes[..]), Some(exif));
        let names: Vec<_> = std::fs::read_dir(&folder)
            .unwrap()
            .map(|e| e.unwrap().file_name())
            .collect();
        assert_eq!(names, ["pano.jpg"]);
        std::fs::remove_dir_all(&folder).ok();
    }

    #[test]
    fn the_decoder_keeps_the_lens_order_and_the_full_range() {
        let line = |range: &str| {
            format!(
                "width=64|height=64|r_frame_rate=24/1|nb_frames=5|color_range={range}
"
            )
        };
        let args = |range: &str, lens_size: usize| -> Vec<String> {
            let probe = parse_probe(&line(range).repeat(2)).unwrap();
            decoder_command(
                &test_video_options(),
                &probe,
                lens_size,
                None,
                Path::new("in.insv"),
                FrameRange::whole(&probe),
            )
            .get_args()
            .map(|a| a.to_string_lossy().into_owned())
            .collect()
        };
        let full = args("pc", 64);
        assert!(
            full.contains(&"[0:v:1][0:v:0]vstack=inputs=2,format=yuvj420p[v]".to_string()),
            "{full:?}"
        );
        assert!(
            full.windows(2).any(|w| w == ["-pix_fmt", "yuvj420p"]),
            "{full:?}"
        );
        // The decoder threads and the options of the user come before the input, the options of the user last.
        let mut options = test_video_options();
        options.decoder_threads = 3;
        options.decoder_args = ["-threads", "8"].map(String::from).to_vec();
        let probe = parse_probe(&line("pc").repeat(2)).unwrap();
        let tuned: Vec<_> = decoder_command(
            &options,
            &probe,
            64,
            None,
            Path::new("in.insv"),
            FrameRange::whole(&probe),
        )
        .get_args()
        .map(|a| a.to_string_lossy().into_owned())
        .collect();
        let input = tuned.iter().position(|a| a == "file:in.insv").unwrap();
        let threads: Vec<_> = (0..input)
            .filter(|&i| tuned[i] == "-threads")
            .map(|i| &tuned[i + 1])
            .collect();
        assert_eq!(threads, ["3", "8"], "{tuned:?}");
        assert!(
            tuned[..input]
                .windows(2)
                .any(|w| w == ["-filter_complex_threads", "1"]),
            "{tuned:?}"
        );
        let limited = args("tv", 32);
        let filter = "[0:v:1][0:v:0]vstack=inputs=2,scale=32:64:flags=area,format=yuv420p[v]";
        assert!(limited.contains(&filter.to_string()), "{limited:?}");
        assert!(
            limited.windows(2).any(|w| w == ["-pix_fmt", "yuv420p"]),
            "{limited:?}"
        );
    }

    #[test]
    fn the_stabilization_is_the_requested_one_else_follow_for_a_time_shift_else_lock() {
        assert_eq!(stabilization_for(None, false), Stabilization::Lock);
        assert_eq!(stabilization_for(None, true), Stabilization::Follow);
        for time_shift in [false, true] {
            let off = stabilization_for(Some(StabilizationArg::Off), time_shift);
            assert_eq!(off, Stabilization::Off);
            let lock = stabilization_for(Some(StabilizationArg::Lock), time_shift);
            assert_eq!(lock, Stabilization::Lock);
        }
    }

    #[test]
    fn lock_without_orientations_uses_off_and_other_errors_stop() {
        let rotations = |error: fn() -> insta360_stitch::Error| {
            move |mode| match mode {
                Stabilization::Off => Ok(vec![IDENTITY]),
                _ => Err(error()),
            }
        };
        let unsupported = || insta360_stitch::Error::Unsupported("too short".into());
        let invalid = || insta360_stitch::Error::InvalidArgument("bad".into());
        assert_eq!(
            stabilize(Stabilization::Lock, rotations(unsupported)).unwrap(),
            (Stabilization::Off, vec![IDENTITY])
        );
        assert!(stabilize(Stabilization::Follow, rotations(invalid)).is_err());
        let lock = stabilize(Stabilization::Lock, |_| Ok(vec![IDENTITY; 2])).unwrap();
        assert_eq!(lock.0, Stabilization::Lock);
    }

    #[test]
    fn a_file_without_imu_data_gives_no_imu_data_and_other_errors_stop() {
        let none = imu_or_empty(Err(insta360_stitch::Error::Unsupported(
            "no IMU record in trailer".into(),
        )))
        .unwrap();
        assert!(none.is_empty());
        let io = std::io::Error::other("disk");
        assert!(imu_or_empty(Err(insta360_stitch::Error::Io(io))).is_err());
    }

    #[test]
    fn read_frames_gives_full_frames_and_stops_at_the_end_or_the_limit() {
        let data: Vec<u8> = (0..10).collect();
        let run = |limit: usize| {
            let (free_tx, free) = sync_channel(4);
            let (full_tx, full) = sync_channel(4);
            for _ in 0..4 {
                free_tx.send(Vec::new()).unwrap();
            }
            let n = read_frames(&data[..], 4, limit, free, full_tx).unwrap();
            (n, full.iter().collect::<Vec<_>>())
        };
        // 10 bytes in frames of 4: two full frames, the rest is not a frame.
        assert_eq!(run(10), (2, vec![vec![0, 1, 2, 3], vec![4, 5, 6, 7]]));
        assert_eq!(run(1), (1, vec![vec![0, 1, 2, 3]]));
    }
}