Files
bytesize/src-tauri/src/encode.rs
T
lashman 2eca4b64b6 fix GIF speed: remove capture-side fps filter, let encoder handle conversion
The capture pipeline was applying fps=N to drop frames from monitor refresh
rate to user fps. Then the GIF encoder applied fps=M on the already-converted
file. Double fps conversion = broken frame timestamps = wrong playback speed.

Fix: remove fps filter from capture. Intermediate files keep monitor's native
refresh rate (e.g. 120fps). The GIF/video encoder's fps filter handles the
conversion correctly in one clean step.

Also removed redundant -r flag from GIF encoder (already done), and restored
the 16:9 preset and low FPS options that were removed earlier.
2026-05-30 00:43:10 +03:00

1033 lines
32 KiB
Rust

use std::collections::HashSet;
use std::ffi::{OsStr, OsString};
use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc::Sender;
use std::sync::Arc;
use std::thread;
use anyhow::{anyhow, bail, Context, Result};
use crate::clicks::Click;
use crate::config::{Format, GifBudgetMode, GifDither, Mp4Codec, WebmCodec};
use crate::CaptureRect;
// Used both for bitrate budget calculation and final mux. Must be consistent.
const AUDIO_BITRATE_KBPS: u64 = 192;
/// Progress update sent during encoding.
/// pass: 1-based pass number (1 or 2 for two-pass video, 1 for GIF).
/// total_passes: total number of passes.
/// percent: 0.0 to 100.0.
#[derive(Debug, Clone, Copy, serde::Serialize)]
pub struct EncodeProgress {
pub pass: u8,
pub total_passes: u8,
pub percent: f64,
}
#[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 crop: Option<CaptureRect>,
pub gif_budget_mode: GifBudgetMode,
pub gif_colors: u16,
pub deleted_frame_indices: Vec<u32>,
pub trim_start_secs: Option<f64>,
pub trim_end_secs: Option<f64>,
pub clicks: Vec<Click>,
pub clip_width: u32,
pub clip_height: u32,
/// Optional channel to report encoding progress.
#[doc(hidden)]
pub progress_tx: Option<Sender<EncodeProgress>>,
/// Optional cancel signal. When set to true, ffmpeg will be killed.
#[doc(hidden)]
pub cancel: Option<Arc<AtomicBool>>,
}
const MAX_CLICK_HIGHLIGHTS: usize = 50;
fn click_filters(req: &TranscodeRequest) -> Option<String> {
if req.clicks.is_empty() {
return None;
}
let size = 24i32;
let half = size / 2;
let mut parts: Vec<String> = Vec::new();
let clicks_to_render = req.clicks.len().min(MAX_CLICK_HIGHLIGHTS);
if req.clicks.len() > MAX_CLICK_HIGHLIGHTS {
tracing::warn!(
"{} click events recorded, only first {} will be highlighted",
req.clicks.len(),
MAX_CLICK_HIGHLIGHTS
);
}
for click in &req.clicks[..clicks_to_render] {
let x = click.x - half;
let y = click.y - half;
let t1 = (click.time_secs - 0.05).max(0.0);
let t2 = click.time_secs + 0.25;
let color = match click.button {
crate::clicks::MouseButton::Left => "yellow@0.6",
crate::clicks::MouseButton::Right => "blue@0.6",
crate::clicks::MouseButton::Middle => "green@0.6",
};
parts.push(format!(
"drawbox=x={x}:y={y}:w={size}:h={size}:color={color}:t=2:enable='between(t,{t1:.3},{t2:.3})'"
));
}
if parts.is_empty() {
None
} else {
Some(parts.join(","))
}
}
fn apply_trim(cmd: &mut Command, req: &TranscodeRequest) {
if let Some(start) = req.trim_start_secs {
if start > 0.001 {
cmd.args(["-ss", &format!("{start}")]);
}
}
if let Some(end) = req.trim_end_secs {
cmd.args(["-to", &format!("{end}")]);
}
}
fn select_filter_for_deleted(deleted: &[u32]) -> Option<String> {
if deleted.is_empty() {
return None;
}
let parts: Vec<String> = deleted.iter().map(|n| format!("eq(n\\,{n})")).collect();
let expr = parts.join("+");
Some(format!("select='not({expr})',setpts=N/FRAME_RATE/TB"))
}
fn crop_filter(crop: Option<CaptureRect>) -> Option<String> {
crop.map(|c| {
format!(
"crop={w}:{h}:{x}:{y}",
w = c.width,
h = c.height,
x = c.x.max(0),
y = c.y.max(0)
)
})
}
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")?;
}
let encoders = list_encoders(ffmpeg)?;
match req.format {
Format::Mp4 => {
let codec = pick_video_codec(
&encoders,
&[mp4_video_codec(req.mp4_codec), "libx264"],
)?;
let audio = pick_audio_codec(&encoders, &["aac", "libfdk_aac"])?;
two_pass_video(ffmpeg, req, codec, audio, "mp4")
}
Format::Webm => {
let codec = pick_video_codec(
&encoders,
&[webm_video_codec(req.webm_codec), "libvpx-vp9", "libvpx"],
)?;
let audio = pick_audio_codec(&encoders, &["libopus", "libvorbis"])?;
two_pass_video(ffmpeg, req, codec, audio, "webm")
}
Format::Gif => encode_gif(ffmpeg, req),
}
}
use std::sync::OnceLock;
static ENCODER_CACHE: OnceLock<HashSet<String>> = OnceLock::new();
fn list_encoders(ffmpeg: &Path) -> Result<&'static HashSet<String>> {
if let Some(cached) = ENCODER_CACHE.get() {
return Ok(cached);
}
let out = Command::new(ffmpeg)
.args(["-hide_banner", "-encoders"])
.output()
.context("listing ffmpeg encoders")?;
let text = String::from_utf8_lossy(&out.stdout);
let mut set: HashSet<String> = HashSet::new();
for line in text.lines() {
let trimmed = line.trim_start();
let mut iter = trimmed.split_whitespace();
let (Some(flags), Some(name)) = (iter.next(), iter.next()) else {
continue;
};
if flags.len() != 6 {
continue;
}
if !matches!(flags.chars().next(), Some('V' | 'A' | 'S')) {
continue;
}
set.insert(name.to_string());
}
let _ = ENCODER_CACHE.set(set);
Ok(ENCODER_CACHE.get().unwrap())
}
fn pick_video_codec<'a>(
encoders: &HashSet<String>,
candidates: &[&'a str],
) -> Result<&'a str> {
for c in candidates {
if encoders.contains(*c) {
return Ok(c);
}
}
bail!(
"no video encoder available - tried {}",
candidates.join(", ")
)
}
fn pick_audio_codec<'a>(
encoders: &HashSet<String>,
candidates: &[&'a str],
) -> Result<&'a str> {
for c in candidates {
if encoders.contains(*c) {
return Ok(c);
}
}
bail!(
"no audio encoder available - tried {}",
candidates.join(", ")
)
}
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 as f64) * 8.0 * 0.95;
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("ffmpeg2pass");
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 crop = crop_filter(req.crop);
let clicks = click_filters(req);
let combined_vf: Option<String> = match (&crop, &clicks) {
(Some(c), Some(k)) => Some(format!("{c},{k}")),
(Some(c), None) => Some(c.clone()),
(None, Some(k)) => Some(k.clone()),
(None, None) => None,
};
let mut pass1 = Command::new(ffmpeg);
pass1
.arg("-y")
.arg("-hide_banner")
.arg("-i")
.arg(&req.input);
apply_trim(&mut pass1, req);
if let Some(c) = &combined_vf {
pass1.args(["-vf", c]);
}
pass1
.args(["-c:v", video_codec])
.args(["-b:v", &bitrate])
.args(["-pass", "1"])
.args(["-passlogfile", log_stem_str])
.arg("-an")
.args(["-f", "null"])
.arg(null_target);
let tx = req.progress_tx.clone();
let dur = req.duration_secs;
let fps = req.fps;
let cancel = req.cancel.clone();
run_with_progress(&mut pass1, "pass 1", 1, 2, dur, fps, tx.as_ref(), cancel.as_ref())?;
// Send 50% to signal pass 1 done, pass 2 starting.
if let Some(ref t) = tx {
let _ = t.send(EncodeProgress { pass: 1, total_passes: 2, percent: 100.0 });
}
let mut pass2 = Command::new(ffmpeg);
pass2
.arg("-y")
.arg("-hide_banner")
.arg("-i")
.arg(&req.input);
apply_trim(&mut pass2, req);
if let Some(c) = &combined_vf {
pass2.args(["-vf", c]);
}
pass2
.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_with_progress(&mut pass2, "pass 2", 2, 2, dur, fps, tx.as_ref(), cancel.as_ref())?;
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 budget_input = GifBudgetInput {
gif_colors: req.gif_colors,
target_bytes: req.target_bytes,
fps: req.fps,
duration_secs: req.duration_secs,
gif_budget_mode: req.gif_budget_mode,
};
let (mut scale_width, mut effective_fps) = gif_params(&budget_input, req.clip_width, req.clip_height);
let target = req.target_bytes;
let max_retries = 6;
for attempt in 0..max_retries {
if req.cancel.as_ref().map_or(false, |c| c.load(Ordering::Relaxed)) {
bail!("export cancelled");
}
// Last resort: use minimal settings to hit the target
if attempt == 5 {
scale_width = (scale_width / 2).max(60);
effective_fps = 1;
}
encode_gif_pass(ffmpeg, req, scale_width, effective_fps)?;
let actual = std::fs::metadata(&req.output)
.map(|m| m.len())
.unwrap_or(0);
if actual == 0 {
bail!("gif output is empty");
}
let ratio = target as f64 / actual as f64;
// Accept if at or under target (even if significantly under - don't upscale)
if ratio >= 1.0 {
tracing::info!(
"gif encode done on attempt {}: {} bytes (target {})",
attempt + 1, actual, target
);
return Ok(());
}
// Only adjust DOWN when file is too big
// Accept within 15% over target
if ratio >= 0.85 {
tracing::info!(
"gif encode done on attempt {}: {} bytes (target {} - close enough)",
attempt + 1, actual, target
);
return Ok(());
}
// File is too big - scale down based on budget priority
match req.gif_budget_mode {
GifBudgetMode::Resolution => {
// Reduce fps (resolution is priority, keep it)
effective_fps = ((effective_fps as f64 * ratio).round() as u32).max(1);
}
GifBudgetMode::Framerate => {
// Reduce resolution (fps is priority, keep it)
scale_width = ((scale_width as f64 * ratio.sqrt()).round() as u32 / 2).max(60).min(1280) * 2;
}
GifBudgetMode::Balanced => {
// Reduce both
let factor = ratio.sqrt();
scale_width = ((scale_width as f64 * factor).round() as u32 / 2).max(60).min(1280) * 2;
effective_fps = ((effective_fps as f64 * factor).round() as u32).max(1);
}
}
tracing::info!(
"gif retry {}: was {} bytes (target {}), adjusting to {}x @ {}fps",
attempt + 1, actual, target, scale_width, effective_fps
);
}
// All retries exhausted - warn if still over target
let final_size = std::fs::metadata(&req.output).map(|m| m.len()).unwrap_or(0);
if final_size > req.target_bytes {
tracing::warn!(
"gif encode: could not meet target size after {} attempts. Final: {} bytes (target: {})",
max_retries, final_size, req.target_bytes
);
}
Ok(())
}
fn encode_gif_pass(
ffmpeg: &Path,
req: &TranscodeRequest,
scale_width: u32,
effective_fps: u32,
) -> Result<()> {
let crop_prefix = crop_filter(req.crop)
.map(|c| format!("{c},"))
.unwrap_or_default();
let click_prefix = click_filters(req)
.map(|c| format!("{c},"))
.unwrap_or_default();
let select_prefix = select_filter_for_deleted(&req.deleted_frame_indices)
.map(|s| format!("{s},"))
.unwrap_or_default();
let dither = match req.gif_dither {
GifDither::FloydSteinberg => "floyd_steinberg",
GifDither::Bayer => "bayer:bayer_scale=3",
GifDither::None => "none",
};
// Single-pass approach: split the stream, generate palette from one copy,
// apply palette to the other. The fps filter handles frame rate conversion.
let filter_complex = format!(
"{cprefix}{kprefix}fps={fps},{sprefix}scale={w}:-1:flags=lanczos,split[s0][s1];[s0]palettegen=stats_mode=diff:max_colors={colors}[p];[s1][p]paletteuse=dither={d}",
cprefix = crop_prefix,
kprefix = click_prefix,
sprefix = select_prefix,
fps = effective_fps,
w = scale_width,
colors = req.gif_colors,
d = dither,
);
let mut encode = Command::new(ffmpeg);
encode
.arg("-y")
.arg("-hide_banner")
.arg("-i")
.arg(&req.input);
apply_trim(&mut encode, req);
encode
.args(["-filter_complex", &filter_complex])
.args(["-loop", "0"])
.arg(&req.output);
run_with_progress(
&mut encode,
"gif encode",
1,
1,
req.duration_secs,
effective_fps,
req.progress_tx.as_ref(),
req.cancel.as_ref(),
)?;
Ok(())
}
#[derive(Debug, Clone)]
pub struct GifBudgetInput {
pub gif_colors: u16,
pub target_bytes: u64,
pub fps: u32,
pub duration_secs: f64,
pub gif_budget_mode: GifBudgetMode,
}
pub fn gif_params(input: &GifBudgetInput, clip_width: u32, clip_height: u32) -> (u32, u32) {
let aspect = if clip_height > 0 { clip_width as f64 / clip_height as f64 } else { 16.0 / 9.0 };
// GIF LZW compression on typical screen content averages ~0.2 bytes/pixel at 256 colors.
// Real compression varies 3-5x depending on content (solid colors compress much better
// than gradients/noise). The retry loop in encode_gif handles correction on mismatch.
// Fewer colors = better compression. Adjust proportionally.
// 256 colors = 1.0x, 128 = ~0.85x, 64 = ~0.7x, 32 = ~0.55x, 16 = ~0.4x, 2 = ~0.2x
let color_factor = (input.gif_colors as f64 / 256.0).sqrt().clamp(0.15, 1.0);
let bytes_per_pixel_per_frame = 0.2 * color_factor;
let target_bytes = input.target_bytes as f64;
let requested_fps = input.fps as f64;
let duration = input.duration_secs;
match input.gif_budget_mode {
GifBudgetMode::Resolution => {
let max_w = (clip_width.min(1280) as f64).clamp(120.0, 1280.0);
let w = (max_w / 2.0).round() as u32 * 2;
let h = (w as f64 / aspect).round() as u32;
let pixels_per_frame = w as f64 * h as f64;
let bytes_per_frame = pixels_per_frame * bytes_per_pixel_per_frame;
let max_frames = (target_bytes / bytes_per_frame).floor().max(1.0);
let min_fps = (max_frames / duration).max(1.0).round() as u32;
let fps = (input.fps).min(min_fps).max(1);
(w, fps)
}
GifBudgetMode::Framerate => {
let frames = (requested_fps * duration).max(1.0);
let budget = target_bytes / (frames * bytes_per_pixel_per_frame);
let w = (budget * aspect).sqrt();
let w = (w.clamp(120.0, 1280.0).round() as u32 / 2) * 2;
(w, input.fps)
}
GifBudgetMode::Balanced => {
let frames_at_full = (requested_fps * duration).max(1.0);
let budget_at_full = target_bytes / (frames_at_full * bytes_per_pixel_per_frame);
let w_at_full = (budget_at_full * aspect).sqrt().clamp(120.0, 1280.0);
let scale = if w_at_full < clip_width as f64 {
(w_at_full / clip_width as f64).sqrt()
} else {
1.0
};
let scale = scale.max(0.1);
let w = ((clip_width as f64 * scale).round() as u32 / 2).max(60) * 2;
let fps = ((requested_fps * scale).round() as u32).max(1).min(input.fps);
(w, fps)
}
}
}
pub fn render_preview(
ffmpeg: &Path,
input: &Path,
out_path: &Path,
midpoint_secs: f64,
target_width: u32,
) -> Result<()> {
if let Some(parent) = out_path.parent() {
std::fs::create_dir_all(parent).context("creating preview parent")?;
}
let scale_filter = format!("scale={}:-2", target_width);
let mut cmd = Command::new(ffmpeg);
cmd.arg("-y")
.arg("-hide_banner")
.args(["-ss", &format!("{midpoint_secs}")])
.arg("-i")
.arg(input)
.args(["-vf", &scale_filter])
.args(["-frames:v", "1"])
.arg(out_path);
run(&mut cmd, "preview render")
}
/// Render a GIF preview with actual palette and dithering applied.
/// Generates a palette from the full clip, then applies it to a single frame.
pub fn render_gif_preview(
ffmpeg: &Path,
input: &Path,
out_path: &Path,
midpoint_secs: f64,
target_width: u32,
gif_colors: u16,
gif_dither: &str,
duration_secs: f64,
) -> Result<()> {
if let Some(parent) = out_path.parent() {
std::fs::create_dir_all(parent).context("creating preview parent")?;
}
// Generate palette from a sample of the clip (middle 2 seconds or full clip)
let palette_path = out_path.parent().unwrap_or(input.parent().unwrap()).join("preview-palette.png");
let sample_start = (midpoint_secs - 1.0).max(0.0);
let sample_dur = duration_secs.min(2.0);
let palette_filter = format!(
"scale={}:-2:flags=lanczos,palettegen=stats_mode=diff:max_colors={}",
target_width, gif_colors
);
let mut gen = Command::new(ffmpeg);
gen.arg("-y")
.arg("-hide_banner")
.args(["-ss", &format!("{sample_start}")])
.args(["-t", &format!("{sample_dur}")])
.arg("-i")
.arg(input)
.args(["-vf", &palette_filter])
.arg(&palette_path);
run(&mut gen, "gif preview palette")?;
// Apply palette to the target frame
let use_filter = format!(
"scale={}:-2:flags=lanczos[x];[x][1:v]paletteuse=dither={}",
target_width, gif_dither
);
let mut encode = Command::new(ffmpeg);
encode.arg("-y")
.arg("-hide_banner")
.args(["-ss", &format!("{midpoint_secs}")])
.arg("-i")
.arg(input)
.arg("-i")
.arg(&palette_path)
.args(["-lavfi", &use_filter])
.args(["-frames:v", "1"])
.arg(out_path);
let result = run(&mut encode, "gif preview encode");
let _ = std::fs::remove_file(&palette_path);
result
}
pub fn extract_thumbnails(
ffmpeg: &Path,
input: &Path,
out_dir: &Path,
fps: u32,
crop: Option<CaptureRect>,
) -> Result<Vec<PathBuf>> {
std::fs::create_dir_all(out_dir).context("creating thumbnails dir")?;
for entry in std::fs::read_dir(out_dir).into_iter().flatten().flatten() {
let _ = std::fs::remove_file(entry.path());
}
let crop_prefix = crop_filter(crop)
.map(|c| format!("{c},"))
.unwrap_or_default();
let filter = format!(
"{prefix}fps={fps},scale=120:-1:flags=lanczos",
prefix = crop_prefix,
fps = fps
);
let pattern = out_dir.join("thumb-%05d.png");
let mut cmd = Command::new(ffmpeg);
cmd.arg("-y")
.arg("-hide_banner")
.arg("-i")
.arg(input)
.args(["-vf", &filter])
.arg(&pattern);
run(&mut cmd, "thumbnail extraction")?;
let mut paths: Vec<PathBuf> = std::fs::read_dir(out_dir)?
.flatten()
.map(|e| e.path())
.filter(|p| {
p.extension().and_then(|s| s.to_str()) == Some("png")
&& p.file_name()
.and_then(|s| s.to_str())
.map(|s| s.starts_with("thumb-"))
.unwrap_or(false)
})
.collect();
paths.sort();
Ok(paths)
}
pub fn mux_with_audio(
ffmpeg: &Path,
video: &Path,
audio_pcm: &Path,
sample_rate: u32,
channels: u16,
output: &Path,
) -> Result<()> {
if let Some(parent) = output.parent() {
std::fs::create_dir_all(parent).context("creating output parent dir")?;
}
let mut cmd = Command::new(ffmpeg);
cmd.arg("-y")
.arg("-hide_banner")
.arg("-i")
.arg(video)
.args(["-f", "f32le"])
.args(["-ar", &sample_rate.to_string()])
.args(["-ac", &channels.to_string()])
.arg("-i")
.arg(audio_pcm)
.args(["-c:v", "copy"])
.args(["-c:a", "aac"])
.args(["-b:a", "192k"])
.args(["-shortest"])
.arg(output);
run(&mut cmd, "mux")
}
pub fn concat_pcm(segments: &[PathBuf], output: &Path) -> Result<()> {
use std::io::{Read, Write};
if segments.is_empty() {
bail!("no audio segments to concatenate");
}
if let Some(parent) = output.parent() {
std::fs::create_dir_all(parent).context("creating audio concat parent")?;
}
let mut out = std::fs::File::create(output).context("creating audio concat file")?;
for seg in segments {
let mut f = std::fs::File::open(seg).with_context(|| format!("opening {seg:?}"))?;
let mut buf = vec![0u8; 64 * 1024];
loop {
let n = f.read(&mut buf)?;
if n == 0 {
break;
}
out.write_all(&buf[..n])?;
}
}
Ok(())
}
struct TempFileGuard(PathBuf);
impl Drop for TempFileGuard {
fn drop(&mut self) { let _ = std::fs::remove_file(&self.0); }
}
pub fn concat_segments(ffmpeg: &Path, segments: &[PathBuf], output: &Path) -> Result<()> {
if segments.is_empty() {
bail!("no segments to concatenate");
}
if segments.len() == 1 {
std::fs::copy(&segments[0], output).context("copying single segment")?;
return Ok(());
}
let parent = output
.parent()
.ok_or_else(|| anyhow!("output has no parent dir"))?;
std::fs::create_dir_all(parent).context("creating output parent dir")?;
let list_path = parent.join("concat-list.txt");
let _guard = TempFileGuard(list_path.clone());
let mut body = String::new();
for seg in segments {
let s = seg
.to_str()
.ok_or_else(|| anyhow!("segment path is not UTF-8"))?
.replace('\\', "/");
body.push_str(&format!("file '{s}'\n"));
}
std::fs::write(&list_path, body).context("writing concat list")?;
let mut cmd = Command::new(ffmpeg);
cmd.arg("-y")
.arg("-hide_banner")
.args(["-f", "concat"])
.args(["-safe", "0"])
.arg("-i")
.arg(&list_path)
.args(["-c", "copy"])
.arg(output);
run(&mut cmd, "concat")
}
fn run(cmd: &mut Command, label: &str) -> Result<()> {
let output = run_impl(cmd, label, 0, 0, 0.0, 0, None, None)?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
let head: String = stderr.lines().take(12).collect::<Vec<_>>().join("\n");
bail!("ffmpeg {label} exited with {}: {}", output.status, head);
}
Ok(())
}
/// Run an ffmpeg command with progress monitoring.
/// progress_tx, if provided, receives (pass, total_passes, percent) updates.
fn run_with_progress(
cmd: &mut Command,
label: &str,
pass: u8,
total_passes: u8,
duration_secs: f64,
fps: u32,
progress_tx: Option<&Sender<EncodeProgress>>,
cancel: Option<&Arc<AtomicBool>>,
) -> Result<()> {
let output = run_impl(cmd, label, pass, total_passes, duration_secs, fps, progress_tx.cloned(), cancel.cloned())?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
let head: String = stderr.lines().take(12).collect::<Vec<_>>().join("\n");
bail!("ffmpeg {label} exited with {}: {}", output.status, head);
}
Ok(())
}
fn run_impl(
cmd: &mut Command,
label: &str,
progress_pass: u8,
progress_total_passes: u8,
progress_duration_secs: f64,
progress_fps: u32,
progress_tx: Option<Sender<EncodeProgress>>,
cancel: Option<Arc<AtomicBool>>,
) -> Result<std::process::Output> {
use std::process::Stdio;
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 mut child = cmd
.stdout(Stdio::null())
.stderr(Stdio::piped())
.spawn()
.with_context(|| format!("spawning ffmpeg for {label}"))?;
let stderr = child.stderr.take();
let tx = progress_tx.clone();
let mut stderr_handle: Option<thread::JoinHandle<Vec<u8>>> = stderr.map(move |serr| {
let tx = tx.as_ref().map(|t| t.clone());
let encode_dur = progress_duration_secs;
let fps = progress_fps;
let pass = progress_pass;
let total_passes = progress_total_passes;
thread::spawn(move || {
use std::io::{BufRead, BufReader};
let mut collected = Vec::new();
let reader = BufReader::new(serr);
for line in reader.lines().map_while(Result::ok) {
collected.extend_from_slice(line.as_bytes());
collected.push(b'\n');
if let Some(frame) = parse_frame_from_stderr(&line) {
let total = (encode_dur * fps as f64).max(1.0);
let percent = (frame / total * 100.0).min(100.0);
if let Some(ref sender) = tx {
let _ = sender.send(EncodeProgress {
pass,
total_passes,
percent,
});
}
}
}
collected
})
});
loop {
if let Some(ref c) = cancel {
if c.load(Ordering::Relaxed) {
let _ = child.kill();
let _ = child.wait();
if let Some(h) = stderr_handle.take() {
let _ = h.join();
}
bail!("export cancelled");
}
}
match child.try_wait() {
Ok(Some(status)) => {
let stderr_bytes = stderr_handle.take()
.and_then(|h| h.join().ok())
.unwrap_or_default();
return Ok(std::process::Output {
status,
stdout: Vec::new(),
stderr: stderr_bytes,
});
}
Ok(None) => {
std::thread::sleep(std::time::Duration::from_millis(50));
}
Err(e) => bail!("waiting for ffmpeg: {e}"),
}
}
}
/// Parse a frame count from an ffmpeg stderr progress line.
/// Lines look like: "frame= 123 fps= 30 q=-0.0 size= 1024kB time=00:00:04.10 ..."
fn parse_frame_from_stderr(line: &str) -> Option<f64> {
let trimmed = line.trim();
if !trimmed.starts_with("frame=") {
return None;
}
// Find the "frame= NNN" token and extract the number after it.
let after = trimmed.strip_prefix("frame=")?.trim_start();
let end = after
.find(|c: char| !c.is_ascii_digit())
.unwrap_or(after.len());
let frame_str = &after[..end];
frame_str.parse().ok()
}
#[cfg(test)]
mod tests {
use super::*;
// Paths are empty - these tests only exercise bitrate math, not ffmpeg.
fn dummy_request() -> TranscodeRequest {
TranscodeRequest {
input: PathBuf::new(),
output: PathBuf::new(),
format: Format::Mp4,
target_bytes: 0,
duration_secs: 10.0,
fps: 30,
keep_audio: true,
gif_dither: GifDither::FloydSteinberg,
webm_codec: WebmCodec::Vp9,
mp4_codec: Mp4Codec::H264,
scratch_dir: PathBuf::new(),
crop: None,
gif_budget_mode: GifBudgetMode::Balanced,
gif_colors: 256,
deleted_frame_indices: vec![],
trim_start_secs: None,
trim_end_secs: None,
clicks: vec![],
clip_width: 1920,
clip_height: 1080,
progress_tx: None,
cancel: None,
}
}
#[test]
fn bitrate_for_8mb_10s_with_audio() {
let mut req = dummy_request();
req.target_bytes = 8 * 1024 * 1024;
req.duration_secs = 10.0;
req.keep_audio = true;
let kbps = video_bitrate_kbps(&req).unwrap();
// 8 MB * 8 * 0.95 = 60.96 Mbits total
// minus 192k * 10 = 1.92 Mbits audio
// video = ~59 Mbits / 10s = ~5900 kbps
assert!(kbps > 5800 && kbps < 6200);
}
#[test]
fn bitrate_for_8mb_10s_no_audio() {
let mut req = dummy_request();
req.target_bytes = 8 * 1024 * 1024;
req.duration_secs = 10.0;
req.keep_audio = false;
let kbps = video_bitrate_kbps(&req).unwrap();
// 8 MB * 8 * 0.95 = 60.96 Mbits total, all video
// 60.96 Mbits / 10s = ~6096 kbps
assert!(kbps > 6000 && kbps < 6500);
}
#[test]
fn bitrate_rejects_too_small() {
let mut req = dummy_request();
req.target_bytes = 1000;
req.duration_secs = 10.0;
req.keep_audio = true;
assert!(video_bitrate_kbps(&req).is_err());
}
#[test]
fn bitrate_floor_at_16_kbps() {
let mut req = dummy_request();
req.target_bytes = 1024 * 1024;
req.duration_secs = 600.0;
req.keep_audio = false;
let kbps = video_bitrate_kbps(&req).unwrap();
assert_eq!(kbps, 16);
}
#[test]
fn parse_ffmpeg_stderr_frame() {
assert_eq!(
parse_frame_from_stderr("frame= 123 fps= 30 q=-0.0 size= 1024kB"),
Some(123.0)
);
assert_eq!(
parse_frame_from_stderr("frame=9999 fps=60.0"),
Some(9999.0)
);
assert_eq!(parse_frame_from_stderr("size= 1024kB"), None);
}
#[test]
fn crop_filter_output() {
let rect = CaptureRect { x: 10, y: 20, width: 100, height: 200 };
assert_eq!(
crop_filter(Some(rect)),
Some("crop=100:200:10:20".to_string())
);
assert_eq!(crop_filter(None), None);
}
#[test]
fn click_filters_capped_at_max() {
let clicks: Vec<Click> = (0..100)
.map(|i| Click { time_secs: i as f64, x: i, y: i, button: crate::clicks::MouseButton::Left })
.collect();
let req = TranscodeRequest {
clicks,
..dummy_request()
};
let filter = click_filters(&req).unwrap();
let count = filter.matches("drawbox").count();
assert_eq!(count, MAX_CLICK_HIGHLIGHTS);
}
}