tighten export and capture handling

This commit is contained in:
2026-06-04 23:09:13 +03:00
parent a48d82ddc9
commit 4ca802ef71
14 changed files with 736 additions and 456 deletions
+162 -58
View File
@@ -140,18 +140,14 @@ pub fn transcode(ffmpeg: &Path, req: &TranscodeRequest) -> Result<()> {
match req.format {
Format::Mp4 => {
let codec = pick_video_codec(
&encoders,
&[mp4_video_codec(req.mp4_codec), "libx264"],
)?;
let requested = mp4_video_codec(req.mp4_codec);
let codec = require_video_codec(&encoders, requested, "MP4")?;
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 requested = webm_video_codec(req.webm_codec);
let codec = require_video_codec(&encoders, requested, "WebM")?;
let audio = pick_audio_codec(&encoders, &["libopus", "libvorbis"])?;
two_pass_video(ffmpeg, req, codec, audio, "webm")
}
@@ -159,6 +155,18 @@ pub fn transcode(ffmpeg: &Path, req: &TranscodeRequest) -> Result<()> {
}
}
fn require_video_codec<'a>(
encoders: &HashSet<String>,
requested: &'a str,
container: &str,
) -> Result<&'a str> {
if encoders.contains(requested) {
Ok(requested)
} else {
bail!("{container} codec unavailable: ffmpeg does not include {requested}")
}
}
use std::sync::OnceLock;
static ENCODER_CACHE: OnceLock<HashSet<String>> = OnceLock::new();
@@ -191,21 +199,6 @@ fn list_encoders(ffmpeg: &Path) -> Result<&'static HashSet<String>> {
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],
@@ -298,7 +291,21 @@ fn two_pass_video(
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())?;
let pass_start = std::time::Instant::now();
run_with_progress(
&mut pass1,
"pass 1",
1,
2,
dur,
fps,
tx.as_ref(),
cancel.as_ref(),
)?;
tracing::info!(
elapsed_ms = pass_start.elapsed().as_millis(),
"ffmpeg pass 1 finished"
);
// Send 50% to signal pass 1 done, pass 2 starting.
if let Some(ref t) = tx {
@@ -328,7 +335,21 @@ fn two_pass_video(
pass2.arg("-an");
}
pass2.arg(&req.output);
run_with_progress(&mut pass2, "pass 2", 2, 2, dur, fps, tx.as_ref(), cancel.as_ref())?;
let pass_start = std::time::Instant::now();
run_with_progress(
&mut pass2,
"pass 2",
2,
2,
dur,
fps,
tx.as_ref(),
cancel.as_ref(),
)?;
tracing::info!(
elapsed_ms = pass_start.elapsed().as_millis(),
"ffmpeg pass 2 finished"
);
cleanup_pass_logs(&log_stem);
Ok(())
@@ -365,18 +386,29 @@ fn encode_gif(ffmpeg: &Path, req: &TranscodeRequest) -> Result<()> {
};
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;
// Retry budget scales with the input. A 5s clip rarely needs more than 3-4
// attempts; a 60s clip with tight target and high colors can take 8-10.
// Cap at 12 to avoid runaway loops on pathological inputs.
let max_retries = ((req.duration_secs / 5.0).ceil() as u32 + 4).clamp(5, 12);
let mut prev_actual: Option<u64> = None;
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 {
if attempt == max_retries - 1 {
scale_width = (scale_width / 2).max(60);
effective_fps = 1;
}
let pass_start = std::time::Instant::now();
encode_gif_pass(ffmpeg, req, scale_width, effective_fps)?;
tracing::info!(
attempt = attempt + 1,
elapsed_ms = pass_start.elapsed().as_millis(),
"gif pass finished"
);
let actual = std::fs::metadata(&req.output)
.map(|m| m.len())
@@ -397,29 +429,69 @@ fn encode_gif(ffmpeg: &Path, req: &TranscodeRequest) -> Result<()> {
return Ok(());
}
// Only adjust DOWN when file is too big - never exceed target
// File is too big - scale down based on budget priority
// Compute a shrink factor. Clamp the multiplicative shrink between
// 0.6 and 0.9 so a single bad estimate can't half the resolution in
// one step (which is the oscillation problem) and so we don't creep
// toward the target at a snail's pace.
let raw_factor = match req.gif_budget_mode {
GifBudgetMode::Resolution => ratio,
GifBudgetMode::Framerate => ratio.sqrt(),
GifBudgetMode::Balanced => {
// Split the required reduction between resolution and fps
// so we reduce both proportionally rather than halving
// resolution alone (which the old `factor = ratio.sqrt()`
// would do after a large overshoot).
let half = 0.5_f64;
(ratio * (1.0 - half) + ratio.sqrt() * half).clamp(0.1, 1.0)
}
};
let mut factor = raw_factor.clamp(0.6, 0.9);
// Track trend across attempts. If shrinking settings did not shrink
// the file, or moved us farther from the target, force the strongest
// allowed shrink next time instead of creeping/oscillating.
if let Some(prev) = prev_actual {
let prev_dist = (target as f64 - prev as f64).abs();
let cur_dist = (target as f64 - actual as f64).abs();
if actual >= prev || cur_dist > prev_dist {
tracing::warn!(
"gif encode: retry trend worsened. prev={}B, now={}B. using stronger shrink.",
prev,
actual
);
factor = 0.6;
}
}
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);
effective_fps = ((effective_fps as f64 * factor).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;
scale_width = ((scale_width as f64 * factor).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;
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
"gif retry {}: was {} bytes (target {}), adjusting to {}x @ {}fps (factor={:.2})",
attempt + 1,
actual,
target,
scale_width,
effective_fps,
factor
);
prev_actual = Some(actual);
}
// All retries exhausted - warn if still over target
@@ -505,7 +577,7 @@ pub struct GifBudgetInput {
}
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 };
let aspect = aspect_ratio(clip_width, clip_height);
// 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.
@@ -555,6 +627,23 @@ pub fn gif_params(input: &GifBudgetInput, clip_width: u32, clip_height: u32) ->
}
}
pub fn aspect_ratio(width: u32, height: u32) -> f64 {
if height > 0 {
width as f64 / height as f64
} else {
16.0 / 9.0
}
}
pub fn gif_height_for_width(width: u32, clip_width: u32, clip_height: u32) -> u32 {
let aspect = aspect_ratio(clip_width, clip_height);
if width == 0 {
0
} else {
((width as f64 / aspect).round() as u32 / 2) * 2
}
}
pub fn render_preview(
ffmpeg: &Path,
input: &Path,
@@ -709,7 +798,7 @@ pub fn mux_with_audio(
}
pub fn concat_pcm(segments: &[PathBuf], output: &Path) -> Result<()> {
use std::io::{Read, Write};
use std::io::Write;
if segments.is_empty() {
bail!("no audio segments to concatenate");
}
@@ -719,15 +808,9 @@ pub fn concat_pcm(segments: &[PathBuf], output: &Path) -> Result<()> {
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])?;
}
std::io::copy(&mut f, &mut out).context("copying audio segment")?;
}
out.flush()?;
Ok(())
}
@@ -777,9 +860,7 @@ pub fn concat_segments(ffmpeg: &Path, segments: &[PathBuf], output: &Path) -> Re
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);
bail!(ffmpeg_failure_message(label, output.status, &output.stderr));
}
Ok(())
}
@@ -798,13 +879,36 @@ fn run_with_progress(
) -> 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);
bail!(ffmpeg_failure_message(label, output.status, &output.stderr));
}
Ok(())
}
fn ffmpeg_failure_message(label: &str, status: std::process::ExitStatus, stderr: &[u8]) -> String {
let text = String::from_utf8_lossy(stderr);
let head: String = text.lines().take(12).collect::<Vec<_>>().join("\n");
let lower = text.to_ascii_lowercase();
let hint = if lower.contains("unknown encoder")
|| lower.contains("error while opening encoder")
{
Some("selected codec is not available in this ffmpeg build")
} else if lower.contains("permission denied") {
Some("output path is not writable")
} else if lower.contains("no such file or directory") {
Some("input or output path does not exist")
} else if lower.contains("invalid data found") {
Some("input clip could not be read")
} else if lower.contains("invalid argument") {
Some("ffmpeg rejected one of the encode settings")
} else {
None
};
match hint {
Some(h) => format!("ffmpeg {label} failed: {h}. Details: {head}"),
None => format!("ffmpeg {label} exited with {status}: {head}"),
}
}
fn run_impl(
cmd: &mut Command,
label: &str,
@@ -914,11 +1018,11 @@ fn parse_frame_from_stderr(line: &str) -> Option<f64> {
mod tests {
use super::*;
// Paths are empty - these tests only exercise bitrate math, not ffmpeg.
fn dummy_request() -> TranscodeRequest {
let dir = std::env::temp_dir().join(format!("bytesize-encode-test-{}", std::process::id()));
TranscodeRequest {
input: PathBuf::new(),
output: PathBuf::new(),
input: dir.join("input.mp4"),
output: dir.join("output.mp4"),
format: Format::Mp4,
target_bytes: 0,
duration_secs: 10.0,
@@ -927,7 +1031,7 @@ mod tests {
gif_dither: GifDither::FloydSteinberg,
webm_codec: WebmCodec::Vp9,
mp4_codec: Mp4Codec::H264,
scratch_dir: PathBuf::new(),
scratch_dir: dir.join("scratch"),
crop: None,
gif_budget_mode: GifBudgetMode::Balanced,
gif_colors: 256,