diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index 5c63f46..34af4ce 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -1643,6 +1643,12 @@ dependencies = [ "pin-project-lite", ] +[[package]] +name = "http-range" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "21dec9db110f5f872ed9699c3ecf50cf16f423502706ba5c72462e28d3157573" + [[package]] name = "httparse" version = "1.10.1" @@ -3988,6 +3994,7 @@ dependencies = [ "gtk", "heck 0.5.0", "http", + "http-range", "jni", "libc", "log", diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 65b7202..b232dfd 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -14,7 +14,7 @@ crate-type = ["staticlib", "cdylib", "rlib"] tauri-build = { version = "2", features = [] } [dependencies] -tauri = { version = "2.11", features = [] } +tauri = { version = "2.11", features = ["protocol-asset"] } tauri-plugin-dialog = "2" windows-capture = "2.0" tokio = { version = "1.47", features = ["full"] } diff --git a/src-tauri/src/encode.rs b/src-tauri/src/encode.rs index 9176754..e08cda6 100644 --- a/src-tauri/src/encode.rs +++ b/src-tauri/src/encode.rs @@ -23,6 +23,16 @@ pub struct TranscodeRequest { pub mp4_codec: Mp4Codec, pub scratch_dir: PathBuf, pub crop: Option, + pub deleted_frame_indices: Vec, +} + +fn select_filter_for_deleted(deleted: &[u32]) -> Option { + if deleted.is_empty() { + return None; + } + let parts: Vec = deleted.iter().map(|n| format!("eq(n\\,{n})")).collect(); + let expr = parts.join("+"); + Some(format!("select='not({expr})',setpts=N/FRAME_RATE/TB")) } fn crop_filter(crop: Option) -> Option { @@ -180,9 +190,13 @@ fn encode_gif(ffmpeg: &Path, req: &TranscodeRequest) -> Result<()> { let crop_prefix = crop_filter(req.crop) .map(|c| format!("{c},")) .unwrap_or_default(); + let select_prefix = select_filter_for_deleted(&req.deleted_frame_indices) + .map(|s| format!("{s},")) + .unwrap_or_default(); let palettegen_filter = format!( - "{prefix}fps={fps},scale={w}:-1:flags=lanczos,palettegen=stats_mode=diff", - prefix = crop_prefix, + "{cprefix}fps={fps},{sprefix}scale={w}:-1:flags=lanczos,palettegen=stats_mode=diff", + cprefix = crop_prefix, + sprefix = select_prefix, fps = req.fps, w = scale_width, ); @@ -202,8 +216,9 @@ fn encode_gif(ffmpeg: &Path, req: &TranscodeRequest) -> Result<()> { GifDither::None => "none", }; let use_filter = format!( - "{prefix}fps={fps},scale={w}:-1:flags=lanczos[x];[x][1:v]paletteuse=dither={d}", - prefix = crop_prefix, + "{cprefix}fps={fps},{sprefix}scale={w}:-1:flags=lanczos[x];[x][1:v]paletteuse=dither={d}", + cprefix = crop_prefix, + sprefix = select_prefix, fps = req.fps, w = scale_width, d = dither, @@ -236,6 +251,52 @@ fn estimate_gif_scale_width(req: &TranscodeRequest) -> u32 { (w / 2) * 2 } +pub fn extract_thumbnails( + ffmpeg: &Path, + input: &Path, + out_dir: &Path, + fps: u32, + crop: Option, +) -> Result> { + std::fs::create_dir_all(out_dir).context("creating thumbnails dir")?; + for entry in std::fs::read_dir(out_dir).into_iter().flatten().flatten() { + let _ = std::fs::remove_file(entry.path()); + } + + let crop_prefix = crop_filter(crop) + .map(|c| format!("{c},")) + .unwrap_or_default(); + let filter = format!( + "{prefix}fps={fps},scale=120:-1:flags=lanczos", + prefix = crop_prefix, + fps = fps + ); + let pattern = out_dir.join("thumb-%05d.png"); + + let mut cmd = Command::new(ffmpeg); + cmd.arg("-y") + .arg("-hide_banner") + .arg("-i") + .arg(input) + .args(["-vf", &filter]) + .arg(&pattern); + run(&mut cmd, "thumbnail extraction")?; + + let mut paths: Vec = std::fs::read_dir(out_dir)? + .flatten() + .map(|e| e.path()) + .filter(|p| { + p.extension().and_then(|s| s.to_str()) == Some("png") + && p.file_name() + .and_then(|s| s.to_str()) + .map(|s| s.starts_with("thumb-")) + .unwrap_or(false) + }) + .collect(); + paths.sort(); + Ok(paths) +} + pub fn concat_segments(ffmpeg: &Path, segments: &[PathBuf], output: &Path) -> Result<()> { if segments.is_empty() { bail!("no segments to concatenate"); diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index a49ee8b..8587603 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -366,6 +366,28 @@ pub struct ExportRequest { pub target_bytes: u64, pub fps: u32, pub keep_audio: bool, + #[serde(default)] + pub deleted_frame_indices: Vec, +} + +#[tauri::command] +fn extract_thumbnails( + state: State<'_, AppState>, + fps: u32, +) -> Result, String> { + let clip = state + .last_clip + .lock() + .expect("clip mutex") + .clone() + .ok_or_else(|| "no recorded clip available".to_string())?; + let ffmpeg = bootstrap::ffmpeg_path(&state.app_dir); + if !ffmpeg.is_file() { + return Err("ffmpeg.exe not found".to_string()); + } + let thumbs_dir = temp_dir(&state.app_dir).join("thumbs"); + encode::extract_thumbnails(&ffmpeg, &clip.temp_path, &thumbs_dir, fps, clip.crop) + .map_err(|e| format!("{e:#}")) } #[derive(Debug, Serialize)] @@ -469,6 +491,7 @@ fn export(state: State<'_, AppState>, request: ExportRequest) -> Result = $state(new Set()) + let loadingThumbs: boolean = $state(false) onMount(async () => { config = await api.getConfig() @@ -127,6 +131,34 @@ return Math.min(200, Math.max(10, durationSecs * 5)) } + async function loadThumbnails() { + if (format !== "gif") { + thumbnails = [] + return + } + loadingThumbs = true + try { + const paths = await api.extractThumbnails(fps) + thumbnails = paths + deletedFrames = new Set() + } catch (e) { + errMsg = String(e) + } finally { + loadingThumbs = false + } + } + + function toggleThumb(idx: number) { + const next = new Set(deletedFrames) + if (next.has(idx)) next.delete(idx) + else next.add(idx) + deletedFrames = next + } + + function clearDeleted() { + deletedFrames = new Set() + } + async function doExport() { if (!clip) return errMsg = null @@ -137,6 +169,7 @@ target_bytes: Math.round(targetMB * 1_048_576), fps, keep_audio: keepAudio && format !== "gif", + deleted_frame_indices: format === "gif" ? Array.from(deletedFrames) : [], }) exportResult = result phase = "done" @@ -146,11 +179,21 @@ } } + $effect(() => { + if (phase === "editing" && format === "gif") { + void loadThumbnails() + } else if (format !== "gif") { + thumbnails = [] + } + }) + function startOver() { clip = null exportResult = null errMsg = null elapsed = 0 + thumbnails = [] + deletedFrames = new Set() phase = "idle" } @@ -261,6 +304,34 @@ {/if} + {#if format === "gif"} +
+
+ frames {thumbnails.length > 0 ? `(${thumbnails.length - deletedFrames.size} kept / ${thumbnails.length})` : ""} + {#if deletedFrames.size > 0} + + {/if} +
+ {#if loadingThumbs} +

extracting frames...

+ {:else if thumbnails.length > 0} +
+ {#each thumbnails as path, idx} + + {/each} +
+ {/if} +
+ {/if} +
@@ -506,4 +577,83 @@ color: #888; font-size: 0.85rem; } + .frames { + margin: 1rem 0; + padding: 0.75rem; + background: #1e1e1e; + border: 1px solid #2a2a2a; + border-radius: 6px; + } + .frames-head { + display: flex; + justify-content: space-between; + align-items: center; + margin-bottom: 0.6rem; + font-size: 0.85rem; + color: #aaa; + } + .small { + padding: 0.25rem 0.5rem; + font-size: 0.8rem; + } + .strip { + display: flex; + gap: 4px; + overflow-x: auto; + padding-bottom: 4px; + } + .strip::-webkit-scrollbar { + height: 8px; + } + .strip::-webkit-scrollbar-thumb { + background: #3a3a3a; + border-radius: 4px; + } + .thumb { + position: relative; + flex: 0 0 auto; + padding: 0; + border: 2px solid transparent; + border-radius: 3px; + background: transparent; + cursor: pointer; + } + .thumb img { + display: block; + width: 80px; + height: auto; + border-radius: 2px; + } + .thumb:hover { + border-color: #4a8; + } + .thumb.deleted img { + opacity: 0.25; + filter: grayscale(1); + } + .thumb.deleted { + border-color: #c33; + } + .thumb.deleted::after { + content: "×"; + position: absolute; + inset: 0; + display: grid; + place-items: center; + color: #c33; + font-size: 1.6rem; + font-weight: bold; + pointer-events: none; + } + .thumb .idx { + position: absolute; + bottom: 2px; + right: 2px; + background: rgba(0, 0, 0, 0.7); + color: #ccc; + padding: 0 4px; + border-radius: 2px; + font-size: 0.7rem; + font-variant-numeric: tabular-nums; + } diff --git a/src/lib/api.ts b/src/lib/api.ts index 23a4fd2..6ac230b 100644 --- a/src/lib/api.ts +++ b/src/lib/api.ts @@ -1,6 +1,8 @@ -import { invoke } from "@tauri-apps/api/core" +import { invoke, convertFileSrc } from "@tauri-apps/api/core" import { listen, type UnlistenFn } from "@tauri-apps/api/event" +export { convertFileSrc } + export type FfmpegStatus = "ready" | "missing" export type AppStatus = { @@ -73,6 +75,7 @@ export type ExportRequest = { target_bytes: number fps: number keep_audio: boolean + deleted_frame_indices: number[] } export type ExportResult = { @@ -97,6 +100,8 @@ export const api = { showOverlay: () => invoke("show_overlay"), hideOverlay: () => invoke("hide_overlay"), getOverlayRect: () => invoke("get_overlay_rect"), + extractThumbnails: (fps: number) => + invoke("extract_thumbnails", { fps }), } export function formatBytes(n: number): string {