gif encode retry loop (up to 5 passes, adjusts resolution/fps until within 15% of target size), aspect ratio enforcement via rust command instead of unreliable cross-window emit
This commit is contained in:
+61
-1
@@ -342,8 +342,68 @@ fn cleanup_pass_logs(stem: &Path) {
|
||||
}
|
||||
|
||||
fn encode_gif(ffmpeg: &Path, req: &TranscodeRequest) -> Result<()> {
|
||||
let (mut scale_width, mut effective_fps) = gif_params(req, req.clip_width, req.clip_height);
|
||||
let target = req.target_bytes;
|
||||
let max_retries = 5;
|
||||
|
||||
for attempt in 0..max_retries {
|
||||
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 within 15% of target
|
||||
if ratio >= 0.85 && ratio <= 1.15 {
|
||||
tracing::info!(
|
||||
"gif encode done on attempt {}: {} bytes (target {})",
|
||||
attempt + 1, actual, target
|
||||
);
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
// Adjust for next attempt
|
||||
if ratio < 0.85 {
|
||||
// Too big - scale down
|
||||
let factor = ratio.sqrt(); // sqrt because both dims scale
|
||||
scale_width = ((scale_width as f64 * factor).round() as u32 / 2).max(60) * 2;
|
||||
if req.gif_budget_mode == GifBudgetMode::Framerate {
|
||||
effective_fps = ((effective_fps as f64 * factor).round() as u32).max(1);
|
||||
}
|
||||
} else {
|
||||
// Too small - scale up
|
||||
let factor = ratio.sqrt().min(2.0); // cap at 2x per retry
|
||||
let new_w = ((scale_width as f64 * factor).round() as u32 / 2).min(1280) * 2;
|
||||
if new_w == scale_width {
|
||||
// Can't scale up resolution more, try fps
|
||||
effective_fps = ((effective_fps as f64 * factor).round() as u32).min(req.fps);
|
||||
}
|
||||
scale_width = new_w;
|
||||
}
|
||||
|
||||
tracing::info!(
|
||||
"gif retry {}: was {} bytes (target {}), adjusting to {}x @ {}fps",
|
||||
attempt + 1, actual, target, scale_width, effective_fps
|
||||
);
|
||||
}
|
||||
|
||||
// Final attempt was the best we could do
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn encode_gif_pass(
|
||||
ffmpeg: &Path,
|
||||
req: &TranscodeRequest,
|
||||
scale_width: u32,
|
||||
effective_fps: u32,
|
||||
) -> Result<()> {
|
||||
let palette_path = req.scratch_dir.join("palette.png");
|
||||
let (scale_width, effective_fps) = gif_params(req, req.clip_width, req.clip_height);
|
||||
let crop_prefix = crop_filter(req.crop)
|
||||
.map(|c| format!("{c},"))
|
||||
.unwrap_or_default();
|
||||
|
||||
Reference in New Issue
Block a user