From f732cdda4d3311c5a95de27e535c4ad8d829561f Mon Sep 17 00:00:00 2001 From: lashman Date: Wed, 17 Jun 2026 23:09:53 +0300 Subject: [PATCH] calibrate gif size, probe codecs, align audio with video - sample-encode gif calibration before the retry loop - probe ffmpeg encoders and grey out missing codecs in settings - pad audio head with silence so it lines up with video start - cache gif preview palette keyed on colors and sample window - read encode progress from -progress pipe:1 instead of stderr scraping - thread bt709 color metadata through capture, fix, and gif scale - sweep temp on startup - gif estimate table for the ui, interpolated locally on slider drag --- src-tauri/src/audio.rs | 15 +- src-tauri/src/capture.rs | 163 ++++++++++++++----- src-tauri/src/encode.rs | 331 +++++++++++++++++++++++++++++++-------- src-tauri/src/lib.rs | 164 +++++++++++++++++-- src/lib/Main.svelte | 72 ++++++--- src/lib/Settings.svelte | 26 ++- src/lib/api.ts | 31 ++++ 7 files changed, 647 insertions(+), 155 deletions(-) diff --git a/src-tauri/src/audio.rs b/src-tauri/src/audio.rs index f01319a..d026df9 100644 --- a/src-tauri/src/audio.rs +++ b/src-tauri/src/audio.rs @@ -14,7 +14,7 @@ use windows::Win32::System::Com::{ CoCreateInstance, CoInitializeEx, CoTaskMemFree, CLSCTX_ALL, COINIT_APARTMENTTHREADED, }; -// WASAPI constants — defined here so we don't depend on exact windows-crate naming. +// WASAPI constants - defined here so we don't depend on exact windows-crate naming. const AUDCLNT_STREAMFLAGS_LOOPBACK: u32 = 0x2000_0000; const AUDCLNT_BUFFERFLAGS_SILENT: u32 = 0x0000_0002; @@ -28,6 +28,7 @@ pub struct AudioSession { output_path: PathBuf, pub sample_rate: u32, pub channels: u16, + pub started_at: std::time::Instant, } pub fn start(output_path: PathBuf) -> Result { @@ -45,7 +46,7 @@ pub fn start(output_path: PathBuf) -> Result { result }); - let (sample_rate, channels) = init_rx + let (sample_rate, channels, started_at) = init_rx .recv_timeout(std::time::Duration::from_secs(3)) .context("audio capture thread failed to initialize within 3 seconds")? .context("audio capture initialization failed")?; @@ -56,6 +57,7 @@ pub fn start(output_path: PathBuf) -> Result { output_path, sample_rate, channels, + started_at, }) } @@ -96,7 +98,7 @@ fn parse_format(fmt: &WAVEFORMATEX) -> Result<(u32, u16, u16, bool)> { fn capture_thread( running: Arc, output_path: PathBuf, - init_tx: std::sync::mpsc::Sender>, + init_tx: std::sync::mpsc::Sender>, ) -> Result<()> { // SAFETY: Initializes COM for this thread before any COM operations. COINIT_APARTMENTTHREADED is required for WASAPI. unsafe { @@ -167,8 +169,13 @@ fn capture_thread( let file = File::create(&output_path).context("creating audio output file")?; let mut writer = BufWriter::new(file); + // Stamp the moment audio capture actually begins so stop_capture can pad + // the head of the PCM to align with video start (WASAPI init + Start adds + // a small delay relative to the video capture start). + let started_at = std::time::Instant::now(); + // Notify parent that init succeeded. - let _ = init_tx.send(Ok((sample_rate, channels))); + let _ = init_tx.send(Ok((sample_rate, channels, started_at))); let result = capture_loop(&running, &capture_client, channels, bits_per_sample, is_float, &mut writer); diff --git a/src-tauri/src/capture.rs b/src-tauri/src/capture.rs index 9c422c7..58ee0df 100644 --- a/src-tauri/src/capture.rs +++ b/src-tauri/src/capture.rs @@ -19,6 +19,7 @@ use windows_capture::settings::{ use crate::CaptureRect; const MAX_ENCODE_WIDTH: u32 = 1920; +const FALLBACK_REFRESH_HZ: u32 = 60; #[derive(Debug, Clone)] pub struct CaptureSetup { @@ -26,9 +27,8 @@ pub struct CaptureSetup { pub ffmpeg_path: PathBuf, pub width: u32, pub height: u32, - #[allow(dead_code)] - pub fps: u32, pub crop: Option, + pub pipe_fps: u32, pub frame_counter: Arc, } @@ -60,10 +60,6 @@ impl GraphicsCaptureApiHandler for CaptureHandler { setup.width }; - // Capture at declared rate, apply fps filter to normalize timestamps. - // fix_intermediate_fps re-encodes with measured actual rate after. - filter_parts.push(format!("fps={}", setup.fps)); - if working_width > MAX_ENCODE_WIDTH { filter_parts.push(format!("scale={}:-2", MAX_ENCODE_WIDTH)); } else { @@ -74,13 +70,14 @@ impl GraphicsCaptureApiHandler for CaptureHandler { // The capture API delivers frames at the monitor's refresh rate, not the // user's chosen FPS. We must tell ffmpeg the actual rate so timestamps are // correct. The fps filter in the export pipeline handles the conversion. - tracing::info!("capture: size={}x{}", setup.width, setup.height); - - // Declare a high-ish framerate so ffmpeg accepts all frames from the pipe. - // The actual delivery rate varies; fix_intermediate_fps re-encodes with - // the measured rate after capture. - let capture_fps = 120u32; + tracing::info!( + "capture: size={}x{} pipe_fps={}", + setup.width, setup.height, setup.pipe_fps + ); + // Declare the detected refresh rate so ffmpeg accepts all frames from the + // pipe. The actual delivery rate varies; fix_intermediate_fps re-encodes + // with the measured rate after capture. let mut cmd = Command::new(&setup.ffmpeg_path); cmd.arg("-y") .arg("-hide_banner") @@ -88,12 +85,15 @@ impl GraphicsCaptureApiHandler for CaptureHandler { .args(["-f", "rawvideo"]) .args(["-pixel_format", "bgra"]) .args(["-video_size", &format!("{}x{}", setup.width, setup.height)]) - .args(["-framerate", &capture_fps.to_string()]) + .args(["-framerate", &setup.pipe_fps.to_string()]) .args(["-i", "-"]) .args(["-vf", &filter]) .args(["-c:v", "libx264"]) .args(["-preset", "ultrafast"]) .args(["-tune", "zerolatency"]) + .args(["-color_primaries", "bt709"]) + .args(["-color_trc", "bt709"]) + .args(["-colorspace", "bt709"]) .args(["-pix_fmt", "yuv420p"]) .args(["-movflags", "+faststart"]) .arg(&setup.output_path) @@ -118,13 +118,13 @@ impl GraphicsCaptureApiHandler for CaptureHandler { }); } - let frame_size = (setup.width as usize) * (setup.height as usize) * 4; + let pixels = (setup.width as usize) * (setup.height as usize); Ok(Self { stdin: Some(stdin), child: Some(child), width: setup.width, height: setup.height, - scratch: Vec::with_capacity(frame_size), + scratch: Vec::with_capacity(pixels * 4), frame_count: setup.frame_counter.clone(), }) } @@ -141,9 +141,15 @@ impl GraphicsCaptureApiHandler for CaptureHandler { let buf = frame .buffer() .map_err(|e| anyhow!("frame buffer: {e:?}"))?; - self.scratch.clear(); - let bytes = buf.as_nopadding_buffer(&mut self.scratch); let expected = (self.width as usize) * (self.height as usize) * 4; + if buf.has_padding() { + // windows-capture copies padded rows into the provided Vec, but only + // grows it when capacity is too small. Keep len valid. + self.scratch.resize(expected, 0); + } else { + self.scratch.clear(); + } + let bytes = buf.as_nopadding_buffer(&mut self.scratch); if bytes.len() < expected { tracing::warn!("frame buffer too small: got {} bytes, expected {}", bytes.len(), expected); return Ok(()); @@ -172,6 +178,7 @@ pub struct CaptureSession { pub width: u32, pub height: u32, pub crop: Option, + pub pipe_fps: u32, pub frame_counter: Arc, control: CaptureControl, } @@ -187,23 +194,36 @@ pub fn primary_monitor_dims() -> Result<(u32, u32)> { Ok((w & !1, h & !1)) } -#[allow(dead_code)] -/// Detect the primary monitor's refresh rate in Hz. -/// Falls back to 60 if detection fails. -fn detect_monitor_refresh_rate() -> u32 { - use windows::Win32::Graphics::Gdi::{DEVMODEW, ENUM_CURRENT_SETTINGS, EnumDisplaySettingsW}; - unsafe { - let mut devmode: DEVMODEW = std::mem::zeroed(); - devmode.dmSize = std::mem::size_of::() as u16; - if EnumDisplaySettingsW(None, ENUM_CURRENT_SETTINGS, &mut devmode).as_bool() && devmode.dmDisplayFrequency > 0 { - return devmode.dmDisplayFrequency as u32; +/// Detect the monitor's refresh rate (Hz) via `Monitor::refresh_rate`, which +/// resolves the device name through `GetMonitorInfoW` and queries its current +/// settings with `EnumDisplaySettingsW`. Falls back to [`FALLBACK_REFRESH_HZ`] +/// on any failure. +fn monitor_refresh_rate(monitor: &Monitor) -> u32 { + match monitor.refresh_rate() { + Ok(0) => { + tracing::warn!("monitor reported 0 Hz refresh, using fallback"); + FALLBACK_REFRESH_HZ + } + Ok(hz) => hz, + Err(e) => { + tracing::warn!("refresh rate detection failed ({e:?}), using fallback"); + FALLBACK_REFRESH_HZ } } - 60 // fallback +} + +/// Pick the pipe framerate ffmpeg should declare for raw input from the +/// capture API. WGC delivers frames roughly at the monitor's refresh rate; +/// declaring that rate (instead of a fixed high constant) keeps the raw +/// timestamps close to real time so `fix_intermediate_fps` only nudges. +fn detect_pipe_framerate(monitor: &Monitor) -> u32 { + monitor_refresh_rate(monitor) } /// Find the monitor containing the given screen point using the Win32 API. /// Falls back to the primary monitor if no monitor is found. +/// Resolve the monitor containing the given screen point, falling back to the +/// primary monitor on failure. fn monitor_at_point(x: i32, y: i32) -> Result { use windows::Win32::Foundation::POINT; use windows::Win32::Graphics::Gdi::{MonitorFromPoint, MONITOR_DEFAULTTONEAREST}; @@ -214,8 +234,7 @@ fn monitor_at_point(x: i32, y: i32) -> Result { bail!("MonitorFromPoint returned null for ({x}, {y})"); } // SAFETY: hmonitor is a valid monitor handle from MonitorFromPoint. - let monitor = Monitor::from_raw_hmonitor(hmonitor.0 as *mut _); - Ok(monitor) + Ok(Monitor::from_raw_hmonitor(hmonitor.0)) } pub fn start( @@ -224,7 +243,7 @@ pub fn start( capture_cursor: bool, _audio: bool, crop: Option, - fps: u32, + _fps: u32, ) -> Result { // Use the center of the capture region to determine which monitor to capture. // If the region spans monitors, we pick the one containing the center. @@ -252,13 +271,15 @@ pub fn start( let frame_counter = Arc::new(std::sync::atomic::AtomicU64::new(0)); + let pipe_fps = detect_pipe_framerate(&monitor); + let setup = CaptureSetup { output_path: output_path.clone(), ffmpeg_path, width, height, - fps, crop, + pipe_fps, frame_counter: frame_counter.clone(), }; @@ -288,6 +309,7 @@ pub fn start( width: out_w, height: out_h, crop, + pipe_fps, frame_counter, control, }) @@ -327,8 +349,8 @@ impl CaptureSession { } /// Re-encode the intermediate file with correct timestamps. -/// The capture declares -framerate N and applies fps=M filter. -/// This scales PTS to match real-time duration. +/// The capture declares a fixed pipe framerate and later scales PTS to match +/// real-time duration from the measured frame count. /// /// Idempotent: if `input` has already been consumed (e.g. a previous /// pause/resume cycle ran this to completion and removed it), and @@ -339,7 +361,7 @@ pub fn fix_intermediate_fps( output: &std::path::Path, elapsed_secs: f64, frame_count: u64, - capture_fps: u32, + pipe_fps: u32, ) -> Result<()> { use std::process::Command; @@ -350,17 +372,31 @@ pub fn fix_intermediate_fps( if frame_count == 0 || elapsed_secs <= 0.0 { tracing::warn!("capture fix: no frames counted, keeping original"); - let _ = std::fs::rename(input, output); - return Ok(()); + return rename_or_copy(input, output); } - let actual_fps = frame_count as f64 / elapsed_secs; - let pts_scale = capture_fps as f64 / actual_fps; + let (actual_fps, pts_scale) = capture_timing(frame_count, elapsed_secs, pipe_fps) + .expect("frame_count and elapsed_secs were checked above"); tracing::info!( - "capture fix: {frame_count} frames in {elapsed_secs:.1}s = {actual_fps:.1}fps (declared {capture_fps}), pts_scale={pts_scale:.2}" + "capture fix: {frame_count} frames in {elapsed_secs:.1}s = {actual_fps:.1}fps (declared {pipe_fps}), pts_scale={pts_scale:.4}" ); - // Re-encode with scaled PTS to fix timing + // If the measured rate already matches the declared pipe rate within 2%, + // the timestamps are already correct - the capture API's clock and the + // ffmpeg input clock agree. Skip the lossy re-encode and just rename. + // This is the common case now that pipe_fps tracks the monitor's refresh + // rate instead of a fixed high constant. + if (pts_scale - 1.0).abs() <= 0.02 { + tracing::debug!( + "capture fix: pts_scale={pts_scale:.4} within no-op tolerance, renaming without re-encode" + ); + return rename_or_copy(input, output); + } + + // Re-encode with scaled PTS to fix timing. + // CRF 18 is visually lossless and avoids a second generation of H264 + // quantization on top of the segment encode. The preset stays fast so the + // re-encode does not stall stop/pause/resume. let status = Command::new(ffmpeg) .arg("-y") .arg("-hide_banner") @@ -368,7 +404,11 @@ pub fn fix_intermediate_fps( .args(["-i", &input.to_string_lossy()]) .args(["-vf", &format!("setpts=PTS*{:.4}", pts_scale)]) .args(["-c:v", "libx264"]) - .args(["-preset", "ultrafast"]) + .args(["-preset", "veryfast"]) + .args(["-crf", "18"]) + .args(["-color_primaries", "bt709"]) + .args(["-color_trc", "bt709"]) + .args(["-colorspace", "bt709"]) .args(["-pix_fmt", "yuv420p"]) .arg(output) .status() @@ -378,7 +418,44 @@ pub fn fix_intermediate_fps( let _ = std::fs::remove_file(input); } else { tracing::warn!("capture fix: re-encode failed, keeping original"); - let _ = std::fs::rename(input, output); + let _ = rename_or_copy(input, output); } Ok(()) } + +/// Move `input` to `output`, falling back to a copy if the rename fails +/// (e.g. cross-volume or a handle still holds the file on Windows). +fn rename_or_copy(input: &std::path::Path, output: &std::path::Path) -> Result<()> { + std::fs::rename(input, output) + .or_else(|_| std::fs::copy(input, output).map(|_| ())) + .with_context(|| format!("moving {} to {}", input.display(), output.display()))?; + Ok(()) +} + +fn capture_timing(frame_count: u64, elapsed_secs: f64, pipe_fps: u32) -> Option<(f64, f64)> { + if frame_count == 0 || elapsed_secs <= 0.0 { + return None; + } + let actual_fps = frame_count as f64 / elapsed_secs; + Some((actual_fps, pipe_fps as f64 / actual_fps)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn timing_scale_uses_declared_pipe_rate() { + let (actual_fps, pts_scale) = capture_timing(600, 10.0, 60).unwrap(); + assert_eq!(actual_fps, 60.0); + assert_eq!(pts_scale, 1.0); + } + + #[test] + fn timing_scale_for_high_pipe_rate() { + // 600 frames in 10s = 60 actual; pipe declared 120 -> pts scale 2.0 + let (actual_fps, pts_scale) = capture_timing(600, 10.0, 120).unwrap(); + assert_eq!(actual_fps, 60.0); + assert_eq!(pts_scale, 2.0); + } +} diff --git a/src-tauri/src/encode.rs b/src-tauri/src/encode.rs index 7e9d66c..9537713 100644 --- a/src-tauri/src/encode.rs +++ b/src-tauri/src/encode.rs @@ -228,6 +228,40 @@ fn webm_video_codec(c: WebmCodec) -> &'static str { } } +/// 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)] +pub 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 fn all_unknown() -> Self { + Self { h264: true, h265: true, vp9: true, av1: true } + } +} + +pub fn codec_availability(ffmpeg: &Path) -> CodecAvailability { + let encoders = match list_encoders(ffmpeg) { + Ok(set) => set, + Err(_) => 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 = (req.target_bytes as f64) * 8.0 * 0.95; let audio_bits = if req.keep_audio { @@ -376,6 +410,68 @@ fn cleanup_pass_logs(stem: &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); + + // Build a throwaway request scoped to the sample window. + let mut sample_req = req.clone(); + sample_req.output = sample_path.clone(); + 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; + + let result = encode_gif_pass(ffmpeg, &sample_req, est_width, est_fps); + let _ = std::fs::remove_file(&sample_path); + if result.is_err() { + return None; + } + let sample_bytes = match std::fs::metadata(&sample_path) { + Ok(m) => m.len(), + Err(_) => return None, + }; + 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 = (est_width as f64 / aspect).round() as u32; + let frames = (est_fps as f64 * sample_dur).max(1.0); + let measured_bpp = sample_bytes as f64 / (est_width as f64 * sample_h as f64 * 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 = (req.gif_colors as f64 / 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 = ((est_width as f64 * ratio.sqrt()).round() as u32 / 2).max(60) * 2; + let new_fps = ((est_fps as f64 * ratio.sqrt()).round() as u32).max(1).min(est_fps); + Some((new_width.min(1280), new_fps)) +} + fn encode_gif(ffmpeg: &Path, req: &TranscodeRequest) -> Result<()> { let budget_input = GifBudgetInput { gif_colors: req.gif_colors, @@ -385,6 +481,21 @@ fn encode_gif(ffmpeg: &Path, req: &TranscodeRequest) -> Result<()> { 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 req.duration_secs > 4.0 { + if let Some((calibrated_w, calibrated_fps)) = calibrate_via_sample(ffmpeg, req, scale_width, effective_fps) { + tracing::info!( + "gif calibration: sample suggested {calibrated_w}x @ {calibrated_fps}fps (initial was {scale_width}x @ {effective_fps}fps)" + ); + scale_width = calibrated_w; + effective_fps = calibrated_fps; + } + } + 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. @@ -529,13 +640,14 @@ fn encode_gif_pass( // 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={w}:-1:flags=lanczos,split[s0][s1];[s0]palettegen=stats_mode=diff:max_colors={colors}[p];[s1][p]paletteuse=dither={d}", + "{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, - w = scale_width, + scale = scale, colors = req.gif_colors, d = dither, ); @@ -567,6 +679,12 @@ fn encode_gif_pass( 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 struct GifBudgetInput { pub gif_colors: u16, @@ -682,29 +800,39 @@ pub fn render_gif_preview( if let Some(parent) = out_path.parent() { std::fs::create_dir_all(parent).context("creating preview parent")?; } - // Generate palette from a sample of the clip (middle 2 seconds or full clip) - let palette_path = out_path.parent().unwrap_or(input.parent().unwrap()).join("preview-palette.png"); + // 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_filter = format!( - "scale={}:-2:flags=lanczos,palettegen=stats_mode=diff:max_colors={}", - 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")?; + let palette_key = palette_cache_key(gif_colors, target_width, sample_start, sample_dur); + let palette_path = out_path.parent().unwrap_or(input.parent().unwrap()) + .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!( - "scale={}:-2:flags=lanczos[x];[x][1:v]paletteuse=dither={}", - target_width, gif_dither + "{}[x];[x][1:v]paletteuse=dither={}", + gif_rgb_scale_filter(target_width), gif_dither ); let mut encode = Command::new(ffmpeg); encode.arg("-y") @@ -722,6 +850,28 @@ pub fn render_gif_preview( result } +/// 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{:.3}-d{:.3}", + sample_start, sample_dur + ) +} + +/// 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() { + if name.starts_with("preview-palette-") && name.ends_with(".png") { + let _ = std::fs::remove_file(entry.path()); + } + } + } + } +} + pub fn extract_thumbnails( ffmpeg: &Path, input: &Path, @@ -858,15 +1008,17 @@ pub fn concat_segments(ffmpeg: &Path, segments: &[PathBuf], output: &Path) -> Re } fn run(cmd: &mut Command, label: &str) -> Result<()> { - let output = run_impl(cmd, label, 0, 0, 0.0, 0, None, None)?; + 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. -/// progress_tx, if provided, receives (pass, total_passes, percent) updates. +/// 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, @@ -877,7 +1029,13 @@ fn run_with_progress( progress_tx: Option<&Sender>, cancel: Option<&Arc>, ) -> Result<()> { - let output = run_impl(cmd, label, pass, total_passes, duration_secs, fps, progress_tx.cloned(), cancel.cloned())?; + // 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)); } @@ -915,9 +1073,10 @@ fn run_impl( progress_pass: u8, progress_total_passes: u8, progress_duration_secs: f64, - progress_fps: u32, + _progress_fps: u32, progress_tx: Option>, cancel: Option>, + read_stdout: bool, ) -> Result { use std::process::Stdio; @@ -930,40 +1089,57 @@ fn run_impl( } tracing::debug!("{}", printable.to_string_lossy()); + // 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(Stdio::null()) + .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(); - let mut stderr_handle: Option>> = stderr.map(move |serr| { + // 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.as_ref().map(|t| t.clone()); - let encode_dur = progress_duration_secs; - let fps = progress_fps; + 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 mut collected = Vec::new(); - let reader = BufReader::new(serr); + let reader = BufReader::new(out); + let mut last_out_time_us: f64 = 0.0; for line in reader.lines().map_while(Result::ok) { - collected.extend_from_slice(line.as_bytes()); - collected.push(b'\n'); - if let Some(frame) = parse_frame_from_stderr(&line) { - let total = (encode_dur * fps as f64).max(1.0); - let percent = (frame / total * 100.0).min(100.0); - if let Some(ref sender) = tx { - let _ = sender.send(EncodeProgress { - pass, - total_passes, - percent, - }); + if let Some((key, value)) = parse_progress_kv(&line) { + if key == "out_time_us" { + last_out_time_us = value; + } else if key == "progress" { + let percent = (last_out_time_us / encode_dur_us * 100.0).clamp(0.0, 100.0); + if let Some(ref sender) = tx { + let _ = sender.send(EncodeProgress { + pass, + total_passes, + percent, + }); + } } } } + }) + }); + + // Stderr reader: collect bytes for diagnostics. No more frame regex. + let mut stderr_handle: Option>> = stderr.map(move |serr| { + thread::spawn(move || { + let mut collected = Vec::new(); + use std::io::Read; + let mut s = serr; + let _ = s.read_to_end(&mut collected); collected }) }); @@ -973,14 +1149,14 @@ fn run_impl( if c.load(Ordering::Relaxed) { let _ = child.kill(); let _ = child.wait(); - if let Some(h) = stderr_handle.take() { - let _ = h.join(); - } + if let Some(h) = stdout_handle.take() { let _ = h.join(); } + if let Some(h) = stderr_handle.take() { let _ = h.join(); } bail!("export cancelled"); } } match child.try_wait() { Ok(Some(status)) => { + if let Some(h) = stdout_handle.take() { let _ = h.join(); } let stderr_bytes = stderr_handle.take() .and_then(|h| h.join().ok()) .unwrap_or_default(); @@ -998,20 +1174,15 @@ fn run_impl( } } -/// Parse a frame count from an ffmpeg stderr progress line. -/// Lines look like: "frame= 123 fps= 30 q=-0.0 size= 1024kB time=00:00:04.10 ..." -fn parse_frame_from_stderr(line: &str) -> Option { - let trimmed = line.trim(); - if !trimmed.starts_with("frame=") { - return None; - } - // Find the "frame= NNN" token and extract the number after it. - let after = trimmed.strip_prefix("frame=")?.trim_start(); - let end = after - .find(|c: char| !c.is_ascii_digit()) - .unwrap_or(after.len()); - let frame_str = &after[..end]; - frame_str.parse().ok() +/// 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)] @@ -1091,16 +1262,38 @@ mod tests { } #[test] - fn parse_ffmpeg_stderr_frame() { - assert_eq!( - parse_frame_from_stderr("frame= 123 fps= 30 q=-0.0 size= 1024kB"), - Some(123.0) - ); - assert_eq!( - parse_frame_from_stderr("frame=9999 fps=60.0"), - Some(9999.0) - ); - assert_eq!(parse_frame_from_stderr("size= 1024kB"), None); + 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] diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index e0f8dcd..77a69ab 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -66,6 +66,11 @@ pub struct SessionState { pub monitor_height: u32, pub clicks: Vec, pub segment_start_offsets: Vec, + /// Wall-clock time the first video segment began. Used to align the head + /// of the audio track (which starts a little later due to WASAPI init). + pub video_started_at: Option, + /// Wall-clock time the first audio segment began capturing. + pub audio_started_at: Option, } #[derive(Debug, Clone, Serialize)] @@ -315,6 +320,7 @@ fn clear_temp_segments(app_dir: &Path) { if let Some(name) = entry.file_name().to_str() { if (name.starts_with("segment-") && name.ends_with(".mp4")) || (name.starts_with("audio-") && name.ends_with(".pcm")) + || (name.starts_with("preview-palette-") && name.ends_with(".png")) { let _ = std::fs::remove_file(entry.path()); } @@ -357,6 +363,37 @@ fn adjust_audio_length(path: &Path, sample_rate: u32, channels: u16, target_secs Ok(()) } +/// Prepend `head_secs` of silence to a raw f32le PCM file so the audio track +/// aligns with the video start. WASAPI init adds a delay between capture +/// start and the first audio packet; this pads the gap. +fn pad_audio_head(path: &Path, sample_rate: u32, channels: u16, head_secs: f64) -> Result<()> { + use std::io::{Read, Write}; + let bytes_per_sec = sample_rate as f64 * channels as f64 * 4.0; + let pad_bytes = (head_secs * bytes_per_sec).round() as u64; + if pad_bytes == 0 { + return Ok(()); + } + let mut existing = Vec::new(); + { + let mut f = std::fs::File::open(path)?; + f.read_to_end(&mut existing)?; + } + let mut f = std::fs::File::create(path)?; + let zeros = vec![0u8; 64 * 1024]; + let mut remaining = pad_bytes; + while remaining > 0 { + let to_write = remaining.min(zeros.len() as u64) as usize; + f.write_all(&zeros[..to_write])?; + remaining -= to_write as u64; + } + f.write_all(&existing)?; + tracing::debug!( + "padded audio head with {:.1}ms ({} bytes) of silence", + head_secs * 1000.0, pad_bytes + ); + Ok(()) +} + fn set_overlay_clickthrough(app: &AppHandle, enabled: bool) { if let Some(win) = app.get_webview_window("overlay") { let _ = win.set_ignore_cursor_events(enabled); @@ -453,6 +490,8 @@ fn start_capture( monitor_height: monitor_h, clicks: Vec::new(), segment_start_offsets: vec![0.0], + video_started_at: Some(session.started_at), + audio_started_at: audio_session.as_ref().map(|a| a.started_at), }; let click_rec = start_click_recorder(cfg.capture.capture_cursor); @@ -471,11 +510,11 @@ fn pause_capture(state: State<'_, AppState>) -> Result<(), String> { .ok_or_else(|| "no capture in progress".to_string())?; let elapsed = session.started_at.elapsed().as_secs_f64(); let frames = session.frame_counter.load(std::sync::atomic::Ordering::Relaxed); + let pipe_fps = session.pipe_fps; let raw_path = session.stop().map_err(|e| format!("{e:#}"))?; let ffmpeg = bootstrap::ffmpeg_path(&state.app_dir); - let cap_fps = lock(&state.config).capture.default_fps; let fixed_path = raw_path.with_extension("fixed.mp4"); - capture::fix_intermediate_fps(&ffmpeg, &raw_path, &fixed_path, elapsed, frames, cap_fps) + capture::fix_intermediate_fps(&ffmpeg, &raw_path, &fixed_path, elapsed, frames, pipe_fps) .map_err(|e| format!("fixing fps: {e:#}"))?; let path = if fixed_path.exists() { fixed_path } else { raw_path }; @@ -602,11 +641,11 @@ fn stop_capture(app: AppHandle, state: State<'_, AppState>) -> Result) -> Result video_start { + let head_offset_secs = audio_start.duration_since(video_start).as_secs_f64(); + if head_offset_secs > 0.001 { + pad_audio_head( + &audio_concat, + ss.audio_sample_rate.unwrap(), + ss.audio_channels.unwrap(), + head_offset_secs, + ) + .map_err(|e| format!("padding audio head: {e:#}"))?; + } + } + } adjust_audio_length( &audio_concat, ss.audio_sample_rate.unwrap(), @@ -821,6 +877,20 @@ pub struct GifEstimate { pub dims_label: String, } +#[derive(Debug, Serialize)] +pub struct GifEstimateTable { + /// Sorted ascending. Frontend interpolates between points. + pub points: Vec, +} + +#[derive(Debug, Serialize)] +pub struct GifEstimatePoint { + pub target_bytes: u64, + pub width: u32, + pub fps: u32, + pub height: u32, +} + #[tauri::command] fn estimate_gif_params(request: PreviewRequest) -> GifEstimate { let budget = encode::GifBudgetInput { @@ -833,9 +903,44 @@ fn estimate_gif_params(request: PreviewRequest) -> GifEstimate { let (w, fps) = encode::gif_params(&budget, request.clip_width, request.clip_height); let height = encode::gif_height_for_width(w, request.clip_width, request.clip_height); let dims_label = format!("{w}x{height} @ {fps}fps"); + GifEstimate { width: w, fps, height, dims_label } } +/// Return estimates for a grid of target_bytes values so the frontend can +/// interpolate on slider drag without an IPC per debounce tick. The grid is +/// geometric from 100KB to 200MB. +#[tauri::command] +fn estimate_gif_params_table(request: PreviewRequest) -> GifEstimateTable { + let colors = request.gif_colors.unwrap_or(256); + let dur = request.duration_secs.unwrap_or(0.0).max(0.1); + let fps = request.fps; + let mode = request.gif_budget_mode; + + // Geometric grid: 100KB, 200KB, 500KB, 1MB, 2MB, 5MB, 10MB, 20MB, 50MB, 100MB, 200MB + const GRID: &[u64] = &[ + 100_000, 200_000, 500_000, + 1_048_576, 2_097_152, 5_242_880, + 10_485_760, 20_971_520, 52_428_800, + 104_857_600, 209_715_200, + ]; + + let mut points = Vec::with_capacity(GRID.len()); + for &target in GRID { + let budget = encode::GifBudgetInput { + gif_colors: colors, + target_bytes: target, + fps, + duration_secs: dur, + gif_budget_mode: mode, + }; + let (w, f) = encode::gif_params(&budget, request.clip_width, request.clip_height); + let h = encode::gif_height_for_width(w, request.clip_width, request.clip_height); + points.push(GifEstimatePoint { target_bytes: target, width: w, fps: f, height: h }); + } + GifEstimateTable { points } +} + #[cfg(test)] mod tests { use super::*; @@ -1467,13 +1572,25 @@ fn cancel_export(state: State<'_, AppState>) { } #[tauri::command] -fn export(app: AppHandle, state: State<'_, AppState>, request: ExportRequest) -> Result { - let cfg = lock(&state.config).clone(); - let clip = lock(&state.last_clip) - .clone() - .ok_or_else(|| "no recorded clip available".to_string())?; - +fn codec_availability(state: State<'_, AppState>) -> Result { let ffmpeg = bootstrap::ffmpeg_path(&state.app_dir); + if !ffmpeg.is_file() { + return Ok(encode::CodecAvailability::all_unknown()); + } + Ok(encode::codec_availability(&ffmpeg)) +} + +#[tauri::command] +async fn export(app: AppHandle, state: State<'_, AppState>, request: ExportRequest) -> Result { + let (cfg, clip, app_dir, export_cancel) = { + let cfg = lock(&state.config).clone(); + let clip = lock(&state.last_clip) + .clone() + .ok_or_else(|| "no recorded clip available".to_string())?; + (cfg, clip, state.app_dir.clone(), state.export_cancel.clone()) + }; + + let ffmpeg = bootstrap::ffmpeg_path(&app_dir); if !ffmpeg.is_file() { return Err("ffmpeg.exe not found - run the encoder setup first".to_string()); } @@ -1481,7 +1598,7 @@ fn export(app: AppHandle, state: State<'_, AppState>, request: ExportRequest) -> let out_path: PathBuf = match request.output_path.as_deref() { Some(p) if !p.trim().is_empty() => PathBuf::from(p), _ => { - let out_dir = output_dir(&state.app_dir, &cfg); + let out_dir = output_dir(&app_dir, &cfg); out_dir.join(format!( "bytesize-{}.{}", timestamp_slug(), @@ -1539,7 +1656,7 @@ fn export(app: AppHandle, state: State<'_, AppState>, request: ExportRequest) -> gif_colors: request.gif_colors.unwrap_or(256), webm_codec: cfg.export.webm_codec, mp4_codec: cfg.export.mp4_codec, - scratch_dir: temp_dir(&state.app_dir), + scratch_dir: temp_dir(&app_dir), crop: request.crop, gif_budget_mode: request.gif_budget_mode, deleted_frame_indices: request.deleted_frame_indices, @@ -1549,7 +1666,7 @@ fn export(app: AppHandle, state: State<'_, AppState>, request: ExportRequest) -> clip_width: clip.width, clip_height: clip.height, progress_tx: None, - cancel: Some(state.export_cancel.clone()), + cancel: Some(export_cancel.clone()), }; let total_passes: u8 = if request.format == crate::config::Format::Gif { 1 } else { 2 }; @@ -1572,8 +1689,18 @@ fn export(app: AppHandle, state: State<'_, AppState>, request: ExportRequest) -> } }); - state.export_cancel.store(false, Ordering::SeqCst); - encode::transcode(&ffmpeg, &req_with_progress).map_err(|e| format!("{e:#}"))?; + export_cancel.store(false, Ordering::SeqCst); + + // Run the (potentially minutes-long) ffmpeg encode on a blocking thread so + // we don't hold a Tauri async worker for the whole duration. + let ffmpeg_arc = std::sync::Arc::new(ffmpeg); + let ffmpeg_for_task = ffmpeg_arc.clone(); + let result = tauri::async_runtime::spawn_blocking(move || { + encode::transcode(&ffmpeg_for_task, &req_with_progress) + }) + .await + .map_err(|e| format!("encode task panicked: {e:#}"))?; + result.map_err(|e| format!("{e:#}"))?; let size_bytes = std::fs::metadata(&out_path) .map(|m| m.len()) @@ -1587,6 +1714,11 @@ fn export(app: AppHandle, state: State<'_, AppState>, request: ExportRequest) -> pub fn run() { let app_dir = exe_dir().expect("resolve exe directory"); + // Sweep temp/ before anything else so a crash on the previous run does not + // leave orphaned segments, previews, or thumbs behind - the portability + // spec promises no trace, and stale temp is trace. + clear_temp_segments(&app_dir); + let log_dir = app_dir.join("logs"); let _ = std::fs::create_dir_all(&log_dir); let file_appender = tracing_appender::rolling::daily(&log_dir, "bytesize.log"); @@ -1742,6 +1874,7 @@ pub fn run() { render_preview, render_raw_preview, estimate_gif_params, + estimate_gif_params_table, reveal_in_explorer, open_url, show_overlay, @@ -1756,6 +1889,7 @@ pub fn run() { close_window_picker, get_overlay_rect, cancel_export, + codec_availability, ]) .build(tauri::generate_context!()) .expect("error while building ByteSize"); diff --git a/src/lib/Main.svelte b/src/lib/Main.svelte index d190010..27c31bc 100644 --- a/src/lib/Main.svelte +++ b/src/lib/Main.svelte @@ -74,17 +74,21 @@ // Derived let trimmedDuration = $derived(Math.max(0.1, trimEnd - trimStart)) // GIF size/dimensions estimate - computed by the Rust backend so the - // math stays in lockstep with encode.rs::gif_params. + // math stays in lockstep with encode.rs::gif_params. We fetch a table of + // estimates across a target-bytes grid once per parameter set (fps, dims, + // duration, mode, colors) and interpolate on slider drag locally to avoid + // one IPC per debounce tick. let gifEstimate: { width: number; fps: number; height: number; dims_label: string } | null = $state(null) let gifEstimateTimer: number | null = null + let gifTable: { key: string; points: { target_bytes: number; width: number; fps: number; height: number }[] } | null = $state(null) - async function refreshGifEstimate() { - if (!clip || format !== "gif") { gifEstimate = null; return } + async function refreshGifTable() { + if (!clip || format !== "gif") { gifTable = null; return } + const key = `${fps}|${gifBudgetMode}|${gifColors}|${clip.width}x${clip.height}|${trimmedDuration}` try { - gifEstimate = await api.estimateGifParams({ + const table = await api.estimateGifParamsTable({ format: "gif", fps, - target_bytes: Math.round(targetMB * 1_048_576), gif_budget_mode: gifBudgetMode, gif_dither: gifDither, gif_colors: gifColors, @@ -92,26 +96,50 @@ clip_height: clip.height, duration_secs: trimmedDuration, }) + gifTable = { key, points: table.points } } catch { - gifEstimate = null + gifTable = null } } - // Debounced reactive estimate: any change to the inputs re-estimates - // ~150 ms after the last change. Cancels in-flight when inputs change again. + // Interpolate the cached table for the current target_bytes. GIF width/fps + // are step functions of budget, so we find the bracketing grid points and + // pick the lower one (slightly conservative on dims). + function interpolateTable(): { width: number; fps: number; height: number; dims_label: string } | null { + if (!gifTable || gifTable.points.length === 0) return null + const target = Math.round(targetMB * 1_048_576) + const pts = gifTable.points + let chosen = pts[0] + for (const p of pts) { + if (p.target_bytes <= target) chosen = p + else break + } + const { width, fps, height } = chosen + return { width, fps, height, dims_label: `${width}x${height} @ ${fps}fps` } + } + + // Debounced: re-fetch the table when any non-target parameter changes; + // re-interpolate when targetMB changes (local, no IPC). $effect(() => { - // Touch every input so the effect re-runs on any of them changing. - void phase; void clip; void format; void fps; void targetMB - void gifBudgetMode; void gifDither; void gifColors - void trimStart; void trimEnd - if (phase !== "editing" || !clip) return - if (gifEstimateTimer !== null) clearTimeout(gifEstimateTimer) - gifEstimateTimer = window.setTimeout(() => { void refreshGifEstimate() }, 150) + void phase; void clip; void format + if (phase !== "editing" || !clip || format !== "gif") { gifTable = null; gifEstimate = null; return } + const key = `${fps}|${gifBudgetMode}|${gifColors}|${clip.width}x${clip.height}|${trimmedDuration}` + if (!gifTable || gifTable.key !== key) { + if (gifEstimateTimer !== null) clearTimeout(gifEstimateTimer) + gifEstimateTimer = window.setTimeout(() => { void refreshGifTable() }, 150) + } return () => { if (gifEstimateTimer !== null) { clearTimeout(gifEstimateTimer); gifEstimateTimer = null } } }) + // Local interpolation on targetMB changes - no IPC. + $effect(() => { + void targetMB + if (phase !== "editing" || !clip || format !== "gif") { gifEstimate = null; return } + gifEstimate = interpolateTable() + }) + let previewDims = $derived.by(() => { if (!clip) return "" if (format === "gif") { @@ -267,14 +295,22 @@ if (format !== "gif") { thumbnails = []; return } const cacheKey = `${format}-${fps}` const cached = thumbCache.get(cacheKey) - if (cached) { thumbnails = cached; deletedFrames = new Set(); return } + if (cached) { + // Promote to most-recently-used so eviction is LRU, not FIFO. + // Map iteration is insertion-order; delete + re-set moves the key to the end. + thumbCache.delete(cacheKey) + thumbCache.set(cacheKey, cached) + thumbnails = cached + deletedFrames = new Set() + return + } loadingThumbs = true try { const thumbs = await api.extractThumbnails(fps) thumbCache.set(cacheKey, thumbs) if (thumbCache.size > 5) { - const firstKey = thumbCache.keys().next().value - if (firstKey) thumbCache.delete(firstKey) + const oldestKey = thumbCache.keys().next().value + if (oldestKey) thumbCache.delete(oldestKey) } thumbnails = thumbs deletedFrames = new Set() diff --git a/src/lib/Settings.svelte b/src/lib/Settings.svelte index 66505ea..cadb5b8 100644 --- a/src/lib/Settings.svelte +++ b/src/lib/Settings.svelte @@ -1,6 +1,6 @@