keep recording audio and video in sync
This commit is contained in:
@@ -52,7 +52,7 @@ tauri = { version = "2.11", features = ["protocol-asset"] }
|
||||
tauri-plugin-dialog = "2"
|
||||
tauri-plugin-global-shortcut = "2"
|
||||
windows-capture = "2.0"
|
||||
windows = { version = "0.62", features = ["Win32_UI_WindowsAndMessaging", "Win32_UI_Input_KeyboardAndMouse", "Win32_UI_Shell", "Win32_UI_HiDpi", "Win32_Foundation", "Win32_Graphics_Dwm", "Win32_Graphics_Gdi", "Win32_Graphics_Direct3D", "Win32_Graphics_Direct3D11", "Win32_Graphics_Dxgi", "Win32_Graphics_Dxgi_Common", "Win32_System_SystemInformation", "Win32_Media_Audio", "Win32_Media_Multimedia", "Win32_System_Com", "Win32_System_Com_StructuredStorage", "Win32_System_Threading", "Win32_System_Variant"] }
|
||||
windows = { version = "0.62", features = ["Win32_UI_WindowsAndMessaging", "Win32_UI_Input_KeyboardAndMouse", "Win32_UI_Shell", "Win32_UI_HiDpi", "Win32_Foundation", "Win32_Graphics_Dwm", "Win32_Graphics_Gdi", "Win32_Graphics_Direct3D", "Win32_Graphics_Direct3D11", "Win32_Graphics_Dxgi", "Win32_Graphics_Dxgi_Common", "Win32_System_SystemInformation", "Win32_Media_Audio", "Win32_Media_Multimedia", "Win32_System_Com", "Win32_System_Com_StructuredStorage", "Win32_System_Threading", "Win32_System_Variant", "Win32_Storage_FileSystem"] }
|
||||
tokio = { version = "1.47", features = ["rt-multi-thread", "macros"] }
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
serde_json = "1.0"
|
||||
|
||||
+47
-44
@@ -22,54 +22,60 @@ const WAVE_FORMAT_PCM: u16 = 0x0001;
|
||||
const WAVE_FORMAT_IEEE_FLOAT: u16 = 0x0003;
|
||||
const WAVE_FORMAT_EXTENSIBLE: u16 = 0xFFFE;
|
||||
|
||||
pub struct AudioSession {
|
||||
pub(crate) 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,
|
||||
pub started_at: std::time::Instant,
|
||||
}
|
||||
|
||||
pub(crate) fn start(output_path: PathBuf) -> Result<AudioSession> {
|
||||
pub(crate) fn start(
|
||||
output_path: PathBuf,
|
||||
on_status: impl Fn(Result<(), String>) + Send + 'static,
|
||||
) -> Result<AudioSession> {
|
||||
let running = Arc::new(AtomicBool::new(true));
|
||||
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_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);
|
||||
}
|
||||
let mut initialized = false;
|
||||
let result = capture_thread(
|
||||
&running_for_thread,
|
||||
&path_clone,
|
||||
&init_tx,
|
||||
&mut initialized,
|
||||
|| on_status(Ok(())),
|
||||
);
|
||||
if let Err(ref e) = result {
|
||||
tracing::error!("audio capture thread ended with error: {e:#}");
|
||||
if !initialized {
|
||||
drop(init_tx.send(Err(anyhow::anyhow!("{e:#}"))));
|
||||
} else if running_for_thread.load(Ordering::Relaxed) {
|
||||
on_status(Err(format!("audio capture stopped: {e:#}")));
|
||||
}
|
||||
}
|
||||
result
|
||||
});
|
||||
|
||||
let (sample_rate, channels, started_at) = init_rx
|
||||
let initialized = init_rx
|
||||
.recv_timeout(std::time::Duration::from_secs(3))
|
||||
.context("audio capture thread failed to initialize within 3 seconds")?
|
||||
.context("audio capture initialization failed")?;
|
||||
.context("audio capture thread failed to initialize within 3 seconds")
|
||||
.and_then(|result| result.context("audio capture initialization failed"));
|
||||
let (sample_rate, channels, started_at) = match initialized {
|
||||
Ok(format) => format,
|
||||
Err(error) => {
|
||||
running.store(false, Ordering::Relaxed);
|
||||
return Err(error);
|
||||
}
|
||||
};
|
||||
|
||||
Ok(AudioSession {
|
||||
thread: Some(thread),
|
||||
running,
|
||||
died,
|
||||
output_path,
|
||||
sample_rate,
|
||||
channels,
|
||||
@@ -81,7 +87,7 @@ impl AudioSession {
|
||||
/// Stop the capture thread and hand back the PCM file it wrote. Joining can
|
||||
/// only fail if the thread panicked, which is logged rather than returned -
|
||||
/// the recorded audio is still usable either way.
|
||||
pub fn stop(self) -> PathBuf {
|
||||
pub(crate) fn stop(self) -> PathBuf {
|
||||
self.running.store(false, Ordering::Relaxed);
|
||||
if let Some(t) = self.thread {
|
||||
if let Ok(Err(ref e)) = t.join() {
|
||||
@@ -90,12 +96,6 @@ impl AudioSession {
|
||||
}
|
||||
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)> {
|
||||
@@ -134,21 +134,21 @@ fn parse_format(fmt: &WAVEFORMATEX) -> Result<(u32, u16, u16, bool)> {
|
||||
bail!("unsupported WAVEFORMATEX format tag: {w_format_tag}");
|
||||
};
|
||||
|
||||
if n_samples_per_sec == 0
|
||||
|| n_channels == 0
|
||||
|| !matches!((is_float, w_bits_per_sample), (_, 32) | (false, 16))
|
||||
{
|
||||
bail!("unsupported audio mix format");
|
||||
}
|
||||
Ok((n_samples_per_sec, n_channels, w_bits_per_sample, is_float))
|
||||
}
|
||||
|
||||
// Owns the thread's handles for its whole life: `running` is the stop flag, the
|
||||
// sender hands the init result back, and output_path is where the PCM lands.
|
||||
// Passing any of them by reference would just move the same ownership into the
|
||||
// closure that spawns this.
|
||||
#[allow(
|
||||
clippy::needless_pass_by_value,
|
||||
reason = "the spawned thread owns all three values for its entire lifetime"
|
||||
)]
|
||||
fn capture_thread(
|
||||
running: Arc<AtomicBool>,
|
||||
output_path: PathBuf,
|
||||
init_tx: std::sync::mpsc::Sender<Result<(u32, u16, std::time::Instant)>>,
|
||||
running: &AtomicBool,
|
||||
output_path: &std::path::Path,
|
||||
init_tx: &std::sync::mpsc::Sender<Result<(u32, u16, std::time::Instant)>>,
|
||||
initialized: &mut bool,
|
||||
on_started: impl FnOnce(),
|
||||
) -> Result<()> {
|
||||
// SAFETY: Initializes COM for this thread before any COM operations. COINIT_APARTMENTTHREADED is required for WASAPI.
|
||||
unsafe {
|
||||
@@ -216,7 +216,7 @@ fn capture_thread(
|
||||
client.Start().context("IAudioClient::Start")?;
|
||||
}
|
||||
|
||||
let file = File::create(&output_path).context("creating audio output file")?;
|
||||
let file = File::create(output_path).context("creating audio output file")?;
|
||||
let mut writer = BufWriter::new(file);
|
||||
|
||||
// Stamp the moment audio capture actually begins so stop_capture can pad
|
||||
@@ -225,10 +225,13 @@ fn capture_thread(
|
||||
let started_at = std::time::Instant::now();
|
||||
|
||||
// Notify parent that init succeeded.
|
||||
drop(init_tx.send(Ok((sample_rate, channels, started_at))));
|
||||
*initialized = init_tx.send(Ok((sample_rate, channels, started_at))).is_ok();
|
||||
if *initialized {
|
||||
on_started();
|
||||
}
|
||||
|
||||
let result = capture_loop(
|
||||
&running,
|
||||
running,
|
||||
&capture_client,
|
||||
channels,
|
||||
bits_per_sample,
|
||||
@@ -257,7 +260,7 @@ fn capture_thread(
|
||||
}
|
||||
|
||||
fn capture_loop(
|
||||
running: &Arc<AtomicBool>,
|
||||
running: &AtomicBool,
|
||||
capture_client: &IAudioCaptureClient,
|
||||
channels: u16,
|
||||
bits_per_sample: u16,
|
||||
|
||||
+170
-227
@@ -1,7 +1,7 @@
|
||||
use std::io::Write;
|
||||
use std::path::PathBuf;
|
||||
use std::process::{Child, ChildStdin, Command, Stdio};
|
||||
use std::sync::Arc;
|
||||
use std::sync::{Arc, OnceLock};
|
||||
use std::time::Instant;
|
||||
|
||||
use anyhow::{anyhow, bail, Context, Result};
|
||||
@@ -33,6 +33,7 @@ use windows_capture::settings::{
|
||||
};
|
||||
|
||||
use crate::config::CaptureQuality;
|
||||
use crate::timed_video::TimedVideo;
|
||||
use crate::CaptureRect;
|
||||
|
||||
// Precompiled shader bytecode (build.rs invokes fxc). See shaders/tonemap.hlsl.
|
||||
@@ -79,11 +80,13 @@ pub(crate) struct CaptureSetup {
|
||||
pub encode_width_limit: u32,
|
||||
/// Whether the captured output is running HDR, which decides the pixel shader.
|
||||
pub hdr: bool,
|
||||
pub frame_counter: Arc<std::sync::atomic::AtomicU64>,
|
||||
started_at: Instant,
|
||||
stopped_at: Arc<OnceLock<Instant>>,
|
||||
encoder_error: Arc<OnceLock<String>>,
|
||||
}
|
||||
|
||||
pub(crate) struct CaptureHandler {
|
||||
stdin: Option<ChildStdin>,
|
||||
stdin: Option<TimedVideo<ChildStdin>>,
|
||||
child: Option<Child>,
|
||||
width: u32,
|
||||
height: u32,
|
||||
@@ -92,7 +95,13 @@ pub(crate) struct CaptureHandler {
|
||||
/// GPU tonemap pipeline, lazily initialized on the first frame (needs the
|
||||
/// D3D11 device/context from the frame). Recreated on resize.
|
||||
pipeline: Option<TonemapPipeline>,
|
||||
frame_count: Arc<std::sync::atomic::AtomicU64>,
|
||||
started_at: Instant,
|
||||
stopped_at: Arc<OnceLock<Instant>>,
|
||||
encoder_error: Arc<OnceLock<String>>,
|
||||
first_timestamp: Option<(i64, u64)>,
|
||||
last_timestamp: Option<u64>,
|
||||
frame_period_ms: u64,
|
||||
pixels: Vec<u8>,
|
||||
}
|
||||
|
||||
/// Persistent D3D11 state for the HDR->SDR tonemap pass. Owns the render
|
||||
@@ -572,18 +581,14 @@ impl GraphicsCaptureApiHandler for CaptureHandler {
|
||||
// monitor all the way to the encode limit, while the session reported the
|
||||
// crop's own width - so the recorded clip's dimensions were a lie and the
|
||||
// click overlays were scaled against the wrong frame.
|
||||
let (crop_w, crop_h) = cropped_dims(setup.width, setup.height, setup.crop);
|
||||
if let Some(c) = setup.crop {
|
||||
let x = c.x.max(0);
|
||||
let y = c.y.max(0);
|
||||
filter_parts.push(format!("crop={crop_w}:{crop_h}:{x}:{y}"));
|
||||
}
|
||||
let limit = setup.encode_width_limit;
|
||||
if crop_w > limit {
|
||||
filter_parts.push(format!("scale={limit}:-2"));
|
||||
} else {
|
||||
filter_parts.push("scale=trunc(iw/2)*2:trunc(ih/2)*2".to_string());
|
||||
let CaptureRect { x, y, width, height } = c;
|
||||
filter_parts.push(format!("crop={width}:{height}:{x}:{y}"));
|
||||
}
|
||||
let (encode_w, encode_h) = compute_output_dims(
|
||||
setup.width, setup.height, setup.crop, setup.encode_width_limit,
|
||||
);
|
||||
filter_parts.push(format!("scale={encode_w}:{encode_h}"));
|
||||
let filter = filter_parts.join(",");
|
||||
|
||||
tracing::info!(
|
||||
@@ -597,11 +602,10 @@ impl GraphicsCaptureApiHandler for CaptureHandler {
|
||||
cmd.arg("-y")
|
||||
.arg("-hide_banner")
|
||||
.args(["-loglevel", "error"])
|
||||
.args(["-f", "rawvideo"])
|
||||
.args(["-pixel_format", "bgra"])
|
||||
.args(["-video_size", &format!("{}x{}", setup.width, setup.height)])
|
||||
.args(["-framerate", &setup.pipe_fps.to_string()])
|
||||
.args(["-f", "matroska"])
|
||||
.args(["-i", "-"])
|
||||
.args(["-fps_mode", "vfr"])
|
||||
.args(["-enc_time_base", "1/1000"])
|
||||
.args(["-vf", &filter])
|
||||
.args(["-c:v", "libx264"])
|
||||
.args(["-preset", "ultrafast"])
|
||||
@@ -621,6 +625,7 @@ impl GraphicsCaptureApiHandler for CaptureHandler {
|
||||
.stdin
|
||||
.take()
|
||||
.ok_or_else(|| anyhow!("ffmpeg stdin not captured"))?;
|
||||
let stdin = TimedVideo::new(stdin, setup.width, setup.height, setup.pipe_fps)?;
|
||||
// Read stderr in background to capture ffmpeg errors
|
||||
let stderr = child.stderr.take();
|
||||
if let Some(serr) = stderr {
|
||||
@@ -640,7 +645,13 @@ impl GraphicsCaptureApiHandler for CaptureHandler {
|
||||
height: setup.height,
|
||||
hdr: setup.hdr,
|
||||
pipeline: None,
|
||||
frame_count: setup.frame_counter.clone(),
|
||||
started_at: setup.started_at,
|
||||
stopped_at: setup.stopped_at,
|
||||
encoder_error: setup.encoder_error,
|
||||
first_timestamp: None,
|
||||
last_timestamp: None,
|
||||
frame_period_ms: 1000 / u64::from(setup.pipe_fps.max(1)),
|
||||
pixels: Vec::new(),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -652,6 +663,22 @@ impl GraphicsCaptureApiHandler for CaptureHandler {
|
||||
let Some(stdin) = self.stdin.as_mut() else {
|
||||
return Ok(());
|
||||
};
|
||||
if self.stopped_at.get().is_some() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let elapsed_ms = elapsed_millis(self.started_at, Instant::now());
|
||||
let timestamp = frame.timestamp().ok().map_or(elapsed_ms, |time| {
|
||||
let (first, elapsed_at_first) = *self
|
||||
.first_timestamp
|
||||
.get_or_insert((time.Duration, elapsed_ms));
|
||||
let delta_ms = time.Duration.saturating_sub(first) / 10_000;
|
||||
elapsed_at_first.saturating_add(u64::try_from(delta_ms).unwrap_or(0))
|
||||
});
|
||||
let timestamp = if self.last_timestamp.is_none() { 0 } else { timestamp };
|
||||
if self.last_timestamp.is_some_and(|last| timestamp <= last) {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let device = frame.device();
|
||||
let context = frame.device_context();
|
||||
@@ -671,19 +698,36 @@ impl GraphicsCaptureApiHandler for CaptureHandler {
|
||||
.pipeline
|
||||
.as_mut()
|
||||
.ok_or_else(|| anyhow!("tonemap pipeline missing after initialization"))?;
|
||||
pipeline.process(device, context, src, stdin)?;
|
||||
|
||||
self.frame_count
|
||||
.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
self.pixels.clear();
|
||||
pipeline.process(device, context, src, &mut self.pixels)?;
|
||||
stdin.write_frame(timestamp, &self.pixels)?;
|
||||
self.last_timestamp = Some(timestamp);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for CaptureHandler {
|
||||
fn drop(&mut self) {
|
||||
if let (Some(pipe), Some(last), Some(end)) =
|
||||
(self.stdin.as_mut(), self.last_timestamp, self.stopped_at.get())
|
||||
{
|
||||
let tail = elapsed_millis(self.started_at, *end).saturating_sub(self.frame_period_ms);
|
||||
if tail > last {
|
||||
if let Err(e) = pipe.write_frame(tail, &self.pixels) {
|
||||
drop(self.encoder_error.set(e.to_string()));
|
||||
}
|
||||
}
|
||||
}
|
||||
drop(self.stdin.take());
|
||||
if let Some(mut child) = self.child.take() {
|
||||
drop(child.wait());
|
||||
match child.wait() {
|
||||
Ok(status) if status.success() => {}
|
||||
Ok(status) => drop(self.encoder_error.set(format!("capture encoder exited with {status}"))),
|
||||
Err(e) => drop(self.encoder_error.set(e.to_string())),
|
||||
}
|
||||
}
|
||||
if self.last_timestamp.is_none() {
|
||||
drop(self.encoder_error.set("no frames were captured".to_string()));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -694,8 +738,8 @@ pub struct CaptureSession {
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
pub crop: Option<CaptureRect>,
|
||||
pub pipe_fps: u32,
|
||||
pub frame_counter: Arc<std::sync::atomic::AtomicU64>,
|
||||
stopped_at: Arc<OnceLock<Instant>>,
|
||||
encoder_error: Arc<OnceLock<String>>,
|
||||
control: CaptureControl<CaptureHandler, anyhow::Error>,
|
||||
}
|
||||
|
||||
@@ -794,17 +838,7 @@ fn is_hdr_output(device_name: &str) -> Option<bool> {
|
||||
None
|
||||
}
|
||||
|
||||
/// Resolve what the raw pipe declares, and whether WGC has to be throttled to
|
||||
/// get there. Returns `(fps, throttled)`.
|
||||
///
|
||||
/// With no limit the pipe declares the panel's refresh rate, which is what WGC
|
||||
/// delivers on its own - and the declared rate has to match what actually
|
||||
/// arrives, or `fix_intermediate_fps` rescales every timestamp by the difference
|
||||
/// and changes the clip's speed rather than its smoothness.
|
||||
///
|
||||
/// A limit above the refresh rate needs no throttle, and one below it caps at
|
||||
/// the panel either way. The `max(1)` keeps `clamp` from panicking if a panel
|
||||
/// ever reports 0 Hz, which `monitor_refresh_rate` already guards against.
|
||||
/// The pipe rate gives frames a nominal duration. Capture timestamps drive playback.
|
||||
fn pipe_rate(refresh_hz: u32, limit: Option<u32>) -> (u32, bool) {
|
||||
match limit {
|
||||
Some(requested) => {
|
||||
@@ -815,11 +849,11 @@ fn pipe_rate(refresh_hz: u32, limit: Option<u32>) -> (u32, bool) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Find the monitor containing the given screen point, falling back to the
|
||||
/// primary monitor on failure.
|
||||
fn monitor_at_point(x: i32, y: i32) -> Result<Monitor> {
|
||||
fn monitor_at_point(x: i32, y: i32) -> Result<(Monitor, (i32, i32))> {
|
||||
use windows::Win32::Foundation::POINT;
|
||||
use windows::Win32::Graphics::Gdi::{MonitorFromPoint, MONITOR_DEFAULTTONEAREST};
|
||||
use windows::Win32::Graphics::Gdi::{
|
||||
GetMonitorInfoW, MonitorFromPoint, MONITORINFO, MONITOR_DEFAULTTONEAREST,
|
||||
};
|
||||
|
||||
let pt = POINT { x, y };
|
||||
let hmonitor = unsafe {
|
||||
@@ -830,15 +864,52 @@ fn monitor_at_point(x: i32, y: i32) -> Result<Monitor> {
|
||||
if hmonitor.0.is_null() {
|
||||
bail!("MonitorFromPoint returned null for ({x}, {y})");
|
||||
}
|
||||
// SAFETY: hmonitor is a valid monitor handle from MonitorFromPoint.
|
||||
Ok(Monitor::from_raw_hmonitor(hmonitor.0))
|
||||
let mut info = MONITORINFO {
|
||||
cbSize: u32::try_from(size_of::<MONITORINFO>())?,
|
||||
..Default::default()
|
||||
};
|
||||
// SAFETY: hmonitor comes from MonitorFromPoint and info is a live local
|
||||
// whose declared size matches the type that GetMonitorInfoW writes.
|
||||
if !unsafe { GetMonitorInfoW(hmonitor, &raw mut info) }.as_bool() {
|
||||
bail!("could not read the monitor bounds for ({x}, {y})");
|
||||
}
|
||||
Ok((
|
||||
Monitor::from_raw_hmonitor(hmonitor.0),
|
||||
(info.rcMonitor.left, info.rcMonitor.top),
|
||||
))
|
||||
}
|
||||
|
||||
/// Returns both coordinate spaces so mouse clicks stay aligned with the crop.
|
||||
fn fit_capture_rect(
|
||||
crop: CaptureRect,
|
||||
(left, top): (i32, i32),
|
||||
(width, height): (u32, u32),
|
||||
) -> Option<(CaptureRect, CaptureRect)> {
|
||||
let x = i64::from(crop.x) - i64::from(left);
|
||||
let y = i64::from(crop.y) - i64::from(top);
|
||||
let local_x = x.max(0);
|
||||
let local_y = y.max(0);
|
||||
let right = (x + i64::from(crop.width)).min(i64::from(width));
|
||||
let bottom = (y + i64::from(crop.height)).min(i64::from(height));
|
||||
let width = u32::try_from(right - local_x).ok()?;
|
||||
let height = u32::try_from(bottom - local_y).ok()?;
|
||||
if width < 2 || height < 2 {
|
||||
return None;
|
||||
}
|
||||
let local = CaptureRect {
|
||||
x: i32::try_from(local_x).ok()?,
|
||||
y: i32::try_from(local_y).ok()?,
|
||||
width,
|
||||
height,
|
||||
};
|
||||
let desktop = CaptureRect {
|
||||
x: left.checked_add(local.x)?,
|
||||
y: top.checked_add(local.y)?,
|
||||
..local
|
||||
};
|
||||
Some((desktop, local))
|
||||
}
|
||||
|
||||
#[allow(
|
||||
clippy::expect_used,
|
||||
clippy::unwrap_in_result,
|
||||
reason = "Windows always has a primary monitor; if enumeration fails there is nothing sensible to capture instead"
|
||||
)]
|
||||
pub(crate) fn start(
|
||||
output_path: PathBuf,
|
||||
ffmpeg_path: PathBuf,
|
||||
@@ -849,30 +920,34 @@ pub(crate) fn start(
|
||||
) -> 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.
|
||||
let monitor = if let Some(ref c) = crop {
|
||||
let cx = c.x.saturating_add(c.width.cast_signed() / 2);
|
||||
let cy = c.y.saturating_add(c.height.cast_signed() / 2);
|
||||
let (monitor, origin) = if let Some(c) = crop {
|
||||
let cx = c.x.saturating_add((c.width / 2).cast_signed());
|
||||
let cy = c.y.saturating_add((c.height / 2).cast_signed());
|
||||
tracing::info!("capture center=({cx}, {cy}), selecting monitor");
|
||||
monitor_at_point(cx, cy).unwrap_or_else(|_| {
|
||||
tracing::warn!("no monitor at ({cx}, {cy}), falling back to primary");
|
||||
Monitor::primary().expect("primary monitor always available")
|
||||
})
|
||||
monitor_at_point(cx, cy)?
|
||||
} else {
|
||||
Monitor::primary().expect("primary monitor always available")
|
||||
(
|
||||
Monitor::primary().map_err(|e| anyhow!("primary monitor: {e:?}"))?,
|
||||
(0, 0),
|
||||
)
|
||||
};
|
||||
let raw_width = monitor
|
||||
let width = monitor
|
||||
.width()
|
||||
.map_err(|e| anyhow!("monitor width: {e:?}"))?;
|
||||
let raw_height = monitor
|
||||
let height = monitor
|
||||
.height()
|
||||
.map_err(|e| anyhow!("monitor height: {e:?}"))?;
|
||||
let width = raw_width & !1;
|
||||
let height = raw_height & !1;
|
||||
let (desktop_crop, local_crop) = match crop {
|
||||
Some(crop) => {
|
||||
let (desktop, local) = fit_capture_rect(crop, origin, (width, height))
|
||||
.context("the capture region is outside the selected monitor or too small")?;
|
||||
(Some(desktop), Some(local))
|
||||
}
|
||||
None => (None, None),
|
||||
};
|
||||
|
||||
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));
|
||||
let (out_w, out_h) = compute_output_dims(width, height, local_crop, limit);
|
||||
|
||||
// Off by default, so the pipe declares the panel's refresh rate and WGC
|
||||
// delivers it untouched. Only an explicit cap throttles, and then the
|
||||
@@ -896,16 +971,21 @@ pub(crate) fn start(
|
||||
"capture: output {device_name} hdr={hdr} pipe_fps={pipe_fps} (refresh {refresh_hz})"
|
||||
);
|
||||
|
||||
let started_at = Instant::now();
|
||||
let stopped_at = Arc::new(OnceLock::new());
|
||||
let encoder_error = Arc::new(OnceLock::new());
|
||||
let setup = CaptureSetup {
|
||||
output_path: output_path.clone(),
|
||||
ffmpeg_path,
|
||||
width,
|
||||
height,
|
||||
crop,
|
||||
crop: local_crop,
|
||||
pipe_fps,
|
||||
encode_width_limit: limit,
|
||||
hdr,
|
||||
frame_counter: frame_counter.clone(),
|
||||
started_at,
|
||||
stopped_at: stopped_at.clone(),
|
||||
encoder_error: encoder_error.clone(),
|
||||
};
|
||||
|
||||
let cursor_setting = if capture_cursor {
|
||||
@@ -930,12 +1010,12 @@ pub(crate) fn start(
|
||||
|
||||
Ok(CaptureSession {
|
||||
output_path,
|
||||
started_at: Instant::now(),
|
||||
started_at,
|
||||
width: out_w,
|
||||
height: out_h,
|
||||
crop,
|
||||
pipe_fps,
|
||||
frame_counter,
|
||||
crop: desktop_crop,
|
||||
stopped_at,
|
||||
encoder_error,
|
||||
control,
|
||||
})
|
||||
}
|
||||
@@ -946,37 +1026,28 @@ fn compute_output_dims(
|
||||
crop: Option<CaptureRect>,
|
||||
width_limit: u32,
|
||||
) -> (u32, u32) {
|
||||
let (raw_w, raw_h) = cropped_dims(monitor_w, monitor_h, crop);
|
||||
let (raw_w, raw_h) = crop.map_or((monitor_w, monitor_h), |c| (c.width, c.height));
|
||||
let cap = width_limit;
|
||||
if raw_w > cap {
|
||||
let scale = f64::from(cap) / f64::from(raw_w);
|
||||
let nh = crate::encode::round_u32(f64::from(raw_h) * scale);
|
||||
(cap, (nh / 2) * 2)
|
||||
let half_height = crate::encode::round_u32(f64::from(raw_h) * scale / 2.0);
|
||||
(cap, half_height.max(1) * 2)
|
||||
} else {
|
||||
((raw_w / 2) * 2, (raw_h / 2) * 2)
|
||||
}
|
||||
}
|
||||
|
||||
/// The dimensions left after the crop, clamped so the rect cannot hang off the
|
||||
/// monitor. Shared by the ffmpeg filter and the reported clip size so the two
|
||||
/// cannot disagree about how wide the frame ends up.
|
||||
fn cropped_dims(monitor_w: u32, monitor_h: u32, crop: Option<CaptureRect>) -> (u32, u32) {
|
||||
match crop {
|
||||
Some(c) => {
|
||||
let x = c.x.max(0).cast_unsigned();
|
||||
let y = c.y.max(0).cast_unsigned();
|
||||
(
|
||||
c.width.min(monitor_w.saturating_sub(x)),
|
||||
c.height.min(monitor_h.saturating_sub(y)),
|
||||
)
|
||||
}
|
||||
None => (monitor_w, monitor_h),
|
||||
}
|
||||
impl CaptureSession {
|
||||
pub fn mark_stopped_at(&self, end: Instant) {
|
||||
let _cutoff = self.stopped_at.get_or_init(|| end);
|
||||
}
|
||||
|
||||
impl CaptureSession {
|
||||
pub fn stop(self) -> Result<PathBuf> {
|
||||
self.mark_stopped_at(Instant::now());
|
||||
drop(self.control.stop());
|
||||
if let Some(error) = self.encoder_error.get() {
|
||||
bail!("{error}");
|
||||
}
|
||||
let meta = std::fs::metadata(&self.output_path)
|
||||
.with_context(|| format!("checking output file {}", self.output_path.display()))?;
|
||||
if meta.len() == 0 {
|
||||
@@ -986,128 +1057,8 @@ impl CaptureSession {
|
||||
}
|
||||
}
|
||||
|
||||
/// Re-encode the intermediate file with correct timestamps.
|
||||
/// The capture declares a fixed pipe framerate and later scales PTS to match
|
||||
/// real-time duration from the measured frame count.
|
||||
///
|
||||
/// Idempotent: if `input` has already been consumed (e.g. a previous
|
||||
/// pause/resume cycle ran this to completion and removed it), and
|
||||
/// `output` exists, returns Ok without re-running ffmpeg.
|
||||
#[allow(
|
||||
clippy::expect_used,
|
||||
clippy::unwrap_in_result,
|
||||
reason = "callers rule out the None case that capture_timing returns None for"
|
||||
)]
|
||||
pub(crate) fn fix_intermediate_fps(
|
||||
ffmpeg: &std::path::Path,
|
||||
input: &std::path::Path,
|
||||
output: &std::path::Path,
|
||||
elapsed_secs: f64,
|
||||
frame_count: u64,
|
||||
pipe_fps: u32,
|
||||
) -> Result<()> {
|
||||
use std::process::Command;
|
||||
|
||||
if !input.is_file() && output.is_file() {
|
||||
tracing::debug!("capture fix: input already consumed, output exists, skipping");
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
if frame_count == 0 || elapsed_secs <= 0.0 {
|
||||
tracing::warn!("capture fix: no frames counted, keeping original");
|
||||
return rename_or_copy(input, output);
|
||||
}
|
||||
|
||||
let (actual_fps, pts_scale) = capture_timing(frame_count, elapsed_secs, pipe_fps)
|
||||
.expect("frame_count and elapsed_secs were checked above");
|
||||
tracing::info!(
|
||||
"capture fix: {frame_count} frames in {elapsed_secs:.1}s = {actual_fps:.1}fps (declared {pipe_fps}), pts_scale={pts_scale:.4}"
|
||||
);
|
||||
|
||||
// If the measured rate already matches the declared pipe rate within 2%,
|
||||
// the timestamps are already correct - the capture API's clock and the
|
||||
// ffmpeg input clock agree. Skip the lossy re-encode and just rename.
|
||||
// This is the common case now that pipe_fps tracks the monitor's refresh
|
||||
// rate instead of a fixed high constant.
|
||||
if (pts_scale - 1.0).abs() <= 0.02 {
|
||||
tracing::debug!(
|
||||
"capture fix: pts_scale={pts_scale:.4} within no-op tolerance, renaming without re-encode"
|
||||
);
|
||||
return rename_or_copy(input, output);
|
||||
}
|
||||
|
||||
// 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!("{pts_scale:.6}")])
|
||||
.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");
|
||||
drop(std::fs::remove_file(input));
|
||||
return Ok(());
|
||||
}
|
||||
tracing::warn!("capture fix: -itsscale copy failed, falling back to re-encode");
|
||||
drop(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")
|
||||
.args(["-loglevel", "error"])
|
||||
.args(["-i", &input.to_string_lossy()])
|
||||
.args(["-vf", &format!("setpts=PTS*{pts_scale:.4}")])
|
||||
.args(["-c:v", "libx264"])
|
||||
.args(["-preset", "veryfast"])
|
||||
.args(["-crf", "18"])
|
||||
.args(["-color_primaries", "bt709"])
|
||||
.args(["-color_trc", "bt709"])
|
||||
.args(["-colorspace", "bt709"])
|
||||
.args(["-pix_fmt", "yuv420p"])
|
||||
.arg(output)
|
||||
.status()
|
||||
.context("re-encoding with corrected timestamps")?;
|
||||
|
||||
if status.success() {
|
||||
drop(std::fs::remove_file(input));
|
||||
} else {
|
||||
tracing::warn!("capture fix: re-encode failed, keeping original");
|
||||
drop(rename_or_copy(input, output));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Move `input` to `output`, falling back to a copy if the rename fails
|
||||
/// (e.g. cross-volume or a handle still holds the file on Windows).
|
||||
fn rename_or_copy(input: &std::path::Path, output: &std::path::Path) -> Result<()> {
|
||||
std::fs::rename(input, output)
|
||||
.or_else(|_| std::fs::copy(input, output).map(|_| ()))
|
||||
.with_context(|| format!("moving {} to {}", input.display(), output.display()))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn capture_timing(frame_count: u64, elapsed_secs: f64, pipe_fps: u32) -> Option<(f64, f64)> {
|
||||
if frame_count == 0 || elapsed_secs <= 0.0 {
|
||||
return None;
|
||||
}
|
||||
// A frame count high enough to lose f64 precision would be ~2^53 frames,
|
||||
// which is centuries of capture; f64 handles this ratio exactly enough.
|
||||
#[allow(
|
||||
clippy::cast_precision_loss,
|
||||
reason = "frame counts that could lose f64 precision are unreachable in a recording session"
|
||||
)]
|
||||
let actual_fps = frame_count as f64 / elapsed_secs;
|
||||
Some((actual_fps, f64::from(pipe_fps) / actual_fps))
|
||||
fn elapsed_millis(start: Instant, end: Instant) -> u64 {
|
||||
u64::try_from(end.saturating_duration_since(start).as_millis()).unwrap_or(u64::MAX)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -1119,25 +1070,17 @@ mod tests {
|
||||
|
||||
use super::*;
|
||||
|
||||
/// The maths under test is a ratio, so a tolerance says what the test means;
|
||||
/// a strict float compare would be asserting the division is bit-perfect.
|
||||
fn assert_close(got: f64, want: f64) {
|
||||
assert!((got - want).abs() < 1e-9, "expected {want}, got {got}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn timing_scale_uses_declared_pipe_rate() {
|
||||
let (actual_fps, pts_scale) = capture_timing(600, 10.0, 60).unwrap();
|
||||
assert_close(actual_fps, 60.0);
|
||||
assert_close(pts_scale, 1.0);
|
||||
}
|
||||
fn capture_crop_is_clipped_and_translated_on_secondary_monitors() {
|
||||
let selection = CaptureRect { x: 2010, y: -200, width: 160, height: 250 };
|
||||
let (desktop, local) = fit_capture_rect(selection, (1920, -1080), (1920, 1080)).unwrap();
|
||||
assert_eq!((desktop.x, desktop.y, desktop.width, desktop.height), (2010, -200, 160, 200));
|
||||
assert_eq!((local.x, local.y, local.width, local.height), (90, 880, 160, 200));
|
||||
|
||||
#[test]
|
||||
fn timing_scale_for_high_pipe_rate() {
|
||||
// 600 frames in 10s = 60 actual; pipe declared 120 -> pts scale 2.0
|
||||
let (actual_fps, pts_scale) = capture_timing(600, 10.0, 120).unwrap();
|
||||
assert_close(actual_fps, 60.0);
|
||||
assert_close(pts_scale, 2.0);
|
||||
let selection = CaptureRect { x: -1500, y: 24, width: 300, height: 200 };
|
||||
let (_, local) = fit_capture_rect(selection, (-1920, 0), (1920, 1080)).unwrap();
|
||||
assert_eq!((local.x, local.y), (420, 24));
|
||||
assert!(fit_capture_rect(selection, (0, 0), (1920, 1080)).is_none());
|
||||
}
|
||||
|
||||
/// No cap is the default and must leave the rate exactly where WGC puts it.
|
||||
|
||||
+109
-15
@@ -2,7 +2,7 @@ use std::collections::HashSet;
|
||||
use std::ffi::{OsStr, OsString};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
|
||||
use std::sync::mpsc::Sender;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::thread;
|
||||
@@ -1176,30 +1176,124 @@ pub(crate) fn mux_with_audio(
|
||||
run(&mut cmd, "mux")
|
||||
}
|
||||
|
||||
pub(crate) fn concat_pcm(segments: &[PathBuf], output: &Path) -> Result<()> {
|
||||
pub(crate) struct AudioSegment {
|
||||
pub path: PathBuf,
|
||||
pub sample_rate: u32,
|
||||
pub channels: u16,
|
||||
pub start_secs: f64,
|
||||
pub end_secs: f64,
|
||||
}
|
||||
|
||||
/// Align the audio takes to video time and fill gaps with whole sample frames.
|
||||
pub(crate) fn assemble_pcm(
|
||||
ffmpeg: &Path,
|
||||
segments: &[AudioSegment],
|
||||
output: &Path,
|
||||
duration_secs: f64,
|
||||
) -> Result<Option<(u32, u16)>> {
|
||||
use std::io::{Read, Seek, SeekFrom};
|
||||
|
||||
let Some(first) = segments.first() else {
|
||||
return Ok(None);
|
||||
};
|
||||
let (sample_rate, channels) = (first.sample_rate, first.channels);
|
||||
let frame_bytes = u64::from(channels) * 4;
|
||||
let frame_at = |seconds: f64| round_u64(seconds * f64::from(sample_rate));
|
||||
let total_frames = frame_at(duration_secs);
|
||||
let mut out = std::fs::File::create(output).context("creating aligned audio file")?;
|
||||
let mut written = 0;
|
||||
let resampled = TempFileGuard(output.with_extension("resampled.pcm"));
|
||||
|
||||
for segment in segments {
|
||||
let start = frame_at(segment.start_secs);
|
||||
let end = frame_at(segment.end_secs).min(total_frames);
|
||||
let from = start.max(written);
|
||||
if end <= from || std::fs::metadata(&segment.path)?.len() == 0 {
|
||||
continue;
|
||||
}
|
||||
let path = if (segment.sample_rate, segment.channels) == (sample_rate, channels) {
|
||||
&segment.path
|
||||
} else {
|
||||
resample_pcm(ffmpeg, segment, &resampled.0, sample_rate, channels)?;
|
||||
&resampled.0
|
||||
};
|
||||
let mut input = std::fs::File::open(path)?;
|
||||
let skipped = from - start;
|
||||
let available = (input.metadata()?.len() / frame_bytes).saturating_sub(skipped);
|
||||
let frames = available.min(end - from);
|
||||
if frames == 0 {
|
||||
continue;
|
||||
}
|
||||
write_silence(&mut out, (from - written) * frame_bytes)?;
|
||||
input.seek(SeekFrom::Start(skipped * frame_bytes))?;
|
||||
let bytes = frames * frame_bytes;
|
||||
if std::io::copy(&mut input.take(bytes), &mut out)? != bytes {
|
||||
bail!("audio segment ended before its recorded length");
|
||||
}
|
||||
written = from + frames;
|
||||
}
|
||||
|
||||
if written == 0 {
|
||||
return Ok(None);
|
||||
}
|
||||
write_silence(&mut out, (total_frames - written) * frame_bytes)?;
|
||||
Ok(Some((sample_rate, channels)))
|
||||
}
|
||||
|
||||
fn write_silence(output: &mut std::fs::File, mut bytes: u64) -> Result<()> {
|
||||
use std::io::Write;
|
||||
if segments.is_empty() {
|
||||
bail!("no audio segments to concatenate");
|
||||
|
||||
const ZEROS: [u8; 8192] = [0; 8192];
|
||||
while bytes > 0 {
|
||||
let chunk = bytes.min(8192);
|
||||
let zeros = ZEROS
|
||||
.get(..usize::try_from(chunk)?)
|
||||
.context("audio padding exceeds its buffer")?;
|
||||
output.write_all(zeros)?;
|
||||
bytes -= chunk;
|
||||
}
|
||||
if let Some(parent) = output.parent() {
|
||||
std::fs::create_dir_all(parent).context("creating audio concat parent")?;
|
||||
}
|
||||
let mut out = std::fs::File::create(output).context("creating audio concat file")?;
|
||||
for seg in segments {
|
||||
let mut f =
|
||||
std::fs::File::open(seg).with_context(|| format!("opening {}", seg.display()))?;
|
||||
std::io::copy(&mut f, &mut out).context("copying audio segment")?;
|
||||
}
|
||||
out.flush()?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
struct TempFileGuard(PathBuf);
|
||||
fn resample_pcm(
|
||||
ffmpeg: &Path,
|
||||
segment: &AudioSegment,
|
||||
output: &Path,
|
||||
sample_rate: u32,
|
||||
channels: u16,
|
||||
) -> Result<()> {
|
||||
let mut cmd = Command::new(ffmpeg);
|
||||
cmd.args(["-y", "-hide_banner", "-f", "f32le"])
|
||||
.args(["-ar", &segment.sample_rate.to_string()])
|
||||
.args(["-ac", &segment.channels.to_string()])
|
||||
.arg("-i")
|
||||
.arg(&segment.path)
|
||||
.args(["-ar", &sample_rate.to_string()])
|
||||
.args(["-ac", &channels.to_string()])
|
||||
.args(["-f", "f32le"])
|
||||
.arg(output);
|
||||
run(&mut cmd, "audio resampling")
|
||||
}
|
||||
|
||||
pub(crate) struct TempFileGuard(pub(crate) PathBuf);
|
||||
|
||||
impl TempFileGuard {
|
||||
pub(crate) fn create_in(dir: &Path, purpose: &str, extension: &str) -> Result<Self> {
|
||||
static SEQUENCE: AtomicU64 = AtomicU64::new(0);
|
||||
let sequence = SEQUENCE.fetch_add(1, Ordering::Relaxed);
|
||||
let path = dir.join(format!("{purpose}-{}-{sequence}.{extension}", std::process::id()));
|
||||
drop(std::fs::File::create_new(&path)?);
|
||||
Ok(Self(path))
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for TempFileGuard {
|
||||
fn drop(&mut self) {
|
||||
if !self.0.as_os_str().is_empty() {
|
||||
drop(std::fs::remove_file(&self.0));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn concat_segments(ffmpeg: &Path, segments: &[PathBuf], output: &Path) -> Result<()> {
|
||||
use std::fmt::Write as _;
|
||||
|
||||
+255
-296
@@ -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(());
|
||||
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,
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
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;
|
||||
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 })
|
||||
}
|
||||
match audio::start(audio_path) {
|
||||
Ok(s) => Some(s),
|
||||
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
|
||||
let _transition = state.begin_capture_transition()?;
|
||||
let started_at = lock(&state.capture)
|
||||
.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 = {
|
||||
.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 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);
|
||||
}
|
||||
|
||||
let live_audio = lock(&state.audio).take();
|
||||
if let Some(a) = live_audio {
|
||||
ss.audio_segments.push(a.stop());
|
||||
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_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,
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
use std::io::{self, Write};
|
||||
|
||||
/// Matroska stream of BGRA frames with millisecond timestamps.
|
||||
pub(crate) struct TimedVideo<W> {
|
||||
out: W,
|
||||
frame_size: usize,
|
||||
}
|
||||
|
||||
impl<W: Write> TimedVideo<W> {
|
||||
pub(crate) fn new(mut out: W, width: u32, height: u32, fps: u32) -> io::Result<Self> {
|
||||
let frame_bytes = width
|
||||
.checked_mul(height)
|
||||
.and_then(|pixels| pixels.checked_mul(4))
|
||||
.ok_or_else(|| io::Error::other("capture dimensions exceed the recording limit"))?;
|
||||
let mut ebml = Vec::new();
|
||||
for (id, value) in [
|
||||
(&[0x42, 0x86], 1),
|
||||
(&[0x42, 0xf7], 1),
|
||||
(&[0x42, 0xf2], 4),
|
||||
(&[0x42, 0xf3], 8),
|
||||
(&[0x42, 0x87], 4),
|
||||
(&[0x42, 0x85], 2),
|
||||
] {
|
||||
uint(&mut ebml, id, value)?;
|
||||
}
|
||||
element(&mut ebml, &[0x42, 0x82], b"matroska")?;
|
||||
element(&mut out, &[0x1a, 0x45, 0xdf, 0xa3], &ebml)?;
|
||||
// Unknown-size Segment permits streaming through a non-seekable pipe.
|
||||
out.write_all(&[0x18, 0x53, 0x80, 0x67, 0xff])?;
|
||||
|
||||
let mut info = Vec::new();
|
||||
uint(&mut info, &[0x2a, 0xd7, 0xb1], 1_000_000)?;
|
||||
element(&mut info, &[0x4d, 0x80], b"ByteSize")?;
|
||||
element(&mut info, &[0x57, 0x41], b"ByteSize")?;
|
||||
element(&mut out, &[0x15, 0x49, 0xa9, 0x66], &info)?;
|
||||
|
||||
let mut video = Vec::new();
|
||||
uint(&mut video, &[0xb0], u64::from(width))?;
|
||||
uint(&mut video, &[0xba], u64::from(height))?;
|
||||
let mut track = Vec::new();
|
||||
uint(&mut track, &[0xd7], 1)?; // TrackNumber
|
||||
uint(&mut track, &[0x73, 0xc5], 1)?; // TrackUID
|
||||
uint(&mut track, &[0x83], 1)?; // TrackType = video
|
||||
uint(
|
||||
&mut track,
|
||||
&[0x23, 0xe3, 0x83],
|
||||
1_000_000_000 / u64::from(fps.max(1)),
|
||||
)?;
|
||||
element(&mut track, &[0x86], b"V_MS/VFW/FOURCC")?;
|
||||
|
||||
// BITMAPINFOHEADER. A negative height identifies top-down BGRA rows.
|
||||
let mut bitmap = Vec::with_capacity(40);
|
||||
bitmap.extend(40u32.to_le_bytes());
|
||||
bitmap.extend(width.to_le_bytes());
|
||||
bitmap.extend((-i32::try_from(height).map_err(io::Error::other)?).to_le_bytes());
|
||||
bitmap.extend(1u16.to_le_bytes()); // planes
|
||||
bitmap.extend(32u16.to_le_bytes()); // bits per pixel
|
||||
bitmap.extend(0u32.to_le_bytes()); // BI_RGB
|
||||
bitmap.extend(frame_bytes.to_le_bytes());
|
||||
bitmap.extend([0; 16]);
|
||||
element(&mut track, &[0x63, 0xa2], &bitmap)?;
|
||||
element(&mut track, &[0xe0], &video)?;
|
||||
let mut tracks = Vec::new();
|
||||
element(&mut tracks, &[0xae], &track)?;
|
||||
element(&mut out, &[0x16, 0x54, 0xae, 0x6b], &tracks)?;
|
||||
Ok(Self {
|
||||
out,
|
||||
frame_size: usize::try_from(frame_bytes).map_err(io::Error::other)?,
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn write_frame(&mut self, timestamp_ms: u64, pixels: &[u8]) -> io::Result<()> {
|
||||
if pixels.len() != self.frame_size {
|
||||
return Err(io::Error::other(
|
||||
"display dimensions changed during capture",
|
||||
));
|
||||
}
|
||||
let block_size = pixels.len() + 4;
|
||||
let mut header = Vec::with_capacity(16);
|
||||
uint(&mut header, &[0xe7], timestamp_ms)?;
|
||||
header.push(0xa3); // SimpleBlock
|
||||
write_size(&mut header, block_size)?;
|
||||
self.out.write_all(&[0x1f, 0x43, 0xb6, 0x75])?; // Cluster
|
||||
write_size(&mut self.out, header.len() + block_size)?;
|
||||
self.out.write_all(&header)?;
|
||||
// Track 1, timestamp relative to the cluster = 0, keyframe flag.
|
||||
self.out.write_all(&[0x81, 0, 0, 0x80])?;
|
||||
self.out.write_all(pixels)
|
||||
}
|
||||
}
|
||||
|
||||
fn element(out: &mut impl Write, id: &[u8], payload: &[u8]) -> io::Result<()> {
|
||||
out.write_all(id)?;
|
||||
write_size(out, payload.len())?;
|
||||
out.write_all(payload)
|
||||
}
|
||||
|
||||
fn uint(out: &mut impl Write, id: &[u8], value: u64) -> io::Result<()> {
|
||||
let bytes = value.to_be_bytes();
|
||||
let first = (value.leading_zeros() / 8).min(7);
|
||||
let payload = bytes
|
||||
.get(usize::try_from(first).map_err(io::Error::other)?..)
|
||||
.ok_or_else(|| io::Error::other("invalid unsigned Matroska value"))?;
|
||||
element(out, id, payload)
|
||||
}
|
||||
|
||||
fn write_size(out: &mut impl Write, size: usize) -> io::Result<()> {
|
||||
let size = u64::try_from(size).map_err(io::Error::other)?;
|
||||
for width in 1..=8 {
|
||||
let marker = 1u64 << (width * 7);
|
||||
if size < marker - 1 {
|
||||
let bytes = (marker | size).to_be_bytes();
|
||||
let payload = bytes
|
||||
.get(8 - width..)
|
||||
.ok_or_else(|| io::Error::other("invalid Matroska size width"))?;
|
||||
return out.write_all(payload);
|
||||
}
|
||||
}
|
||||
Err(io::Error::other("Matroska element is too large"))
|
||||
}
|
||||
+3
-1
@@ -373,7 +373,9 @@
|
||||
showDiscardConfirm = false
|
||||
}
|
||||
|
||||
function doDiscard() {
|
||||
async function doDiscard() {
|
||||
try { await api.discardClip() }
|
||||
catch (error) { errMsg = String(error); return }
|
||||
showDiscardConfirm = false
|
||||
startOver()
|
||||
}
|
||||
|
||||
@@ -107,6 +107,7 @@ export type RecordedClip = {
|
||||
|
||||
export type StartCaptureRequest = {
|
||||
crop: CaptureRect | null
|
||||
options?: CaptureConfig
|
||||
}
|
||||
|
||||
export type ExportRequest = {
|
||||
@@ -194,6 +195,7 @@ export const api = {
|
||||
resumeCapture: () => invoke<void>("resume_capture"),
|
||||
restartAudioCapture: () => invoke<void>("restart_audio_capture"),
|
||||
stopCapture: () => invoke<RecordedClip>("stop_capture"),
|
||||
discardClip: () => invoke<void>("discard_clip"),
|
||||
export: (request: ExportRequest) => invoke<ExportResult>("export", { request }),
|
||||
revealInExplorer: (path: string) => invoke<void>("reveal_in_explorer", { path }),
|
||||
showOverlay: () => invoke<void>("show_overlay"),
|
||||
|
||||
Reference in New Issue
Block a user