vidmerger 0.4.3

A wrapper around FFmpeg which simplifies merging multiple videos and adds chapters from the file names
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
use crate::commander::_cmd::{self, AudioProfile, MediaStream, VideoTarget};
use crate::commander::cropper;
use crate::helper::str_helper::gen_input_file_content_for_ffmpeg;
use std::fs::{self, File};
use std::io::Write;
use std::path::{Path, PathBuf};
use std::process::Output;
use std::str;
use term_painter::Color::BrightBlue;
use term_painter::ToStyle;

/// What happens to one input before the merge.
#[derive(Debug, PartialEq, Eq)]
enum InputAction {
  /// Use the file as it is (stream copy).
  Copy,
  /// Re-encode the file to the shared profile. `silent_audio` adds silence when the file has no audio.
  Convert { silent_audio: bool },
}

/// The shared audio profile, the one video codec used for every converted input, and one action
/// per input (same order as the inputs).
#[derive(Debug, PartialEq, Eq)]
struct MergePlan {
  profile: Option<AudioProfile>,
  /// `true` when every input is HEVC and the OS has a hardware HEVC encoder. Otherwise H.264.
  hevc: bool,
  actions: Vec<InputAction>,
  /// The `(width, height)` each input's video is scaled to when converted. `None` for inputs
  /// without video.
  video_size: Vec<Option<(u32, u32)>>,
  /// Secondary video streams (index among video streams, from 1) kept in converted inputs. Kept
  /// only when every input has the same secondary video codecs in the same order, and the MP4
  /// format can hold each codec. Index 1 is the cover image.
  keep_video_streams: Vec<usize>,
  /// Output video indices (from 1) of the kept streams that are attached pictures (covers). The
  /// final merge must flag each again, because concatenation drops that flag.
  attached_covers: Vec<usize>,
  /// How many audio tracks each input has, in input order.
  audio_tracks: Vec<usize>,
  /// How many audio tracks every converted input gets. Inputs with fewer get silent tracks.
  target_audio_tracks: usize,
}

/// The audio settings of the first audio stream found in any input, or `None` if no input has audio.
fn audio_profile(probes: &[Vec<MediaStream>]) -> Option<AudioProfile> {
  let stream = probes
    .iter()
    .flatten()
    .find(|stream| stream.kind == "audio")?;
  Some(AudioProfile {
    sample_rate: stream.sample_rate?,
    channels: stream.channels?,
  })
}

/// The audio codec an input must have to be copied into the output format.
/// Converted inputs are always AAC, so MP3 output needs MP3 audio.
fn copyable_audio_codec(file_format: &str) -> &'static str {
  if file_format == "mp3" {
    "mp3"
  } else {
    "aac"
  }
}

/// Returns the `(width, height)` that most inputs share, or `None` if no input has video. When
/// two sizes are equally common, the one that appears first wins.
fn most_common_size(sizes: &[Option<(u32, u32)>]) -> Option<(u32, u32)> {
  let mut best: Option<((u32, u32), usize)> = None;
  for size in sizes.iter().flatten() {
    let count = sizes
      .iter()
      .flatten()
      .filter(|other| *other == size)
      .count();
    best = match best {
      Some((_, best_count)) if best_count >= count => best,
      _ => Some((*size, count)),
    };
  }
  best.map(|(size, _)| size)
}

/// True when the MP4 format can hold a secondary video stream with this codec and attached-picture
/// status. Converting keeps a stream only when this is true, because FFmpeg fails on other codecs.
/// BMP is accepted only as an attached cover: ordinary BMP video is not kept.
fn mp4_can_hold_codec(codec: &str, attached_pic: bool) -> bool {
  match codec {
    "bmp" => attached_pic,
    "png" | "mjpeg" | "h264" | "hevc" | "mpeg2video" | "mpeg4" | "av1" | "vp9" => true,
    _ => false,
  }
}

/// The secondary video streams of an input (every video stream after the first), in order, as
/// `(codec, attached_pic)`. An attached picture is a cover image (album art), which is ffprobe's
/// `attached_pic` disposition. Other secondary video is ordinary extra video.
fn secondary_video(streams: &[MediaStream]) -> Vec<(String, bool)> {
  streams
    .iter()
    .filter(|s| s.kind == "video")
    .skip(1)
    .map(|s| (s.codec.clone(), s.attached_pic))
    .collect()
}

