From 4ca802ef711fd2307c438824e904c02655c8eba0 Mon Sep 17 00:00:00 2001 From: lashman Date: Thu, 4 Jun 2026 23:09:13 +0300 Subject: [PATCH] tighten export and capture handling --- src-tauri/src/audio.rs | 190 +++++++++++------- src-tauri/src/bootstrap.rs | 78 +++++--- src-tauri/src/capture.rs | 9 + src-tauri/src/config.rs | 25 ++- src-tauri/src/encode.rs | 220 +++++++++++++++------ src-tauri/src/lib.rs | 53 +++-- src-tauri/src/updates.rs | 55 +++++- src/lib/ExportSidebar.svelte | 200 +++++++++++++++++++ src/lib/GifControls.svelte | 2 + src/lib/Main.svelte | 304 +++++------------------------ src/lib/Preview.svelte | 11 +- src/lib/TrimPanel.svelte | 21 +- src/lib/exportSizing.ts | 9 + src/lib/trimPreviewState.svelte.ts | 15 ++ 14 files changed, 736 insertions(+), 456 deletions(-) create mode 100644 src/lib/ExportSidebar.svelte create mode 100644 src/lib/exportSizing.ts create mode 100644 src/lib/trimPreviewState.svelte.ts diff --git a/src-tauri/src/audio.rs b/src-tauri/src/audio.rs index 5069969..f01319a 100644 --- a/src-tauri/src/audio.rs +++ b/src-tauri/src/audio.rs @@ -176,6 +176,17 @@ fn capture_thread( unsafe { let _ = client.Stop(); } + + // Drain any remaining packets that were buffered before Stop(). + // Without this, the last ~5ms of audio would be silently dropped. + drain_remaining_packets( + &capture_client, + channels, + bits_per_sample, + is_float, + &mut writer, + )?; + writer.flush().context("flushing audio writer")?; result @@ -198,74 +209,7 @@ fn capture_loop( }; while packet_length > 0 { - let mut data_ptr = std::ptr::null_mut(); - let mut num_frames_available = 0u32; - let mut flags = 0u32; - // SAFETY: GetBuffer provides valid data_ptr and metadata for the current packet. - unsafe { - capture_client - .GetBuffer( - &mut data_ptr, - &mut num_frames_available, - &mut flags, - None, - None, - ) - .context("GetBuffer")?; - } - - if num_frames_available > 0 { - let is_silent = (flags & AUDCLNT_BUFFERFLAGS_SILENT) != 0; - let samples = (num_frames_available as usize) * (channels as usize); - - if is_silent { - let zero_bytes = samples * 4; - let zeros = vec![0u8; zero_bytes]; - writer.write_all(&zeros).context("writing silent audio")?; - } else if is_float { - let num_bytes = samples * (bits_per_sample as usize / 8); - // SAFETY: data_ptr from GetBuffer is valid for num_bytes. - let slice = unsafe { - std::slice::from_raw_parts(data_ptr as *const u8, num_bytes) - }; - writer.write_all(slice).context("writing audio data")?; - } else { - match bits_per_sample { - 16 => { - // SAFETY: data_ptr from GetBuffer points to valid i16 samples. - let i16_slice = unsafe { - std::slice::from_raw_parts(data_ptr as *const i16, samples) - }; - for &sample in i16_slice { - let f = sample as f32 / 32768.0; - writer - .write_all(&f.to_le_bytes()) - .context("writing f32 sample")?; - } - } - 32 => { - // SAFETY: data_ptr from GetBuffer points to valid i32 samples. - let i32_slice = unsafe { - std::slice::from_raw_parts(data_ptr as *const i32, samples) - }; - for &sample in i32_slice { - let f = sample as f32 / 2147483648.0; - writer - .write_all(&f.to_le_bytes()) - .context("writing f32 sample")?; - } - } - _ => bail!("unsupported bits per sample: {bits_per_sample}"), - } - } - } - - // SAFETY: Releases the buffer obtained from GetBuffer. Standard WASAPI pattern. - unsafe { - capture_client - .ReleaseBuffer(num_frames_available) - .context("ReleaseBuffer")?; - } + write_next_packet(capture_client, channels, bits_per_sample, is_float, writer)?; // SAFETY: Standard WASAPI query for the next available packet size. packet_length = unsafe { @@ -279,3 +223,113 @@ fn capture_loop( } Ok(()) } + +fn write_next_packet( + capture_client: &IAudioCaptureClient, + channels: u16, + bits_per_sample: u16, + is_float: bool, + writer: &mut BufWriter, +) -> Result<()> { + let mut data_ptr = std::ptr::null_mut(); + let mut num_frames_available = 0u32; + let mut flags = 0u32; + // SAFETY: GetBuffer provides valid data_ptr and metadata for the current packet. + unsafe { + capture_client + .GetBuffer( + &mut data_ptr, + &mut num_frames_available, + &mut flags, + None, + None, + ) + .context("GetBuffer")?; + } + + let write_result = (|| -> Result<()> { + if num_frames_available == 0 { + return Ok(()); + } + + let is_silent = (flags & AUDCLNT_BUFFERFLAGS_SILENT) != 0; + let samples = (num_frames_available as usize) * (channels as usize); + + if is_silent { + let zeros = vec![0u8; samples * 4]; + writer.write_all(&zeros).context("writing silent audio")?; + } else if is_float { + let num_bytes = samples * (bits_per_sample as usize / 8); + // SAFETY: data_ptr from GetBuffer is valid for num_bytes. + let slice = unsafe { std::slice::from_raw_parts(data_ptr as *const u8, num_bytes) }; + writer.write_all(slice).context("writing audio data")?; + } else { + match bits_per_sample { + 16 => { + // SAFETY: data_ptr from GetBuffer points to valid i16 samples. + let i16_slice = + unsafe { std::slice::from_raw_parts(data_ptr as *const i16, samples) }; + for &sample in i16_slice { + let f = sample as f32 / 32768.0; + writer + .write_all(&f.to_le_bytes()) + .context("writing f32 sample")?; + } + } + 32 => { + // SAFETY: data_ptr from GetBuffer points to valid i32 samples. + let i32_slice = + unsafe { std::slice::from_raw_parts(data_ptr as *const i32, samples) }; + for &sample in i32_slice { + let f = sample as f32 / 2147483648.0; + writer + .write_all(&f.to_le_bytes()) + .context("writing f32 sample")?; + } + } + _ => bail!("unsupported bits per sample: {bits_per_sample}"), + } + } + + Ok(()) + })(); + + // SAFETY: Releases the buffer obtained from GetBuffer. Standard WASAPI pattern. + let release_result = unsafe { + capture_client + .ReleaseBuffer(num_frames_available) + .context("ReleaseBuffer") + }; + + write_result?; + release_result?; + Ok(()) +} + +fn drain_remaining_packets( + capture_client: &IAudioCaptureClient, + channels: u16, + bits_per_sample: u16, + is_float: bool, + writer: &mut BufWriter, +) -> Result<()> { + // SAFETY: Standard WASAPI query for the next available packet size. + let mut packet_length = unsafe { + capture_client + .GetNextPacketSize() + .context("GetNextPacketSize")? + }; + + while packet_length > 0 { + write_next_packet(capture_client, channels, bits_per_sample, is_float, writer)?; + + // SAFETY: Standard WASAPI query for the next available packet size. + packet_length = unsafe { + capture_client + .GetNextPacketSize() + .context("GetNextPacketSize")? + }; + } + + Ok(()) +} diff --git a/src-tauri/src/bootstrap.rs b/src-tauri/src/bootstrap.rs index 4f00d59..f90b2b7 100644 --- a/src-tauri/src/bootstrap.rs +++ b/src-tauri/src/bootstrap.rs @@ -1,5 +1,5 @@ use std::fs::{self, File}; -use std::io::{self, Cursor}; +use std::io::{self, Write}; use std::path::{Path, PathBuf}; use anyhow::{anyhow, bail, Context, Result}; @@ -118,21 +118,39 @@ where None }; - let archive = if let Some(ref hash) = expected { - download_verified(&client, &asset.browser_download_url, hash, on_progress) - .await - .with_context(|| format!("downloading {}", asset.browser_download_url))? + let app_dir = dest + .parent() + .and_then(|p| p.parent()) + .context("invalid dest path for temp archive")?; + let scratch_dir = app_dir.join("temp"); + fs::create_dir_all(&scratch_dir).context("creating temp dir for archive")?; + let archive_path = scratch_dir.join(format!( + "ffmpeg-archive-{}.tmp", + source.name.to_lowercase() + )); + + if let Some(ref hash) = expected { + download_verified( + &client, + &asset.browser_download_url, + hash, + &archive_path, + on_progress, + ) + .await + .with_context(|| format!("downloading {}", asset.browser_download_url))?; } else { - download_plain(&client, &asset.browser_download_url, on_progress) + download_plain(&client, &asset.browser_download_url, &archive_path, on_progress) .await - .with_context(|| format!("downloading {}", asset.browser_download_url))? + .with_context(|| format!("downloading {}", asset.browser_download_url))?; }; - match source.kind { - ArchiveKind::SevenZ => extract_ffmpeg_from_7z(&archive, dest)?, - ArchiveKind::Zip => extract_ffmpeg_from_zip(&archive, dest)?, - } - Ok(()) + let result = match source.kind { + ArchiveKind::SevenZ => extract_ffmpeg_from_7z(&archive_path, dest), + ArchiveKind::Zip => extract_ffmpeg_from_zip(&archive_path, dest), + }; + let _ = fs::remove_file(&archive_path); + result } /// Fetch and parse a SHA-256 checksums file from GyanD. @@ -174,23 +192,25 @@ async fn fetch_sha256(client: &reqwest::Client, url: &str) -> Result<[u8; 32]> { async fn download_plain( client: &reqwest::Client, url: &str, + dest: &Path, mut on_progress: F, -) -> Result> +) -> Result<()> where F: FnMut(u64, Option), { let resp = client.get(url).send().await?.error_for_status()?; let total = resp.content_length(); - let mut buf: Vec = Vec::with_capacity(total.unwrap_or(0) as usize); + let mut file = std::fs::File::create(dest).context("creating archive temp file")?; let mut downloaded = 0u64; let mut stream = resp.bytes_stream(); while let Some(chunk) = stream.next().await { let chunk = chunk?; - buf.extend_from_slice(&chunk); + file.write_all(&chunk)?; downloaded += chunk.len() as u64; on_progress(downloaded, total); } - Ok(buf) + file.flush()?; + Ok(()) } async fn pick_asset(client: &reqwest::Client, source: &Source) -> Result<(GithubAsset, String)> { @@ -224,33 +244,36 @@ async fn download_verified( client: &reqwest::Client, url: &str, expected: &[u8; 32], + dest: &Path, on_progress: &mut F, -) -> Result> +) -> Result<()> where F: FnMut(u64, Option), { let resp = client.get(url).send().await?.error_for_status()?; let total = resp.content_length(); let mut hasher = Sha256::new(); - let mut buf: Vec = Vec::with_capacity(total.unwrap_or(0) as usize); + let mut file = std::fs::File::create(dest).context("creating archive temp file")?; let mut downloaded = 0u64; let mut stream = resp.bytes_stream(); while let Some(chunk) = stream.next().await { let chunk = chunk?; hasher.update(&chunk); - buf.extend_from_slice(&chunk); + file.write_all(&chunk)?; downloaded += chunk.len() as u64; on_progress(downloaded, total); } + file.flush()?; let got: [u8; 32] = hasher.finalize().into(); if &got != expected { + let _ = std::fs::remove_file(dest); bail!( "sha256 mismatch: expected {} got {}", hex::encode(expected), hex::encode(got) ); } - Ok(buf) + Ok(()) } fn is_ffmpeg_entry(name: &str) -> bool { @@ -265,7 +288,7 @@ fn is_ffmpeg_entry(name: &str) -> bool { .unwrap_or(false) } -fn extract_ffmpeg_from_7z(archive: &[u8], dest: &Path) -> Result<()> { +fn extract_ffmpeg_from_7z(archive_path: &Path, dest: &Path) -> Result<()> { let app_dir = dest .parent() .and_then(|p| p.parent()) @@ -274,9 +297,10 @@ fn extract_ffmpeg_from_7z(archive: &[u8], dest: &Path) -> Result<()> { let _ = fs::remove_dir_all(&scratch); fs::create_dir_all(&scratch).context("create 7z scratch dir")?; - let reader = Cursor::new(archive); - let extract_result = sevenz_rust2::decompress_with_extract_fn(reader, &scratch, |_, _, _| Ok(true)) - .map_err(|e| anyhow!("7z extraction failed: {e}")); + let file = std::fs::File::open(archive_path).context("opening 7z archive")?; + let extract_result = + sevenz_rust2::decompress_with_extract_fn(file, &scratch, |_, _, _| Ok(true)) + .map_err(|e| anyhow!("7z extraction failed: {e}")); let found = find_ffmpeg_in(&scratch); let _ = fs::remove_dir_all(&scratch); @@ -305,9 +329,9 @@ fn find_ffmpeg_in(dir: &Path) -> Option { None } -fn extract_ffmpeg_from_zip(archive: &[u8], dest: &Path) -> Result<()> { - let reader = Cursor::new(archive); - let mut zip = zip::ZipArchive::new(reader).context("open zip archive")?; +fn extract_ffmpeg_from_zip(archive_path: &Path, dest: &Path) -> Result<()> { + let file = std::fs::File::open(archive_path).context("opening zip archive")?; + let mut zip = zip::ZipArchive::new(file).context("open zip archive")?; for i in 0..zip.len() { let mut entry = zip.by_index(i)?; if entry.is_dir() { diff --git a/src-tauri/src/capture.rs b/src-tauri/src/capture.rs index e1ec0d4..9c422c7 100644 --- a/src-tauri/src/capture.rs +++ b/src-tauri/src/capture.rs @@ -329,6 +329,10 @@ 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. +/// +/// Idempotent: if `input` has already been consumed (e.g. a previous +/// pause/resume cycle ran this to completion and removed it), and +/// `output` exists, returns Ok without re-running ffmpeg. pub fn fix_intermediate_fps( ffmpeg: &std::path::Path, input: &std::path::Path, @@ -339,6 +343,11 @@ pub fn fix_intermediate_fps( ) -> Result<()> { use std::process::Command; + if !input.is_file() && output.is_file() { + tracing::debug!("capture fix: input already consumed, output exists, skipping"); + return Ok(()); + } + if frame_count == 0 || elapsed_secs <= 0.0 { tracing::warn!("capture fix: no frames counted, keeping original"); let _ = std::fs::rename(input, output); diff --git a/src-tauri/src/config.rs b/src-tauri/src/config.rs index 972eba0..5c68dc8 100644 --- a/src-tauri/src/config.rs +++ b/src-tauri/src/config.rs @@ -148,8 +148,29 @@ impl Config { match toml::from_str::(&raw) { Ok(cfg) => Ok(cfg), Err(e) => { - let backup = path.with_extension("toml.bak"); - tracing::warn!("config.toml is corrupt ({}), backing up to {:?} and using defaults", e, backup); + // Use a timestamped backup so successive corruptions don't + // clobber each other. Falls back to .toml.bak if the + // timestamped name collides for some reason. + let ts = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_secs()) + .unwrap_or(0); + let stem = path + .file_stem() + .and_then(|s| s.to_str()) + .unwrap_or("config"); + let ext = path.extension().and_then(|s| s.to_str()).unwrap_or("toml"); + let backup = path.with_file_name(format!("{stem}-{ts}.{ext}.bak")); + let backup = if backup.exists() { + path.with_extension("toml.bak") + } else { + backup + }; + tracing::warn!( + "config.toml is corrupt ({}), backing up to {:?} and using defaults", + e, + backup + ); let _ = std::fs::copy(path, &backup); let cfg = Self::default(); cfg.save(path)?; diff --git a/src-tauri/src/encode.rs b/src-tauri/src/encode.rs index 1a53f10..7e9d66c 100644 --- a/src-tauri/src/encode.rs +++ b/src-tauri/src/encode.rs @@ -140,18 +140,14 @@ pub fn transcode(ffmpeg: &Path, req: &TranscodeRequest) -> Result<()> { match req.format { Format::Mp4 => { - let codec = pick_video_codec( - &encoders, - &[mp4_video_codec(req.mp4_codec), "libx264"], - )?; + 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 codec = pick_video_codec( - &encoders, - &[webm_video_codec(req.webm_codec), "libvpx-vp9", "libvpx"], - )?; + 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") } @@ -159,6 +155,18 @@ pub fn transcode(ffmpeg: &Path, req: &TranscodeRequest) -> Result<()> { } } +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}") + } +} + use std::sync::OnceLock; static ENCODER_CACHE: OnceLock> = OnceLock::new(); @@ -191,21 +199,6 @@ fn list_encoders(ffmpeg: &Path) -> Result<&'static HashSet> { Ok(ENCODER_CACHE.get().unwrap()) } -fn pick_video_codec<'a>( - encoders: &HashSet, - candidates: &[&'a str], -) -> Result<&'a str> { - for c in candidates { - if encoders.contains(*c) { - return Ok(c); - } - } - bail!( - "no video encoder available - tried {}", - candidates.join(", ") - ) -} - fn pick_audio_codec<'a>( encoders: &HashSet, candidates: &[&'a str], @@ -298,7 +291,21 @@ fn two_pass_video( let dur = req.duration_secs; let fps = req.fps; let cancel = req.cancel.clone(); - run_with_progress(&mut pass1, "pass 1", 1, 2, dur, fps, tx.as_ref(), cancel.as_ref())?; + let pass_start = std::time::Instant::now(); + run_with_progress( + &mut pass1, + "pass 1", + 1, + 2, + dur, + fps, + tx.as_ref(), + cancel.as_ref(), + )?; + tracing::info!( + elapsed_ms = pass_start.elapsed().as_millis(), + "ffmpeg pass 1 finished" + ); // Send 50% to signal pass 1 done, pass 2 starting. if let Some(ref t) = tx { @@ -328,7 +335,21 @@ fn two_pass_video( pass2.arg("-an"); } pass2.arg(&req.output); - run_with_progress(&mut pass2, "pass 2", 2, 2, dur, fps, tx.as_ref(), cancel.as_ref())?; + let pass_start = std::time::Instant::now(); + run_with_progress( + &mut pass2, + "pass 2", + 2, + 2, + dur, + fps, + tx.as_ref(), + cancel.as_ref(), + )?; + tracing::info!( + elapsed_ms = pass_start.elapsed().as_millis(), + "ffmpeg pass 2 finished" + ); cleanup_pass_logs(&log_stem); Ok(()) @@ -365,18 +386,29 @@ fn encode_gif(ffmpeg: &Path, req: &TranscodeRequest) -> Result<()> { }; let (mut scale_width, mut effective_fps) = gif_params(&budget_input, req.clip_width, req.clip_height); let target = req.target_bytes; - let max_retries = 6; + // 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. + let max_retries = ((req.duration_secs / 5.0).ceil() as u32 + 4).clamp(5, 12); + + let mut prev_actual: Option = None; for attempt in 0..max_retries { if req.cancel.as_ref().map_or(false, |c| c.load(Ordering::Relaxed)) { bail!("export cancelled"); } // Last resort: use minimal settings to hit the target - if attempt == 5 { + if attempt == max_retries - 1 { scale_width = (scale_width / 2).max(60); effective_fps = 1; } + let pass_start = std::time::Instant::now(); encode_gif_pass(ffmpeg, req, scale_width, effective_fps)?; + tracing::info!( + attempt = attempt + 1, + elapsed_ms = pass_start.elapsed().as_millis(), + "gif pass finished" + ); let actual = std::fs::metadata(&req.output) .map(|m| m.len()) @@ -397,29 +429,69 @@ fn encode_gif(ffmpeg: &Path, req: &TranscodeRequest) -> Result<()> { return Ok(()); } - // Only adjust DOWN when file is too big - never exceed target - // File is too big - scale down based on budget priority + // 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. + let raw_factor = match req.gif_budget_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 (which the old `factor = ratio.sqrt()` + // would do after a large overshoot). + let half = 0.5_f64; + (ratio * (1.0 - half) + ratio.sqrt() * half).clamp(0.1, 1.0) + } + }; + 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 = (target as f64 - prev as f64).abs(); + let cur_dist = (target as f64 - actual as f64).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; + } + } + match req.gif_budget_mode { GifBudgetMode::Resolution => { - // Reduce fps (resolution is priority, keep it) - effective_fps = ((effective_fps as f64 * ratio).round() as u32).max(1); + effective_fps = ((effective_fps as f64 * factor).round() as u32).max(1); } GifBudgetMode::Framerate => { - // Reduce resolution (fps is priority, keep it) - scale_width = ((scale_width as f64 * ratio.sqrt()).round() as u32 / 2).max(60).min(1280) * 2; + scale_width = ((scale_width as f64 * factor).round() as u32 / 2) + .max(60) + .min(1280) + * 2; } GifBudgetMode::Balanced => { - // Reduce both - let factor = ratio.sqrt(); - scale_width = ((scale_width as f64 * factor).round() as u32 / 2).max(60).min(1280) * 2; + scale_width = ((scale_width as f64 * factor).round() as u32 / 2) + .max(60) + .min(1280) + * 2; effective_fps = ((effective_fps as f64 * factor).round() as u32).max(1); } } tracing::info!( - "gif retry {}: was {} bytes (target {}), adjusting to {}x @ {}fps", - attempt + 1, actual, target, scale_width, effective_fps + "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 @@ -505,7 +577,7 @@ pub struct GifBudgetInput { } pub fn gif_params(input: &GifBudgetInput, clip_width: u32, clip_height: u32) -> (u32, u32) { - let aspect = if clip_height > 0 { clip_width as f64 / clip_height as f64 } else { 16.0 / 9.0 }; + 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. @@ -555,6 +627,23 @@ pub fn gif_params(input: &GifBudgetInput, clip_width: u32, clip_height: u32) -> } } +pub fn aspect_ratio(width: u32, height: u32) -> f64 { + if height > 0 { + width as f64 / height as f64 + } else { + 16.0 / 9.0 + } +} + +pub 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 { + ((width as f64 / aspect).round() as u32 / 2) * 2 + } +} + pub fn render_preview( ffmpeg: &Path, input: &Path, @@ -709,7 +798,7 @@ pub fn mux_with_audio( } pub fn concat_pcm(segments: &[PathBuf], output: &Path) -> Result<()> { - use std::io::{Read, Write}; + use std::io::Write; if segments.is_empty() { bail!("no audio segments to concatenate"); } @@ -719,15 +808,9 @@ pub fn concat_pcm(segments: &[PathBuf], output: &Path) -> Result<()> { let mut out = std::fs::File::create(output).context("creating audio concat file")?; for seg in segments { let mut f = std::fs::File::open(seg).with_context(|| format!("opening {seg:?}"))?; - let mut buf = vec![0u8; 64 * 1024]; - loop { - let n = f.read(&mut buf)?; - if n == 0 { - break; - } - out.write_all(&buf[..n])?; - } + std::io::copy(&mut f, &mut out).context("copying audio segment")?; } + out.flush()?; Ok(()) } @@ -777,9 +860,7 @@ 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)?; if !output.status.success() { - let stderr = String::from_utf8_lossy(&output.stderr); - let head: String = stderr.lines().take(12).collect::>().join("\n"); - bail!("ffmpeg {label} exited with {}: {}", output.status, head); + bail!(ffmpeg_failure_message(label, output.status, &output.stderr)); } Ok(()) } @@ -798,13 +879,36 @@ fn run_with_progress( ) -> Result<()> { let output = run_impl(cmd, label, pass, total_passes, duration_secs, fps, progress_tx.cloned(), cancel.cloned())?; if !output.status.success() { - let stderr = String::from_utf8_lossy(&output.stderr); - let head: String = stderr.lines().take(12).collect::>().join("\n"); - bail!("ffmpeg {label} exited with {}: {}", output.status, head); + 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}"), + } +} + fn run_impl( cmd: &mut Command, label: &str, @@ -914,11 +1018,11 @@ fn parse_frame_from_stderr(line: &str) -> Option { mod tests { use super::*; - // Paths are empty - these tests only exercise bitrate math, not ffmpeg. fn dummy_request() -> TranscodeRequest { + let dir = std::env::temp_dir().join(format!("bytesize-encode-test-{}", std::process::id())); TranscodeRequest { - input: PathBuf::new(), - output: PathBuf::new(), + input: dir.join("input.mp4"), + output: dir.join("output.mp4"), format: Format::Mp4, target_bytes: 0, duration_secs: 10.0, @@ -927,7 +1031,7 @@ mod tests { gif_dither: GifDither::FloydSteinberg, webm_codec: WebmCodec::Vp9, mp4_codec: Mp4Codec::H264, - scratch_dir: PathBuf::new(), + scratch_dir: dir.join("scratch"), crop: None, gif_budget_mode: GifBudgetMode::Balanced, gif_colors: 256, diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index d98da70..e0f8dcd 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -182,12 +182,49 @@ struct SaveConfigResult { hotkey_result: HotkeyRegistrationResult, } +fn validate_config(config: &Config) -> Result<(), String> { + let mut keys = Vec::new(); + if let Some(k) = config + .hotkeys + .start + .as_deref() + .filter(|s| !s.trim().is_empty()) + { + keys.push(("start", k)); + } + if let Some(k) = config + .hotkeys + .stop + .as_deref() + .filter(|s| !s.trim().is_empty()) + { + keys.push(("stop", k)); + } + if let Some(k) = config + .hotkeys + .pause + .as_deref() + .filter(|s| !s.trim().is_empty()) + { + keys.push(("pause", k)); + } + for (i, (a, ka)) in keys.iter().enumerate() { + for (b, kb) in keys.iter().skip(i + 1) { + if ka.eq_ignore_ascii_case(kb) { + return Err(format!("duplicate hotkey: {a} and {b} both use {ka}")); + } + } + } + Ok(()) +} + #[tauri::command] fn save_config( app: AppHandle, state: State<'_, AppState>, config: Config, ) -> Result { + validate_config(&config)?; let path = config::config_path(&state.app_dir); config.save(&path).map_err(|e| format!("{e:#}"))?; *lock(&state.config) = config.clone(); @@ -794,16 +831,7 @@ fn estimate_gif_params(request: PreviewRequest) -> GifEstimate { gif_budget_mode: request.gif_budget_mode, }; let (w, fps) = encode::gif_params(&budget, request.clip_width, request.clip_height); - let aspect = if request.clip_height > 0 { - request.clip_width as f64 / request.clip_height as f64 - } else { - 16.0 / 9.0 - }; - let height = if w == 0 { - 0 - } else { - ((w as f64 / aspect).round() as u32 / 2) * 2 - }; + 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 } } @@ -845,7 +873,7 @@ mod tests { assert_eq!(est.fps, encode_fps); // height should be a multiple of 2 and within aspect assert_eq!(est.height % 2, 0); - let expected_height = ((encode_w as f64 / (1920.0 / 1080.0)).round() as u32 / 2) * 2; + let expected_height = encode::gif_height_for_width(encode_w, 1920, 1080); assert_eq!(est.height, expected_height); // dims_label should be "{w}x{h} @ {fps}fps" assert_eq!(est.dims_label, format!("{}x{} @ {}fps", encode_w, est.height, encode_fps)); @@ -1571,7 +1599,10 @@ pub fn run() { let registry = tracing_subscriber::registry().with(env_filter).with(file_layer); #[cfg(debug_assertions)] let registry = registry.with(tracing_subscriber::fmt::layer().with_writer(std::io::stdout)); + #[cfg(test)] let _ = registry.try_init(); + #[cfg(not(test))] + registry.init(); let webview_dir = app_dir.join("temp").join("webview"); match std::fs::create_dir_all(&webview_dir) { diff --git a/src-tauri/src/updates.rs b/src-tauri/src/updates.rs index f44d1e7..319580d 100644 --- a/src-tauri/src/updates.rs +++ b/src-tauri/src/updates.rs @@ -155,15 +155,40 @@ pub fn write_apply_script(app_dir: &Path) -> Result { Ok(bat_path) } +#[derive(Debug, PartialEq, Eq)] +struct VersionParts { + nums: Vec, + pre: Option, +} + +fn parse_version(v: &str) -> VersionParts { + let trimmed = v.trim().trim_start_matches('v'); + let (core, pre) = trimmed + .split_once('-') + .map(|(core, pre)| (core, Some(pre.to_ascii_lowercase()))) + .unwrap_or((trimmed, None)); + let nums = core + .split('.') + .map(|s| s.parse::().unwrap_or(0)) + .collect(); + VersionParts { nums, pre } +} + fn is_newer(latest: &str, current: &str) -> bool { - // Note: pre-release suffixes (e.g., "-beta") are filtered out by parse().ok(), - // so "1.0.0-beta" compares equal to "1.0.0". Acceptable for v1. - let mut l: Vec = latest.split('.').filter_map(|s| s.parse().ok()).collect(); - let mut c: Vec = current.split('.').filter_map(|s| s.parse().ok()).collect(); - let max = l.len().max(c.len()); - l.resize(max, 0); - c.resize(max, 0); - l > c + let mut l = parse_version(latest); + let mut c = parse_version(current); + let max = l.nums.len().max(c.nums.len()); + l.nums.resize(max, 0); + c.nums.resize(max, 0); + if l.nums != c.nums { + return l.nums > c.nums; + } + match (&l.pre, &c.pre) { + (None, Some(_)) => true, + (Some(_), None) => false, + (Some(a), Some(b)) => a > b, + (None, None) => false, + } } #[cfg(test)] @@ -203,7 +228,17 @@ mod tests { #[test] fn version_ignores_extra_text() { assert!(is_newer("1.0.0-beta", "0.9.0")); - // "beta" doesn't parse as u32, so it's filtered out. - // 1.0.0 vs 0.9.0 -> newer + } + + #[test] + fn stable_is_newer_than_matching_prerelease() { + assert!(is_newer("1.0.0", "1.0.0-beta")); + assert!(!is_newer("1.0.0-beta", "1.0.0")); + } + + #[test] + fn prerelease_compares_when_core_matches() { + assert!(is_newer("1.0.0-rc", "1.0.0-beta")); + assert!(!is_newer("1.0.0-beta", "1.0.0-rc")); } } diff --git a/src/lib/ExportSidebar.svelte b/src/lib/ExportSidebar.svelte new file mode 100644 index 0000000..b993561 --- /dev/null +++ b/src/lib/ExportSidebar.svelte @@ -0,0 +1,200 @@ + + +
+
+
+ Target size + {targetMB.toFixed(1)} MB +
+ +

{previewDims} · {fps}fps · {trimmedDuration.toFixed(1)}s

+
+ + {#if format === "gif"} + + {/if} + +
+ + {#if format !== "gif"} + + {/if} +
+ +
+
+ Crop + +
+ {#if cropEnabled} +
+ + + + +
+ {/if} +
+ +
+ Output +
+ + +
+
+ +
+ + +
+
+ + diff --git a/src/lib/GifControls.svelte b/src/lib/GifControls.svelte index 7e586e9..acd2c86 100644 --- a/src/lib/GifControls.svelte +++ b/src/lib/GifControls.svelte @@ -107,6 +107,7 @@ .styled-range { -webkit-appearance: none; + appearance: none; width: 100%; height: 3px; background: var(--bg-3); @@ -116,6 +117,7 @@ } .styled-range::-webkit-slider-thumb { -webkit-appearance: none; + appearance: none; width: 14px; height: 14px; border-radius: 50%; background: var(--accent); diff --git a/src/lib/Main.svelte b/src/lib/Main.svelte index c1413ed..d190010 100644 --- a/src/lib/Main.svelte +++ b/src/lib/Main.svelte @@ -4,9 +4,11 @@ import { save } from "@tauri-apps/plugin-dialog" import { emit, listen } from "@tauri-apps/api/event" import TrimPanel from "./TrimPanel.svelte" - import GifControls from "./GifControls.svelte" import Preview from "./Preview.svelte" import FramesStrip from "./FramesStrip.svelte" + import ExportSidebar from "./ExportSidebar.svelte" + import { resetTrimPreview } from "./trimPreviewState.svelte" + import { minTargetMB } from "./exportSizing" type Phase = "idle" | "recording" | "paused" | "editing" | "exporting" | "done" @@ -209,7 +211,7 @@ cropH = c.height pathOverridden = false outputPath = await api.defaultOutputPath(format) - const sensible = Math.min(50, Math.max(minMB(c.duration_secs), Math.round(c.duration_secs * 0.5))) + const sensible = Math.min(50, Math.max(minTargetMB(c.duration_secs), Math.round(c.duration_secs * 0.5))) targetMB = sensible } catch (e) { errMsg = String(e); phase = "idle"; clearTick() } } @@ -314,7 +316,7 @@ clip = null; exportResult = null; errMsg = null; encodeProgress = null thumbnails = []; deletedFrames = new Set() thumbCache = new Map() - previewPath = null; trimPreviewPath = null + previewPath = null; resetTrimPreview() if (previewTimer !== null) { clearTimeout(previewTimer); previewTimer = null } elapsed = 0; phase = "idle" if (config) { @@ -347,25 +349,6 @@ function tick() { elapsedTimer = window.setInterval(() => { elapsed += 0.1 }, 100) } function clearTick() { if (elapsedTimer !== null) { clearInterval(elapsedTimer); elapsedTimer = null } } - // Minimum target file size (MB) for a clip of `s` seconds. - // Hard floor of 0.1 MB; otherwise scale ~50 KB/sec with a 50 KB absolute floor. - function minMB(s: number): number { - const perSecBytes = s * 50_000 - const floorBytes = 50_000 - return Math.max(0.1, Math.max(floorBytes, perSecBytes) / 1_048_576) - } - // Maximum target file size (MB) for a clip of `s` seconds. - // Capped at 200 MB; floor of 10 MB; otherwise scale 5 MB/sec. - function maxMB(s: number): number { - return Math.min(200, Math.max(10, s * 5)) - } - - // Trim state is lifted here so the Preview component can read it - // (to swap to the raw frame during drag) and the parent can debounce - // exports that depend on the values. - let dragging: 'start' | 'end' | null = $state(null) - let trimPreviewPath: string | null = $state(null) - let trimPreviewBust: number = $state(0) // Reactivity $effect(() => { @@ -563,9 +546,6 @@ {previewPath} {previewLoading} {previewCacheBust} - {trimPreviewPath} - {trimPreviewBust} - {dragging} /> @@ -573,9 +553,6 @@ {clip} bind:trimStart bind:trimEnd - bind:dragging - bind:trimPreviewPath - bind:trimPreviewBust onAfterChange={refreshPreview} /> @@ -592,96 +569,29 @@ -
- -
-
- Target size - {targetMB.toFixed(1)} MB -
- -

{previewDims} · {fps}fps · {trimmedDuration.toFixed(1)}s

-
- - {#if format === "gif"} - - {/if} - - -
- - {#if format !== "gif"} - - {/if} -
- - -
-
- Crop - -
- {#if cropEnabled} -
- - - - -
- {/if} -
- - -
- Output -
- pathOverridden = true} aria-label="output file path" /> - -
-
- - -
- - -
-
+ pathOverridden = true} + onBrowse={browseOutput} + onExport={doExport} + onDiscard={confirmDiscard} + /> @@ -693,11 +603,18 @@ {encodeProgress.pct.toFixed(0)}%
-
+ {#each Array(encodeProgress.total) as _, i} +
+
+
+ {/each}
{:else}
Preparing
-
+
{/if}

ffmpeg is encoding your clip

@@ -1066,7 +983,7 @@ background: var(--border); min-height: 0; } - .edit-left, .edit-right { + .edit-left { background: var(--bg); display: flex; flex-direction: column; @@ -1075,11 +992,9 @@ min-height: 0; } .edit-left { padding: 20px; gap: 20px; } - .edit-right { padding: 20px; gap: 20px; border-left: 1px solid var(--border); } @media (max-width: 720px) { .edit { grid-template-columns: 1fr; } - .edit-right { border-left: none; border-top: 1px solid var(--border); } } /* Format bar */ @@ -1108,135 +1023,6 @@ .fmt-chip:hover { color: var(--text-2); } .fmt-chip.active { background: var(--accent); border-color: var(--accent); color: var(--accent-text); } - /* Preview (Trim, Frames, GifControls own their styles in their components) */ - .control-group { display: flex; flex-direction: column; gap: 8px; } - .control-head { - display: flex; - justify-content: space-between; - align-items: center; - } - .section-title { - font-size: 10px; - font-weight: 600; - text-transform: uppercase; - letter-spacing: 0.1em; - color: var(--text-3); - } - .size-readout { font-size: 14px; color: var(--text); } - - .styled-range { - -webkit-appearance: none; - width: 100%; - height: 3px; - background: var(--bg-3); - border-radius: 2px; - outline: none; - cursor: pointer; - } - .styled-range::-webkit-slider-thumb { - -webkit-appearance: none; - width: 14px; height: 14px; - border-radius: 50%; - background: var(--accent); - border: 2px solid var(--bg); - cursor: pointer; - transition: transform 80ms; - } - .styled-range::-webkit-slider-thumb:hover { transform: scale(1.2); } - - .estimate { - margin: 0; - font-size: 11px; - color: var(--text-3); - font-family: var(--mono); - } - - .control-row { - display: flex; - gap: 16px; - align-items: flex-end; - } - .control { display: flex; flex-direction: column; gap: 6px; } - .control-label { - font-size: 10px; - text-transform: uppercase; - letter-spacing: 0.08em; - color: var(--text-3); - } - - select { - padding: 7px 10px; - background: var(--bg-2); - border: 1px solid var(--border); - color: var(--text); - border-radius: var(--r-sm); - font-family: var(--mono); - font-size: 12px; - cursor: pointer; - outline: none; - } - select:focus { border-color: var(--accent); } - - .check-control { - display: flex; - align-items: center; - gap: 8px; - font-size: 12px; - color: var(--text-2); - cursor: pointer; - } - .check-control.compact { font-size: 11px; } - .check-control input[type="checkbox"] { - width: 14px; height: 14px; - accent-color: var(--accent); - cursor: pointer; - } - - /* Crop */ - .crop-grid { - display: grid; - grid-template-columns: repeat(4, 1fr); - gap: 8px; - } - .crop-field { - display: flex; - flex-direction: column; - gap: 4px; - } - .crop-field span { - font-size: 10px; - text-transform: uppercase; - letter-spacing: 0.06em; - color: var(--text-3); - } - .crop-field input { - padding: 6px 8px; - background: var(--bg-2); - border: 1px solid var(--border); - color: var(--text); - border-radius: var(--r-sm); - font-family: var(--mono); - font-size: 12px; - outline: none; - width: 100%; - } - .crop-field input:focus { border-color: var(--accent); } - - /* Path */ - .path-row { display: flex; gap: 6px; } - .path-input { - flex: 1; - padding: 7px 10px; - background: var(--bg-2); - border: 1px solid var(--border); - color: var(--text); - border-radius: var(--r-sm); - font-family: var(--mono); - font-size: 11px; - outline: none; - } - .path-input:focus { border-color: var(--accent); } - .btn-primary { padding: 10px 24px; background: var(--accent); @@ -1266,13 +1052,6 @@ } .btn-ghost:hover { border-color: var(--border-3); color: var(--text); } - .edit-actions { - display: flex; - gap: 10px; - margin-top: auto; - padding-top: 8px; - } - /* ---- Exporting ---- */ .exporting { flex: 1; @@ -1299,7 +1078,10 @@ background: var(--bg-3); border-radius: 2px; overflow: hidden; + display: flex; + gap: 2px; } + .enc-segment { flex: 1; background: var(--bg-3); overflow: hidden; } .enc-fill { height: 100%; background: var(--accent); @@ -1398,6 +1180,7 @@ background: rgba(0,0,0,0.5); display: grid; place-items: center; z-index: 50; + animation: fadein 120ms ease-out; } .confirm-card { background: var(--bg-2); @@ -1406,7 +1189,10 @@ padding: 24px; min-width: 280px; text-align: center; + animation: cardin 140ms ease-out; } + @keyframes fadein { from { opacity: 0; } to { opacity: 1; } } + @keyframes cardin { from { opacity: 0; transform: translateY(6px) scale(0.98); } to { opacity: 1; transform: translateY(0) scale(1); } } .confirm-card p { margin: 0 0 16px; font-size: 14px; color: var(--text); } .confirm-actions { display: flex; gap: 10px; justify-content: center; } diff --git a/src/lib/Preview.svelte b/src/lib/Preview.svelte index 117fc80..0da762d 100644 --- a/src/lib/Preview.svelte +++ b/src/lib/Preview.svelte @@ -1,26 +1,21 @@ -{#if dragging && trimPreviewPath} +{#if trimPreviewState.dragging && trimPreviewState.path}
- +
original
{:else if previewPath} diff --git a/src/lib/TrimPanel.svelte b/src/lib/TrimPanel.svelte index 028ab57..be0817d 100644 --- a/src/lib/TrimPanel.svelte +++ b/src/lib/TrimPanel.svelte @@ -1,21 +1,16 @@