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:
+27
-3
@@ -25,6 +25,12 @@ const WAVE_FORMAT_EXTENSIBLE: u16 = 0xFFFE;
|
||||
pub struct AudioSession {
|
||||
thread: Option<JoinHandle<Result<()>>>,
|
||||
running: Arc<AtomicBool>,
|
||||
/// Set by the capture thread when it exits abnormally (i.e. not because
|
||||
/// `running` was flipped to false by a normal stop). The frontend-facing
|
||||
/// watchdog in lib.rs polls this to emit `audio-failed` mid-record, since
|
||||
/// an unplugged endpoint or a default-output switch otherwise leaves the
|
||||
/// session slot populated with a dead thread until stop_capture.
|
||||
died: Arc<AtomicBool>,
|
||||
output_path: PathBuf,
|
||||
pub sample_rate: u32,
|
||||
pub channels: u16,
|
||||
@@ -33,13 +39,22 @@ pub struct AudioSession {
|
||||
|
||||
pub fn start(output_path: PathBuf) -> Result<AudioSession> {
|
||||
let running = Arc::new(AtomicBool::new(true));
|
||||
let running_clone = running.clone();
|
||||
let died = Arc::new(AtomicBool::new(false));
|
||||
let running_for_thread = running.clone();
|
||||
let running_for_check = running.clone();
|
||||
let died_clone = died.clone();
|
||||
let path_clone = output_path.clone();
|
||||
|
||||
let (init_tx, init_rx) = std::sync::mpsc::channel();
|
||||
|
||||
let thread = thread::spawn(move || {
|
||||
let result = capture_thread(running_clone, path_clone, init_tx);
|
||||
let result = capture_thread(running_for_thread, path_clone, init_tx);
|
||||
// Flag abnormal death only if we weren't asked to stop normally.
|
||||
// A normal stop flips `running` to false before join; an error exit
|
||||
// while `running` is still true means the endpoint died under us.
|
||||
if result.is_err() && running_for_check.load(Ordering::Relaxed) {
|
||||
died_clone.store(true, Ordering::Relaxed);
|
||||
}
|
||||
if let Err(ref e) = result {
|
||||
tracing::error!("audio capture thread ended with error: {e:#}");
|
||||
}
|
||||
@@ -54,6 +69,7 @@ pub fn start(output_path: PathBuf) -> Result<AudioSession> {
|
||||
Ok(AudioSession {
|
||||
thread: Some(thread),
|
||||
running,
|
||||
died,
|
||||
output_path,
|
||||
sample_rate,
|
||||
channels,
|
||||
@@ -65,10 +81,18 @@ impl AudioSession {
|
||||
pub fn stop(self) -> Result<PathBuf> {
|
||||
self.running.store(false, Ordering::Relaxed);
|
||||
if let Some(t) = self.thread {
|
||||
let _ = t.join();
|
||||
if let Ok(Err(ref e)) = t.join() {
|
||||
tracing::warn!("audio capture thread reported error on stop: {e:#}");
|
||||
}
|
||||
}
|
||||
Ok(self.output_path)
|
||||
}
|
||||
|
||||
/// True if the capture thread flagged an abnormal exit (endpoint lost,
|
||||
/// device invalidated, etc.). Polled by the watchdog in lib.rs.
|
||||
pub fn died_flag(&self) -> &Arc<AtomicBool> {
|
||||
&self.died
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_format(fmt: &WAVEFORMATEX) -> Result<(u32, u16, u16, bool)> {
|
||||
|
||||
+61
-12
@@ -16,11 +16,25 @@ use windows_capture::settings::{
|
||||
MinimumUpdateIntervalSettings, SecondaryWindowSettings, Settings,
|
||||
};
|
||||
|
||||
use crate::config::CaptureQuality;
|
||||
use crate::CaptureRect;
|
||||
|
||||
const MAX_ENCODE_WIDTH: u32 = 1920;
|
||||
/// Hard ceiling for the Full quality mode so a 4K recording can't balloon to
|
||||
/// 8K on exotic hardware. Auto mode caps at AUTO_ENCODE_WIDTH instead.
|
||||
const MAX_ENCODE_WIDTH: u32 = 3840;
|
||||
const AUTO_ENCODE_WIDTH: u32 = 1920;
|
||||
const FALLBACK_REFRESH_HZ: u32 = 60;
|
||||
|
||||
/// Returns the cap to apply to the encode width, or None for native res.
|
||||
/// Auto keeps the historic 1920 cap so nothing changes for existing users;
|
||||
/// Full records at native res up to MAX_ENCODE_WIDTH (3840).
|
||||
fn encode_width_limit(quality: CaptureQuality) -> Option<u32> {
|
||||
match quality {
|
||||
CaptureQuality::Auto => Some(AUTO_ENCODE_WIDTH),
|
||||
CaptureQuality::Full => Some(MAX_ENCODE_WIDTH),
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct CaptureSetup {
|
||||
pub output_path: PathBuf,
|
||||
@@ -29,6 +43,7 @@ pub struct CaptureSetup {
|
||||
pub height: u32,
|
||||
pub crop: Option<CaptureRect>,
|
||||
pub pipe_fps: u32,
|
||||
pub encode_width_limit: Option<u32>,
|
||||
pub frame_counter: Arc<std::sync::atomic::AtomicU64>,
|
||||
}
|
||||
|
||||
@@ -60,8 +75,12 @@ impl GraphicsCaptureApiHandler for CaptureHandler {
|
||||
setup.width
|
||||
};
|
||||
|
||||
if working_width > MAX_ENCODE_WIDTH {
|
||||
filter_parts.push(format!("scale={}:-2", MAX_ENCODE_WIDTH));
|
||||
if let Some(limit) = setup.encode_width_limit {
|
||||
if working_width > limit {
|
||||
filter_parts.push(format!("scale={}:-2", limit));
|
||||
} else {
|
||||
filter_parts.push("scale=trunc(iw/2)*2:trunc(ih/2)*2".to_string());
|
||||
}
|
||||
} else {
|
||||
filter_parts.push("scale=trunc(iw/2)*2:trunc(ih/2)*2".to_string());
|
||||
}
|
||||
@@ -244,6 +263,7 @@ pub fn start(
|
||||
_audio: bool,
|
||||
crop: Option<CaptureRect>,
|
||||
_fps: u32,
|
||||
quality: CaptureQuality,
|
||||
) -> Result<CaptureSession> {
|
||||
// Use the center of the capture region to determine which monitor to capture.
|
||||
// If the region spans monitors, we pick the one containing the center.
|
||||
@@ -267,7 +287,8 @@ pub fn start(
|
||||
let width = raw_width & !1;
|
||||
let height = raw_height & !1;
|
||||
|
||||
let (out_w, out_h) = compute_output_dims(width, height, crop);
|
||||
let limit = encode_width_limit(quality);
|
||||
let (out_w, out_h) = compute_output_dims(width, height, crop, limit);
|
||||
|
||||
let frame_counter = Arc::new(std::sync::atomic::AtomicU64::new(0));
|
||||
|
||||
@@ -280,6 +301,7 @@ pub fn start(
|
||||
height,
|
||||
crop,
|
||||
pipe_fps,
|
||||
encode_width_limit: limit,
|
||||
frame_counter: frame_counter.clone(),
|
||||
};
|
||||
|
||||
@@ -315,7 +337,12 @@ pub fn start(
|
||||
})
|
||||
}
|
||||
|
||||
fn compute_output_dims(monitor_w: u32, monitor_h: u32, crop: Option<CaptureRect>) -> (u32, u32) {
|
||||
fn compute_output_dims(
|
||||
monitor_w: u32,
|
||||
monitor_h: u32,
|
||||
crop: Option<CaptureRect>,
|
||||
width_limit: Option<u32>,
|
||||
) -> (u32, u32) {
|
||||
let (raw_w, raw_h) = match crop {
|
||||
Some(c) => {
|
||||
let x = c.x.max(0) as u32;
|
||||
@@ -327,10 +354,11 @@ fn compute_output_dims(monitor_w: u32, monitor_h: u32, crop: Option<CaptureRect>
|
||||
}
|
||||
None => (monitor_w, monitor_h),
|
||||
};
|
||||
if raw_w > MAX_ENCODE_WIDTH {
|
||||
let scale = MAX_ENCODE_WIDTH as f64 / raw_w as f64;
|
||||
let cap = width_limit.unwrap_or(u32::MAX);
|
||||
if raw_w > cap {
|
||||
let scale = cap as f64 / raw_w as f64;
|
||||
let nh = (raw_h as f64 * scale).round() as u32;
|
||||
(MAX_ENCODE_WIDTH, (nh / 2) * 2)
|
||||
(cap, (nh / 2) * 2)
|
||||
} else {
|
||||
((raw_w / 2) * 2, (raw_h / 2) * 2)
|
||||
}
|
||||
@@ -393,10 +421,31 @@ pub fn fix_intermediate_fps(
|
||||
return rename_or_copy(input, output);
|
||||
}
|
||||
|
||||
// Re-encode with scaled PTS to fix timing.
|
||||
// CRF 18 is visually lossless and avoids a second generation of H264
|
||||
// quantization on top of the segment encode. The preset stays fast so the
|
||||
// re-encode does not stall stop/pause/resume.
|
||||
// First try a stream copy with -itsscale: it rescales the input timestamps
|
||||
// without re-encoding, so no second generation of H264 quantization. The
|
||||
// segment encode uses ultrafast (no B-frames), so PTS stays monotonic and
|
||||
// -c copy + -itsscale is safe. If ffmpeg rejects it for some reason, fall
|
||||
// back to the lossy re-encode below.
|
||||
let copy_status = Command::new(ffmpeg)
|
||||
.arg("-y")
|
||||
.arg("-hide_banner")
|
||||
.args(["-loglevel", "error"])
|
||||
.args(["-itsscale", &format!("{:.6}", pts_scale)])
|
||||
.args(["-i", &input.to_string_lossy()])
|
||||
.args(["-c", "copy"])
|
||||
.arg(output)
|
||||
.status()
|
||||
.context("stream-copy timestamp fix")?;
|
||||
if copy_status.success() && output.is_file() {
|
||||
tracing::debug!("capture fix: stream copy with -itsscale succeeded, no re-encode");
|
||||
let _ = std::fs::remove_file(input);
|
||||
return Ok(());
|
||||
}
|
||||
tracing::warn!("capture fix: -itsscale copy failed, falling back to re-encode");
|
||||
let _ = std::fs::remove_file(output);
|
||||
|
||||
// Fallback: re-encode with scaled PTS to fix timing.
|
||||
// CRF 18 is visually lossless; preset veryfast keeps stop/pause/resume snappy.
|
||||
let status = Command::new(ffmpeg)
|
||||
.arg("-y")
|
||||
.arg("-hide_banner")
|
||||
|
||||
@@ -35,11 +35,25 @@ pub struct ExportConfig {
|
||||
pub mp4_codec: Mp4Codec,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum CaptureQuality {
|
||||
/// Cap the capture/encode width at 1920px (downscales larger monitors).
|
||||
/// Lower CPU and disk during recording; the default.
|
||||
#[default]
|
||||
Auto,
|
||||
/// Record at the monitor's native resolution (capped at 3840px to bound
|
||||
/// CPU). Sharp text on 4K screens at the cost of more encode load.
|
||||
Full,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct CaptureConfig {
|
||||
pub default_fps: u32,
|
||||
pub capture_cursor: bool,
|
||||
pub capture_audio: bool,
|
||||
#[serde(default)]
|
||||
pub capture_quality: CaptureQuality,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
|
||||
@@ -127,6 +141,7 @@ impl Default for CaptureConfig {
|
||||
default_fps: 30,
|
||||
capture_cursor: true,
|
||||
capture_audio: false,
|
||||
capture_quality: CaptureQuality::Auto,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -139,6 +154,7 @@ impl Default for UpdatesConfig {
|
||||
|
||||
impl Config {
|
||||
pub fn load_or_create(path: &Path) -> Result<Self> {
|
||||
sweep_stale_backups(path);
|
||||
if !path.exists() {
|
||||
let cfg = Self::default();
|
||||
cfg.save(path)?;
|
||||
@@ -199,6 +215,33 @@ pub fn config_path(app_dir: &Path) -> PathBuf {
|
||||
app_dir.join("config.toml")
|
||||
}
|
||||
|
||||
/// Remove config backup files older than 30 days. Corruption handling writes
|
||||
/// `config-{unix_secs}.toml.bak` (plus a `config.toml.bak` fallback) and never
|
||||
/// cleaned them up, so a long-lived install could accumulate a pile. Parses
|
||||
/// the embedded timestamp; anything unparsable is left alone (the fallback
|
||||
/// name has no timestamp and is kept as the most recent safety net).
|
||||
fn sweep_stale_backups(config_path: &Path) {
|
||||
const MAX_AGE_SECS: u64 = 30 * 24 * 3600;
|
||||
let Some(dir) = config_path.parent() else { return };
|
||||
let now = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map(|d| d.as_secs())
|
||||
.unwrap_or(0);
|
||||
let Ok(entries) = std::fs::read_dir(dir) else { return };
|
||||
for entry in entries.flatten() {
|
||||
let name = entry.file_name();
|
||||
let Some(name) = name.to_str() else { continue };
|
||||
// Match config-{digits}.toml.bak - extract the unix secs and age it out.
|
||||
if let Some(rest) = name.strip_prefix("config-").and_then(|s| s.strip_suffix(".toml.bak")) {
|
||||
if let Ok(ts) = rest.parse::<u64>() {
|
||||
if now.saturating_sub(ts) > MAX_AGE_SECS {
|
||||
let _ = std::fs::remove_file(entry.path());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -216,6 +259,7 @@ mod tests {
|
||||
default_fps: 60,
|
||||
capture_cursor: false,
|
||||
capture_audio: true,
|
||||
capture_quality: CaptureQuality::Full,
|
||||
},
|
||||
hotkeys: HotkeyConfig {
|
||||
start: Some("F9".to_string()),
|
||||
|
||||
+113
-32
@@ -4,8 +4,9 @@ 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::sync::{Arc, Mutex};
|
||||
use std::thread;
|
||||
use std::time::SystemTime;
|
||||
|
||||
use anyhow::{anyhow, bail, Context, Result};
|
||||
|
||||
@@ -167,14 +168,41 @@ fn require_video_codec<'a>(
|
||||
}
|
||||
}
|
||||
|
||||
use std::sync::OnceLock;
|
||||
/// Cached encoder list keyed on the ffmpeg binary's mtime. The bootstrap flow
|
||||
/// lets users drop their own ffmpeg.exe into bin/, and a build swap mid-session
|
||||
/// must be picked up - so we re-probe when the file changes rather than caching
|
||||
/// for the whole process lifetime.
|
||||
static ENCODER_CACHE: Mutex<Option<EncoderCacheEntry>> = Mutex::new(None);
|
||||
|
||||
static ENCODER_CACHE: OnceLock<HashSet<String>> = OnceLock::new();
|
||||
struct EncoderCacheEntry {
|
||||
ffmpeg_mtime: SystemTime,
|
||||
encoders: HashSet<String>,
|
||||
}
|
||||
|
||||
fn list_encoders(ffmpeg: &Path) -> Result<&'static HashSet<String>> {
|
||||
if let Some(cached) = ENCODER_CACHE.get() {
|
||||
return Ok(cached);
|
||||
fn list_encoders(ffmpeg: &Path) -> Result<HashSet<String>> {
|
||||
let mtime = std::fs::metadata(ffmpeg)
|
||||
.and_then(|m| m.modified())
|
||||
.unwrap_or(SystemTime::UNIX_EPOCH);
|
||||
|
||||
if let Ok(guard) = ENCODER_CACHE.lock() {
|
||||
if let Some(entry) = guard.as_ref() {
|
||||
if entry.ffmpeg_mtime == mtime {
|
||||
return Ok(entry.encoders.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let set = probe_encoders(ffmpeg)?;
|
||||
if let Ok(mut guard) = ENCODER_CACHE.lock() {
|
||||
*guard = Some(EncoderCacheEntry {
|
||||
ffmpeg_mtime: mtime,
|
||||
encoders: set.clone(),
|
||||
});
|
||||
}
|
||||
Ok(set)
|
||||
}
|
||||
|
||||
fn probe_encoders(ffmpeg: &Path) -> Result<HashSet<String>> {
|
||||
let out = Command::new(ffmpeg)
|
||||
.args(["-hide_banner", "-encoders"])
|
||||
.output()
|
||||
@@ -195,8 +223,7 @@ fn list_encoders(ffmpeg: &Path) -> Result<&'static HashSet<String>> {
|
||||
}
|
||||
set.insert(name.to_string());
|
||||
}
|
||||
let _ = ENCODER_CACHE.set(set);
|
||||
Ok(ENCODER_CACHE.get().unwrap())
|
||||
Ok(set)
|
||||
}
|
||||
|
||||
fn pick_audio_codec<'a>(
|
||||
@@ -433,8 +460,11 @@ fn calibrate_via_sample(
|
||||
sample_req.clicks.clear();
|
||||
sample_req.progress_tx = None;
|
||||
|
||||
let result = encode_gif_pass(ffmpeg, &sample_req, est_width, est_fps);
|
||||
let _ = std::fs::remove_file(&sample_path);
|
||||
let result = encode_gif_pass(ffmpeg, &sample_req, est_width, est_fps, 1, 1);
|
||||
// Defer cleanup until we've measured the sample. Earlier versions removed
|
||||
// the file here, which made the metadata read below always fail and the
|
||||
// whole calibration path silently no-op.
|
||||
let _guard = TempFileGuard(sample_path.clone());
|
||||
if result.is_err() {
|
||||
return None;
|
||||
}
|
||||
@@ -472,6 +502,23 @@ fn calibrate_via_sample(
|
||||
Some((new_width.min(1280), new_fps))
|
||||
}
|
||||
|
||||
/// Per-mode raw shrink factor (before clamping to 0.6..0.9) given the
|
||||
/// target/actual ratio. Bytes scale as width*height*fps; with fixed aspect,
|
||||
/// width drives bytes quadratically and fps linearly, so the factor must
|
||||
/// 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::Balanced => {
|
||||
// Split the required reduction between resolution and fps so we
|
||||
// reduce both proportionally rather than halving resolution alone.
|
||||
let half = 0.5_f64;
|
||||
(ratio * (1.0 - half) + ratio.sqrt() * half).clamp(0.1, 1.0)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn encode_gif(ffmpeg: &Path, req: &TranscodeRequest) -> Result<()> {
|
||||
let budget_input = GifBudgetInput {
|
||||
gif_colors: req.gif_colors,
|
||||
@@ -499,8 +546,11 @@ fn encode_gif(ffmpeg: &Path, req: &TranscodeRequest) -> Result<()> {
|
||||
let target = req.target_bytes;
|
||||
// Retry budget scales with the input. A 5s clip rarely needs more than 3-4
|
||||
// attempts; a 60s clip with tight target and high colors can take 8-10.
|
||||
// Cap at 12 to avoid runaway loops on pathological inputs.
|
||||
// Cap at 12 to avoid runaway loops on pathological inputs. This also drives
|
||||
// the progress bar: each attempt is one segment, so the bar accumulates
|
||||
// across retries instead of resetting.
|
||||
let max_retries = ((req.duration_secs / 5.0).ceil() as u32 + 4).clamp(5, 12);
|
||||
let max_attempts = max_retries as u8;
|
||||
|
||||
let mut prev_actual: Option<u64> = None;
|
||||
|
||||
@@ -514,7 +564,10 @@ fn encode_gif(ffmpeg: &Path, req: &TranscodeRequest) -> Result<()> {
|
||||
effective_fps = 1;
|
||||
}
|
||||
let pass_start = std::time::Instant::now();
|
||||
encode_gif_pass(ffmpeg, req, scale_width, effective_fps)?;
|
||||
encode_gif_pass(
|
||||
ffmpeg, req, scale_width, effective_fps,
|
||||
(attempt as u8) + 1, max_attempts,
|
||||
)?;
|
||||
tracing::info!(
|
||||
attempt = attempt + 1,
|
||||
elapsed_ms = pass_start.elapsed().as_millis(),
|
||||
@@ -544,18 +597,11 @@ fn encode_gif(ffmpeg: &Path, req: &TranscodeRequest) -> Result<()> {
|
||||
// 0.6 and 0.9 so a single bad estimate can't half the resolution in
|
||||
// one step (which is the oscillation problem) and so we don't creep
|
||||
// toward the target at a snail's pace.
|
||||
let raw_factor = match req.gif_budget_mode {
|
||||
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 (which the old `factor = ratio.sqrt()`
|
||||
// would do after a large overshoot).
|
||||
let half = 0.5_f64;
|
||||
(ratio * (1.0 - half) + ratio.sqrt() * half).clamp(0.1, 1.0)
|
||||
}
|
||||
};
|
||||
// Bytes scale as width*height*fps. With fixed aspect, width drives
|
||||
// bytes quadratically (width*height ~ width^2) and fps linearly, so
|
||||
// the shrink factor must match the dimension it's applied to: sqrt
|
||||
// for resolution, linear for framerate.
|
||||
let raw_factor = gif_shrink_factor(req.gif_budget_mode, ratio);
|
||||
let mut factor = raw_factor.clamp(0.6, 0.9);
|
||||
|
||||
// Track trend across attempts. If shrinking settings did not shrink
|
||||
@@ -576,14 +622,14 @@ fn encode_gif(ffmpeg: &Path, req: &TranscodeRequest) -> Result<()> {
|
||||
|
||||
match req.gif_budget_mode {
|
||||
GifBudgetMode::Resolution => {
|
||||
effective_fps = ((effective_fps as f64 * factor).round() as u32).max(1);
|
||||
}
|
||||
GifBudgetMode::Framerate => {
|
||||
scale_width = ((scale_width as f64 * factor).round() as u32 / 2)
|
||||
.max(60)
|
||||
.min(1280)
|
||||
* 2;
|
||||
}
|
||||
GifBudgetMode::Framerate => {
|
||||
effective_fps = ((effective_fps as f64 * factor).round() as u32).max(1);
|
||||
}
|
||||
GifBudgetMode::Balanced => {
|
||||
scale_width = ((scale_width as f64 * factor).round() as u32 / 2)
|
||||
.max(60)
|
||||
@@ -621,6 +667,8 @@ fn encode_gif_pass(
|
||||
req: &TranscodeRequest,
|
||||
scale_width: u32,
|
||||
effective_fps: u32,
|
||||
attempt: u8,
|
||||
max_attempts: u8,
|
||||
) -> Result<()> {
|
||||
let crop_prefix = crop_filter(req.crop)
|
||||
.map(|c| format!("{c},"))
|
||||
@@ -668,8 +716,8 @@ fn encode_gif_pass(
|
||||
run_with_progress(
|
||||
&mut encode,
|
||||
"gif encode",
|
||||
1,
|
||||
1,
|
||||
attempt,
|
||||
max_attempts,
|
||||
req.duration_secs,
|
||||
effective_fps,
|
||||
req.progress_tx.as_ref(),
|
||||
@@ -699,8 +747,9 @@ pub fn gif_params(input: &GifBudgetInput, clip_width: u32, clip_height: u32) ->
|
||||
// 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
|
||||
// Fewer colors = better compression. Adjust proportionally to the sqrt of the color
|
||||
// fraction (LZW code width tracks palette depth roughly logarithmically).
|
||||
// 256 colors = 1.0x, 128 = ~0.71x, 64 = 0.5x, 32 = ~0.35x, 16 = 0.25x, 2 = ~0.13x
|
||||
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 = input.target_bytes as f64;
|
||||
@@ -1167,7 +1216,7 @@ fn run_impl(
|
||||
});
|
||||
}
|
||||
Ok(None) => {
|
||||
std::thread::sleep(std::time::Duration::from_millis(50));
|
||||
std::thread::sleep(std::time::Duration::from_millis(20));
|
||||
}
|
||||
Err(e) => bail!("waiting for ffmpeg: {e}"),
|
||||
}
|
||||
@@ -1319,4 +1368,36 @@ mod tests {
|
||||
let count = filter.matches("drawbox").count();
|
||||
assert_eq!(count, MAX_CLICK_HIGHLIGHTS);
|
||||
}
|
||||
|
||||
#[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);
|
||||
}
|
||||
|
||||
#[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);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gif_shrink_factor_balanced_between_sqrt_and_linear() {
|
||||
let f = gif_shrink_factor(GifBudgetMode::Balanced, 0.25);
|
||||
let lo = 0.25_f64;
|
||||
let hi = 0.5_f64; // sqrt(0.25)
|
||||
assert!(f > lo && f < hi, "balanced factor {f} should sit between linear {lo} and sqrt {hi}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gif_color_factor_matches_comment_values() {
|
||||
// comment claims: 256=1.0x, 128=~0.71x, 64=0.5x, 32=~0.35x, 16=0.25x
|
||||
let cf = |colors: u16| (colors as f64 / 256.0).sqrt().clamp(0.15, 1.0);
|
||||
assert!((cf(256) - 1.0).abs() < 1e-9);
|
||||
assert!((cf(128) - 2f64.sqrt() / 2.0).abs() < 1e-9); // ~0.707
|
||||
assert!((cf(64) - 0.5).abs() < 1e-9);
|
||||
assert!((cf(16) - 0.25).abs() < 1e-9);
|
||||
}
|
||||
}
|
||||
|
||||
+219
-21
@@ -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");
|
||||
|
||||
+61
-11
@@ -392,7 +392,15 @@
|
||||
else if (format !== "gif") thumbnails = []
|
||||
})
|
||||
|
||||
// Single owner of preview rendering. Touches every input that affects the
|
||||
// preview so one debounced render fires per change-burst - previously the
|
||||
// debounced effect here and TrimPanel's synchronous onAfterChange could
|
||||
// both trigger a render for the same change.
|
||||
$effect(() => {
|
||||
void phase; void format; void fps; void targetMB
|
||||
void gifBudgetMode; void gifDither; void gifColors
|
||||
void trimStart; void trimEnd
|
||||
void cropEnabled; void cropX; void cropY; void cropW; void cropH
|
||||
if (phase === "editing" && format) {
|
||||
const timer = window.setTimeout(() => { void refreshPreview() }, 300)
|
||||
return () => { clearTimeout(timer) }
|
||||
@@ -423,6 +431,20 @@
|
||||
phase === "done" ? "DONE" : ""
|
||||
)
|
||||
|
||||
// Overall encode percent across all passes/attempts. The encoder reports
|
||||
// per-pass percent (0-100 within one pass); with GIF retrying up to ~12
|
||||
// times the headline number otherwise jumps back to single digits each
|
||||
// attempt. Spread each pass's percent across its share of the whole.
|
||||
let encodeOverall = $derived.by(() => {
|
||||
if (!encodeProgress) return 0
|
||||
const { pass, total, pct } = encodeProgress
|
||||
if (total <= 0) return pct
|
||||
return ((pass - 1) / total) * 100 + (pct / total)
|
||||
})
|
||||
|
||||
// GIF retry loop calls each pass an "attempt"; two-pass video keeps "pass".
|
||||
let encodeUnit = $derived(format === "gif" ? "attempt" : "pass")
|
||||
|
||||
let phaseColor: string = $derived.by(() => {
|
||||
const p: string = phase
|
||||
return p === "recording" ? "var(--recording)" :
|
||||
@@ -584,12 +606,12 @@
|
||||
{previewCacheBust}
|
||||
/>
|
||||
|
||||
<!-- Trim timeline -->
|
||||
<!-- Trim timeline. Preview re-render is driven by the debounced
|
||||
$effect that watches trimStart/trimEnd, so no onAfterChange. -->
|
||||
<TrimPanel
|
||||
{clip}
|
||||
bind:trimStart
|
||||
bind:trimEnd
|
||||
onAfterChange={refreshPreview}
|
||||
/>
|
||||
|
||||
<!-- GIF frames -->
|
||||
@@ -635,10 +657,10 @@
|
||||
<div class="exporting">
|
||||
{#if encodeProgress}
|
||||
<div class="enc-meta">
|
||||
<span>Pass {encodeProgress.pass}/{encodeProgress.total}</span>
|
||||
<span class="mono">{encodeProgress.pct.toFixed(0)}%</span>
|
||||
<span class="text-cap">{encodeUnit} {encodeProgress.pass}/{encodeProgress.total}</span>
|
||||
<span class="mono">{encodeOverall.toFixed(0)}%</span>
|
||||
</div>
|
||||
<div class="enc-track">
|
||||
<div class="enc-track" class:multi={encodeProgress.total > 3}>
|
||||
{#each Array(encodeProgress.total) as _, i}
|
||||
<div class="enc-segment">
|
||||
<div
|
||||
@@ -652,20 +674,33 @@
|
||||
<div class="enc-meta"><span>Preparing</span></div>
|
||||
<div class="enc-track"><div class="enc-segment"><div class="enc-fill" style="width:0%"></div></div></div>
|
||||
{/if}
|
||||
<p class="enc-hint">ffmpeg is encoding your clip</p>
|
||||
<p class="enc-hint">ffmpeg is encoding your clip{format === "gif" ? " (retrying to hit target size)" : ""}</p>
|
||||
<button class="btn-ghost" onclick={cancelExport}>Cancel</button>
|
||||
</div>
|
||||
|
||||
<!-- DONE -->
|
||||
{:else if phase === "done" && exportResult}
|
||||
<div class="done">
|
||||
<div class="done-mark">
|
||||
<svg width="28" height="28" viewBox="0 0 28 28" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<circle cx="14" cy="14" r="11"/><polyline points="9,14 13,18 19,11"/>
|
||||
</svg>
|
||||
<div class="done-mark" class:warn={!exportResult.met_target}>
|
||||
{#if exportResult.met_target}
|
||||
<svg width="28" height="28" viewBox="0 0 28 28" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<circle cx="14" cy="14" r="11"/><polyline points="9,14 13,18 19,11"/>
|
||||
</svg>
|
||||
{:else}
|
||||
<svg width="28" height="28" viewBox="0 0 28 28" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<circle cx="14" cy="14" r="11"/><line x1="14" y1="8" x2="14" y2="15"/><circle cx="14" cy="19" r="0.5" fill="currentColor"/>
|
||||
</svg>
|
||||
{/if}
|
||||
</div>
|
||||
<h2 class="done-title">Exported</h2>
|
||||
<h2 class="done-title">
|
||||
{exportResult.met_target ? "Exported" : "Exported (over budget)"}
|
||||
</h2>
|
||||
<p class="done-size mono">{formatBytes(exportResult.size_bytes)}</p>
|
||||
{#if !exportResult.met_target}
|
||||
<p class="done-caveat">
|
||||
target {formatBytes(exportResult.target_bytes)} - could not shrink further without wrecking quality
|
||||
</p>
|
||||
{/if}
|
||||
<p class="done-path mono">{exportResult.output_path}</p>
|
||||
<div class="done-actions">
|
||||
<button class="btn-primary" onclick={startOver}>Record another</button>
|
||||
@@ -1117,6 +1152,9 @@
|
||||
display: flex;
|
||||
gap: 2px;
|
||||
}
|
||||
/* GIF retry renders many thin segments; tighten the gap so they don't read as
|
||||
a dotted line at 10+ attempts. */
|
||||
.enc-track.multi { gap: 1px; }
|
||||
.enc-segment { flex: 1; background: var(--bg-3); overflow: hidden; }
|
||||
.enc-fill {
|
||||
height: 100%;
|
||||
@@ -1124,6 +1162,7 @@
|
||||
border-radius: 2px;
|
||||
transition: width 0.4s ease;
|
||||
}
|
||||
.text-cap { text-transform: capitalize; }
|
||||
.enc-hint {
|
||||
margin: 0;
|
||||
font-size: 11px;
|
||||
@@ -1143,6 +1182,17 @@
|
||||
.done-mark {
|
||||
color: var(--accent);
|
||||
}
|
||||
.done-mark.warn {
|
||||
color: var(--warn);
|
||||
}
|
||||
.done-caveat {
|
||||
margin: 0;
|
||||
font-size: 11px;
|
||||
color: var(--warn);
|
||||
text-align: center;
|
||||
max-width: 320px;
|
||||
line-height: 1.5;
|
||||
}
|
||||
.done-title {
|
||||
margin: 0;
|
||||
font-size: 18px;
|
||||
|
||||
+83
-2
@@ -1,6 +1,6 @@
|
||||
<script lang="ts">
|
||||
import { onMount } from "svelte"
|
||||
import { api, type Config, type CodecAvailability } from "./api"
|
||||
import { api, type Config, type CodecAvailability, type DiagnosticsInfo } from "./api"
|
||||
import HotkeyInput from "./HotkeyInput.svelte"
|
||||
import { open } from "@tauri-apps/plugin-dialog"
|
||||
|
||||
@@ -20,6 +20,7 @@
|
||||
|| cfg.capture.default_fps !== initialCfg.capture.default_fps
|
||||
|| cfg.capture.capture_cursor !== initialCfg.capture.capture_cursor
|
||||
|| cfg.capture.capture_audio !== initialCfg.capture.capture_audio
|
||||
|| cfg.capture.capture_quality !== initialCfg.capture.capture_quality
|
||||
|| cfg.export.default_format !== initialCfg.export.default_format
|
||||
|| cfg.export.gif_dither !== initialCfg.export.gif_dither
|
||||
|| cfg.export.webm_codec !== initialCfg.export.webm_codec
|
||||
@@ -31,12 +32,15 @@
|
||||
|| cfg.output_dir !== initialCfg.output_dir
|
||||
})
|
||||
|
||||
let diagnostics: DiagnosticsInfo | null = $state(null)
|
||||
|
||||
const TABS = [
|
||||
{ id: "capture", label: "Capture" },
|
||||
{ id: "export", label: "Export" },
|
||||
{ id: "hotkeys", label: "Hotkeys" },
|
||||
{ id: "output", label: "Output" },
|
||||
{ id: "system", label: "System" },
|
||||
{ id: "diagnostics", label: "Diagnostics" },
|
||||
]
|
||||
|
||||
onMount(async () => {
|
||||
@@ -49,6 +53,15 @@
|
||||
if (cfg) document.documentElement.setAttribute("data-theme", cfg.theme)
|
||||
})
|
||||
|
||||
$effect(() => {
|
||||
if (activeTab !== "diagnostics") return
|
||||
api.diagnosticsInfo().then(d => { diagnostics = d }).catch(() => { diagnostics = null })
|
||||
})
|
||||
|
||||
async function refreshDiagnostics() {
|
||||
try { diagnostics = await api.diagnosticsInfo() } catch { diagnostics = null }
|
||||
}
|
||||
|
||||
async function save() {
|
||||
if (!cfg) return
|
||||
|
||||
@@ -124,6 +137,13 @@
|
||||
{#each [15,24,30,60] as f}<option value={f}>{f} fps</option>{/each}
|
||||
</select>
|
||||
</label>
|
||||
<label class="field">
|
||||
<span class="field-label">Capture quality</span>
|
||||
<select bind:value={cfg.capture.capture_quality}>
|
||||
<option value="auto">Auto (cap 1920px, lower CPU)</option>
|
||||
<option value="full">Full (native res up to 3840px)</option>
|
||||
</select>
|
||||
</label>
|
||||
<label class="field-check">
|
||||
<input type="checkbox" bind:checked={cfg.capture.capture_cursor} />
|
||||
<span>Capture cursor</span>
|
||||
@@ -247,6 +267,36 @@
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{:else if activeTab === "diagnostics"}
|
||||
<div class="tab-panel">
|
||||
<div class="panel-head">
|
||||
<h2>Diagnostics</h2>
|
||||
<p class="panel-desc">Versions and recent log output</p>
|
||||
</div>
|
||||
<div class="field-list">
|
||||
<div class="diag-row">
|
||||
<span class="field-label">ByteSize</span>
|
||||
<span class="diag-val mono">{diagnostics ? `v${diagnostics.app_version}` : "..."}</span>
|
||||
</div>
|
||||
<div class="diag-row">
|
||||
<span class="field-label">ffmpeg</span>
|
||||
<span class="diag-val mono">{diagnostics ? diagnostics.ffmpeg_version : "..."}</span>
|
||||
</div>
|
||||
<div class="diag-row">
|
||||
<span class="field-label">Log folder</span>
|
||||
<span class="diag-val mono">{diagnostics ? diagnostics.log_dir : "..."}</span>
|
||||
<button class="btn-ghost compact" onclick={() => api.openLogDir()} disabled={!diagnostics}>Open</button>
|
||||
</div>
|
||||
<div class="diag-tail-wrap">
|
||||
<div class="diag-tail-head">
|
||||
<span class="field-label">Recent log</span>
|
||||
<button class="link" onclick={refreshDiagnostics}>Refresh</button>
|
||||
</div>
|
||||
<pre class="diag-tail">{diagnostics ? diagnostics.log_tail || "(empty)" : "loading..."}</pre>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
{#if hotkeyWarnings.length > 0}
|
||||
@@ -257,7 +307,7 @@
|
||||
<button class="btn-ghost" onclick={onClose}>Cancel</button>
|
||||
</div>
|
||||
</div>
|
||||
{:else}
|
||||
{:else if activeTab !== "diagnostics"}
|
||||
<div class="panel-foot">
|
||||
<button class="btn-primary" onclick={save} disabled={saving}>
|
||||
{saving ? "Saving" : "Save changes"}
|
||||
@@ -265,6 +315,10 @@
|
||||
{#if dirty}<span class="unsaved-dot" title="unsaved changes"></span>{/if}
|
||||
<button class="btn-ghost" onclick={onClose}>Cancel</button>
|
||||
</div>
|
||||
{:else}
|
||||
<div class="panel-foot">
|
||||
<button class="btn-ghost" onclick={onClose}>Close</button>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
@@ -528,4 +582,31 @@
|
||||
margin-left: 8px;
|
||||
vertical-align: middle;
|
||||
}
|
||||
|
||||
/* ---- Diagnostics ---- */
|
||||
.diag-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
}
|
||||
.diag-row .field-label { flex-shrink: 0; width: 90px; }
|
||||
.diag-val { font-size: 12px; color: var(--text-2); flex: 1; min-width: 0; word-break: break-all; }
|
||||
.btn-ghost.compact { padding: 5px 12px; font-size: 12px; }
|
||||
.diag-tail-wrap { display: flex; flex-direction: column; gap: 6px; margin-top: 4px; }
|
||||
.diag-tail-head { display: flex; align-items: center; justify-content: space-between; }
|
||||
.diag-tail {
|
||||
margin: 0;
|
||||
padding: 10px;
|
||||
background: var(--bg-3);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--r-sm);
|
||||
font-family: var(--mono);
|
||||
font-size: 10px;
|
||||
line-height: 1.5;
|
||||
color: var(--text-3);
|
||||
max-height: 220px;
|
||||
overflow: auto;
|
||||
white-space: pre-wrap;
|
||||
word-break: break-all;
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -6,12 +6,12 @@
|
||||
clip,
|
||||
trimStart = $bindable(),
|
||||
trimEnd = $bindable(),
|
||||
onAfterChange,
|
||||
onAfterChange = () => {},
|
||||
}: {
|
||||
clip: { temp_path: string; duration_secs: number; width: number; height: number }
|
||||
trimStart: number
|
||||
trimEnd: number
|
||||
onAfterChange: () => void
|
||||
onAfterChange?: () => void
|
||||
} = $props()
|
||||
|
||||
let trackEl: HTMLDivElement | null = $state(null)
|
||||
|
||||
@@ -23,10 +23,13 @@ export type ExportConfig = {
|
||||
mp4_codec: Mp4Codec
|
||||
}
|
||||
|
||||
export type CaptureQuality = "auto" | "full"
|
||||
|
||||
export type CaptureConfig = {
|
||||
default_fps: number
|
||||
capture_cursor: boolean
|
||||
capture_audio: boolean
|
||||
capture_quality: CaptureQuality
|
||||
}
|
||||
|
||||
export type HotkeyConfig = {
|
||||
@@ -124,6 +127,8 @@ export type ExportRequest = {
|
||||
export type ExportResult = {
|
||||
output_path: string
|
||||
size_bytes: number
|
||||
target_bytes: number
|
||||
met_target: boolean
|
||||
}
|
||||
|
||||
export type HotkeyRegistrationResult = {
|
||||
@@ -167,6 +172,13 @@ export type CodecAvailability = {
|
||||
av1: boolean
|
||||
}
|
||||
|
||||
export type DiagnosticsInfo = {
|
||||
app_version: string
|
||||
ffmpeg_version: string
|
||||
log_dir: string
|
||||
log_tail: string
|
||||
}
|
||||
|
||||
export type AudioFailed = string
|
||||
|
||||
export const api = {
|
||||
@@ -245,6 +257,8 @@ export const api = {
|
||||
listen<string>("audio-failed", (e) => handler(e.payload)),
|
||||
cancelExport: () => invoke<void>("cancel_export"),
|
||||
codecAvailability: () => invoke<CodecAvailability>("codec_availability"),
|
||||
diagnosticsInfo: () => invoke<DiagnosticsInfo>("diagnostics_info"),
|
||||
openLogDir: () => invoke<void>("open_log_dir"),
|
||||
}
|
||||
|
||||
export function formatBytes(n: number): string {
|
||||
|
||||
Reference in New Issue
Block a user