insta360-stitch-cli 0.0.3

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
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::{sync_channel, Receiver, RecvError, SendError, SyncSender};

use clap::{Parser, Subcommand, ValueEnum};
use image::{ImageFormat, ImageReader};
use insta360_stitch::{
    check_different_files, check_photo_layout, preview_rgb, read_imu, read_preview, read_trailer,
    stitch_photo_band_with, uses_exposure_table, write_spherical_mp4_file, FrameFlow, Image, Imu,
    LensModel, PhotoSeam, Stabilization, Stitcher, Trailer, MAX_VIDEO_WIDTH,
};
use jpeg_encoder::{rgb_to_ycbcr, Encoder, ImageBuffer, JpegColorType};

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 of a video uses 1 or 2 of these threads
    /// (with 1 thread, the video uses 2)
    #[arg(long, global = true, value_parser = clap::value_parser!(u16).range(1..))]
    threads: Option<u16>,
    #[command(subcommand)]
    command: Commands,
}

#[derive(Subcommand)]
enum Commands {
    /// 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,
    },
    /// 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
    #[arg(long, value_enum, default_value_t = StabilizationArg::Lock)]
    stabilization: StabilizationArg,
    /// The ffmpeg video encoder, for example libx264, libx265, hevc_vaapi or hevc_qsv
    #[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 vaapi, qsv, cuda or d3d11va
    #[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,
    #[arg(long, default_value = "ffmpeg")]
    ffmpeg: String,
    #[arg(long, default_value = "ffprobe")]
    ffprobe: String,
}

#[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 seam flow of a video. With `--threads`, the
/// seam flow gets its threads from that number: half, 1 or 2.
fn split_threads(threads: Option<u16>, seam_flow: bool) -> (Option<usize>, usize) {
    match (threads.map(usize::from), seam_flow) {
        (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 seam_flow =
        matches!(&cli.command, Commands::Video { options, .. } if !options.no_seam_flow);
    let (threads, flow_threads) = split_threads(cli.threads, seam_flow);
    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 result = match cli.command {
        Commands::Info { file } => info(&file),
        Commands::Photo {
            input,
            output,
            quality,
        } => photo(&input, &output, quality),
        Commands::Preview { input, output } => preview(&input, &output),
        Commands::Video {
            input,
            output,
            options,
        } => video(&input, &output, &options, flow_threads),
    };
    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 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": trailer.offset_state,
        "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()),
        "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.
const BAND_ROWS: usize = 64;

/// The RGB rows that the JPEG encoder reads. The encoder reads the rows in sequence.
/// For a photo, the CLI stitches one band of rows at a time. Thus, it does not keep the full output in memory.
enum Rows<'a> {
    Plain {
        rgb: &'a [u8],
        width: usize,
        height: usize,
    },
    Stitched {
        source: Image<'a>,
        model: &'a LensModel,
        seam: PhotoSeam,
        /// The first row of the band, and the stitched band.
        band: RefCell<(usize, Vec<u8>)>,
    },
}

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

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, height) = self.size();
        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 {
                source,
                model,
                seam,
                band,
            } => {
                let mut band = band.borrow_mut();
                let (first, rows) = (band.0, band.1.len() / row_len);
                if y < first || y >= first + rows {
                    let rows = BAND_ROWS.min(height - y);
                    band.0 = y;
                    band.1.resize(rows * row_len, 0);
                    // The CLI checked the source and the model before it started the encoder.
                    stitch_photo_band_with(source, model, seam, y, &mut band.1)
                        .expect("a valid source");
                }
                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());
    }
    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"/></rdf:RDF></x:xmpmeta>"#
        ),
        w = width,
        h = height
    );
    let mut part = output.as_os_str().to_owned();
    part.push(format!(".{}.part", std::process::id()));
    let result = (|| -> Result<()> {
        let mut out = BufWriter::new(File::create(&part)?);
        let mut encoder = Encoder::new(&mut out, quality);
        if let Some(exif) = exif {
            encoder.add_app_segment(1, exif)?;
        }
        encoder.add_app_segment(1, xmp.into_bytes())?;
        encoder.encode_image(rows)?;
        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);
        }
    }
}