/// Decides how each input is merged. An input is copied only when its audio has the codec the
/// output format needs, the shared profile, it has no extra streams (e.g. `tmcd`), and its video
/// has the most common size (`sizes`). Other inputs are converted and scaled to that size.
/// With `force_convert`, every input is converted.
fn plan_merge(
  probes: &[Vec<MediaStream>],
  sizes: &[Option<(u32, u32)>],
  cropped: &[bool],
  file_format: &str,
  force_convert: bool,
) -> MergePlan {
  let target_size = most_common_size(sizes);
  let profile = audio_profile(probes);
  // Converted inputs all get the most audio tracks any input has. At least one track is needed
  // when there is audio, so an input without audio can get silence.
  let audio_tracks: Vec<usize> = probes
    .iter()
    .map(|streams| streams.iter().filter(|s| s.kind == "audio").count())
    .collect();
  let target_audio_tracks = audio_tracks
    .iter()
    .copied()
    .max()
    .unwrap_or(0)
    .max(usize::from(profile.is_some()));
  // Secondary video (covers and extra video) is kept only when every input has the same ones, in
  // the same order, with the same attached-picture status. Covers and extra video use this same
  // layout rule, so one check covers both.
  let secondary: Vec<Vec<(String, bool)>> = probes.iter().map(|s| secondary_video(s)).collect();
  // Inputs share a layout when every one matches the first. An empty layout (no secondary video)
  // is shared too, but nothing needs keeping then.
  let layouts_match = secondary
    .iter()
    .all(|layout| Some(layout) == secondary.first());
  let shared_secondary = if layouts_match {
    secondary.first().cloned().unwrap_or_default()
  } else {
    Vec::new()
  };
  // Only the streams the MP4 format can hold are kept (e.g. a `gif` cover is not). The index is the
  // stream's position among the video streams, starting at 1 (0 is the picture).
  let kept: Vec<(usize, bool)> = shared_secondary
    .iter()
    .enumerate()
    .filter(|(_, (codec, attached))| mp4_can_hold_codec(codec, *attached))
    .map(|(position, (_, attached))| (position + 1, *attached))
    .collect();
  let keep_video_streams: Vec<usize> = kept.iter().map(|(index, _)| *index).collect();
  // The copied streams keep their order, so a kept stream's output index is its place in the
  // kept list (starting at 1, since 0 is the picture). Record the output index of each cover.
  let attached_covers: Vec<usize> = kept
    .iter()
    .enumerate()
    .filter(|(_, (_, attached))| *attached)
    .map(|(output_position, _)| output_position + 1)
    .collect();
  // Secondary video is dropped from every input unless the layouts match and all of it is kept.
  // A mismatch is never treated as keeping everything, even though the kept list is empty.
  let keeps_all_secondary = layouts_match && keep_video_streams.len() == shared_secondary.len();
  let codec = copyable_audio_codec(file_format);
  let matches_profile = |stream: &MediaStream| {
    stream.codec == codec
      && profile.is_some_and(|p| {
        Some(p.sample_rate) == stream.sample_rate && Some(p.channels) == stream.channels
      })
  };
  // The ordered video, audio and subtitle streams (kind and codec) of an input. For `-c copy`
  // concatenation every input must have the same streams in the same order. An input that
  // differs must be converted.
  let stream_layout = |streams: &[MediaStream]| -> Vec<(String, String)> {
    streams
      .iter()
      .filter(|s| matches!(s.kind.as_str(), "video" | "audio" | "subtitle"))
      .map(|s| (s.kind.clone(), s.codec.clone()))
      .collect()
  };
  let reference_layout = probes.first().map(|streams| stream_layout(streams));
  // Per input: (needs conversion, silent audio needed).
  let decisions: Vec<(bool, bool)> = probes
    .iter()
    .zip(sizes)
    .zip(&audio_tracks)
    .zip(cropped)
    .map(|(((streams, size), own_audio_tracks), &is_cropped)| {
      let has_audio = streams.iter().any(|s| s.kind == "audio");
      let has_video = streams.iter().any(|s| s.kind == "video");
      // Data streams (e.g. `tmcd`) cannot be copied into the output, so they force a conversion.
      // The cropper writes only video, audio and subtitles, so a cropped input never has them.
      let has_extra = !is_cropped
        && streams
          .iter()
          .any(|s| !matches!(s.kind.as_str(), "audio" | "video" | "subtitle"));
      let audio_fits = streams
        .iter()
        .filter(|s| s.kind == "audio")
        .all(matches_profile);
      let layout_differs = reference_layout.as_ref() != Some(&stream_layout(streams));
      let own_secondary = secondary_video(streams);
      // Frames of different sizes cannot be stream-copied together, so they are converted.
      let size_differs = target_size.is_some() && size.is_some() && *size != target_size;
      // Silent tracks fill the gap up to the target track count. Inputs with neither audio nor
      // video get none, because `-shortest` would end the output with them.
      let silent_audio =
        profile.is_some() && *own_audio_tracks < target_audio_tracks && (has_video || has_audio);
      (
        // Secondary video that is dropped must not stay in an input that is copied.
        has_extra
          || !audio_fits
          || layout_differs
          || size_differs
          || silent_audio
          || (!own_secondary.is_empty() && !keeps_all_secondary),
        silent_audio,
      )
    })
    .collect();
  // Converted inputs always get H.264 video, so copied inputs could have a different video
  // codec and break `-c copy`. If any input is converted, convert all of them.
  let convert_all = force_convert || decisions.iter().any(|(convert, _)| *convert);
  let actions = decisions
    .into_iter()
    .map(|(_, silent_audio)| {
      if convert_all {
        InputAction::Convert { silent_audio }
      } else {
        InputAction::Copy
      }
    })
    .collect();
  // One video codec for the whole merge. HEVC only when every input is HEVC and the OS has a
  // hardware HEVC encoder, so mixed inputs all become H.264 and the concat step sees one codec.
  let hevc = cfg!(target_os = "macos")
    && !probes.is_empty()
    && probes.iter().all(|streams| {
      streams
        .iter()
        .any(|s| s.kind == "video" && s.codec == "hevc")
    });
  MergePlan {
    profile,
    hevc,
    actions,
    video_size: sizes.iter().map(|size| size.and(target_size)).collect(),
    attached_covers,
    keep_video_streams,
    audio_tracks,
    target_audio_tracks,
  }
}

/// Merges the inputs into `output`. Inputs are assumed to share one video codec (all H.264 or
/// all HEVC), so only audio and stream differences cause a conversion.
pub fn merge(
  input: String,
  output: String,
  files_to_merge_as_strings: Vec<String>,
  cropped: Vec<bool>,
  file_format: &str,
  tmp_dir: PathBuf,
) {
  // Probe every input once. The plan decides which inputs can be copied as they are.
  let probes: Vec<Vec<MediaStream>> = files_to_merge_as_strings
    .iter()
    .map(|path| {
      _cmd::probe_streams(path).unwrap_or_else(|err| panic!("❌ Probing {path} failed: {err}"))
    })
    .collect();

  // Untruncated total length, used as the progress bar denominator.
  let durations: Vec<f64> = files_to_merge_as_strings
    .iter()
    .map(|path| _cmd::get_media_seconds(path).unwrap())
    .collect();
  let total_seconds: f64 = durations.iter().sum();
  // Each input's path with its duration, read once above. Conversions reuse these durations.
  let inputs_with_durations: Vec<(String, f64)> = files_to_merge_as_strings
    .iter()
    .cloned()
    .zip(durations.iter().copied())
    .collect();
  let bounds = chapter_bounds_ms(&durations);

  let mut metadata_string = String::from(";FFMETADATA1\n");
  for (path, (start_ms, end_ms)) in files_to_merge_as_strings.iter().zip(bounds) {
    let title = extract_title(path, file_format);
    metadata_string.push_str(&format!(
      "\n[CHAPTER]\nTIMEBASE=1/1000\nSTART={}\nEND={}\ntitle={}\n",
      start_ms, end_ms, title
    ));
  }
  let mut file_path = tmp_dir.clone();
  file_path.push("chapters.txt");
  println!(
    "📖 Chapters file: {}",
    BrightBlue.paint(file_path.to_string_lossy())
  );
  let mut file = File::create(&file_path).expect("Failed to create file");
  file
    .write_all(metadata_string.as_bytes())
    .expect("Failed to write to file");

  // ========== Merge with chapters ========== //

  let output_str = output.clone();
  let chapters = file_path.to_string_lossy().to_string();
  // Each input's video size. Inputs of another size are converted and scaled to the common one.
  let sizes: Vec<Option<(u32, u32)>> = files_to_merge_as_strings
    .iter()
    .map(|path| cropper::frame_size(path))
    .collect();
  // First try: copy inputs that already fit and convert the rest.
  let plan = plan_merge(&probes, &sizes, &cropped, file_format, false);
  let mut res = run_plan(
    &plan,
    &inputs_with_durations,
    &tmp_dir,
    &input,
    &output,
    &chapters,
    total_seconds,
  );

  // Fallback for issue #53: an input has a stream MP4 cannot hold (e.g. a `tmcd` data
  // stream in a .mov). Convert every input to the shared profile and merge once more.
  if !res.status.success() && is_unsupported_stream_error(&res.stderr) {
    println!("⚠️  Unsupported stream found, converting every input and retrying the merge");
    let plan = plan_merge(&probes, &sizes, &cropped, file_format, true);
    res = run_plan(
      &plan,
      &inputs_with_durations,
      &tmp_dir,
      &input,
      &output,
      &chapters,
      total_seconds,
    );
  }

  if res.status.success() {
    println!("🐣 Generated: {}", BrightBlue.paint(&output_str));
  } else {
    panic!(
      "❌ Something went wrong (exit code: {:?}):{}",
      res.status.code(),
      String::from_utf8_lossy(&res.stderr)
    );
  }
}

