Files
bytesize/src-tauri/src/encode.rs
T

1735 lines
59 KiB
Rust

use std::collections::HashSet;
use std::ffi::{OsStr, OsString};
use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc::Sender;
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::SystemTime;
use anyhow::{anyhow, bail, Context, Result};
use crate::clicks::Click;
use crate::config::{Format, GifBudgetMode, GifDither, Mp4Codec, WebmCodec};
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"
)]
#[allow(
clippy::cast_sign_loss,
reason = "value is clamped to 0.0 or above 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"
)]
#[allow(
clippy::cast_sign_loss,
reason = "value is clamped to 0.0 or above on the line above the cast"
)]
let out = v.round().clamp(0.0, 18_446_744_073_709_551_615.0) as u64;
out
}
/// Round a logical-pixel measurement to the signed int a Win32 call wants.
/// DPI scales here are at most a handful, so the result is nothing like i32
/// range; clamping just makes that explicit.
pub(crate) fn round_i32(v: f64) -> i32 {
#[allow(
clippy::cast_possible_truncation,
reason = "value is clamped into i32 range on the line above the cast"
)]
let out = v.round().clamp(f64::from(i32::MIN), f64::from(i32::MAX)) as i32;
out
}
/// Byte counts and bitrates are many orders of magnitude below 2^53, so f64
/// holds them exactly. This is the single place that conversion is justified.
pub(crate) fn bytes_f64(v: u64) -> f64 {
#[allow(
clippy::cast_precision_loss,
reason = "byte counts and bitrates in this app are far below f64's exact-integer range"
)]
let out = v as f64;
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.
/// percent: 0.0 to 100.0.
#[derive(Debug, Clone, Copy, serde::Serialize)]
pub(crate) struct EncodeProgress {
pub pass: u8,
pub total_passes: u8,
pub percent: f64,
}
#[derive(Debug, Clone)]
pub(crate) struct TranscodeRequest {
pub input: PathBuf,
pub output: PathBuf,
pub format: Format,
pub target_bytes: u64,
pub duration_secs: f64,
pub fps: u32,
pub keep_audio: bool,
pub gif_dither: GifDither,
pub webm_codec: WebmCodec,
pub mp4_codec: Mp4Codec,
pub scratch_dir: PathBuf,
pub crop: Option<CaptureRect>,
pub gif_budget_mode: GifBudgetMode,
pub gif_colors: u16,
pub deleted_frame_indices: Vec<u32>,
pub trim_start_secs: Option<f64>,
pub trim_end_secs: Option<f64>,
pub clicks: Vec<Click>,
pub clip_width: u32,
pub clip_height: u32,
/// Optional channel to report encoding progress.
#[doc(hidden)]
pub progress_tx: Option<Sender<EncodeProgress>>,
/// Optional cancel signal. When set to true, ffmpeg will be killed.
#[doc(hidden)]
pub cancel: Option<Arc<AtomicBool>>,
}
const MAX_CLICK_HIGHLIGHTS: usize = 50;
const BOX_SIZE: i32 = 24;
const BOX_HALF: i32 = BOX_SIZE / 2;
/// What `click_filters` needs to place the highlight boxes.
fn click_box(clip_x: i32, clip_y: i32, clip_w: u32, clip_h: u32) -> Option<(i32, i32)> {
let vw = clip_w.cast_signed();
let vh = clip_h.cast_signed();
// Only suppress when the point lies entirely outside the frame, so a click
// just inside an edge still gets the sliver of box that is visible.
let outside = clip_x + BOX_HALF <= 0
|| clip_y + BOX_HALF <= 0
|| clip_x - BOX_HALF >= vw
|| clip_y - BOX_HALF >= vh;
if outside {
return None;
}
let x = (clip_x - BOX_HALF).clamp(0, (vw - BOX_SIZE).max(0));
let y = (clip_y - BOX_HALF).clamp(0, (vh - BOX_SIZE).max(0));
Some((x, y))
}
/// The time `apply_trim` cuts off the head of the clip. A seek rebases the
/// filter graph's timestamps to zero, so anything recorded against clip time -
/// the click highlights - has to be shifted by the same amount or it lands late
/// by the length of the trim.
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> {
if clicks.is_empty() {
return None;
}
let mut parts: Vec<String> = Vec::new();
let clicks_to_render = clicks.len().min(MAX_CLICK_HIGHLIGHTS);
if clicks.len() > MAX_CLICK_HIGHLIGHTS {
tracing::warn!(
"{} click events recorded, only first {} will be highlighted",
clicks.len(),
MAX_CLICK_HIGHLIGHTS
);
}
// clicks_to_render is clicks.len().min(MAX_CLICK_HIGHLIGHTS), and get()
// falls back to the whole slice rather than panicking.
for click in clicks.get(..clicks_to_render).unwrap_or(clicks) {
// Clicks recorded outside the capture region (or outside the crop) land
// behind the origin. Clamping here keeps the box inside the frame;
// without it the offsets went negative and drawbox dropped the box.
let Some((x, y)) = click_box(click.x, click.y, clip_w, clip_h) else {
continue;
};
let t = click.time_secs - time_offset;
if t + 0.25 < 0.0 {
continue;
}
let t1 = (t - 0.05).max(0.0);
let t2 = t + 0.25;
let color = match click.button {
crate::clicks::MouseButton::Left => "yellow@0.6",
crate::clicks::MouseButton::Right => "blue@0.6",
crate::clicks::MouseButton::Middle => "green@0.6",
};
parts.push(format!(
"drawbox=x={x}:y={y}:w={BOX_SIZE}:h={BOX_SIZE}:color={color}:t=2:enable='between(t,{t1:.3},{t2:.3})'"
));
}
if parts.is_empty() {
None
} else {
Some(parts.join(","))
}
}
fn apply_trim(cmd: &mut Command, req: &TranscodeRequest) {
if let Some(start) = req.trim_start_secs {
if start > 0.001 {
cmd.args(["-ss", &format!("{start}")]);
}
}
if let Some(end) = req.trim_end_secs {
cmd.args(["-to", &format!("{end}")]);
}
}
fn select_filter_for_deleted(deleted: &[u32]) -> Option<String> {
if deleted.is_empty() {
return None;
}
let parts: Vec<String> = deleted.iter().map(|n| format!("eq(n\\,{n})")).collect();
let expr = parts.join("+");
Some(format!("select='not({expr})',setpts=N/FRAME_RATE/TB"))
}
fn crop_filter(crop: Option<CaptureRect>) -> Option<String> {
crop.map(|c| {
format!(
"crop={w}:{h}:{x}:{y}",
w = c.width,
h = c.height,
x = c.x.max(0),
y = c.y.max(0)
)
})
}
pub(crate) fn transcode(ffmpeg: &Path, req: &TranscodeRequest) -> Result<()> {
if req.duration_secs <= 0.01 {
bail!("clip duration is essentially zero - nothing to encode");
}
std::fs::create_dir_all(&req.scratch_dir).context("creating scratch dir")?;
if let Some(parent) = req.output.parent() {
std::fs::create_dir_all(parent).context("creating output dir")?;
}
let encoders = list_encoders(ffmpeg)?;
match req.format {
Format::Mp4 => {
let requested = mp4_video_codec(req.mp4_codec);
let codec = require_video_codec(&encoders, requested, "MP4")?;
let audio = pick_audio_codec(&encoders, &["aac", "libfdk_aac"])?;
two_pass_video(ffmpeg, req, codec, audio, "mp4")
}
Format::Webm => {
let requested = webm_video_codec(req.webm_codec);
let codec = require_video_codec(&encoders, requested, "WebM")?;
let audio = pick_audio_codec(&encoders, &["libopus", "libvorbis"])?;
two_pass_video(ffmpeg, req, codec, audio, "webm")
}
Format::Gif => encode_gif(ffmpeg, req),
}
}
fn require_video_codec<'a>(
encoders: &HashSet<String>,
requested: &'a str,
container: &str,
) -> Result<&'a str> {
if encoders.contains(requested) {
Ok(requested)
} else {
bail!("{container} codec unavailable: ffmpeg does not include {requested}")
}
}
/// 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);
struct EncoderCacheEntry {
ffmpeg_mtime: SystemTime,
encoders: HashSet<String>,
}
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()
.context("listing ffmpeg encoders")?;
let text = String::from_utf8_lossy(&out.stdout);
let mut set: HashSet<String> = HashSet::new();
for line in text.lines() {
let trimmed = line.trim_start();
let mut iter = trimmed.split_whitespace();
let (Some(flags), Some(name)) = (iter.next(), iter.next()) else {
continue;
};
if flags.len() != 6 {
continue;
}
if !matches!(flags.chars().next(), Some('V' | 'A' | 'S')) {
continue;
}
set.insert(name.to_string());
}
Ok(set)
}
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);
}
}
bail!(
"no audio encoder available - tried {}",
candidates.join(", ")
)
}
fn mp4_video_codec(c: Mp4Codec) -> &'static str {
match c {
Mp4Codec::H264 => "libx264",
Mp4Codec::H265 => "libx265",
}
}
fn webm_video_codec(c: WebmCodec) -> &'static str {
match c {
WebmCodec::Vp9 => "libvpx-vp9",
WebmCodec::Av1 => "libsvtav1",
}
}
/// 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)]
// Four independent per-codec flags, each meaningful on its own; they are what
// the settings screen disables individually, so a bitflag would obscure more
// than it saves.
#[allow(
clippy::struct_excessive_bools,
reason = "one flag per codec, each surfaced separately in the UI"
)]
pub(crate) 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(crate) fn all_unknown() -> Self {
Self {
h264: true,
h265: true,
vp9: true,
av1: true,
}
}
}
pub(crate) fn codec_availability(ffmpeg: &Path) -> CodecAvailability {
let Ok(encoders) = list_encoders(ffmpeg) else {
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 = bytes_f64(req.target_bytes) * 8.0 * 0.95;
let audio_bits = if req.keep_audio {
bytes_f64(AUDIO_BITRATE_KBPS) * 1000.0 * req.duration_secs
} else {
0.0
};
let video_bits = target_bits - audio_bits;
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 = round_u64(video_bits / 1000.0 / req.duration_secs);
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,
video_codec: &str,
audio_codec: &str,
_container: &str,
) -> Result<()> {
let bitrate_kbps = video_bitrate_kbps(req)?;
let bitrate = format!("{bitrate_kbps}k");
let log_stem = req.scratch_dir.join("ffmpeg2pass");
let log_stem_str = log_stem
.to_str()
.ok_or_else(|| anyhow!("scratch dir contains non-UTF8"))?;
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 = combined_video_filter(crop.as_ref(), clicks.as_ref());
let mut pass1 = Command::new(ffmpeg);
pass1
.arg("-y")
.arg("-hide_banner")
.arg("-i")
.arg(&req.input);
apply_trim(&mut pass1, req);
if let Some(c) = &combined_vf {
pass1.args(["-vf", c]);
}
pass1
.args(["-c:v", video_codec])
.args(["-b:v", &bitrate])
.args(["-pass", "1"])
.args(["-passlogfile", log_stem_str])
.arg("-an")
.args(["-f", "null"])
.arg(null_target);
let tx = req.progress_tx.clone();
let dur = req.duration_secs;
let fps = req.fps;
let cancel = req.cancel.clone();
let pass_start = std::time::Instant::now();
run_with_progress(
&mut pass1,
"pass 1",
1,
2,
dur,
fps,
tx.as_ref(),
cancel.as_ref(),
)?;
tracing::info!(
elapsed_ms = pass_start.elapsed().as_millis(),
"ffmpeg pass 1 finished"
);
// Send 50% to signal pass 1 done, pass 2 starting.
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();
}
let mut pass2 = Command::new(ffmpeg);
pass2
.arg("-y")
.arg("-hide_banner")
.arg("-i")
.arg(&req.input);
apply_trim(&mut pass2, req);
if let Some(c) = &combined_vf {
pass2.args(["-vf", c]);
}
pass2
.args(["-c:v", video_codec])
.args(["-b:v", &bitrate])
.args(["-pass", "2"])
.args(["-passlogfile", log_stem_str]);
if req.keep_audio {
pass2
.args(["-c:a", audio_codec])
.args(["-b:a", &format!("{AUDIO_BITRATE_KBPS}k")]);
} else {
pass2.arg("-an");
}
pass2.arg(&req.output);
let pass_start = std::time::Instant::now();
run_with_progress(
&mut pass2,
"pass 2",
2,
2,
dur,
fps,
tx.as_ref(),
cancel.as_ref(),
)?;
tracing::info!(
elapsed_ms = pass_start.elapsed().as_millis(),
"ffmpeg pass 2 finished"
);
cleanup_pass_logs(&log_stem);
Ok(())
}
fn cleanup_pass_logs(stem: &Path) {
let Some(parent) = stem.parent() else { return };
let prefix = stem.file_name().and_then(OsStr::to_str).unwrap_or("");
if prefix.is_empty() {
return;
}
if let Ok(entries) = std::fs::read_dir(parent) {
for entry in entries.flatten() {
let name = entry.file_name();
if let Some(name_str) = name.to_str() {
if name_str.starts_with(prefix) {
drop(std::fs::remove_file(entry.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);
// Defer cleanup until we've measured the sample: the guard owns a copy of
// the path, which lets the original move into the request below. Earlier
// versions removed the file here, which made the metadata read always fail
// and the whole calibration path silently no-op.
let sample_bytes;
{
let _guard = TempFileGuard(sample_path.clone());
// Build a throwaway request scoped to the sample window.
let mut sample_req = req.clone();
sample_req.output = sample_path;
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;
if encode_gif_pass(ffmpeg, &sample_req, est_width, est_fps, 1, 1).is_err() {
return None;
}
sample_bytes = std::fs::metadata(&_guard.0).map(|m| m.len()).ok()?;
}
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 = 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);
// 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 = (f64::from(req.gif_colors) / 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 = (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))
}
/// 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)
}
}
}
/// 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,
target_bytes: req.target_bytes,
fps: req.fps,
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);
// 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 let Some((w, f)) = gif_calibration(ffmpeg, req, scale_width, effective_fps) {
scale_width = w;
effective_fps = f;
}
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. This also drives
// the progress bar: each attempt is one segment, so the bar accumulates
// across retries instead of resetting.
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;
for attempt in 0..max_retries {
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
if attempt == max_retries - 1 {
scale_width = (scale_width / 2).max(60);
effective_fps = 1;
}
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,
)?;
tracing::info!(
attempt = attempt + 1,
elapsed_ms = pass_start.elapsed().as_millis(),
"gif pass finished"
);
let actual = std::fs::metadata(&req.output).map_or(0, |m| m.len());
if actual == 0 {
bail!("gif output is empty");
}
let ratio = bytes_f64(target) / bytes_f64(actual);
// Accept if at or under target (even if significantly under - don't upscale)
if ratio >= 1.0 {
tracing::info!(
"gif encode done on attempt {}: {} bytes (target {})",
attempt + 1,
actual,
target
);
return Ok(());
}
// Compute a shrink factor. Clamp the multiplicative shrink between
// 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.
// 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
// the file, or moved us farther from the target, force the strongest
// allowed shrink next time instead of creeping/oscillating.
if let Some(prev) = prev_actual {
let prev_dist = (bytes_f64(target) - bytes_f64(prev)).abs();
let cur_dist = (bytes_f64(target) - bytes_f64(actual)).abs();
if actual >= prev || cur_dist > prev_dist {
tracing::warn!(
"gif encode: retry trend worsened. prev={}B, now={}B. using stronger shrink.",
prev,
actual
);
factor = 0.6;
}
}
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})",
attempt + 1,
actual,
target,
scale_width,
effective_fps,
factor
);
prev_actual = Some(actual);
}
// All retries exhausted - warn if still over target
let final_size = std::fs::metadata(&req.output).map_or(0, |m| m.len());
if final_size > req.target_bytes {
tracing::warn!(
"gif encode: could not meet target size after {} attempts. Final: {} bytes (target: {})",
max_retries, final_size, req.target_bytes
);
}
Ok(())
}
fn encode_gif_pass(
ffmpeg: &Path,
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},"))
.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();
let dither = match req.gif_dither {
GifDither::FloydSteinberg => "floyd_steinberg",
GifDither::Bayer => "bayer:bayer_scale=3",
GifDither::None => "none",
};
// 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},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,
scale = scale,
colors = req.gif_colors,
d = dither,
);
tracing::info!(
"gif encode: fps={effective_fps} scale={scale_width} colors={} filter={filter_complex}",
req.gif_colors
);
let mut encode = Command::new(ffmpeg);
encode
.arg("-y")
.arg("-hide_banner")
.arg("-i")
.arg(&req.input);
apply_trim(&mut encode, req);
encode
.args(["-filter_complex", &filter_complex])
.args(["-loop", "0"])
.arg(&req.output);
run_with_progress(
&mut encode,
"gif encode",
attempt,
max_attempts,
req.duration_secs,
effective_fps,
req.progress_tx.as_ref(),
req.cancel.as_ref(),
)?;
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(crate) struct GifBudgetInput {
pub gif_colors: u16,
pub target_bytes: u64,
pub fps: u32,
pub duration_secs: f64,
pub gif_budget_mode: GifBudgetMode,
}
pub(crate) fn gif_params(input: &GifBudgetInput, clip_width: u32, clip_height: u32) -> (u32, u32) {
let aspect = aspect_ratio(clip_width, clip_height);
// 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 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 bytes_per_pixel_per_frame = 0.2 * color_factor;
let target_bytes = bytes_f64(input.target_bytes);
let requested_fps = f64::from(input.fps);
let duration = input.duration_secs;
match input.gif_budget_mode {
GifBudgetMode::Resolution => {
let max_w = f64::from(clip_width.min(1280)).clamp(120.0, 1280.0);
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 = round_u32((max_frames / duration).max(1.0));
let fps = (input.fps).min(min_fps).max(1);
(w, fps)
}
GifBudgetMode::Framerate => {
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 = (round_u32(w.clamp(120.0, 1280.0)) / 2) * 2;
(w, input.fps)
}
GifBudgetMode::Balanced => {
let frames_at_full = (requested_fps * duration).max(1.0);
let budget_at_full = target_bytes / (frames_at_full * bytes_per_pixel_per_frame);
let w_at_full = (budget_at_full * aspect).sqrt().clamp(120.0, 1280.0);
let scale = if w_at_full < f64::from(clip_width) {
(w_at_full / f64::from(clip_width)).sqrt()
} else {
1.0
};
let scale = scale.max(0.1);
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)
}
}
}
pub(crate) fn aspect_ratio(width: u32, height: u32) -> f64 {
if height > 0 {
f64::from(width) / f64::from(height)
} else {
16.0 / 9.0
}
}
pub(crate) fn gif_height_for_width(width: u32, clip_width: u32, clip_height: u32) -> u32 {
let aspect = aspect_ratio(clip_width, clip_height);
if width == 0 {
0
} else {
(round_u32(f64::from(width) / aspect) / 2) * 2
}
}
pub(crate) fn render_preview(
ffmpeg: &Path,
input: &Path,
out_path: &Path,
midpoint_secs: f64,
target_width: u32,
) -> Result<()> {
if let Some(parent) = out_path.parent() {
std::fs::create_dir_all(parent).context("creating preview parent")?;
}
let scale_filter = format!("scale={target_width}:-2");
let mut cmd = Command::new(ffmpeg);
cmd.arg("-y")
.arg("-hide_banner")
.args(["-ss", &format!("{midpoint_secs}")])
.arg("-i")
.arg(input)
.args(["-vf", &scale_filter])
.args(["-frames:v", "1"])
.arg(out_path);
run(&mut cmd, "preview render")
}
/// Render a GIF preview with actual palette and dithering applied.
/// Generates a palette from the full clip, then applies it to a single frame.
// Every argument is a distinct knob the caller already has in hand; bundling
// them into a struct would only move the same list one level up.
#[allow(
clippy::too_many_arguments,
reason = "flat parameter list mirrors the preview request fields the caller owns"
)]
pub(crate) fn render_gif_preview(
ffmpeg: &Path,
input: &Path,
out_path: &Path,
midpoint_secs: f64,
target_width: u32,
gif_colors: u16,
gif_dither: &str,
duration_secs: f64,
) -> Result<()> {
if let Some(parent) = out_path.parent() {
std::fs::create_dir_all(parent).context("creating preview parent")?;
}
// 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_key = palette_cache_key(gif_colors, target_width, sample_start, sample_dur);
// The preview and its input both live in the scratch dir, so the preview's
// parent is the normal case. Fall back to the input's parent rather than
// panicking on a bare filename.
let palette_dir = out_path
.parent()
.filter(|p| !p.as_os_str().is_empty())
.or_else(|| input.parent().filter(|p| !p.as_os_str().is_empty()))
.context("preview palette has no parent directory")?;
let palette_path = palette_dir.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!(
"{}[x];[x][1:v]paletteuse=dither={}",
gif_rgb_scale_filter(target_width),
gif_dither
);
let mut encode = Command::new(ffmpeg);
encode
.arg("-y")
.arg("-hide_banner")
.args(["-ss", &format!("{midpoint_secs}")])
.arg("-i")
.arg(input)
.arg("-i")
.arg(&palette_path)
.args(["-lavfi", &use_filter])
.args(["-frames:v", "1"])
.arg(out_path);
// The palette is deliberately left in place: the cache key above exists so a
// render with the same inputs can skip palettegen entirely, and deleting it
// here meant every render regenerated it. clear_temp_segments sweeps
// preview-palette-*.png between recordings, and clean_stale_palettes drops
// the keys that no longer apply.
run(&mut encode, "gif preview encode")
}
/// 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}")
}
/// 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() {
// Case-insensitive for the same reason as the temp sweep: these
// are the app's own files, but Windows keeps the case it was given.
let is_png = Path::new(name)
.extension()
.is_some_and(|e| e.eq_ignore_ascii_case("png"));
if name.starts_with("preview-palette-") && is_png {
drop(std::fs::remove_file(entry.path()));
}
}
}
}
}
pub(crate) fn extract_thumbnails(
ffmpeg: &Path,
input: &Path,
out_dir: &Path,
fps: u32,
crop: Option<CaptureRect>,
) -> Result<Vec<PathBuf>> {
std::fs::create_dir_all(out_dir).context("creating thumbnails dir")?;
for entry in std::fs::read_dir(out_dir).into_iter().flatten().flatten() {
drop(std::fs::remove_file(entry.path()));
}
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 pattern = out_dir.join("thumb-%05d.png");
let mut cmd = Command::new(ffmpeg);
cmd.arg("-y")
.arg("-hide_banner")
.arg("-i")
.arg(input)
.args(["-vf", &filter])
.arg(&pattern);
run(&mut cmd, "thumbnail extraction")?;
let mut paths: Vec<PathBuf> = std::fs::read_dir(out_dir)?
.flatten()
.map(|e| e.path())
.filter(|p| {
p.extension().and_then(|s| s.to_str()) == Some("png")
&& p.file_name()
.and_then(|s| s.to_str())
.is_some_and(|s| s.starts_with("thumb-"))
})
.collect();
paths.sort();
Ok(paths)
}
pub(crate) fn mux_with_audio(
ffmpeg: &Path,
video: &Path,
audio_pcm: &Path,
sample_rate: u32,
channels: u16,
output: &Path,
) -> Result<()> {
if let Some(parent) = output.parent() {
std::fs::create_dir_all(parent).context("creating output parent dir")?;
}
let mut cmd = Command::new(ffmpeg);
cmd.arg("-y")
.arg("-hide_banner")
.arg("-i")
.arg(video)
.args(["-f", "f32le"])
.args(["-ar", &sample_rate.to_string()])
.args(["-ac", &channels.to_string()])
.arg("-i")
.arg(audio_pcm)
.args(["-c:v", "copy"])
.args(["-c:a", "aac"])
.args(["-b:a", "192k"])
.args(["-shortest"])
.arg(output);
run(&mut cmd, "mux")
}
pub(crate) fn concat_pcm(segments: &[PathBuf], output: &Path) -> Result<()> {
use std::io::Write;
if segments.is_empty() {
bail!("no audio segments to concatenate");
}
if let Some(parent) = output.parent() {
std::fs::create_dir_all(parent).context("creating audio concat parent")?;
}
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()))?;
std::io::copy(&mut f, &mut out).context("copying audio segment")?;
}
out.flush()?;
Ok(())
}
struct TempFileGuard(PathBuf);
impl Drop for TempFileGuard {
fn drop(&mut self) {
drop(std::fs::remove_file(&self.0));
}
}
pub(crate) fn concat_segments(ffmpeg: &Path, segments: &[PathBuf], output: &Path) -> Result<()> {
use std::fmt::Write as _;
if segments.is_empty() {
bail!("no segments to concatenate");
}
if let [only] = segments {
std::fs::copy(only, output).context("copying single segment")?;
return Ok(());
}
let parent = output
.parent()
.ok_or_else(|| anyhow!("output has no parent dir"))?;
std::fs::create_dir_all(parent).context("creating output parent dir")?;
let list_path = parent.join("concat-list.txt");
let _guard = TempFileGuard(list_path.clone());
let mut body = String::new();
for seg in segments {
let s = seg
.to_str()
.ok_or_else(|| anyhow!("segment path is not UTF-8"))?
.replace('\\', "/");
let _ = writeln!(body, "file '{s}'");
}
std::fs::write(&list_path, body).context("writing concat list")?;
let mut cmd = Command::new(ffmpeg);
cmd.arg("-y")
.arg("-hide_banner")
.args(["-f", "concat"])
.args(["-safe", "0"])
.arg("-i")
.arg(&list_path)
.args(["-c", "copy"])
.arg(output);
run(&mut cmd, "concat")
}
fn run(cmd: &mut Command, label: &str) -> Result<()> {
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 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.
// Thin forwarder to run_impl, which needs the same list; a params struct here
// would just be reconstructed at each of the four call sites.
#[allow(
clippy::too_many_arguments,
reason = "thin forwarder for the ffmpeg invocation; callers already hold these as locals"
)]
fn run_with_progress(
cmd: &mut Command,
label: &str,
pass: u8,
total_passes: u8,
duration_secs: f64,
fps: u32,
progress_tx: Option<&Sender<EncodeProgress>>,
cancel: Option<&Arc<AtomicBool>>,
) -> Result<()> {
// 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));
}
Ok(())
}
fn ffmpeg_failure_message(label: &str, status: std::process::ExitStatus, stderr: &[u8]) -> String {
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")
{
Some("selected codec is not available in this ffmpeg build")
} else if lower.contains("permission denied") {
Some("output path is not writable")
} else if lower.contains("no such file or directory") {
Some("input or output path does not exist")
} else if lower.contains("invalid data found") {
Some("input clip could not be read")
} else if lower.contains("invalid argument") {
Some("ffmpeg rejected one of the encode settings")
} else {
None
};
match hint {
Some(h) => format!("ffmpeg {label} failed: {h}. Details: {head}"),
None => format!("ffmpeg {label} exited with {status}: {head}"),
}
}
/// 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.
#[allow(
clippy::needless_pass_by_value,
reason = "progress_tx and cancel are moved into the threads spawned below"
)]
#[allow(
clippy::too_many_arguments,
reason = "receives the ffmpeg invocation plus its progress plumbing from run_with_progress"
)]
fn run_impl(
cmd: &mut Command,
label: &str,
progress_pass: u8,
progress_total_passes: u8,
progress_duration_secs: f64,
_progress_fps: u32,
progress_tx: Option<Sender<EncodeProgress>>,
cancel: Option<Arc<AtomicBool>>,
read_stdout: bool,
) -> Result<std::process::Output> {
use std::process::Stdio;
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 mut child = cmd
.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();
// 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.clone();
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 reader = BufReader::new(out);
let mut last_out_time_us: f64 = 0.0;
for line in reader.lines().map_while(Result::ok) {
if let Some((key, value)) = parse_progress_kv(&line) {
match key {
"out_time_us" => last_out_time_us = value,
"progress" => {
let percent =
(last_out_time_us / encode_dur_us * 100.0).clamp(0.0, 100.0);
if let Some(ref sender) = tx {
// A dropped receiver means the frontend is gone;
// the encode keeps running either way.
sender
.send(EncodeProgress {
pass,
total_passes,
percent,
})
.ok();
}
}
// frame=, fps=, bitrate= and friends are not needed.
_ => {}
}
}
}
})
});
// 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 || {
use std::io::Read;
let mut collected = Vec::new();
let mut s = serr;
drop(s.read_to_end(&mut collected));
collected
})
});
loop {
if let Some(ref c) = cancel {
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());
}
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()
.and_then(|h| h.join().ok())
.unwrap_or_default();
return Ok(std::process::Output {
status,
stdout: Vec::new(),
stderr: stderr_bytes,
});
}
Ok(None) => {
thread::sleep(std::time::Duration::from_millis(20));
}
Err(e) => bail!("waiting for ffmpeg: {e}"),
}
}
}
/// 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)]
mod tests {
use super::*;
fn dummy_request() -> TranscodeRequest {
let dir = std::env::temp_dir().join(format!("bytesize-encode-test-{}", std::process::id()));
TranscodeRequest {
input: dir.join("input.mp4"),
output: dir.join("output.mp4"),
format: Format::Mp4,
target_bytes: 0,
duration_secs: 10.0,
fps: 30,
keep_audio: true,
gif_dither: GifDither::FloydSteinberg,
webm_codec: WebmCodec::Vp9,
mp4_codec: Mp4Codec::H264,
scratch_dir: dir.join("scratch"),
crop: None,
gif_budget_mode: GifBudgetMode::Balanced,
gif_colors: 256,
deleted_frame_indices: vec![],
trim_start_secs: None,
trim_end_secs: None,
clicks: vec![],
clip_width: 1920,
clip_height: 1080,
progress_tx: None,
cancel: None,
}
}
#[test]
fn bitrate_for_8mb_10s_with_audio() {
let mut req = dummy_request();
req.target_bytes = 8 * 1024 * 1024;
req.duration_secs = 10.0;
req.keep_audio = true;
let kbps = video_bitrate_kbps(&req).unwrap();
// 8 MB * 8 * 0.95 = 60.96 Mbits total
// minus 192k * 10 = 1.92 Mbits audio
// video = ~59 Mbits / 10s = ~5900 kbps
assert!(kbps > 5800 && kbps < 6200);
}
#[test]
fn bitrate_for_8mb_10s_no_audio() {
let mut req = dummy_request();
req.target_bytes = 8 * 1024 * 1024;
req.duration_secs = 10.0;
req.keep_audio = false;
let kbps = video_bitrate_kbps(&req).unwrap();
// 8 MB * 8 * 0.95 = 60.96 Mbits total, all video
// 60.96 Mbits / 10s = ~6096 kbps
assert!(kbps > 6000 && kbps < 6500);
}
#[test]
fn bitrate_rejects_too_small() {
let mut req = dummy_request();
req.target_bytes = 1000;
req.duration_secs = 10.0;
req.keep_audio = true;
assert!(video_bitrate_kbps(&req).is_err());
}
#[test]
fn bitrate_floor_at_16_kbps() {
let mut req = dummy_request();
req.target_bytes = 1024 * 1024;
req.duration_secs = 600.0;
req.keep_audio = false;
let kbps = video_bitrate_kbps(&req).unwrap();
assert_eq!(kbps, 16);
}
#[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))
);
}
#[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]
fn crop_filter_output() {
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())
);
assert_eq!(crop_filter(None), None);
}
#[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,
})
.collect();
let filter = click_filters(&clicks, 1920, 1080, 0.0).unwrap();
let count = filter.matches("drawbox").count();
assert_eq!(count, MAX_CLICK_HIGHLIGHTS);
}
#[test]
fn click_boxes_stay_inside_the_frame() {
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(960, 540, frame.0, frame.1), Some((948, 528)));
}
#[test]
fn clicks_outside_the_capture_region_are_skipped() {
let frame = (1920u32, 1080u32);
// A click to the left of / above the crop maps to a negative offset, and
// one past the far edge lands beyond the frame. Both used to produce a
// negative drawbox offset that ffmpeg silently dropped.
assert_eq!(click_box(-620, 115, frame.0, frame.1), None);
assert_eq!(click_box(100, -40, frame.0, frame.1), None);
assert_eq!(click_box(2100, 500, frame.0, frame.1), None);
assert_eq!(click_box(500, 1200, frame.0, frame.1), None);
}
#[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,
},
];
let filter = click_filters(&clicks, 1920, 1080, 0.0).unwrap();
assert_eq!(filter.matches("drawbox").count(), 1);
assert!(filter.contains("x=488:y=388"));
// Every emitted box must be non-negative, or drawbox throws it away.
assert!(!filter.contains("x=-"));
assert!(!filter.contains("y=-"));
}
/// A trim seeks past the head of the clip, which rebases the filter timeline
/// to zero, so a click recorded against clip time has to move back by the
/// 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 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();
assert!(trimmed.contains("between(t,0.950,1.250)"));
assert!(!trimmed.contains("6.250"));
}
/// 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,
}];
assert!(click_filters(&clicks, 1920, 1080, 5.0).is_none());
}
#[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| (f64::from(colors) / 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);
}
}