format the rust sources and split the functions that pushed over the line

This commit is contained in:
2026-09-21 06:33:23 +03:00
parent 205f68222c
commit 4125d509cc
10 changed files with 611 additions and 326 deletions
+230 -95
View File
@@ -147,12 +147,7 @@ fn trim_offset(req: &TranscodeRequest) -> f64 {
req.trim_start_secs.filter(|s| *s > 0.001).unwrap_or(0.0)
}
fn click_filters(
clicks: &[Click],
clip_w: u32,
clip_h: u32,
time_offset: f64,
) -> Option<String> {
fn click_filters(clicks: &[Click], clip_w: u32, clip_h: u32, time_offset: f64) -> Option<String> {
if clicks.is_empty() {
return None;
}
@@ -326,10 +321,7 @@ fn probe_encoders(ffmpeg: &Path) -> Result<HashSet<String>> {
Ok(set)
}
fn pick_audio_codec<'a>(
encoders: &HashSet<String>,
candidates: &[&'a str],
) -> Result<&'a str> {
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);
@@ -379,7 +371,12 @@ 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(crate) fn all_unknown() -> Self {
Self { h264: true, h265: true, vp9: true, av1: true }
Self {
h264: true,
h265: true,
vp9: true,
av1: true,
}
}
}
@@ -410,6 +407,17 @@ fn video_bitrate_kbps(req: &TranscodeRequest) -> Result<u64> {
Ok(kbps.max(16))
}
/// Chain the crop and the click highlights into the single `-vf` argument the
/// two video passes share.
fn combined_video_filter(crop: Option<&String>, clicks: Option<&String>) -> 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,
}
}
fn two_pass_video(
ffmpeg: &Path,
req: &TranscodeRequest,
@@ -427,13 +435,13 @@ fn two_pass_video(
let null_target = if cfg!(windows) { "NUL" } else { "/dev/null" };
let crop = crop_filter(req.crop);
let clicks = click_filters(&req.clicks, req.clip_width, req.clip_height, trim_offset(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 clicks = click_filters(
&req.clicks,
req.clip_width,
req.clip_height,
trim_offset(req),
);
let combined_vf = combined_video_filter(crop.as_ref(), clicks.as_ref());
let mut pass1 = Command::new(ffmpeg);
pass1
@@ -478,7 +486,12 @@ fn two_pass_video(
if let Some(ref t) = tx {
// The receiver is gone only if the UI navigated away; the encode is
// unaffected, so the send error is deliberately discarded.
t.send(EncodeProgress { pass: 1, total_passes: 2, percent: 100.0 }).ok();
t.send(EncodeProgress {
pass: 1,
total_passes: 2,
percent: 100.0,
})
.ok();
}
let mut pass2 = Command::new(ffmpeg);
@@ -588,7 +601,8 @@ fn calibrate_via_sample(
let aspect = aspect_ratio(req.clip_width, req.clip_height);
let sample_h = round_u32(f64::from(est_width) / aspect);
let frames = (f64::from(est_fps) * sample_dur).max(1.0);
let measured_bpp = bytes_f64(sample_bytes) / (f64::from(est_width) * f64::from(sample_h) * frames);
let measured_bpp =
bytes_f64(sample_bytes) / (f64::from(est_width) * f64::from(sample_h) * 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;
@@ -604,7 +618,9 @@ fn calibrate_via_sample(
// Recompute target params with the corrected constant. Scale resolution
// by the sqrt of the ratio so file size scales roughly linearly.
let new_width = (round_u32(f64::from(est_width) * ratio.sqrt()) / 2).max(60) * 2;
let new_fps = round_u32(f64::from(est_fps) * ratio.sqrt()).max(1).min(est_fps);
let new_fps = round_u32(f64::from(est_fps) * ratio.sqrt())
.max(1)
.min(est_fps);
Some((new_width.min(1280), new_fps))
}
@@ -625,6 +641,42 @@ fn gif_shrink_factor(mode: GifBudgetMode, ratio: f64) -> f64 {
}
}
/// Spend one retry's shrink factor on whichever knobs the budget mode reduces,
/// keeping the width even (the `*2` after the halving clamp).
fn shrink_gif_params(mode: GifBudgetMode, factor: f64, width: &mut u32, fps: &mut u32) {
match mode {
GifBudgetMode::Resolution => {
*width = (round_u32(f64::from(*width) * factor) / 2).clamp(60, 640) * 2;
}
GifBudgetMode::Framerate => {
*fps = round_u32(f64::from(*fps) * factor).max(1);
}
GifBudgetMode::Balanced => {
*width = (round_u32(f64::from(*width) * factor) / 2).clamp(60, 640) * 2;
*fps = round_u32(f64::from(*fps) * factor).max(1);
}
}
}
/// Refine the retry loop's starting dimensions from a short sample encode, and
/// log what the sample suggested. None when the clip is too short to sample or
/// the sample did not reveal a meaningful gap.
fn gif_calibration(
ffmpeg: &Path,
req: &TranscodeRequest,
width: u32,
fps: u32,
) -> Option<(u32, u32)> {
if req.duration_secs <= 4.0 {
return None;
}
let (w, f) = calibrate_via_sample(ffmpeg, req, width, fps)?;
tracing::info!(
"gif calibration: sample suggested {w}x @ {f}fps (initial was {width}x @ {fps}fps)"
);
Some((w, f))
}
fn encode_gif(ffmpeg: &Path, req: &TranscodeRequest) -> Result<()> {
let budget_input = GifBudgetInput {
gif_colors: req.gif_colors,
@@ -633,20 +685,16 @@ fn encode_gif(ffmpeg: &Path, req: &TranscodeRequest) -> Result<()> {
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 (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;
}
if let Some((w, f)) = gif_calibration(ffmpeg, req, scale_width, effective_fps) {
scale_width = w;
effective_fps = f;
}
let target = req.target_bytes;
@@ -661,7 +709,11 @@ fn encode_gif(ffmpeg: &Path, req: &TranscodeRequest) -> Result<()> {
let mut prev_actual: Option<u64> = None;
for attempt in 0..max_retries {
if req.cancel.as_ref().is_some_and(|c| c.load(Ordering::Relaxed)) {
if req
.cancel
.as_ref()
.is_some_and(|c| c.load(Ordering::Relaxed))
{
bail!("export cancelled");
}
// Last resort: use minimal settings to hit the target
@@ -671,8 +723,12 @@ fn encode_gif(ffmpeg: &Path, req: &TranscodeRequest) -> Result<()> {
}
let pass_start = std::time::Instant::now();
encode_gif_pass(
ffmpeg, req, scale_width, effective_fps,
(u8::try_from(attempt).unwrap_or(0)) + 1, max_attempts,
ffmpeg,
req,
scale_width,
effective_fps,
(u8::try_from(attempt).unwrap_or(0)) + 1,
max_attempts,
)?;
tracing::info!(
attempt = attempt + 1,
@@ -680,8 +736,7 @@ fn encode_gif(ffmpeg: &Path, req: &TranscodeRequest) -> Result<()> {
"gif pass finished"
);
let actual = std::fs::metadata(&req.output)
.map_or(0, |m| m.len());
let actual = std::fs::metadata(&req.output).map_or(0, |m| m.len());
if actual == 0 {
bail!("gif output is empty");
@@ -693,7 +748,9 @@ fn encode_gif(ffmpeg: &Path, req: &TranscodeRequest) -> Result<()> {
if ratio >= 1.0 {
tracing::info!(
"gif encode done on attempt {}: {} bytes (target {})",
attempt + 1, actual, target
attempt + 1,
actual,
target
);
return Ok(());
}
@@ -725,19 +782,12 @@ fn encode_gif(ffmpeg: &Path, req: &TranscodeRequest) -> Result<()> {
}
}
match req.gif_budget_mode {
GifBudgetMode::Resolution => {
// Halve before clamping so the *2 keeps the width even.
scale_width = (round_u32(f64::from(scale_width) * factor) / 2).clamp(60, 640) * 2;
}
GifBudgetMode::Framerate => {
effective_fps = round_u32(f64::from(effective_fps) * factor).max(1);
}
GifBudgetMode::Balanced => {
scale_width = (round_u32(f64::from(scale_width) * factor) / 2).clamp(60, 640) * 2;
effective_fps = round_u32(f64::from(effective_fps) * factor).max(1);
}
}
shrink_gif_params(
req.gif_budget_mode,
factor,
&mut scale_width,
&mut effective_fps,
);
tracing::info!(
"gif retry {}: was {} bytes (target {}), adjusting to {}x @ {}fps (factor={:.2})",
@@ -773,9 +823,14 @@ fn encode_gif_pass(
let crop_prefix = crop_filter(req.crop)
.map(|c| format!("{c},"))
.unwrap_or_default();
let click_prefix = click_filters(&req.clicks, req.clip_width, req.clip_height, trim_offset(req))
.map(|c| format!("{c},"))
.unwrap_or_default();
let click_prefix = click_filters(
&req.clicks,
req.clip_width,
req.clip_height,
trim_offset(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();
@@ -800,7 +855,10 @@ fn encode_gif_pass(
d = dither,
);
tracing::info!("gif encode: fps={effective_fps} scale={scale_width} colors={} filter={filter_complex}", req.gif_colors);
tracing::info!(
"gif encode: fps={effective_fps} scale={scale_width} colors={} filter={filter_complex}",
req.gif_colors
);
let mut encode = Command::new(ffmpeg);
encode
@@ -850,7 +908,9 @@ pub(crate) fn gif_params(input: &GifBudgetInput, clip_width: u32, clip_height: u
// 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 = (f64::from(input.gif_colors) / 256.0).sqrt().clamp(0.15, 1.0);
let color_factor = (f64::from(input.gif_colors) / 256.0)
.sqrt()
.clamp(0.15, 1.0);
let bytes_per_pixel_per_frame = 0.2 * color_factor;
let target_bytes = bytes_f64(input.target_bytes);
let requested_fps = f64::from(input.fps);
@@ -977,7 +1037,8 @@ pub(crate) fn render_gif_preview(
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
gif_rgb_scale_filter(target_width),
gif_colors
);
let mut gen = Command::new(ffmpeg);
gen.arg("-y")
@@ -994,10 +1055,12 @@ pub(crate) fn render_gif_preview(
// Apply palette to the target frame
let use_filter = format!(
"{}[x];[x][1:v]paletteuse=dither={}",
gif_rgb_scale_filter(target_width), gif_dither
gif_rgb_scale_filter(target_width),
gif_dither
);
let mut encode = Command::new(ffmpeg);
encode.arg("-y")
encode
.arg("-y")
.arg("-hide_banner")
.args(["-ss", &format!("{midpoint_secs}")])
.arg("-i")
@@ -1017,10 +1080,13 @@ pub(crate) fn render_gif_preview(
/// 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{sample_start:.3}-d{sample_dur:.3}"
)
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{sample_start:.3}-d{sample_dur:.3}")
}
/// Remove old `preview-palette-*.png` files so only the current key remains.
@@ -1056,9 +1122,7 @@ pub(crate) fn extract_thumbnails(
let crop_prefix = crop_filter(crop)
.map(|c| format!("{c},"))
.unwrap_or_default();
let filter = format!(
"{crop_prefix}fps={fps},scale=120:-1:flags=lanczos"
);
let filter = format!("{crop_prefix}fps={fps},scale=120:-1:flags=lanczos");
let pattern = out_dir.join("thumb-%05d.png");
let mut cmd = Command::new(ffmpeg);
@@ -1123,8 +1187,8 @@ pub(crate) 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.display()))?;
let mut f =
std::fs::File::open(seg).with_context(|| format!("opening {}", seg.display()))?;
std::io::copy(&mut f, &mut out).context("copying audio segment")?;
}
out.flush()?;
@@ -1133,7 +1197,9 @@ pub(crate) fn concat_pcm(segments: &[PathBuf], output: &Path) -> Result<()> {
struct TempFileGuard(PathBuf);
impl Drop for TempFileGuard {
fn drop(&mut self) { drop(std::fs::remove_file(&self.0)); }
fn drop(&mut self) {
drop(std::fs::remove_file(&self.0));
}
}
pub(crate) fn concat_segments(ffmpeg: &Path, segments: &[PathBuf], output: &Path) -> Result<()> {
@@ -1208,8 +1274,15 @@ fn run_with_progress(
// "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,
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));
@@ -1221,8 +1294,7 @@ fn ffmpeg_failure_message(label: &str, status: std::process::ExitStatus, stderr:
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")
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") {
@@ -1242,6 +1314,19 @@ fn ffmpeg_failure_message(label: &str, status: std::process::ExitStatus, stderr:
}
}
/// Render an ffmpeg invocation for the log. A failed encode is only diagnosable
/// from the exact argument list, and the arg vector is not printable on its own.
fn describe_command(label: &str, cmd: &Command) -> String {
let mut printable = OsString::from(label);
printable.push(": ");
printable.push(cmd.get_program());
for arg in cmd.get_args() {
printable.push(" ");
printable.push(arg);
}
printable.to_string_lossy().into_owned()
}
// Consumes the progress sender and the cancel flag: both are moved into the
// reader threads this spawns, so borrowing them here would not typecheck.
// The argument count matches run_with_progress, its only caller.
@@ -1266,18 +1351,15 @@ fn run_impl(
) -> 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());
tracing::debug!("{}", describe_command(label, cmd));
// 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 stdout_cfg = if read_stdout {
Stdio::piped()
} else {
Stdio::null()
};
let mut child = cmd
.stdout(stdout_cfg)
.stderr(Stdio::piped())
@@ -1285,7 +1367,11 @@ fn run_impl(
.with_context(|| format!("spawning ffmpeg for {label}"))?;
let stderr = child.stderr.take();
let stdout = if read_stdout { child.stdout.take() } else { None };
let stdout = if read_stdout {
child.stdout.take()
} else {
None
};
let tx = progress_tx.clone();
// Progress reader: parse the key=value stream from stdout. Each update
@@ -1343,15 +1429,22 @@ fn run_impl(
if c.load(Ordering::Relaxed) {
drop(child.kill());
drop(child.wait());
if let Some(h) = stdout_handle.take() { drop(h.join()); }
if let Some(h) = stderr_handle.take() { drop(h.join()); }
if let Some(h) = stdout_handle.take() {
drop(h.join());
}
if let Some(h) = stderr_handle.take() {
drop(h.join());
}
bail!("export cancelled");
}
}
match child.try_wait() {
Ok(Some(status)) => {
if let Some(h) = stdout_handle.take() { drop(h.join()); }
let stderr_bytes = stderr_handle.take()
if let Some(h) = stdout_handle.take() {
drop(h.join());
}
let stderr_bytes = stderr_handle
.take()
.and_then(|h| h.join().ok())
.unwrap_or_default();
return Ok(std::process::Output {
@@ -1457,13 +1550,19 @@ mod tests {
#[test]
fn parse_progress_kv_out_time_us() {
assert_eq!(parse_progress_kv("out_time_us=5000000"), Some(("out_time_us", 5_000_000.0)));
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=continue"),
Some(("progress", 0.0))
);
assert_eq!(parse_progress_kv("progress=end"), Some(("progress", 0.0)));
}
@@ -1492,7 +1591,12 @@ mod tests {
#[test]
fn crop_filter_output() {
let rect = CaptureRect { x: 10, y: 20, width: 100, height: 200 };
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())
@@ -1503,7 +1607,12 @@ mod tests {
#[test]
fn click_filters_capped_at_max() {
let clicks: Vec<Click> = (0..100)
.map(|i| Click { time_secs: f64::from(i), x: i, y: i, button: crate::clicks::MouseButton::Left })
.map(|i| Click {
time_secs: f64::from(i),
x: i,
y: i,
button: crate::clicks::MouseButton::Left,
})
.collect();
let filter = click_filters(&clicks, 1920, 1080, 0.0).unwrap();
let count = filter.matches("drawbox").count();
@@ -1515,7 +1624,10 @@ mod tests {
let frame = (1920u32, 1080u32);
// Near each edge, and one dead-centre.
assert_eq!(click_box(2, 2, frame.0, frame.1), Some((0, 0)));
assert_eq!(click_box(1919, 1079, frame.0, frame.1), Some((1920 - BOX_SIZE, 1080 - BOX_SIZE)));
assert_eq!(
click_box(1919, 1079, frame.0, frame.1),
Some((1920 - BOX_SIZE, 1080 - BOX_SIZE))
);
assert_eq!(click_box(960, 540, frame.0, frame.1), Some((948, 528)));
}
@@ -1534,8 +1646,18 @@ mod tests {
#[test]
fn click_filters_drops_clicks_off_frame() {
let clicks = vec![
Click { time_secs: 0.5, x: -620, y: 115, button: crate::clicks::MouseButton::Left },
Click { time_secs: 0.9, x: 500, y: 400, button: crate::clicks::MouseButton::Left },
Click {
time_secs: 0.5,
x: -620,
y: 115,
button: crate::clicks::MouseButton::Left,
},
Click {
time_secs: 0.9,
x: 500,
y: 400,
button: crate::clicks::MouseButton::Left,
},
];
let filter = click_filters(&clicks, 1920, 1080, 0.0).unwrap();
assert_eq!(filter.matches("drawbox").count(), 1);
@@ -1550,7 +1672,12 @@ mod tests {
/// same amount or it fires late by the length of the trim.
#[test]
fn click_times_are_rebased_by_the_trim() {
let clicks = vec![Click { time_secs: 6.0, x: 500, y: 400, button: crate::clicks::MouseButton::Left }];
let clicks = vec![Click {
time_secs: 6.0,
x: 500,
y: 400,
button: crate::clicks::MouseButton::Left,
}];
let untrimmed = click_filters(&clicks, 1920, 1080, 0.0).unwrap();
assert!(untrimmed.contains("between(t,5.950,6.250)"));
let trimmed = click_filters(&clicks, 1920, 1080, 5.0).unwrap();
@@ -1561,7 +1688,12 @@ mod tests {
/// A click that happened before the trimmed window has nothing left to draw.
#[test]
fn clicks_before_the_trim_are_dropped() {
let clicks = vec![Click { time_secs: 1.0, x: 500, y: 400, button: crate::clicks::MouseButton::Left }];
let clicks = vec![Click {
time_secs: 1.0,
x: 500,
y: 400,
button: crate::clicks::MouseButton::Left,
}];
assert!(click_filters(&clicks, 1920, 1080, 5.0).is_none());
}
@@ -1584,7 +1716,10 @@ mod tests {
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}");
assert!(
f > lo && f < hi,
"balanced factor {f} should sit between linear {lo} and sqrt {hi}"
);
}
#[test]