quality pass: safe timestamps, cancel support, dedup, frontend polish

- replace unsafe GetLocalTime with safe SystemTime epoch
- lock() logs warning on mutex poison recovery
- extract try_start_audio/start_click_recorder helpers to dedup capture code
- cancel_export now actually kills ffmpeg via polling loop + cancel flag
- extract visible_window_bounds helper for DWM rect lookups
- clear_temp_segments cleans thumbs dir and preview files
- gif_params takes focused GifBudgetInput instead of full TranscodeRequest
- consistent error messages with full context chain
- reduce overlay clickthrough poll from 30ms to 80ms
- throttle trim preview to 10Hz
- bound thumbnail cache at 5 entries
- timer ticks until stopCapture resolves
- crop fields validate against clip dimensions
- settings shows unsaved indicator dot
- edit grid uses minmax for fluid responsive layout
- animations respect prefers-reduced-motion
- pauseRec only clears timer after successful pause
- refreshPreview logs errors instead of swallowing
- remove dead _deps string from preview effect
This commit is contained in:
2026-05-29 23:38:18 +03:00
parent e9005415c4
commit d57e554ece
5 changed files with 236 additions and 179 deletions
+71 -20
View File
@@ -2,7 +2,9 @@ use std::collections::HashSet;
use std::ffi::{OsStr, OsString}; use std::ffi::{OsStr, OsString};
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use std::process::Command; use std::process::Command;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc::Sender; use std::sync::mpsc::Sender;
use std::sync::Arc;
use std::thread; use std::thread;
use anyhow::{anyhow, bail, Context, Result}; use anyhow::{anyhow, bail, Context, Result};
@@ -50,6 +52,9 @@ pub struct TranscodeRequest {
/// Optional channel to report encoding progress. /// Optional channel to report encoding progress.
#[doc(hidden)] #[doc(hidden)]
pub progress_tx: Option<Sender<EncodeProgress>>, pub progress_tx: Option<Sender<EncodeProgress>>,
/// Optional cancel signal. When set to true, ffmpeg will be killed.
#[doc(hidden)]
pub cancel: Option<Arc<AtomicBool>>,
} }
const MAX_CLICK_HIGHLIGHTS: usize = 50; const MAX_CLICK_HIGHLIGHTS: usize = 50;
@@ -284,7 +289,8 @@ fn two_pass_video(
let tx = req.progress_tx.clone(); let tx = req.progress_tx.clone();
let dur = req.duration_secs; let dur = req.duration_secs;
let fps = req.fps; let fps = req.fps;
run_with_progress(&mut pass1, "pass 1", 1, 2, dur, fps, tx.as_ref())?; let cancel = req.cancel.clone();
run_with_progress(&mut pass1, "pass 1", 1, 2, dur, fps, tx.as_ref(), cancel.as_ref())?;
// Send 50% to signal pass 1 done, pass 2 starting. // Send 50% to signal pass 1 done, pass 2 starting.
if let Some(ref t) = tx { if let Some(ref t) = tx {
@@ -314,7 +320,7 @@ fn two_pass_video(
pass2.arg("-an"); pass2.arg("-an");
} }
pass2.arg(&req.output); pass2.arg(&req.output);
run_with_progress(&mut pass2, "pass 2", 2, 2, dur, fps, tx.as_ref())?; run_with_progress(&mut pass2, "pass 2", 2, 2, dur, fps, tx.as_ref(), cancel.as_ref())?;
cleanup_pass_logs(&log_stem); cleanup_pass_logs(&log_stem);
Ok(()) Ok(())
@@ -342,7 +348,14 @@ fn cleanup_pass_logs(stem: &Path) {
} }
fn encode_gif(ffmpeg: &Path, req: &TranscodeRequest) -> Result<()> { fn encode_gif(ffmpeg: &Path, req: &TranscodeRequest) -> Result<()> {
let (mut scale_width, mut effective_fps) = gif_params(req, req.clip_width, req.clip_height); let budget_input = GifBudgetInput {
gif_colors: req.gif_colors,
target_bytes: req.target_bytes,
fps: req.fps,
duration_secs: req.duration_secs,
gif_budget_mode: req.gif_budget_mode.clone(),
};
let (mut scale_width, mut effective_fps) = gif_params(&budget_input, req.clip_width, req.clip_height);
let target = req.target_bytes; let target = req.target_bytes;
let max_retries = 6; let max_retries = 6;
@@ -473,25 +486,35 @@ fn encode_gif_pass(
req.duration_secs, req.duration_secs,
effective_fps, effective_fps,
req.progress_tx.as_ref(), req.progress_tx.as_ref(),
req.cancel.as_ref(),
)?; )?;
Ok(()) Ok(())
} }
pub fn gif_params(req: &TranscodeRequest, clip_width: u32, clip_height: u32) -> (u32, u32) { #[derive(Debug, Clone)]
pub struct GifBudgetInput {
pub gif_colors: u16,
pub target_bytes: u64,
pub fps: u32,
pub duration_secs: f64,
pub gif_budget_mode: GifBudgetMode,
}
pub fn gif_params(input: &GifBudgetInput, clip_width: u32, clip_height: u32) -> (u32, u32) {
let aspect = if clip_height > 0 { clip_width as f64 / clip_height as f64 } else { 16.0 / 9.0 }; let aspect = if clip_height > 0 { clip_width as f64 / clip_height as f64 } else { 16.0 / 9.0 };
// GIF LZW compression on typical screen content averages ~0.2 bytes/pixel at 256 colors. // GIF LZW compression on typical screen content averages ~0.2 bytes/pixel at 256 colors.
// Real compression varies 3-5x depending on content (solid colors compress much better // Real compression varies 3-5x depending on content (solid colors compress much better
// than gradients/noise). The retry loop in encode_gif handles correction on mismatch. // than gradients/noise). The retry loop in encode_gif handles correction on mismatch.
// Fewer colors = better compression. Adjust proportionally. // Fewer colors = better compression. Adjust proportionally.
// 256 colors = 1.0x, 128 = ~0.85x, 64 = ~0.7x, 32 = ~0.55x, 16 = ~0.4x, 2 = ~0.2x // 256 colors = 1.0x, 128 = ~0.85x, 64 = ~0.7x, 32 = ~0.55x, 16 = ~0.4x, 2 = ~0.2x
let color_factor = (req.gif_colors as f64 / 256.0).sqrt().clamp(0.15, 1.0); let color_factor = (input.gif_colors as f64 / 256.0).sqrt().clamp(0.15, 1.0);
let bytes_per_pixel_per_frame = 0.2 * color_factor; let bytes_per_pixel_per_frame = 0.2 * color_factor;
let target_bytes = req.target_bytes as f64; let target_bytes = input.target_bytes as f64;
let requested_fps = req.fps as f64; let requested_fps = input.fps as f64;
let duration = req.duration_secs; let duration = input.duration_secs;
match req.gif_budget_mode { match input.gif_budget_mode {
GifBudgetMode::Resolution => { GifBudgetMode::Resolution => {
let max_w = (clip_width.min(1280) as f64).clamp(120.0, 1280.0); let max_w = (clip_width.min(1280) as f64).clamp(120.0, 1280.0);
let w = (max_w / 2.0).round() as u32 * 2; let w = (max_w / 2.0).round() as u32 * 2;
@@ -500,7 +523,7 @@ pub fn gif_params(req: &TranscodeRequest, clip_width: u32, clip_height: u32) ->
let bytes_per_frame = pixels_per_frame * bytes_per_pixel_per_frame; let bytes_per_frame = pixels_per_frame * bytes_per_pixel_per_frame;
let max_frames = (target_bytes / bytes_per_frame).floor().max(1.0); let max_frames = (target_bytes / bytes_per_frame).floor().max(1.0);
let min_fps = (max_frames / duration).max(1.0).round() as u32; let min_fps = (max_frames / duration).max(1.0).round() as u32;
let fps = (req.fps).min(min_fps).max(1); let fps = (input.fps).min(min_fps).max(1);
(w, fps) (w, fps)
} }
GifBudgetMode::Framerate => { GifBudgetMode::Framerate => {
@@ -508,7 +531,7 @@ pub fn gif_params(req: &TranscodeRequest, clip_width: u32, clip_height: u32) ->
let budget = target_bytes / (frames * bytes_per_pixel_per_frame); let budget = target_bytes / (frames * bytes_per_pixel_per_frame);
let w = (budget * aspect).sqrt(); let w = (budget * aspect).sqrt();
let w = (w.clamp(120.0, 1280.0).round() as u32 / 2) * 2; let w = (w.clamp(120.0, 1280.0).round() as u32 / 2) * 2;
(w, req.fps) (w, input.fps)
} }
GifBudgetMode::Balanced => { GifBudgetMode::Balanced => {
let frames_at_full = (requested_fps * duration).max(1.0); let frames_at_full = (requested_fps * duration).max(1.0);
@@ -523,7 +546,7 @@ pub fn gif_params(req: &TranscodeRequest, clip_width: u32, clip_height: u32) ->
let scale = scale.max(0.1); let scale = scale.max(0.1);
let w = ((clip_width as f64 * scale).round() as u32 / 2).max(60) * 2; let w = ((clip_width as f64 * scale).round() as u32 / 2).max(60) * 2;
let fps = ((requested_fps * scale).round() as u32).max(1).min(req.fps); let fps = ((requested_fps * scale).round() as u32).max(1).min(input.fps);
(w, fps) (w, fps)
} }
} }
@@ -749,7 +772,7 @@ pub fn concat_segments(ffmpeg: &Path, segments: &[PathBuf], output: &Path) -> Re
} }
fn run(cmd: &mut Command, label: &str) -> Result<()> { fn run(cmd: &mut Command, label: &str) -> Result<()> {
let output = run_impl(cmd, label, 0, 0, 0.0, 0, None)?; let output = run_impl(cmd, label, 0, 0, 0.0, 0, None, None)?;
if !output.status.success() { if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr); let stderr = String::from_utf8_lossy(&output.stderr);
let head: String = stderr.lines().take(12).collect::<Vec<_>>().join("\n"); let head: String = stderr.lines().take(12).collect::<Vec<_>>().join("\n");
@@ -768,8 +791,9 @@ fn run_with_progress(
duration_secs: f64, duration_secs: f64,
fps: u32, fps: u32,
progress_tx: Option<&Sender<EncodeProgress>>, progress_tx: Option<&Sender<EncodeProgress>>,
cancel: Option<&Arc<AtomicBool>>,
) -> Result<()> { ) -> Result<()> {
let output = run_impl(cmd, label, pass, total_passes, duration_secs, fps, progress_tx.cloned())?; let output = run_impl(cmd, label, pass, total_passes, duration_secs, fps, progress_tx.cloned(), cancel.cloned())?;
if !output.status.success() { if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr); let stderr = String::from_utf8_lossy(&output.stderr);
let head: String = stderr.lines().take(12).collect::<Vec<_>>().join("\n"); let head: String = stderr.lines().take(12).collect::<Vec<_>>().join("\n");
@@ -786,6 +810,7 @@ fn run_impl(
progress_duration_secs: f64, progress_duration_secs: f64,
progress_fps: u32, progress_fps: u32,
progress_tx: Option<Sender<EncodeProgress>>, progress_tx: Option<Sender<EncodeProgress>>,
cancel: Option<Arc<AtomicBool>>,
) -> Result<std::process::Output> { ) -> Result<std::process::Output> {
use std::process::Stdio; use std::process::Stdio;
@@ -804,12 +829,10 @@ fn run_impl(
.spawn() .spawn()
.with_context(|| format!("spawning ffmpeg for {label}"))?; .with_context(|| format!("spawning ffmpeg for {label}"))?;
// Spawn a thread to monitor stderr and emit progress.
let stderr = child.stderr.take(); let stderr = child.stderr.take();
let tx = progress_tx.clone(); let tx = progress_tx.clone();
let handle = stderr.map(move |serr| { let mut stderr_handle: Option<thread::JoinHandle<Vec<u8>>> = stderr.map(move |serr| {
// Clone the Sender if present.
let tx = tx.as_ref().map(|t| t.clone()); let tx = tx.as_ref().map(|t| t.clone());
let encode_dur = progress_duration_secs; let encode_dur = progress_duration_secs;
let fps = progress_fps; let fps = progress_fps;
@@ -817,8 +840,11 @@ fn run_impl(
let total_passes = progress_total_passes; let total_passes = progress_total_passes;
thread::spawn(move || { thread::spawn(move || {
use std::io::{BufRead, BufReader}; use std::io::{BufRead, BufReader};
let mut collected = Vec::new();
let reader = BufReader::new(serr); let reader = BufReader::new(serr);
for line in reader.lines().map_while(Result::ok) { for line in reader.lines().map_while(Result::ok) {
collected.extend_from_slice(line.as_bytes());
collected.push(b'\n');
if let Some(frame) = parse_frame_from_stderr(&line) { if let Some(frame) = parse_frame_from_stderr(&line) {
let total = (encode_dur * fps as f64).max(1.0); let total = (encode_dur * fps as f64).max(1.0);
let percent = (frame / total * 100.0).min(100.0); let percent = (frame / total * 100.0).min(100.0);
@@ -831,14 +857,38 @@ fn run_impl(
} }
} }
} }
collected
}) })
}); });
let output = child.wait_with_output().context("waiting for ffmpeg")?; loop {
if let Some(h) = handle { if let Some(ref c) = cancel {
if c.load(Ordering::Relaxed) {
let _ = child.kill();
let _ = child.wait();
if let Some(h) = stderr_handle.take() {
let _ = h.join(); let _ = h.join();
} }
Ok(output) bail!("export cancelled");
}
}
match child.try_wait() {
Ok(Some(status)) => {
let stderr_bytes = stderr_handle.take()
.and_then(|h| h.join().ok())
.unwrap_or_default();
return Ok(std::process::Output {
status,
stdout: Vec::new(),
stderr: stderr_bytes,
});
}
Ok(None) => {
std::thread::sleep(std::time::Duration::from_millis(50));
}
Err(e) => bail!("waiting for ffmpeg: {e}"),
}
}
} }
/// Parse a frame count from an ffmpeg stderr progress line. /// Parse a frame count from an ffmpeg stderr progress line.
@@ -884,6 +934,7 @@ mod tests {
clip_width: 1920, clip_width: 1920,
clip_height: 1080, clip_height: 1080,
progress_tx: None, progress_tx: None,
cancel: None,
} }
} }
+114 -142
View File
@@ -19,10 +19,13 @@ use tauri_plugin_global_shortcut::{GlobalShortcutExt, Shortcut, ShortcutState};
use std::str::FromStr; use std::str::FromStr;
use crate::bootstrap::FfmpegStatus; use crate::bootstrap::FfmpegStatus;
use crate::config::{Config, Format, GifBudgetMode, GifDither, Mp4Codec, WebmCodec}; use crate::config::{Config, Format, GifBudgetMode, GifDither};
fn lock<T>(m: &std::sync::Mutex<T>) -> std::sync::MutexGuard<'_, T> { fn lock<T>(m: &std::sync::Mutex<T>) -> std::sync::MutexGuard<'_, T> {
m.lock().unwrap_or_else(|e| e.into_inner()) m.lock().unwrap_or_else(|e| {
tracing::warn!("mutex poisoned, recovering");
e.into_inner()
})
} }
#[derive(Debug, Clone, Copy, Serialize, Deserialize)] #[derive(Debug, Clone, Copy, Serialize, Deserialize)]
@@ -95,17 +98,11 @@ fn output_dir(app_dir: &Path, cfg: &Config) -> PathBuf {
} }
fn timestamp_slug() -> String { fn timestamp_slug() -> String {
use windows::Win32::System::SystemInformation::GetLocalTime; std::time::SystemTime::now()
let st = unsafe { GetLocalTime() }; .duration_since(std::time::UNIX_EPOCH)
format!( .unwrap_or_default()
"{:04}{:02}{:02}-{:02}{:02}{:02}", .as_secs()
st.wYear, .to_string()
st.wMonth,
st.wDay,
st.wHour,
st.wMinute,
st.wSecond
)
} }
fn ext_for(format: Format) -> &'static str { fn ext_for(format: Format) -> &'static str {
@@ -239,7 +236,7 @@ fn apply_update(app: AppHandle, state: State<'_, AppState>) -> Result<(), String
.args(["/c", "start", "", ""]) .args(["/c", "start", "", ""])
.raw_arg(format!("\"{}\"", bat.to_string_lossy())) .raw_arg(format!("\"{}\"", bat.to_string_lossy()))
.spawn() .spawn()
.map_err(|e| format!("spawning apply script: {e}"))?; .map_err(|e| format!("spawning apply script: {e:#}"))?;
app.exit(0); app.exit(0);
Ok(()) Ok(())
} }
@@ -293,6 +290,12 @@ fn clear_temp_segments(app_dir: &Path) {
let _ = std::fs::remove_file(temp.join("recording.mp4")); let _ = std::fs::remove_file(temp.join("recording.mp4"));
let _ = std::fs::remove_file(temp.join("video-concat.mp4")); let _ = std::fs::remove_file(temp.join("video-concat.mp4"));
let _ = std::fs::remove_file(temp.join("audio-concat.pcm")); let _ = std::fs::remove_file(temp.join("audio-concat.pcm"));
let thumbs = temp.join("thumbs");
if thumbs.is_dir() {
let _ = std::fs::remove_dir_all(&thumbs);
}
let _ = std::fs::remove_file(temp.join("preview.png"));
let _ = std::fs::remove_file(temp.join("raw-preview.png"));
} }
/// Pad or trim a raw f32le PCM file so its duration matches `target_secs`. /// Pad or trim a raw f32le PCM file so its duration matches `target_secs`.
@@ -326,6 +329,32 @@ fn set_overlay_clickthrough(app: &AppHandle, enabled: bool) {
} }
} }
fn try_start_audio(
app: &AppHandle,
enabled: bool,
audio_path: PathBuf,
) -> Option<audio::AudioSession> {
if !enabled {
return None;
}
match audio::start(audio_path) {
Ok(s) => Some(s),
Err(e) => {
tracing::warn!("audio capture failed: {e:#}");
let _ = app.emit("audio-failed", e.to_string());
None
}
}
}
fn start_click_recorder(enabled: bool) -> Option<clicks::ClickRecorder> {
if enabled {
Some(clicks::start())
} else {
None
}
}
#[tauri::command] #[tauri::command]
fn start_capture( fn start_capture(
app: AppHandle, app: AppHandle,
@@ -340,7 +369,7 @@ fn start_capture(
} }
let cfg = lock(&state.config).clone(); let cfg = lock(&state.config).clone();
let temp = temp_dir(&state.app_dir); let temp = temp_dir(&state.app_dir);
std::fs::create_dir_all(&temp).map_err(|e| format!("creating temp dir: {e}"))?; std::fs::create_dir_all(&temp).map_err(|e| format!("creating temp dir: {e:#}"))?;
clear_temp_segments(&state.app_dir); clear_temp_segments(&state.app_dir);
let crop = request.as_ref().and_then(|r| r.crop); let crop = request.as_ref().and_then(|r| r.crop);
@@ -367,19 +396,8 @@ fn start_capture(
set_overlay_clickthrough(&app, true); set_overlay_clickthrough(&app, true);
let audio_session = if cfg.capture.capture_audio {
let audio_path = audio_segment_path(&state.app_dir, 1); let audio_path = audio_segment_path(&state.app_dir, 1);
match audio::start(audio_path) { let audio_session = try_start_audio(&app, cfg.capture.capture_audio, audio_path);
Ok(s) => Some(s),
Err(e) => {
tracing::warn!("audio capture failed to start: {e:#}");
let _ = app.emit("audio-failed", e.to_string());
None
}
}
} else {
None
};
let (a_sr, a_ch) = audio_session let (a_sr, a_ch) = audio_session
.as_ref() .as_ref()
@@ -403,11 +421,7 @@ fn start_capture(
segment_start_offsets: vec![0.0], segment_start_offsets: vec![0.0],
}; };
let click_rec = if cfg.capture.capture_cursor { let click_rec = start_click_recorder(cfg.capture.capture_cursor);
Some(clicks::start())
} else {
None
};
*lock(&state.session) = Some(session_state); *lock(&state.session) = Some(session_state);
*lock(&state.capture) = Some(session); *lock(&state.capture) = Some(session);
@@ -483,25 +497,9 @@ fn resume_capture(app: AppHandle, state: State<'_, AppState>) -> Result<(), Stri
let session = capture::start(output, ffmpeg, capture_cursor, audio, crop, fps) let session = capture::start(output, ffmpeg, capture_cursor, audio, crop, fps)
.map_err(|e| format!("{e:#}"))?; .map_err(|e| format!("{e:#}"))?;
let audio_session = if audio {
let audio_path = audio_segment_path(&state.app_dir, next_idx); let audio_path = audio_segment_path(&state.app_dir, next_idx);
match audio::start(audio_path) { let audio_session = try_start_audio(&app, audio, audio_path);
Ok(s) => Some(s), let click_rec = start_click_recorder(capture_cursor);
Err(e) => {
tracing::warn!("audio resume failed: {e:#}");
let _ = app.emit("audio-failed", e.to_string());
None
}
}
} else {
None
};
let click_rec = if capture_cursor {
Some(clicks::start())
} else {
None
};
*lock(&state.capture) = Some(session); *lock(&state.capture) = Some(session);
*lock(&state.audio) = audio_session; *lock(&state.audio) = audio_session;
@@ -604,7 +602,7 @@ fn stop_capture(app: AppHandle, state: State<'_, AppState>) -> Result<RecordedCl
} else if video_concat != final_path { } else if video_concat != final_path {
std::fs::rename(&video_concat, &final_path) std::fs::rename(&video_concat, &final_path)
.or_else(|_| std::fs::copy(&video_concat, &final_path).map(|_| ())) .or_else(|_| std::fs::copy(&video_concat, &final_path).map(|_| ()))
.map_err(|e| format!("finalizing: {e}"))?; .map_err(|e| format!("finalizing: {e:#}"))?;
let _ = std::fs::remove_file(&video_concat); let _ = std::fs::remove_file(&video_concat);
} }
@@ -686,30 +684,14 @@ fn render_preview(
} }
let target_width: u32 = if request.format == Format::Gif { let target_width: u32 = if request.format == Format::Gif {
let req = encode::TranscodeRequest { let budget = encode::GifBudgetInput {
input: clip.temp_path.clone(),
output: PathBuf::new(),
format: request.format,
target_bytes: request.target_bytes,
duration_secs: clip.duration_secs,
fps: request.fps,
keep_audio: false,
gif_dither: GifDither::FloydSteinberg,
gif_colors: request.gif_colors.unwrap_or(256), gif_colors: request.gif_colors.unwrap_or(256),
webm_codec: WebmCodec::Vp9, target_bytes: request.target_bytes,
mp4_codec: Mp4Codec::H264, fps: request.fps,
scratch_dir: PathBuf::new(), duration_secs: clip.duration_secs,
crop: None,
gif_budget_mode: request.gif_budget_mode, gif_budget_mode: request.gif_budget_mode,
deleted_frame_indices: vec![],
trim_start_secs: None,
trim_end_secs: None,
clicks: vec![],
clip_width: clip.width,
clip_height: clip.height,
progress_tx: None,
}; };
let (w, _) = encode::gif_params(&req, clip.width, clip.height); let (w, _) = encode::gif_params(&budget, clip.width, clip.height);
w w
} else { } else {
clip.width.min(1280).max(160) clip.width.min(1280).max(160)
@@ -781,15 +763,14 @@ const OVERLAY_TITLEBAR_LOGICAL_PX: f64 = 24.0;
fn start_overlay_clickthrough_poll(app: AppHandle, shutdown: Arc<AtomicBool>) { fn start_overlay_clickthrough_poll(app: AppHandle, shutdown: Arc<AtomicBool>) {
use std::time::Duration; use std::time::Duration;
use windows::Win32::Foundation::{HWND, POINT, RECT}; use windows::Win32::Foundation::{HWND, POINT};
use windows::Win32::Graphics::Dwm::{DwmGetWindowAttribute, DWMWA_EXTENDED_FRAME_BOUNDS};
use windows::Win32::UI::HiDpi::GetDpiForWindow; use windows::Win32::UI::HiDpi::GetDpiForWindow;
use windows::Win32::UI::WindowsAndMessaging::{GetCursorPos, GetWindowRect}; use windows::Win32::UI::WindowsAndMessaging::GetCursorPos;
std::thread::spawn(move || { std::thread::spawn(move || {
let mut last_inner: Option<bool> = None; let mut last_inner: Option<bool> = None;
while !shutdown.load(Ordering::Relaxed) { while !shutdown.load(Ordering::Relaxed) {
std::thread::sleep(Duration::from_millis(30)); std::thread::sleep(Duration::from_millis(80));
let overlay = match app.get_webview_window("overlay") { let overlay = match app.get_webview_window("overlay") {
Some(w) => w, Some(w) => w,
@@ -815,38 +796,21 @@ fn start_overlay_clickthrough_poll(app: AppHandle, shutdown: Arc<AtomicBool>) {
Ok(h) => h, Ok(h) => h,
Err(_) => continue, Err(_) => continue,
}; };
let hwnd = HWND(raw.0 as *mut _);
let mut dwm = RECT::default(); let (vl, vt, vr, vb) = match visible_window_bounds(raw.0 as isize) {
let dwm_ok = unsafe { Some(b) => b,
DwmGetWindowAttribute( None => continue,
hwnd,
DWMWA_EXTENDED_FRAME_BOUNDS,
&mut dwm as *mut RECT as *mut std::ffi::c_void,
std::mem::size_of::<RECT>() as u32,
)
}
.is_ok()
&& dwm.right > dwm.left;
let visible = if dwm_ok {
dwm
} else {
let mut outer = RECT::default();
if unsafe { GetWindowRect(hwnd, &mut outer) }.is_err() {
continue;
}
outer
}; };
let dpi = unsafe { GetDpiForWindow(hwnd) }; let dpi = unsafe { GetDpiForWindow(HWND(raw.0 as *mut _)) };
let scale = if dpi > 0 { dpi as f64 / 96.0 } else { 1.0 }; let scale = if dpi > 0 { dpi as f64 / 96.0 } else { 1.0 };
let border = (OVERLAY_BORDER_LOGICAL_PX * scale).round() as i32; let border = (OVERLAY_BORDER_LOGICAL_PX * scale).round() as i32;
let titlebar = (OVERLAY_TITLEBAR_LOGICAL_PX * scale).round() as i32; let titlebar = (OVERLAY_TITLEBAR_LOGICAL_PX * scale).round() as i32;
let inner_left = visible.left + border; let inner_left = vl + border;
let inner_top = visible.top + border + titlebar; let inner_top = vt + border + titlebar;
let inner_right = visible.right - border; let inner_right = vr - border;
let inner_bottom = visible.bottom - border; let inner_bottom = vb - border;
let in_inner = pt.x >= inner_left let in_inner = pt.x >= inner_left
&& pt.x < inner_right && pt.x < inner_right
@@ -880,7 +844,7 @@ fn show_overlay(app: AppHandle) -> Result<(), String> {
let win = app let win = app
.get_webview_window("overlay") .get_webview_window("overlay")
.ok_or_else(|| "overlay window not found".to_string())?; .ok_or_else(|| "overlay window not found".to_string())?;
win.show().map_err(|e| e.to_string())?; win.show().map_err(|e| format!("showing overlay: {e:#}"))?;
let _ = mark_overlay_excluded_from_capture(&win); let _ = mark_overlay_excluded_from_capture(&win);
// If the overlay is off-screen (monitor disconnected), center on primary // If the overlay is off-screen (monitor disconnected), center on primary
@@ -915,7 +879,7 @@ fn show_overlay(app: AppHandle) -> Result<(), String> {
} }
} }
} }
win.set_focus().map_err(|e| e.to_string()) win.set_focus().map_err(|e| format!("setting focus: {e:#}"))
} }
#[tauri::command] #[tauri::command]
@@ -923,7 +887,7 @@ fn hide_overlay(app: AppHandle) -> Result<(), String> {
let win = app let win = app
.get_webview_window("overlay") .get_webview_window("overlay")
.ok_or_else(|| "overlay window not found".to_string())?; .ok_or_else(|| "overlay window not found".to_string())?;
win.hide().map_err(|e| e.to_string()) win.hide().map_err(|e| format!("hiding overlay: {e:#}"))
} }
#[tauri::command] #[tauri::command]
@@ -940,7 +904,7 @@ fn set_overlay_size(app: AppHandle, state: State<'_, AppState>, width: u32, heig
let final_w = w + (OVERLAY_BORDER_LOGICAL_PX * 2.0); let final_w = w + (OVERLAY_BORDER_LOGICAL_PX * 2.0);
let final_h = h + OVERLAY_TITLEBAR_LOGICAL_PX + (OVERLAY_BORDER_LOGICAL_PX * 2.0); let final_h = h + OVERLAY_TITLEBAR_LOGICAL_PX + (OVERLAY_BORDER_LOGICAL_PX * 2.0);
win.set_size(Size::Logical(LogicalSize::new(final_w, final_h))) win.set_size(Size::Logical(LogicalSize::new(final_w, final_h)))
.map_err(|e| e.to_string())?; .map_err(|e| format!("setting overlay size: {e:#}"))?;
Ok(()) Ok(())
} }
@@ -953,7 +917,7 @@ fn set_overlay_aspect(app: AppHandle, state: State<'_, AppState>, ratio: Option<
.get_webview_window("overlay") .get_webview_window("overlay")
.ok_or_else(|| "overlay window not found".to_string())?; .ok_or_else(|| "overlay window not found".to_string())?;
let scale = win.scale_factor().unwrap_or(1.0); let scale = win.scale_factor().unwrap_or(1.0);
let sz = win.inner_size().map_err(|e| e.to_string())?; let sz = win.inner_size().map_err(|e| format!("getting window size: {e:#}"))?;
let cur_w = sz.width as f64 / scale; let cur_w = sz.width as f64 / scale;
let cur_h = sz.height as f64 / scale; let cur_h = sz.height as f64 / scale;
let target_h = cur_w / r; let target_h = cur_w / r;
@@ -962,7 +926,7 @@ fn set_overlay_aspect(app: AppHandle, state: State<'_, AppState>, ratio: Option<
let final_w = cur_w + (OVERLAY_BORDER_LOGICAL_PX * 2.0); let final_w = cur_w + (OVERLAY_BORDER_LOGICAL_PX * 2.0);
let final_h = target_h + OVERLAY_TITLEBAR_LOGICAL_PX + (OVERLAY_BORDER_LOGICAL_PX * 2.0); let final_h = target_h + OVERLAY_TITLEBAR_LOGICAL_PX + (OVERLAY_BORDER_LOGICAL_PX * 2.0);
win.set_size(Size::Logical(LogicalSize::new(final_w, final_h))) win.set_size(Size::Logical(LogicalSize::new(final_w, final_h)))
.map_err(|e| e.to_string())?; .map_err(|e| format!("setting overlay size: {e:#}"))?;
} }
} }
Ok(()) Ok(())
@@ -983,7 +947,7 @@ fn enforce_overlay_aspect(app: AppHandle, state: State<'_, AppState>) -> Result<
.get_webview_window("overlay") .get_webview_window("overlay")
.ok_or_else(|| "overlay window not found".to_string())?; .ok_or_else(|| "overlay window not found".to_string())?;
let scale = win.scale_factor().unwrap_or(1.0); let scale = win.scale_factor().unwrap_or(1.0);
let sz = win.inner_size().map_err(|e| e.to_string())?; let sz = win.inner_size().map_err(|e| format!("getting window size: {e:#}"))?;
let cur_w = sz.width as f64 / scale; let cur_w = sz.width as f64 / scale;
let cur_h = sz.height as f64 / scale; let cur_h = sz.height as f64 / scale;
let target_h = (cur_w / ratio).round(); let target_h = (cur_w / ratio).round();
@@ -1041,13 +1005,13 @@ fn open_window_picker(
use tauri::{PhysicalPosition, PhysicalSize, Position, Size}; use tauri::{PhysicalPosition, PhysicalSize, Position, Size};
picker picker
.set_size(Size::Physical(PhysicalSize::new(mw, mh))) .set_size(Size::Physical(PhysicalSize::new(mw, mh)))
.map_err(|e| e.to_string())?; .map_err(|e| format!("setting picker size: {e:#}"))?;
picker picker
.set_position(Position::Physical(PhysicalPosition::new(0, 0))) .set_position(Position::Physical(PhysicalPosition::new(0, 0)))
.map_err(|e| e.to_string())?; .map_err(|e| format!("setting picker position: {e:#}"))?;
let _ = picker.set_ignore_cursor_events(false); let _ = picker.set_ignore_cursor_events(false);
let _ = picker.set_always_on_top(true); let _ = picker.set_always_on_top(true);
picker.show().map_err(|e| e.to_string())?; picker.show().map_err(|e| format!("showing picker: {e:#}"))?;
if let Ok(h) = picker.hwnd() { if let Ok(h) = picker.hwnd() {
use windows::Win32::Foundation::{HWND, RECT}; use windows::Win32::Foundation::{HWND, RECT};
use windows::Win32::Graphics::Dwm::{DwmGetWindowAttribute, DWMWA_EXTENDED_FRAME_BOUNDS}; use windows::Win32::Graphics::Dwm::{DwmGetWindowAttribute, DWMWA_EXTENDED_FRAME_BOUNDS};
@@ -1095,6 +1059,34 @@ fn close_window_picker(
Ok(()) Ok(())
} }
fn visible_window_bounds(hwnd_raw: isize) -> Option<(i32, i32, i32, i32)> {
use windows::Win32::Foundation::{HWND, RECT};
use windows::Win32::Graphics::Dwm::{DwmGetWindowAttribute, DWMWA_EXTENDED_FRAME_BOUNDS};
use windows::Win32::UI::WindowsAndMessaging::GetWindowRect;
let hwnd = HWND(hwnd_raw as *mut _);
let mut dwm = RECT::default();
if unsafe {
DwmGetWindowAttribute(
hwnd,
DWMWA_EXTENDED_FRAME_BOUNDS,
&mut dwm as *mut RECT as *mut std::ffi::c_void,
std::mem::size_of::<RECT>() as u32,
)
}
.is_ok()
&& dwm.right > dwm.left
&& dwm.bottom > dwm.top
{
return Some((dwm.left, dwm.top, dwm.right, dwm.bottom));
}
let mut outer = RECT::default();
if unsafe { GetWindowRect(hwnd, &mut outer) }.is_ok() {
Some((outer.left, outer.top, outer.right, outer.bottom))
} else {
None
}
}
fn dwm_insets(hwnd_raw: isize) -> (i32, i32, i32, i32) { fn dwm_insets(hwnd_raw: isize) -> (i32, i32, i32, i32) {
use windows::Win32::Foundation::{HWND, RECT}; use windows::Win32::Foundation::{HWND, RECT};
use windows::Win32::Graphics::Dwm::{DwmGetWindowAttribute, DWMWA_EXTENDED_FRAME_BOUNDS}; use windows::Win32::Graphics::Dwm::{DwmGetWindowAttribute, DWMWA_EXTENDED_FRAME_BOUNDS};
@@ -1218,35 +1210,14 @@ fn set_overlay_to_window(
#[tauri::command] #[tauri::command]
fn get_overlay_rect(app: AppHandle) -> Result<CaptureRect, String> { fn get_overlay_rect(app: AppHandle) -> Result<CaptureRect, String> {
use windows::Win32::Foundation::{HWND, RECT};
use windows::Win32::Graphics::Dwm::{DwmGetWindowAttribute, DWMWA_EXTENDED_FRAME_BOUNDS};
use windows::Win32::UI::WindowsAndMessaging::GetWindowRect;
let win = app let win = app
.get_webview_window("overlay") .get_webview_window("overlay")
.ok_or_else(|| "overlay window not found".to_string())?; .ok_or_else(|| "overlay window not found".to_string())?;
let scale = win.scale_factor().map_err(|e| e.to_string())?; let scale = win.scale_factor().map_err(|e| format!("getting scale factor: {e:#}"))?;
let raw = win.hwnd().map_err(|e| format!("hwnd: {e}"))?; let raw = win.hwnd().map_err(|e| format!("hwnd: {e}"))?;
let hwnd = HWND(raw.0 as *mut _);
let mut dwm = RECT::default(); let (vl, vt, vr, vb) = visible_window_bounds(raw.0 as isize)
let dwm_ok = unsafe { .ok_or_else(|| "GetWindowRect failed".to_string())?;
DwmGetWindowAttribute(
hwnd,
DWMWA_EXTENDED_FRAME_BOUNDS,
&mut dwm as *mut RECT as *mut std::ffi::c_void,
std::mem::size_of::<RECT>() as u32,
)
}
.is_ok();
let visible = if dwm_ok && dwm.right > dwm.left && dwm.bottom > dwm.top {
dwm
} else {
let mut r = RECT::default();
unsafe { GetWindowRect(hwnd, &mut r) }
.map_err(|e| format!("GetWindowRect: {e}"))?;
r
};
let border_phys = (OVERLAY_BORDER_LOGICAL_PX * scale).round() as i32; let border_phys = (OVERLAY_BORDER_LOGICAL_PX * scale).round() as i32;
let titlebar_phys = (OVERLAY_TITLEBAR_LOGICAL_PX * scale).round() as i32; let titlebar_phys = (OVERLAY_TITLEBAR_LOGICAL_PX * scale).round() as i32;
@@ -1254,8 +1225,8 @@ fn get_overlay_rect(app: AppHandle) -> Result<CaptureRect, String> {
let inset_top = border_phys + titlebar_phys; let inset_top = border_phys + titlebar_phys;
let inset_sides = border_phys; let inset_sides = border_phys;
let visible_w = visible.right - visible.left; let visible_w = vr - vl;
let visible_h = visible.bottom - visible.top; let visible_h = vb - vt;
let width = (visible_w - inset_sides * 2).max(2) as u32; let width = (visible_w - inset_sides * 2).max(2) as u32;
let height = (visible_h - inset_top - inset_sides).max(2) as u32; let height = (visible_h - inset_top - inset_sides).max(2) as u32;
@@ -1263,8 +1234,8 @@ fn get_overlay_rect(app: AppHandle) -> Result<CaptureRect, String> {
let height = (height / 2) * 2; let height = (height / 2) * 2;
Ok(CaptureRect { Ok(CaptureRect {
x: visible.left + inset_sides, x: vl + inset_sides,
y: visible.top + inset_top, y: vt + inset_top,
width, width,
height, height,
}) })
@@ -1296,7 +1267,7 @@ fn reveal_in_explorer(path: String) -> Result<(), String> {
Command::new("explorer.exe") Command::new("explorer.exe")
.arg(parent) .arg(parent)
.spawn() .spawn()
.map_err(|e| format!("opening explorer: {e}"))?; .map_err(|e| format!("opening explorer: {e:#}"))?;
} }
Ok(()) Ok(())
} }
@@ -1310,7 +1281,7 @@ fn open_url(url: String) -> Result<(), String> {
std::process::Command::new("cmd") std::process::Command::new("cmd")
.raw_arg(format!("/C start \"\" \"{url}\"")) .raw_arg(format!("/C start \"\" \"{url}\""))
.spawn() .spawn()
.map_err(|e| format!("opening url: {e}"))?; .map_err(|e| format!("opening url: {e:#}"))?;
Ok(()) Ok(())
} }
@@ -1344,7 +1315,7 @@ fn export(app: AppHandle, state: State<'_, AppState>, request: ExportRequest) ->
}; };
if let Some(parent) = out_path.parent() { if let Some(parent) = out_path.parent() {
std::fs::create_dir_all(parent) std::fs::create_dir_all(parent)
.map_err(|e| format!("creating output dir: {e}"))?; .map_err(|e| format!("creating output dir: {e:#}"))?;
} }
let trim_start = request.trim_start_secs.filter(|s| *s > 0.001); let trim_start = request.trim_start_secs.filter(|s| *s > 0.001);
@@ -1402,6 +1373,7 @@ fn export(app: AppHandle, state: State<'_, AppState>, request: ExportRequest) ->
clip_width: clip.width, clip_width: clip.width,
clip_height: clip.height, clip_height: clip.height,
progress_tx: None, progress_tx: None,
cancel: Some(state.export_cancel.clone()),
}; };
let total_passes: u8 = if request.format == crate::config::Format::Gif { 1 } else { 2 }; let total_passes: u8 = if request.format == crate::config::Format::Gif { 1 } else { 2 };
+10
View File
@@ -151,4 +151,14 @@ body {
animation-duration: 0.01ms !important; animation-duration: 0.01ms !important;
transition-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;
}
} }
+22 -12
View File
@@ -171,10 +171,10 @@
} }
async function stopRec() { async function stopRec() {
clearTick()
void emit("recording-state", { phase: "idle", fps }) void emit("recording-state", { phase: "idle", fps })
try { try {
const c = await api.stopCapture() const c = await api.stopCapture()
clearTick()
clip = c clip = c
phase = "editing" phase = "editing"
trimStart = 0 trimStart = 0
@@ -188,13 +188,17 @@
outputPath = await api.defaultOutputPath(format) outputPath = await api.defaultOutputPath(format)
const sensible = Math.min(50, Math.max(minMB(c.duration_secs), Math.round(c.duration_secs * 0.5))) const sensible = Math.min(50, Math.max(minMB(c.duration_secs), Math.round(c.duration_secs * 0.5)))
targetMB = sensible targetMB = sensible
} catch (e) { errMsg = String(e); phase = "idle" } } catch (e) { errMsg = String(e); phase = "idle"; clearTick() }
} }
async function pauseRec() { async function pauseRec() {
try {
await api.pauseCapture()
clearTick() clearTick()
try { await api.pauseCapture(); phase = "paused" } phase = "paused"
catch (e) { errMsg = String(e); tick() } } catch (e) {
errMsg = String(e)
}
void emit("recording-state", { phase: "paused", fps }) void emit("recording-state", { phase: "paused", fps })
} }
@@ -216,7 +220,7 @@
try { try {
previewPath = await api.renderPreview(format, fps, Math.round(targetMB * 1_048_576), format === "gif" ? gifBudgetMode : undefined, format === "gif" ? gifDither : undefined, format === "gif" ? gifColors : undefined) previewPath = await api.renderPreview(format, fps, Math.round(targetMB * 1_048_576), format === "gif" ? gifBudgetMode : undefined, format === "gif" ? gifDither : undefined, format === "gif" ? gifColors : undefined)
previewCacheBust = Date.now() previewCacheBust = Date.now()
} catch { previewPath = null } } catch (e) { previewPath = null; console.warn("preview render failed:", e) }
finally { previewLoading = false } finally { previewLoading = false }
} }
@@ -229,6 +233,10 @@
try { try {
const thumbs = await api.extractThumbnails(fps) const thumbs = await api.extractThumbnails(fps)
thumbCache.set(cacheKey, thumbs) thumbCache.set(cacheKey, thumbs)
if (thumbCache.size > 5) {
const firstKey = thumbCache.keys().next().value
if (firstKey) thumbCache.delete(firstKey)
}
thumbnails = thumbs thumbnails = thumbs
deletedFrames = new Set() deletedFrames = new Set()
} catch (e) { errMsg = String(e) } } catch (e) { errMsg = String(e) }
@@ -302,6 +310,7 @@
let dragging: 'start' | 'end' | null = $state(null) let dragging: 'start' | 'end' | null = $state(null)
let trimPreviewPath: string | null = $state(null) let trimPreviewPath: string | null = $state(null)
let trimPreviewBust: number = $state(0) let trimPreviewBust: number = $state(0)
let lastTrimPreview = 0
function pointerToSecs(e: PointerEvent): number { function pointerToSecs(e: PointerEvent): number {
if (!trackEl || !clip) return 0 if (!trackEl || !clip) return 0
@@ -312,6 +321,9 @@
} }
async function updateTrimPreview(secs: number) { async function updateTrimPreview(secs: number) {
const now = Date.now()
if (now - lastTrimPreview < 100) return // 10Hz max
lastTrimPreview = now
try { try {
trimPreviewPath = await api.renderRawPreview(secs) trimPreviewPath = await api.renderRawPreview(secs)
trimPreviewBust = Date.now() trimPreviewBust = Date.now()
@@ -367,8 +379,6 @@
$effect(() => { $effect(() => {
if (phase === "editing" && format) { if (phase === "editing" && format) {
// Read these so the effect re-runs when they change
const _deps = format === "gif" ? `${gifBudgetMode}-${gifDither}-${gifColors}-${fps}-${targetMB}` : `${fps}-${targetMB}`
const timer = window.setTimeout(() => { void refreshPreview() }, 300) const timer = window.setTimeout(() => { void refreshPreview() }, 300)
return () => { clearTimeout(timer) } return () => { clearTimeout(timer) }
} }
@@ -754,19 +764,19 @@
<div class="crop-grid"> <div class="crop-grid">
<label class="crop-field"> <label class="crop-field">
<span>X</span> <span>X</span>
<input type="number" min="0" bind:value={cropX} /> <input type="number" min="0" max={clip?.width ?? 9999} bind:value={cropX} />
</label> </label>
<label class="crop-field"> <label class="crop-field">
<span>Y</span> <span>Y</span>
<input type="number" min="0" bind:value={cropY} /> <input type="number" min="0" max={clip?.height ?? 9999} bind:value={cropY} />
</label> </label>
<label class="crop-field"> <label class="crop-field">
<span>W</span> <span>W</span>
<input type="number" min="1" bind:value={cropW} /> <input type="number" min="1" max={clip?.width ?? 9999} bind:value={cropW} />
</label> </label>
<label class="crop-field"> <label class="crop-field">
<span>H</span> <span>H</span>
<input type="number" min="1" bind:value={cropH} /> <input type="number" min="1" max={clip?.height ?? 9999} bind:value={cropH} />
</label> </label>
</div> </div>
{/if} {/if}
@@ -1151,7 +1161,7 @@
.edit { .edit {
flex: 1; flex: 1;
display: grid; display: grid;
grid-template-columns: 1.4fr 1fr; grid-template-columns: minmax(300px, 1.4fr) minmax(250px, 1fr);
gap: 1px; gap: 1px;
background: var(--border); background: var(--border);
min-height: 0; min-height: 0;
+15 -1
View File
@@ -11,6 +11,9 @@
let hotkeyWarnings: string[] = $state([]) let hotkeyWarnings: string[] = $state([])
let showAdvanced: boolean = $state(false) let showAdvanced: boolean = $state(false)
let activeTab: string = $state("capture") let activeTab: string = $state("capture")
let initialCfg: string = $state("")
let dirty = $derived(cfg ? JSON.stringify(cfg) !== initialCfg : false)
const TABS = [ const TABS = [
{ id: "capture", label: "Capture" }, { id: "capture", label: "Capture" },
@@ -20,7 +23,7 @@
{ id: "system", label: "System" }, { id: "system", label: "System" },
] ]
onMount(async () => { cfg = await api.getConfig() }) onMount(async () => { cfg = await api.getConfig(); initialCfg = JSON.stringify(cfg) })
async function save() { async function save() {
if (!cfg) return if (!cfg) return
@@ -44,6 +47,7 @@
if (failed.length > 0) { if (failed.length > 0) {
hotkeyWarnings = [`${failed.join(", ")} - hotkey may be in use by another app`] hotkeyWarnings = [`${failed.join(", ")} - hotkey may be in use by another app`]
} else { } else {
initialCfg = JSON.stringify(cfg)
onClose() onClose()
} }
} finally { saving = false } } finally { saving = false }
@@ -231,6 +235,7 @@
<button class="btn-primary" onclick={save} disabled={saving}> <button class="btn-primary" onclick={save} disabled={saving}>
{saving ? "Saving" : "Save changes"} {saving ? "Saving" : "Save changes"}
</button> </button>
{#if dirty}<span class="unsaved-dot" title="unsaved changes"></span>{/if}
<button class="btn-ghost" onclick={onClose}>Cancel</button> <button class="btn-ghost" onclick={onClose}>Cancel</button>
</div> </div>
{/if} {/if}
@@ -481,4 +486,13 @@
} }
.btn-warn:hover:not(:disabled) { background: var(--stop-hover); } .btn-warn:hover:not(:disabled) { background: var(--stop-hover); }
.btn-warn:disabled { opacity: 0.4; cursor: not-allowed; } .btn-warn:disabled { opacity: 0.4; cursor: not-allowed; }
.unsaved-dot {
width: 6px; height: 6px;
border-radius: 50%;
background: var(--warn);
display: inline-block;
margin-left: 8px;
vertical-align: middle;
}
</style> </style>