vidmerger 0.4.4

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
use crate::cli::Cli;
use crate::helper::io_helper::verbose;
use crate::helper::progress_helper::ProgressBar;
use crate::helper::str_helper::blue;
use clap::ArgMatches;
use lazy_static::lazy_static;
use path_slash::PathBufExt;
use std::{
  collections::BTreeMap,
  io::{BufRead, BufReader, Error, Read},
  path::PathBuf,
  process::{Child, Command, Output, Stdio},
  sync::OnceLock,
};

lazy_static! {
  static ref MATCHES: ArgMatches = Cli::init().get_matches();
  static ref VERBOSE: bool = MATCHES.get_flag("verbose");
}

/// FFmpeg flags that make it write progress lines (`out_time_us=...`) to stdout
/// and keep stderr short. Used when not in verbose mode.
pub const PROGRESS_ARGS: [&str; 5] = ["-progress", "pipe:1", "-nostats", "-loglevel", "error"];

/// Merges the files with stream copy and shows a 0–100% progress bar.
/// `total_seconds` is the combined length of all input files. Each output video index in
/// `attached_covers` is flagged as an attached picture again, because the concat step drops that
/// flag even though the cover itself is kept.
pub fn merge(
  input: String,
  output: &str,
  chapters: &str,
  total_seconds: f64,
  attached_covers: &[usize],
) -> Output {
  let mut args: Vec<&str> = vec![
    "-y",
    "-f",
    "concat",
    "-safe",
    "0",
    "-i",
    input.as_str(),
    "-i",
    chapters,
    "-map",
    "0",
    "-map_metadata",
    "1",
    "-c",
    "copy",
  ];
  let cover_flags: Vec<String> = attached_covers
    .iter()
    .map(|index| format!("-disposition:v:{index}"))
    .collect();
  for flag in &cover_flags {
    args.extend([flag.as_str(), "attached_pic"]);
  }
  if !verbose() {
    args.extend(PROGRESS_ARGS);
  }
  args.push(output);

  println!(
    "🚀 Run Merger, calling: {}",
    blue(describe("ffmpeg", &args))
  );

  if verbose() {
    return spawn_command("ffmpeg", &args, false)
      .unwrap()
      .wait_with_output()
      .unwrap();
  }

  run_with_progress(&args, "Merging videos", total_seconds)
}

/// GPU H.264 encoders for Linux and Windows, in order of preference.
const GPU_H264_ENCODERS: [&str; 3] = ["h264_nvenc", "h264_qsv", "h264_amf"];

/// GPU HEVC encoders for Linux and Windows, in order of preference.
const GPU_HEVC_ENCODERS: [&str; 3] = ["hevc_nvenc", "hevc_qsv", "hevc_amf"];

/// Returns the first candidate for which `works` is true, or `fallback` if none is.
/// Stops at the first success, so later candidates are not tested.
fn pick_encoder(
  candidates: &[&'static str],
  fallback: &'static str,
  works: impl Fn(&str) -> bool,
) -> &'static str {
  candidates
    .iter()
    .copied()
    .find(|encoder| works(encoder))
    .unwrap_or(fallback)
}

/// Returns true if FFmpeg can encode one test frame with `encoder`.
/// FFmpeg can list a GPU encoder even when no GPU is present, so a real test encode is used.
fn encoder_works(encoder: &str) -> bool {
  Command::new("ffmpeg")
    .args([
      "-v",
      "error",
      "-f",
      "lavfi",
      "-i",
      "nullsrc=s=256x256",
      "-frames:v",
      "1",
      "-c:v",
      encoder,
      "-f",
      "null",
      "-",
    ])
    .output()
    .map(|output| output.status.success())
    .unwrap_or(false)
}

/// Returns the H.264 encoder to use. The result is found once per run.
/// macOS tries VideoToolbox. Linux and Windows try the GPU encoders (NVIDIA, Intel or AMD).
/// Each candidate is tested first. If none works, `libx264` (CPU) is used.
pub fn h264_encoder() -> &'static str {
  static ENCODER: OnceLock<&'static str> = OnceLock::new();
  ENCODER.get_or_init(|| {
    let candidates: &[&'static str] = if cfg!(target_os = "macos") {
      &["h264_videotoolbox"]
    } else {
      &GPU_H264_ENCODERS
    };
    pick_encoder(candidates, "libx264", encoder_works)
  })
}

/// Returns the HEVC encoder for HEVC input that is cropped. The result is found once per run.
/// macOS uses VideoToolbox. Linux and Windows try the GPU encoders, then the CPU encoder
/// `libx265`. Keeping HEVC lets cropped and uncropped HEVC files share one video codec in the merge.
pub fn hevc_encoder() -> &'static str {
  static ENCODER: OnceLock<&'static str> = OnceLock::new();
  ENCODER.get_or_init(|| {
    if cfg!(target_os = "macos") {
      "hevc_videotoolbox"
    } else {
      pick_encoder(&GPU_HEVC_ENCODERS, "libx265", encoder_works)
    }
  })
}

/// The video settings of one converted input: the `(width, height)` it is scaled to (if any),
/// and which secondary video streams are copied (their index among the video streams, starting at 1).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct VideoTarget {
  pub size: Option<(u32, u32)>,
  pub keep_video_streams: Vec<usize>,
}