/// Returns the `(start_ms, end_ms)` of each chapter, given each clip's duration in seconds.
/// The running total is kept unrounded and rounded once per boundary, so the error
/// does not grow with the number of clips.
fn chapter_bounds_ms(durations: &[f64]) -> Vec<(i64, i64)> {
  let mut elapsed_seconds: f64 = 0.0;
  durations
    .iter()
    .map(|duration| {
      let start_ms = (elapsed_seconds * 1000.0).round() as i64;
      elapsed_seconds += duration;
      let end_ms = (elapsed_seconds * 1000.0).round() as i64;
      (start_ms, end_ms)
    })
    .collect()
}

/// True when FFmpeg failed because an input stream has a type the output cannot hold.
fn is_unsupported_stream_error(stderr: &[u8]) -> bool {
  String::from_utf8_lossy(stderr).contains("unsupported type")
}

/// Converts the inputs as `plan` says, rewrites the concat list to use them, and runs the merge.
fn run_plan(
  plan: &MergePlan,
  inputs_with_durations: &[(String, f64)],
  tmp_dir: &Path,
  concat_list: &str,
  output: &str,
  chapters: &str,
  total_seconds: f64,
) -> Output {
  let inputs = convert_inputs(inputs_with_durations, plan, tmp_dir);
  // If a HEVC conversion fell back to H.264 (libx264), the converted inputs no longer share one
  // codec. Redo every conversion with H.264, so the concat step sees a single codec.
  // Only converted outputs can fall back. Copied inputs keep their own streams, so they are not
  // checked. Skip the check entirely when nothing was converted.
  let converted_outputs = plan
    .actions
    .iter()
    .zip(&inputs)
    .filter(|(action, _)| matches!(action, InputAction::Convert { .. }))
    .map(|(_, path)| path);
  let fell_back = plan.hevc && converted_outputs.clone().any(|path| !is_hevc_file(path));
  let inputs = if fell_back {
    println!("⚠️  A HEVC conversion fell back to H.264, converting every input to H.264");
    let h264_plan = MergePlan {
      profile: plan.profile,
      hevc: false,
      video_size: plan.video_size.clone(),
      keep_video_streams: plan.keep_video_streams.clone(),
      attached_covers: plan.attached_covers.clone(),
      audio_tracks: plan.audio_tracks.clone(),
      target_audio_tracks: plan.target_audio_tracks,
      actions: plan
        .actions
        .iter()
        .map(|action| match action {
          InputAction::Copy => InputAction::Convert {
            silent_audio: false,
          },
          InputAction::Convert { silent_audio } => InputAction::Convert {
            silent_audio: *silent_audio,
          },
        })
        .collect(),
    };
    convert_inputs(inputs_with_durations, &h264_plan, tmp_dir)
  } else {
    inputs
  };
  fs::write(concat_list, gen_input_file_content_for_ffmpeg(&inputs))
    .expect("Failed to write the concat list");
  _cmd::merge(
    concat_list.to_string(),
    output,
    chapters,
    total_seconds,
    &plan.attached_covers,
  )
}

/// True when the file's first video stream is HEVC. A file that cannot be probed is not HEVC.
fn is_hevc_file(path: &str) -> bool {
  _cmd::is_hevc(path)
}

/// Returns the path to merge for each input, in the same order as the inputs. Copied inputs
/// keep their path. Converted inputs are written as MP4 files in `tmp_dir`.
fn convert_inputs(
  inputs_with_durations: &[(String, f64)],
  plan: &MergePlan,
  tmp_dir: &Path,
) -> Vec<String> {
  inputs_with_durations
    .iter()
    .zip(&plan.actions)
    .enumerate()
    .map(|(index, ((input, duration), action))| match action {
      InputAction::Copy => input.clone(),
      InputAction::Convert { silent_audio } => {
        let output = tmp_dir.join(format!("converted_{index}.mp4"));
        let output = output.to_string_lossy().to_string();
        let res = _cmd::convert_for_merge(
          input,
          &output,
          plan.profile,
          // Silent tracks fill the gap up to the target track count.
          if *silent_audio {
            plan
              .target_audio_tracks
              .saturating_sub(plan.audio_tracks[index])
          } else {
            0
          },
          plan.hevc,
          *duration,
          VideoTarget {
            size: plan.video_size[index],
            keep_video_streams: plan.keep_video_streams.clone(),
          },
        );
        if !res.status.success() {
          panic!(
            "❌ Converting {} failed (exit code: {:?}):{}",
            input,
            res.status.code(),
            String::from_utf8_lossy(&res.stderr)
          );
        }
        output
      }
    })
    .collect()
}

/// Returns the chapter title from a file name: the text after the first `-`, up to the extension.
/// Returns an empty string when the name has no `-`. If the extension is missing, the rest of
/// the name is returned.
fn extract_title(path: &str, file_format: &str) -> String {
  let file_name = path.split('/').next_back().unwrap_or("");
  let mut parts = file_name.splitn(2, '-');
  parts.next(); // Skip the part before the first '-'
  let content_with_extension = parts.next().unwrap_or("").trim();

  let format_str = format!(".{file_format}");
  content_with_extension
    .split(&format_str)
    .next()
    .unwrap_or("")
    .trim()
    .to_string()
}

#[cfg(test)]
mod test_chapter_bounds_ms {
  use super::chapter_bounds_ms;

  #[test]
  fn test_chapter_bounds_with_fractional_durations() {
    let durations = [1.40, 2.64, 1.96, 3.32];
    assert_eq!(
      chapter_bounds_ms(&durations),
      vec![(0, 1400), (1400, 4040), (4040, 6000), (6000, 9320)]
    );
  }

