use crate::commander::_cmd::{self, AudioProfile, MediaStream, VideoTarget};
use crate::commander::cropper;
use crate::helper::str_helper::blue;
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;
#[derive(Debug, PartialEq, Eq)]
enum InputAction {
Copy,
Convert { silent_audio: bool },
}
#[derive(Debug, PartialEq, Eq)]
struct MergePlan {
profile: Option<AudioProfile>,
hevc: bool,
actions: Vec<InputAction>,
video_size: Vec<Option<(u32, u32)>>,
keep_video_streams: Vec<usize>,
attached_covers: Vec<usize>,
audio_tracks: Vec<usize>,
target_audio_tracks: usize,
}
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?,
})
}
fn copyable_audio_codec(file_format: &str) -> &'static str {
if file_format == "mp3" {
"mp3"
} else {
"aac"
}
}
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)
}
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,
}
}
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()
}
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);
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()));
let secondary: Vec<Vec<(String, bool)>> = probes.iter().map(|s| secondary_video(s)).collect();
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()
};
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();
let attached_covers: Vec<usize> = kept
.iter()
.enumerate()
.filter(|(_, (_, attached))| *attached)
.map(|(output_position, _)| output_position + 1)
.collect();
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
})
};
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));
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");
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);
let size_differs = target_size.is_some() && size.is_some() && *size != target_size;
let silent_audio =
profile.is_some() && *own_audio_tracks < target_audio_tracks && (has_video || has_audio);
(
has_extra
|| !audio_fits
|| layout_differs
|| size_differs
|| silent_audio
|| (!own_secondary.is_empty() && !keeps_all_secondary),
silent_audio,
)
})
.collect();
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();
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,
}
}
pub fn merge(
input: String,
output: String,
files_to_merge_as_strings: Vec<String>,
cropped: Vec<bool>,
file_format: &str,
tmp_dir: PathBuf,
) {
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();
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();
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: {}", blue(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");
let output_str = output.clone();
let chapters = file_path.to_string_lossy().to_string();
let sizes: Vec<Option<(u32, u32)>> = files_to_merge_as_strings
.iter()
.map(|path| cropper::frame_size(path))
.collect();
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,
);
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: {}", blue(&output_str));
} else {
panic!(
"❌ Something went wrong (exit code: {:?}):{}",
res.status.code(),
String::from_utf8_lossy(&res.stderr)
);
}
}
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()
}
fn is_unsupported_stream_error(stderr: &[u8]) -> bool {
String::from_utf8_lossy(stderr).contains("unsupported type")
}
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);
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,
)
}
fn is_hevc_file(path: &str) -> bool {
_cmd::is_hevc(path)
}
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,
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()
}
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(); 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};
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,
}
}
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() {
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() {
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() {
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() {
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() {
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() {
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() {
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() {
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() {
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() {
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() {
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() {
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() {
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() {
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() {
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() {
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()],
];
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"), "");
}
#[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");
}
}
#[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;
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);
}
}
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}"
);
}
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() {
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)
);
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}"
);
}
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,
};
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:?}");
}
}