fn photo(input: &Path, output: &Path, quality: u8) -> Result<()> {
    check_different_files(input, output)?;
    let stitcher = Stitcher::new(trailer_of(input)?);
    // A .insp file is a usual JPEG with the trailer at the end.
    let decoded = ImageReader::with_format(BufReader::new(File::open(input)?), ImageFormat::Jpeg)
        .decode()?
        .into_rgb8();
    let (width, height) = (decoded.width() as usize, decoded.height() as usize);
    check_photo_layout(width, height)?;
    let model = stitcher.model(height)?;
    let source = Image {
        width,
        height,
        channels: 3,
        data: decoded.as_raw(),
    };
    let rows = Rows::Stitched {
        seam: PhotoSeam::new(&source, &model)?,
        source,
        model: &model,
        band: RefCell::new((0, Vec::new())),
    };
    // As the video keeps the metadata of its source, the photo keeps its EXIF (capture time, GPS).
    let exif = exif_segment(File::open(input)?);
    write_panorama_jpeg(output, rows, quality, exif)
}

fn preview(input: &Path, output: &Path) -> Result<()> {
    check_different_files(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 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,
}

/// 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")
        .args(["-of", "compact=p=0"])
        .arg(input)
        .output()?;
    if !out.status.success() {
        return Err(format!(
            "ffprobe failed: {}",
            String::from_utf8_lossy(&out.stderr).trim()
        )
        .into());
    }
    parse_probe(&String::from_utf8_lossy(&out.stdout))
}

/// 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) || width != height {
        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()),
    };
    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,
        rate,
        fps,
        frame_count,
        colour_args,
        full_range: first.get("color_range") == Some(&"pc"),
    })
}

/// The ffmpeg arguments of the encoder: the codec, then the quality options for libx264 and libx265,
/// then the options of the user.
fn encoder_args(options: &VideoOptions) -> Vec<String> {
    let mut args = vec!["-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;

/// 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.
fn pipeline<P: Send>(
    decoded: impl Read + Send,
    mut encoded: impl Write + Send,
    (in_bytes, out_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> {
    // 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);
    let (done_tx, done) = sync_channel::<Vec<u8>>(2);
    for _ in 0..2 + lookahead {
        free_in_tx.send(Vec::new())?;
    }
    for _ in 0..2 {
        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: Vec<u8>, index: usize| -> Result<()> {
            free_in_tx.send(frame).ok();
            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 mut 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, &mut out);
                    (next.join(), stitched)
                });
                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 mut out = free_out.recv()?;
                stitch(
                    index,
                    &held[0],
                    &window(&data, first, index, radius),
                    &mut 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 mut out = free_out.recv()?;
            stitch(
                index,
                &frame,
                &window(&data, first, index, radius),
                &mut out,
            )?;
            send(frame, out, index)?;
            index += 1;
        }
        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))
    })
}

/// 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)
}

/// Gives the frame rotations of `mode`. Lock and follow need orientations from the IMU stream. Without them,
/// the video uses off, with a warning.
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,
    input: &Path,
) -> 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()
    };
    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"])
        // After the defaults: thus an option of the user replaces a default.
        .args(&options.decoder_args)
        .arg("-i")
        .arg(input)
        .arg("-filter_complex")
        .arg(format!(
            "[0:v:1][0:v:0]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", "-f", "rawvideo"])
        .args(["-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),
    input: &Path,
    stitched: &Path,
) -> Command {
    let mut command = Command::new(&options.ffmpeg);
    command
        .args(["-v", "error", "-y", "-f", "rawvideo", "-pix_fmt", "yuv420p"])
        .args([
            "-s",
            &format!("{width}x{height}"),
            "-framerate",
            &probe.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", "-i"])
        .arg(input)
        .args(["-map", "0:v:0", "-map", "1:a?", "-c:a", "copy"])
        // The global metadata (for example creation_time) of the .insv. ffmpeg copies it from input 0 only.
        .args(["-map_metadata", "1"])
        .args(encoder_args(options))
        // ffmpeg writes moov at the end. finish_video moves it to the start and adds the 360 video metadata.
        .arg(stitched);
    command
}

fn video(input: &Path, output: &Path, options: &VideoOptions, flow_threads: usize) -> Result<()> {
    check_different_files(input, output)?;
    let mut reader = BufReader::new(File::open(input)?);
    let stitcher = Stitcher::new(read_trailer(&mut reader)?);
    let probe = probe(&options.ffprobe, input)?;
    // 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.
    let width = 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 mode = Stabilization::from(options.stabilization);
    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) {
        (Stabilization::Off, false) => Imu::default(),
        // Without IMU data, the video has no rolling shutter correction; a read error stops the command.
        (Stabilization::Off, true) => match read_imu(&mut reader, &stitcher.trailer) {
            Err(insta360_stitch::Error::Unsupported(_)) => Imu::default(),
            imu => imu?,
        },
        _ => read_imu(&mut reader, &stitcher.trailer)?,
    };
    let (mode, rotations) = stabilize(mode, |mode| {
        stitcher.frame_motions(&imu, probe.frame_count, probe.fps, mode, rolling)
    })?;
    if mode != Stabilization::Off && !uses_exposure_table(&stitcher.trailer, probe.frame_count) {
        eprintln!("insta360-stitch: the exposure table does not have all frames, the frame times use the frame rate");
    }
    drop(imu);

    // 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<()> {
        let mut decoder = decoder_command(options, &probe, lens_size, input)
            .stdout(Stdio::piped())
            .spawn()?;
        let mut encoder = encoder_command(
            options,
            &probe,
            (frames.width(), frames.height()),
            input,
            &stitched,
        )
        .stdin(Stdio::piped())
        .spawn()?;
        let decoded = decoder.stdout.take().ok_or("no decoder output")?;
        let encoded = BufWriter::new(encoder.stdin.take().ok_or("no encoder input")?);

        // 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 started = std::time::Instant::now();
        let count = pipeline(
            decoded,
            encoded,
            (frames.input_frame_bytes(), frames.output_frame_bytes()),
            probe.frame_count,
            if options.no_seam_flow { 0 } else { FLOW_RADIUS },
            |frame| match options.no_seam_flow {
                true => Ok(None),
                false => flow_pool.install(|| frames.frame_flow(frame)),
            },
            |index, frame, near, out| {
                let near: Vec<&FrameFlow> = near.iter().filter_map(|f| f.as_ref()).collect();
                let flow = (!near.is_empty()).then(|| FrameFlow::mean(&near));
                Ok(frames.stitch_yuv420_flow(&rotations[index], flow.as_ref(), frame, out)?)
            },
        );
        // 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 < probe.frame_count {
            Some(decoder.wait()?)
        } else {
            decoder.kill().ok();
            decoder.wait().ok();
            None
        };
        let encoder_status = encoder.wait()?;
        eprintln!(
            "\rframe {count}/{} in {:.1} s",
            probe.frame_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 < probe.frame_count {
            eprintln!(
                "insta360-stitch: the decoder gave {count} of {} frames",
                probe.frame_count
            );
        }
        finish_video(&stitched, output)
    })();
    std::fs::remove_dir_all(&folder).ok();
    result
}