  #[test]
  fn test_chapter_bounds_do_not_drift_over_many_clips() {
    let durations = [1.0003; 100];
    let bounds = chapter_bounds_ms(&durations);
    assert_eq!(bounds.last(), Some(&(99_030, 100_030)));
  }

  #[test]
  fn test_chapter_bounds_empty() {
    assert!(chapter_bounds_ms(&[]).is_empty());
  }
}

#[cfg(test)]
mod test_plan_merge {
  use super::{InputAction, MergePlan};
  use crate::commander::_cmd::{AudioProfile, MediaStream};

  /// Plans for an MP4 output, the common case. The inputs have no known video size.
  fn plan_merge(probes: &[Vec<MediaStream>], force_convert: bool) -> MergePlan {
    let sizes = vec![None; probes.len()];
    let cropped = vec![false; probes.len()];
    super::plan_merge(probes, &sizes, &cropped, "mp4", force_convert)
  }

  fn video() -> MediaStream {
    stream("video", "h264")
  }

  fn stream(kind: &str, codec: &str) -> MediaStream {
    MediaStream {
      kind: kind.into(),
      codec: codec.into(),
      sample_rate: None,
      channels: None,
      attached_pic: false,
    }
  }

  /// A cover image stored as a video stream (ffprobe's `attached_pic` disposition).
  fn attached_cover(codec: &str) -> MediaStream {
    MediaStream {
      attached_pic: true,
      ..stream("video", codec)
    }
  }

  fn audio(codec: &str, sample_rate: u32, channels: u32) -> MediaStream {
    MediaStream {
      kind: "audio".into(),
      codec: codec.into(),
      sample_rate: Some(sample_rate),
      channels: Some(channels),
      attached_pic: false,
    }
  }

  fn aac_stereo_48k() -> MediaStream {
    audio("aac", 48_000, 2)
  }

  const STEREO_48K: AudioProfile = AudioProfile {
    sample_rate: 48_000,
    channels: 2,
  };

  #[test]
  fn copies_inputs_that_already_match() {
    let probes = vec![
      vec![video(), aac_stereo_48k()],
      vec![video(), aac_stereo_48k()],
    ];
    assert_eq!(
      plan_merge(&probes, false),
      MergePlan {
        profile: Some(STEREO_48K),
        hevc: false,
        actions: vec![InputAction::Copy, InputAction::Copy],
        video_size: vec![None, None],
        keep_video_streams: vec![],
        attached_covers: vec![],
        audio_tracks: vec![1, 1],
        target_audio_tracks: 1,
      }
    );
  }

  #[test]
  fn converts_all_inputs_when_one_needs_conversion() {
    let probes = vec![
      vec![video(), aac_stereo_48k()],
      vec![video(), audio("pcm_alaw", 8_000, 1)],
    ];
    assert_eq!(
      plan_merge(&probes, false).actions,
      vec![
        InputAction::Convert {
          silent_audio: false
        },
        InputAction::Convert {
          silent_audio: false
        }
      ]
    );
  }

  #[test]
  fn converts_all_inputs_when_sample_rate_differs() {
    let probes = vec![
      vec![video(), aac_stereo_48k()],
      vec![video(), audio("aac", 44_100, 2)],
    ];
    assert_eq!(
      plan_merge(&probes, false).actions,
      vec![
        InputAction::Convert {
          silent_audio: false
        },
        InputAction::Convert {
          silent_audio: false
        }
      ]
    );
  }

  #[test]
  fn converts_all_inputs_when_one_has_data_stream() {
    let probes = vec![
      vec![video(), aac_stereo_48k()],
      vec![video(), aac_stereo_48k(), stream("data", "tmcd")],
    ];
    assert_eq!(
      plan_merge(&probes, false).actions,
      vec![
        InputAction::Convert {
          silent_audio: false
        },
        InputAction::Convert {
          silent_audio: false
        }
      ]
    );
  }

  #[test]
  fn adds_silence_to_video_input_without_audio() {
    let probes = vec![vec![video(), aac_stereo_48k()], vec![video()]];
    assert_eq!(
      plan_merge(&probes, false).actions,
      vec![
        InputAction::Convert {
          silent_audio: false
        },
        InputAction::Convert { silent_audio: true }
      ]
    );
  }

  #[test]
  fn does_not_add_silence_without_video() {
    let probes = vec![
      vec![stream("data", "tmcd")],
      vec![video(), aac_stereo_48k()],
    ];
    assert_eq!(
      plan_merge(&probes, false).actions,
      vec![
        InputAction::Convert {
          silent_audio: false
        },
        InputAction::Convert {
          silent_audio: false
        }
      ]
    );
  }

  #[test]
  fn copies_everything_when_no_input_has_audio() {
    let probes = vec![vec![video()], vec![video()]];
    assert_eq!(
      plan_merge(&probes, false),
      MergePlan {
        profile: None,
        hevc: false,
        actions: vec![InputAction::Copy, InputAction::Copy],
        video_size: vec![None, None],
        keep_video_streams: vec![],
        attached_covers: vec![],
        audio_tracks: vec![0, 0],
        target_audio_tracks: 0,
      }
    );
  }

  fn hevc_video() -> MediaStream {
    stream("video", "hevc")
  }

  #[test]
  fn one_codec_for_mixed_hevc_and_h264_inputs() {
    // A mix must not split the merge: every input uses H.264 (never HEVC for only some inputs).
    let probes = vec![
      vec![hevc_video(), aac_stereo_48k()],
      vec![video(), aac_stereo_48k()],
    ];
    assert!(!plan_merge(&probes, false).hevc);
  }

  #[test]
  fn mixed_video_codecs_are_converted_not_copied() {
    // Matching AAC audio would normally allow a copy. The video codecs differ, so `-c copy`
    // concatenation would mix them. Both inputs must be converted.
    let probes = vec![
      vec![hevc_video(), aac_stereo_48k()],
      vec![video(), aac_stereo_48k()],
    ];
    let plan = plan_merge(&probes, false);
    assert!(!plan.hevc);
    assert_eq!(
      plan.actions,
      vec![
        InputAction::Convert {
          silent_audio: false
        },
        InputAction::Convert {
          silent_audio: false
        },
      ]
    );
  }

  #[test]
  fn matching_secondary_video_streams_are_copied() {
    // Both inputs have the same video streams in the same order (H.264 then HEVC), so they can
    // be copied. Converting would drop the second video stream, since only the first is mapped.
    let probes = vec![
      vec![video(), hevc_video(), aac_stereo_48k()],
      vec![video(), hevc_video(), aac_stereo_48k()],
    ];
    assert_eq!(
      plan_merge(&probes, false).actions,
      vec![InputAction::Copy, InputAction::Copy]
    );
  }

