#![allow(dead_code)]
use std::path::Path;
#[macro_export]
macro_rules! args {
() => {
Vec::<String>::new()
};
($($arg:expr),+ $(,)?) => {{
let mut v = Vec::new();
$(v.push($arg.to_string());)*
v
}};
}
const CODEC_COPY: &str = "copy";
const CODEC_MP3: &str = "libmp3lame";
const CODEC_H264: &str = "libx264";
const CODEC_AAC: &str = "aac";
const PRESET_ULTRAFAST: &str = "ultrafast";
const TUNE_STILLIMAGE: &str = "stillimage";
const PIX_FMT_YUV420P: &str = "yuv420p";
const PIX_FMT_YUVJ420P: &str = "yuvj420p";
const FORMAT_LAVFI: &str = "lavfi";
const COLOR_FILTER: &str = "color=c=black:s=1280x720:r=1";
const VF_SCALE_EVEN_ONLY: &str = "scale=trunc(iw/2)*2:trunc(ih/2)*2";
const VF_SCALE_EVEN: &str = "scale=trunc(iw/2)*2:trunc(ih/2)*2,setsar=1,format=yuv420p";
const VF_SCALE_SQUARE_TEMPLATE: &str =
"scale={size}:{size}:force_original_aspect_ratio=decrease,format=rgb24";
const ID3V2_VERSION: &str = "3";
const WRITE_ID3V1: bool = true;
const MOVFLAGS_FASTSTART: &str = "+faststart";
const CRF_DEFAULT: u8 = 23;
const THREADS_AUTO: &str = "auto";
const SCALE_AND_PAD_FILTER_TEMPLATE: &str =
"scale={width}:{height}:force_original_aspect_ratio=decrease,pad={width}:{height}:(ow-iw)/2:(oh-ih)/2:black";
const WIDTH: u16 = 1980;
const HEIGHT: u16 = 1080;
const FRAME_RATE: u8 = 30;
#[derive(Debug, Clone)]
pub struct VideoConfig {
pub width: u16,
pub height: u16,
pub framerate: u8,
}
impl Default for VideoConfig {
fn default() -> Self {
Self {
width: WIDTH,
height: HEIGHT,
framerate: FRAME_RATE,
}
}
}
impl VideoConfig {
fn from_options(options: &[VideoOption]) -> Self {
let mut config = Self::default();
for option in options {
option(&mut config);
}
config
}
fn scale_and_pad_filter(&self) -> String {
SCALE_AND_PAD_FILTER_TEMPLATE
.replace("{width}", &self.width.to_string())
.replace("{height}", &self.height.to_string())
}
}
pub type VideoOption = Box<dyn Fn(&mut VideoConfig)>;
#[derive(Debug, Default)]
pub struct FfmpegArgs {
args: Vec<String>,
}
impl FfmpegArgs {
pub fn new() -> Self {
Self::default()
}
pub fn input(self, input_path: &Path) -> Self {
self.option("-i", path(input_path))
}
pub fn input_with_format(self, format: &str, input_path: &Path) -> Self {
self.option("-f", format).input(input_path)
}
pub fn input_with_filter(self, filtergraph: &str) -> Self {
self.option("-i", filtergraph)
}
pub fn output(mut self, output_path: &Path) -> Self {
self.args.push(path(output_path));
self
}
pub fn codec(self, codec: &str) -> Self {
self.option("-c", codec)
}
pub fn video_codec(self, codec: &str) -> Self {
self.option("-c:v", codec)
}
pub fn audio_codec(self, codec: &str) -> Self {
self.option("-c:a", codec)
}
pub fn vf(self, filter: &str) -> Self {
self.option("-vf", filter)
}
pub fn af(self, filter: &str) -> Self {
self.option("-af", filter)
}
pub fn map(self, spec: &str) -> Self {
self.option("-map", spec)
}
pub fn disposition(self, stream_spec: &str, value: &str) -> Self {
self.option(format!("-disposition:{stream_spec}"), value)
}
pub fn audio_bitrate(self, bitrate_k: u32) -> Self {
self.option("-b:a", format!("{bitrate_k}k"))
}
pub fn video_bitrate(self, bitrate_k: u32) -> Self {
self.option("-b:v", format!("{bitrate_k}k"))
}
pub fn crf(self, value: u8) -> Self {
self.option("-crf", value.to_string())
}
pub fn preset(self, preset: &str) -> Self {
self.option("-preset", preset)
}
pub fn tune(self, tune: &str) -> Self {
self.option("-tune", tune)
}
pub fn pix_fmt(self, fmt: &str) -> Self {
self.option("-pix_fmt", fmt)
}
pub fn movflags(self, flags: &str) -> Self {
self.option("-movflags", flags)
}
pub fn id3v2_version(self, version: &str) -> Self {
self.option("-id3v2_version", version)
}
pub fn write_id3v1(self, yes: bool) -> Self {
self.option("-write_id3v1", if yes { "1" } else { "0" })
}
pub fn duration(self, seconds: f64) -> Self {
self.option("-t", seconds.to_string())
}
pub fn shortest(self) -> Self {
self.flag("-shortest")
}
pub fn frames(self, stream_spec: &str, count: u32) -> Self {
self.option(format!("-frames:{stream_spec}"), count.to_string())
}
pub fn loop_input(self, count: u32) -> Self {
self.option("-loop", count.to_string())
}
pub fn framerate(self, fps: u8) -> Self {
self.option("-framerate", fps.to_string())
}
pub fn seek(self, timestamp: &str) -> Self {
self.option("-ss", timestamp)
}
pub fn no_audio(self) -> Self {
self.flag("-an")
}
pub fn no_video(self) -> Self {
self.flag("-vn")
}
pub fn overwrite(self) -> Self {
self.flag("-y")
}
pub fn no_overwrite(self) -> Self {
self.flag("-n")
}
pub fn overwrite_if(self, force: bool) -> Self {
if force {
self.overwrite()
} else {
self.no_overwrite()
}
}
pub fn threads(self, n: &str) -> Self {
self.option("-threads", n)
}
pub fn arg<S: Into<String>>(mut self, arg: S) -> Self {
self.args.push(arg.into());
self
}
pub fn option<K: Into<String>, V: Into<String>>(mut self, key: K, value: V) -> Self {
self.args.extend([key.into(), value.into()]);
self
}
pub fn lavfi_input(self, filtergraph: &str) -> Self {
self.option("-f", FORMAT_LAVFI).option("-i", filtergraph)
}
pub fn build(self) -> Vec<String> {
self.args
}
fn flag(mut self, flag: &str) -> Self {
self.args.push(flag.to_string());
self
}
}
pub fn remux_copy(input: &Path, output: &Path, force: bool) -> Vec<String> {
FfmpegArgs::new()
.input(input)
.codec(CODEC_COPY)
.overwrite_if(force)
.output(output)
.build()
}
pub fn extract_frame(input: &Path, output: &Path, size: u32) -> Vec<String> {
let filter = VF_SCALE_SQUARE_TEMPLATE.replace("{size}", &size.to_string());
FfmpegArgs::new()
.seek("00:00:01")
.input(input)
.frames("v", 1)
.vf(&filter)
.overwrite()
.output(output)
.build()
}
pub fn extract_embedded_cover(input: &Path, output: &Path) -> Vec<String> {
FfmpegArgs::new()
.input(input)
.no_audio()
.video_codec(CODEC_COPY)
.overwrite()
.output(output)
.build()
}
pub fn encode_mp3(
input: &Path,
cover: Option<&Path>,
output: &Path,
bitrate: u32,
force: bool,
) -> Vec<String> {
let builder = FfmpegArgs::new().threads(THREADS_AUTO).input(input);
let builder = add_optional_cover_input(builder, cover);
let builder = builder
.map("0:a:0")
.audio_codec(CODEC_MP3)
.audio_bitrate(bitrate)
.id3v2_version(ID3V2_VERSION)
.write_id3v1(WRITE_ID3V1);
let builder = maybe_attach_cover_stream(builder, cover);
builder.overwrite_if(force).output(output).build()
}
pub fn encode_mp4(
image: Option<&Path>,
audio: &Path,
output: &Path,
bitrate: u32,
force: bool,
) -> Vec<String> {
let builder = match image {
Some(image) => FfmpegArgs::new()
.loop_input(1)
.input(image)
.vf(VF_SCALE_EVEN),
None => FfmpegArgs::new().lavfi_input(COLOR_FILTER),
};
builder
.input(audio)
.video_codec(CODEC_H264)
.preset(PRESET_ULTRAFAST)
.tune(TUNE_STILLIMAGE)
.pix_fmt(PIX_FMT_YUV420P)
.audio_codec(CODEC_AAC)
.audio_bitrate(bitrate)
.shortest()
.movflags(MOVFLAGS_FASTSTART)
.overwrite_if(force)
.output(output)
.build()
}
pub fn image_to_jpg(input: &Path, output: &Path) -> Vec<String> {
FfmpegArgs::new()
.input(input)
.vf(VF_SCALE_EVEN_ONLY)
.pix_fmt(PIX_FMT_YUVJ420P)
.overwrite()
.output(output)
.build()
}
pub fn strip_thumbnail_args(input: &Path, output: &Path) -> Vec<String> {
FfmpegArgs::new()
.input(input)
.map("0:v")
.map("0:a")
.codec(CODEC_COPY)
.overwrite()
.output(output)
.build()
}
pub fn encode_loop_args(image: &Path, media: &Path, output: &Path) -> Vec<String> {
FfmpegArgs::new()
.loop_input(1)
.input(image)
.input(media)
.video_codec(CODEC_H264)
.preset(PRESET_ULTRAFAST)
.crf(CRF_DEFAULT)
.audio_codec(CODEC_COPY)
.shortest()
.overwrite()
.output(output)
.build()
}
pub fn attach_thumbnail_args(video: &Path, image: &Path, output: &Path) -> Vec<String> {
FfmpegArgs::new()
.input(video)
.input(image)
.map("0:v")
.map("0:a?")
.map("1")
.codec(CODEC_COPY)
.disposition("v:1", "attached_pic")
.overwrite()
.output(output)
.build()
}
pub fn replace_video_with_image(
image: &Path,
video: &Path,
output: &Path,
options: &[VideoOption],
) -> Vec<String> {
let config = VideoConfig::from_options(options);
let scale_filter = config.scale_and_pad_filter();
FfmpegArgs::new()
.loop_input(1)
.framerate(config.framerate)
.input(image)
.input(video)
.map("0:v")
.map("1:a")
.vf(&scale_filter)
.video_codec(CODEC_H264)
.preset(PRESET_ULTRAFAST)
.tune(TUNE_STILLIMAGE)
.pix_fmt(PIX_FMT_YUV420P)
.audio_codec(CODEC_COPY)
.movflags(MOVFLAGS_FASTSTART)
.shortest()
.overwrite()
.output(output)
.build()
}
pub fn with_width(w: u16) -> VideoOption {
Box::new(move |cfg| cfg.width = w)
}
pub fn with_height(h: u16) -> VideoOption {
Box::new(move |cfg| cfg.height = h)
}
pub fn with_framerate(f: u8) -> VideoOption {
Box::new(move |cfg| cfg.framerate = f)
}
fn add_optional_cover_input(builder: FfmpegArgs, cover: Option<&Path>) -> FfmpegArgs {
match cover {
Some(cover) => builder.input(cover),
None => builder,
}
}
fn maybe_attach_cover_stream(builder: FfmpegArgs, cover: Option<&Path>) -> FfmpegArgs {
match cover {
Some(_) => builder
.map("1:v:0")
.video_codec(CODEC_COPY)
.disposition("v:0", "attached_pic"),
None => builder,
}
}
fn path(path: &Path) -> String {
path.to_string_lossy().into_owned()
}
#[deprecated(since = "0.1.6", note = "use FfmpegArgs::overwrite_if")]
fn overwrite(force: bool) -> Vec<String> {
args![if force { "-y" } else { "-n" }]
}
#[cfg(test)]
mod tests {
use super::*;
use std::path::Path;
#[test]
fn remux_uses_copy() {
assert_eq!(
remux_copy(Path::new("a.ts"), Path::new("out/a.mp4"), false),
vec!["-i", "a.ts", "-c", CODEC_COPY, "-n", "out/a.mp4"]
);
}
#[test]
fn mp3_with_cover_maps_picture() {
let args = encode_mp3(
Path::new("a.mkv"),
Some(Path::new("c.jpg")),
Path::new("a.mp3"),
320,
true,
);
assert!(args
.windows(2)
.any(|window| { window[0] == "-disposition:v:0" && window[1] == "attached_pic" }));
}
#[test]
fn builder_works() {
let args = FfmpegArgs::new()
.input(Path::new("in.mp4"))
.codec("copy")
.output(Path::new("out.mp4"))
.build();
assert_eq!(args, vec!["-i", "in.mp4", "-c", "copy", "out.mp4"]);
}
}