From a48d82ddc95fd472601912004c87af57bd116894 Mon Sep 17 00:00:00 2001 From: lashman Date: Thu, 4 Jun 2026 22:03:20 +0300 Subject: [PATCH] split Main into components, move gif math to backend --- src-tauri/src/lib.rs | 157 ++++++++++++ src-tauri/src/updates.rs | 28 +++ src/lib/FramesStrip.svelte | 102 ++++++++ src/lib/GifControls.svelte | 128 ++++++++++ src/lib/Main.svelte | 498 ++++++++++--------------------------- src/lib/Preview.svelte | 70 ++++++ src/lib/TrimPanel.svelte | 179 +++++++++++++ src/lib/api.ts | 20 ++ 8 files changed, 811 insertions(+), 371 deletions(-) create mode 100644 src/lib/FramesStrip.svelte create mode 100644 src/lib/GifControls.svelte create mode 100644 src/lib/Preview.svelte create mode 100644 src/lib/TrimPanel.svelte diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 122f29d..d98da70 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -511,6 +511,48 @@ fn resume_capture(app: AppHandle, state: State<'_, AppState>) -> Result<(), Stri Ok(()) } +/// Restart the audio capture mid-recording. Used when the initial WASAPI +/// session failed (e.g. endpoint was busy) and the user wants to retry +/// without ending the recording. Stops the current session, appends its +/// pcm segment to the session, and starts a new one with a fresh file. +#[tauri::command] +fn restart_audio_capture( + app: AppHandle, + state: State<'_, AppState>, +) -> Result<(), String> { + let audio_enabled = { + let ss = lock(&state.session); + let ss = ss.as_ref().ok_or_else(|| "no session in progress".to_string())?; + if !ss.audio { + return Err("audio is not enabled for this recording".to_string()); + } + ss.audio + }; + + // Stop the existing session and stash its file. Don't touch capture + // or click recording - they keep running. + let next_idx = { + let mut ss = lock(&state.session); + let ss = ss.as_mut().ok_or_else(|| "no session in progress".to_string())?; + if let Some(a) = lock(&state.audio).take() { + if let Ok(p) = a.stop() { + ss.audio_segments.push(p); + } + } + ss.audio_segments.len() + 1 + }; + + let audio_path = audio_segment_path(&state.app_dir, next_idx); + let audio_recovered = try_start_audio(&app, audio_enabled, audio_path); + let recovered = audio_recovered.is_some(); + *lock(&state.audio) = audio_recovered; + + if recovered { + let _ = app.emit("audio-recovered", ()); + } + Ok(()) +} + #[tauri::command] fn stop_capture(app: AppHandle, state: State<'_, AppState>) -> Result { set_overlay_clickthrough(&app, false); @@ -678,6 +720,14 @@ pub struct PreviewRequest { pub gif_dither: Option, #[serde(default)] pub gif_colors: Option, + /// Optional clip dimensions/duration. Required by `estimate_gif_params`, + /// unused by `render_preview` (which uses the current `last_clip`). + #[serde(default)] + pub clip_width: u32, + #[serde(default)] + pub clip_height: u32, + #[serde(default)] + pub duration_secs: Option, } #[tauri::command] @@ -726,6 +776,91 @@ fn render_preview( Ok(preview_path) } +#[derive(Debug, Serialize)] +pub struct GifEstimate { + pub width: u32, + pub fps: u32, + pub height: u32, + pub dims_label: String, +} + +#[tauri::command] +fn estimate_gif_params(request: PreviewRequest) -> GifEstimate { + let budget = encode::GifBudgetInput { + gif_colors: request.gif_colors.unwrap_or(256), + target_bytes: request.target_bytes, + fps: request.fps, + duration_secs: request.duration_secs.unwrap_or(0.0), + 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 dims_label = format!("{w}x{height} @ {fps}fps"); + GifEstimate { width: w, fps, height, dims_label } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn make_request(target_bytes: u64, fps: u32, mode: GifBudgetMode) -> PreviewRequest { + PreviewRequest { + format: Format::Gif, + fps, + target_bytes, + gif_budget_mode: mode, + gif_dither: Some(GifDither::FloydSteinberg), + gif_colors: Some(256), + clip_width: 1920, + clip_height: 1080, + duration_secs: Some(5.0), + } + } + + #[test] + fn estimate_balanced_matches_gif_params() { + // The frontend uses estimate_gif_params for the on-screen dims label. + // The backend uses gif_params for the actual encode. The two must agree. + let req = make_request(8 * 1024 * 1024, 30, GifBudgetMode::Balanced); + let est = estimate_gif_params(req); + + let budget = encode::GifBudgetInput { + gif_colors: 256, + target_bytes: 8 * 1024 * 1024, + fps: 30, + duration_secs: 5.0, + gif_budget_mode: GifBudgetMode::Balanced, + }; + let (encode_w, encode_fps) = encode::gif_params(&budget, 1920, 1080); + assert_eq!(est.width, encode_w); + 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; + 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)); + } + + #[test] + fn estimate_zero_height_falls_back_aspect() { + let mut req = make_request(1024, 30, GifBudgetMode::Balanced); + req.clip_height = 0; + let est = estimate_gif_params(req); + // Should not panic and should produce some height + assert!(est.height > 0 || est.width == 0); + } +} + #[tauri::command] fn extract_thumbnails( state: State<'_, AppState>, @@ -771,6 +906,16 @@ const OVERLAY_BORDER_LOGICAL_PX: f64 = 4.0; const OVERLAY_TITLEBAR_LOGICAL_PX: f64 = 24.0; +/// Remove temporary recording artifacts (segments, previews, thumbs). +/// Called on app exit so a discarded clip doesn't linger in `temp/`. +fn cleanup_temp_on_exit(app: &AppHandle) { + let st = match app.try_state::() { + Some(s) => s, + None => return, + }; + clear_temp_segments(&st.app_dir); +} + fn start_overlay_clickthrough_poll(app: AppHandle, shutdown: Arc) { use std::time::Duration; use windows::Win32::Foundation::{HWND, POINT}; @@ -1525,7 +1670,13 @@ pub fn run() { } if check_on_launch { let handle = app.handle().clone(); + let app_dir = app.state::().app_dir.clone(); tauri::async_runtime::spawn(async move { + // Skip the network call if we checked within the last 6 hours. + if !updates::should_check(&app_dir, std::time::Duration::from_secs(6 * 3600)) { + tracing::debug!("update check skipped (TTL not elapsed)"); + return; + } match updates::check_for_update().await { Ok(Some(info)) => { tracing::info!(version = info.version, "update available"); @@ -1534,6 +1685,9 @@ pub fn run() { Ok(None) => tracing::debug!("no update available"), Err(e) => tracing::warn!("update check failed: {e:#}"), } + // Stamp success on Ok results so a future launch won't + // re-check until the TTL elapses. Errors don't stamp. + updates::stamp_check(&app_dir); }); } Ok(()) @@ -1549,12 +1703,14 @@ pub fn run() { start_capture, pause_capture, resume_capture, + restart_audio_capture, stop_capture, export, default_output_path, extract_thumbnails, render_preview, render_raw_preview, + estimate_gif_params, reveal_in_explorer, open_url, show_overlay, @@ -1577,6 +1733,7 @@ pub fn run() { if let Some(st) = _app.try_state::() { st.overlay_poll_shutdown.store(true, Ordering::SeqCst); } + cleanup_temp_on_exit(_app); } }); } diff --git a/src-tauri/src/updates.rs b/src-tauri/src/updates.rs index 553b801..f44d1e7 100644 --- a/src-tauri/src/updates.rs +++ b/src-tauri/src/updates.rs @@ -93,6 +93,34 @@ pub fn pending_update_path(app_dir: &Path) -> PathBuf { app_dir.join("ByteSize.new.exe") } +fn last_check_path(app_dir: &Path) -> PathBuf { + app_dir.join("temp").join("last-update-check") +} + +/// Returns true if the last successful update check happened more than `ttl` +/// ago, or never. The stamp file's mtime is the source of truth. +pub fn should_check(app_dir: &Path, ttl: std::time::Duration) -> bool { + let path = last_check_path(app_dir); + let Ok(meta) = std::fs::metadata(&path) else { + return true; + }; + let Ok(modified) = meta.modified() else { + return true; + }; + let Ok(elapsed) = modified.elapsed() else { + return true; + }; + elapsed > ttl +} + +pub fn stamp_check(app_dir: &Path) { + let path = last_check_path(app_dir); + if let Some(parent) = path.parent() { + let _ = std::fs::create_dir_all(parent); + } + let _ = std::fs::write(&path, b""); +} + pub fn has_pending_update(app_dir: &Path) -> bool { pending_update_path(app_dir).is_file() } diff --git a/src/lib/FramesStrip.svelte b/src/lib/FramesStrip.svelte new file mode 100644 index 0000000..7633185 --- /dev/null +++ b/src/lib/FramesStrip.svelte @@ -0,0 +1,102 @@ + + +
+
+ Frames + {#if deletedFrames.size > 0} + + {/if} +
+ {#if loading} +

extracting...

+ {:else} +
+ {#each thumbnails as path, idx} + + {/each} +
+ {/if} +
+ + diff --git a/src/lib/GifControls.svelte b/src/lib/GifControls.svelte new file mode 100644 index 0000000..7e586e9 --- /dev/null +++ b/src/lib/GifControls.svelte @@ -0,0 +1,128 @@ + + +
+ Budget priority +
+ {#each (["resolution", "framerate", "balanced"] as const) as m} + + {/each} +
+

+ {budgetMode === "resolution" ? "Keeps resolution high, may reduce FPS" : + budgetMode === "framerate" ? "Keeps FPS high, may reduce resolution" : + "Balances resolution and FPS"} +

+
+ +
+ Colors +
+ + {colors} +
+

{colors <= 32 ? "Low - small file, posterized" : colors <= 128 ? "Medium - balanced" : "High - full color"}

+
+ +
+ Dithering +
+ {#each (["floyd_steinberg", "bayer", "none"] as const) as d} + + {/each} +
+

{dither === "floyd_steinberg" ? "Smooth gradients, slightly larger" : dither === "bayer" ? "Patterned, smaller file" : "No dithering, smallest file"}

+
+ + diff --git a/src/lib/Main.svelte b/src/lib/Main.svelte index 305e675..c1413ed 100644 --- a/src/lib/Main.svelte +++ b/src/lib/Main.svelte @@ -1,8 +1,12 @@ + +{#if dragging && trimPreviewPath} +
+ +
original
+
+{:else if previewPath} +
+ + {#if previewLoading}
rendering
{/if} +
+{:else} +
+ preview +
+{/if} + + diff --git a/src/lib/TrimPanel.svelte b/src/lib/TrimPanel.svelte new file mode 100644 index 0000000..028ab57 --- /dev/null +++ b/src/lib/TrimPanel.svelte @@ -0,0 +1,179 @@ + + +
+
+ {trimStart.toFixed(2)}s + {trimmedDuration.toFixed(2)}s kept + {trimEnd.toFixed(2)}s +
+
+
+
startDrag("start", e)} + onpointermove={onDrag} + onpointerup={endDrag} + onkeydown={(e) => { + const step = e.shiftKey ? 0.5 : 0.05 + if (e.key === "ArrowLeft") { trimStart = Math.max(0, trimStart - step); e.preventDefault() } + else if (e.key === "ArrowRight") { trimStart = Math.min(trimEnd - 0.1, trimStart + step); e.preventDefault() } + }} + >
+
startDrag("end", e)} + onpointermove={onDrag} + onpointerup={endDrag} + onkeydown={(e) => { + const step = e.shiftKey ? 0.5 : 0.05 + if (e.key === "ArrowLeft") { trimEnd = Math.max(trimStart + 0.1, trimEnd - step); e.preventDefault() } + else if (e.key === "ArrowRight") { trimEnd = Math.min(clip.duration_secs, trimEnd + step); e.preventDefault() } + }} + >
+
+ { const v = parseFloat((e.currentTarget as HTMLInputElement).value); trimStart = Math.min(v, trimEnd - 0.1) }} + class="sr-only" aria-label="trim start seconds" /> + { const v = parseFloat((e.currentTarget as HTMLInputElement).value); trimEnd = Math.max(v, trimStart + 0.1) }} + class="sr-only" aria-label="trim end seconds" /> +
+ + diff --git a/src/lib/api.ts b/src/lib/api.ts index 81437a3..085736c 100644 --- a/src/lib/api.ts +++ b/src/lib/api.ts @@ -141,6 +141,13 @@ export type EncodeProgress = { percent: number } +export type GifEstimate = { + width: number + fps: number + height: number + dims_label: string +} + export type AudioFailed = string export const api = { @@ -154,6 +161,7 @@ export const api = { invoke("start_capture", { request }), pauseCapture: () => invoke("pause_capture"), resumeCapture: () => invoke("resume_capture"), + restartAudioCapture: () => invoke("restart_audio_capture"), stopCapture: () => invoke("stop_capture"), export: (request: ExportRequest) => invoke("export", { request }), revealInExplorer: (path: string) => invoke("reveal_in_explorer", { path }), @@ -171,6 +179,18 @@ export const api = { invoke("extract_thumbnails", { fps }), renderPreview: (format: Format, fps: number, target_bytes: number, gif_budget_mode?: GifBudgetMode, gif_dither?: GifDither, gif_colors?: number) => invoke("render_preview", { request: { format, fps, target_bytes, gif_budget_mode, gif_dither, gif_colors } }), + estimateGifParams: (input: { + format: Format + fps: number + target_bytes: number + gif_budget_mode?: GifBudgetMode + gif_dither?: GifDither + gif_colors?: number + clip_width: number + clip_height: number + duration_secs: number + }) => + invoke("estimate_gif_params", { request: input }), renderRawPreview: (timestamp: number) => invoke("render_raw_preview", { timestamp }), defaultOutputPath: (format: Format) =>