get the encoder work off the main thread and harden the update path

This commit is contained in:
2026-09-21 06:29:39 +03:00
parent af30963223
commit 205f68222c
7 changed files with 125 additions and 67 deletions
+22 -4
View File
@@ -343,8 +343,9 @@ fn extract_ffmpeg_from_7z(archive_path: &Path, dest: &Path) -> Result<()> {
let Some(src) = found else { let Some(src) = found else {
bail!("ffmpeg.exe not found inside the 7z archive"); bail!("ffmpeg.exe not found inside the 7z archive");
}; };
fs::copy(&src, dest).context("write ffmpeg.exe from 7z")?; install_from(dest, |staging| {
Ok(()) fs::copy(&src, staging).map(|_| ()).context("write ffmpeg.exe from 7z")
})
} }
fn find_ffmpeg_in(dir: &Path) -> Option<PathBuf> { fn find_ffmpeg_in(dir: &Path) -> Option<PathBuf> {
@@ -366,6 +367,21 @@ fn find_ffmpeg_in(dir: &Path) -> Option<PathBuf> {
None None
} }
/// Write `dest` through a sibling staging file and rename it into place. A
/// half-written ffmpeg.exe used to be left behind by a failed extraction, and
/// `check` reports any file at that path as ready - so every later encode failed
/// on a truncated binary with no way to tell it apart from a good install.
fn install_from(dest: &Path, write: impl FnOnce(&Path) -> Result<()>) -> Result<()> {
let staging = dest.with_extension("exe.part");
drop(fs::remove_file(&staging));
let staged = write(&staging)
.and_then(|()| fs::rename(&staging, dest).context("moving ffmpeg.exe into place"));
if staged.is_err() {
drop(fs::remove_file(&staging));
}
staged
}
fn extract_ffmpeg_from_zip(archive_path: &Path, dest: &Path) -> Result<()> { fn extract_ffmpeg_from_zip(archive_path: &Path, dest: &Path) -> Result<()> {
let file = File::open(archive_path).context("opening zip archive")?; let file = File::open(archive_path).context("opening zip archive")?;
let mut zip = zip::ZipArchive::new(file).context("open zip archive")?; let mut zip = zip::ZipArchive::new(file).context("open zip archive")?;
@@ -376,9 +392,11 @@ fn extract_ffmpeg_from_zip(archive_path: &Path, dest: &Path) -> Result<()> {
} }
let name = entry.name().to_string(); let name = entry.name().to_string();
if is_ffmpeg_entry(&name) { if is_ffmpeg_entry(&name) {
let mut out = File::create(dest).context("create ffmpeg.exe")?; return install_from(dest, |staging| {
let mut out = File::create(staging).context("create ffmpeg.exe")?;
io::copy(&mut entry, &mut out).context("write ffmpeg.exe from zip")?; io::copy(&mut entry, &mut out).context("write ffmpeg.exe from zip")?;
return Ok(()); Ok(())
});
} }
} }
bail!("ffmpeg.exe not found inside the zip archive"); bail!("ffmpeg.exe not found inside the zip archive");
+10 -1
View File
@@ -27,7 +27,14 @@ pub struct Config {
pub theme: Theme, pub theme: Theme,
} }
// Every persisted section carries a container-level `serde(default)`, so a
// config.toml written by an older build still loads once a field is added. The
// outer Config already defaulted its own fields; without the same treatment here
// a single unknown field made the whole file fail to parse, and the recovery
// path backs it up and rewrites defaults - losing the user's hotkeys and
// dropping them back into first-run.
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct ExportConfig { pub struct ExportConfig {
pub default_format: Format, pub default_format: Format,
pub gif_dither: GifDither, pub gif_dither: GifDither,
@@ -48,15 +55,16 @@ pub enum CaptureQuality {
} }
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct CaptureConfig { pub struct CaptureConfig {
pub default_fps: u32, pub default_fps: u32,
pub capture_cursor: bool, pub capture_cursor: bool,
pub capture_audio: bool, pub capture_audio: bool,
#[serde(default)]
pub capture_quality: CaptureQuality, pub capture_quality: CaptureQuality,
} }
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(default)]
pub struct HotkeyConfig { pub struct HotkeyConfig {
pub start: Option<String>, pub start: Option<String>,
pub stop: Option<String>, pub stop: Option<String>,
@@ -64,6 +72,7 @@ pub struct HotkeyConfig {
} }
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct UpdatesConfig { pub struct UpdatesConfig {
pub check_on_launch: bool, pub check_on_launch: bool,
} }
+15 -7
View File
@@ -369,6 +369,10 @@ fn clear_temp_segments(app_dir: &Path, keep_previews: bool) {
if (name.starts_with("segment-") && has_ext(name, "mp4")) if (name.starts_with("segment-") && has_ext(name, "mp4"))
|| (name.starts_with("audio-") && has_ext(name, "pcm")) || (name.starts_with("audio-") && has_ext(name, "pcm"))
|| (name.starts_with("preview-palette-") && has_ext(name, "png")) || (name.starts_with("preview-palette-") && has_ext(name, "png"))
// Two-pass stats, named ffmpeg2pass-0.log and its .mbtree
// sibling. cleanup_pass_logs only runs on a successful
// encode, so a cancelled one left them here forever.
|| name.starts_with("ffmpeg2pass")
|| padtmp || padtmp
{ {
drop(std::fs::remove_file(entry.path())); drop(std::fs::remove_file(entry.path()));
@@ -622,7 +626,7 @@ fn start_capture(
Ok(()) Ok(())
} }
#[tauri::command] #[tauri::command(async)]
fn pause_capture(state: State<'_, AppState>) -> Result<(), String> { fn pause_capture(state: State<'_, AppState>) -> Result<(), String> {
let session = lock(&state.capture) let session = lock(&state.capture)
.take() .take()
@@ -760,7 +764,7 @@ fn restart_audio_capture(
clippy::too_many_lines, clippy::too_many_lines,
reason = "one recording-finalisation transaction; the steps share session state and temp paths" reason = "one recording-finalisation transaction; the steps share session state and temp paths"
)] )]
#[tauri::command] #[tauri::command(async)]
fn stop_capture(state: State<'_, AppState>) -> Result<RecordedClip, String> { fn stop_capture(state: State<'_, AppState>) -> Result<RecordedClip, String> {
let mut ss = lock(&state.session) let mut ss = lock(&state.session)
.take() .take()
@@ -955,7 +959,7 @@ pub struct PreviewRequest {
pub duration_secs: Option<f64>, pub duration_secs: Option<f64>,
} }
#[tauri::command] #[tauri::command(async)]
fn render_preview( fn render_preview(
state: State<'_, AppState>, state: State<'_, AppState>,
request: PreviewRequest, request: PreviewRequest,
@@ -1138,6 +1142,8 @@ mod tests {
"audio-001.pcm", "audio-001.pcm",
"preview.png", "preview.png",
"raw-preview.png", "raw-preview.png",
"ffmpeg2pass-0.log",
"ffmpeg2pass-0.log.mbtree",
] { ] {
std::fs::write(temp.join(name), b"x").unwrap(); std::fs::write(temp.join(name), b"x").unwrap();
} }
@@ -1147,6 +1153,8 @@ mod tests {
assert!(!temp.join("audio-concat.pcm.padtmp").exists(), "padtmp should be swept"); assert!(!temp.join("audio-concat.pcm.padtmp").exists(), "padtmp should be swept");
assert!(!temp.join("segment-001.mp4").exists()); assert!(!temp.join("segment-001.mp4").exists());
assert!(!temp.join("audio-001.pcm").exists()); assert!(!temp.join("audio-001.pcm").exists());
assert!(!temp.join("ffmpeg2pass-0.log").exists(), "pass stats should be swept");
assert!(!temp.join("ffmpeg2pass-0.log.mbtree").exists());
assert!(temp.join("preview.png").exists(), "preview must survive a new capture"); assert!(temp.join("preview.png").exists(), "preview must survive a new capture");
assert!(temp.join("raw-preview.png").exists()); assert!(temp.join("raw-preview.png").exists());
@@ -1192,7 +1200,7 @@ mod tests {
} }
} }
#[tauri::command] #[tauri::command(async)]
fn extract_thumbnails( fn extract_thumbnails(
state: State<'_, AppState>, state: State<'_, AppState>,
fps: u32, fps: u32,
@@ -1209,7 +1217,7 @@ fn extract_thumbnails(
.map_err(|e| format!("{e:#}")) .map_err(|e| format!("{e:#}"))
} }
#[tauri::command] #[tauri::command(async)]
fn render_raw_preview( fn render_raw_preview(
state: State<'_, AppState>, state: State<'_, AppState>,
timestamp: f64, timestamp: f64,
@@ -1889,7 +1897,7 @@ fn read_log_tail(log_dir: &Path) -> String {
String::from_utf8_lossy(data.get(start..).unwrap_or_default()).into_owned() String::from_utf8_lossy(data.get(start..).unwrap_or_default()).into_owned()
} }
#[tauri::command] #[tauri::command(async)]
fn diagnostics_info(state: State<'_, AppState>) -> DiagnosticsInfo { fn diagnostics_info(state: State<'_, AppState>) -> DiagnosticsInfo {
let log_dir = state.app_dir.join("logs"); let log_dir = state.app_dir.join("logs");
let log_tail = read_log_tail(&log_dir); let log_tail = read_log_tail(&log_dir);
@@ -1936,7 +1944,7 @@ fn cancel_export(state: State<'_, AppState>) {
state.export_cancel.store(true, Ordering::SeqCst); state.export_cancel.store(true, Ordering::SeqCst);
} }
#[tauri::command] #[tauri::command(async)]
/// Tauri deserializes the return into a JS Result, so the wrapper stays even /// Tauri deserializes the return into a JS Result, so the wrapper stays even
/// though there is no failure path. /// though there is no failure path.
#[allow( #[allow(
+18 -2
View File
@@ -1,12 +1,17 @@
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use anyhow::{Context, Result}; use anyhow::{bail, Context, Result};
use futures_util::StreamExt; use futures_util::StreamExt;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
const GITEA_LATEST: &str = const GITEA_LATEST: &str =
"https://git.lashman.live/api/v1/repos/lashman/bytesize/releases/latest"; "https://git.lashman.live/api/v1/repos/lashman/bytesize/releases/latest";
/// Everything the updater will fetch has to live under this prefix. The download
/// URL arrives from the frontend, and an unconstrained one there would let
/// anything that can reach the webview hand the app a new executable to install.
const UPDATE_ORIGIN: &str = "https://git.lashman.live/";
#[derive(Debug, Clone, Serialize)] #[derive(Debug, Clone, Serialize)]
pub(crate) struct UpdateInfo { pub(crate) struct UpdateInfo {
pub version: String, pub version: String,
@@ -37,7 +42,14 @@ pub(crate) async fn check_for_update() -> Result<Option<UpdateInfo>> {
.build()?; .build()?;
let resp = client.get(GITEA_LATEST).send().await?; let resp = client.get(GITEA_LATEST).send().await?;
if !resp.status().is_success() { if !resp.status().is_success() {
tracing::debug!("update check returned status {}", resp.status()); // A 404 means the endpoint itself is wrong or the repo has no releases -
// not that the app is up to date, which is how it reads if this is only
// ever a debug line.
if resp.status() == reqwest::StatusCode::NOT_FOUND {
tracing::warn!("no release published at {GITEA_LATEST}");
} else {
tracing::warn!("update check returned status {}", resp.status());
}
return Ok(None); return Ok(None);
} }
let body = resp.text().await?; let body = resp.text().await?;
@@ -69,6 +81,10 @@ where
{ {
use std::io::Write; use std::io::Write;
if !url.starts_with(UPDATE_ORIGIN) {
bail!("refusing to download an update from {url}");
}
if let Some(parent) = dest.parent() { if let Some(parent) = dest.parent() {
std::fs::create_dir_all(parent).context("creating update parent dir")?; std::fs::create_dir_all(parent).context("creating update parent dir")?;
} }
+19 -28
View File
@@ -149,16 +149,17 @@
}) })
onMount(() => { onMount(() => {
let unlistenHotkey: (() => void) | null = null const unlisten: (() => void)[] = []
let unlistenProgress: (() => void) | null = null // Registered one at a time rather than through a single Promise.all: one
let unlistenAudio: (() => void) | null = null // rejected registration used to lose the whole batch, which left every
let unlistenAudioRecovered: (() => void) | null = null // listener live and none of them removable - hotkeys included.
let unlistenOverlayClosed: (() => void) | null = null const keep = (p: Promise<() => void>) => {
void p.then(fn => unlisten.push(fn))
.catch(e => console.warn("could not register a listener:", e))
}
void (async () => { keep(listen("overlay-closed", () => { useFrame = false }))
const [overlayClosed, hotkey, progress, audio, audioRecovered] = await Promise.all([ keep(api.onHotkey((kind) => {
listen("overlay-closed", () => { useFrame = false }),
api.onHotkey((kind) => {
if (kind === "start" && phase === "idle") void startRec() if (kind === "start" && phase === "idle") void startRec()
else if (kind === "pause") { else if (kind === "pause") {
if (phase === "recording") void pauseRec() if (phase === "recording") void pauseRec()
@@ -166,21 +167,16 @@
} else if (kind === "stop") { } else if (kind === "stop") {
if (phase === "recording" || phase === "paused") void stopRec() if (phase === "recording" || phase === "paused") void stopRec()
} }
}), }))
api.onEncodeProgress((p) => { keep(api.onEncodeProgress((p) => {
encodeProgress = { pass: p.pass, total: p.total_passes, pct: p.percent } encodeProgress = { pass: p.pass, total: p.total_passes, pct: p.percent }
}), }))
api.onAudioFailed((msg) => { keep(api.onAudioFailed((msg) => {
audioWarning = msg || "audio capture failed - audio will not be recorded" audioWarning = msg || "audio capture failed - audio will not be recorded"
}), }))
listen("audio-recovered", () => { audioWarning = null }), keep(listen("audio-recovered", () => { audioWarning = null }))
])
unlistenOverlayClosed = overlayClosed
unlistenHotkey = hotkey
unlistenProgress = progress
unlistenAudio = audio
unlistenAudioRecovered = audioRecovered
void (async () => {
try { try {
config = await api.getConfig() config = await api.getConfig()
format = config.export.default_format format = config.export.default_format
@@ -191,13 +187,8 @@
console.warn("failed to load config:", e) console.warn("failed to load config:", e)
} }
})() })()
return () => {
unlistenHotkey?.() return () => { unlisten.forEach(fn => fn()) }
unlistenProgress?.()
unlistenAudio?.()
unlistenAudioRecovered?.()
unlistenOverlayClosed?.()
}
}) })
// ---- Actions ---- // ---- Actions ----
+17 -6
View File
@@ -11,7 +11,15 @@
onMount(() => { onMount(() => {
const win = getCurrentWebviewWindow() const win = getCurrentWebviewWindow()
let unlisten: (() => void)[] = [] const unlisten: (() => void)[] = []
let hoverDebounce = 0
// A registration that lands after the window is gone still has to
// unregister, so a late unlisten runs immediately rather than being dropped.
const keep = (p: Promise<() => void>) => {
void p.then(fn => { if (mounted) unlisten.push(fn); else fn() })
.catch(e => console.warn("could not register a listener:", e))
}
const refresh = async () => { const refresh = async () => {
scale = await win.scaleFactor() scale = await win.scaleFactor()
@@ -20,18 +28,21 @@
} }
void (async () => { void (async () => {
try {
await refresh() await refresh()
win.onMoved(refresh).then(fn => { if (mounted) unlisten.push(fn) }) } catch (e) {
.catch(e => console.warn("could not watch the picker window position:", e)) console.warn("could not read the picker window geometry:", e)
let hoverDebounce = 0 }
listen<Rect>("picker-hover", (e) => { keep(win.onMoved(refresh))
keep(listen<Rect>("picker-hover", (e) => {
clearTimeout(hoverDebounce) clearTimeout(hoverDebounce)
hoverDebounce = window.setTimeout(() => { hover = e.payload }, 30) hoverDebounce = window.setTimeout(() => { hover = e.payload }, 30)
}).then(fn => { if (mounted) unlisten.push(fn) }) }))
})() })()
return () => { return () => {
mounted = false mounted = false
clearTimeout(hoverDebounce)
unlisten.forEach(fn => fn()) unlisten.forEach(fn => fn())
emit("picker-cancel", {}).catch(() => {}) emit("picker-cancel", {}).catch(() => {})
} }
+13 -8
View File
@@ -9,14 +9,19 @@
let errMsg: string | null = $state(null) let errMsg: string | null = $state(null)
onMount(() => { onMount(() => {
let unlistenInfo: (() => void) | null = null const unlisten: (() => void)[] = []
let unlistenProg: (() => void) | null = null const keep = (p: Promise<() => void>) => {
void (async () => { void p.then(fn => unlisten.push(fn))
unlistenInfo = await api.onUpdateAvailable((i) => { info = i; phase = "info" }) .catch(e => console.warn("could not register an update listener:", e))
unlistenProg = await api.onUpdateDownloadProgress((p) => { progress = p }) }
if (await api.pendingUpdate()) phase = "ready"
})() keep(api.onUpdateAvailable((i) => { info = i; phase = "info" }))
return () => { unlistenInfo?.(); unlistenProg?.() } keep(api.onUpdateDownloadProgress((p) => { progress = p }))
void api.pendingUpdate()
.then(pending => { if (pending) phase = "ready" })
.catch(e => console.warn("could not read the pending update state:", e))
return () => { unlisten.forEach(fn => fn()) }
}) })
function dismiss() { info = null; errMsg = null; phase = "info" } function dismiss() { info = null; errMsg = null; phase = "info" }