route the size and byte maths through saturating helpers

This commit is contained in:
2026-09-21 01:20:11 +03:00
parent 7c577eafd7
commit cd583ba02b
3 changed files with 46 additions and 21 deletions
+43 -18
View File
@@ -17,6 +17,33 @@ use crate::CaptureRect;
// Used both for bitrate budget calculation and final mux. Must be consistent.
const AUDIO_BITRATE_KBPS: u64 = 192;
// The GIF budget maths works in f64 but every result is a pixel count, a frame
// rate or a byte count, all of which are far inside these limits. Saturating
// here keeps `as` honest - a NaN or a runaway estimate clamps instead of
// wrapping to a nonsense dimension - and documents the bound once rather than
// at each of the twenty-odd call sites.
pub(crate) fn round_u32(v: f64) -> u32 {
// NaN fails every comparison, so `min` leaves it NaN and `as` turns that
// into 0; the clamp then bounds the top end.
#[allow(
clippy::cast_possible_truncation,
reason = "value is clamped into u32 range on the line above the cast"
)]
let out = v.round().clamp(0.0, f64::from(u32::MAX)) as u32;
out
}
pub(crate) fn round_u64(v: f64) -> u64 {
// u64::MAX is not exactly representable as f64; the literal below is the
// nearest value under it, which is close enough for a byte budget.
#[allow(
clippy::cast_possible_truncation,
reason = "value is clamped into u64 range on the line above the cast"
)]
let out = v.round().clamp(0.0, 18_446_744_073_709_551_615.0) as u64;
out
}
/// Progress update sent during encoding.
/// pass: 1-based pass number (1 or 2 for two-pass video, 1 for GIF).
/// `total_passes`: total number of passes.
@@ -322,7 +349,7 @@ fn video_bitrate_kbps(req: &TranscodeRequest) -> Result<u64> {
if video_bits <= 0.0 {
bail!("target size too small to fit audio at {AUDIO_BITRATE_KBPS}k - increase target or strip audio");
}
let kbps = (video_bits / 1000.0 / req.duration_secs).round() as u64;
let kbps = round_u64(video_bits / 1000.0 / req.duration_secs);
Ok(kbps.max(16))
}
@@ -501,7 +528,7 @@ fn calibrate_via_sample(
// 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 = (f64::from(est_width) / aspect).round() as u32;
let sample_h = round_u32(f64::from(est_width) / aspect);
let frames = (f64::from(est_fps) * sample_dur).max(1.0);
let measured_bpp = sample_bytes as f64 / (f64::from(est_width) * f64::from(sample_h) * frames);
// Blend toward the assumed 0.2 constant - don't over-trust a 2s sample.
@@ -518,8 +545,8 @@ 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 = ((f64::from(est_width) * ratio.sqrt()).round() as u32 / 2).max(60) * 2;
let new_fps = ((f64::from(est_fps) * ratio.sqrt()).round() as u32).max(1).min(est_fps);
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);
Some((new_width.min(1280), new_fps))
}
@@ -570,7 +597,7 @@ fn encode_gif(ffmpeg: &Path, req: &TranscodeRequest) -> Result<()> {
// 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_retries = (round_u32((req.duration_secs / 5.0).ceil()) + 4).clamp(5, 12);
let max_attempts = max_retries as u8;
let mut prev_actual: Option<u64> = None;
@@ -643,16 +670,14 @@ 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 =
((f64::from(scale_width) * factor).round() as u32 / 2).clamp(60, 640) * 2;
scale_width = (round_u32(f64::from(scale_width) * factor) / 2).clamp(60, 640) * 2;
}
GifBudgetMode::Framerate => {
effective_fps = ((f64::from(effective_fps) * factor).round() as u32).max(1);
effective_fps = round_u32(f64::from(effective_fps) * factor).max(1);
}
GifBudgetMode::Balanced => {
scale_width =
((f64::from(scale_width) * factor).round() as u32 / 2).clamp(60, 640) * 2;
effective_fps = ((f64::from(effective_fps) * factor).round() as u32).max(1);
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);
}
}
@@ -776,12 +801,12 @@ pub(crate) fn gif_params(input: &GifBudgetInput, clip_width: u32, clip_height: u
match input.gif_budget_mode {
GifBudgetMode::Resolution => {
let max_w = f64::from(clip_width.min(1280)).clamp(120.0, 1280.0);
let w = (max_w / 2.0).round() as u32 * 2;
let h = (f64::from(w) / aspect).round() as u32;
let w = round_u32(max_w / 2.0) * 2;
let h = round_u32(f64::from(w) / aspect);
let pixels_per_frame = f64::from(w) * f64::from(h);
let bytes_per_frame = pixels_per_frame * bytes_per_pixel_per_frame;
let max_frames = (target_bytes / bytes_per_frame).floor().max(1.0);
let min_fps = (max_frames / duration).max(1.0).round() as u32;
let min_fps = round_u32((max_frames / duration).max(1.0));
let fps = (input.fps).min(min_fps).max(1);
(w, fps)
}
@@ -789,7 +814,7 @@ pub(crate) fn gif_params(input: &GifBudgetInput, clip_width: u32, clip_height: u
let frames = (requested_fps * duration).max(1.0);
let budget = target_bytes / (frames * bytes_per_pixel_per_frame);
let w = (budget * aspect).sqrt();
let w = (w.clamp(120.0, 1280.0).round() as u32 / 2) * 2;
let w = (round_u32(w.clamp(120.0, 1280.0)) / 2) * 2;
(w, input.fps)
}
GifBudgetMode::Balanced => {
@@ -804,8 +829,8 @@ pub(crate) fn gif_params(input: &GifBudgetInput, clip_width: u32, clip_height: u
};
let scale = scale.max(0.1);
let w = ((f64::from(clip_width) * scale).round() as u32 / 2).max(60) * 2;
let fps = ((requested_fps * scale).round() as u32).max(1).min(input.fps);
let w = (round_u32(f64::from(clip_width) * scale) / 2).max(60) * 2;
let fps = round_u32(requested_fps * scale).max(1).min(input.fps);
(w, fps)
}
}
@@ -824,7 +849,7 @@ pub(crate) fn gif_height_for_width(width: u32, clip_width: u32, clip_height: u32
if width == 0 {
0
} else {
((f64::from(width) / aspect).round() as u32 / 2) * 2
(round_u32(f64::from(width) / aspect) / 2) * 2
}
}