/// Converts one input to an MP4 file that is safe to merge.
/// Only video and audio streams are mapped, so data streams (e.g. `tmcd`) are dropped.
/// Video is re-encoded to H.264. Audio is encoded to AAC with the shared `profile`.
/// `silent_tracks` silent audio tracks are added after the input's own audio, so the output has
/// the track count the merge needs. Each silent track lasts as long as the input. `-write_tmcd 0` stops the MP4/MOV muxer from
/// adding a `tmcd` track again. If `video.size` is set, the video is scaled to fit and padded with
/// black bars to that `(width, height)`, so it can be concatenated with the other inputs.
pub fn convert_for_merge(
  input: &str,
  output: &str,
  profile: Option<AudioProfile>,
  silent_tracks: usize,
  hevc: bool,
  duration_seconds: f64,
  video: VideoTarget,
) -> Output {
  // The merge chooses one video codec for every input (see `plan_merge`), so the converter does
  // not pick its own. HEVC uses the hardware HEVC encoder, H.264 uses the H.264 encoder.
  let encoder = if hevc {
    "hevc_videotoolbox"
  } else {
    h264_encoder()
  };
  convert_with_cpu_fallback(
    encoder,
    |result: &Output| result.status.success(),
    |encoder| {
      run_convert(
        input,
        output,
        profile,
        silent_tracks,
        encoder,
        duration_seconds,
        video.clone(),
      )
    },
  )
}

/// True when the input's first video stream is HEVC (H.265).
pub fn is_hevc(input: &str) -> bool {
  Command::new("ffprobe")
    .args([
      "-v",
      "error",
      "-select_streams",
      "v:0",
      "-show_entries",
      "stream=codec_name",
      "-of",
      "csv=p=0",
      input,
    ])
    .output()
    .map(|output| is_hevc_codec_output(&String::from_utf8_lossy(&output.stdout)))
    .unwrap_or(false)
}

/// Reads ffprobe's `codec_name` output. ffprobe can print a trailing comma (e.g. "hevc,"), so
/// only the first field is the codec.
fn is_hevc_codec_output(text: &str) -> bool {
  text
    .trim()
    .split(',')
    .next()
    .is_some_and(|codec| codec == "hevc")
}

#[cfg(test)]
mod test_is_hevc_codec_output {
  use super::is_hevc_codec_output;

  #[test]
  fn accepts_plain_hevc() {
    assert!(is_hevc_codec_output("hevc\n"));
  }

  #[test]
  fn accepts_hevc_with_trailing_comma() {
    assert!(is_hevc_codec_output("hevc,\n"));
  }

  #[test]
  fn rejects_other_codecs() {
    assert!(!is_hevc_codec_output("h264,\n"));
    assert!(!is_hevc_codec_output(""));
  }
}

/// Runs `convert` with `encoder`. If that fails and `encoder` is not `libx264`, runs it again
/// with `libx264`. A GPU encoder can pass the test frame but still fail on a real input.
fn convert_with_cpu_fallback<T>(
  encoder: &str,
  succeeded: impl Fn(&T) -> bool,
  convert: impl Fn(&str) -> T,
) -> T {
  let result = convert(encoder);
  if succeeded(&result) || encoder == "libx264" {
    return result;
  }
  println!("⚠️  {encoder} failed, retrying with libx264");
  convert("libx264")
}

/// Inputs shorter than this keep the encoder's own bitrate. Forcing a bitrate on very short clips
/// is not needed to control the size of a long film, and it changed the length of short clips.
const MIN_SECONDS_FOR_SOURCE_BIT_RATE: f64 = 60.0;

/// The bitrate to pass to the encoder for `input`, or `None` to let the encoder choose. Only
/// long inputs get the source bitrate, which is what keeps a film's output size close to its source.
pub fn keep_source_bit_rate(input: &str, duration_seconds: f64) -> Option<u64> {
  if duration_seconds >= MIN_SECONDS_FOR_SOURCE_BIT_RATE {
    video_bit_rate(input)
  } else {
    None
  }
}

/// Returns the video stream's bitrate in bits per second, or `None` when the file does not
/// report one (e.g. some containers only report the format bitrate).
pub fn video_bit_rate(input: &str) -> Option<u64> {
  let output = Command::new("ffprobe")
    .args([
      "-v",
      "error",
      "-select_streams",
      "v:0",
      "-show_entries",
      "stream=bit_rate",
      "-of",
      "csv=p=0",
      input,
    ])
    .output()
    .ok()?;
  parse_bit_rate(&String::from_utf8_lossy(&output.stdout))
}

/// Reads ffprobe's bitrate output. ffprobe can print a trailing comma (e.g. "12345,"), so only
/// the first field is the bitrate. A zero or missing value is `None`.
fn parse_bit_rate(text: &str) -> Option<u64> {
  text
    .trim()
    .split(',')
    .next()
    .and_then(|field| field.parse::<u64>().ok())
    .filter(|bit_rate| *bit_rate > 0)
}

#[cfg(test)]
mod test_parse_bit_rate {
  use super::parse_bit_rate;

  #[test]
  fn reads_a_plain_bitrate() {
    assert_eq!(parse_bit_rate("12345\n"), Some(12345));
  }

  #[test]
  fn reads_a_bitrate_with_a_trailing_comma() {
    assert_eq!(parse_bit_rate("12345,\n"), Some(12345));
  }

  #[test]
  fn ignores_missing_or_zero_bitrate() {
    assert_eq!(parse_bit_rate(""), None);
    assert_eq!(parse_bit_rate("N/A\n"), None);
    assert_eq!(parse_bit_rate("0\n"), None);
  }
}

