capture, encode, export wiring
This commit is contained in:
+225
-1
@@ -1 +1,225 @@
|
||||
// ffmpeg invocation, target-size encoding logic, codec selection
|
||||
use std::ffi::{OsStr, OsString};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
|
||||
use anyhow::{anyhow, bail, Context, Result};
|
||||
|
||||
use crate::config::{Format, GifDither, Mp4Codec, WebmCodec};
|
||||
|
||||
const AUDIO_BITRATE_KBPS: u64 = 128;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct TranscodeRequest {
|
||||
pub input: PathBuf,
|
||||
pub output: PathBuf,
|
||||
pub format: Format,
|
||||
pub target_bytes: u64,
|
||||
pub duration_secs: f64,
|
||||
pub fps: u32,
|
||||
pub keep_audio: bool,
|
||||
pub gif_dither: GifDither,
|
||||
pub webm_codec: WebmCodec,
|
||||
pub mp4_codec: Mp4Codec,
|
||||
pub scratch_dir: PathBuf,
|
||||
}
|
||||
|
||||
pub fn transcode(ffmpeg: &Path, req: &TranscodeRequest) -> Result<()> {
|
||||
if req.duration_secs <= 0.01 {
|
||||
bail!("clip duration is essentially zero - nothing to encode");
|
||||
}
|
||||
std::fs::create_dir_all(&req.scratch_dir).context("creating scratch dir")?;
|
||||
if let Some(parent) = req.output.parent() {
|
||||
std::fs::create_dir_all(parent).context("creating output dir")?;
|
||||
}
|
||||
|
||||
match req.format {
|
||||
Format::Mp4 => two_pass_video(ffmpeg, req, mp4_video_codec(req.mp4_codec), "aac", "mp4"),
|
||||
Format::Webm => two_pass_video(
|
||||
ffmpeg,
|
||||
req,
|
||||
webm_video_codec(req.webm_codec),
|
||||
"libopus",
|
||||
"webm",
|
||||
),
|
||||
Format::Gif => encode_gif(ffmpeg, req),
|
||||
}
|
||||
}
|
||||
|
||||
fn mp4_video_codec(c: Mp4Codec) -> &'static str {
|
||||
match c {
|
||||
Mp4Codec::H264 => "libx264",
|
||||
Mp4Codec::H265 => "libx265",
|
||||
}
|
||||
}
|
||||
|
||||
fn webm_video_codec(c: WebmCodec) -> &'static str {
|
||||
match c {
|
||||
WebmCodec::Vp9 => "libvpx-vp9",
|
||||
WebmCodec::Av1 => "libsvtav1",
|
||||
}
|
||||
}
|
||||
|
||||
fn video_bitrate_kbps(req: &TranscodeRequest) -> Result<u64> {
|
||||
let target_bits = req.target_bytes.saturating_mul(8) as f64;
|
||||
let audio_bits = if req.keep_audio {
|
||||
AUDIO_BITRATE_KBPS as f64 * 1000.0 * req.duration_secs
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
let video_bits = target_bits - audio_bits;
|
||||
if video_bits <= 0.0 {
|
||||
bail!("target size too small to fit audio at {AUDIO_BITRATE_KBPS}k - increase target or strip audio");
|
||||
}
|
||||
let kbps = (video_bits / 1000.0 / req.duration_secs).round() as u64;
|
||||
Ok(kbps.max(16))
|
||||
}
|
||||
|
||||
fn two_pass_video(
|
||||
ffmpeg: &Path,
|
||||
req: &TranscodeRequest,
|
||||
video_codec: &str,
|
||||
audio_codec: &str,
|
||||
container: &str,
|
||||
) -> Result<()> {
|
||||
let bitrate_kbps = video_bitrate_kbps(req)?;
|
||||
let bitrate = format!("{bitrate_kbps}k");
|
||||
|
||||
let log_stem = req.scratch_dir.join(format!("ffmpeg2pass-{container}"));
|
||||
let log_stem_str = log_stem
|
||||
.to_str()
|
||||
.ok_or_else(|| anyhow!("scratch dir contains non-UTF8"))?;
|
||||
let null_target = if cfg!(windows) { "NUL" } else { "/dev/null" };
|
||||
|
||||
let mut pass1 = Command::new(ffmpeg);
|
||||
pass1
|
||||
.arg("-y")
|
||||
.arg("-hide_banner")
|
||||
.arg("-i")
|
||||
.arg(&req.input)
|
||||
.args(["-c:v", video_codec])
|
||||
.args(["-b:v", &bitrate])
|
||||
.args(["-pass", "1"])
|
||||
.args(["-passlogfile", log_stem_str])
|
||||
.arg("-an")
|
||||
.args(["-f", container])
|
||||
.arg(null_target);
|
||||
run(&mut pass1, "pass 1")?;
|
||||
|
||||
let mut pass2 = Command::new(ffmpeg);
|
||||
pass2
|
||||
.arg("-y")
|
||||
.arg("-hide_banner")
|
||||
.arg("-i")
|
||||
.arg(&req.input)
|
||||
.args(["-c:v", video_codec])
|
||||
.args(["-b:v", &bitrate])
|
||||
.args(["-pass", "2"])
|
||||
.args(["-passlogfile", log_stem_str]);
|
||||
if req.keep_audio {
|
||||
pass2
|
||||
.args(["-c:a", audio_codec])
|
||||
.args(["-b:a", &format!("{AUDIO_BITRATE_KBPS}k")]);
|
||||
} else {
|
||||
pass2.arg("-an");
|
||||
}
|
||||
pass2.arg(&req.output);
|
||||
run(&mut pass2, "pass 2")?;
|
||||
|
||||
cleanup_pass_logs(&log_stem);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn cleanup_pass_logs(stem: &Path) {
|
||||
let parent = match stem.parent() {
|
||||
Some(p) => p,
|
||||
None => return,
|
||||
};
|
||||
let prefix = stem.file_name().and_then(OsStr::to_str).unwrap_or("");
|
||||
if prefix.is_empty() {
|
||||
return;
|
||||
}
|
||||
if let Ok(entries) = std::fs::read_dir(parent) {
|
||||
for entry in entries.flatten() {
|
||||
let name = entry.file_name();
|
||||
if let Some(name_str) = name.to_str() {
|
||||
if name_str.starts_with(prefix) {
|
||||
let _ = std::fs::remove_file(entry.path());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn encode_gif(ffmpeg: &Path, req: &TranscodeRequest) -> Result<()> {
|
||||
let palette_path = req.scratch_dir.join("palette.png");
|
||||
let scale_width = estimate_gif_scale_width(req);
|
||||
let palettegen_filter = format!(
|
||||
"fps={fps},scale={w}:-1:flags=lanczos,palettegen=stats_mode=diff",
|
||||
fps = req.fps,
|
||||
w = scale_width,
|
||||
);
|
||||
|
||||
let mut gen = Command::new(ffmpeg);
|
||||
gen.arg("-y")
|
||||
.arg("-hide_banner")
|
||||
.arg("-i")
|
||||
.arg(&req.input)
|
||||
.args(["-vf", &palettegen_filter])
|
||||
.arg(&palette_path);
|
||||
run(&mut gen, "gif palette generation")?;
|
||||
|
||||
let dither = match req.gif_dither {
|
||||
GifDither::FloydSteinberg => "floyd_steinberg",
|
||||
GifDither::Bayer => "bayer:bayer_scale=3",
|
||||
GifDither::None => "none",
|
||||
};
|
||||
let use_filter = format!(
|
||||
"fps={fps},scale={w}:-1:flags=lanczos[x];[x][1:v]paletteuse=dither={d}",
|
||||
fps = req.fps,
|
||||
w = scale_width,
|
||||
d = dither,
|
||||
);
|
||||
|
||||
let mut encode = Command::new(ffmpeg);
|
||||
encode
|
||||
.arg("-y")
|
||||
.arg("-hide_banner")
|
||||
.arg("-i")
|
||||
.arg(&req.input)
|
||||
.arg("-i")
|
||||
.arg(&palette_path)
|
||||
.args(["-lavfi", &use_filter])
|
||||
.args(["-loop", "0"])
|
||||
.arg(&req.output);
|
||||
run(&mut encode, "gif encode")?;
|
||||
|
||||
let _ = std::fs::remove_file(&palette_path);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn estimate_gif_scale_width(req: &TranscodeRequest) -> u32 {
|
||||
let bytes_per_pixel_per_frame = 0.5_f64;
|
||||
let frames = (req.fps as f64 * req.duration_secs).max(1.0);
|
||||
let budget = req.target_bytes as f64 / (frames * bytes_per_pixel_per_frame);
|
||||
let aspect = 16.0_f64 / 9.0;
|
||||
let w = (budget * aspect).sqrt();
|
||||
let w = w.clamp(120.0, 1280.0).round() as u32;
|
||||
(w / 2) * 2
|
||||
}
|
||||
|
||||
fn run(cmd: &mut Command, label: &str) -> Result<()> {
|
||||
let mut printable = OsString::from(label);
|
||||
printable.push(": ");
|
||||
printable.push(cmd.get_program());
|
||||
for arg in cmd.get_args() {
|
||||
printable.push(" ");
|
||||
printable.push(arg);
|
||||
}
|
||||
tracing::debug!("{}", printable.to_string_lossy());
|
||||
|
||||
let status = cmd.status().with_context(|| format!("spawning ffmpeg for {label}"))?;
|
||||
if !status.success() {
|
||||
bail!("ffmpeg {label} exited with {status}");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user