calibrate gif size, probe codecs, align audio with video

- sample-encode gif calibration before the retry loop
- probe ffmpeg encoders and grey out missing codecs in settings
- pad audio head with silence so it lines up with video start
- cache gif preview palette keyed on colors and sample window
- read encode progress from -progress pipe:1 instead of stderr scraping
- thread bt709 color metadata through capture, fix, and gif scale
- sweep temp on startup
- gif estimate table for the ui, interpolated locally on slider drag
This commit is contained in:
2026-06-17 23:09:53 +03:00
parent 4ca802ef71
commit f732cdda4d
7 changed files with 647 additions and 155 deletions
+262 -69
View File
@@ -228,6 +228,40 @@ fn webm_video_codec(c: WebmCodec) -> &'static str {
}
}
/// Per-codec availability for the installed ffmpeg, surfaced to the frontend
/// so Settings can grey out codecs that would fail at export time. H264 and
/// VP9 are assumed always present (they are the defaults) - only the optional
/// codecs (H265, AV1) are reported because those are the ones users pick to
/// save size and only learn at minute 5 that their build lacks them.
#[derive(Debug, Clone, serde::Serialize)]
pub struct CodecAvailability {
pub h264: bool,
pub h265: bool,
pub vp9: bool,
pub av1: bool,
}
impl CodecAvailability {
/// Returns all-true when ffmpeg is not installed yet (the bootstrap screen
/// is still up). Settings will re-query after the user installs ffmpeg.
pub fn all_unknown() -> Self {
Self { h264: true, h265: true, vp9: true, av1: true }
}
}
pub fn codec_availability(ffmpeg: &Path) -> CodecAvailability {
let encoders = match list_encoders(ffmpeg) {
Ok(set) => set,
Err(_) => return CodecAvailability::all_unknown(),
};
CodecAvailability {
h264: encoders.contains(mp4_video_codec(Mp4Codec::H264)),
h265: encoders.contains(mp4_video_codec(Mp4Codec::H265)),
vp9: encoders.contains(webm_video_codec(WebmCodec::Vp9)),
av1: encoders.contains(webm_video_codec(WebmCodec::Av1)),
}
}
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 {
@@ -376,6 +410,68 @@ fn cleanup_pass_logs(stem: &Path) {
}
}
/// Encode a short sample of the clip at the given settings and measure the
/// actual bytes-per-pixel to calibrate the retry loop's starting estimate.
/// Returns corrected (width, fps) if the sample revealed a meaningful gap
/// between the assumed 0.2 bytes/pixel constant and reality.
fn calibrate_via_sample(
ffmpeg: &Path,
req: &TranscodeRequest,
est_width: u32,
est_fps: u32,
) -> Option<(u32, u32)> {
let sample_path = req.scratch_dir.join("gif-calib-sample.gif");
let sample_dur = 2.0_f64.min(req.duration_secs);
let sample_start = (req.duration_secs / 2.0 - sample_dur / 2.0).max(0.0);
// Build a throwaway request scoped to the sample window.
let mut sample_req = req.clone();
sample_req.output = sample_path.clone();
sample_req.trim_start_secs = Some(sample_start);
sample_req.trim_end_secs = Some(sample_start + sample_dur);
sample_req.deleted_frame_indices.clear();
sample_req.clicks.clear();
sample_req.progress_tx = None;
let result = encode_gif_pass(ffmpeg, &sample_req, est_width, est_fps);
let _ = std::fs::remove_file(&sample_path);
if result.is_err() {
return None;
}
let sample_bytes = match std::fs::metadata(&sample_path) {
Ok(m) => m.len(),
Err(_) => return None,
};
if sample_bytes == 0 {
return None;
}
// Back-compute the effective bytes/pixel from the sample. LZW on a short
// clip overstates per-frame cost slightly (less inter-frame reuse) so we
// apply a small correction factor toward the conservative side.
let aspect = aspect_ratio(req.clip_width, req.clip_height);
let sample_h = (est_width as f64 / aspect).round() as u32;
let frames = (est_fps as f64 * sample_dur).max(1.0);
let measured_bpp = sample_bytes as f64 / (est_width as f64 * sample_h as f64 * frames);
// Blend toward the assumed 0.2 constant - don't over-trust a 2s sample.
let blended_bpp = measured_bpp * 0.7 + 0.2 * 0.3;
let color_factor = (req.gif_colors as f64 / 256.0).sqrt().clamp(0.15, 1.0);
let assumed_bpp = 0.2 * color_factor;
let ratio = assumed_bpp / blended_bpp;
// Only recalibrate if the gap is meaningful (>15%). Small gaps aren't
// worth the risk of overshooting on a noisy 2s sample.
if (ratio - 1.0).abs() < 0.15 {
return None;
}
// Recompute target params with the corrected constant. Scale resolution
// by the sqrt of the ratio so file size scales roughly linearly.
let new_width = ((est_width as f64 * ratio.sqrt()).round() as u32 / 2).max(60) * 2;
let new_fps = ((est_fps as f64 * ratio.sqrt()).round() as u32).max(1).min(est_fps);
Some((new_width.min(1280), new_fps))
}
fn encode_gif(ffmpeg: &Path, req: &TranscodeRequest) -> Result<()> {
let budget_input = GifBudgetInput {
gif_colors: req.gif_colors,
@@ -385,6 +481,21 @@ fn encode_gif(ffmpeg: &Path, req: &TranscodeRequest) -> Result<()> {
gif_budget_mode: req.gif_budget_mode,
};
let (mut scale_width, mut effective_fps) = gif_params(&budget_input, req.clip_width, req.clip_height);
// Calibrate the bytes/pixel constant by encoding a short sample first.
// The default 0.2 bytes/pixel assumption varies 3-5x by content; measuring
// it on this specific clip gives the retry loop a much better starting
// point and typically cuts retry count from 4-8 down to 1-2.
if req.duration_secs > 4.0 {
if let Some((calibrated_w, calibrated_fps)) = calibrate_via_sample(ffmpeg, req, scale_width, effective_fps) {
tracing::info!(
"gif calibration: sample suggested {calibrated_w}x @ {calibrated_fps}fps (initial was {scale_width}x @ {effective_fps}fps)"
);
scale_width = calibrated_w;
effective_fps = calibrated_fps;
}
}
let target = req.target_bytes;
// 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.
@@ -529,13 +640,14 @@ fn encode_gif_pass(
// Single-pass approach: split the stream, generate palette from one copy,
// apply palette to the other. The fps filter handles frame rate conversion.
let scale = gif_rgb_scale_filter(scale_width);
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}{kprefix}fps={fps},{sprefix}{scale},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,
scale = scale,
colors = req.gif_colors,
d = dither,
);
@@ -567,6 +679,12 @@ fn encode_gif_pass(
Ok(())
}
fn gif_rgb_scale_filter(width: u32) -> String {
format!(
"scale={width}:-1:flags=lanczos:in_color_matrix=bt709:in_range=tv:in_primaries=bt709:in_transfer=bt709:out_primaries=bt709:out_transfer=srgb:out_range=pc,format=rgb24"
)
}
#[derive(Debug, Clone)]
pub struct GifBudgetInput {
pub gif_colors: u16,
@@ -682,29 +800,39 @@ pub fn render_gif_preview(
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");
// The palette depends only on gif_colors and the sampled frame range, not
// on target_bytes or dither. Cache it keyed on those inputs so slider
// drags (which change target_bytes) skip the expensive palettegen pass.
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")?;
let palette_key = palette_cache_key(gif_colors, target_width, sample_start, sample_dur);
let palette_path = out_path.parent().unwrap_or(input.parent().unwrap())
.join(format!("preview-palette-{palette_key}.png"));
let need_regen = !palette_path.is_file();
if need_regen {
// Drop any stale palettes from previous inputs so temp doesn't grow.
clean_stale_palettes(palette_path.parent().unwrap_or(Path::new(".")));
let palette_filter = format!(
"{},palettegen=stats_mode=diff:max_colors={}",
gif_rgb_scale_filter(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
"{}[x];[x][1:v]paletteuse=dither={}",
gif_rgb_scale_filter(target_width), gif_dither
);
let mut encode = Command::new(ffmpeg);
encode.arg("-y")
@@ -722,6 +850,28 @@ pub fn render_gif_preview(
result
}
/// Build a stable cache key for a GIF preview palette from the inputs that
/// actually affect palettegen output. Same inputs -> same palette.
fn palette_cache_key(gif_colors: u16, target_width: u32, sample_start: f64, sample_dur: f64) -> String {
format!(
"c{gif_colors}-w{target_width}-s{:.3}-d{:.3}",
sample_start, sample_dur
)
}
/// Remove old `preview-palette-*.png` files so only the current key remains.
fn clean_stale_palettes(dir: &Path) {
if let Ok(entries) = std::fs::read_dir(dir) {
for entry in entries.flatten() {
if let Some(name) = entry.file_name().to_str() {
if name.starts_with("preview-palette-") && name.ends_with(".png") {
let _ = std::fs::remove_file(entry.path());
}
}
}
}
}
pub fn extract_thumbnails(
ffmpeg: &Path,
input: &Path,
@@ -858,15 +1008,17 @@ 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)?;
let output = run_impl(cmd, label, 0, 0, 0.0, 0, None, None, false)?;
if !output.status.success() {
bail!(ffmpeg_failure_message(label, output.status, &output.stderr));
}
Ok(())
}
/// Run an ffmpeg command with progress monitoring.
/// progress_tx, if provided, receives (pass, total_passes, percent) updates.
/// Run an ffmpeg command with progress monitoring via `-progress pipe:1`.
/// progress_tx, if provided, receives (pass, total_passes, percent) updates
/// driven by ffmpeg's stable key=value output (`out_time_us`) rather than
/// fragile stderr line parsing.
fn run_with_progress(
cmd: &mut Command,
label: &str,
@@ -877,7 +1029,13 @@ fn run_with_progress(
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())?;
// Ask ffmpeg to emit machine-readable progress on stdout. The output is
// "key=value" lines terminated by "progress=continue" / "progress=end".
cmd.arg("-progress").arg("pipe:1");
let output = run_impl(
cmd, label, pass, total_passes, duration_secs, fps,
progress_tx.cloned(), cancel.cloned(), true,
)?;
if !output.status.success() {
bail!(ffmpeg_failure_message(label, output.status, &output.stderr));
}
@@ -915,9 +1073,10 @@ fn run_impl(
progress_pass: u8,
progress_total_passes: u8,
progress_duration_secs: f64,
progress_fps: u32,
_progress_fps: u32,
progress_tx: Option<Sender<EncodeProgress>>,
cancel: Option<Arc<AtomicBool>>,
read_stdout: bool,
) -> Result<std::process::Output> {
use std::process::Stdio;
@@ -930,40 +1089,57 @@ fn run_impl(
}
tracing::debug!("{}", printable.to_string_lossy());
// When we asked ffmpeg for `-progress pipe:1`, stdout carries the stable
// key=value stream; stderr still carries errors. Otherwise null stdout.
let stdout_cfg = if read_stdout { Stdio::piped() } else { Stdio::null() };
let mut child = cmd
.stdout(Stdio::null())
.stdout(stdout_cfg)
.stderr(Stdio::piped())
.spawn()
.with_context(|| format!("spawning ffmpeg for {label}"))?;
let stderr = child.stderr.take();
let stdout = if read_stdout { child.stdout.take() } else { None };
let tx = progress_tx.clone();
let mut stderr_handle: Option<thread::JoinHandle<Vec<u8>>> = stderr.map(move |serr| {
// Progress reader: parse the key=value stream from stdout. Each update
// block ends with "progress=continue" or "progress=end". We track the
// latest out_time_us and emit a percent when progress= is seen.
let mut stdout_handle: Option<thread::JoinHandle<()>> = stdout.map(|out| {
let tx = tx.as_ref().map(|t| t.clone());
let encode_dur = progress_duration_secs;
let fps = progress_fps;
let encode_dur_us = (progress_duration_secs * 1_000_000.0).max(1.0);
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);
let reader = BufReader::new(out);
let mut last_out_time_us: f64 = 0.0;
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,
});
if let Some((key, value)) = parse_progress_kv(&line) {
if key == "out_time_us" {
last_out_time_us = value;
} else if key == "progress" {
let percent = (last_out_time_us / encode_dur_us * 100.0).clamp(0.0, 100.0);
if let Some(ref sender) = tx {
let _ = sender.send(EncodeProgress {
pass,
total_passes,
percent,
});
}
}
}
}
})
});
// Stderr reader: collect bytes for diagnostics. No more frame regex.
let mut stderr_handle: Option<thread::JoinHandle<Vec<u8>>> = stderr.map(move |serr| {
thread::spawn(move || {
let mut collected = Vec::new();
use std::io::Read;
let mut s = serr;
let _ = s.read_to_end(&mut collected);
collected
})
});
@@ -973,14 +1149,14 @@ fn run_impl(
if c.load(Ordering::Relaxed) {
let _ = child.kill();
let _ = child.wait();
if let Some(h) = stderr_handle.take() {
let _ = h.join();
}
if let Some(h) = stdout_handle.take() { let _ = h.join(); }
if let Some(h) = stderr_handle.take() { let _ = h.join(); }
bail!("export cancelled");
}
}
match child.try_wait() {
Ok(Some(status)) => {
if let Some(h) = stdout_handle.take() { let _ = h.join(); }
let stderr_bytes = stderr_handle.take()
.and_then(|h| h.join().ok())
.unwrap_or_default();
@@ -998,20 +1174,15 @@ fn run_impl(
}
}
/// 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()
/// Parse one line of ffmpeg `-progress` output into (key, numeric value).
/// Lines are `key=value`. For `out_time_us` the value is integer microseconds;
/// for `progress` the value is non-numeric ("continue"/"end") so we return 0.0
/// and the caller discriminates on the key.
fn parse_progress_kv(line: &str) -> Option<(&str, f64)> {
let line = line.trim();
let (key, value) = line.split_once('=')?;
let num = value.trim().parse::<f64>().unwrap_or(0.0);
Some((key, num))
}
#[cfg(test)]
@@ -1091,16 +1262,38 @@ mod tests {
}
#[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);
fn parse_progress_kv_out_time_us() {
assert_eq!(parse_progress_kv("out_time_us=5000000"), Some(("out_time_us", 5_000_000.0)));
}
#[test]
fn parse_progress_kv_progress_continue_returns_zero() {
// "continue" is non-numeric, so value parses to 0.0; the key is what matters.
assert_eq!(parse_progress_kv("progress=continue"), Some(("progress", 0.0)));
assert_eq!(parse_progress_kv("progress=end"), Some(("progress", 0.0)));
}
#[test]
fn parse_progress_kv_ignores_non_kv() {
assert_eq!(parse_progress_kv("not a kv line"), None);
assert_eq!(parse_progress_kv("no_equals_here"), None);
}
#[test]
fn parse_progress_kv_handles_other_keys() {
assert_eq!(parse_progress_kv("frame=123"), Some(("frame", 123.0)));
assert_eq!(parse_progress_kv("fps=30.0"), Some(("fps", 30.0)));
assert_eq!(parse_progress_kv("bitrate=N/A"), Some(("bitrate", 0.0)));
}
#[test]
fn gif_scale_forces_bt709_rgb() {
let filter = gif_rgb_scale_filter(640);
assert!(filter.contains("in_color_matrix=bt709"));
assert!(filter.contains("in_range=tv"));
assert!(filter.contains("in_transfer=bt709"));
assert!(filter.contains("out_transfer=srgb"));
assert!(filter.contains("format=rgb24"));
}
#[test]