/// Runs one conversion with the given H.264 `encoder`. See `convert_for_merge`.
fn run_convert(
  input: &str,
  output: &str,
  profile: Option<AudioProfile>,
  silent_tracks: usize,
  encoder: &str,
  duration_seconds: f64,
  video: VideoTarget,
) -> Output {
  let mut args: Vec<String> = ["-y", "-i", input].map(String::from).to_vec();
  // Each silent track gets its own silent source (input 1, 2, ...). The input's own audio
  // tracks come first, then the silent ones.
  let mut audio_maps: Vec<String> = ["-map", "0:a?"].map(String::from).to_vec();
  if silent_tracks > 0 {
    let profile = profile.expect("silent audio needs an audio profile");
    for track in 0..silent_tracks {
      // `-t` cuts the silence to the input's length, so the output ends with the video.
      args.extend(["-f", "lavfi", "-t"].map(String::from));
      args.push(duration_seconds.to_string());
      args.extend(["-i"].map(String::from));
      args.push(format!("anullsrc=r={}", profile.sample_rate));
      audio_maps.extend(["-map".to_string(), format!("{}:a", track + 1)]);
    }
  }
  // The picture is video stream 0, which is re-encoded. A cover image (e.g. PNG) is video stream 1,
  // which is copied as it is. Video is mapped first, then the audio tracks.
  args.extend(["-map", "0:v:0?"].map(String::from));
  for index in &video.keep_video_streams {
    args.extend(["-map".to_string(), format!("0:v:{index}?")]);
  }
  args.extend(audio_maps);
  // Scale to fit inside the target size, then pad with black bars to the exact size.
  if let Some((width, height)) = video.size {
    args.extend([
      "-filter:v:0".to_string(),
      format!(
        "scale={width}:{height}:force_original_aspect_ratio=decrease,pad={width}:{height}:(ow-iw)/2:(oh-ih)/2"
      ),
    ]);
  }
  args.push("-c:v:0".to_string());
  args.push(encoder.to_string());
  // Apple players only open HEVC in MP4 when it is tagged `hvc1`.
  if encoder.starts_with("hevc") {
    args.extend(["-tag:v:0", "hvc1"].map(String::from));
  }
  // Keep the source's video bitrate on long inputs (see `keep_source_bit_rate`).
  if let Some(bit_rate) = keep_source_bit_rate(input, duration_seconds) {
    args.extend(["-b:v:0".to_string(), bit_rate.to_string()]);
  }
  // Output video streams: 0 is the re-encoded picture, so the kept streams are 1, 2, ...
  for output_index in 1..=video.keep_video_streams.len() {
    args.extend([format!("-c:v:{output_index}"), "copy".to_string()]);
  }
  args.extend(["-c:a", "aac"].map(String::from));
  if let Some(profile) = profile {
    args.extend(["-ar".to_string(), profile.sample_rate.to_string()]);
    args.extend(["-ac".to_string(), profile.channels.to_string()]);
  }
  args.extend(["-write_tmcd", "0"].map(String::from));
  args.push(output.to_string());

  let shown: Vec<&str> = args.iter().map(String::as_str).collect();
  println!(
    "🔁 Converting for merge, calling: {}",
    blue(describe("ffmpeg", &shown))
  );

  // `output()` captures stderr too, so a failure message can be shown.
  Command::new("ffmpeg").args(&args).output().unwrap()
}

/// Runs FFmpeg by the time it has written (`out_time_us`). Use it when there are no subtitle
/// streams, because copied subtitles make FFmpeg report the end of the file at once.
/// `total_seconds` is the length of the input. If it is 0, the bar only jumps to 100% at the end.
pub fn run_with_progress(args: &[&str], label: &str, total_seconds: f64) -> Output {
  run_with_progress_by(args, label, |line| {
    if total_seconds <= 0.0 {
      return None;
    }
    parse_out_time_us(line).map(|micros| micros as f64 / 1_000_000.0 / total_seconds)
  })
}

/// Runs FFmpeg by its video frame count (`frame=`), out of `total_frames`. Use it when subtitles
/// are copied, because the time reported by FFmpeg then jumps to the end of the file at once.
pub fn run_with_frame_progress(args: &[&str], label: &str, total_frames: u64) -> Output {
  run_with_progress_by(args, label, |line| {
    if total_frames == 0 {
      return None;
    }
    parse_frame(line).map(|frame| frame as f64 / total_frames as f64)
  })
}

/// Runs FFmpeg (with `PROGRESS_ARGS` set) and shows a 0–100% bar. `fraction_of` turns each
/// progress line into a fraction of the job (0.0 to 1.0), or `None` to ignore the line.
/// Returns FFmpeg's status and stderr. The stdout in the result is empty.
fn run_with_progress_by(
  args: &[&str],
  label: &str,
  fraction_of: impl Fn(&str) -> Option<f64>,
) -> Output {
  let mut child = Command::new("ffmpeg")
    .args(args)
    .stdout(Stdio::piped())
    .stderr(Stdio::piped())
    .spawn()
    .unwrap();
  // Drain stderr on its own thread, so FFmpeg never blocks on a full stderr pipe.
  let stderr_reader = child.stderr.take().map(|mut stderr| {
    std::thread::spawn(move || {
      let mut buf = Vec::new();
      let _ = stderr.read_to_end(&mut buf);
      buf
    })
  });
  let mut bar = ProgressBar::start(label);
  if let Some(stdout) = child.stdout.take() {
    for line in BufReader::new(stdout).lines().map_while(Result::ok) {
      if let Some(fraction) = fraction_of(&line) {
        bar.set(fraction);
      }
    }
  }
  let status = child.wait().unwrap();
  let stderr = stderr_reader
    .and_then(|handle| handle.join().ok())
    .unwrap_or_default();
  bar.finish(status.success());
  // stdout is consumed above for progress, so the returned Output has it empty.
  Output {
    status,
    stdout: Vec::new(),
    stderr,
  }
}