  #[test]
  fn keeps_matching_secondary_video_streams_when_conversion_is_forced_by_audio() {
    // The second input's PCM audio forces a conversion. Both inputs share a `hevc` secondary video
    // stream, so it must be kept in the converted files instead of being dropped.
    let probes = vec![
      vec![video(), hevc_video(), aac_stereo_48k()],
      vec![video(), hevc_video(), audio("pcm_alaw", 8_000, 1)],
    ];
    let plan = plan_merge(&probes, false);
    assert_eq!(plan.keep_video_streams, vec![1]);
    assert!(plan
      .actions
      .iter()
      .all(|action| matches!(action, InputAction::Convert { .. })));
  }

  #[test]
  fn keeps_shared_vp9_secondary_stream_alongside_h264() {
    // Both inputs have a `vp9` secondary stream, which MP4 can hold. Audio differences force
    // conversion, so both kept streams (indices 1 and 2) must be listed.
    let probes = vec![
      vec![
        video(),
        stream("video", "h264"),
        stream("video", "vp9"),
        aac_stereo_48k(),
      ],
      vec![
        video(),
        stream("video", "h264"),
        stream("video", "vp9"),
        audio("pcm_alaw", 8_000, 1),
      ],
    ];
    let plan = plan_merge(&probes, false);
    assert_eq!(plan.keep_video_streams, vec![1, 2]);
  }

  #[test]
  fn keeps_attached_cover_and_ordinary_secondary_video_together() {
    // An attached cover (index 1) and an ordinary extra video stream (index 2) are both kept
    // when every input has the same two streams in the same order.
    let probes = vec![
      vec![
        video(),
        attached_cover("png"),
        stream("video", "h264"),
        aac_stereo_48k(),
      ],
      vec![
        video(),
        attached_cover("png"),
        stream("video", "h264"),
        audio("pcm_alaw", 8_000, 1),
      ],
    ];
    let plan = plan_merge(&probes, false);
    assert_eq!(plan.keep_video_streams, vec![1, 2]);
  }

  #[test]
  fn drops_cover_when_one_input_marks_the_same_codec_as_ordinary_video() {
    // Same codec, but only the first input's second stream is an attached picture. The layouts
    // differ, so neither is kept and both inputs are converted without it.
    let probes = vec![
      vec![video(), attached_cover("png"), aac_stereo_48k()],
      vec![video(), stream("video", "png"), aac_stereo_48k()],
    ];
    let plan = plan_merge(&probes, false);
    assert!(plan.keep_video_streams.is_empty());
    assert_eq!(
      plan.actions,
      vec![
        InputAction::Convert {
          silent_audio: false
        },
        InputAction::Convert {
          silent_audio: false
        },
      ]
    );
  }

  #[test]
  fn keeps_matching_mpeg2_secondary_video_without_conversion() {
    // MP4 holds MPEG-2 video (verified with ffmpeg copy). Matching MPEG-2 secondary streams in
    // two inputs must be kept without forcing a conversion.
    let probes = vec![
      vec![video(), stream("video", "mpeg2video"), aac_stereo_48k()],
      vec![video(), stream("video", "mpeg2video"), aac_stereo_48k()],
    ];
    let plan = plan_merge(&probes, false);
    assert_eq!(plan.keep_video_streams, vec![1]);
    assert_eq!(plan.actions, vec![InputAction::Copy, InputAction::Copy]);
  }

  #[test]
  fn keeps_matching_bmp_attached_covers() {
    // BMP is kept when it is an attached cover, since MP4 holds BMP covers.
    let probes = vec![
      vec![video(), attached_cover("bmp"), aac_stereo_48k()],
      vec![video(), attached_cover("bmp"), audio("pcm_alaw", 8_000, 1)],
    ];
    let plan = plan_merge(&probes, false);
    assert_eq!(plan.keep_video_streams, vec![1]);
    assert_eq!(plan.attached_covers, vec![1]);
  }

  #[test]
  fn drops_ordinary_bmp_video_even_when_both_inputs_have_it() {
    // Ordinary BMP video is not an attached cover, so MP4 is not assumed to hold it.
    let probes = vec![
      vec![video(), stream("video", "bmp"), aac_stereo_48k()],
      vec![video(), stream("video", "bmp"), audio("pcm_alaw", 8_000, 1)],
    ];
    let plan = plan_merge(&probes, false);
    assert!(plan.keep_video_streams.is_empty());
  }

  #[test]
  fn records_the_output_index_of_a_cover_after_an_ordinary_stream() {
    // Both inputs have an ordinary H.264 stream at index 1 and an attached cover at index 2. The
    // cover's output index is 2, so the merge must flag output video 2, not index 1.
    let probes = vec![
      vec![
        video(),
        stream("video", "h264"),
        attached_cover("mjpeg"),
        aac_stereo_48k(),
      ],
      vec![
        video(),
        stream("video", "h264"),
        attached_cover("mjpeg"),
        audio("pcm_alaw", 8_000, 1),
      ],
    ];
    let plan = plan_merge(&probes, false);
    assert_eq!(plan.keep_video_streams, vec![1, 2]);
    assert_eq!(plan.attached_covers, vec![2]);
  }

  #[test]
  fn drops_secondary_video_streams_when_inputs_have_mismatched_layouts() {
    // The first input has an extra secondary stream the second does not. Neither is kept, so
    // the converted outputs have one layout.
    let probes = vec![
      vec![video(), hevc_video(), aac_stereo_48k()],
      vec![video(), aac_stereo_48k()],
    ];
    let plan = plan_merge(&probes, false);
    assert!(plan.keep_video_streams.is_empty());
    assert_eq!(
      plan.actions,
      vec![
        InputAction::Convert {
          silent_audio: false
        },
        InputAction::Convert {
          silent_audio: false
        },
      ]
    );
  }

  #[test]
  fn keeps_covers_when_every_input_has_the_same_cover_codec() {
    let probes = vec![
      vec![video(), attached_cover("png"), aac_stereo_48k()],
      vec![video(), attached_cover("png"), aac_stereo_48k()],
    ];
    let plan = plan_merge(&probes, false);
    assert_eq!(plan.keep_video_streams, vec![1]);
    assert_eq!(plan.actions, vec![InputAction::Copy, InputAction::Copy]);
  }

