use std::collections::HashSet; use std::ffi::{OsStr, OsString}; use std::path::{Path, PathBuf}; use std::process::Command; use std::sync::atomic::{AtomicBool, AtomicU64, 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, SourceRange}; // 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, pub gif_budget_mode: GifBudgetMode, pub gif_colors: u16, pub gif_removed_ranges: Vec, pub trim_start_secs: Option, pub trim_end_secs: Option, pub clicks: Vec, pub clip_width: u32, pub clip_height: u32, /// Optional channel to report encoding progress. #[doc(hidden)] pub progress_tx: Option>, /// Optional cancel signal. When set to true, ffmpeg will be killed. #[doc(hidden)] pub cancel: Option>, } 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)) } 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) -> Option { if clicks.is_empty() { return None; } let mut parts: Vec = 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; 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}")]); } } pub(crate) fn gif_cuts(mut ranges: Vec, start: f64, end: f64) -> Result> { if ranges.iter().any(|range| !range.start_secs.is_finite() || !range.end_secs.is_finite() || range.start_secs < 0.0 || range.end_secs <= range.start_secs) { bail!("invalid GIF frame removal range"); } ranges.sort_by(|a, b| a.start_secs.total_cmp(&b.start_secs)); let mut merged: Vec = Vec::new(); for range in ranges { let start_secs = range.start_secs.max(start); let end_secs = range.end_secs.min(end); if end_secs <= start_secs { continue; } if let Some(previous) = merged.last_mut().filter(|previous| previous.end_secs >= start_secs) { previous.end_secs = previous.end_secs.max(end_secs); } else { merged.push(SourceRange { start_secs, end_secs }); } } Ok(merged) } fn gif_timeline_filter(req: &TranscodeRequest, effective_fps: u32) -> String { use std::fmt::Write as _; if req.gif_removed_ranges.is_empty() { let mut trim = Vec::new(); if let Some(start) = req.trim_start_secs { trim.push(format!("start={start}")); } if let Some(end) = req.trim_end_secs { trim.push(format!("end={end}")); } let fps = format!("fps={effective_fps}"); return if trim.is_empty() { fps } else { format!("trim={},setpts=PTS-STARTPTS,{fps}", trim.join(":")) }; } // Cut before resampling so changing FPS can't bring removed frames back. // Only subtract gaps after the first kept frame. let deleted: Vec = req .gif_removed_ranges .iter() .map(|range| format!("gte(t,{})*lt(t,{})", range.start_secs, range.end_secs)) .collect(); let gaps: Vec = req.gif_removed_ranges.iter().map(|range| { let end = range.end_secs; let length = end - range.start_secs; format!("(gte(PTS*TB,{end})-gte(STARTPTS*TB,{end}))*{length}") }).collect(); let mut keep = format!("not({})", deleted.join("+")); if let Some(start) = req.trim_start_secs { let _ = write!(keep, "*gte(t,{start})"); } if let Some(end) = req.trim_end_secs { let _ = write!(keep, "*lt(t,{end})"); } format!("settb=AVTB,select='{keep}',setpts='PTS-STARTPTS-({})/TB',fps={effective_fps}:eof_action=pass,trim=duration={}", gaps.join("+"), req.duration_secs) } fn crop_filter(crop: Option) -> Option { crop.map(|c| { format!( "crop={w}:{h}:{x}:{y}:exact=1", 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"); } if req.fps == 0 { bail!("export frame rate must be greater than zero"); } 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, 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> = Mutex::new(None); struct EncoderCacheEntry { ffmpeg_mtime: SystemTime, encoders: HashSet, } fn list_encoders(ffmpeg: &Path) -> Result> { 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> { 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 = 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, 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 { 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)) } fn video_filters(req: &TranscodeRequest) -> String { let crop = crop_filter(req.crop); let clicks = click_filters(&req.clicks, req.clip_width, req.clip_height); [clicks, crop, Some(format!("fps={}", req.fps))] .into_iter() .flatten() .collect::>() .join(",") } 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 combined_vf = video_filters(req); let mut pass1 = Command::new(ffmpeg); pass1 .arg("-y") .arg("-hide_banner") .arg("-i") .arg(&req.input); apply_trim(&mut pass1, req); pass1 .args(["-vf", &combined_vf]) .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 cancel = req.cancel.clone(); let pass_start = std::time::Instant::now(); run_with_progress( &mut pass1, "pass 1", 1, 2, dur, 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); pass2 .args(["-vf", &combined_vf]) .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.args(["-abort_on", "empty_output_stream", "-f", container]).arg(&req.output); let pass_start = std::time::Instant::now(); run_with_progress( &mut pass2, "pass 2", 2, 2, dur, 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 = trim_offset(req) + ((req.duration_secs - 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.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 (clip_width, clip_height) = req.crop.map_or((req.clip_width, req.clip_height), |r| (r.width, r.height)); let aspect = aspect_ratio(clip_width, 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 >= 0.85 { return None; } // Recompute target params with the corrected constant. Scale resolution // by the sqrt of the ratio so file size scales roughly linearly. let (mut width, mut fps) = (est_width, est_fps); shrink_gif_params( req.gif_budget_mode, gif_shrink_factor(req.gif_budget_mode, ratio.min(1.0)), &mut width, &mut fps, ); Some((width, 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, GifBudgetMode::Framerate => ratio.sqrt(), GifBudgetMode::Balanced => { // Split the required reduction between resolution and fps so we // reduce both proportionally rather than halving resolution alone. (ratio * 0.5 + ratio.sqrt() * 0.5).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::Framerate => { *width = (round_u32(f64::from(*width) * factor) / 2).clamp(60, 640) * 2; } GifBudgetMode::Resolution => { *fps = round_u32(f64::from(*fps) * factor) .clamp(1, fps.saturating_sub(1).max(1)); } GifBudgetMode::Balanced => { *width = (round_u32(f64::from(*width) * factor) / 2).clamp(60, 640) * 2; *fps = round_u32(f64::from(*fps) * factor) .clamp(1, fps.saturating_sub(1).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 || !req.gif_removed_ranges.is_empty() { 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 gif_starting_params(req: &TranscodeRequest) -> (u32, u32) { 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 (width, height) = req.crop.map_or((req.clip_width, req.clip_height), |r| (r.width, r.height)); gif_params(&budget_input, width, height) } fn encode_gif(ffmpeg: &Path, req: &TranscodeRequest) -> Result<()> { let (mut scale_width, mut effective_fps) = gif_starting_params(req); // 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 = None; for attempt in 0..max_retries { if req .cancel .as_ref() .is_some_and(|c| c.load(Ordering::Relaxed)) { bail!("export cancelled"); } 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; } } let previous = (scale_width, effective_fps); shrink_gif_params( req.gif_budget_mode, factor, &mut scale_width, &mut effective_fps, ); if (scale_width, effective_fps) == previous { // Try the other setting when the preferred one hits its floor. let fallback = match req.gif_budget_mode { GifBudgetMode::Resolution => GifBudgetMode::Framerate, GifBudgetMode::Framerate | GifBudgetMode::Balanced => GifBudgetMode::Resolution, }; shrink_gif_params(fallback, gif_shrink_factor(fallback, ratio).clamp(0.6, 0.9), &mut scale_width, &mut effective_fps); if (scale_width, effective_fps) == previous { break; } } 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 gif_filters(req: &TranscodeRequest, scale_width: u32, effective_fps: u32) -> String { 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) .map(|c| format!("{c},")) .unwrap_or_default(); let timeline = gif_timeline_filter(req, effective_fps); let stats = if req.gif_removed_ranges.is_empty() { "diff" } else { "full" }; 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 colors = req.gif_colors; let reserve = u8::from(colors > 2); format!( "{kprefix}{cprefix}{timeline},{scale},split[s0][s1];[s0]palettegen=stats_mode={stats}:max_colors={colors}:reserve_transparent={reserve}[p];[s1][p]paletteuse=dither={d}", cprefix = crop_prefix, kprefix = click_prefix, scale = scale, d = dither, ) } fn encode_gif_pass( ffmpeg: &Path, req: &TranscodeRequest, scale_width: u32, effective_fps: u32, attempt: u8, max_attempts: u8, ) -> Result<()> { let filter_complex = gif_filters(req, scale_width, effective_fps); 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); encode .args(["-filter_complex", &filter_complex]) .args(["-loop", "0"]) .args(["-abort_on", "empty_output", "-f", "gif"]) .arg(&req.output); run_with_progress( &mut encode, "gif encode", attempt, max_attempts, req.duration_secs, 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:out_range=pc:in_primaries=bt709:in_transfer=bt709:out_primaries=bt709:out_transfer=srgb,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 } } #[derive(Clone, Copy, Debug, serde::Serialize)] pub(crate) struct OutputProperties { pub width: u32, pub height: u32, pub fps: f64, pub duration_secs: f64, } /// Inspect packet timing without decoding the video. pub(crate) fn inspect_output(ffmpeg: &Path, path: &Path) -> Result { use std::os::windows::process::CommandExt; use windows::Win32::System::Threading::CREATE_NO_WINDOW; let mut cmd = Command::new(ffmpeg); let output = cmd .creation_flags(CREATE_NO_WINDOW.0) .args(["-v", "error", "-nostdin", "-i"]) .arg(path) .args(["-map", "0:v:0", "-c:v", "copy", "-f", "framecrc", "pipe:1"]) .output() .context("reading rendered output details")?; if !output.status.success() { bail!(ffmpeg_failure_message("reading output details", output.status, &output.stderr)); } parse_output_properties(&String::from_utf8_lossy(&output.stdout)) .ok_or_else(|| anyhow!("could not read the output dimensions or frame timing")) } fn parse_output_properties(report: &str) -> Option { let (width, height) = report.lines() .find_map(|line| line.strip_prefix("#dimensions 0: "))?.trim().split_once('x')?; let (tick, timescale) = report.lines() .find_map(|line| line.strip_prefix("#tb 0: "))?.trim().split_once('/')?; let mut first = f64::INFINITY; let mut end = f64::NEG_INFINITY; let mut frames = 0u32; for line in report.lines().filter(|line| line.starts_with('0')) { let mut columns = line.split(',').skip(2); let pts = columns.next()?.trim().parse::().ok()?; let duration = columns.next()?.trim().parse::().ok()?; first = first.min(pts); end = end.max(pts + duration); frames += 1; } let duration_secs = (end - first) * tick.parse::().ok()? / timescale.parse::().ok()?; if !duration_secs.is_finite() || duration_secs <= 0.0 { return None; } Some(OutputProperties { width: width.parse().ok()?, height: height.parse().ok()?, fps: f64::from(frames) / duration_secs, duration_secs, }) } #[derive(serde::Serialize)] pub(crate) struct ThumbnailPage { pub paths: Vec, pub has_more: bool, } pub(crate) fn timeline_thumbnails(ffmpeg: &Path, input: &Path, out_dir: &Path, seconds: f64) -> Result> { if !seconds.is_finite() || seconds <= 0.0 { bail!("invalid clip duration for the timeline"); } std::fs::create_dir_all(out_dir).context("creating timeline thumbnail folder")?; let filter = format!("fps={:.6},scale=160:-2", (8.0 / seconds).min(120.0)); let mut cmd = Command::new(ffmpeg); cmd.args(["-y", "-hide_banner", "-i"]).arg(input) .args(["-vf", &filter, "-frames:v", "8"]).arg(out_dir.join("frame-%02d.jpg")); run(&mut cmd, "timeline thumbnails")?; Ok((1..=8).map(|i| out_dir.join(format!("frame-{i:02}.jpg"))).filter(|path| path.is_file()).collect()) } pub(crate) fn display_preview(ffmpeg: &Path, x: i32, y: i32, width: u32, height: u32) -> Result> { use std::os::windows::process::CommandExt; const CREATE_NO_WINDOW: u32 = 0x0800_0000; let output = Command::new(ffmpeg) .creation_flags(CREATE_NO_WINDOW) .args(["-hide_banner", "-loglevel", "error", "-f", "gdigrab", "-draw_mouse", "0"]) .args(["-offset_x", &x.to_string(), "-offset_y", &y.to_string(), "-video_size", &format!("{width}x{height}")]) .args(["-i", "desktop", "-frames:v", "1", "-vf", "scale=960:-2", "-c:v", "mjpeg", "-f", "image2pipe", "pipe:1"]) .output().context("opening display preview")?; if !output.status.success() || output.stdout.is_empty() { bail!(ffmpeg_failure_message("display preview", output.status, &output.stderr)); } Ok(output.stdout) } pub(crate) fn extract_thumbnails( ffmpeg: &Path, input: &Path, out_dir: &Path, fps: u32, start: u32, ) -> Result { const PAGE_SIZE: usize = 80; if !(1..=60).contains(&fps) { bail!("thumbnail frame rate must be between 1 and 60"); } let page_dir = out_dir.join(format!("{fps}-{start}")); std::fs::create_dir_all(&page_dir).context("creating thumbnail page")?; for entry in std::fs::read_dir(&page_dir)?.flatten() { drop(std::fs::remove_file(entry.path())); } // Seek in whole seconds to keep the sampling grid aligned with source time. // A second of preroll gives the FPS filter the same frames at the page edge. let seek_seconds = (start / fps).saturating_sub(1); let page_start = start - seek_seconds * fps; let filter = format!("fps={fps},trim=start_frame={page_start},setpts=PTS-STARTPTS,scale=120:-1:flags=lanczos"); let pattern = page_dir.join("thumb-%03d.png"); let mut cmd = Command::new(ffmpeg); cmd.args(["-y", "-hide_banner"]); if seek_seconds > 0 { cmd.arg("-ss").arg(seek_seconds.to_string()); } cmd.arg("-i").arg(input) .args(["-vf", &filter, "-frames:v", &(PAGE_SIZE + 1).to_string()]) .arg(&pattern); run(&mut cmd, "thumbnail extraction")?; let mut paths: Vec = std::fs::read_dir(&page_dir)? .flatten() .map(|e| e.path()) .filter(|p| p.extension().is_some_and(|ext| ext.eq_ignore_ascii_case("png"))) .collect(); paths.sort(); let has_more = paths.len() > PAGE_SIZE; if has_more { if let Some(extra) = paths.pop() { drop(std::fs::remove_file(extra)); } } // Keep both sides of a page boundary available while scrolling. for entry in std::fs::read_dir(out_dir)?.flatten() { let path = entry.path(); let name = entry.file_name(); let nearby = name.to_str().and_then(|name| name.split_once('-')) .and_then(|(rate, offset)| Some((rate.parse::().ok()?, offset.parse::().ok()?))) .is_some_and(|(rate, offset)| rate == fps && offset.abs_diff(start) <= PAGE_SIZE as u32 * 2); if !nearby && entry.file_type().is_ok_and(|kind| kind.is_dir()) { drop(std::fs::remove_dir_all(path)); } } Ok(ThumbnailPage { paths, has_more }) } 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) struct AudioSegment { pub path: PathBuf, pub sample_rate: u32, pub channels: u16, pub start_secs: f64, pub end_secs: f64, } /// Align the audio takes to video time and fill gaps with whole sample frames. pub(crate) fn assemble_pcm( ffmpeg: &Path, segments: &[AudioSegment], output: &Path, duration_secs: f64, ) -> Result> { use std::io::{Read, Seek, SeekFrom}; let Some(first) = segments.first() else { return Ok(None); }; let (sample_rate, channels) = (first.sample_rate, first.channels); let frame_bytes = u64::from(channels) * 4; let frame_at = |seconds: f64| round_u64(seconds * f64::from(sample_rate)); let total_frames = frame_at(duration_secs); let mut out = std::fs::File::create(output).context("creating aligned audio file")?; let mut written = 0; let resampled = TempFileGuard(output.with_extension("resampled.pcm")); for segment in segments { let start = frame_at(segment.start_secs); let end = frame_at(segment.end_secs).min(total_frames); let from = start.max(written); if end <= from || std::fs::metadata(&segment.path)?.len() == 0 { continue; } let path = if (segment.sample_rate, segment.channels) == (sample_rate, channels) { &segment.path } else { resample_pcm(ffmpeg, segment, &resampled.0, sample_rate, channels)?; &resampled.0 }; let mut input = std::fs::File::open(path)?; let skipped = from - start; let available = (input.metadata()?.len() / frame_bytes).saturating_sub(skipped); let frames = available.min(end - from); if frames == 0 { continue; } write_silence(&mut out, (from - written) * frame_bytes)?; input.seek(SeekFrom::Start(skipped * frame_bytes))?; let bytes = frames * frame_bytes; if std::io::copy(&mut input.take(bytes), &mut out)? != bytes { bail!("audio segment ended before its recorded length"); } written = from + frames; } if written == 0 { return Ok(None); } write_silence(&mut out, (total_frames - written) * frame_bytes)?; Ok(Some((sample_rate, channels))) } fn write_silence(output: &mut std::fs::File, mut bytes: u64) -> Result<()> { use std::io::Write; const ZEROS: [u8; 8192] = [0; 8192]; while bytes > 0 { let chunk = bytes.min(8192); let zeros = ZEROS .get(..usize::try_from(chunk)?) .context("audio padding exceeds its buffer")?; output.write_all(zeros)?; bytes -= chunk; } Ok(()) } fn resample_pcm( ffmpeg: &Path, segment: &AudioSegment, output: &Path, sample_rate: u32, channels: u16, ) -> Result<()> { let mut cmd = Command::new(ffmpeg); cmd.args(["-y", "-hide_banner", "-f", "f32le"]) .args(["-ar", &segment.sample_rate.to_string()]) .args(["-ac", &segment.channels.to_string()]) .arg("-i") .arg(&segment.path) .args(["-ar", &sample_rate.to_string()]) .args(["-ac", &channels.to_string()]) .args(["-f", "f32le"]) .arg(output); run(&mut cmd, "audio resampling") } pub(crate) struct TempFileGuard(pub(crate) PathBuf); impl TempFileGuard { pub(crate) fn create_in(dir: &Path, purpose: &str, extension: &str) -> Result { static SEQUENCE: AtomicU64 = AtomicU64::new(0); let sequence = SEQUENCE.fetch_add(1, Ordering::Relaxed); let path = dir.join(format!("{purpose}-{}-{sequence}.{extension}", std::process::id())); drop(std::fs::File::create_new(&path)?); Ok(Self(path)) } } impl Drop for TempFileGuard { fn drop(&mut self) { if !self.0.as_os_str().is_empty() { 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, 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. fn run_with_progress( cmd: &mut Command, label: &str, pass: u8, total_passes: u8, duration_secs: f64, progress_tx: Option<&Sender>, cancel: Option<&Arc>, ) -> 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, 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::>().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_tx: Option>, cancel: Option>, read_stdout: bool, ) -> Result { 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> = 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>> = 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::().unwrap_or(0.0); Some((key, num)) } #[cfg(test)] mod tests { // Tests fail by panicking, which is the harness contract; unwrap and expect // are denied to keep panics out of the shipping paths. #![allow(clippy::unwrap_used, reason = "a failing test is meant to panic")] use super::*; #[test] fn review_properties_use_muxed_frame_timing() { let properties = parse_output_properties(concat!( "#tb 0: 1/100\n#dimensions 0: 128x96\n", "0, 0, 4, 3, 42, 0x00\n0, 3, 0, 4, 42, 0x00\n0, 6, 7, 3, 42, 0x00\n", )).unwrap(); assert_eq!((properties.width, properties.height), (128, 96)); assert!((properties.duration_secs - 0.1).abs() < 0.000_001); assert!((properties.fps - 30.0).abs() < 0.000_001); } 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, gif_removed_ranges: 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 gif_cuts_are_applied_before_output_frame_rate_conversion() { let mut req = dummy_request(); req.gif_removed_ranges = vec![SourceRange { start_secs: 0.4, end_secs: 0.5 }]; req.trim_start_secs = Some(0.2); req.trim_end_secs = Some(0.8); let selection = "settb=AVTB,select='not(gte(t,0.4)*lt(t,0.5))*gte(t,0.2)*lt(t,0.8)'"; let first = gif_timeline_filter(&req, 30); assert!(first.starts_with(selection)); assert!(first.contains("setpts='PTS-STARTPTS-")); req.fps = 5; assert_eq!(gif_timeline_filter(&req, 5), first.replace("fps=30", "fps=5")); } #[test] #[ignore = "requires FFmpeg; set BYTESIZE_TEST_FFMPEG"] fn gif_source_cuts_close_gaps_without_reintroducing_frames_at_another_fps() -> Result<()> { let ffmpeg = std::env::var_os("BYTESIZE_TEST_FFMPEG").map(PathBuf::from) .ok_or_else(|| anyhow!("set BYTESIZE_TEST_FFMPEG to ffmpeg.exe"))?; let dir = std::env::temp_dir().join(format!("bytesize-gif-cuts-test-{}", std::process::id())); std::fs::create_dir_all(&dir)?; let input = TempFileGuard::create_in(&dir, "source", "mp4")?; let mut source = Command::new(&ffmpeg); source.args(["-y", "-hide_banner"]); for color in ["green", "red", "blue"] { source.args(["-f", "lavfi", "-i", &format!("color=c={color}:size=128x96:rate=10:duration=1")]); } source.args(["-filter_complex", "concat=n=3:v=1:a=0", "-c:v", "libx264"]).arg(&input.0); run(&mut source, "test recording")?; for fps in [5, 10] { let output = TempFileGuard::create_in(&dir, "review", "gif")?; let mut request = dummy_request(); request.input = input.0.clone(); request.output = output.0.clone(); request.scratch_dir = dir.clone(); request.format = Format::Gif; request.target_bytes = 1_000_000; request.clip_width = 128; request.clip_height = 96; request.duration_secs = 2.0; request.fps = fps; request.gif_removed_ranges = vec![SourceRange { start_secs: 1.0, end_secs: 2.0 }]; transcode(&ffmpeg, &request)?; let media = inspect_output(&ffmpeg, &output.0)?; assert!((media.duration_secs - 2.0).abs() < 0.02, "{media:?}"); let pixels = Command::new(&ffmpeg).args(["-v", "error", "-i"]).arg(&output.0) .args(["-vf", "scale=1:1", "-fps_mode", "passthrough", "-pix_fmt", "rgb24", "-f", "rawvideo", "pipe:1"]).output()?; assert!(pixels.status.success()); let frames: Vec<_> = pixels.stdout.chunks_exact(3).collect(); assert_eq!(frames.len(), (fps * 2) as usize); assert!(frames.iter().all(|pixel| pixel[0] < 30), "the red frames should stay removed at {fps} FPS"); assert!(frames.first().is_some_and(|first| first[1] > 80)); assert!(frames.last().is_some_and(|last| last[2] > 150), "expected blue at {fps} FPS, got {frames:?}"); } drop(input); std::fs::remove_dir(dir)?; Ok(()) } #[test] fn audio_alignment_pads_whole_sample_frames_and_preserves_retry_gaps() { let dir = std::env::temp_dir(); let id = std::process::id(); let first = TempFileGuard(dir.join(format!("bytesize-align-{id}-first.pcm"))); let retry = TempFileGuard(dir.join(format!("bytesize-align-{id}-retry.pcm"))); let out = TempFileGuard(dir.join(format!("bytesize-align-{id}-output.pcm"))); let pcm = |samples: &[f32]| { samples.iter().copied().flat_map(f32::to_le_bytes).collect::>() }; std::fs::write(&first.0, pcm(&[0.1, 0.2, 0.3, 0.4])).unwrap(); std::fs::write(&retry.0, pcm(&[0.5, 0.6, 0.7, 0.8])).unwrap(); let segments = [ AudioSegment { path: first.0.clone(), sample_rate: 10, channels: 2, start_secs: 0.12, end_secs: 0.3, }, AudioSegment { path: retry.0.clone(), sample_rate: 10, channels: 2, start_secs: 0.48, end_secs: 0.6, }, ]; assert_eq!( assemble_pcm(Path::new("ffmpeg"), &segments, &out.0, 0.7).unwrap(), Some((10, 2)), ); assert_eq!( std::fs::read(&out.0).unwrap(), pcm(&[0., 0., 0.1, 0.2, 0.3, 0.4, 0., 0., 0., 0., 0.5, 0.6, 0., 0.]), ); } #[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:exact=1".to_string()) ); assert_eq!(crop_filter(None), None); } #[test] fn click_filters_capped_at_max() { let clicks: Vec = (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).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).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=-")); } #[test] fn click_geometry_and_time_use_the_source_before_crop_and_trim() { let mut req = dummy_request(); req.crop = Some(CaptureRect { x: 400, y: 300, width: 520, height: 380 }); req.trim_start_secs = Some(5.0); req.clicks = vec![Click { time_secs: 6.0, x: 500, y: 400, button: crate::clicks::MouseButton::Left, }]; let filters = video_filters(&req); assert!(filters.starts_with("drawbox=x=488:y=388:")); assert!(filters.contains("between(t,5.950,6.250)")); assert!(filters.ends_with(",crop=520:380:400:300:exact=1,fps=30")); } #[test] fn gif_budget_retries_preserve_the_selected_priority() { let (mut width, mut fps) = (800, 20); let mode = GifBudgetMode::Resolution; shrink_gif_params(mode, gif_shrink_factor(mode, 0.5), &mut width, &mut fps); assert_eq!((width, fps), (800, 10)); let mode = GifBudgetMode::Framerate; shrink_gif_params(mode, gif_shrink_factor(mode, 0.25), &mut width, &mut fps); assert_eq!((width, fps), (400, 10)); } #[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); } }