diff --git a/src-tauri/src/encode.rs b/src-tauri/src/encode.rs index 11f9673..9437ed0 100644 --- a/src-tauri/src/encode.rs +++ b/src-tauri/src/encode.rs @@ -102,7 +102,6 @@ pub(crate) struct TranscodeRequest { pub crop: Option, pub gif_budget_mode: GifBudgetMode, pub gif_colors: u16, - pub deleted_frame_indices: Vec, pub trim_start_secs: Option, pub trim_end_secs: Option, pub clicks: Vec, @@ -139,15 +138,11 @@ fn click_box(clip_x: i32, clip_y: i32, clip_w: u32, clip_h: u32) -> Option<(i32, Some((x, y)) } -/// The time `apply_trim` cuts off the head of the clip. A seek rebases the -/// filter graph's timestamps to zero, so anything recorded against clip time - -/// the click highlights - has to be shifted by the same amount or it lands late -/// by the length of the trim. fn trim_offset(req: &TranscodeRequest) -> f64 { req.trim_start_secs.filter(|s| *s > 0.001).unwrap_or(0.0) } -fn click_filters(clicks: &[Click], clip_w: u32, clip_h: u32, time_offset: f64) -> Option { +fn click_filters(clicks: &[Click], clip_w: u32, clip_h: u32) -> Option { if clicks.is_empty() { return None; } @@ -169,10 +164,7 @@ fn click_filters(clicks: &[Click], clip_w: u32, clip_h: u32, time_offset: f64) - let Some((x, y)) = click_box(click.x, click.y, clip_w, clip_h) else { continue; }; - let t = click.time_secs - time_offset; - if t + 0.25 < 0.0 { - continue; - } + let t = click.time_secs; let t1 = (t - 0.05).max(0.0); let t2 = t + 0.25; let color = match click.button { @@ -202,19 +194,26 @@ fn apply_trim(cmd: &mut Command, req: &TranscodeRequest) { } } -fn select_filter_for_deleted(deleted: &[u32]) -> Option { - if deleted.is_empty() { - return None; +fn gif_timeline_filter(req: &TranscodeRequest, effective_fps: u32) -> String { + let mut trim = Vec::new(); + if let Some(start) = req.trim_start_secs { + trim.push(format!("start={start}")); + } + if let Some(end) = req.trim_end_secs { + trim.push(format!("end={end}")); + } + let fps = format!("fps={effective_fps}"); + if trim.is_empty() { + fps + } else { + format!("trim={},setpts=PTS-STARTPTS,{fps}", trim.join(":")) } - 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 { crop.map(|c| { format!( - "crop={w}:{h}:{x}:{y}", + "crop={w}:{h}:{x}:{y}:exact=1", w = c.width, h = c.height, x = c.x.max(0), @@ -227,6 +226,9 @@ pub(crate) fn transcode(ffmpeg: &Path, req: &TranscodeRequest) -> Result<()> { if req.duration_secs <= 0.01 { bail!("clip duration is essentially zero - nothing to encode"); } + if req.fps == 0 { + bail!("export frame rate must be greater than zero"); + } std::fs::create_dir_all(&req.scratch_dir).context("creating scratch dir")?; if let Some(parent) = req.output.parent() { std::fs::create_dir_all(parent).context("creating output dir")?; @@ -407,15 +409,14 @@ fn video_bitrate_kbps(req: &TranscodeRequest) -> Result { Ok(kbps.max(16)) } -/// Chain the crop and the click highlights into the single `-vf` argument the -/// two video passes share. -fn combined_video_filter(crop: Option<&String>, clicks: Option<&String>) -> Option { - match (crop, clicks) { - (Some(c), Some(k)) => Some(format!("{c},{k}")), - (Some(c), None) => Some(c.clone()), - (None, Some(k)) => Some(k.clone()), - (None, None) => None, - } +fn video_filters(req: &TranscodeRequest) -> String { + let crop = crop_filter(req.crop); + let clicks = click_filters(&req.clicks, req.clip_width, req.clip_height); + [clicks, crop, Some(format!("fps={}", req.fps))] + .into_iter() + .flatten() + .collect::>() + .join(",") } fn two_pass_video( @@ -423,7 +424,7 @@ fn two_pass_video( req: &TranscodeRequest, video_codec: &str, audio_codec: &str, - _container: &str, + container: &str, ) -> Result<()> { let bitrate_kbps = video_bitrate_kbps(req)?; let bitrate = format!("{bitrate_kbps}k"); @@ -434,14 +435,7 @@ fn two_pass_video( .ok_or_else(|| anyhow!("scratch dir contains non-UTF8"))?; let null_target = if cfg!(windows) { "NUL" } else { "/dev/null" }; - let crop = crop_filter(req.crop); - let clicks = click_filters( - &req.clicks, - req.clip_width, - req.clip_height, - trim_offset(req), - ); - let combined_vf = combined_video_filter(crop.as_ref(), clicks.as_ref()); + let combined_vf = video_filters(req); let mut pass1 = Command::new(ffmpeg); pass1 @@ -450,10 +444,8 @@ fn two_pass_video( .arg("-i") .arg(&req.input); apply_trim(&mut pass1, req); - if let Some(c) = &combined_vf { - pass1.args(["-vf", c]); - } pass1 + .args(["-vf", &combined_vf]) .args(["-c:v", video_codec]) .args(["-b:v", &bitrate]) .args(["-pass", "1"]) @@ -464,7 +456,6 @@ fn two_pass_video( let tx = req.progress_tx.clone(); let dur = req.duration_secs; - let fps = req.fps; let cancel = req.cancel.clone(); let pass_start = std::time::Instant::now(); run_with_progress( @@ -473,7 +464,6 @@ fn two_pass_video( 1, 2, dur, - fps, tx.as_ref(), cancel.as_ref(), )?; @@ -501,10 +491,8 @@ fn two_pass_video( .arg("-i") .arg(&req.input); apply_trim(&mut pass2, req); - if let Some(c) = &combined_vf { - pass2.args(["-vf", c]); - } pass2 + .args(["-vf", &combined_vf]) .args(["-c:v", video_codec]) .args(["-b:v", &bitrate]) .args(["-pass", "2"]) @@ -516,7 +504,7 @@ fn two_pass_video( } else { pass2.arg("-an"); } - pass2.arg(&req.output); + pass2.args(["-abort_on", "empty_output_stream", "-f", container]).arg(&req.output); let pass_start = std::time::Instant::now(); run_with_progress( &mut pass2, @@ -524,7 +512,6 @@ fn two_pass_video( 2, 2, dur, - fps, tx.as_ref(), cancel.as_ref(), )?; @@ -567,7 +554,7 @@ fn calibrate_via_sample( ) -> 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); + let sample_start = trim_offset(req) + ((req.duration_secs - sample_dur) / 2.0).max(0.0); // Defer cleanup until we've measured the sample: the guard owns a copy of // the path, which lets the original move into the request below. Earlier @@ -582,7 +569,6 @@ fn calibrate_via_sample( sample_req.output = sample_path; sample_req.trim_start_secs = Some(sample_start); sample_req.trim_end_secs = Some(sample_start + sample_dur); - sample_req.deleted_frame_indices.clear(); sample_req.clicks.clear(); sample_req.progress_tx = None; @@ -598,7 +584,8 @@ fn calibrate_via_sample( // 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 (clip_width, clip_height) = req.crop.map_or((req.clip_width, req.clip_height), |r| (r.width, r.height)); + let aspect = aspect_ratio(clip_width, clip_height); let sample_h = round_u32(f64::from(est_width) / aspect); let frames = (f64::from(est_fps) * sample_dur).max(1.0); let measured_bpp = @@ -611,17 +598,20 @@ fn calibrate_via_sample( 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 { + if ratio >= 0.85 { return None; } // Recompute target params with the corrected constant. Scale resolution // by the sqrt of the ratio so file size scales roughly linearly. - let new_width = (round_u32(f64::from(est_width) * ratio.sqrt()) / 2).max(60) * 2; - let new_fps = round_u32(f64::from(est_fps) * ratio.sqrt()) - .max(1) - .min(est_fps); - Some((new_width.min(1280), new_fps)) + let (mut width, mut fps) = (est_width, est_fps); + shrink_gif_params( + req.gif_budget_mode, + gif_shrink_factor(req.gif_budget_mode, ratio.min(1.0)), + &mut width, + &mut fps, + ); + Some((width, fps)) } /// Per-mode raw shrink factor (before clamping to 0.6..0.9) given the @@ -630,8 +620,8 @@ fn calibrate_via_sample( /// match the dimension it is applied to. fn gif_shrink_factor(mode: GifBudgetMode, ratio: f64) -> f64 { match mode { - GifBudgetMode::Resolution => ratio.sqrt(), - GifBudgetMode::Framerate => ratio, + 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. @@ -644,15 +634,17 @@ fn gif_shrink_factor(mode: GifBudgetMode, ratio: f64) -> f64 { /// keeping the width even (the `*2` after the halving clamp). fn shrink_gif_params(mode: GifBudgetMode, factor: f64, width: &mut u32, fps: &mut u32) { match mode { - GifBudgetMode::Resolution => { + GifBudgetMode::Framerate => { *width = (round_u32(f64::from(*width) * factor) / 2).clamp(60, 640) * 2; } - GifBudgetMode::Framerate => { - *fps = round_u32(f64::from(*fps) * factor).max(1); + GifBudgetMode::Resolution => { + *fps = round_u32(f64::from(*fps) * factor) + .clamp(1, fps.saturating_sub(1).max(1)); } GifBudgetMode::Balanced => { *width = (round_u32(f64::from(*width) * factor) / 2).clamp(60, 640) * 2; - *fps = round_u32(f64::from(*fps) * factor).max(1); + *fps = round_u32(f64::from(*fps) * factor) + .clamp(1, fps.saturating_sub(1).max(1)); } } } @@ -676,7 +668,7 @@ fn gif_calibration( Some((w, f)) } -fn encode_gif(ffmpeg: &Path, req: &TranscodeRequest) -> Result<()> { +fn gif_starting_params(req: &TranscodeRequest) -> (u32, u32) { let budget_input = GifBudgetInput { gif_colors: req.gif_colors, target_bytes: req.target_bytes, @@ -684,8 +676,12 @@ fn encode_gif(ffmpeg: &Path, req: &TranscodeRequest) -> Result<()> { duration_secs: req.duration_secs, gif_budget_mode: req.gif_budget_mode, }; - let (mut scale_width, mut effective_fps) = - gif_params(&budget_input, req.clip_width, req.clip_height); + let (width, height) = req.crop.map_or((req.clip_width, req.clip_height), |r| (r.width, r.height)); + gif_params(&budget_input, width, height) +} + +fn encode_gif(ffmpeg: &Path, req: &TranscodeRequest) -> Result<()> { + let (mut scale_width, mut effective_fps) = gif_starting_params(req); // Calibrate the bytes/pixel constant by encoding a short sample first. // The default 0.2 bytes/pixel assumption varies 3-5x by content; measuring @@ -715,11 +711,6 @@ fn encode_gif(ffmpeg: &Path, req: &TranscodeRequest) -> Result<()> { { bail!("export cancelled"); } - // Last resort: use minimal settings to hit the target - 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, @@ -781,12 +772,25 @@ fn encode_gif(ffmpeg: &Path, req: &TranscodeRequest) -> Result<()> { } } + let previous = (scale_width, effective_fps); shrink_gif_params( req.gif_budget_mode, factor, &mut scale_width, &mut effective_fps, ); + if (scale_width, effective_fps) == previous { + // Try the other setting when the preferred one hits its floor. + let fallback = match req.gif_budget_mode { + GifBudgetMode::Resolution => GifBudgetMode::Framerate, + GifBudgetMode::Framerate | GifBudgetMode::Balanced => GifBudgetMode::Resolution, + }; + shrink_gif_params(fallback, gif_shrink_factor(fallback, ratio).clamp(0.6, 0.9), + &mut scale_width, &mut effective_fps); + if (scale_width, effective_fps) == previous { + break; + } + } tracing::info!( "gif retry {}: was {} bytes (target {}), adjusting to {}x @ {}fps (factor={:.2})", @@ -811,28 +815,15 @@ fn encode_gif(ffmpeg: &Path, req: &TranscodeRequest) -> Result<()> { Ok(()) } -fn encode_gif_pass( - ffmpeg: &Path, - req: &TranscodeRequest, - scale_width: u32, - effective_fps: u32, - attempt: u8, - max_attempts: u8, -) -> Result<()> { +fn gif_filters(req: &TranscodeRequest, scale_width: u32, effective_fps: u32) -> String { let crop_prefix = crop_filter(req.crop) .map(|c| format!("{c},")) .unwrap_or_default(); - let click_prefix = click_filters( - &req.clicks, - req.clip_width, - req.clip_height, - trim_offset(req), - ) - .map(|c| format!("{c},")) - .unwrap_or_default(); - let select_prefix = select_filter_for_deleted(&req.deleted_frame_indices) - .map(|s| format!("{s},")) + let click_prefix = click_filters(&req.clicks, req.clip_width, req.clip_height) + .map(|c| format!("{c},")) .unwrap_or_default(); + let timeline = gif_timeline_filter(req, effective_fps); + let stats = "diff"; let dither = match req.gif_dither { GifDither::FloydSteinberg => "floyd_steinberg", @@ -843,16 +834,26 @@ 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},split[s0][s1];[s0]palettegen=stats_mode=diff:max_colors={colors}[p];[s1][p]paletteuse=dither={d}", + let colors = req.gif_colors; + let reserve = u8::from(colors > 2); + format!( + "{kprefix}{cprefix}{timeline},{scale},split[s0][s1];[s0]palettegen=stats_mode={stats}:max_colors={colors}:reserve_transparent={reserve}[p];[s1][p]paletteuse=dither={d}", cprefix = crop_prefix, kprefix = click_prefix, - sprefix = select_prefix, - fps = effective_fps, scale = scale, - colors = req.gif_colors, d = dither, - ); + ) +} + +fn encode_gif_pass( + ffmpeg: &Path, + req: &TranscodeRequest, + scale_width: u32, + effective_fps: u32, + attempt: u8, + max_attempts: u8, +) -> Result<()> { + let filter_complex = gif_filters(req, scale_width, effective_fps); tracing::info!( "gif encode: fps={effective_fps} scale={scale_width} colors={} filter={filter_complex}", @@ -865,10 +866,10 @@ fn encode_gif_pass( .arg("-hide_banner") .arg("-i") .arg(&req.input); - apply_trim(&mut encode, req); encode .args(["-filter_complex", &filter_complex]) .args(["-loop", "0"]) + .args(["-abort_on", "empty_output", "-f", "gif"]) .arg(&req.output); run_with_progress( &mut encode, @@ -876,7 +877,6 @@ fn encode_gif_pass( attempt, max_attempts, req.duration_secs, - effective_fps, req.progress_tx.as_ref(), req.cancel.as_ref(), )?; @@ -886,7 +886,7 @@ fn encode_gif_pass( 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" + "scale={width}:-1:flags=lanczos:in_color_matrix=bt709:in_range=tv:out_range=pc:in_primaries=bt709:in_transfer=bt709:out_primaries=bt709:out_transfer=srgb,format=rgb24" ) } @@ -970,181 +970,69 @@ pub(crate) fn gif_height_for_width(width: u32, clip_width: u32, clip_height: u32 } } -pub(crate) fn render_preview( - ffmpeg: &Path, - input: &Path, - out_path: &Path, - midpoint_secs: f64, - target_width: u32, -) -> Result<()> { - if let Some(parent) = out_path.parent() { - std::fs::create_dir_all(parent).context("creating preview parent")?; - } - let scale_filter = format!("scale={target_width}:-2"); - let mut cmd = Command::new(ffmpeg); - cmd.arg("-y") - .arg("-hide_banner") - .args(["-ss", &format!("{midpoint_secs}")]) - .arg("-i") - .arg(input) - .args(["-vf", &scale_filter]) - .args(["-frames:v", "1"]) - .arg(out_path); - run(&mut cmd, "preview render") +#[derive(Clone, Copy, Debug, serde::Serialize)] +pub(crate) struct OutputProperties { + pub width: u32, + pub height: u32, + pub fps: f64, + pub duration_secs: f64, } -/// Render a GIF preview with actual palette and dithering applied. -/// Generates a palette from the full clip, then applies it to a single frame. -// Every argument is a distinct knob the caller already has in hand; bundling -// them into a struct would only move the same list one level up. -#[allow( - clippy::too_many_arguments, - reason = "flat parameter list mirrors the preview request fields the caller owns" -)] -pub(crate) fn render_gif_preview( - ffmpeg: &Path, - input: &Path, - out_path: &Path, - midpoint_secs: f64, - target_width: u32, - gif_colors: u16, - gif_dither: &str, - duration_secs: f64, -) -> Result<()> { - if let Some(parent) = out_path.parent() { - std::fs::create_dir_all(parent).context("creating preview parent")?; - } - // 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_key = palette_cache_key(gif_colors, target_width, sample_start, sample_dur); - // The preview and its input both live in the scratch dir, so the preview's - // parent is the normal case. Fall back to the input's parent rather than - // panicking on a bare filename. - let palette_dir = out_path - .parent() - .filter(|p| !p.as_os_str().is_empty()) - .or_else(|| input.parent().filter(|p| !p.as_os_str().is_empty())) - .context("preview palette has no parent directory")?; - let palette_path = palette_dir.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!( - "{}[x];[x][1:v]paletteuse=dither={}", - gif_rgb_scale_filter(target_width), - gif_dither - ); - let mut encode = Command::new(ffmpeg); - encode - .arg("-y") - .arg("-hide_banner") - .args(["-ss", &format!("{midpoint_secs}")]) - .arg("-i") - .arg(input) - .arg("-i") - .arg(&palette_path) - .args(["-lavfi", &use_filter]) - .args(["-frames:v", "1"]) - .arg(out_path); - // The palette is deliberately left in place: the cache key above exists so a - // render with the same inputs can skip palettegen entirely, and deleting it - // here meant every render regenerated it. clear_temp_segments sweeps - // preview-palette-*.png between recordings, and clean_stale_palettes drops - // the keys that no longer apply. - run(&mut encode, "gif preview encode") -} - -/// 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{sample_start:.3}-d{sample_dur:.3}") -} - -/// 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() { - // Case-insensitive for the same reason as the temp sweep: these - // are the app's own files, but Windows keeps the case it was given. - let is_png = Path::new(name) - .extension() - .is_some_and(|e| e.eq_ignore_ascii_case("png")); - if name.starts_with("preview-palette-") && is_png { - drop(std::fs::remove_file(entry.path())); - } - } - } - } -} - -pub(crate) 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() { - drop(std::fs::remove_file(entry.path())); - } - - let crop_prefix = crop_filter(crop) - .map(|c| format!("{c},")) - .unwrap_or_default(); - let filter = format!("{crop_prefix}fps={fps},scale=120:-1:flags=lanczos"); - let pattern = out_dir.join("thumb-%05d.png"); +/// Inspect packet timing without decoding the video. +pub(crate) fn inspect_output(ffmpeg: &Path, path: &Path) -> Result { + use std::os::windows::process::CommandExt; + use windows::Win32::System::Threading::CREATE_NO_WINDOW; let mut cmd = Command::new(ffmpeg); - cmd.arg("-y") - .arg("-hide_banner") - .arg("-i") - .arg(input) - .args(["-vf", &filter]) - .arg(&pattern); - run(&mut cmd, "thumbnail extraction")?; + let output = cmd + .creation_flags(CREATE_NO_WINDOW.0) + .args(["-v", "error", "-nostdin", "-i"]) + .arg(path) + .args(["-map", "0:v:0", "-c:v", "copy", "-f", "framecrc", "pipe:1"]) + .output() + .context("reading rendered output details")?; + if !output.status.success() { + bail!(ffmpeg_failure_message("reading output details", output.status, &output.stderr)); + } + parse_output_properties(&String::from_utf8_lossy(&output.stdout)) + .ok_or_else(|| anyhow!("could not read the output dimensions or frame timing")) +} - 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()) - .is_some_and(|s| s.starts_with("thumb-")) - }) - .collect(); - paths.sort(); - Ok(paths) +fn parse_output_properties(report: &str) -> Option { + let (width, height) = report.lines() + .find_map(|line| line.strip_prefix("#dimensions 0: "))?.trim().split_once('x')?; + let (tick, timescale) = report.lines() + .find_map(|line| line.strip_prefix("#tb 0: "))?.trim().split_once('/')?; + let mut first = f64::INFINITY; + let mut end = f64::NEG_INFINITY; + let mut frames = 0u32; + for line in report.lines().filter(|line| line.starts_with('0')) { + let mut columns = line.split(',').skip(2); + let pts = columns.next()?.trim().parse::().ok()?; + let duration = columns.next()?.trim().parse::().ok()?; + first = first.min(pts); + end = end.max(pts + duration); + frames += 1; + } + let duration_secs = (end - first) * tick.parse::().ok()? / timescale.parse::().ok()?; + if !duration_secs.is_finite() || duration_secs <= 0.0 { return None; } + Some(OutputProperties { + width: width.parse().ok()?, height: height.parse().ok()?, + fps: f64::from(frames) / duration_secs, duration_secs, + }) +} + +pub(crate) fn timeline_thumbnails(ffmpeg: &Path, input: &Path, out_dir: &Path, seconds: f64) -> Result> { + if !seconds.is_finite() || seconds <= 0.0 { + bail!("invalid clip duration for the timeline"); + } + std::fs::create_dir_all(out_dir).context("creating timeline thumbnail folder")?; + let filter = format!("fps={:.6},scale=160:-2", (8.0 / seconds).min(120.0)); + let mut cmd = Command::new(ffmpeg); + cmd.args(["-y", "-hide_banner", "-i"]).arg(input) + .args(["-vf", &filter, "-frames:v", "8"]).arg(out_dir.join("frame-%02d.jpg")); + run(&mut cmd, "timeline thumbnails")?; + Ok((1..=8).map(|i| out_dir.join(format!("frame-{i:02}.jpg"))).filter(|path| path.is_file()).collect()) } pub(crate) fn display_preview(ffmpeg: &Path, x: i32, y: i32, width: u32, height: u32) -> Result> { @@ -1351,7 +1239,7 @@ pub(crate) fn concat_segments(ffmpeg: &Path, segments: &[PathBuf], output: &Path } fn run(cmd: &mut Command, label: &str) -> Result<()> { - let output = run_impl(cmd, label, 0, 0, 0.0, 0, None, None, false)?; + let output = run_impl(cmd, label, 0, 0, 0.0, None, None, false)?; if !output.status.success() { bail!(ffmpeg_failure_message(label, output.status, &output.stderr)); } @@ -1362,19 +1250,12 @@ fn run(cmd: &mut Command, label: &str) -> Result<()> { /// `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. -// Thin forwarder to run_impl, which needs the same list; a params struct here -// would just be reconstructed at each of the four call sites. -#[allow( - clippy::too_many_arguments, - reason = "thin forwarder for the ffmpeg invocation; callers already hold these as locals" -)] fn run_with_progress( cmd: &mut Command, label: &str, pass: u8, total_passes: u8, duration_secs: f64, - fps: u32, progress_tx: Option<&Sender>, cancel: Option<&Arc>, ) -> Result<()> { @@ -1387,7 +1268,6 @@ fn run_with_progress( pass, total_passes, duration_secs, - fps, progress_tx.cloned(), cancel.cloned(), true, @@ -1452,7 +1332,6 @@ fn run_impl( progress_pass: u8, progress_total_passes: u8, progress_duration_secs: f64, - _progress_fps: u32, progress_tx: Option>, cancel: Option>, read_stdout: bool, @@ -1588,6 +1467,17 @@ mod tests { use super::*; + #[test] + fn review_properties_use_muxed_frame_timing() { + let properties = parse_output_properties(concat!( + "#tb 0: 1/100\n#dimensions 0: 128x96\n", + "0, 0, 4, 3, 42, 0x00\n0, 3, 0, 4, 42, 0x00\n0, 6, 7, 3, 42, 0x00\n", + )).unwrap(); + assert_eq!((properties.width, properties.height), (128, 96)); + assert!((properties.duration_secs - 0.1).abs() < 0.000_001); + assert!((properties.fps - 30.0).abs() < 0.000_001); + } + fn dummy_request() -> TranscodeRequest { let dir = std::env::temp_dir().join(format!("bytesize-encode-test-{}", std::process::id())); TranscodeRequest { @@ -1605,7 +1495,6 @@ mod tests { crop: None, gif_budget_mode: GifBudgetMode::Balanced, gif_colors: 256, - deleted_frame_indices: vec![], trim_start_secs: None, trim_end_secs: None, clicks: vec![], @@ -1701,6 +1590,36 @@ mod tests { assert!(filter.contains("format=rgb24")); } + #[test] + fn audio_alignment_pads_whole_sample_frames_and_preserves_retry_gaps() { + let dir = std::env::temp_dir(); + let id = std::process::id(); + let first = TempFileGuard(dir.join(format!("bytesize-align-{id}-first.pcm"))); + let retry = TempFileGuard(dir.join(format!("bytesize-align-{id}-retry.pcm"))); + let out = TempFileGuard(dir.join(format!("bytesize-align-{id}-output.pcm"))); + let pcm = |samples: &[f32]| { + samples.iter().copied().flat_map(f32::to_le_bytes).collect::>() + }; + std::fs::write(&first.0, pcm(&[0.1, 0.2, 0.3, 0.4])).unwrap(); + std::fs::write(&retry.0, pcm(&[0.5, 0.6, 0.7, 0.8])).unwrap(); + let segments = [ + AudioSegment { + path: first.0.clone(), sample_rate: 10, channels: 2, start_secs: 0.12, end_secs: 0.3, + }, + AudioSegment { + path: retry.0.clone(), sample_rate: 10, channels: 2, start_secs: 0.48, end_secs: 0.6, + }, + ]; + assert_eq!( + assemble_pcm(Path::new("ffmpeg"), &segments, &out.0, 0.7).unwrap(), + Some((10, 2)), + ); + assert_eq!( + std::fs::read(&out.0).unwrap(), + pcm(&[0., 0., 0.1, 0.2, 0.3, 0.4, 0., 0., 0., 0., 0.5, 0.6, 0., 0.]), + ); + } + #[test] fn crop_filter_output() { let rect = CaptureRect { @@ -1711,7 +1630,7 @@ mod tests { }; assert_eq!( crop_filter(Some(rect)), - Some("crop=100:200:10:20".to_string()) + Some("crop=100:200:10:20:exact=1".to_string()) ); assert_eq!(crop_filter(None), None); } @@ -1726,7 +1645,7 @@ mod tests { button: crate::clicks::MouseButton::Left, }) .collect(); - let filter = click_filters(&clicks, 1920, 1080, 0.0).unwrap(); + let filter = click_filters(&clicks, 1920, 1080).unwrap(); let count = filter.matches("drawbox").count(); assert_eq!(count, MAX_CLICK_HIGHLIGHTS); } @@ -1771,7 +1690,7 @@ mod tests { button: crate::clicks::MouseButton::Left, }, ]; - let filter = click_filters(&clicks, 1920, 1080, 0.0).unwrap(); + let filter = click_filters(&clicks, 1920, 1080).unwrap(); assert_eq!(filter.matches("drawbox").count(), 1); assert!(filter.contains("x=488:y=388")); // Every emitted box must be non-negative, or drawbox throws it away. @@ -1779,48 +1698,33 @@ mod tests { assert!(!filter.contains("y=-")); } - /// A trim seeks past the head of the clip, which rebases the filter timeline - /// to zero, so a click recorded against clip time has to move back by the - /// same amount or it fires late by the length of the trim. #[test] - fn click_times_are_rebased_by_the_trim() { - let clicks = vec![Click { + fn click_geometry_and_time_use_the_source_before_crop_and_trim() { + let mut req = dummy_request(); + req.crop = Some(CaptureRect { x: 400, y: 300, width: 520, height: 380 }); + req.trim_start_secs = Some(5.0); + req.clicks = vec![Click { time_secs: 6.0, x: 500, y: 400, button: crate::clicks::MouseButton::Left, }]; - let untrimmed = click_filters(&clicks, 1920, 1080, 0.0).unwrap(); - assert!(untrimmed.contains("between(t,5.950,6.250)")); - let trimmed = click_filters(&clicks, 1920, 1080, 5.0).unwrap(); - assert!(trimmed.contains("between(t,0.950,1.250)")); - assert!(!trimmed.contains("6.250")); - } - - /// A click that happened before the trimmed window has nothing left to draw. - #[test] - fn clicks_before_the_trim_are_dropped() { - let clicks = vec![Click { - time_secs: 1.0, - x: 500, - y: 400, - button: crate::clicks::MouseButton::Left, - }]; - assert!(click_filters(&clicks, 1920, 1080, 5.0).is_none()); + let filters = video_filters(&req); + assert!(filters.starts_with("drawbox=x=488:y=388:")); + assert!(filters.contains("between(t,5.950,6.250)")); + assert!(filters.ends_with(",crop=520:380:400:300:exact=1,fps=30")); } #[test] - fn gif_shrink_factor_resolution_uses_sqrt() { - // ratio 0.25 -> halving the *width* (which quarters pixels) needs sqrt(0.25)=0.5 - let f = gif_shrink_factor(GifBudgetMode::Resolution, 0.25); - assert!((f - 0.5).abs() < 1e-9); - } + fn gif_budget_retries_preserve_the_selected_priority() { + let (mut width, mut fps) = (800, 20); + let mode = GifBudgetMode::Resolution; + shrink_gif_params(mode, gif_shrink_factor(mode, 0.5), &mut width, &mut fps); + assert_eq!((width, fps), (800, 10)); - #[test] - fn gif_shrink_factor_framerate_is_linear() { - // ratio 0.5 -> halving fps needs factor 0.5 - let f = gif_shrink_factor(GifBudgetMode::Framerate, 0.5); - assert!((f - 0.5).abs() < 1e-9); + let mode = GifBudgetMode::Framerate; + shrink_gif_params(mode, gif_shrink_factor(mode, 0.25), &mut width, &mut fps); + assert_eq!((width, fps), (400, 10)); } #[test] diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index bbda6ac..2323607 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -67,9 +67,9 @@ pub struct AppState { capture_transition: Mutex<()>, pub picker: Mutex>, pub overlay_poll_shutdown: Arc, - pub export_cancel: Arc, - pub exporting: Arc, + encode_operation: Mutex>>, thumbnail_operation: Mutex<()>, + reviewed_output: Mutex>, pub overlay_aspect_ratio: Mutex>, /// (active flag, condvar) so the overlay click-through poll thread can park /// itself when no overlay is on screen instead of waking every 80ms. @@ -137,7 +137,7 @@ fn timestamp_slug() -> String { std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .unwrap_or_default() - .as_secs() + .as_millis() .to_string() } @@ -304,7 +304,7 @@ async fn download_update( fn apply_update(app: AppHandle, state: State<'_, AppState>) -> Result<(), String> { if state.capture_transition.try_lock().is_err() || lock(&state.session).is_some() - || state.exporting.load(Ordering::SeqCst) + || lock(&state.encode_operation).is_some() || state.unexported_clip.load(Ordering::Relaxed) { return Err("finish or discard the current recording before applying the update".to_string()); @@ -463,7 +463,7 @@ fn start_capture( request: Option, ) -> Result<(), String> { let _transition = state.begin_capture_transition()?; - if state.exporting.load(Ordering::SeqCst) { + if lock(&state.encode_operation).is_some() { return Err("wait for the current output operation".to_string()); } { @@ -480,6 +480,7 @@ fn start_capture( let _thumbnails = state.thumbnail_operation.try_lock() .map_err(|_| "wait for thumbnail generation to finish".to_string())?; *lock(&state.last_clip) = None; + *lock(&state.reviewed_output) = None; state.unexported_clip.store(false, Ordering::Relaxed); clear_temp_segments(&state.app_dir, true); @@ -770,10 +771,11 @@ fn stop_capture(state: State<'_, AppState>) -> Result { #[tauri::command] fn discard_clip(state: State<'_, AppState>) -> Result<(), String> { let _transition = state.begin_capture_transition()?; - if state.exporting.load(Ordering::SeqCst) { + if lock(&state.encode_operation).is_some() { return Err("wait for the current preview or export".to_string()); } *lock(&state.last_clip) = None; + *lock(&state.reviewed_output) = None; state.unexported_clip.store(false, Ordering::Relaxed); Ok(()) } @@ -785,14 +787,14 @@ pub struct ExportRequest { pub fps: u32, pub keep_audio: bool, #[serde(default)] - pub deleted_frame_indices: Vec, - #[serde(default)] pub trim_start_secs: Option, #[serde(default)] pub trim_end_secs: Option, #[serde(default)] pub output_path: Option, #[serde(default)] + pub overwrite: bool, + #[serde(default)] pub crop: Option, #[serde(default)] pub gif_budget_mode: GifBudgetMode, @@ -803,11 +805,8 @@ pub struct ExportRequest { } #[tauri::command] -fn default_output_path(state: State<'_, AppState>, format: Format) -> String { - let dir = output_dir(&state.app_dir, &lock(&state.config)); - dir.join(format!("bytesize-{}.{}", timestamp_slug(), ext_for(format))) - .to_string_lossy() - .into_owned() +fn default_output_path(state: State<'_, AppState>, format: Format) -> Result { + export_path(&state, format, None) } #[derive(Debug, Deserialize)] @@ -821,8 +820,6 @@ 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)] @@ -831,62 +828,6 @@ pub struct PreviewRequest { pub duration_secs: Option, } -#[tauri::command(async)] -fn render_preview(state: State<'_, AppState>, request: PreviewRequest) -> Result { - let clip = lock(&state.last_clip) - .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 target_width: u32 = if request.format == Format::Gif { - let budget = encode::GifBudgetInput { - gif_colors: request.gif_colors.unwrap_or(256), - target_bytes: request.target_bytes, - fps: request.fps, - duration_secs: clip.duration_secs, - gif_budget_mode: request.gif_budget_mode, - }; - let (w, _) = encode::gif_params(&budget, clip.width, clip.height); - w - } else { - clip.width.clamp(160, 1280) - }; - - let preview_path = temp_dir(&state.app_dir).join("preview.png"); - let midpoint = (clip.duration_secs / 2.0).max(0.0); - if request.format == Format::Gif { - let dither_str = match request.gif_dither.unwrap_or(GifDither::FloydSteinberg) { - GifDither::FloydSteinberg => "floyd_steinberg", - GifDither::Bayer => "bayer:bayer_scale=3", - GifDither::None => "none", - }; - encode::render_gif_preview( - &ffmpeg, - &clip.temp_path, - &preview_path, - midpoint, - target_width, - request.gif_colors.unwrap_or(256), - dither_str, - clip.duration_secs, - ) - .map_err(|e| format!("{e:#}"))?; - } else { - encode::render_preview( - &ffmpeg, - &clip.temp_path, - &preview_path, - midpoint, - target_width, - ) - .map_err(|e| format!("{e:#}"))?; - } - Ok(preview_path) -} - #[derive(Debug, Serialize)] pub struct GifEstimate { pub width: u32, @@ -1003,6 +944,103 @@ mod tests { use super::*; + #[test] + fn export_preserves_existing_file_until_authorized_publish() -> Result<()> { + let dir = std::env::temp_dir().join(format!("bytesize-export-test-{}", std::process::id())); + std::fs::create_dir_all(&dir)?; + let old = encode::TempFileGuard(dir.join("output.mp4")); + std::fs::write(&old.0, b"existing")?; + let staged = encode::TempFileGuard::create_in(&dir, "export", "tmp")?; + std::fs::write(&staged.0, b"new export")?; + assert!(publish_export(&staged.0, &old.0, false).is_err()); + assert_eq!(std::fs::read(&old.0)?, b"existing"); + publish_export(&staged.0, &old.0, true)?; + assert_eq!(std::fs::read(&old.0)?, b"new export"); + drop((old, staged)); + std::fs::remove_dir(dir)?; + Ok(()) + } + + #[test] + fn saving_reviewed_output_preserves_preview_bytes_and_keeps_the_preview() -> Result<()> { + let dir = std::env::temp_dir().join(format!("bytesize-review-test-{}", std::process::id())); + std::fs::create_dir_all(&dir)?; + let artifact = encode::TempFileGuard::create_in(&dir, "output-review", "gif")?; + let encoded = b"GIF89a\x80\x00\x60\x00\x00\xff\x01\x3b"; + std::fs::write(&artifact.0, encoded)?; + let preview = OutputPreview { + id: "reviewed-file".to_string(), path: artifact.0.clone(), format: Format::Gif, + size_bytes: encoded.len() as u64, target_bytes: 1024, + media: encode::OutputProperties { width: 128, height: 96, fps: 5.0, duration_secs: 1.0 }, + }; + let staging = encode::TempFileGuard::create_in(&dir, "export", "tmp")?; + let destination = encode::TempFileGuard::create_in(&dir, "saved", "gif")?; + std::fs::write(&destination.0, b"existing output")?; + assert!(copy_reviewed_file(&preview, &staging.0, &destination.0, false).is_err()); + assert_eq!(std::fs::read(&destination.0)?, b"existing output"); + copy_reviewed_file(&preview, &staging.0, &destination.0, true)?; + assert_eq!(std::fs::read(&destination.0)?, encoded); + assert_eq!(std::fs::read(&artifact.0)?, encoded); + drop((artifact, staging, destination)); + std::fs::remove_dir(dir)?; + Ok(()) + } + + #[test] + #[ignore = "requires an FFmpeg build with H.264 and VP9; set BYTESIZE_TEST_FFMPEG"] + fn encodes_inspects_and_saves_reviewed_media() -> Result<()> { + let ffmpeg = std::env::var_os("BYTESIZE_TEST_FFMPEG").map(PathBuf::from) + .ok_or_else(|| anyhow!("set BYTESIZE_TEST_FFMPEG to ffmpeg.exe"))?; + let dir = std::env::temp_dir().join(format!("bytesize-media-review-test-{}", std::process::id())); + std::fs::create_dir_all(&dir)?; + let source = encode::TempFileGuard::create_in(&dir, "sample", "mp4")?; + let status = std::process::Command::new(&ffmpeg) + .args(["-y", "-v", "error", "-f", "lavfi", "-i", "testsrc2=size=128x96:rate=10:duration=2", "-c:v", "libx264"]) + .arg(&source.0).status()?; + anyhow::ensure!(status.success(), "could not generate sample video"); + for format in [Format::Gif, Format::Mp4, Format::Webm] { + let artifact = encode::TempFileGuard::create_in(&dir, "output-review", ext_for(format))?; + let req = encode::TranscodeRequest { + input: source.0.clone(), output: artifact.0.clone(), format, target_bytes: 102_400, + duration_secs: 1.0, fps: 10, keep_audio: false, gif_colors: 128, + gif_dither: GifDither::Bayer, gif_budget_mode: GifBudgetMode::Balanced, + webm_codec: config::WebmCodec::Vp9, mp4_codec: config::Mp4Codec::H264, + scratch_dir: dir.clone(), crop: None, + trim_start_secs: Some(0.3), trim_end_secs: Some(1.3), + clicks: Vec::new(), clip_width: 128, clip_height: 96, progress_tx: None, cancel: None, + }; + encode::transcode(&ffmpeg, &req)?; + let media = encode::inspect_output(&ffmpeg, &artifact.0)?; + assert!(media.width > 0 && media.height > 0 && media.fps > 0.0); + assert!((media.duration_secs - 1.0).abs() < 0.15, "{format:?}: {media:?}"); + let preview = OutputPreview { + id: "review".to_string(), path: artifact.0.clone(), format, + size_bytes: std::fs::metadata(&artifact.0)?.len(), target_bytes: req.target_bytes, media, + }; + let staging = encode::TempFileGuard::create_in(&dir, "export", "tmp")?; + let output = encode::TempFileGuard::create_in(&dir, "saved", ext_for(format))?; + copy_reviewed_file(&preview, &staging.0, &output.0, true)?; + assert_eq!(std::fs::read(&output.0)?, std::fs::read(&artifact.0)?); + } + drop(source); + std::fs::remove_dir(dir)?; + Ok(()) + } + + #[test] + fn a_second_instance_cannot_lock_the_same_folder() -> Result<()> { + let dir = std::env::temp_dir().join(format!("bytesize-lock-test-{}", std::process::id())); + let first = lock_instance(&dir)?; + assert!(lock_instance(&dir).is_err()); + drop(first); + drop(lock_instance(&dir)?); + let temp = temp_dir(&dir); + std::fs::remove_file(temp.join("instance.lock"))?; + std::fs::remove_dir(temp)?; + std::fs::remove_dir(dir)?; + Ok(()) + } + fn make_request(target_bytes: u64, fps: u32, mode: GifBudgetMode) -> PreviewRequest { PreviewRequest { format: Format::Gif, @@ -1117,39 +1155,13 @@ mod tests { } #[tauri::command(async)] -fn extract_thumbnails(state: State<'_, AppState>, fps: u32) -> Result, String> { - let _thumbnails = lock(&state.thumbnail_operation); - let clip = lock(&state.last_clip) - .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:#}")) -} - -#[tauri::command(async)] -fn render_raw_preview(state: State<'_, AppState>, timestamp: f64) -> Result { - let clip = lock(&state.last_clip) - .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 out_path = temp_dir(&state.app_dir).join("raw-preview.png"); - encode::render_preview( - &ffmpeg, - &clip.temp_path, - &out_path, - timestamp, - clip.width.min(1280), - ) - .map_err(|e| format!("{e:#}"))?; - Ok(out_path) +fn timeline_thumbnails(state: State<'_, AppState>) -> Result, String> { + let _page = lock(&state.thumbnail_operation); + let clip = lock(&state.last_clip).clone().ok_or_else(|| "no recorded clip available".to_string())?; + let clip_name = clip.temp_path.file_stem().ok_or_else(|| "invalid clip file name".to_string())?; + let dir = temp_dir(&state.app_dir).join("thumbs").join("timeline").join(clip_name); + encode::timeline_thumbnails(&bootstrap::ffmpeg_path(&state.app_dir), &clip.temp_path, &dir, clip.duration_secs) + .map_err(|error| format!("{error:#}")) } #[tauri::command(async)] @@ -1172,6 +1184,23 @@ pub struct ExportResult { pub met_target: bool, } +#[derive(Clone, Serialize)] +struct OutputPreview { + id: String, + path: PathBuf, + format: Format, + size_bytes: u64, + target_bytes: u64, + #[serde(flatten)] + media: encode::OutputProperties, +} + +struct ReviewedOutput { + preview: OutputPreview, + source: PathBuf, + _file: encode::TempFileGuard, +} + const OVERLAY_BORDER_LOGICAL_PX: f64 = 4.0; const OVERLAY_TITLEBAR_LOGICAL_PX: f64 = 44.0; const OVERLAY_TOOLBAR_WIDTH_LOGICAL_PX: f64 = 380.0; @@ -1185,7 +1214,6 @@ fn cleanup_temp_on_exit(app: &AppHandle) { clear_temp_segments(&st.app_dir, false); } -/// Keep click-through decisions in the poller so its cached state stays current. fn lock_instance(app_dir: &Path) -> std::io::Result { use std::os::windows::fs::OpenOptionsExt; @@ -1210,7 +1238,7 @@ fn close_main(window: &tauri::Window) { let app = window.app_handle(); let owner = window.hwnd().ok().map(|handle| HWND(handle.0)); let transitioning = state.capture_transition.try_lock().is_err(); - if transitioning || lock(&state.session).is_some() || state.exporting.load(Ordering::SeqCst) + if transitioning || lock(&state.session).is_some() || lock(&state.encode_operation).is_some() || state.thumbnail_operation.try_lock().is_err() { // SAFETY: The owner is the main window. Both strings have static storage. @@ -1770,6 +1798,15 @@ fn reveal_in_explorer(path: String) -> Result<(), String> { Ok(()) } +#[tauri::command] +fn open_url(url: String) -> Result<(), String> { + let url = reqwest::Url::parse(&url).map_err(|e| format!("invalid URL: {e}"))?; + if !matches!(url.scheme(), "http" | "https") || !url.has_host() { + return Err("only http/https URLs are supported".to_string()); + } + open_shell_target(std::ffi::OsStr::new(url.as_str())) +} + fn open_shell_target(target: &std::ffi::OsStr) -> Result<(), String> { use windows::core::{w, HSTRING, PCWSTR}; use windows::Win32::UI::Shell::ShellExecuteW; @@ -1795,15 +1832,6 @@ fn open_shell_target(target: &std::ffi::OsStr) -> Result<(), String> { Ok(()) } -#[tauri::command] -fn open_url(url: String) -> Result<(), String> { - let url = reqwest::Url::parse(&url).map_err(|e| format!("invalid URL: {e}"))?; - if !matches!(url.scheme(), "http" | "https") || !url.has_host() { - return Err("only http/https URLs are supported".to_string()); - } - open_shell_target(std::ffi::OsStr::new(url.as_str())) -} - #[derive(Debug, Serialize)] pub struct DiagnosticsInfo { pub app_version: String, @@ -1892,7 +1920,9 @@ fn open_log_dir(state: State<'_, AppState>) -> Result<(), String> { #[tauri::command] fn cancel_export(state: State<'_, AppState>) { - state.export_cancel.store(true, Ordering::SeqCst); + if let Some(cancel) = lock(&state.encode_operation).as_ref() { + cancel.store(true, Ordering::SeqCst); + } } #[tauri::command(async)] @@ -1910,161 +1940,303 @@ fn codec_availability(state: State<'_, AppState>) -> Result); +struct EncodeOperation<'a> { + slot: &'a Mutex>>, + cancel: Arc, +} -impl Drop for ExportGuard { - fn drop(&mut self) { - self.0.store(false, Ordering::SeqCst); +impl<'a> EncodeOperation<'a> { + fn begin(state: &'a AppState) -> Result { + let _transition = state.begin_capture_transition()?; + if lock(&state.session).is_some() { + return Err("finish recording before preparing output".to_string()); + } + let mut active = lock(&state.encode_operation); + if active.is_some() { + return Err("an export or preview is already running".to_string()); + } + let cancel = Arc::new(AtomicBool::new(false)); + *active = Some(cancel.clone()); + Ok(Self { slot: &state.encode_operation, cancel }) } } -// One export is one transaction: resolve the output path, translate the trim -// and crop into encoder terms, run the encode, and report the size. Splitting -// it would mean threading the same resolved state through the pieces. -#[allow( - clippy::too_many_lines, - reason = "one export transaction; the request translation feeds directly into the encode call" -)] +impl Drop for EncodeOperation<'_> { + fn drop(&mut self) { + *lock(self.slot) = None; + } +} + +fn export_path(state: &AppState, format: Format, entered: Option<&str>) -> Result { + let directory = output_dir(&state.app_dir, &lock(&state.config)); + let mut path = entered.map(str::trim).filter(|path| !path.is_empty()).map_or_else( + || directory.join(format!("bytesize-{}.{}", timestamp_slug(), ext_for(format))), + PathBuf::from, + ); + if path.is_relative() { + path = state.app_dir.join(path); + } + if path.is_dir() || !path.set_extension(ext_for(format)) { + return Err("choose a file name for the export".to_string()); + } + Ok(path) +} + +#[derive(Serialize)] +struct ExportDestination { + path: PathBuf, + exists: bool, +} + #[tauri::command] -async fn export( - app: AppHandle, +fn export_destination( state: State<'_, AppState>, + format: Format, + path: String, +) -> Result { + let path = export_path(&state, format, Some(&path))?; + let exists = path.try_exists().map_err(|e| e.to_string())?; + Ok(ExportDestination { path, exists }) +} + +fn transcode_request( + state: &AppState, request: ExportRequest, -) -> Result { - if state.exporting.swap(true, Ordering::SeqCst) { - return Err("an export is already running".to_string()); + output: PathBuf, + cancel: Arc, +) -> Result { + let cfg = lock(&state.config).clone(); + let clip = lock(&state.last_clip) + .clone() + .ok_or_else(|| "no recorded clip available".to_string())?; + let start = request.trim_start_secs.unwrap_or(0.0); + let end = request.trim_end_secs.unwrap_or(clip.duration_secs); + if !start.is_finite() || !end.is_finite() || start < 0.0 || end > clip.duration_secs || end <= start { + return Err("choose a valid trim range".to_string()); } - let _export = ExportGuard(state.exporting.clone()); - - 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()); - } - - 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(&app_dir, &cfg); - out_dir.join(format!( - "bytesize-{}.{}", - timestamp_slug(), - ext_for(request.format) - )) + if let Some(crop) = request.crop { + if crop.width < 2 || crop.height < 2 || crop.width % 2 != 0 || crop.height % 2 != 0 + || crop.x < 0 || crop.y < 0 + || crop.x.cast_unsigned().saturating_add(crop.width) > clip.width + || crop.y.cast_unsigned().saturating_add(crop.height) > clip.height + { + return Err("choose an in-frame crop with even width and height of at least 2 pixels".to_string()); } - }; - if let Some(parent) = out_path.parent() { - std::fs::create_dir_all(parent).map_err(|e| format!("creating output dir: {e:#}"))?; + } + if request.fps == 0 { + return Err("choose an export frame rate above zero".to_string()); } - let trim_start = request.trim_start_secs.filter(|s| *s > 0.001); - let trim_end = request - .trim_end_secs - .filter(|e| *e < clip.duration_secs - 0.001); - let effective_duration = match (trim_start, trim_end) { - (Some(s), Some(e)) => (e - s).max(0.1), - (Some(s), None) => (clip.duration_secs - s).max(0.1), - (None, Some(e)) => e.max(0.1), - (None, None) => clip.duration_secs, - }; + let duration_secs = end - start; - let (src_w, src_origin) = if let Some(c) = clip.crop { - (c.width, (c.x, c.y)) - } else { - (clip.monitor_width.max(1), (0, 0)) - }; - let scale = f64::from(clip.width) / f64::from(src_w); - let transformed_clicks: Vec = clip - .clicks - .iter() - .map(|c| clicks::Click { - time_secs: c.time_secs, - x: encode::round_i32(f64::from(c.x - src_origin.0) * scale), - y: encode::round_i32(f64::from(c.y - src_origin.1) * scale), - button: c.button, - }) - .collect(); + let (src_w, src_h, src_x, src_y) = clip.crop.map_or( + (clip.monitor_width, clip.monitor_height, 0, 0), + |crop| (crop.width, crop.height, crop.x, crop.y), + ); + let scale_x = f64::from(clip.width) / f64::from(src_w.max(1)); + let scale_y = f64::from(clip.height) / f64::from(src_h.max(1)); + let clicks = clip.clicks.iter() + .filter(|click| click.time_secs + 0.25 >= start && click.time_secs - 0.05 < end) + .map(|click| clicks::Click { + time_secs: click.time_secs, + x: encode::round_i32((f64::from(click.x) - f64::from(src_x)) * scale_x), + y: encode::round_i32((f64::from(click.y) - f64::from(src_y)) * scale_y), + button: click.button, + }).collect(); - let req = encode::TranscodeRequest { - input: clip.temp_path.clone(), - output: out_path.clone(), + Ok(encode::TranscodeRequest { + input: clip.temp_path, + output, format: request.format, target_bytes: request.target_bytes, - duration_secs: effective_duration, + duration_secs, fps: request.fps, keep_audio: request.keep_audio, gif_dither: request.gif_dither.unwrap_or(cfg.export.gif_dither), gif_colors: request.gif_colors.unwrap_or(256), webm_codec: cfg.export.webm_codec, mp4_codec: cfg.export.mp4_codec, - scratch_dir: temp_dir(&app_dir), + scratch_dir: temp_dir(&state.app_dir), crop: request.crop, gif_budget_mode: request.gif_budget_mode, - deleted_frame_indices: request.deleted_frame_indices, - trim_start_secs: trim_start, - trim_end_secs: trim_end, - clicks: transformed_clicks, + trim_start_secs: request.trim_start_secs, + trim_end_secs: request.trim_end_secs, + clicks, clip_width: clip.width, clip_height: clip.height, progress_tx: None, - cancel: Some(export_cancel.clone()), - }; + cancel: Some(cancel), + }) +} +fn publish_export(staging: &Path, output: &Path, overwrite: bool) -> Result<()> { + if overwrite { + std::fs::rename(staging, output)?; + } else { + use windows::core::HSTRING; + use windows::Win32::Storage::FileSystem::MoveFileW; + let staging = HSTRING::from(staging.as_os_str()); + let output = HSTRING::from(output.as_os_str()); + // SAFETY: Both paths are NUL-terminated and live through the call. + unsafe { MoveFileW(&staging, &output) }?; + } + Ok(()) +} + +async fn run_output_encode( + app: AppHandle, + ffmpeg: PathBuf, + mut request: encode::TranscodeRequest, +) -> Result<(), String> { let (tx, rx) = std::sync::mpsc::channel(); - let mut req_with_progress = req; - req_with_progress.progress_tx = Some(tx); - let app_handle = app.clone(); - - // Spawn a thread to forward encode progress to the frontend. The encoder - // owns total_passes: 2 for two-pass video, max_retries (up to 12) for GIF - // so the progress bar accumulates across retry attempts. - std::thread::spawn(move || { - while let Ok(progress) = rx.recv() { - drop(app_handle.emit( - "encode-progress", - encode::EncodeProgress { - pass: progress.pass, - total_passes: progress.total_passes, - percent: progress.percent, - }, - )); + request.progress_tx = Some(tx); + let progress = std::thread::spawn(move || { + while let Ok(update) = rx.recv() { + drop(app.emit("encode-progress", update)); } }); - - 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 = 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) + tauri::async_runtime::spawn_blocking(move || { + let result = encode::transcode(&ffmpeg, &request); + drop(request); + drop(progress.join()); + result }) .await - .map_err(|e| format!("encode task panicked: {e:#}"))?; - result.map_err(|e| format!("{e:#}"))?; + .map_err(|e| format!("encode task failed: {e:#}"))? + .map_err(|e| format!("{e:#}")) +} - let size_bytes = std::fs::metadata(&out_path).map_or(0, |m| m.len()); +fn output_size(path: &Path) -> Result { + let size = std::fs::metadata(path) + .map_err(|e| format!("checking encoded output: {e:#}"))?.len(); + if size == 0 { return Err("the encoder produced an empty file".to_string()); } + Ok(size) +} + +#[tauri::command] +async fn render_output_preview( + app: AppHandle, + state: State<'_, AppState>, + request: ExportRequest, +) -> Result { + let operation = EncodeOperation::begin(&state)?; + let format = request.format; + let target_bytes = request.target_bytes; + let dir = temp_dir(&state.app_dir); + let staging = encode::TempFileGuard::create_in(&dir, "output-review", ext_for(format)) + .map_err(|e| format!("creating output preview file: {e:#}"))?; + let path = staging.0.clone(); + let req = transcode_request(&state, request, path.clone(), operation.cancel.clone())?; + let source = req.input.clone(); + let ffmpeg = bootstrap::ffmpeg_path(&state.app_dir); + run_output_encode(app, ffmpeg.clone(), req).await?; + if operation.cancel.load(Ordering::SeqCst) { return Err("preview cancelled".to_string()); } + + let size_bytes = output_size(&path)?; + let inspection_path = path.clone(); + let media = tauri::async_runtime::spawn_blocking(move || encode::inspect_output(&ffmpeg, &inspection_path)) + .await.map_err(|e| format!("output inspection task failed: {e:#}"))? + .map_err(|e| format!("{e:#}"))?; + if operation.cancel.load(Ordering::SeqCst) { return Err("preview cancelled".to_string()); } + + let id = path.file_stem().and_then(std::ffi::OsStr::to_str) + .ok_or_else(|| "could not identify the output preview".to_string())?.to_string(); + let preview = OutputPreview { id, path, format, size_bytes, target_bytes, media }; + *lock(&state.reviewed_output) = Some(ReviewedOutput { preview: preview.clone(), source, _file: staging }); + Ok(preview) +} + +fn reviewed_output(state: &AppState, preview_id: &str) -> Result { + let clip = lock(&state.last_clip); + lock(&state.reviewed_output).as_ref() + .filter(|item| item.preview.id == preview_id && item.preview.path.is_file() + && clip.as_ref().is_some_and(|clip| clip.temp_path == item.source)) + .map(|item| item.preview.clone()) + .ok_or_else(|| "this output preview is unavailable. Render the current edits again.".to_string()) +} + +#[tauri::command] +fn open_output_preview(state: State<'_, AppState>, preview_id: &str) -> Result<(), String> { + let preview = reviewed_output(&state, preview_id)?; + open_shell_target(preview.path.as_os_str()) +} + +fn stage_export( + state: &AppState, + format: Format, + entered: Option<&str>, + overwrite: bool, +) -> Result<(PathBuf, encode::TempFileGuard), String> { + let output = export_path(state, format, entered)?; + let exists = output.try_exists().map_err(|e| e.to_string())?; + if exists && !overwrite { return Err("the output file already exists".to_string()); } + let canonical = std::fs::canonicalize(&output).ok(); + let matches = |source: &Path| { + source == output || canonical.as_ref().is_some_and(|output| { + std::fs::canonicalize(source).is_ok_and(|source| source == *output) + }) + }; + if lock(&state.last_clip).as_ref().is_some_and(|clip| matches(&clip.temp_path)) + || lock(&state.reviewed_output).as_ref().is_some_and(|item| matches(&item.preview.path)) + { + return Err("choose a destination outside the recording and preview files".to_string()); + } + let parent = output.parent().ok_or_else(|| "choose an output folder".to_string())?; + std::fs::create_dir_all(parent).map_err(|e| format!("creating output folder: {e:#}"))?; + let staging = encode::TempFileGuard::create_in(parent, "export", "tmp") + .map_err(|e| format!("creating export staging file: {e:#}"))?; + Ok((output, staging)) +} + +fn finish_export(state: &AppState, output_path: PathBuf, size_bytes: u64, target_bytes: u64) -> ExportResult { state.unexported_clip.store(false, Ordering::Relaxed); - Ok(ExportResult { - met_target: size_bytes <= request.target_bytes, - target_bytes: request.target_bytes, - output_path: out_path, - size_bytes, - }) + ExportResult { met_target: size_bytes <= target_bytes, target_bytes, output_path, size_bytes } +} + +fn copy_reviewed_file(preview: &OutputPreview, staging: &Path, output: &Path, overwrite: bool) -> Result<()> { + let copied = std::fs::copy(&preview.path, staging)?; + anyhow::ensure!(copied == preview.size_bytes, "the reviewed file changed on disk"); + publish_export(staging, output, overwrite) +} + +#[tauri::command] +async fn save_output_preview( + state: State<'_, AppState>, + preview_id: String, + output_path: String, + overwrite: bool, +) -> Result { + let _operation = EncodeOperation::begin(&state)?; + let preview = reviewed_output(&state, &preview_id)?; + let (output, staging) = stage_export(&state, preview.format, Some(&output_path), overwrite)?; + let target = output.clone(); + let (size_bytes, target_bytes) = (preview.size_bytes, preview.target_bytes); + tauri::async_runtime::spawn_blocking(move || copy_reviewed_file(&preview, &staging.0, &target, overwrite)) + .await.map_err(|e| format!("save task failed: {e:#}"))? + .map_err(|e| format!("saving the reviewed file: {e:#}"))?; + Ok(finish_export(&state, output, size_bytes, target_bytes)) +} + +#[tauri::command] +async fn export( + app: AppHandle, + state: State<'_, AppState>, + request: ExportRequest, +) -> Result { + let operation = EncodeOperation::begin(&state)?; + let target_bytes = request.target_bytes; + let overwrite = request.overwrite; + let (out_path, staging) = stage_export(&state, request.format, request.output_path.as_deref(), overwrite)?; + let req = transcode_request(&state, request, staging.0.clone(), operation.cancel.clone())?; + let ffmpeg = bootstrap::ffmpeg_path(&state.app_dir); + run_output_encode(app, ffmpeg, req).await?; + if operation.cancel.load(Ordering::SeqCst) { + return Err("export cancelled".to_string()); + } + let size_bytes = output_size(&staging.0)?; + publish_export(&staging.0, &out_path, overwrite) + .map_err(|e| format!("saving export: {e:#}"))?; + Ok(finish_export(&state, out_path, size_bytes, target_bytes)) } fn show_startup_error(message: &str) { @@ -2092,7 +2264,6 @@ fn show_startup_error(message: &str) { )] pub fn run() { let app_dir = exe_dir().expect("resolve exe directory"); - let _instance = match lock_instance(&app_dir) { Ok(lock) => lock, Err(e) => { @@ -2165,11 +2336,11 @@ pub fn run() { unexported_clip: AtomicBool::new(false), session: Mutex::new(None), capture_transition: Mutex::new(()), - thumbnail_operation: Mutex::new(()), picker: Mutex::new(None), overlay_poll_shutdown: Arc::new(AtomicBool::new(false)), - export_cancel: Arc::new(AtomicBool::new(false)), - exporting: Arc::new(AtomicBool::new(false)), + encode_operation: Mutex::new(None), + thumbnail_operation: Mutex::new(()), + reviewed_output: Mutex::new(None), overlay_aspect_ratio: Mutex::new(None), overlay_poll_live: Arc::new((Mutex::new(false), std::sync::Condvar::new())), }; @@ -2243,9 +2414,7 @@ pub fn run() { let cfg = lock(&st.config).clone(); (cfg.updates.check_on_launch, cfg) }; - // Result is not Drop, so the old drop() here did nothing beyond - // extending its lifetime; the hotkey outcome is logged upstream. - let _hotkeys = register_hotkeys(app.handle(), &cfg); + drop(register_hotkeys(app.handle(), &cfg)); { let st = app.state::(); start_overlay_clickthrough_poll( @@ -2289,7 +2458,6 @@ pub fn run() { download_update, apply_update, pending_update, - check_for_updates, start_capture, pause_capture, resume_capture, @@ -2298,10 +2466,12 @@ pub fn run() { discard_clip, export, default_output_path, - extract_thumbnails, - render_preview, + export_destination, + timeline_thumbnails, preview_display, - render_raw_preview, + render_output_preview, + save_output_preview, + open_output_preview, estimate_gif_params, estimate_gif_params_table, reveal_in_explorer, @@ -2317,6 +2487,7 @@ pub fn run() { open_window_picker, close_window_picker, get_overlay_rect, + check_for_updates, cancel_export, codec_availability, diagnostics_info, diff --git a/src/app.css b/src/app.css deleted file mode 100644 index bb5d4b6..0000000 --- a/src/app.css +++ /dev/null @@ -1,164 +0,0 @@ -/* ============================================================ - ByteSize - Noir Precision Design System - Ultra-dark instrument panel aesthetic. - Electric teal accent. Monospace data readouts. - ============================================================ */ - -@import url('https://fonts.bunny.net/css2?family=DM+Sans:ital,opsz,wght@0,9..40,400;0,9..40,500;0,9..40,600;1,9..40,400&family=JetBrains+Mono:wght@400;500&display=swap'); - -/* ---- Dark theme (default) ---- */ -:root, -[data-theme="dark"] { - /* Backgrounds - layered near-blacks */ - --bg: #09090B; - --bg-2: #0E0E11; - --bg-3: #13131A; - --bg-4: #1A1A22; - - /* Accent - electric teal */ - --accent: #14B8A6; - --accent-hover: #2DD4BF; - --accent-dim: rgba(20, 184, 166, 0.10); - --accent-glow: rgba(20, 184, 166, 0.25); - --accent-text: #020617; - - /* Semantic - recording */ - --recording: #22C55E; - --recording-dim: rgba(34, 197, 94, 0.10); - --recording-glow: rgba(34, 197, 94, 0.20); - - /* Semantic - stop / danger */ - --stop: #EF4444; - --stop-hover: #F87171; - --stop-dim: rgba(239, 68, 68, 0.10); - - /* Semantic - error */ - --err: #EF4444; - --err-border: rgba(239, 68, 68, 0.30); - --err-dim: rgba(239, 68, 68, 0.08); - - /* Semantic - warning */ - --warn: #EAB308; - --warn-dim: rgba(234, 179, 8, 0.08); - - /* Borders */ - --border: rgba(255, 255, 255, 0.06); - --border-2: rgba(255, 255, 255, 0.10); - --border-3: rgba(255, 255, 255, 0.14); - - /* Text */ - --text: #E4E4E7; - --text-2: #A1A1AA; - --text-3: #71717A; - --text-4: #52525B; - - /* Typography */ - --sans: 'DM Sans', system-ui, sans-serif; - --mono: 'JetBrains Mono', ui-monospace, monospace; - - /* Radii */ - --r-sm: 3px; - --r-md: 6px; - --r-lg: 8px; - - color-scheme: dark; -} - -/* ---- Light theme ---- */ -[data-theme="light"] { - --bg: #FAFAFA; - --bg-2: #F4F4F5; - --bg-3: #E4E4E7; - --bg-4: #D4D4D8; - - --accent: #0D9488; - --accent-hover: #0F766E; - --accent-dim: rgba(13, 148, 136, 0.08); - --accent-glow: rgba(13, 148, 136, 0.15); - --accent-text: #FFFFFF; - - --recording: #16A34A; - --recording-dim: rgba(22, 163, 74, 0.08); - --recording-glow: rgba(22, 163, 74, 0.12); - - --stop: #DC2626; - --stop-hover: #B91C1C; - --stop-dim: rgba(220, 38, 38, 0.08); - - --err: #DC2626; - --err-border: rgba(220, 38, 38, 0.25); - --err-dim: rgba(220, 38, 38, 0.06); - - --warn: #CA8A04; - --warn-dim: rgba(202, 138, 4, 0.06); - - --border: rgba(0, 0, 0, 0.08); - --border-2: rgba(0, 0, 0, 0.12); - --border-3: rgba(0, 0, 0, 0.18); - - --text: #18181B; - --text-2: #52525B; - --text-3: #71717A; - --text-4: #A1A1AA; - - color-scheme: light; -} - -/* ---- Reset & base ---- */ -*, *::before, *::after { - box-sizing: border-box; -} - -html { - font-family: var(--sans); - font-size: 14px; - -webkit-font-smoothing: antialiased; - -moz-osx-font-smoothing: grayscale; -} - -body { - margin: 0; - background: var(--bg); - color: var(--text); - min-height: 100vh; -} - -/* ---- Selection ---- */ -::selection { - background: var(--accent-dim); - color: var(--text); -} - -/* ---- Scrollbar ---- */ -::-webkit-scrollbar { width: 5px; height: 5px; } -::-webkit-scrollbar-track { background: transparent; } -::-webkit-scrollbar-thumb { - background: var(--border-2); - border-radius: 3px; -} -::-webkit-scrollbar-thumb:hover { background: var(--text-4); } - -/* ---- Focus ---- */ -:focus-visible { - outline: none; - box-shadow: 0 0 0 1px var(--accent), 0 0 0 3px var(--accent-glow); - border-radius: var(--r-sm); -} - -/* ---- Reduced motion ---- */ -@media (prefers-reduced-motion: reduce) { - *, *::before, *::after { - animation-duration: 0.01ms !important; - transition-duration: 0.01ms !important; - } - .phase-dot.pulse, - .bar, - .blink, - .enc-fill, - .fill, - .audio-dot.active, - .dot.pulse { - animation: none !important; - transition: none !important; - } -} diff --git a/src/lib/ExportSidebar.svelte b/src/lib/ExportSidebar.svelte index df444a6..d1dea81 100644 --- a/src/lib/ExportSidebar.svelte +++ b/src/lib/ExportSidebar.svelte @@ -1,201 +1,91 @@ -
-
-
- Target size - {targetMB.toFixed(1)} MB + diff --git a/src/lib/GifControls.svelte b/src/lib/GifControls.svelte index 902cc4f..f8dfad2 100644 --- a/src/lib/GifControls.svelte +++ b/src/lib/GifControls.svelte @@ -1,131 +1,22 @@ -
- 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"} -

+

GIF compression

+
Budget priority
+
+
Palette colors{colors}
+
- -
- 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"}

-
- - +
Dithering
diff --git a/src/lib/Main.svelte b/src/lib/Main.svelte index e889478..2131808 100644 --- a/src/lib/Main.svelte +++ b/src/lib/Main.svelte @@ -1,7 +1,7 @@ { phase = "editing" } : undefined} + onCapture={!exportPending && !previewLoading && (phase === "editing" || phase === "review") ? () => { discardDialog = true } : phase === "done" ? doDiscard : undefined} + onEditor={clip && !exportPending && !previewLoading && ["review", "done", "export-error", "export-canceled"].includes(phase) ? () => { phase = "editing" } : undefined} {onSettings} disabled={settingsLocked || sourcePending} /> +
    + {#each workflow as step, index} +
  1. + {#if index > 0}
  2. + {/each} +
-
+
{#if phase === "idle" || phase === "recording" || phase === "paused"}
@@ -772,349 +793,162 @@ {/if}
- {:else if phase === "editing" && clip} -
- -
- -
- {#each (["gif","webm","mp4"] as const) as f} - - {/each} -
- - - - - - - - - {#if format === "gif" && (thumbnails.length > 0 || loadingThumbs)} - - {/if} -
- - - pathOverridden = true} - onBrowse={browseOutput} - onExport={doExport} - onDiscard={confirmDiscard} - /> + {:else if phase === "editing" && clip} +
+
+
+

Trim recording

Choose what to keep, then set up the output.

+ +
+ +
- - - {:else if phase === "exporting"} -
- {#if encodeProgress} -
- {encodeUnit} {encodeProgress.pass}/{encodeProgress.total} - {encodeOverall.toFixed(0)}% + pathOverridden = true} onBrowse={browseOutput} + onReview={reviewOutput} onSave={saveOutput} /> +
+ {:else if phase === "review" && clip} +
+
+
+

Review output

Check the encoded {format.toUpperCase()} before saving.

+ +
+ {#if previewLoading} +
+
{previewCanceling ? "Canceling preview..." : encodeProgress ? "Encoding " + encodeUnit + " " + encodeProgress.pass + "/" + encodeProgress.total : "Preparing output..."}{encodeOverall.toFixed(0)}%
+ +

Encoding the full trimmed segment with your export settings.

-
3}> - {#each Array(encodeProgress.total) as _, i} -
-
-
- {/each} +
+ {:else if outputPreview} + {@const file = outputPreview} + toastOnFail(api.openOutputPreview(file.id))} /> + {:else} +
+ {#if previewFailure} + {:else}

Render the current cuts and export settings to continue.

{/if} +
+
+ {/if} +
+ +
+ {:else if clip} +
+
+ {#if phase === "exporting"} +
+ +

{savingReviewed ? "Saving reviewed file" : exportCanceling ? "Canceling save" : "Saving clip"}

+
+
+ {#if savingReviewed} +

Copying the encoded file you reviewed.

+ {:else} +
{encodeProgress ? "Encoding " + encodeUnit + " " + encodeProgress.pass + "/" + encodeProgress.total : "Preparing clip"}{encodeOverall.toFixed(0)}%
+ +

{exportCanceling ? "Finishing the current operation." : "Compressing the clip to fit your target size."}

+ {/if} +
+ {#if !savingReviewed && !exportCanceling}
{/if} + {:else if phase === "done" && exportResult} +
+ +

{exportResult.met_target ? "File saved" : "Saved over target"}

+

{savingReviewed ? "The reviewed file was saved." : "Your clip is ready to share."}

+
+
Final file size{formatBytes(exportResult.size_bytes)}

{exportResult.met_target ? "Within the " + formatBytes(exportResult.target_bytes) + " target." : "Target size was " + formatBytes(exportResult.target_bytes) + "."}

+
+ + +
{:else} -
Preparing
-
+
+

{phase === "export-canceled" ? "Save canceled" : "Save failed"}

+

Your edits are still available.

+
+ {#if phase === "export-error" && exportFailure}{/if} +
+ + {#if savingReviewed && outputPreview}{/if} + {#if !savingReviewed || outputPreview}{/if} +
{/if} -

ffmpeg is encoding your clip{format === "gif" ? " (retrying to hit target size)" : ""}

-
- - - {:else if phase === "done" && exportResult} -
-
- {#if exportResult.met_target} - - - - {:else} - - - - {/if} +
+
+
Target size
{formatBytes(exportResult?.target_bytes ?? Math.round(targetMB * 1_048_576))}
+
Duration
{(savingReviewed && outputPreview ? outputPreview.duration_secs : trimmedDuration).toFixed(2)} s
+ {#if savingReviewed && outputPreview}
Avg. frame rate
{Number(outputPreview.fps.toFixed(2))} FPS
{/if} +
+
Destination

{exportResult?.output_path || outputPath}

+ +
{/if}
- {#if showDiscardConfirm} -
-
-

Discard this recording?

-
- - -
-
+
+ {phaseLabel} + {#if (phase === "idle" || phase === "recording" || phase === "paused") && config} +
+ {#if config.hotkeys.start}{config.hotkeys.start} Start{/if} + {#if config.hotkeys.stop}{config.hotkeys.stop} Stop{/if} + {#if config.hotkeys.pause}{config.hotkeys.pause} Pause{/if}
{/if} +
+ +{#if discardDialog} + { discardDialog = false; if (accepted) void doDiscard() }} /> +{/if} +{#if overwriteDialog} + { overwriteDialog = false; decideOverwrite?.(accepted); decideOverwrite = undefined }} /> +{/if} {#if errMsg} {/if} - diff --git a/src/lib/Preview.svelte b/src/lib/Preview.svelte index 1b367f2..8635df3 100644 --- a/src/lib/Preview.svelte +++ b/src/lib/Preview.svelte @@ -1,64 +1,121 @@ -{#if trimPreviewState.dragging && trimPreviewState.path} -
- -
original
+
+
+ {label}{dimensions} +
+ {#key path} +
+ + + {#if crop} + + {/if} +
+ {/key} + {#if loadError} + + {/if} +
+ +
+ + + +
+ {timecode(playhead)} / {timecode(trimEnd)}
-{:else if previewPath} -
- - {#if previewLoading}
rendering
{/if} -
-{:else} -
- preview -
-{/if} +
diff --git a/src/lib/ReviewPlayer.svelte b/src/lib/ReviewPlayer.svelte new file mode 100644 index 0000000..22d63a5 --- /dev/null +++ b/src/lib/ReviewPlayer.svelte @@ -0,0 +1,68 @@ + + +
+
+ {#key source} + {#if source === "output" && output.format === "gif"} +
+
Encoded GIF{output.width} × {output.height}
+ {#key replay} + Rendered output GIF gifError = true} /> + {/key} + {#if gifError} + + {:else} +
+ Looping GIF + +
+ {/if} +
+ {:else if source === "output"} + + {:else} + + {/if} + {/key} +
+ + diff --git a/src/lib/TrimPanel.svelte b/src/lib/TrimPanel.svelte index 0a30b8d..527e856 100644 --- a/src/lib/TrimPanel.svelte +++ b/src/lib/TrimPanel.svelte @@ -1,170 +1,195 @@ -
-
- {trimStart.toFixed(2)}s - {trimmedDuration.toFixed(2)}s kept - {trimEnd.toFixed(2)}s + + +
+
+

Trim clip

While dragging a handle, move up or down for finer control.

+
+ Kept {keptDuration.toFixed(2)} s + +
+
+
+ +
+ + + +
pointerDown(event,"seek")} onkeydown={event => key(event,"seek")}>
+ {#each boundaries as edge} + {@const value = edge.key === "start" ? trimStart : trimEnd} +
pointerDown(event,edge.key)} + onpointerenter={() => hovered = edge.key} onpointerleave={() => hovered = null} + onfocus={event => { if (event.currentTarget.matches(":focus-visible")) focused = edge.key }} + onblur={() => focused = null} onkeydown={event => key(event,edge.key)}> +
+ {/each} + +
-
-
-
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() } - }} - >
+
+ {#each boundaries as edge} +
+ + commitTime(event,edge.key)} onkeydown={event => { + if (event.key === "Enter") event.currentTarget.blur() + else if (event.key === "Escape") { event.currentTarget.value = timecode(edge.key === "start" ? trimStart : trimEnd); error = null } + }} /> + +
+ {/each}
- { 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" /> -
+ {#if error}{/if} +
diff --git a/src/lib/api.ts b/src/lib/api.ts index b45f2de..096a8cf 100644 --- a/src/lib/api.ts +++ b/src/lib/api.ts @@ -115,10 +115,10 @@ export type ExportRequest = { target_bytes: number fps: number keep_audio: boolean - deleted_frame_indices: number[] trim_start_secs?: number | null trim_end_secs?: number | null output_path?: string | null + overwrite?: boolean crop?: CaptureRect | null gif_budget_mode?: GifBudgetMode gif_dither?: GifDither @@ -132,6 +132,18 @@ export type ExportResult = { met_target: boolean } +export type OutputPreview = { + id: string + path: string + format: Format + size_bytes: number + target_bytes: number + width: number + height: number + fps: number + duration_secs: number +} + export type HotkeyRegistrationResult = { start_ok: boolean | null stop_ok: boolean | null @@ -197,6 +209,8 @@ export const api = { stopCapture: () => invoke("stop_capture"), discardClip: () => invoke("discard_clip"), export: (request: ExportRequest) => invoke("export", { request }), + exportDestination: (format: Format, path: string) => + invoke<{ path: string; exists: boolean }>("export_destination", { format, path }), revealInExplorer: (path: string) => invoke("reveal_in_explorer", { path }), showOverlay: () => invoke("show_overlay"), openWindowPicker: () => invoke("open_window_picker"), @@ -209,11 +223,13 @@ export const api = { invoke("set_overlay_to_window", { x, y, width, height }), listWindows: () => invoke("list_windows"), getOverlayRect: () => invoke("get_overlay_rect"), - extractThumbnails: (fps: number) => - invoke("extract_thumbnails", { fps }), + timelineThumbnails: () => invoke("timeline_thumbnails"), previewDisplay: (x: number, y: number) => invoke("preview_display", { x, y }), - 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 } }), + renderOutputPreview: (request: ExportRequest) => + invoke("render_output_preview", { request }), + saveOutputPreview: (previewId: string, outputPath: string, overwrite: boolean) => + invoke("save_output_preview", { previewId, outputPath, overwrite }), + openOutputPreview: (previewId: string) => invoke("open_output_preview", { previewId }), estimateGifParams: (input: { format: Format fps: number @@ -237,8 +253,6 @@ export const api = { duration_secs: number }) => invoke("estimate_gif_params_table", { request: input }), - renderRawPreview: (timestamp: number) => - invoke("render_raw_preview", { timestamp }), defaultOutputPath: (format: Format) => invoke("default_output_path", { format }), openUrl: (url: string) => invoke("open_url", { url }), diff --git a/src/lib/trimPreviewState.svelte.ts b/src/lib/trimPreviewState.svelte.ts deleted file mode 100644 index 640819c..0000000 --- a/src/lib/trimPreviewState.svelte.ts +++ /dev/null @@ -1,15 +0,0 @@ -export const trimPreviewState = $state<{ - dragging: "start" | "end" | null - path: string | null - bust: number -}>({ - dragging: null, - path: null, - bust: 0, -}) - -export function resetTrimPreview() { - trimPreviewState.dragging = null - trimPreviewState.path = null - trimPreviewState.bust = 0 -} diff --git a/src/main.ts b/src/main.ts index 2dc7ff1..68e39cc 100644 --- a/src/main.ts +++ b/src/main.ts @@ -1,5 +1,4 @@ import { mount } from "svelte" -import "./app.css" import "./ui.css" import App from "./App.svelte" import { installMotion } from "./lib/ui/motion"