keep recording audio and video in sync

This commit is contained in:
2026-09-28 20:14:00 +03:00
parent 730b8df0fe
commit 99ff7fc5e2
8 changed files with 713 additions and 590 deletions
+259 -300
View File
@@ -20,6 +20,7 @@ mod capture;
mod clicks;
mod config;
mod encode;
mod timed_video;
mod updates;
mod window_picker;
mod windows_list;
@@ -28,7 +29,7 @@ use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use anyhow::{anyhow, Context as _, Result};
use anyhow::{anyhow, Result};
use serde::{Deserialize, Serialize};
use std::str::FromStr;
use tauri::{AppHandle, Emitter, Manager, State};
@@ -36,7 +37,7 @@ use tauri_plugin_global_shortcut::{GlobalShortcutExt, Shortcut, ShortcutState};
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt, EnvFilter};
use crate::bootstrap::FfmpegStatus;
use crate::config::{Config, Format, GifBudgetMode, GifDither};
use crate::config::{CaptureConfig, CaptureQuality, Config, Format, GifBudgetMode, GifDither};
fn lock<T>(m: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
m.lock().unwrap_or_else(|e| {
@@ -57,17 +58,17 @@ pub struct AppState {
pub app_dir: PathBuf,
pub config: Mutex<Config>,
pub capture: Mutex<Option<capture::CaptureSession>>,
pub audio: Mutex<Option<audio::AudioSession>>,
audio: Mutex<Option<ActiveAudio>>,
pub click_recorder: Mutex<Option<clicks::ClickRecorder>>,
pub last_clip: Mutex<Option<RecordedClip>>,
unexported_clip: AtomicBool,
pub session: Mutex<Option<SessionState>>,
capture_transition: Mutex<()>,
pub picker: Mutex<Option<window_picker::PickerSession>>,
pub overlay_poll_shutdown: Arc<AtomicBool>,
pub export_cancel: Arc<AtomicBool>,
/// Held for the duration of an export. Without it a second export could
/// start while the first was still encoding, and its reset of the shared
/// cancel flag would revive the run the user had just cancelled.
pub exporting: Arc<AtomicBool>,
thumbnail_operation: Mutex<()>,
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.
@@ -77,12 +78,13 @@ pub struct AppState {
pub struct SessionState {
pub segments: Vec<PathBuf>,
pub audio_segments: Vec<PathBuf>,
pub audio_sample_rate: Option<u32>,
pub audio_channels: Option<u16>,
audio_segments: Vec<encode::AudioSegment>,
next_audio_index: usize,
pub total_recorded_secs: f64,
pub capture_cursor: bool,
pub audio: bool,
rate_limit: Option<u32>,
quality: CaptureQuality,
pub crop: Option<CaptureRect>,
pub width: u32,
pub height: u32,
@@ -90,11 +92,14 @@ pub struct SessionState {
pub monitor_height: u32,
pub clicks: Vec<clicks::Click>,
pub segment_start_offsets: Vec<f64>,
/// Wall-clock time the first video segment began. Used to align the head
/// of the audio track (which starts a little later due to WASAPI init).
pub video_started_at: Option<std::time::Instant>,
/// Wall-clock time the first audio segment began capturing.
pub audio_started_at: Option<std::time::Instant>,
}
impl AppState {
fn begin_capture_transition(&self) -> Result<std::sync::MutexGuard<'_, ()>, String> {
self.capture_transition
.try_lock()
.map_err(|_| "a capture operation is already in progress".to_string())
}
}
#[derive(Debug, Clone, Serialize)]
@@ -294,7 +299,10 @@ async fn download_update(
)]
#[tauri::command]
fn apply_update(app: AppHandle, state: State<'_, AppState>) -> Result<(), String> {
if lock(&state.session).is_some() || state.exporting.load(Ordering::SeqCst)
if state.capture_transition.try_lock().is_err()
|| lock(&state.session).is_some()
|| state.exporting.load(Ordering::SeqCst)
|| state.unexported_clip.load(Ordering::Relaxed)
{
return Err("finish or discard the current recording before applying the update".to_string());
}
@@ -323,6 +331,7 @@ async fn download_ffmpeg(app: AppHandle, state: State<'_, AppState>) -> Result<(
#[derive(Debug, Deserialize)]
pub struct StartCaptureRequest {
pub crop: Option<CaptureRect>,
pub options: Option<CaptureConfig>,
}
fn segment_path(app_dir: &Path, idx: usize) -> PathBuf {
@@ -356,7 +365,9 @@ fn clear_temp_segments(app_dir: &Path, keep_previews: bool) {
// The padtmp files carry a double extension, so they are matched
// on the whole name rather than through Path::extension.
let padtmp = name.to_ascii_lowercase().ends_with(".pcm.padtmp");
if (name.starts_with("segment-") && has_ext(name, "mp4"))
if ((name.starts_with("segment-") || name.starts_with("preview-edit-")
|| name.starts_with("recording-")) && has_ext(name, "mp4"))
|| (name.starts_with("output-review-") && ["gif", "webm", "mp4"].iter().any(|ext| has_ext(name, ext)))
|| (name.starts_with("audio-") && has_ext(name, "pcm"))
|| (name.starts_with("preview-palette-") && has_ext(name, "png"))
// Two-pass stats, named ffmpeg2pass-0.log and its .mbtree
@@ -383,111 +394,57 @@ fn clear_temp_segments(app_dir: &Path, keep_previews: bool) {
}
}
/// Pad or trim a raw f32le PCM file so its duration matches `target_secs`.
fn adjust_audio_length(
path: &Path,
sample_rate: u32,
channels: u16,
target_secs: f64,
) -> Result<()> {
use std::io::Write;
let bytes_per_sec = f64::from(sample_rate) * f64::from(channels) * 4.0;
let target_bytes = encode::round_u64(target_secs * bytes_per_sec);
let current_bytes = std::fs::metadata(path)?.len();
if current_bytes == target_bytes {
return Ok(());
}
if current_bytes < target_bytes {
let mut file = std::fs::OpenOptions::new().append(true).open(path)?;
let zeros = vec![0u8; 64 * 1024];
let mut remaining = target_bytes - current_bytes;
while remaining > 0 {
// zeros.len() is 64KiB, so both directions are lossless here.
let chunk = u64::try_from(zeros.len()).unwrap_or(u64::MAX);
let to_write = usize::try_from(remaining.min(chunk))
.unwrap_or(zeros.len())
.min(zeros.len());
// to_write was clamped to zeros.len() just above.
file.write_all(zeros.get(..to_write).unwrap_or_default())?;
remaining -= u64::try_from(to_write).unwrap_or(0);
}
} else {
let file = std::fs::OpenOptions::new().write(true).open(path)?;
file.set_len(target_bytes)?;
}
Ok(())
struct ActiveAudio {
session: audio::AudioSession,
start_secs: f64,
}
/// 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::Write;
let bytes_per_sec = f64::from(sample_rate) * f64::from(channels) * 4.0;
let pad_bytes = encode::round_u64(head_secs * bytes_per_sec);
if pad_bytes == 0 {
return Ok(());
}
let temp = path.with_extension("pcm.padtmp");
{
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 {
// zeros.len() is 64KiB, so both directions are lossless here.
let chunk = u64::try_from(zeros.len()).unwrap_or(u64::MAX);
let to_write = usize::try_from(remaining.min(chunk))
.unwrap_or(zeros.len())
.min(zeros.len());
// to_write was clamped to zeros.len() just above.
out.write_all(zeros.get(..to_write).unwrap_or_default())?;
remaining -= u64::try_from(to_write).unwrap_or(0);
impl ActiveAudio {
fn stop(self, end_secs: f64) -> encode::AudioSegment {
let sample_rate = self.session.sample_rate;
let channels = self.session.channels;
encode::AudioSegment {
path: self.session.stop(),
sample_rate,
channels,
start_secs: self.start_secs,
end_secs,
}
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()?;
}
// 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)?;
drop(std::fs::remove_file(&temp));
}
tracing::debug!(
"padded audio head with {:.1}ms ({} bytes) of silence",
head_secs * 1000.0,
pad_bytes
);
Ok(())
}
fn try_start_audio(
app: &AppHandle,
enabled: bool,
audio_path: PathBuf,
) -> Option<audio::AudioSession> {
if !enabled {
return None;
}
match audio::start(audio_path) {
Ok(s) => Some(s),
video_started_at: std::time::Instant,
segment_start_secs: f64,
) -> Option<ActiveAudio> {
let handle = app.clone();
match audio::start(audio_path, move |status| match status {
Ok(()) => drop(handle.emit("audio-recovered", ())),
Err(message) => drop(handle.emit("audio-failed", message)),
}) {
Ok(session) => {
let start_secs = segment_start_secs
+ session
.started_at
.saturating_duration_since(video_started_at)
.as_secs_f64();
Some(ActiveAudio { session, start_secs })
}
Err(e) => {
tracing::warn!("audio capture failed: {e:#}");
drop(app.emit("audio-failed", e.to_string()));
drop(app.emit("audio-failed", format!("{e:#}")));
None
}
}
}
fn finish_audio(state: &AppState, end_secs: f64) -> Option<encode::AudioSegment> {
let audio = lock(&state.audio).take()?;
Some(audio.stop(end_secs))
}
fn start_click_recorder(enabled: bool) -> Option<clicks::ClickRecorder> {
if enabled {
Some(clicks::start())
@@ -496,69 +453,31 @@ 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, and keep the
// pcm it already wrote: stop_capture muxes whatever is in
// audio_segments, so discarding the path here threw away
// everything captured before the device went away.
let path = session.stop();
{
let st = app.state::<AppState>();
let mut slot = lock(&st.session);
if let Some(ss) = slot.as_mut() {
ss.audio_segments.push(path);
}
}
drop(app.emit(
"audio-failed",
"audio device lost - endpoint changed or was unplugged".to_string(),
));
}
return;
}
});
}
#[tauri::command]
fn start_capture(
app: AppHandle,
state: State<'_, AppState>,
request: Option<StartCaptureRequest>,
) -> Result<(), String> {
let _transition = state.begin_capture_transition()?;
if state.exporting.load(Ordering::SeqCst) {
return Err("wait for the current output operation".to_string());
}
{
let slot = lock(&state.capture);
if slot.is_some() {
return Err("a capture is already running".to_string());
}
}
let cfg = lock(&state.config).clone();
let options = request.as_ref().and_then(|request| request.options.clone())
.unwrap_or_else(|| lock(&state.config).capture.clone());
let rate_limit = options.limit_capture_fps.then(|| options.default_fps.clamp(1, 60));
let temp = temp_dir(&state.app_dir);
std::fs::create_dir_all(&temp).map_err(|e| format!("creating temp dir: {e:#}"))?;
let _thumbnails = state.thumbnail_operation.try_lock()
.map_err(|_| "wait for thumbnail generation to finish".to_string())?;
*lock(&state.last_clip) = None;
state.unexported_clip.store(false, Ordering::Relaxed);
clear_temp_segments(&state.app_dir, true);
let crop = request.as_ref().and_then(|r| r.crop);
@@ -574,46 +493,42 @@ fn start_capture(
let session = capture::start(
output,
ffmpeg,
cfg.capture.capture_cursor,
options.capture_cursor,
crop,
cfg.capture.limit_capture_fps.then_some(cfg.capture.default_fps),
cfg.capture.capture_quality,
rate_limit,
options.capture_quality,
)
.map_err(|e| format!("{e:#}"))?;
let audio_path = audio_segment_path(&state.app_dir, 1);
let audio_session = try_start_audio(&app, cfg.capture.capture_audio, audio_path);
let (a_sr, a_ch) = audio_session
.as_ref()
.map_or((None, None), |s| (Some(s.sample_rate), Some(s.channels)));
let audio_session = if options.capture_audio {
let path = audio_segment_path(&state.app_dir, 1);
try_start_audio(&app, path, session.started_at, 0.0)
} else {
None
};
let session_state = SessionState {
segments: Vec::new(),
audio_segments: Vec::new(),
audio_sample_rate: a_sr,
audio_channels: a_ch,
next_audio_index: 2,
total_recorded_secs: 0.0,
capture_cursor: cfg.capture.capture_cursor,
audio: cfg.capture.capture_audio,
crop,
capture_cursor: options.capture_cursor,
audio: options.capture_audio,
rate_limit,
quality: options.capture_quality,
crop: session.crop,
width: session.width,
height: session.height,
monitor_width: monitor_w,
monitor_height: monitor_h,
clicks: Vec::new(),
segment_start_offsets: vec![0.0],
video_started_at: Some(session.started_at),
audio_started_at: audio_session.as_ref().map(|a| a.started_at),
};
let click_rec = start_click_recorder(cfg.capture.capture_cursor);
let click_rec = start_click_recorder(options.capture_cursor);
*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(())
@@ -621,24 +536,19 @@ fn start_capture(
#[tauri::command(async)]
fn pause_capture(state: State<'_, AppState>) -> Result<(), String> {
let _transition = state.begin_capture_transition()?;
let session = lock(&state.capture)
.take()
.ok_or_else(|| "no capture in progress".to_string())?;
let elapsed = session.started_at.elapsed().as_secs_f64();
let frames = session.frame_counter.load(Ordering::Relaxed);
let pipe_fps = session.pipe_fps;
let raw_path = session.stop().map_err(|e| format!("{e:#}"))?;
let ffmpeg = bootstrap::ffmpeg_path(&state.app_dir);
let fixed_path = raw_path.with_extension("fixed.mp4");
capture::fix_intermediate_fps(&ffmpeg, &raw_path, &fixed_path, elapsed, frames, pipe_fps)
.map_err(|e| format!("fixing fps: {e:#}"))?;
let path = if fixed_path.exists() {
fixed_path
} else {
raw_path
};
let audio_path = lock(&state.audio).take().map(audio::AudioSession::stop);
let end = std::time::Instant::now();
session.mark_stopped_at(end);
let elapsed = end.saturating_duration_since(session.started_at).as_secs_f64();
let previously_recorded = lock(&state.session)
.as_ref()
.ok_or_else(|| "no session state".to_string())?
.total_recorded_secs;
let audio = finish_audio(&state, previously_recorded + elapsed);
let path = session.stop().map_err(|e| format!("{e:#}"))?;
let new_clicks: Vec<clicks::Click> = lock(&state.click_recorder)
.take()
@@ -655,8 +565,8 @@ fn pause_capture(state: State<'_, AppState>) -> Result<(), String> {
});
}
ss.segments.push(path);
if let Some(ap) = audio_path {
ss.audio_segments.push(ap);
if let Some(audio) = audio {
ss.audio_segments.push(audio);
}
ss.total_recorded_secs += elapsed;
ss.segment_start_offsets.push(ss.total_recorded_secs);
@@ -665,27 +575,32 @@ fn pause_capture(state: State<'_, AppState>) -> Result<(), String> {
#[tauri::command]
fn resume_capture(app: AppHandle, state: State<'_, AppState>) -> Result<(), String> {
let _transition = state.begin_capture_transition()?;
{
let slot = lock(&state.capture);
if slot.is_some() {
return Err("a capture is already running".to_string());
}
}
let (capture_cursor, audio, crop, next_idx) = {
let ss = lock(&state.session);
let (capture_cursor, audio, crop, next_idx, audio_idx, segment_start_secs, rate_limit, quality) = {
let mut ss = lock(&state.session);
let ss = ss
.as_ref()
.as_mut()
.ok_or_else(|| "no session to resume".to_string())?;
(ss.capture_cursor, ss.audio, ss.crop, ss.segments.len() + 1)
};
let (rate_limit, quality) = {
let c = lock(&state.config);
let audio_idx = ss.next_audio_index;
ss.next_audio_index += 1;
(
c.capture.limit_capture_fps.then_some(c.capture.default_fps),
c.capture.capture_quality,
ss.capture_cursor,
ss.audio,
ss.crop,
ss.segments.len() + 1,
audio_idx,
ss.total_recorded_secs,
ss.rate_limit,
ss.quality,
)
};
let output = segment_path(&state.app_dir, next_idx);
let ffmpeg = bootstrap::ffmpeg_path(&state.app_dir);
if !ffmpeg.is_file() {
@@ -694,14 +609,15 @@ fn resume_capture(app: AppHandle, state: State<'_, AppState>) -> Result<(), Stri
let session = capture::start(output, ffmpeg, capture_cursor, crop, rate_limit, quality)
.map_err(|e| format!("{e:#}"))?;
let audio_path = audio_segment_path(&state.app_dir, next_idx);
let audio_session = try_start_audio(&app, audio, audio_path);
let audio_session = if audio {
let path = audio_segment_path(&state.app_dir, audio_idx);
try_start_audio(&app, path, session.started_at, segment_start_secs)
} else {
None
};
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(())
@@ -713,79 +629,54 @@ fn resume_capture(app: AppHandle, state: State<'_, AppState>) -> Result<(), Stri
/// 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 _transition = state.begin_capture_transition()?;
let started_at = lock(&state.capture)
.as_ref()
.ok_or_else(|| "resume recording before retrying audio".to_string())?
.started_at;
let (next_idx, segment_start_secs) = {
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() {
ss.audio_segments.push(a.stop());
if !ss.audio {
return Err("audio is not enabled for this recording".to_string());
}
ss.audio_segments.len() + 1
let end_secs = ss.total_recorded_secs + started_at.elapsed().as_secs_f64();
if let Some(audio) = finish_audio(&state, end_secs) {
ss.audio_segments.push(audio);
}
let next_idx = ss.next_audio_index;
ss.next_audio_index += 1;
(next_idx, ss.total_recorded_secs)
};
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 {
drop(app.emit("audio-recovered", ()));
}
let audio = try_start_audio(&app, audio_path, started_at, segment_start_secs);
*lock(&state.audio) = audio;
Ok(())
}
// Finalising a recording is one transaction: stop the live sessions, fix each
// segment's timestamps, concatenate, pad and mux the audio, and hand back the
// clip. The steps share `ss` and the temp paths throughout.
#[allow(
clippy::too_many_lines,
reason = "one recording-finalisation transaction; the steps share session state and temp paths"
)]
#[tauri::command(async)]
fn stop_capture(state: State<'_, AppState>) -> Result<RecordedClip, String> {
let _transition = state.begin_capture_transition()?;
let mut ss = lock(&state.session)
.take()
.ok_or_else(|| "no session to stop".to_string())?;
let live = lock(&state.capture).take();
if let Some(session) = live {
let elapsed = session.started_at.elapsed().as_secs_f64();
let frames = session.frame_counter.load(Ordering::Relaxed);
let pipe_fps = session.pipe_fps;
let raw_path = session.stop().map_err(|e| format!("{e:#}"))?;
let ffmpeg = bootstrap::ffmpeg_path(&state.app_dir);
let fixed_path = raw_path.with_extension("fixed.mp4");
capture::fix_intermediate_fps(&ffmpeg, &raw_path, &fixed_path, elapsed, frames, pipe_fps)
.map_err(|e| format!("fixing fps: {e:#}"))?;
let final_path = if fixed_path.exists() {
fixed_path
} else {
raw_path
};
ss.segments.push(final_path);
ss.total_recorded_secs += elapsed;
}
let live_audio = lock(&state.audio).take();
if let Some(a) = live_audio {
ss.audio_segments.push(a.stop());
let end = std::time::Instant::now();
session.mark_stopped_at(end);
ss.total_recorded_secs += end.saturating_duration_since(session.started_at).as_secs_f64();
if let Some(audio) = finish_audio(&state, ss.total_recorded_secs) {
ss.audio_segments.push(audio);
}
ss.segments.push(session.stop().map_err(|e| format!("{e:#}"))?);
}
let live_clicks = lock(&state.click_recorder)
@@ -805,7 +696,7 @@ fn stop_capture(state: State<'_, AppState>) -> Result<RecordedClip, String> {
}
let temp = temp_dir(&state.app_dir);
let final_path = temp.join("recording.mp4");
let final_path = temp.join(format!("recording-{}.mp4", timestamp_slug()));
let ffmpeg = bootstrap::ffmpeg_path(&state.app_dir);
let video_concat = if ss.segments.len() == 1 {
@@ -823,33 +714,15 @@ fn stop_capture(state: State<'_, AppState>) -> Result<RecordedClip, String> {
vc
};
// Bind the audio format here instead of unwrapping at each use below; the
// if-let is the same condition previous `is_some()` checks encoded.
if let (false, Some(sample_rate), Some(channels)) = (
ss.audio_segments.is_empty(),
ss.audio_sample_rate,
ss.audio_channels,
) {
if !ffmpeg.is_file() {
return Err("ffmpeg.exe not found for audio mux".to_string());
}
let audio_concat = temp.join("audio-concat.pcm");
encode::concat_pcm(&ss.audio_segments, &audio_concat)
.map_err(|e| format!("audio concat: {e:#}"))?;
// Pad the head with silence so the audio track starts at the same
// wall-clock moment the video did. WASAPI init + Start adds a delay
// between the capture session start and the first audio packet.
if let (Some(video_start), Some(audio_start)) = (ss.video_started_at, ss.audio_started_at) {
if audio_start > video_start {
let head_offset_secs = audio_start.duration_since(video_start).as_secs_f64();
if head_offset_secs > 0.001 {
pad_audio_head(&audio_concat, sample_rate, channels, head_offset_secs)
.map_err(|e| format!("padding audio head: {e:#}"))?;
}
}
}
adjust_audio_length(&audio_concat, sample_rate, channels, ss.total_recorded_secs)
.map_err(|e| format!("adjusting audio length: {e:#}"))?;
let audio_concat = temp.join("audio-concat.pcm");
let audio_format = encode::assemble_pcm(
&ffmpeg,
&ss.audio_segments,
&audio_concat,
ss.total_recorded_secs,
)
.map_err(|e| format!("assembling audio: {e:#}"))?;
if let Some((sample_rate, channels)) = audio_format {
encode::mux_with_audio(
&ffmpeg,
&video_concat,
@@ -862,10 +735,6 @@ fn stop_capture(state: State<'_, AppState>) -> Result<RecordedClip, String> {
if video_concat != final_path {
drop(std::fs::remove_file(&video_concat));
}
drop(std::fs::remove_file(&audio_concat));
for ap in &ss.audio_segments {
drop(std::fs::remove_file(ap));
}
} else {
// No audio to mux. `video_concat` is either the one segment or the
// concat output, and `final_path` is always recording.mp4, so it always
@@ -875,6 +744,10 @@ fn stop_capture(state: State<'_, AppState>) -> Result<RecordedClip, String> {
.map_err(|e| format!("finalizing: {e:#}"))?;
drop(std::fs::remove_file(&video_concat));
}
drop(std::fs::remove_file(&audio_concat));
for audio in &ss.audio_segments {
drop(std::fs::remove_file(&audio.path));
}
let clip = RecordedClip {
temp_path: final_path,
@@ -887,9 +760,21 @@ fn stop_capture(state: State<'_, AppState>) -> Result<RecordedClip, String> {
clicks: ss.clicks.clone(),
};
*lock(&state.last_clip) = Some(clip.clone());
state.unexported_clip.store(true, Ordering::Relaxed);
Ok(clip)
}
#[tauri::command]
fn discard_clip(state: State<'_, AppState>) -> Result<(), String> {
let _transition = state.begin_capture_transition()?;
if state.exporting.load(Ordering::SeqCst) {
return Err("wait for the current preview or export".to_string());
}
*lock(&state.last_clip) = None;
state.unexported_clip.store(false, Ordering::Relaxed);
Ok(())
}
#[derive(Debug, Deserialize)]
pub struct ExportRequest {
pub format: Format,
@@ -1230,6 +1115,7 @@ mod tests {
#[tauri::command(async)]
fn extract_thumbnails(state: State<'_, AppState>, fps: u32) -> Result<Vec<PathBuf>, String> {
let _thumbnails = lock(&state.thumbnail_operation);
let clip = lock(&state.last_clip)
.clone()
.ok_or_else(|| "no recorded clip available".to_string())?;
@@ -1283,13 +1169,55 @@ fn cleanup_temp_on_exit(app: &AppHandle) {
clear_temp_segments(&st.app_dir, false);
}
/// Whether the overlay should currently ignore the cursor. `None` means there is
/// nothing to decide: no overlay window, it is hidden, or a query failed.
///
/// This is the only writer of the overlay's click-through state. `start_capture`
/// and `stop_capture` used to flip the same property directly, which desynced it
/// from the value tracked in the poll loop: after a recording stopped, the poller
/// believed the frame was already click-through and never put it back.
/// Keep click-through decisions in the poller so its cached state stays current.
fn lock_instance(app_dir: &Path) -> std::io::Result<std::fs::File> {
use std::os::windows::fs::OpenOptionsExt;
let temp = temp_dir(app_dir);
std::fs::create_dir_all(&temp)?;
std::fs::OpenOptions::new()
.write(true)
.create(true)
.truncate(false)
.share_mode(0)
.open(temp.join("instance.lock"))
}
fn close_main(window: &tauri::Window) {
use windows::core::w;
use windows::Win32::Foundation::HWND;
use windows::Win32::UI::WindowsAndMessaging::{
MessageBoxW, IDYES, MB_DEFBUTTON2, MB_ICONINFORMATION, MB_ICONWARNING, MB_OK, MB_YESNO,
};
let state = window.state::<AppState>();
let app = window.app_handle();
let owner = window.hwnd().ok().map(|handle| HWND(handle.0));
let transitioning = state.capture_transition.try_lock().is_err();
if transitioning || lock(&state.session).is_some() || state.exporting.load(Ordering::SeqCst)
|| state.thumbnail_operation.try_lock().is_err()
{
// SAFETY: The owner is the main window. Both strings have static storage.
unsafe {
MessageBoxW(owner, w!("Stop recording or wait for the current export, preview, or frame thumbnails before closing."),
w!("ByteSize"), MB_OK | MB_ICONINFORMATION);
}
return;
}
if lock(&state.last_clip).is_some() && state.unexported_clip.load(Ordering::Relaxed) {
// SAFETY: The owner is the main window. Both strings have static storage.
let response = unsafe {
MessageBoxW(owner, w!("Discard the current recording and close ByteSize?"),
w!("ByteSize"), MB_YESNO | MB_ICONWARNING | MB_DEFBUTTON2)
};
if response != IDYES {
return;
}
}
app.exit(0);
}
/// Keep click-through decisions in the poller so its cached state stays current.
fn overlay_should_ignore_cursor(app: &AppHandle) -> Option<bool> {
use windows::Win32::Foundation::{HWND, POINT};
use windows::Win32::UI::HiDpi::GetDpiForWindow;
@@ -2207,6 +2135,7 @@ async fn export(
result.map_err(|e| format!("{e:#}"))?;
let size_bytes = std::fs::metadata(&out_path).map_or(0, |m| m.len());
state.unexported_clip.store(false, Ordering::Relaxed);
Ok(ExportResult {
met_target: size_bytes <= request.target_bytes,
target_bytes: request.target_bytes,
@@ -2215,11 +2144,16 @@ async fn export(
})
}
// Process startup: if the exe directory cannot be resolved or config.toml
// cannot be created there, there is no degraded mode worth continuing into.
/// Start the app: resolve the portable directory, sweep temp/, wire up logging
/// and the hotkeys, then hand control to Tauri's event loop.
///
fn show_startup_error(message: &str) {
use windows::core::{w, HSTRING};
use windows::Win32::UI::WindowsAndMessaging::{MessageBoxW, MB_ICONINFORMATION, MB_OK};
// SAFETY: The owned message and the caption are NUL-terminated.
unsafe {
MessageBoxW(None, &HSTRING::from(message), w!("ByteSize"), MB_OK | MB_ICONINFORMATION);
}
}
/// # Panics
///
/// Panics if the executable's own directory cannot be resolved or if
@@ -2236,6 +2170,19 @@ async fn export(
pub fn run() {
let app_dir = exe_dir().expect("resolve exe directory");
let _instance = match lock_instance(&app_dir) {
Ok(lock) => lock,
Err(e) => {
let message = if e.raw_os_error() == Some(32) {
"ByteSize is already open from this folder.".to_string()
} else {
format!("Could not open the ByteSize working folder: {e}")
};
show_startup_error(&message);
return;
}
};
// Sweep temp/ before anything else so a crash on the previous run does not
// leave orphaned segments, previews, or thumbs behind - the portability
// spec promises no trace, and stale temp is trace.
@@ -2292,7 +2239,10 @@ pub fn run() {
audio: Mutex::new(None),
click_recorder: Mutex::new(None),
last_clip: Mutex::new(None),
unexported_clip: AtomicBool::new(false),
session: Mutex::new(None),
capture_transition: Mutex::new(()),
thumbnail_operation: Mutex::new(()),
picker: Mutex::new(None),
overlay_poll_shutdown: Arc::new(AtomicBool::new(false)),
export_cancel: Arc::new(AtomicBool::new(false)),
@@ -2302,6 +2252,14 @@ pub fn run() {
};
let app = tauri::Builder::default()
.on_window_event(|window, event| {
if window.label() == "main" {
if let tauri::WindowEvent::CloseRequested { api, .. } = event {
api.prevent_close();
close_main(window);
}
}
})
.plugin(tauri_plugin_dialog::init())
.plugin(
tauri_plugin_global_shortcut::Builder::new()
@@ -2408,6 +2366,7 @@ pub fn run() {
resume_capture,
restart_audio_capture,
stop_capture,
discard_clip,
export,
default_output_path,
extract_thumbnails,