use crate::commander::_cmd::{
describe, get_media_seconds, h264_encoder, hevc_encoder, is_hevc, keep_source_bit_rate,
probe_streams, run_with_frame_progress, run_with_progress, video_frame_count, PROGRESS_ARGS,
};
use crate::helper::io_helper::verbose;
use crate::helper::str_helper::blue;
use crate::helper::str_helper::gen_input_file_content_for_ffmpeg;
use std::{fs, path::Path, process::Command};
pub fn crop_black_bars(
files: &[String],
tmp_dir: &Path,
) -> Option<(Vec<String>, String, Vec<bool>)> {
let detected: Vec<Option<(String, f64)>> =
files.iter().map(|file| detect_black_bars(file)).collect();
if detected.iter().all(Option::is_none) {
return None;
}
let crops: Vec<Option<(String, f64)>> = detected;
let dir = tmp_dir.join("cropper");
fs::create_dir_all(&dir).expect("Failed to create the cropper folder");
let outputs: Vec<(String, bool)> = files
.iter()
.zip(crops)
.map(|(file, detected)| {
let Some((crop, duration)) = detected else {
return (file.clone(), false);
};
let file_name = Path::new(file).file_name().unwrap().to_string_lossy();
let output = dir.join(file_name.as_ref()).to_string_lossy().to_string();
println!("✂️ Removing black bars from {file}, calling: crop={crop}");
println!("💾 Will create: {}", blue(&output));
let res = crop_with_cpu_fallback(file, &crop, &output, duration);
if !res.status.success() {
panic!(
"❌ Cropping {} failed (exit code: {:?}):{}",
file,
res.status.code(),
String::from_utf8_lossy(&res.stderr)
);
}
println!("🔪 Cropped: {}", blue(&output));
(output, true)
})
.collect();
let cropped: Vec<bool> = outputs
.iter()
.map(|(_, was_cropped)| *was_cropped)
.collect();
let inputs: Vec<String> = outputs.into_iter().map(|(path, _)| path).collect();
let content = gen_input_file_content_for_ffmpeg(&inputs);
Some((inputs, content, cropped))
}
fn detect_black_bars(file: &str) -> Option<(String, f64)> {
let streams = probe_streams(file).ok()?;
if !streams.iter().any(|stream| stream.kind == "video") {
return None;
}
let (width, height) = frame_size(file)?;
let duration = get_media_seconds(file).ok()?;
let quick: Vec<Vec<String>> = seek_times_for(duration, PRE_CHECK_POINTS)
.into_iter()
.map(|time| sample_crops(file, &[time]))
.collect::<Option<_>>()?;
if quick_check_is_clean(&quick, width, height) {
return None;
}
let crops = sample_crops(file, &seek_times(duration))?;
let crop = majority_crop(&crops)?;
if is_full_frame(&crop, width, height) {
None
} else {
Some((crop, duration))
}
}
fn all_full_frame(crops: &[String], width: u32, height: u32) -> bool {
!crops.is_empty() && crops.iter().all(|crop| is_full_frame(crop, width, height))
}
fn quick_check_is_clean(seeks: &[Vec<String>], width: u32, height: u32) -> bool {
!seeks.is_empty()
&& seeks
.iter()
.all(|readings| all_full_frame(readings, width, height))
}
fn is_full_frame(crop: &str, width: u32, height: u32) -> bool {
let parts: Vec<i64> = crop.split(':').filter_map(|p| p.parse().ok()).collect();
if parts.len() != 4 {
return false;
}
let (w, h, x, y) = (parts[0], parts[1], parts[2], parts[3]);
let (width, height) = (i64::from(width), i64::from(height));
(width - w) <= 1 && (height - h) <= 1 && x <= 1 && y <= 1
}
pub fn frame_size(file: &str) -> Option<(u32, u32)> {
let output = Command::new("ffprobe")
.args([
"-v",
"error",
"-select_streams",
"v:0",
"-show_entries",
"stream=width,height:stream_side_data=rotation",
"-of",
"csv=p=0",
file,
])
.output()
.ok()?;
parse_frame_size(&String::from_utf8_lossy(&output.stdout))
}
fn parse_frame_size(text: &str) -> Option<(u32, u32)> {
let mut fields = text.trim().split(',').filter(|field| !field.is_empty());
let width: u32 = fields.next()?.parse().ok()?;
let height: u32 = fields.next()?.parse().ok()?;
let quarter_turn = fields
.next()
.and_then(|angle| angle.parse::<f64>().ok())
.is_some_and(|angle| (angle.abs() % 180.0 - 90.0).abs() < 1.0);
Some(if quarter_turn {
(height, width)
} else {
(width, height)
})
}
const SAMPLES_PER_CLIP: f64 = 66.0;
const FRAMES_PER_SEEK: u32 = 2;
fn sample_crops(file: &str, times: &[f64]) -> Option<Vec<String>> {
let mut crops = Vec::new();
for time in times {
let output = Command::new("ffmpeg")
.args(["-v", "info", "-ss", &format!("{time:.3}"), "-i", file])
.args(["-frames:v", &FRAMES_PER_SEEK.to_string()])
.args(["-vf", "cropdetect=round=2:skip=0", "-an", "-f", "null", "-"])
.output()
.ok()?;
crops.extend(parse_crop_values(&String::from_utf8_lossy(&output.stderr)));
}
Some(crops)
}
const PRE_CHECK_POINTS: u32 = 5;
fn seek_times(duration_seconds: f64) -> Vec<f64> {
seek_times_for(duration_seconds, SAMPLES_PER_CLIP as u32)
}
fn seek_times_for(duration_seconds: f64, points: u32) -> Vec<f64> {
(0..points)
.map(|index| duration_seconds * (f64::from(index) + 0.5) / f64::from(points))
.collect()
}
fn is_valid_crop(value: &str) -> bool {
let parts: Vec<i64> = value.split(':').filter_map(|p| p.parse().ok()).collect();
parts.len() == 4 && parts[0] > 0 && parts[1] > 0 && parts[2] >= 0 && parts[3] >= 0
}
fn parse_crop_values(log: &str) -> Vec<String> {
log
.split("crop=")
.skip(1)
.filter_map(|rest| rest.split_whitespace().next())
.filter(|value| is_valid_crop(value))
.map(String::from)
.collect()
}
const MIN_AGREEING_SHARE: f64 = 0.5;
fn majority_crop(values: &[String]) -> Option<String> {
if values.is_empty() {
return None;
}
let mut counts: std::collections::BTreeMap<&str, usize> = std::collections::BTreeMap::new();
for value in values {
*counts.entry(value.as_str()).or_default() += 1;
}
let top_count = counts.values().copied().max()?;
let mut leaders = counts.iter().filter(|(_, count)| **count == top_count);
let (crop, count) = leaders.next()?;
if leaders.next().is_some() {
return None;
}
let share = *count as f64 / values.len() as f64;
(share >= MIN_AGREEING_SHARE).then(|| crop.to_string())
}
fn crop_with_cpu_fallback(
input: &str,
crop: &str,
output: &str,
duration_seconds: f64,
) -> std::process::Output {
let total_frames = video_frame_count(input);
let run = |encoder_override: Option<&str>| {
let mut args = encode_args(input, crop, output, encoder_override, duration_seconds);
let output_arg = args
.pop()
.expect("encode_args always ends with the output path");
let shown: Vec<&str> = args
.iter()
.map(String::as_str)
.chain([output_arg.as_str()])
.collect();
println!("🔪 Cropping, calling: {}", blue(describe("ffmpeg", &shown)));
if !verbose() {
args.extend(PROGRESS_ARGS.map(String::from));
}
args.push(output_arg);
let refs: Vec<&str> = args.iter().map(String::as_str).collect();
if verbose() {
Command::new("ffmpeg").args(&refs).output().unwrap()
} else {
match total_frames {
Some(frames) => run_with_frame_progress(&refs, "Removing black bars", frames),
None => run_with_progress(&refs, "Removing black bars", duration_seconds),
}
}
};
let res = run(None);
if res.status.success() {
return res;
}
let cpu_encoder = if is_hevc(input) { "libx265" } else { "libx264" };
println!("⚠️ Cropping with the default encoder failed, retrying with {cpu_encoder}");
run(Some(cpu_encoder))
}
fn encode_args(
input: &str,
crop: &str,
output: &str,
encoder_override: Option<&str>,
duration_seconds: f64,
) -> Vec<String> {
let mut args: Vec<String> = ["-y", "-v", "error"].map(String::from).to_vec();
if cfg!(target_os = "macos") && encoder_override.is_none() {
args.extend(["-hwaccel", "videotoolbox"].map(String::from));
}
let encoder = encoder_override.or_else(|| video_encoder_for(output));
let keeps_cover = encoder.is_some();
args.extend(["-i", input, "-map", "0:v:0", "-map", "0:a?", "-map", "0:s?"].map(String::from));
if keeps_cover {
args.extend(["-map", "0:v:1?"].map(String::from));
}
args.extend(["-c:s", "copy", "-filter:v:0"].map(String::from));
args.push(format!("crop={crop}"));
if let Some(encoder) = encoder {
let encoder = if encoder_override.is_none() && is_hevc(input) {
hevc_encoder()
} else {
encoder
};
args.extend(["-c:v:0".to_string(), encoder.to_string()]);
if encoder.starts_with("hevc") || encoder == "libx265" {
args.extend(["-tag:v:0", "hvc1"].map(String::from));
}
if let Some(bit_rate) = keep_source_bit_rate(input, duration_seconds) {
args.extend(["-b:v:0".to_string(), bit_rate.to_string()]);
}
if keeps_cover {
args.extend(["-c:v:1", "copy"].map(String::from));
}
}
args.push(output.to_string());
args
}
fn video_encoder_for(output: &str) -> Option<&'static str> {
let extension = Path::new(output)
.extension()?
.to_str()?
.to_ascii_lowercase();
matches!(extension.as_str(), "mp4" | "m4v" | "mov" | "mkv").then(h264_encoder)
}
#[cfg(test)]
mod test_all_full_frame {
use super::all_full_frame;
#[test]
fn empty_readings_do_not_count_as_no_bars() {
assert!(!all_full_frame(&[], 320, 240));
}
#[test]
fn every_full_frame_reading_skips_the_file() {
let readings = vec!["320:240:0:0".to_string(); 5];
assert!(all_full_frame(&readings, 320, 240));
}
#[test]
fn one_bar_reading_keeps_the_file_for_the_full_check() {
let readings = vec!["320:240:0:0".to_string(), "320:180:0:30".to_string()];
assert!(!all_full_frame(&readings, 320, 240));
}
}
#[cfg(test)]
mod test_quick_check_is_clean {
use super::quick_check_is_clean;
#[test]
fn a_seek_without_readings_keeps_the_file_for_the_full_check() {
let seeks = vec![vec!["320:240:0:0".to_string()], vec![]];
assert!(!quick_check_is_clean(&seeks, 320, 240));
}
#[test]
fn every_seek_full_frame_skips_the_file() {
let seeks = vec![
vec!["320:240:0:0".to_string()],
vec!["320:240:0:0".to_string()],
];
assert!(quick_check_is_clean(&seeks, 320, 240));
}
}
#[cfg(test)]
mod test_is_full_frame {
use super::is_full_frame;
#[test]
fn rounding_to_even_size_is_full_frame() {
assert!(is_full_frame("320:180:0:0", 321, 181));
}
#[test]
fn exact_full_frame_is_full_frame() {
assert!(is_full_frame("320:240:0:0", 320, 240));
}
#[test]
fn real_bars_are_not_full_frame() {
assert!(!is_full_frame("320:180:0:30", 320, 240));
}
#[test]
fn garbage_is_not_full_frame() {
assert!(!is_full_frame("not-a-crop", 320, 240));
}
}
#[cfg(test)]
mod test_frame_size_fields {
use super::parse_frame_size;
#[test]
fn reads_plain_size() {
assert_eq!(parse_frame_size("320,240\n"), Some((320, 240)));
}
#[test]
fn reads_size_with_trailing_comma_from_rotation() {
assert_eq!(parse_frame_size("320,180,\n"), Some((320, 180)));
}
#[test]
fn swaps_size_for_a_quarter_turn() {
assert_eq!(parse_frame_size("320,180,-90\n"), Some((180, 320)));
assert_eq!(parse_frame_size("320,180,90\n"), Some((180, 320)));
}
#[test]
fn keeps_size_for_a_half_turn() {
assert_eq!(parse_frame_size("320,180,180\n"), Some((320, 180)));
}
}
#[cfg(test)]
mod test_parse_crop_values {
use super::{is_valid_crop, parse_crop_values, seek_times};
#[test]
fn ignores_negative_sizes_from_black_frames() {
let log = "crop=-318:-238:320:240 pts:0\ncrop=320:180:0:30 pts:1";
assert_eq!(parse_crop_values(log), vec!["320:180:0:30"]);
}
#[test]
fn valid_crop_needs_positive_width_and_height() {
assert!(is_valid_crop("320:180:0:30"));
assert!(!is_valid_crop("-318:-238:320:240"));
assert!(!is_valid_crop("0:180:0:0"));
}
#[test]
fn seek_times_are_spread_across_the_whole_clip() {
let times = seek_times(100.0);
assert_eq!(times.len(), 66);
assert!(
times.first().unwrap() < &1.0,
"first sample is near the start"
);
assert!(times.last().unwrap() > &99.0, "last sample is near the end");
}
#[test]
fn seek_times_stay_inside_the_clip() {
assert!(seek_times(8552.32).iter().all(|t| *t > 0.0 && *t < 8552.32));
}
#[test]
fn reads_every_crop_line() {
let log = "[Parsed_cropdetect_1 @ 0x1] x1:0 x2:1919 y1:0 y2:695 w:1920 h:696 x:0 y:0 pts:0 t:0.0 crop=1920:696:0:0\n\
[Parsed_cropdetect_1 @ 0x1] crop=1920:688:0:16 pts:1 t:1.0";
assert_eq!(
parse_crop_values(log),
vec!["1920:696:0:0", "1920:688:0:16"]
);
}
#[test]
fn ignores_log_without_crop() {
assert!(parse_crop_values("frame= 10 fps=0.0 size=N/A").is_empty());
}
}
#[cfg(test)]
mod test_majority_crop {
use super::majority_crop;
#[test]
fn returns_the_crop_when_every_frame_agrees() {
let values: Vec<String> = ["320:180:0:30", "320:180:0:30"].map(String::from).to_vec();
assert_eq!(majority_crop(&values), Some("320:180:0:30".to_string()));
}
#[test]
fn letterboxed_film_with_a_few_full_frame_scenes_is_cropped() {
let mut values: Vec<String> = vec!["3840:1608:0:276".to_string(); 9];
values.push("3840:2160:0:0".to_string());
assert_eq!(majority_crop(&values), Some("3840:1608:0:276".to_string()));
}
#[test]
fn a_letterboxed_film_with_many_offset_frames_is_still_cropped() {
let mut values: Vec<String> = vec!["3840:1608:0:276".to_string(); 136];
values.extend(vec!["3828:1608:12:276".to_string(); 62]);
assert_eq!(majority_crop(&values), Some("3840:1608:0:276".to_string()));
}
#[test]
fn a_film_with_bars_in_only_58_percent_of_readings_is_cropped() {
let mut values: Vec<String> = vec!["3840:1608:0:276".to_string(); 114];
values.extend(vec!["3418:1608:0:276".to_string(); 84]);
assert_eq!(majority_crop(&values), Some("3840:1608:0:276".to_string()));
}
#[test]
fn an_exact_tie_between_two_crops_is_not_cropped() {
let mut values: Vec<String> = vec!["3840:1608:0:276".to_string(); 50];
values.extend(vec!["3418:1608:0:276".to_string(); 50]);
assert_eq!(majority_crop(&values), None);
}
#[test]
fn an_even_three_way_mix_is_not_cropped() {
let values: Vec<String> = ["320:180:0:30", "320:240:0:0", "300:180:10:30"]
.map(String::from)
.to_vec();
assert_eq!(majority_crop(&values), None);
}
#[test]
fn returns_none_for_no_values() {
assert_eq!(majority_crop(&[]), None);
}
}
#[cfg(test)]
mod test_encode_args {
use super::{encode_args, video_encoder_for};
#[test]
fn decodes_with_videotoolbox_only_on_macos() {
let args = encode_args("in.mp4", "1920:688:0:16", "out.mp4", None, 1.0);
let has_flag = args
.windows(2)
.any(|pair| pair == ["-hwaccel", "videotoolbox"]);
assert_eq!(has_flag, cfg!(target_os = "macos"));
}
#[test]
fn cpu_retry_does_not_decode_with_videotoolbox() {
let args = encode_args("in.mp4", "1920:688:0:16", "out.mp4", Some("libx264"), 1.0);
assert!(!args
.windows(2)
.any(|pair| pair == ["-hwaccel", "videotoolbox"]));
}
#[test]
fn keeps_extension_without_h264_for_webm() {
assert_eq!(video_encoder_for("clip.webm"), None);
}
#[test]
fn crops_and_keeps_video_audio_and_subtitles() {
let args = encode_args("in.webm", "1920:688:0:16", "out.webm", None, 1.0);
assert!(args
.windows(2)
.any(|pair| pair == ["-filter:v:0", "crop=1920:688:0:16"]));
assert!(args.windows(2).any(|pair| pair == ["-map", "0:v:0"]));
assert!(args.windows(2).any(|pair| pair == ["-map", "0:s?"]));
assert!(args.windows(2).any(|pair| pair == ["-c:s", "copy"]));
assert!(!args.contains(&"-c:v:0".to_string()));
}
#[test]
fn keeps_a_cover_image_as_a_copied_second_video_stream() {
let args = encode_args("in.mp4", "1920:688:0:16", "out.mp4", None, 1.0);
assert!(args.windows(2).any(|pair| pair == ["-map", "0:v:1?"]));
assert!(args.windows(2).any(|pair| pair == ["-c:v:1", "copy"]));
}
#[test]
fn drops_the_cover_image_for_webm_output() {
let args = encode_args("in.webm", "1920:688:0:16", "out.webm", None, 1.0);
assert!(!args.contains(&"0:v:1?".to_string()));
}
}
#[cfg(test)]
mod test_cropper_integration {
use super::{crop_black_bars, detect_black_bars, frame_size, sample_crops};
use std::path::PathBuf;
use std::process::Command;
struct Clip(PathBuf);
impl Clip {
fn new(name: &str, bars: bool) -> Self {
let path =
std::env::temp_dir().join(format!("vidmerger-crop-{name}-{}.mp4", std::process::id()));
let mut cmd = Command::new("ffmpeg");
cmd.args(["-v", "error", "-y", "-f", "lavfi", "-i"]);
if bars {
cmd.arg("color=c=white:s=320x180:d=2:r=25");
cmd.args(["-vf", "pad=320:240:0:30:black"]);
} else {
cmd.arg("color=c=white:s=320x240:d=2:r=25");
}
let status = cmd
.args(["-c:v", "libx264", "-pix_fmt", "yuv420p", "-an"])
.arg(&path)
.status()
.expect("ffmpeg must be installed");
assert!(status.success(), "failed to create test clip");
Clip(path)
}
fn path(&self) -> &str {
self.0.to_str().unwrap()
}
}
impl Drop for Clip {
fn drop(&mut self) {
let _ = std::fs::remove_file(&self.0);
}
}
#[test]
fn sample_crops_reads_the_bars_from_a_real_clip() {
let clip = Clip::new("sample-bars", true);
let crops = sample_crops(clip.path(), &[0.5, 1.0]).expect("ffmpeg must run");
assert!(!crops.is_empty(), "expected crop readings from the clip");
assert!(crops.iter().all(|crop| crop == "320:180:0:30"), "{crops:?}");
}
#[test]
fn sample_crops_reads_only_full_frames_from_a_clean_clip() {
let clip = Clip::new("sample-clean", false);
let crops = sample_crops(clip.path(), &[0.5, 1.0]).expect("ffmpeg must run");
assert!(!crops.is_empty(), "expected crop readings from the clip");
assert!(crops.iter().all(|crop| crop == "320:240:0:0"), "{crops:?}");
}
#[test]
fn frame_size_reads_the_real_clip_size() {
let clip = Clip::new("size", false);
assert_eq!(frame_size(clip.path()), Some((320, 240)));
}
#[test]
fn detect_black_bars_finds_the_bars_on_a_real_clip() {
let clip = Clip::new("bars", true);
let (crop, duration) = detect_black_bars(clip.path()).expect("bars should be found");
assert_eq!(crop, "320:180:0:30");
assert!((duration - 2.0).abs() < 0.5, "duration was {duration}");
}
#[test]
fn detect_black_bars_returns_none_for_a_full_frame_clip() {
let clip = Clip::new("full", false);
assert_eq!(detect_black_bars(clip.path()), None);
}
#[test]
fn crop_black_bars_writes_cropped_file_and_returns_new_paths() {
let barred = Clip::new("crop-barred", true);
let full = Clip::new("crop-full", false);
let tmp = TempFolder::new("crop-run");
let files = vec![barred.path().to_string(), full.path().to_string()];
let (new_files, content, cropped) =
crop_black_bars(&files, &tmp.0).expect("bars should be found");
assert_eq!(cropped, vec![true, false]);
assert!(
new_files[0].contains("cropper"),
"not cropped: {}",
new_files[0]
);
assert_eq!(new_files[1], files[1]);
assert!(std::path::Path::new(&new_files[0]).exists());
assert!(content.contains("file '"), "no concat list: {content}");
}
#[test]
fn crop_black_bars_keeps_a_hevc_input_as_hevc() {
let path = std::env::temp_dir().join(format!("vidmerger-crop-hevc-{}.mp4", std::process::id()));
let clip = Clip(path);
let status = Command::new("ffmpeg")
.args(["-v", "error", "-y", "-f", "lavfi", "-i"])
.arg("color=c=white:s=320x180:d=2:r=25")
.args([
"-vf",
"pad=320:240:0:30:black",
"-c:v",
"libx265",
"-tag:v",
"hvc1",
])
.args(["-pix_fmt", "yuv420p", "-an"])
.arg(clip.path())
.status()
.expect("ffmpeg must be installed");
assert!(status.success(), "failed to create HEVC test clip");
let tmp = TempFolder::new("crop-hevc");
let files = vec![clip.path().to_string()];
let (new_files, _, _) = crop_black_bars(&files, &tmp.0).expect("bars should be found");
let probe = Command::new("ffprobe")
.args(["-v", "error", "-select_streams", "v:0"])
.args(["-show_entries", "stream=codec_name", "-of", "csv=p=0"])
.arg(&new_files[0])
.output()
.expect("ffprobe must be installed");
assert_eq!(String::from_utf8_lossy(&probe.stdout).trim(), "hevc");
}
struct TempFolder(PathBuf);
impl TempFolder {
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();
TempFolder(dir)
}
}
impl Drop for TempFolder {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
}