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:
+72
-21
@@ -2,7 +2,9 @@ use std::collections::HashSet;
|
||||
use std::ffi::{OsStr, OsString};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::mpsc::Sender;
|
||||
use std::sync::Arc;
|
||||
use std::thread;
|
||||
|
||||
use anyhow::{anyhow, bail, Context, Result};
|
||||
@@ -50,6 +52,9 @@ pub struct TranscodeRequest {
|
||||
/// Optional channel to report encoding progress.
|
||||
#[doc(hidden)]
|
||||
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;
|
||||
@@ -284,7 +289,8 @@ fn two_pass_video(
|
||||
let tx = req.progress_tx.clone();
|
||||
let dur = req.duration_secs;
|
||||
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.
|
||||
if let Some(ref t) = tx {
|
||||
@@ -314,7 +320,7 @@ fn two_pass_video(
|
||||
pass2.arg("-an");
|
||||
}
|
||||
pass2.arg(&req.output);
|
||||
run_with_progress(&mut pass2, "pass 2", 2, 2, dur, fps, tx.as_ref())?;
|
||||
run_with_progress(&mut pass2, "pass 2", 2, 2, dur, fps, tx.as_ref(), cancel.as_ref())?;
|
||||
|
||||
cleanup_pass_logs(&log_stem);
|
||||
Ok(())
|
||||
@@ -342,7 +348,14 @@ fn cleanup_pass_logs(stem: &Path) {
|
||||
}
|
||||
|
||||
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 max_retries = 6;
|
||||
|
||||
@@ -473,25 +486,35 @@ fn encode_gif_pass(
|
||||
req.duration_secs,
|
||||
effective_fps,
|
||||
req.progress_tx.as_ref(),
|
||||
req.cancel.as_ref(),
|
||||
)?;
|
||||
|
||||
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 };
|
||||
// GIF LZW compression on typical screen content averages ~0.2 bytes/pixel at 256 colors.
|
||||
// Real compression varies 3-5x depending on content (solid colors compress much better
|
||||
// than gradients/noise). The retry loop in encode_gif handles correction on mismatch.
|
||||
// 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
|
||||
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 target_bytes = req.target_bytes as f64;
|
||||
let requested_fps = req.fps as f64;
|
||||
let duration = req.duration_secs;
|
||||
let target_bytes = input.target_bytes as f64;
|
||||
let requested_fps = input.fps as f64;
|
||||
let duration = input.duration_secs;
|
||||
|
||||
match req.gif_budget_mode {
|
||||
match input.gif_budget_mode {
|
||||
GifBudgetMode::Resolution => {
|
||||
let max_w = (clip_width.min(1280) as f64).clamp(120.0, 1280.0);
|
||||
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 max_frames = (target_bytes / bytes_per_frame).floor().max(1.0);
|
||||
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)
|
||||
}
|
||||
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 w = (budget * aspect).sqrt();
|
||||
let w = (w.clamp(120.0, 1280.0).round() as u32 / 2) * 2;
|
||||
(w, req.fps)
|
||||
(w, input.fps)
|
||||
}
|
||||
GifBudgetMode::Balanced => {
|
||||
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 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)
|
||||
}
|
||||
}
|
||||
@@ -749,7 +772,7 @@ pub fn concat_segments(ffmpeg: &Path, segments: &[PathBuf], output: &Path) -> Re
|
||||
}
|
||||
|
||||
fn run(cmd: &mut Command, label: &str) -> Result<()> {
|
||||
let output = run_impl(cmd, label, 0, 0, 0.0, 0, None)?;
|
||||
let output = run_impl(cmd, label, 0, 0, 0.0, 0, None, None)?;
|
||||
if !output.status.success() {
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
let head: String = stderr.lines().take(12).collect::<Vec<_>>().join("\n");
|
||||
@@ -768,8 +791,9 @@ fn run_with_progress(
|
||||
duration_secs: f64,
|
||||
fps: u32,
|
||||
progress_tx: Option<&Sender<EncodeProgress>>,
|
||||
cancel: Option<&Arc<AtomicBool>>,
|
||||
) -> 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() {
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
let head: String = stderr.lines().take(12).collect::<Vec<_>>().join("\n");
|
||||
@@ -786,6 +810,7 @@ fn run_impl(
|
||||
progress_duration_secs: f64,
|
||||
progress_fps: u32,
|
||||
progress_tx: Option<Sender<EncodeProgress>>,
|
||||
cancel: Option<Arc<AtomicBool>>,
|
||||
) -> Result<std::process::Output> {
|
||||
use std::process::Stdio;
|
||||
|
||||
@@ -804,12 +829,10 @@ fn run_impl(
|
||||
.spawn()
|
||||
.with_context(|| format!("spawning ffmpeg for {label}"))?;
|
||||
|
||||
// Spawn a thread to monitor stderr and emit progress.
|
||||
let stderr = child.stderr.take();
|
||||
let tx = progress_tx.clone();
|
||||
|
||||
let handle = stderr.map(move |serr| {
|
||||
// Clone the Sender if present.
|
||||
let mut stderr_handle: Option<thread::JoinHandle<Vec<u8>>> = stderr.map(move |serr| {
|
||||
let tx = tx.as_ref().map(|t| t.clone());
|
||||
let encode_dur = progress_duration_secs;
|
||||
let fps = progress_fps;
|
||||
@@ -817,8 +840,11 @@ fn run_impl(
|
||||
let total_passes = progress_total_passes;
|
||||
thread::spawn(move || {
|
||||
use std::io::{BufRead, BufReader};
|
||||
let mut collected = Vec::new();
|
||||
let reader = BufReader::new(serr);
|
||||
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) {
|
||||
let total = (encode_dur * fps as f64).max(1.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")?;
|
||||
if let Some(h) = handle {
|
||||
let _ = h.join();
|
||||
loop {
|
||||
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();
|
||||
}
|
||||
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}"),
|
||||
}
|
||||
}
|
||||
Ok(output)
|
||||
}
|
||||
|
||||
/// Parse a frame count from an ffmpeg stderr progress line.
|
||||
@@ -884,6 +934,7 @@ mod tests {
|
||||
clip_width: 1920,
|
||||
clip_height: 1080,
|
||||
progress_tx: None,
|
||||
cancel: None,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user