/// Reads the `out_time_us=` value from FFmpeg's `-progress` output, in microseconds.
/// Returns `None` for other lines and for `N/A` values.
fn parse_out_time_us(line: &str) -> Option<i64> {
  line
    .strip_prefix("out_time_us=")?
    .trim()
    .parse::<i64>()
    .ok()
}

/// Reads the `frame=` value from FFmpeg's `-progress` output, the number of video frames done.
/// Returns `None` for other lines and for values that are not numbers.
pub fn parse_frame(line: &str) -> Option<u64> {
  line.strip_prefix("frame=")?.trim().parse::<u64>().ok()
}

/// Returns the number of frames in the first video stream, from ffprobe's `nb_frames`.
/// Returns `None` if ffprobe cannot be run or the container does not store a frame count.
pub fn video_frame_count(file: &str) -> Option<u64> {
  let output = Command::new("ffprobe")
    .args([
      "-v",
      "error",
      "-select_streams",
      "v:0",
      "-show_entries",
      "stream=nb_frames",
      "-of",
      "default=noprint_wrappers=1:nokey=1",
      file,
    ])
    .output()
    .ok()?;
  String::from_utf8_lossy(&output.stdout)
    .trim()
    .parse::<u64>()
    .ok()
}

/// Runs `ffmpeg -i <file>` and returns its output. FFmpeg prints stream info to stderr.
/// Returns `Err` if FFmpeg cannot be started. Panics if the path is not valid UTF-8.
pub fn run_ffmpeg_info_command(file_to_merge: &PathBuf) -> Result<Output, Error> {
  Command::new("ffmpeg")
    .args(["-i", &file_to_merge.to_slash().unwrap()])
    .output()
}

/// Changes the frame rate of `file_to_merge` to `fps_goal` and writes the result to
/// `new_file_location`. Returns the new file's path. In normal (non-verbose) mode it panics if
/// FFmpeg fails. In verbose mode it prints FFmpeg's result and returns the path even on failure.
pub fn adjust_fps_by_ffmpeg(
  file_to_merge: PathBuf,
  fps_goal: &f32,
  new_file_location: PathBuf,
) -> PathBuf {
  let input = file_to_merge.to_str().unwrap();
  let fps = fps_goal.to_string();
  let output = new_file_location.to_str().unwrap();
  let mut args = vec!["-i", input, "-r", fps.as_str()];

  // Print the command without the progress flags, so the log line stays short.
  let shown: Vec<&str> = args.iter().copied().chain([output]).collect();
  println!(
    "🚀 Start FPS Changer, calling: {}",
    blue(describe("ffmpeg", &shown))
  );

  if verbose() {
    args.push(output);
    let res = spawn_command("ffmpeg", &args, false)
      .unwrap()
      .wait_with_output()
      .unwrap();
    println!("{res:?}");
  } else {
    args.extend(PROGRESS_ARGS);
    args.push(output);
    let total_seconds = get_media_seconds(input).unwrap_or(0.0);
    let res = run_with_progress(&args, "Changing FPS", total_seconds);
    if !res.status.success() {
      panic!(
        "❌ FPS change failed (exit code: {:?}):{}",
        res.status.code(),
        String::from_utf8_lossy(&res.stderr)
      );
    }
  }
  new_file_location
}

/// One stream reported by ffprobe. `sample_rate` and `channels` are only set for audio.
/// `attached_pic` is true for a cover image stored as a video stream (ffprobe's `attached_pic`
/// disposition), such as album art.
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct MediaStream {
  pub kind: String,
  pub codec: String,
  pub sample_rate: Option<u32>,
  pub channels: Option<u32>,
  pub attached_pic: bool,
}

/// Audio settings that all merged inputs share (sample rate in Hz, channel count).
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub struct AudioProfile {
  pub sample_rate: u32,
  pub channels: u32,
}

/// Lists the streams of a media file with one ffprobe call.
/// Returns `Err` if ffprobe fails or an audio stream lacks its sample rate or channels.
pub fn probe_streams(media_path: &str) -> Result<Vec<MediaStream>, String> {
  let output = Command::new("ffprobe")
    .args([
      "-v",
      "error",
      "-show_entries",
      "stream=codec_type,codec_name,sample_rate,channels:stream_disposition=attached_pic",
      "-of",
      "flat",
      media_path,
    ])
    .output()
    .map_err(|err| err.to_string())?;
  if !output.status.success() {
    return Err(String::from_utf8_lossy(&output.stderr).trim().to_string());
  }
  parse_flat_streams(&String::from_utf8_lossy(&output.stdout))
}