  #[test]
  fn drops_covers_and_converts_when_only_one_input_has_a_cover() {
    let probes = vec![
      vec![video(), attached_cover("png"), aac_stereo_48k()],
      vec![video(), aac_stereo_48k()],
    ];
    let plan = plan_merge(&probes, false);
    assert!(plan.keep_video_streams.is_empty());
    assert_eq!(
      plan.actions,
      vec![
        InputAction::Convert {
          silent_audio: false
        },
        InputAction::Convert {
          silent_audio: false
        },
      ]
    );
  }

  #[test]
  fn converted_inputs_drop_a_cover_codec_the_mp4_format_cannot_hold() {
    // The inputs share a `gif` cover, which MP4 cannot hold. The second input's PCM audio forces
    // a conversion, so the cover must not be copied into the converted files.
    let probes = vec![
      vec![video(), attached_cover("gif"), aac_stereo_48k()],
      vec![video(), attached_cover("gif"), audio("pcm_alaw", 8_000, 1)],
    ];
    let plan = plan_merge(&probes, false);
    assert!(plan.keep_video_streams.is_empty());
  }

  #[test]
  fn a_cropped_input_with_an_extra_stream_is_copied() {
    // The cropper writes only video, audio and subtitles, so the extra stream only appears in
    // the merge's own muxing. A cropped input is copied, so the merge does not convert it again.
    let probes = vec![
      vec![video(), aac_stereo_48k(), stream("data", "tmcd")],
      vec![video(), aac_stereo_48k()],
    ];
    let sizes = [None, None];
    let cropped = [true, false];
    let plan = super::plan_merge(&probes, &sizes, &cropped, "mp4", false);
    assert_eq!(plan.actions[0], InputAction::Copy);
  }

  #[test]
  fn an_uncropped_input_with_an_extra_stream_is_still_converted() {
    let probes = vec![
      vec![video(), aac_stereo_48k(), stream("data", "tmcd")],
      vec![video(), aac_stereo_48k()],
    ];
    let sizes = [None, None];
    let cropped = [false, false];
    let plan = super::plan_merge(&probes, &sizes, &cropped, "mp4", false);
    assert_eq!(
      plan.actions[0],
      InputAction::Convert {
        silent_audio: false
      }
    );
  }

  #[test]
  fn copies_inputs_with_matching_subtitles() {
    // Subtitles are copied with the other streams, so matching ones do not force a conversion.
    let probes = vec![
      vec![video(), aac_stereo_48k(), stream("subtitle", "mov_text")],
      vec![video(), aac_stereo_48k(), stream("subtitle", "mov_text")],
    ];
    assert_eq!(
      plan_merge(&probes, false).actions,
      vec![InputAction::Copy, InputAction::Copy]
    );
  }

  #[test]
  fn converts_when_audio_track_counts_differ() {
    // Both inputs have matching AAC audio, but the second has one track fewer. `-c copy`
    // concatenation would then mix up the audio streams, so both inputs must be converted, and
    // the second gets one silent track to reach two.
    let probes = vec![
      vec![video(), aac_stereo_48k(), aac_stereo_48k()],
      vec![video(), aac_stereo_48k()],
    ];
    let plan = plan_merge(&probes, false);
    assert_eq!(
      plan.actions,
      vec![
        InputAction::Convert {
          silent_audio: false
        },
        InputAction::Convert { silent_audio: true },
      ]
    );
    assert_eq!(plan.target_audio_tracks, 2);
  }

  #[test]
  fn converts_when_only_one_input_has_subtitles() {
    let probes = vec![
      vec![video(), aac_stereo_48k(), stream("subtitle", "mov_text")],
      vec![video(), aac_stereo_48k()],
    ];
    assert_eq!(
      plan_merge(&probes, false).actions,
      vec![
        InputAction::Convert {
          silent_audio: false
        },
        InputAction::Convert {
          silent_audio: false
        },
      ]
    );
  }

  #[test]
  fn all_hevc_inputs_share_one_hevc_codec() {
    let probes = vec![
      vec![hevc_video(), aac_stereo_48k()],
      vec![hevc_video(), aac_stereo_48k()],
    ];
    // Only on macOS, where the hardware HEVC encoder exists.
    assert_eq!(plan_merge(&probes, false).hevc, cfg!(target_os = "macos"));
  }

  #[test]
  fn force_convert_converts_every_input() {
    let probes = vec![
      vec![video(), aac_stereo_48k()],
      vec![video(), aac_stereo_48k()],
    ];
    assert_eq!(
      plan_merge(&probes, true).actions,
      vec![
        InputAction::Convert {
          silent_audio: false
        },
        InputAction::Convert {
          silent_audio: false
        },
      ]
    );
  }

  #[test]
  fn most_common_size_picks_the_size_most_inputs_share() {
    let sizes = [Some((3840, 2160)), Some((3840, 1608)), Some((3840, 2160))];
    assert_eq!(super::most_common_size(&sizes), Some((3840, 2160)));
  }

  #[test]
  fn most_common_size_breaks_a_tie_with_the_first_size() {
    let sizes = [Some((3840, 1608)), Some((3840, 2160))];
    assert_eq!(super::most_common_size(&sizes), Some((3840, 1608)));
  }

  #[test]
  fn most_common_size_is_none_without_video() {
    assert_eq!(super::most_common_size(&[None, None]), None);
  }

  #[test]
  fn converts_and_scales_an_input_of_another_size() {
    let probes = vec![
      vec![video(), aac_stereo_48k()],
      vec![video(), aac_stereo_48k()],
    ];
    let sizes = [Some((3840, 2160)), Some((3840, 1608))];
    let cropped = [false, false];
    let plan = super::plan_merge(&probes, &sizes, &cropped, "mp4", false);
    assert_eq!(
      plan.actions,
      vec![
        InputAction::Convert {
          silent_audio: false
        },
        InputAction::Convert {
          silent_audio: false
        },
      ]
    );
    assert_eq!(
      plan.video_size,
      vec![Some((3840, 2160)), Some((3840, 2160))]
    );
  }

  #[test]
  fn copies_inputs_of_the_same_size() {
    let probes = vec![
      vec![video(), aac_stereo_48k()],
      vec![video(), aac_stereo_48k()],
    ];
    let sizes = [Some((3840, 2160)), Some((3840, 2160))];
    let cropped = [false, false];
    let plan = super::plan_merge(&probes, &sizes, &cropped, "mp4", false);
    assert_eq!(plan.actions, vec![InputAction::Copy, InputAction::Copy]);
  }
}

#[cfg(test)]
mod test_extract_title {
  use super::extract_title;

  #[test]
  fn test_extract_title() {
    let path = "path/to/video-Title of Video.mp4";
    assert_eq!(extract_title(path, "mp4"), "Title of Video");
  }

