harden gif pipeline, capture, and audio resilience

fix gif calibration (sample deleted before measurement), swap the
budget-mode application so resolution shrinks width not fps, correct the
color factor comment. accumulate gif encode progress across retry
attempts instead of resetting, surface an over-budget result on the done
screen. stream the audio head padding instead of loading it into memory,
detect mid-record audio device loss and offer the existing retry flow,
invalidate the cached encoder list when the ffmpeg binary changes.
add a capture quality setting so 4k screens can record at native res,
try a stream copy before re-encoding when fixing capture timestamps,
park the overlay poll thread when idle, sweep stale config backups, add
a diagnostics tab, and consolidate the preview render debounce.
This commit is contained in:
2026-06-17 23:57:28 +03:00
parent f732cdda4d
commit c3f132507a
9 changed files with 624 additions and 83 deletions
+113 -32
View File
@@ -4,8 +4,9 @@ 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::sync::{Arc, Mutex};
use std::thread;
use std::time::SystemTime;
use anyhow::{anyhow, bail, Context, Result};
@@ -167,14 +168,41 @@ fn require_video_codec<'a>(
}
}
use std::sync::OnceLock;
/// Cached encoder list keyed on the ffmpeg binary's mtime. The bootstrap flow
/// lets users drop their own ffmpeg.exe into bin/, and a build swap mid-session
/// must be picked up - so we re-probe when the file changes rather than caching
/// for the whole process lifetime.
static ENCODER_CACHE: Mutex<Option<EncoderCacheEntry>> = Mutex::new(None);
static ENCODER_CACHE: OnceLock<HashSet<String>> = OnceLock::new();
struct EncoderCacheEntry {
ffmpeg_mtime: SystemTime,
encoders: HashSet<String>,
}
fn list_encoders(ffmpeg: &Path) -> Result<&'static HashSet<String>> {
if let Some(cached) = ENCODER_CACHE.get() {
return Ok(cached);
fn list_encoders(ffmpeg: &Path) -> Result<HashSet<String>> {
let mtime = std::fs::metadata(ffmpeg)
.and_then(|m| m.modified())
.unwrap_or(SystemTime::UNIX_EPOCH);
if let Ok(guard) = ENCODER_CACHE.lock() {
if let Some(entry) = guard.as_ref() {
if entry.ffmpeg_mtime == mtime {
return Ok(entry.encoders.clone());
}
}
}
let set = probe_encoders(ffmpeg)?;
if let Ok(mut guard) = ENCODER_CACHE.lock() {
*guard = Some(EncoderCacheEntry {
ffmpeg_mtime: mtime,
encoders: set.clone(),
});
}
Ok(set)
}
fn probe_encoders(ffmpeg: &Path) -> Result<HashSet<String>> {
let out = Command::new(ffmpeg)
.args(["-hide_banner", "-encoders"])
.output()
@@ -195,8 +223,7 @@ fn list_encoders(ffmpeg: &Path) -> Result<&'static HashSet<String>> {
}
set.insert(name.to_string());
}
let _ = ENCODER_CACHE.set(set);
Ok(ENCODER_CACHE.get().unwrap())
Ok(set)
}
fn pick_audio_codec<'a>(
@@ -433,8 +460,11 @@ fn calibrate_via_sample(
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);
let result = encode_gif_pass(ffmpeg, &sample_req, est_width, est_fps, 1, 1);
// Defer cleanup until we've measured the sample. Earlier versions removed
// the file here, which made the metadata read below always fail and the
// whole calibration path silently no-op.
let _guard = TempFileGuard(sample_path.clone());
if result.is_err() {
return None;
}
@@ -472,6 +502,23 @@ fn calibrate_via_sample(
Some((new_width.min(1280), new_fps))
}
/// Per-mode raw shrink factor (before clamping to 0.6..0.9) given the
/// target/actual ratio. Bytes scale as width*height*fps; with fixed aspect,
/// width drives bytes quadratically and fps linearly, so the factor must
/// match the dimension it is applied to.
fn gif_shrink_factor(mode: GifBudgetMode, ratio: f64) -> f64 {
match mode {
GifBudgetMode::Resolution => ratio.sqrt(),
GifBudgetMode::Framerate => ratio,
GifBudgetMode::Balanced => {
// Split the required reduction between resolution and fps so we
// reduce both proportionally rather than halving resolution alone.
let half = 0.5_f64;
(ratio * (1.0 - half) + ratio.sqrt() * half).clamp(0.1, 1.0)
}
}
}
fn encode_gif(ffmpeg: &Path, req: &TranscodeRequest) -> Result<()> {
let budget_input = GifBudgetInput {
gif_colors: req.gif_colors,
@@ -499,8 +546,11 @@ fn encode_gif(ffmpeg: &Path, req: &TranscodeRequest) -> Result<()> {
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.
// Cap at 12 to avoid runaway loops on pathological inputs.
// Cap at 12 to avoid runaway loops on pathological inputs. This also drives
// the progress bar: each attempt is one segment, so the bar accumulates
// across retries instead of resetting.
let max_retries = ((req.duration_secs / 5.0).ceil() as u32 + 4).clamp(5, 12);
let max_attempts = max_retries as u8;
let mut prev_actual: Option<u64> = None;
@@ -514,7 +564,10 @@ fn encode_gif(ffmpeg: &Path, req: &TranscodeRequest) -> Result<()> {
effective_fps = 1;
}
let pass_start = std::time::Instant::now();
encode_gif_pass(ffmpeg, req, scale_width, effective_fps)?;
encode_gif_pass(
ffmpeg, req, scale_width, effective_fps,
(attempt as u8) + 1, max_attempts,
)?;
tracing::info!(
attempt = attempt + 1,
elapsed_ms = pass_start.elapsed().as_millis(),
@@ -544,18 +597,11 @@ fn encode_gif(ffmpeg: &Path, req: &TranscodeRequest) -> Result<()> {
// 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)
}
};
// Bytes scale as width*height*fps. With fixed aspect, width drives
// bytes quadratically (width*height ~ width^2) and fps linearly, so
// the shrink factor must match the dimension it's applied to: sqrt
// for resolution, linear for framerate.
let raw_factor = gif_shrink_factor(req.gif_budget_mode, ratio);
let mut factor = raw_factor.clamp(0.6, 0.9);
// Track trend across attempts. If shrinking settings did not shrink
@@ -576,14 +622,14 @@ fn encode_gif(ffmpeg: &Path, req: &TranscodeRequest) -> Result<()> {
match req.gif_budget_mode {
GifBudgetMode::Resolution => {
effective_fps = ((effective_fps as f64 * factor).round() as u32).max(1);
}
GifBudgetMode::Framerate => {
scale_width = ((scale_width as f64 * factor).round() as u32 / 2)
.max(60)
.min(1280)
* 2;
}
GifBudgetMode::Framerate => {
effective_fps = ((effective_fps as f64 * factor).round() as u32).max(1);
}
GifBudgetMode::Balanced => {
scale_width = ((scale_width as f64 * factor).round() as u32 / 2)
.max(60)
@@ -621,6 +667,8 @@ fn encode_gif_pass(
req: &TranscodeRequest,
scale_width: u32,
effective_fps: u32,
attempt: u8,
max_attempts: u8,
) -> Result<()> {
let crop_prefix = crop_filter(req.crop)
.map(|c| format!("{c},"))
@@ -668,8 +716,8 @@ fn encode_gif_pass(
run_with_progress(
&mut encode,
"gif encode",
1,
1,
attempt,
max_attempts,
req.duration_secs,
effective_fps,
req.progress_tx.as_ref(),
@@ -699,8 +747,9 @@ pub fn gif_params(input: &GifBudgetInput, clip_width: u32, clip_height: u32) ->
// 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
// Fewer colors = better compression. Adjust proportionally to the sqrt of the color
// fraction (LZW code width tracks palette depth roughly logarithmically).
// 256 colors = 1.0x, 128 = ~0.71x, 64 = 0.5x, 32 = ~0.35x, 16 = 0.25x, 2 = ~0.13x
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;
@@ -1167,7 +1216,7 @@ fn run_impl(
});
}
Ok(None) => {
std::thread::sleep(std::time::Duration::from_millis(50));
std::thread::sleep(std::time::Duration::from_millis(20));
}
Err(e) => bail!("waiting for ffmpeg: {e}"),
}
@@ -1319,4 +1368,36 @@ mod tests {
let count = filter.matches("drawbox").count();
assert_eq!(count, MAX_CLICK_HIGHLIGHTS);
}
#[test]
fn gif_shrink_factor_resolution_uses_sqrt() {
// ratio 0.25 -> halving the *width* (which quarters pixels) needs sqrt(0.25)=0.5
let f = gif_shrink_factor(GifBudgetMode::Resolution, 0.25);
assert!((f - 0.5).abs() < 1e-9);
}
#[test]
fn gif_shrink_factor_framerate_is_linear() {
// ratio 0.5 -> halving fps needs factor 0.5
let f = gif_shrink_factor(GifBudgetMode::Framerate, 0.5);
assert!((f - 0.5).abs() < 1e-9);
}
#[test]
fn gif_shrink_factor_balanced_between_sqrt_and_linear() {
let f = gif_shrink_factor(GifBudgetMode::Balanced, 0.25);
let lo = 0.25_f64;
let hi = 0.5_f64; // sqrt(0.25)
assert!(f > lo && f < hi, "balanced factor {f} should sit between linear {lo} and sqrt {hi}");
}
#[test]
fn gif_color_factor_matches_comment_values() {
// comment claims: 256=1.0x, 128=~0.71x, 64=0.5x, 32=~0.35x, 16=0.25x
let cf = |colors: u16| (colors as f64 / 256.0).sqrt().clamp(0.15, 1.0);
assert!((cf(256) - 1.0).abs() < 1e-9);
assert!((cf(128) - 2f64.sqrt() / 2.0).abs() < 1e-9); // ~0.707
assert!((cf(64) - 0.5).abs() < 1e-9);
assert!((cf(16) - 0.25).abs() < 1e-9);
}
}