split Main into components, move gif math to backend
This commit is contained in:
@@ -511,6 +511,48 @@ fn resume_capture(app: AppHandle, state: State<'_, AppState>) -> Result<(), Stri
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Restart the audio capture mid-recording. Used when the initial WASAPI
|
||||
/// session failed (e.g. endpoint was busy) and the user wants to retry
|
||||
/// without ending the recording. Stops the current session, appends its
|
||||
/// pcm segment to the session, and starts a new one with a fresh file.
|
||||
#[tauri::command]
|
||||
fn restart_audio_capture(
|
||||
app: AppHandle,
|
||||
state: State<'_, AppState>,
|
||||
) -> Result<(), String> {
|
||||
let audio_enabled = {
|
||||
let ss = lock(&state.session);
|
||||
let ss = ss.as_ref().ok_or_else(|| "no session in progress".to_string())?;
|
||||
if !ss.audio {
|
||||
return Err("audio is not enabled for this recording".to_string());
|
||||
}
|
||||
ss.audio
|
||||
};
|
||||
|
||||
// Stop the existing session and stash its file. Don't touch capture
|
||||
// or click recording - they keep running.
|
||||
let next_idx = {
|
||||
let mut ss = lock(&state.session);
|
||||
let ss = ss.as_mut().ok_or_else(|| "no session in progress".to_string())?;
|
||||
if let Some(a) = lock(&state.audio).take() {
|
||||
if let Ok(p) = a.stop() {
|
||||
ss.audio_segments.push(p);
|
||||
}
|
||||
}
|
||||
ss.audio_segments.len() + 1
|
||||
};
|
||||
|
||||
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();
|
||||
*lock(&state.audio) = audio_recovered;
|
||||
|
||||
if recovered {
|
||||
let _ = app.emit("audio-recovered", ());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
fn stop_capture(app: AppHandle, state: State<'_, AppState>) -> Result<RecordedClip, String> {
|
||||
set_overlay_clickthrough(&app, false);
|
||||
@@ -678,6 +720,14 @@ pub struct PreviewRequest {
|
||||
pub gif_dither: Option<GifDither>,
|
||||
#[serde(default)]
|
||||
pub gif_colors: Option<u16>,
|
||||
/// Optional clip dimensions/duration. Required by `estimate_gif_params`,
|
||||
/// unused by `render_preview` (which uses the current `last_clip`).
|
||||
#[serde(default)]
|
||||
pub clip_width: u32,
|
||||
#[serde(default)]
|
||||
pub clip_height: u32,
|
||||
#[serde(default)]
|
||||
pub duration_secs: Option<f64>,
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
@@ -726,6 +776,91 @@ fn render_preview(
|
||||
Ok(preview_path)
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct GifEstimate {
|
||||
pub width: u32,
|
||||
pub fps: u32,
|
||||
pub height: u32,
|
||||
pub dims_label: String,
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
fn estimate_gif_params(request: PreviewRequest) -> GifEstimate {
|
||||
let budget = encode::GifBudgetInput {
|
||||
gif_colors: request.gif_colors.unwrap_or(256),
|
||||
target_bytes: request.target_bytes,
|
||||
fps: request.fps,
|
||||
duration_secs: request.duration_secs.unwrap_or(0.0),
|
||||
gif_budget_mode: request.gif_budget_mode,
|
||||
};
|
||||
let (w, fps) = encode::gif_params(&budget, request.clip_width, request.clip_height);
|
||||
let aspect = if request.clip_height > 0 {
|
||||
request.clip_width as f64 / request.clip_height as f64
|
||||
} else {
|
||||
16.0 / 9.0
|
||||
};
|
||||
let height = if w == 0 {
|
||||
0
|
||||
} else {
|
||||
((w as f64 / aspect).round() as u32 / 2) * 2
|
||||
};
|
||||
let dims_label = format!("{w}x{height} @ {fps}fps");
|
||||
GifEstimate { width: w, fps, height, dims_label }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn make_request(target_bytes: u64, fps: u32, mode: GifBudgetMode) -> PreviewRequest {
|
||||
PreviewRequest {
|
||||
format: Format::Gif,
|
||||
fps,
|
||||
target_bytes,
|
||||
gif_budget_mode: mode,
|
||||
gif_dither: Some(GifDither::FloydSteinberg),
|
||||
gif_colors: Some(256),
|
||||
clip_width: 1920,
|
||||
clip_height: 1080,
|
||||
duration_secs: Some(5.0),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn estimate_balanced_matches_gif_params() {
|
||||
// The frontend uses estimate_gif_params for the on-screen dims label.
|
||||
// The backend uses gif_params for the actual encode. The two must agree.
|
||||
let req = make_request(8 * 1024 * 1024, 30, GifBudgetMode::Balanced);
|
||||
let est = estimate_gif_params(req);
|
||||
|
||||
let budget = encode::GifBudgetInput {
|
||||
gif_colors: 256,
|
||||
target_bytes: 8 * 1024 * 1024,
|
||||
fps: 30,
|
||||
duration_secs: 5.0,
|
||||
gif_budget_mode: GifBudgetMode::Balanced,
|
||||
};
|
||||
let (encode_w, encode_fps) = encode::gif_params(&budget, 1920, 1080);
|
||||
assert_eq!(est.width, encode_w);
|
||||
assert_eq!(est.fps, encode_fps);
|
||||
// height should be a multiple of 2 and within aspect
|
||||
assert_eq!(est.height % 2, 0);
|
||||
let expected_height = ((encode_w as f64 / (1920.0 / 1080.0)).round() as u32 / 2) * 2;
|
||||
assert_eq!(est.height, expected_height);
|
||||
// dims_label should be "{w}x{h} @ {fps}fps"
|
||||
assert_eq!(est.dims_label, format!("{}x{} @ {}fps", encode_w, est.height, encode_fps));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn estimate_zero_height_falls_back_aspect() {
|
||||
let mut req = make_request(1024, 30, GifBudgetMode::Balanced);
|
||||
req.clip_height = 0;
|
||||
let est = estimate_gif_params(req);
|
||||
// Should not panic and should produce some height
|
||||
assert!(est.height > 0 || est.width == 0);
|
||||
}
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
fn extract_thumbnails(
|
||||
state: State<'_, AppState>,
|
||||
@@ -771,6 +906,16 @@ const OVERLAY_BORDER_LOGICAL_PX: f64 = 4.0;
|
||||
const OVERLAY_TITLEBAR_LOGICAL_PX: f64 = 24.0;
|
||||
|
||||
|
||||
/// Remove temporary recording artifacts (segments, previews, thumbs).
|
||||
/// Called on app exit so a discarded clip doesn't linger in `temp/`.
|
||||
fn cleanup_temp_on_exit(app: &AppHandle) {
|
||||
let st = match app.try_state::<AppState>() {
|
||||
Some(s) => s,
|
||||
None => return,
|
||||
};
|
||||
clear_temp_segments(&st.app_dir);
|
||||
}
|
||||
|
||||
fn start_overlay_clickthrough_poll(app: AppHandle, shutdown: Arc<AtomicBool>) {
|
||||
use std::time::Duration;
|
||||
use windows::Win32::Foundation::{HWND, POINT};
|
||||
@@ -1525,7 +1670,13 @@ pub fn run() {
|
||||
}
|
||||
if check_on_launch {
|
||||
let handle = app.handle().clone();
|
||||
let app_dir = app.state::<AppState>().app_dir.clone();
|
||||
tauri::async_runtime::spawn(async move {
|
||||
// Skip the network call if we checked within the last 6 hours.
|
||||
if !updates::should_check(&app_dir, std::time::Duration::from_secs(6 * 3600)) {
|
||||
tracing::debug!("update check skipped (TTL not elapsed)");
|
||||
return;
|
||||
}
|
||||
match updates::check_for_update().await {
|
||||
Ok(Some(info)) => {
|
||||
tracing::info!(version = info.version, "update available");
|
||||
@@ -1534,6 +1685,9 @@ pub fn run() {
|
||||
Ok(None) => tracing::debug!("no update available"),
|
||||
Err(e) => tracing::warn!("update check failed: {e:#}"),
|
||||
}
|
||||
// Stamp success on Ok results so a future launch won't
|
||||
// re-check until the TTL elapses. Errors don't stamp.
|
||||
updates::stamp_check(&app_dir);
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
@@ -1549,12 +1703,14 @@ pub fn run() {
|
||||
start_capture,
|
||||
pause_capture,
|
||||
resume_capture,
|
||||
restart_audio_capture,
|
||||
stop_capture,
|
||||
export,
|
||||
default_output_path,
|
||||
extract_thumbnails,
|
||||
render_preview,
|
||||
render_raw_preview,
|
||||
estimate_gif_params,
|
||||
reveal_in_explorer,
|
||||
open_url,
|
||||
show_overlay,
|
||||
@@ -1577,6 +1733,7 @@ pub fn run() {
|
||||
if let Some(st) = _app.try_state::<AppState>() {
|
||||
st.overlay_poll_shutdown.store(true, Ordering::SeqCst);
|
||||
}
|
||||
cleanup_temp_on_exit(_app);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -93,6 +93,34 @@ pub fn pending_update_path(app_dir: &Path) -> PathBuf {
|
||||
app_dir.join("ByteSize.new.exe")
|
||||
}
|
||||
|
||||
fn last_check_path(app_dir: &Path) -> PathBuf {
|
||||
app_dir.join("temp").join("last-update-check")
|
||||
}
|
||||
|
||||
/// Returns true if the last successful update check happened more than `ttl`
|
||||
/// ago, or never. The stamp file's mtime is the source of truth.
|
||||
pub fn should_check(app_dir: &Path, ttl: std::time::Duration) -> bool {
|
||||
let path = last_check_path(app_dir);
|
||||
let Ok(meta) = std::fs::metadata(&path) else {
|
||||
return true;
|
||||
};
|
||||
let Ok(modified) = meta.modified() else {
|
||||
return true;
|
||||
};
|
||||
let Ok(elapsed) = modified.elapsed() else {
|
||||
return true;
|
||||
};
|
||||
elapsed > ttl
|
||||
}
|
||||
|
||||
pub fn stamp_check(app_dir: &Path) {
|
||||
let path = last_check_path(app_dir);
|
||||
if let Some(parent) = path.parent() {
|
||||
let _ = std::fs::create_dir_all(parent);
|
||||
}
|
||||
let _ = std::fs::write(&path, b"");
|
||||
}
|
||||
|
||||
pub fn has_pending_update(app_dir: &Path) -> bool {
|
||||
pending_update_path(app_dir).is_file()
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user