/// 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};

    #[test]
    fn rows_give_the_encoder_the_stitched_rows_across_bands() {
        // 128 rows: more than one band of BAND_ROWS.
        let (width, height) = (256, 128);
        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,
        };
        let source = Image {
            width,
            height,
            channels: 3,
            data: &pixels,
        };
        let expected = stitch_photo(&source, &model).unwrap();
        let rows = Rows::Stitched {
            seam: PhotoSeam::new(&source, &model).unwrap(),
            source,
            model: &model,
            band: RefCell::new((0, Vec::new())),
        };
        // The encoder asks for each row in sequence and then gives the last row again at the bottom edge.
        // The last request goes back to an earlier band.
        let requests = (0..height).chain([height - 1, height - 1, 5]);
        for y in requests {
            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}");
        }
    }

    /// 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 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),
            preview(&file, &file),
            video(&file, &file, &test_video_options(), 2),
        ];
        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: StabilizationArg::Lock,
            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,
            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,
                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,
            }
        );
        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=3840|height=1920|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),
        ] {
            assert!(parse_probe(&bad).is_err(), "{bad}");
        }
    }

    #[test]
    fn encoder_args_add_quality_only_for_x264_and_x265() {
        let mut options = test_video_options();
        assert_eq!(
            encoder_args(&options),
            [
                "-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),
            ["-c:v", "hevc_vaapi", "-vf", "format=nv12,hwupload"]
        );
    }

    #[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),
            Path::new("in.insv"),
            Path::new("out.mp4"),
        );
        let args: Vec<_> = command.get_args().map(|a| a.to_string_lossy()).collect();
        let at = |value: &str| args.iter().position(|a| a == value).unwrap();
        // The metadata comes from the .insv, the second input. It is an output option: after the inputs.
        assert_eq!(args[at("in.insv") - 1], "-i");
        assert_eq!(args[at("-map_metadata") + 1], "1");
        assert!(at("-map_metadata") > at("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:?}");
    }

    #[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 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(
                &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(
                    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(
                &input[..],
                StoppingWriter(4),
                (16, 16),
                5,
                0,
                |_| Ok(()),
                |_, _, _, _| Ok(()),
            )
            .map_err(|e| encoder_stopped(&*e))
        });
        assert_eq!(at_end, Err(true));
    }

    #[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(
                &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_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);
        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,
                Path::new("in.insv"),
            )
            .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, Path::new("in.insv"))
            .get_args()
            .map(|a| a.to_string_lossy().into_owned())
            .collect();
        let input = tuned.iter().position(|a| a == "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 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 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]]));
    }
}