/// Parses ffprobe `-of flat` output, e.g. `streams.stream.1.codec_type="audio"`.
/// Fields are grouped by stream index. ffprobe leaves out fields a stream does not have.
fn parse_flat_streams(text: &str) -> Result<Vec<MediaStream>, String> {
  let mut streams: BTreeMap<usize, BTreeMap<&str, &str>> = BTreeMap::new();
  for line in text.lines() {
    let Some((key, value)) = line.split_once('=') else {
      continue;
    };
    // Keys look like `streams.stream.N.field`, or `streams.stream.N.disposition.flag` for the
    // disposition flags. The flag is stored under its own name, e.g. `attached_pic`.
    let parts: Vec<&str> = key.split('.').collect();
    let (index, field) = match parts.as_slice() {
      ["streams", "stream", index, field] => (index, *field),
      ["streams", "stream", index, "disposition", flag] => (index, *flag),
      _ => continue,
    };
    let Ok(index) = index.parse::<usize>() else {
      continue;
    };
    streams
      .entry(index)
      .or_default()
      .insert(field, value.trim_matches('"'));
  }
  streams.values().map(stream_from_fields).collect()
}

/// Builds one `MediaStream` from its ffprobe fields. Audio needs a sample rate and channels.
fn stream_from_fields(fields: &BTreeMap<&str, &str>) -> Result<MediaStream, String> {
  let kind = fields.get("codec_type").copied().unwrap_or("unknown");
  let codec = fields.get("codec_name").copied().unwrap_or("");
  let (sample_rate, channels) = if kind == "audio" {
    let sample_rate = fields
      .get("sample_rate")
      .and_then(|v| v.parse::<u32>().ok());
    let channels = fields.get("channels").and_then(|v| v.parse::<u32>().ok());
    match (sample_rate, channels) {
      (Some(rate), Some(count)) => (Some(rate), Some(count)),
      _ => {
        return Err(format!(
          "audio stream without sample rate or channels: {fields:?}"
        ))
      }
    }
  } else {
    (None, None)
  };
  let attached_pic = fields.get("attached_pic").copied() == Some("1");
  Ok(MediaStream {
    kind: kind.to_string(),
    codec: codec.to_string(),
    sample_rate,
    channels,
    attached_pic,
  })
}

/// Returns the length of a media file in seconds, read with ffprobe.
/// Returns `Err` if ffprobe cannot be started or waited on, if its output is not valid UTF-8,
/// or if its output is not a number.
pub fn get_media_seconds(media_path: &str) -> Result<f64, Box<dyn std::error::Error>> {
  let args = [
    "-v",
    "error",
    "-show_entries",
    "format=duration",
    "-of",
    "default=noprint_wrappers=1:nokey=1",
    media_path,
  ];

  if verbose() {
    println!(
      "📖 Getting media seconds, calling: {}",
      blue(describe("ffprobe", &args))
    );
  }
  let output = spawn_command("ffprobe", &args, false)?.wait_with_output()?;
  let output = String::from_utf8(output.stdout)?;
  Ok(output.trim().parse::<f64>()?)
}

/// Starts a program with each argument passed separately (no shell).
/// This keeps file names with quotes, spaces or `$` from being split or
/// interpreted by a shell.
fn spawn_command(program: &str, args: &[&str], silent: bool) -> Result<Child, std::io::Error> {
  let mut command = Command::new(program);
  command.args(args);
  if silent {
    command.stdout(Stdio::null()).stderr(Stdio::null());
  } else {
    command.stdout(Stdio::piped());
  }
  command.spawn()
}

/// Builds a printable version of the command for log output only.
/// It is never executed.
pub fn describe(program: &str, args: &[&str]) -> String {
  std::iter::once(program)
    .chain(args.iter().copied())
    .map(|arg| format!("'{arg}'"))
    .collect::<Vec<_>>()
    .join(" ")
}

#[cfg(test)]
mod test_parse_frame {
  use super::parse_frame;

  #[test]
  fn reads_the_frame_count_from_a_progress_line() {
    assert_eq!(parse_frame("frame=1957"), Some(1957));
  }

  #[test]
  fn ignores_other_progress_lines() {
    assert_eq!(parse_frame("out_time_us=230038666"), None);
    assert_eq!(parse_frame("frame=N/A"), None);
  }
}

#[cfg(test)]
mod test_parse_flat_streams {
  use super::{parse_flat_streams, MediaStream};

  #[test]
  fn parses_audio_and_video_streams_in_index_order() {
    let text = "streams.stream.0.codec_name=\"h264\"\n\
                streams.stream.0.codec_type=\"video\"\n\
                streams.stream.1.codec_name=\"aac\"\n\
                streams.stream.1.codec_type=\"audio\"\n\
                streams.stream.1.sample_rate=\"44100\"\n\
                streams.stream.1.channels=1\n";
    assert_eq!(
      parse_flat_streams(text),
      Ok(vec![
        MediaStream {
          kind: "video".into(),
          codec: "h264".into(),
          sample_rate: None,
          channels: None,
          attached_pic: false,
        },
        MediaStream {
          kind: "audio".into(),
          codec: "aac".into(),
          sample_rate: Some(44100),
          channels: Some(1),
          attached_pic: false,
        },
      ])
    );
  }

  #[test]
  fn reads_the_attached_picture_disposition() {
    let text = "streams.stream.0.codec_name=\"h264\"\n\
                streams.stream.0.codec_type=\"video\"\n\
                streams.stream.0.disposition.attached_pic=0\n\
                streams.stream.1.codec_name=\"mjpeg\"\n\
                streams.stream.1.codec_type=\"video\"\n\
                streams.stream.1.disposition.attached_pic=1\n";
    let streams = parse_flat_streams(text).unwrap();
    assert!(!streams[0].attached_pic);
    assert!(streams[1].attached_pic);
  }

