harden gif pipeline, capture, and audio resilience

fix gif calibration (sample deleted before measurement), swap the
budget-mode application so resolution shrinks width not fps, correct the
color factor comment. accumulate gif encode progress across retry
attempts instead of resetting, surface an over-budget result on the done
screen. stream the audio head padding instead of loading it into memory,
detect mid-record audio device loss and offer the existing retry flow,
invalidate the cached encoder list when the ffmpeg binary changes.
add a capture quality setting so 4k screens can record at native res,
try a stream copy before re-encoding when fixing capture timestamps,
park the overlay poll thread when idle, sweep stale config backups, add
a diagnostics tab, and consolidate the preview render debounce.
This commit is contained in:
2026-06-17 23:57:28 +03:00
parent f732cdda4d
commit c3f132507a
9 changed files with 624 additions and 83 deletions
+219 -21
View File
@@ -12,7 +12,7 @@ use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use anyhow::{anyhow, Result};
use anyhow::{anyhow, Context as _, Result};
use serde::{Deserialize, Serialize};
use tauri::{AppHandle, Emitter, Manager, State};
use tauri_plugin_global_shortcut::{GlobalShortcutExt, Shortcut, ShortcutState};
@@ -49,6 +49,10 @@ pub struct AppState {
pub overlay_poll_shutdown: Arc<AtomicBool>,
pub export_cancel: Arc<AtomicBool>,
pub overlay_aspect_ratio: Mutex<Option<f64>>,
/// (active flag, condvar) so the overlay click-through poll thread can park
/// itself when no overlay is on screen instead of waking every 80ms.
/// show_overlay/hide_overlay flip the flag and notify.
pub overlay_poll_live: Arc<(std::sync::Mutex<bool>, std::sync::Condvar)>,
}
pub struct SessionState {
@@ -366,27 +370,42 @@ fn adjust_audio_length(path: &Path, sample_rate: u32, channels: u16, target_secs
/// Prepend `head_secs` of silence to a raw f32le PCM file so the audio track
/// aligns with the video start. WASAPI init adds a delay between capture
/// start and the first audio packet; this pads the gap.
///
/// Streams through a sibling temp file rather than loading the whole PCM into
/// memory - a 10-minute 48kHz stereo clip is ~230MB and the old read-to-end
/// form held it all in a Vec before rewriting.
fn pad_audio_head(path: &Path, sample_rate: u32, channels: u16, head_secs: f64) -> Result<()> {
use std::io::{Read, Write};
use std::io::Write;
let bytes_per_sec = sample_rate as f64 * channels as f64 * 4.0;
let pad_bytes = (head_secs * bytes_per_sec).round() as u64;
if pad_bytes == 0 {
return Ok(());
}
let mut existing = Vec::new();
let temp = path.with_extension("pcm.padtmp");
{
let mut f = std::fs::File::open(path)?;
f.read_to_end(&mut existing)?;
let mut out = std::fs::File::create(&temp)
.with_context(|| format!("creating pad temp {}", temp.display()))?;
let zeros = vec![0u8; 64 * 1024];
let mut remaining = pad_bytes;
while remaining > 0 {
let to_write = remaining.min(zeros.len() as u64) as usize;
out.write_all(&zeros[..to_write])?;
remaining -= to_write as u64;
}
out.flush()?;
// Append the original PCM in a streaming copy - never holds the file.
let mut src = std::fs::File::open(path)?;
std::io::copy(&mut src, &mut out)?;
out.flush()?;
}
let mut f = std::fs::File::create(path)?;
let zeros = vec![0u8; 64 * 1024];
let mut remaining = pad_bytes;
while remaining > 0 {
let to_write = remaining.min(zeros.len() as u64) as usize;
f.write_all(&zeros[..to_write])?;
remaining -= to_write as u64;
// Rename over the original. Fall back to copy+remove if the rename fails
// (e.g. a handle still holds the file on Windows).
if std::fs::rename(&temp, path).is_err() {
std::fs::copy(&temp, path)?;
let _ = std::fs::remove_file(&temp);
}
f.write_all(&existing)?;
tracing::debug!(
"padded audio head with {:.1}ms ({} bytes) of silence",
head_secs * 1000.0, pad_bytes
@@ -426,6 +445,45 @@ fn start_click_recorder(enabled: bool) -> Option<clicks::ClickRecorder> {
}
}
/// Watch an audio session for abnormal death (endpoint unplugged, default
/// output switched, WASAPI invalidated the client). The capture thread sets
/// its `died` flag on such an exit; this poller emits `audio-failed` so the
/// existing retry UI in Main.svelte can recover mid-record instead of the
/// session slot silently holding a dead thread until stop_capture.
fn watch_audio_death(app: AppHandle, died: Arc<AtomicBool>) {
std::thread::spawn(move || {
use std::time::Duration;
loop {
std::thread::sleep(Duration::from_millis(200));
if !died.load(Ordering::SeqCst) {
continue;
}
// The flag latches; clear it so a retried session on the same Arc
// (not current practice, but defensive) doesn't re-fire.
died.store(false, Ordering::SeqCst);
let take = {
let st = app.state::<AppState>();
let mut slot = lock(&st.audio);
if slot.is_some() {
slot.take()
} else {
None
}
};
if let Some(session) = take {
// Drain the dead thread so its handle doesn't leak. The pcm
// it already wrote stays in place for stop_capture to mux.
let _ = session.stop();
let _ = app.emit(
"audio-failed",
"audio device lost - endpoint changed or was unplugged".to_string(),
);
}
return;
}
});
}
#[tauri::command]
fn start_capture(
app: AppHandle,
@@ -462,6 +520,7 @@ fn start_capture(
cfg.capture.capture_audio,
crop,
fps,
cfg.capture.capture_quality,
)
.map_err(|e| format!("{e:#}"))?;
@@ -498,6 +557,9 @@ fn start_capture(
*lock(&state.session) = Some(session_state);
*lock(&state.capture) = Some(session);
if let Some(ref s) = audio_session {
watch_audio_death(app.clone(), s.died_flag().clone());
}
*lock(&state.audio) = audio_session;
*lock(&state.click_recorder) = click_rec;
Ok(())
@@ -568,13 +630,16 @@ fn resume_capture(app: AppHandle, state: State<'_, AppState>) -> Result<(), Stri
)
};
let fps = lock(&state.config).capture.default_fps;
let (fps, quality) = {
let c = lock(&state.config);
(c.capture.default_fps, c.capture.capture_quality)
};
let output = segment_path(&state.app_dir, next_idx);
let ffmpeg = bootstrap::ffmpeg_path(&state.app_dir);
if !ffmpeg.is_file() {
return Err("ffmpeg.exe not found".to_string());
}
let session = capture::start(output, ffmpeg, capture_cursor, audio, crop, fps)
let session = capture::start(output, ffmpeg, capture_cursor, audio, crop, fps, quality)
.map_err(|e| format!("{e:#}"))?;
let audio_path = audio_segment_path(&state.app_dir, next_idx);
@@ -582,6 +647,9 @@ fn resume_capture(app: AppHandle, state: State<'_, AppState>) -> Result<(), Stri
let click_rec = start_click_recorder(capture_cursor);
*lock(&state.capture) = Some(session);
if let Some(ref s) = audio_session {
watch_audio_death(app.clone(), s.died_flag().clone());
}
*lock(&state.audio) = audio_session;
*lock(&state.click_recorder) = click_rec;
Ok(())
@@ -621,6 +689,9 @@ fn restart_audio_capture(
let audio_path = audio_segment_path(&state.app_dir, next_idx);
let audio_recovered = try_start_audio(&app, audio_enabled, audio_path);
let recovered = audio_recovered.is_some();
if let Some(ref s) = audio_recovered {
watch_audio_death(app.clone(), s.died_flag().clone());
}
*lock(&state.audio) = audio_recovered;
if recovered {
@@ -1033,6 +1104,8 @@ fn render_raw_preview(
pub struct ExportResult {
pub output_path: PathBuf,
pub size_bytes: u64,
pub target_bytes: u64,
pub met_target: bool,
}
const OVERLAY_BORDER_LOGICAL_PX: f64 = 4.0;
@@ -1049,7 +1122,11 @@ fn cleanup_temp_on_exit(app: &AppHandle) {
clear_temp_segments(&st.app_dir);
}
fn start_overlay_clickthrough_poll(app: AppHandle, shutdown: Arc<AtomicBool>) {
fn start_overlay_clickthrough_poll(
app: AppHandle,
shutdown: Arc<AtomicBool>,
live: Arc<(std::sync::Mutex<bool>, std::sync::Condvar)>,
) {
use std::time::Duration;
use windows::Win32::Foundation::{HWND, POINT};
use windows::Win32::UI::HiDpi::GetDpiForWindow;
@@ -1058,7 +1135,20 @@ fn start_overlay_clickthrough_poll(app: AppHandle, shutdown: Arc<AtomicBool>) {
std::thread::spawn(move || {
let mut last_inner: Option<bool> = None;
while !shutdown.load(Ordering::Relaxed) {
std::thread::sleep(Duration::from_millis(80));
// Park until the overlay is shown. Without this the poller woke
// every 80ms for the whole process lifetime just to re-check
// visibility; now it sleeps on the condvar until show_overlay
// flips the flag and notifies.
{
let (lock, cvar) = &*live;
let mut active = lock.lock().unwrap_or_else(|e| e.into_inner());
while !*active && !shutdown.load(Ordering::Relaxed) {
let (g, _timeout) = cvar
.wait_timeout(active, Duration::from_secs(1))
.unwrap_or_else(|e| e.into_inner());
active = g;
}
}
let overlay = match app.get_webview_window("overlay") {
Some(w) => w,
@@ -1109,6 +1199,7 @@ fn start_overlay_clickthrough_poll(app: AppHandle, shutdown: Arc<AtomicBool>) {
let _ = overlay.set_ignore_cursor_events(in_inner);
last_inner = Some(in_inner);
}
std::thread::sleep(Duration::from_millis(80));
}
});
}
@@ -1135,6 +1226,14 @@ fn show_overlay(app: AppHandle) -> Result<(), String> {
win.show().map_err(|e| format!("showing overlay: {e:#}"))?;
let _ = mark_overlay_excluded_from_capture(&win);
// Wake the click-through poll thread out of its parked state.
{
let st = app.state::<AppState>();
let (lock, cvar) = &*st.overlay_poll_live;
*lock.lock().unwrap_or_else(|e| e.into_inner()) = true;
cvar.notify_one();
}
// If the overlay is off-screen (monitor disconnected), center on primary
use windows::Win32::Foundation::{HWND, POINT};
use windows::Win32::Graphics::Gdi::{
@@ -1168,6 +1267,15 @@ fn hide_overlay(app: AppHandle) -> Result<(), String> {
let win = app
.get_webview_window("overlay")
.ok_or_else(|| "overlay window not found".to_string())?;
// Reset click-through so the next show starts from a known state, and park
// the poll thread until show_overlay wakes it again.
let _ = win.set_ignore_cursor_events(false);
{
let st = app.state::<AppState>();
let (lock, cvar) = &*st.overlay_poll_live;
*lock.lock().unwrap_or_else(|e| e.into_inner()) = false;
cvar.notify_one();
}
win.hide().map_err(|e| format!("hiding overlay: {e:#}"))
}
@@ -1566,6 +1674,86 @@ fn open_url(url: String) -> Result<(), String> {
Ok(())
}
#[derive(Debug, Serialize)]
pub struct DiagnosticsInfo {
pub app_version: String,
pub ffmpeg_version: String,
pub log_dir: String,
pub log_tail: String,
}
/// Read the tail of the most recent daily-rotated log file so the Diagnostics
/// tab can show recent activity without the user having to find the file.
/// Logs are written by tracing-appender to {app_dir}/logs/bytesize.log.YYYY-MM-DD.
fn read_log_tail(log_dir: &Path) -> String {
const TAIL_BYTES: usize = 8 * 1024;
let Ok(entries) = std::fs::read_dir(log_dir) else {
return String::new();
};
// Pick the newest bytesize.log.* by mtime.
let mut newest: Option<(std::time::SystemTime, PathBuf)> = None;
for entry in entries.flatten() {
let name = entry.file_name();
let Some(name) = name.to_str() else { continue };
if !name.starts_with("bytesize.log") {
continue;
}
if let Ok(meta) = entry.metadata() {
if let Ok(mtime) = meta.modified() {
if newest.as_ref().map_or(true, |(t, _)| mtime > *t) {
newest = Some((mtime, entry.path()));
}
}
}
}
let Some((_, path)) = newest else { return String::new() };
let Ok(data) = std::fs::read(&path) else { return String::new() };
let start = data.len().saturating_sub(TAIL_BYTES);
String::from_utf8_lossy(&data[start..]).into_owned()
}
#[tauri::command]
fn diagnostics_info(state: State<'_, AppState>) -> DiagnosticsInfo {
let log_dir = state.app_dir.join("logs");
let log_tail = read_log_tail(&log_dir);
let ffmpeg_version = {
let ffmpeg = bootstrap::ffmpeg_path(&state.app_dir);
if ffmpeg.is_file() {
std::process::Command::new(&ffmpeg)
.arg("-version")
.output()
.ok()
.and_then(|o| {
String::from_utf8_lossy(&o.stdout)
.lines()
.next()
.map(|s| s.to_string())
})
.unwrap_or_else(|| "ffmpeg present (version unreadable)".to_string())
} else {
"not installed".to_string()
}
};
DiagnosticsInfo {
app_version: env!("CARGO_PKG_VERSION").to_string(),
ffmpeg_version,
log_dir: log_dir.to_string_lossy().into_owned(),
log_tail,
}
}
#[tauri::command]
fn open_log_dir(state: State<'_, AppState>) -> Result<(), String> {
use std::os::windows::process::CommandExt;
let log_dir = state.app_dir.join("logs");
let _ = std::fs::create_dir_all(&log_dir);
std::process::Command::new("explorer.exe")
.raw_arg(log_dir.to_string_lossy().to_string())
.spawn()
.map_err(|e| format!("opening log dir: {e:#}"))?;
Ok(())
}
#[tauri::command]
fn cancel_export(state: State<'_, AppState>) {
state.export_cancel.store(true, Ordering::SeqCst);
@@ -1669,20 +1857,21 @@ async fn export(app: AppHandle, state: State<'_, AppState>, request: ExportReque
cancel: Some(export_cancel.clone()),
};
let total_passes: u8 = if request.format == crate::config::Format::Gif { 1 } else { 2 };
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.
// 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() {
let _ = app_handle.emit(
"encode-progress",
encode::EncodeProgress {
pass: progress.pass,
total_passes,
total_passes: progress.total_passes,
percent: progress.percent,
},
);
@@ -1706,6 +1895,8 @@ async fn export(app: AppHandle, state: State<'_, AppState>, request: ExportReque
.map(|m| m.len())
.unwrap_or(0);
Ok(ExportResult {
met_target: size_bytes <= request.target_bytes,
target_bytes: request.target_bytes,
output_path: out_path,
size_bytes,
})
@@ -1768,6 +1959,7 @@ pub fn run() {
overlay_poll_shutdown: Arc::new(AtomicBool::new(false)),
export_cancel: Arc::new(AtomicBool::new(false)),
overlay_aspect_ratio: Mutex::new(None),
overlay_poll_live: Arc::new((std::sync::Mutex::new(false), std::sync::Condvar::new())),
};
let app = tauri::Builder::default()
@@ -1829,7 +2021,11 @@ pub fn run() {
let _ = register_hotkeys(app.handle(), &cfg);
{
let st = app.state::<AppState>();
start_overlay_clickthrough_poll(app.handle().clone(), st.overlay_poll_shutdown.clone());
start_overlay_clickthrough_poll(
app.handle().clone(),
st.overlay_poll_shutdown.clone(),
st.overlay_poll_live.clone(),
);
}
if check_on_launch {
let handle = app.handle().clone();
@@ -1890,6 +2086,8 @@ pub fn run() {
get_overlay_rect,
cancel_export,
codec_availability,
diagnostics_info,
open_log_dir,
])
.build(tauri::generate_context!())
.expect("error while building ByteSize");