From 63e41297e92e27d2c851af60cd713dec604d7f49 Mon Sep 17 00:00:00 2001 From: lashman Date: Tue, 12 May 2026 01:39:02 +0300 Subject: [PATCH] system audio capture via wasapi loopback --- src-tauri/Cargo.lock | 150 ++++++++++++++++++++++++++++++++++++++++ src-tauri/Cargo.toml | 1 + src-tauri/src/audio.rs | 77 +++++++++++++++++++++ src-tauri/src/encode.rs | 52 ++++++++++++++ src-tauri/src/lib.rs | 124 +++++++++++++++++++++++++++++---- 5 files changed, 392 insertions(+), 12 deletions(-) create mode 100644 src-tauri/src/audio.rs diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index 08a8772..ae1e985 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -61,6 +61,28 @@ dependencies = [ "alloc-no-stdlib", ] +[[package]] +name = "alsa" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed7572b7ba83a31e20d1b48970ee402d2e3e0537dcfe0a3ff4d6eb7508617d43" +dependencies = [ + "alsa-sys", + "bitflags 2.11.1", + "cfg-if", + "libc", +] + +[[package]] +name = "alsa-sys" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db8fee663d06c4e303404ef5f40488a53e062f89ba8bfed81f42325aafad1527" +dependencies = [ + "libc", + "pkg-config", +] + [[package]] name = "android_system_properties" version = "0.1.5" @@ -356,6 +378,7 @@ name = "bytesize" version = "0.1.0" dependencies = [ "anyhow", + "cpal", "futures-util", "hex", "image", @@ -602,6 +625,46 @@ dependencies = [ "libc", ] +[[package]] +name = "coreaudio-rs" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1aae284fbaf7d27aa0e292f7677dfbe26503b0d555026f702940805a630eac17" +dependencies = [ + "bitflags 1.3.2", + "libc", + "objc2-audio-toolbox", + "objc2-core-audio", + "objc2-core-audio-types", + "objc2-core-foundation", +] + +[[package]] +name = "cpal" +version = "0.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cbd307f43cc2a697e2d1f8bc7a1d824b5269e052209e28883e5bc04d095aaa3f" +dependencies = [ + "alsa", + "coreaudio-rs", + "dasp_sample", + "jni", + "js-sys", + "libc", + "mach2", + "ndk", + "ndk-context", + "num-derive", + "num-traits", + "objc2-audio-toolbox", + "objc2-core-audio", + "objc2-core-audio-types", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", + "windows 0.54.0", +] + [[package]] name = "cpubits" version = "0.1.1" @@ -767,6 +830,12 @@ dependencies = [ "syn 2.0.117", ] +[[package]] +name = "dasp_sample" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c87e182de0887fd5361989c677c4e8f5000cd9491d6d563161a8f3a5519fc7f" + [[package]] name = "dbus" version = "0.9.11" @@ -2272,6 +2341,15 @@ version = "0.16.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "47bb1e988e6fb779cf720ad431242d3f03167c1b3f2b1aae7f1a94b2495b36ae" +[[package]] +name = "mach2" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d640282b302c0bb0a2a8e0233ead9035e3bed871f0b7e81fe4a1ec829765db44" +dependencies = [ + "libc", +] + [[package]] name = "markup5ever" version = "0.38.0" @@ -2398,6 +2476,12 @@ dependencies = [ "thiserror 1.0.69", ] +[[package]] +name = "ndk-context" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27b02d87554356db9e9a873add8782d4ea6e3e58ea071a9adb9a2e8ddb884a8b" + [[package]] name = "ndk-sys" version = "0.6.0+11769913" @@ -2547,6 +2631,21 @@ dependencies = [ "objc2-foundation", ] +[[package]] +name = "objc2-audio-toolbox" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6948501a91121d6399b79abaa33a8aa4ea7857fe019f341b8c23ad6e81b79b08" +dependencies = [ + "bitflags 2.11.1", + "libc", + "objc2", + "objc2-core-audio", + "objc2-core-audio-types", + "objc2-core-foundation", + "objc2-foundation", +] + [[package]] name = "objc2-cloud-kit" version = "0.3.2" @@ -2558,6 +2657,28 @@ dependencies = [ "objc2-foundation", ] +[[package]] +name = "objc2-core-audio" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1eebcea8b0dbff5f7c8504f3107c68fc061a3eb44932051c8cf8a68d969c3b2" +dependencies = [ + "dispatch2", + "objc2", + "objc2-core-audio-types", + "objc2-core-foundation", +] + +[[package]] +name = "objc2-core-audio-types" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a89f2ec274a0cf4a32642b2991e8b351a404d290da87bb6a9a9d8632490bd1c" +dependencies = [ + "bitflags 2.11.1", + "objc2", +] + [[package]] name = "objc2-core-data" version = "0.3.2" @@ -5211,6 +5332,16 @@ dependencies = [ "windows-version", ] +[[package]] +name = "windows" +version = "0.54.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9252e5725dbed82865af151df558e754e4a3c2c30818359eb17465f1346a1b49" +dependencies = [ + "windows-core 0.54.0", + "windows-targets 0.52.6", +] + [[package]] name = "windows" version = "0.61.3" @@ -5267,6 +5398,16 @@ dependencies = [ "windows-core 0.62.2", ] +[[package]] +name = "windows-core" +version = "0.54.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12661b9c89351d684a50a8a643ce5f608e20243b9fb84687800163429f161d65" +dependencies = [ + "windows-result 0.1.2", + "windows-targets 0.52.6", +] + [[package]] name = "windows-core" version = "0.61.2" @@ -5369,6 +5510,15 @@ dependencies = [ "windows-link 0.2.1", ] +[[package]] +name = "windows-result" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e383302e8ec8515204254685643de10811af0ed97ea37210dc26fb0032647f8" +dependencies = [ + "windows-targets 0.52.6", +] + [[package]] name = "windows-result" version = "0.3.4" diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index cd4ce29..137e900 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -19,6 +19,7 @@ tauri-plugin-dialog = "2" tauri-plugin-global-shortcut = "2" windows-capture = "2.0" windows = { version = "0.62", features = ["Win32_UI_WindowsAndMessaging", "Win32_Foundation"] } +cpal = "0.16" tokio = { version = "1.47", features = ["full"] } serde = { version = "1.0", features = ["derive"] } serde_json = "1.0" diff --git a/src-tauri/src/audio.rs b/src-tauri/src/audio.rs new file mode 100644 index 0000000..e305c7d --- /dev/null +++ b/src-tauri/src/audio.rs @@ -0,0 +1,77 @@ +use std::fs::File; +use std::io::{BufWriter, Write}; +use std::path::PathBuf; +use std::sync::{Arc, Mutex}; + +use anyhow::{anyhow, Context, Result}; +use cpal::traits::{DeviceTrait, HostTrait, StreamTrait}; + +pub struct AudioSession { + _stream: cpal::Stream, + pub output_path: PathBuf, + pub sample_rate: u32, + pub channels: u16, + writer: Arc>>>, +} + +pub fn start(output_path: PathBuf) -> Result { + let host = cpal::default_host(); + let device = host + .default_output_device() + .ok_or_else(|| anyhow!("no default output device for loopback"))?; + let supported = device + .default_output_config() + .context("default output config")?; + let sample_rate = supported.sample_rate().0; + let channels = supported.channels(); + let stream_config: cpal::StreamConfig = supported.config(); + + if let Some(parent) = output_path.parent() { + std::fs::create_dir_all(parent).ok(); + } + let file = File::create(&output_path).context("creating audio output file")?; + let writer = Arc::new(Mutex::new(Some(BufWriter::new(file)))); + let writer_clone = writer.clone(); + + let stream = device + .build_input_stream( + &stream_config, + move |data: &[f32], _info: &cpal::InputCallbackInfo| { + if let Ok(mut guard) = writer_clone.lock() { + if let Some(w) = guard.as_mut() { + let bytes: &[u8] = bytemuck_cast(data); + let _ = w.write_all(bytes); + } + } + }, + |err| tracing::warn!("audio capture error: {err}"), + None, + ) + .context("building input stream")?; + stream.play().context("starting audio stream")?; + + Ok(AudioSession { + _stream: stream, + output_path, + sample_rate, + channels, + writer, + }) +} + +impl AudioSession { + pub fn stop(self) -> Result { + drop(self._stream); + if let Ok(mut guard) = self.writer.lock() { + if let Some(mut w) = guard.take() { + let _ = w.flush(); + } + } + Ok(self.output_path) + } +} + +fn bytemuck_cast(data: &[f32]) -> &[u8] { + let len_bytes = std::mem::size_of_val(data); + unsafe { std::slice::from_raw_parts(data.as_ptr() as *const u8, len_bytes) } +} diff --git a/src-tauri/src/encode.rs b/src-tauri/src/encode.rs index 94cddd0..6cfb5f8 100644 --- a/src-tauri/src/encode.rs +++ b/src-tauri/src/encode.rs @@ -381,6 +381,58 @@ pub fn extract_thumbnails( Ok(paths) } +pub fn mux_with_audio( + ffmpeg: &Path, + video: &Path, + audio_pcm: &Path, + sample_rate: u32, + channels: u16, + output: &Path, +) -> Result<()> { + if let Some(parent) = output.parent() { + std::fs::create_dir_all(parent).context("creating output parent dir")?; + } + let mut cmd = Command::new(ffmpeg); + cmd.arg("-y") + .arg("-hide_banner") + .arg("-i") + .arg(video) + .args(["-f", "f32le"]) + .args(["-ar", &sample_rate.to_string()]) + .args(["-ac", &channels.to_string()]) + .arg("-i") + .arg(audio_pcm) + .args(["-c:v", "copy"]) + .args(["-c:a", "aac"]) + .args(["-b:a", "192k"]) + .args(["-shortest"]) + .arg(output); + run(&mut cmd, "mux") +} + +pub fn concat_pcm(segments: &[PathBuf], output: &Path) -> Result<()> { + use std::io::{Read, Write}; + if segments.is_empty() { + bail!("no audio segments to concatenate"); + } + 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:?}"))?; + let mut buf = vec![0u8; 64 * 1024]; + loop { + let n = f.read(&mut buf)?; + if n == 0 { + break; + } + out.write_all(&buf[..n])?; + } + } + Ok(()) +} + pub fn concat_segments(ffmpeg: &Path, segments: &[PathBuf], output: &Path) -> Result<()> { if segments.is_empty() { bail!("no segments to concatenate"); diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 33c6897..bb41f3d 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -1,3 +1,4 @@ +mod audio; mod bootstrap; mod capture; mod config; @@ -29,12 +30,16 @@ pub struct AppState { pub app_dir: PathBuf, pub config: Mutex, pub capture: Mutex>, + pub audio: Mutex>, pub last_clip: Mutex>, pub session: Mutex>, } pub struct SessionState { pub segments: Vec, + pub audio_segments: Vec, + pub audio_sample_rate: Option, + pub audio_channels: Option, pub total_recorded_secs: f64, pub capture_cursor: bool, pub audio: bool, @@ -235,18 +240,26 @@ fn segment_path(app_dir: &Path, idx: usize) -> PathBuf { temp_dir(app_dir).join(format!("segment-{:03}.mp4", idx)) } +fn audio_segment_path(app_dir: &Path, idx: usize) -> PathBuf { + temp_dir(app_dir).join(format!("audio-{:03}.pcm", idx)) +} + fn clear_temp_segments(app_dir: &Path) { let temp = temp_dir(app_dir); if let Ok(entries) = std::fs::read_dir(&temp) { for entry in entries.flatten() { if let Some(name) = entry.file_name().to_str() { - if name.starts_with("segment-") && name.ends_with(".mp4") { + if (name.starts_with("segment-") && name.ends_with(".mp4")) + || (name.starts_with("audio-") && name.ends_with(".pcm")) + { let _ = std::fs::remove_file(entry.path()); } } } } let _ = std::fs::remove_file(temp.join("recording.mp4")); + let _ = std::fs::remove_file(temp.join("video-concat.mp4")); + let _ = std::fs::remove_file(temp.join("audio-concat.pcm")); } fn set_overlay_clickthrough(app: &AppHandle, enabled: bool) { @@ -290,10 +303,31 @@ fn start_capture( ) .map_err(|e| format!("{e:#}"))?; + let audio_session = if cfg.capture.capture_audio { + let audio_path = audio_segment_path(&state.app_dir, 1); + match audio::start(audio_path) { + Ok(s) => Some(s), + Err(e) => { + tracing::warn!("audio capture failed to start: {e:#}"); + None + } + } + } else { + None + }; + set_overlay_clickthrough(&app, true); + let (a_sr, a_ch) = audio_session + .as_ref() + .map(|s| (Some(s.sample_rate), Some(s.channels))) + .unwrap_or((None, None)); + let session_state = SessionState { segments: Vec::new(), + audio_segments: Vec::new(), + audio_sample_rate: a_sr, + audio_channels: a_ch, total_recorded_secs: 0.0, capture_cursor: cfg.capture.capture_cursor, audio: cfg.capture.capture_audio, @@ -304,6 +338,7 @@ fn start_capture( *state.session.lock().expect("session mutex") = Some(session_state); *state.capture.lock().expect("capture mutex") = Some(session); + *state.audio.lock().expect("audio mutex") = audio_session; Ok(()) } @@ -318,11 +353,21 @@ fn pause_capture(state: State<'_, AppState>) -> Result<(), String> { let elapsed = session.started_at.elapsed().as_secs_f64(); let path = session.stop().map_err(|e| format!("{e:#}"))?; + let audio_path = state + .audio + .lock() + .expect("audio mutex") + .take() + .and_then(|a| a.stop().ok()); + let mut ss = state.session.lock().expect("session mutex"); let ss = ss .as_mut() .ok_or_else(|| "no session state".to_string())?; ss.segments.push(path); + if let Some(ap) = audio_path { + ss.audio_segments.push(ap); + } ss.total_recorded_secs += elapsed; Ok(()) } @@ -356,7 +401,22 @@ fn resume_capture(state: State<'_, AppState>) -> Result<(), String> { } let session = capture::start(output, ffmpeg, capture_cursor, audio, crop, fps) .map_err(|e| format!("{e:#}"))?; + + let audio_session = if audio { + let audio_path = audio_segment_path(&state.app_dir, next_idx); + match audio::start(audio_path) { + Ok(s) => Some(s), + Err(e) => { + tracing::warn!("audio resume failed: {e:#}"); + None + } + } + } else { + None + }; + *state.capture.lock().expect("capture mutex") = Some(session); + *state.audio.lock().expect("audio mutex") = audio_session; Ok(()) } @@ -379,29 +439,68 @@ fn stop_capture(app: AppHandle, state: State<'_, AppState>) -> Result