  #[test]
  fn parses_data_stream_without_audio_fields() {
    let text = "streams.stream.0.codec_name=\"tmcd\"\nstreams.stream.0.codec_type=\"data\"\n";
    let streams = parse_flat_streams(text).unwrap();
    assert_eq!(streams[0].codec, "tmcd");
    assert_eq!((streams[0].sample_rate, streams[0].channels), (None, None));
  }

  #[test]
  fn rejects_audio_stream_without_numbers() {
    let text = "streams.stream.0.codec_name=\"aac\"\nstreams.stream.0.codec_type=\"audio\"\n";
    assert!(parse_flat_streams(text).is_err());
  }
}

#[cfg(test)]
mod test_h264_encoder {
  use super::{convert_with_cpu_fallback, pick_encoder, GPU_H264_ENCODERS, GPU_HEVC_ENCODERS};
  use std::cell::RefCell;

  #[test]
  fn fallback_keeps_result_when_encoder_succeeds() {
    let calls = RefCell::new(Vec::new());
    let ok = convert_with_cpu_fallback(
      "h264_nvenc",
      |ok: &bool| *ok,
      |encoder| {
        calls.borrow_mut().push(encoder.to_string());
        true
      },
    );
    assert!(ok);
    assert_eq!(*calls.borrow(), vec!["h264_nvenc"]);
  }

  #[test]
  fn fallback_retries_gpu_failure_with_libx264() {
    let calls = RefCell::new(Vec::new());
    let ok = convert_with_cpu_fallback(
      "h264_nvenc",
      |ok: &bool| *ok,
      |encoder| {
        calls.borrow_mut().push(encoder.to_string());
        encoder == "libx264"
      },
    );
    assert!(ok);
    assert_eq!(*calls.borrow(), vec!["h264_nvenc", "libx264"]);
  }

  #[test]
  fn fallback_does_not_retry_when_libx264_fails() {
    let calls = RefCell::new(Vec::new());
    let ok = convert_with_cpu_fallback(
      "libx264",
      |ok: &bool| *ok,
      |encoder| {
        calls.borrow_mut().push(encoder.to_string());
        false
      },
    );
    assert!(!ok);
    assert_eq!(*calls.borrow(), vec!["libx264"]);
  }

  #[test]
  fn picks_nvenc_first_and_stops_testing() {
    let tested = std::cell::RefCell::new(Vec::new());
    let picked = pick_encoder(&GPU_H264_ENCODERS, "libx264", |encoder| {
      tested.borrow_mut().push(encoder.to_string());
      true
    });
    assert_eq!(picked, "h264_nvenc");
    assert_eq!(*tested.borrow(), vec!["h264_nvenc"]);
  }

  #[test]
  fn picks_qsv_when_only_qsv_works() {
    let picked = pick_encoder(&GPU_H264_ENCODERS, "libx264", |e| e == "h264_qsv");
    assert_eq!(picked, "h264_qsv");
  }

  #[test]
  fn hevc_falls_back_to_libx265_without_gpu_encoder() {
    assert_eq!(
      pick_encoder(&GPU_HEVC_ENCODERS, "libx265", |_| false),
      "libx265"
    );
  }

  #[test]
  fn falls_back_to_libx264_without_gpu_encoder() {
    assert_eq!(
      pick_encoder(&GPU_H264_ENCODERS, "libx264", |_| false),
      "libx264"
    );
  }
}

/// Integration test: this runs real ffmpeg to test each H.264 encoder.
#[cfg(test)]
mod test_h264_encoder_integration {
  use super::{h264_encoder, hevc_encoder};

  #[test]
  fn hevc_encoder_is_a_known_hevc_encoder() {
    let encoder = hevc_encoder();
    let allowed: &[&str] = if cfg!(target_os = "macos") {
      &["hevc_videotoolbox"]
    } else {
      &["hevc_nvenc", "hevc_qsv", "hevc_amf", "libx265"]
    };
    assert!(allowed.contains(&encoder), "unexpected encoder: {encoder}");
  }

  #[test]
  fn uses_videotoolbox_on_macos_and_a_known_encoder_elsewhere() {
    // The probe can fail on a supported system, so the CPU fallback is also valid.
    let encoder = h264_encoder();
    let allowed: &[&str] = if cfg!(target_os = "macos") {
      &["h264_videotoolbox", "libx264"]
    } else {
      &["h264_nvenc", "h264_qsv", "h264_amf", "libx264"]
    };
    assert!(allowed.contains(&encoder), "unexpected encoder: {encoder}");
  }

  #[test]
  fn ffmpeg_is_installed() {
    assert!(
      which::which("ffmpeg").is_ok(),
      "ffmpeg wasn't found on the PATH"
    );
  }
}

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

  #[test]
  fn parses_out_time_us_line() {
    assert_eq!(parse_out_time_us("out_time_us=1500000"), Some(1_500_000));
  }

  #[test]
  fn ignores_other_progress_lines() {
    assert_eq!(parse_out_time_us("out_time=00:00:01.500000"), None);
    assert_eq!(parse_out_time_us("out_time_us=N/A"), None);
    assert_eq!(parse_out_time_us("progress=continue"), None);
  }
}