  #[test]
  fn test_extract_title_with_dot() {
    let path = "path/to/video-[1.0] Title of Video.mp4";
    assert_eq!(extract_title(path, "mp4"), "[1.0] Title of Video");
  }

  #[test]
  fn test_extract_title_with_no_dash() {
    let path = "path/to/videoTitle of Video.mp4";
    assert_eq!(extract_title(path, "mp4"), "");
  }

  #[test]
  fn test_extract_title_with_no_extension() {
    let path = "path/to/video-Title of Video";
    assert_eq!(extract_title(path, "mp4"), "Title of Video");
  }

  #[test]
  fn test_extract_title_with_multiple_dashes() {
    let path = "path/to/video-Title-of-Video.mp4";
    assert_eq!(extract_title(path, "mp4"), "Title-of-Video");
  }

  #[test]
  fn test_extract_title_with_empty_path() {
    let path = "";
    assert_eq!(extract_title(path, "mp4"), "");
  }

  // FAIL
  #[test]
  fn test_extract_title_with_only_dashes() {
    let path = "---";
    assert_eq!(extract_title(path, "mp4"), "--");
  }

  #[test]
  fn test_extract_title_with_special_characters() {
    let path = "path/to/video-Title_@_of_Video.mp4";
    assert_eq!(extract_title(path, "mp4"), "Title_@_of_Video");
  }

  #[test]
  fn test_extract_title_with_different_format() {
    let path = "path/to/video-Title of Video.avi";
    assert_eq!(extract_title(path, "mp4"), "Title of Video.avi");
  }

  #[test]
  fn test_extract_title_with_nested_path() {
    let path = "path/to/some/other/folder/video-Title.mp4";
    assert_eq!(extract_title(path, "mp4"), "Title");
  }
}

/// Integration tests: these run real ffmpeg and ffprobe on generated clips.
#[cfg(test)]
mod test_merge_integration {
  use super::{convert_inputs, run_plan, InputAction, MergePlan};
  use crate::commander::_cmd::{get_media_seconds, probe_streams, AudioProfile, MediaStream};
  use std::fs;
  use std::path::{Path, PathBuf};
  use std::process::Command;

  /// A temp folder that is removed when the test ends, even if an assert fails.
  struct TempDir(PathBuf);

  impl TempDir {
    fn new(name: &str) -> Self {
      let dir = std::env::temp_dir().join(format!("vidmerger-merge-{name}-{}", std::process::id()));
      let _ = fs::remove_dir_all(&dir);
      fs::create_dir_all(&dir).unwrap();
      TempDir(dir)
    }
  }

  impl Drop for TempDir {
    fn drop(&mut self) {
      let _ = fs::remove_dir_all(&self.0);
    }
  }

  /// Creates a 1-second video. With `audio`, it also has a 440 Hz tone.
  fn make_clip(path: &Path, audio: bool) {
    let mut cmd = Command::new("ffmpeg");
    cmd.args(["-v", "error", "-y", "-f", "lavfi", "-i"]);
    cmd.arg("testsrc=d=1:s=160x120:r=25");
    if audio {
      cmd.args(["-f", "lavfi", "-i", "sine=f=440:d=1"]);
    }
    cmd.args(["-c:v", "libx264", "-pix_fmt", "yuv420p"]);
    if audio {
      cmd.args(["-c:a", "aac", "-shortest"]);
    }
    let status = cmd.arg(path).status().expect("ffmpeg must be installed");
    assert!(status.success(), "failed to create test clip");
  }

  #[test]
  fn convert_inputs_turns_a_silent_clip_into_a_clip_with_audio() {
    let dir = TempDir::new("convert");
    let input = dir.0.join("silent.mp4");
    make_clip(&input, false);

    let profile = AudioProfile {
      sample_rate: 48_000,
      channels: 2,
    };
    let plan = MergePlan {
      profile: Some(profile),
      hevc: false,
      actions: vec![InputAction::Convert { silent_audio: true }],
      video_size: vec![None],
      keep_video_streams: vec![],
      attached_covers: vec![],
      audio_tracks: vec![0],
      target_audio_tracks: 1,
    };
    let files = [input.to_str().unwrap().to_string()];

    let inputs_with_durations = vec![(files[0].clone(), 1.0)];
    let converted = convert_inputs(&inputs_with_durations, &plan, &dir.0);

    assert_eq!(converted.len(), 1);
    assert!(
      converted[0].ends_with("converted_0.mp4"),
      "{}",
      converted[0]
    );
    let streams = probe_streams(&converted[0]).unwrap();
    let audio = streams
      .iter()
      .find(|s| s.kind == "audio")
      .expect("no audio");
    assert_eq!(audio.codec, "aac");
    assert_eq!(audio.sample_rate, Some(48_000));
    assert_eq!(audio.channels, Some(2));
  }

  #[test]
  fn run_plan_merges_two_clips_into_one_output() {
    let dir = TempDir::new("plan");
    let first = dir.0.join("1 - first.mp4");
    let second = dir.0.join("2 - second.mp4");
    make_clip(&first, false);
    make_clip(&second, false);

    let plan = MergePlan {
      profile: Some(AudioProfile {
        sample_rate: 44_100,
        channels: 1,
      }),
      hevc: false,
      actions: vec![
        InputAction::Convert { silent_audio: true },
        InputAction::Convert { silent_audio: true },
      ],
      video_size: vec![None, None],
      keep_video_streams: vec![],
      attached_covers: vec![],
      audio_tracks: vec![0, 0],
      target_audio_tracks: 1,
    };
    let files = [
      first.to_str().unwrap().to_string(),
      second.to_str().unwrap().to_string(),
    ];

    let concat_list = dir.0.join("list.txt");
    let chapters = dir.0.join("chapters.txt");
    fs::write(&chapters, ";FFMETADATA1\n").unwrap();
    let output = dir.0.join("merged.mp4");

    let inputs_with_durations: Vec<(String, f64)> =
      files.iter().map(|file| (file.clone(), 1.0)).collect();
    let result = run_plan(
      &plan,
      &inputs_with_durations,
      &dir.0,
      concat_list.to_str().unwrap(),
      output.to_str().unwrap(),
      chapters.to_str().unwrap(),
      2.0,
    );
    assert!(
      result.status.success(),
      "{}",
      String::from_utf8_lossy(&result.stderr)
    );

    let seconds = get_media_seconds(output.to_str().unwrap()).unwrap();
    assert!(
      (seconds - 2.0).abs() < 0.3,
      "expected about 2s, got {seconds}"
    );
  }