/// Integration tests: these call real ffmpeg and ffprobe on generated media files.
#[cfg(test)]
mod test_ffmpeg_integration {
  use super::AudioProfile;
  use super::VideoTarget;
  use super::{
    adjust_fps_by_ffmpeg, convert_for_merge, get_media_seconds, merge, probe_streams,
    run_ffmpeg_info_command, video_frame_count,
  };
  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-{name}-{}", std::process::id()));
      let _ = std::fs::remove_dir_all(&dir);
      std::fs::create_dir_all(&dir).unwrap();
      TempDir(dir)
    }

    fn path(&self, file: &str) -> PathBuf {
      self.0.join(file)
    }
  }

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

  /// Creates a 1-second MP4 with a video stream, and an audio stream when `audio` is true.
  fn make_clip(path: &Path, audio: bool) {
    let mut cmd = Command::new("ffmpeg");
    cmd.args([
      "-v",
      "error",
      "-y",
      "-f",
      "lavfi",
      "-i",
      "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 run_ffmpeg_info_command_reports_stream_info() {
    let dir = TempDir::new("info");
    let clip = dir.path("clip.mp4");
    make_clip(&clip, false);

    let output = run_ffmpeg_info_command(&clip).unwrap();
    let info = String::from_utf8_lossy(&output.stderr);
    assert!(info.contains("Video:"), "no video stream in: {info}");
    assert!(info.contains("25 fps"), "wrong fps in: {info}");
  }

  #[test]
  fn probe_streams_lists_video_and_audio() {
    let dir = TempDir::new("probe");
    let clip = dir.path("clip.mp4");
    make_clip(&clip, true);

    let streams = probe_streams(clip.to_str().unwrap()).unwrap();
    let kinds: Vec<&str> = streams.iter().map(|s| s.kind.as_str()).collect();
    assert_eq!(kinds, ["video", "audio"]);
    let audio = &streams[1];
    assert_eq!(audio.codec, "aac");
    assert_eq!(audio.sample_rate, Some(44100));
    assert_eq!(audio.channels, Some(1));
  }

  #[test]
  fn probe_streams_fails_on_missing_file() {
    let dir = TempDir::new("probe-missing");
    let missing = dir.path("nope.mp4");
    assert!(probe_streams(missing.to_str().unwrap()).is_err());
  }

  #[test]
  fn get_media_seconds_returns_clip_length() {
    let dir = TempDir::new("seconds");
    let clip = dir.path("clip.mp4");
    make_clip(&clip, false);

    let seconds = get_media_seconds(clip.to_str().unwrap()).unwrap();
    assert!(
      (seconds - 1.0).abs() < 0.1,
      "expected about 1s, got {seconds}"
    );
  }

  #[test]
  fn convert_for_merge_writes_mp4_with_aac_audio() {
    let dir = TempDir::new("convert");
    let input = dir.path("input.mp4");
    let output = dir.path("converted.mp4");
    make_clip(&input, true);

    let profile = AudioProfile {
      sample_rate: 48_000,
      channels: 2,
    };
    let result = convert_for_merge(
      input.to_str().unwrap(),
      output.to_str().unwrap(),
      Some(profile),
      0,
      false,
      1.0,
      VideoTarget {
        size: None,
        keep_video_streams: vec![],
      },
    );
    assert!(
      result.status.success(),
      "{}",
      String::from_utf8_lossy(&result.stderr)
    );

    let streams = probe_streams(output.to_str().unwrap()).unwrap();
    let audio = streams.iter().find(|s| s.kind == "audio").unwrap();
    assert_eq!(audio.codec, "aac");
    assert_eq!(audio.sample_rate, Some(48_000));
    assert_eq!(audio.channels, Some(2));
  }

  #[test]
  fn convert_for_merge_scales_and_pads_to_the_target_size() {
    let dir = TempDir::new("scale-target");
    let input = dir.path("input.mp4");
    let output = dir.path("scaled.mp4");
    make_clip(&input, false);

    let result = convert_for_merge(
      input.to_str().unwrap(),
      output.to_str().unwrap(),
      None,
      0,
      false,
      1.0,
      VideoTarget {
        size: Some((160, 240)),
        keep_video_streams: vec![],
      },
    );
    assert!(
      result.status.success(),
      "{}",
      String::from_utf8_lossy(&result.stderr)
    );

    let size = crate::commander::cropper::frame_size(output.to_str().unwrap());
    assert_eq!(size, Some((160, 240)));
  }

  #[test]
  fn video_frame_count_reads_the_frames_of_a_real_clip() {
    let dir = TempDir::new("frames");
    let clip = dir.path("clip.mp4");
    make_clip(&clip, false);

    // `make_clip` makes 1 second at 25 frames per second.
    assert_eq!(video_frame_count(clip.to_str().unwrap()), Some(25));
  }

  #[test]
  fn convert_for_merge_keeps_a_cover_image_as_a_second_video_stream() {
    let dir = TempDir::new("cover");
    let input = dir.path("with-cover.mp4");
    let output = dir.path("converted.mp4");
    // A 1-second video with a single-frame PNG cover as its second video stream.
    let status = Command::new("ffmpeg")
      .args(["-v", "error", "-y", "-f", "lavfi", "-i"])
      .arg("testsrc=d=1:s=160x120:r=25")
      .args(["-f", "lavfi", "-i", "color=c=red:s=64x64:d=1"])
      .args([
        "-map", "0:v", "-map", "1:v", "-c:v:0", "libx264", "-pix_fmt", "yuv420p",
      ])
      .args(["-c:v:1", "png", "-frames:v:1", "1"])
      .arg(&input)
      .status()
      .expect("ffmpeg must be installed");
    assert!(status.success(), "failed to create the cover test clip");

    let profile = AudioProfile {
      sample_rate: 48_000,
      channels: 2,
    };
    let result = convert_for_merge(
      input.to_str().unwrap(),
      output.to_str().unwrap(),
      Some(profile),
      0,
      false,
      1.0,
      VideoTarget {
        size: None,
        keep_video_streams: vec![1],
      },
    );
    assert!(
      result.status.success(),
      "{}",
      String::from_utf8_lossy(&result.stderr)
    );

    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", "png"]);
  }

  #[test]
  fn convert_for_merge_keeps_a_bmp_attached_cover_as_an_attached_picture() {
    let dir = TempDir::new("bmp-cover");
    let input = dir.path("with-bmp-cover.mp4");
    let output = dir.path("converted.mp4");
    // A 1-second video with a single-frame BMP cover, flagged as an attached picture.
    let status = Command::new("ffmpeg")
      .args(["-v", "error", "-y", "-f", "lavfi", "-i"])
      .arg("testsrc=d=1:s=160x120:r=25")
      .args(["-f", "lavfi", "-i", "color=c=red:s=64x64:d=1"])
      .args([
        "-map", "0:v", "-map", "1:v", "-c:v:0", "libx264", "-pix_fmt", "yuv420p",
      ])
      .args([
        "-c:v:1",
        "bmp",
        "-disposition:v:1",
        "attached_pic",
        "-frames:v:1",
        "1",
      ])
      .arg(&input)
      .status()
      .expect("ffmpeg must be installed");
    assert!(status.success(), "failed to create the BMP cover test clip");

    let profile = AudioProfile {
      sample_rate: 48_000,
      channels: 2,
    };
    let result = convert_for_merge(
      input.to_str().unwrap(),
      output.to_str().unwrap(),
      Some(profile),
      0,
      false,
      1.0,
      VideoTarget {
        size: None,
        keep_video_streams: vec![1],
      },
    );
    assert!(
      result.status.success(),
      "{}",
      String::from_utf8_lossy(&result.stderr)
    );

    let streams = probe_streams(output.to_str().unwrap()).unwrap();
    let cover = streams
      .iter()
      .filter(|s| s.kind == "video")
      .nth(1)
      .expect("the BMP cover was not kept");
    assert_eq!(cover.codec, "bmp");
    assert!(
      cover.attached_pic,
      "the BMP cover lost its attached_pic flag"
    );
  }

  /// Creates a 1-second 160x120 video at `fps` frames per second, without audio.
  fn make_clip_with_fps(path: &Path, fps: u32) {
    let status = Command::new("ffmpeg")
      .args(["-v", "error", "-y", "-f", "lavfi", "-i"])
      .arg(format!("testsrc=d=1:s=160x120:r={fps}"))
      .args(["-c:v", "libx264", "-pix_fmt", "yuv420p"])
      .arg(path)
      .status()
      .expect("ffmpeg must be installed");
    assert!(status.success(), "failed to create test clip");
  }

  #[test]
  fn merge_joins_two_clips_into_one_file() {
    let dir = TempDir::new("merge");
    let first = dir.path("1 - first.mp4");
    let second = dir.path("2 - second.mp4");
    make_clip(&first, false);
    make_clip(&second, false);

    // The concat list and the chapter file that `merge` reads.
    let list = dir.path("list.txt");
    std::fs::write(
      &list,
      format!(
        "file '{}'\nfile '{}'\n",
        first.to_str().unwrap(),
        second.to_str().unwrap()
      ),
    )
    .unwrap();
    let chapters = dir.path("chapters.txt");
    std::fs::write(&chapters, ";FFMETADATA1\n").unwrap();
    let output = dir.path("merged.mp4");

    let result = merge(
      list.to_str().unwrap().to_string(),
      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.2,
      "expected about 2s, got {seconds}"
    );
  }

  #[test]
  fn adjust_fps_by_ffmpeg_changes_the_frame_rate() {
    let dir = TempDir::new("fps");
    let input = dir.path("30fps.mp4");
    let output = dir.path("25fps.mp4");
    make_clip_with_fps(&input, 30);

    let written = adjust_fps_by_ffmpeg(input.clone(), &25.0, output.clone());
    assert_eq!(written, output);

    let info = run_ffmpeg_info_command(&output).unwrap();
    let text = String::from_utf8_lossy(&info.stderr);
    assert!(text.contains("25 fps"), "expected 25 fps in: {text}");
  }

  #[test]
  fn convert_for_merge_adds_silence_when_input_has_no_audio() {
    let dir = TempDir::new("silent");
    let input = dir.path("video-only.mp4");
    let output = dir.path("with-silence.mp4");
    make_clip(&input, false);

    let profile = AudioProfile {
      sample_rate: 44_100,
      channels: 1,
    };
    let result = convert_for_merge(
      input.to_str().unwrap(),
      output.to_str().unwrap(),
      Some(profile),
      1,
      false,
      1.0,
      VideoTarget {
        size: None,
        keep_video_streams: vec![],
      },
    );
    assert!(
      result.status.success(),
      "{}",
      String::from_utf8_lossy(&result.stderr)
    );

    let streams = probe_streams(output.to_str().unwrap()).unwrap();
    assert!(
      streams.iter().any(|s| s.kind == "audio"),
      "no silent audio added"
    );
    // The clip is 1 second, so the silence must stop there instead of running on.
    let seconds = get_media_seconds(output.to_str().unwrap()).unwrap();
    assert!(
      (seconds - 1.0).abs() < 0.3,
      "expected about 1s, got {seconds}"
    );
  }
}