  /// Creates a 1-second video with an attached PNG cover as its second video stream, and an
  /// audio stream at `sample_rate` Hz (mono AAC).
  fn make_clip_with_cover(path: &Path, sample_rate: u32) {
    let status = Command::new("ffmpeg")
      .args(["-v", "error", "-y"])
      .args(["-f", "lavfi", "-i", "testsrc=d=1:s=160x120:r=25"])
      .args(["-f", "lavfi", "-i", "color=c=red:s=64x64:d=1"])
      .args(["-f", "lavfi", "-i"])
      .arg(format!("sine=f=440:d=1:sample_rate={sample_rate}"))
      .args(["-map", "0:v", "-map", "1:v", "-map", "2:a"])
      .args(["-c:v:0", "libx264", "-pix_fmt", "yuv420p"])
      .args(["-c:v:1", "mjpeg", "-disposition:v:1", "attached_pic"])
      .args(["-c:a", "aac", "-shortest"])
      .arg(path)
      .status()
      .expect("ffmpeg must be installed");
    assert!(status.success(), "failed to create the cover test clip");
  }

  #[test]
  fn merge_keeps_an_attached_cover_when_audio_forces_conversion() {
    // Both inputs have an attached cover. The second input's audio rate differs, which forces
    // a conversion. The cover must survive the conversion and the concat must succeed.
    let dir = TempDir::new("cover-merge");
    let first = dir.0.join("1 - first.mp4");
    let second = dir.0.join("2 - second.mp4");
    make_clip_with_cover(&first, 48_000);
    make_clip_with_cover(&second, 44_100);

    let files = [
      first.to_str().unwrap().to_string(),
      second.to_str().unwrap().to_string(),
    ];
    let probes: Vec<Vec<MediaStream>> = files
      .iter()
      .map(|path| probe_streams(path).unwrap())
      .collect();
    let sizes = vec![None, None];
    let cropped = vec![false, false];
    let plan = super::plan_merge(&probes, &sizes, &cropped, "mp4", false);
    assert_eq!(plan.keep_video_streams, vec![1]);
    assert!(plan
      .actions
      .iter()
      .all(|action| matches!(action, InputAction::Convert { .. })));

    let concat_list = dir.0.join("list.txt");
    let chapters = dir.0.join("chapters.txt");
    fs::write(&chapters, ";FFMETADATA1\n").unwrap();
    let output = dir.0.join("merged.mp4");
    let inputs_with_durations: Vec<(String, f64)> =
      files.iter().map(|file| (file.clone(), 1.0)).collect();
    let result = run_plan(
      &plan,
      &inputs_with_durations,
      &dir.0,
      concat_list.to_str().unwrap(),
      output.to_str().unwrap(),
      chapters.to_str().unwrap(),
      2.0,
    );
    assert!(
      result.status.success(),
      "{}",
      String::from_utf8_lossy(&result.stderr)
    );

    // The merged output keeps the picture and the cover, and both clips are joined.
    let streams = probe_streams(output.to_str().unwrap()).unwrap();
    let video_codecs: Vec<&str> = streams
      .iter()
      .filter(|s| s.kind == "video")
      .map(|s| s.codec.as_str())
      .collect();
    assert_eq!(video_codecs, vec!["h264", "mjpeg"]);
    let cover = streams
      .iter()
      .find(|s| s.kind == "video" && s.codec == "mjpeg")
      .expect("the merged output has no MJPEG stream");
    assert!(
      cover.attached_pic,
      "the merged MJPEG stream lost its attached_pic disposition"
    );
    let seconds = get_media_seconds(output.to_str().unwrap()).unwrap();
    assert!(
      (seconds - 2.0).abs() < 0.3,
      "expected about 2s, got {seconds}"
    );
  }

  /// Creates a 1-second video with two audio tracks (440 Hz and 880 Hz).
  fn make_clip_with_two_audio_tracks(path: &Path) {
    let status = Command::new("ffmpeg")
      .args(["-v", "error", "-y"])
      .args(["-f", "lavfi", "-i", "testsrc=d=1:s=160x120:r=25"])
      .args(["-f", "lavfi", "-i", "sine=f=440:d=1"])
      .args(["-f", "lavfi", "-i", "sine=f=880:d=1"])
      .args(["-map", "0:v", "-map", "1:a", "-map", "2:a"])
      .args([
        "-c:v",
        "libx264",
        "-pix_fmt",
        "yuv420p",
        "-c:a",
        "aac",
        "-shortest",
      ])
      .arg(path)
      .status()
      .expect("ffmpeg must be installed");
    assert!(status.success(), "failed to create two-track test clip");
  }

  #[test]
  fn run_plan_gives_the_output_every_audio_track_when_the_shorter_input_is_first() {
    let dir = TempDir::new("plan-tracks");
    let one_track = dir.0.join("1 - one track.mp4");
    let two_tracks = dir.0.join("2 - two tracks.mp4");
    make_clip(&one_track, true);
    make_clip_with_two_audio_tracks(&two_tracks);

    let profile = AudioProfile {
      sample_rate: 48_000,
      channels: 2,
    };
    // The input with fewer tracks comes first. It gets one silent track to match the other.
    let plan = MergePlan {
      profile: Some(profile),
      hevc: false,
      actions: vec![
        InputAction::Convert { silent_audio: true },
        InputAction::Convert {
          silent_audio: false,
        },
      ],
      video_size: vec![None, None],
      keep_video_streams: vec![],
      attached_covers: vec![],
      audio_tracks: vec![1, 2],
      target_audio_tracks: 2,
    };
    let files = [
      one_track.to_str().unwrap().to_string(),
      two_tracks.to_str().unwrap().to_string(),
    ];
    let inputs_with_durations: Vec<(String, f64)> =
      files.iter().map(|file| (file.clone(), 1.0)).collect();

    let concat_list = dir.0.join("list.txt");
    let chapters = dir.0.join("chapters.txt");
    fs::write(&chapters, ";FFMETADATA1\n").unwrap();
    let output = dir.0.join("merged.mp4");

    let result = run_plan(
      &plan,
      &inputs_with_durations,
      &dir.0,
      concat_list.to_str().unwrap(),
      output.to_str().unwrap(),
      chapters.to_str().unwrap(),
      2.0,
    );
    assert!(
      result.status.success(),
      "{}",
      String::from_utf8_lossy(&result.stderr)
    );

    let streams = probe_streams(output.to_str().unwrap()).unwrap();
    let audio_tracks = streams.iter().filter(|s| s.kind == "audio").count();
    assert_eq!(audio_tracks, 2, "expected two audio tracks in {streams:?}");
  }
}